Skip to content

Introduce Constructor role - #114

Draft
yuval-block wants to merge 2 commits into
sorterfrom
constructor
Draft

yuval-block wants to merge 2 commits into
sorterfrom
constructor

Conversation

@yuval-block

Copy link
Copy Markdown
Collaborator

Add Constructor<M, S> and ResultConstructor<M, S>, which provide a
typesafe interface to unordered PSBT mutation modeled after the upstream
psbt_v2 crate's interface for BIP 174 and 370.

Like the BIP 370 Constructor role, this can freeze the input or output fields. Unlike the upstream implementation no_more_inputs and no_more_outputs transition the static type.

Unlike the BIP 370 Constructor, this can only transition into the Sorter role, from the fully or partly modifiable states.

@yuval-block
yuval-block added this pull request to stack #113 November 14, 2026 02:51
@yuval-block yuval-block linked an issue Nov 14, 2026 that may be closed by this pull request
@github-actions

Copy link
Copy Markdown
range-diff for force push 7e6e6bdbea → 199a7b165d November 14, 2026 03:29 UTC: 1 modified, 1 dropped, 1 added; 2 commits; base 8a47f49642 → fd221478f4 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 8a47f49..7e6e6bd fd22147..199a7b1

1:  9dc756c88c +890 -1 5f ! 1:  21df455085 +857 -1 5f introduce Constructor role
2:  7e6e6bdbea +262 -2 2f < -:  ----------            Constructor: allow sorting while modifiable
-:  ----------            > 2:  199a7b165d +112 -0 1f Constructor: allow sorting while modifiable
1: 9dc756c88c ! 1: 21df455085 introduce Constructor role
@@ Commit message
     psbt_v2 crate's interface for BIP 174 and 370.
 
     This currently only supports same-modifiability Constructors to be
-    joined. The logical AND of the modifiaiblity flags allows mixed
+    joined. The logical AND of the modifiability flags allows mixed
     modifiability constructors to be joined in principle, but this is not
     implemented in this commit.
 
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +use bitcoin::OutPoint;
 +
 +use crate::output::{OutputSetError, UniqueId};
++use crate::sorter::FlagsMismatch;
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
 +/// Error when constructing a [`Constructor`](super::Constructor) from a PSBT.
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +
 +impl std::error::Error for ConstructorError {}
 +
++impl From<FlagsMismatch> for ConstructorError {
++    fn from(FlagsMismatch { expected, actual }: FlagsMismatch) -> Self {
++        Self::FlagsMismatch { expected, actual }
++    }
++}
++
 +impl From<OutputSetError> for ConstructorError {
 +    fn from(error: OutputSetError) -> Self {
 +        UnorderedPsbtError::from(error).into()
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +use crate::input::InputSet;
 +use crate::lattice::join::Join;
 +use crate::output::{OutputSet, OutputUniqueIdExt, UniqueId};
-+use crate::sorter::{Deterministic, Mixed, Seeded, Sorter};
++use crate::sorter::{
++    BothModifiable, Deterministic, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
++    Sorter, Unmodifiable, check_flags,
++};
 +use crate::tx::UnorderedPsbt;
 +
 +mod error;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +pub use error::ConstructorError;
 +pub use result::ResultConstructor;
 +
-+/// Sealed trait for modifiability markers, carrying the expected `tx_modifiable_flags` value.
-+///
-+/// Used by [`ResultConstructor::try_unwrap`](ResultConstructor::try_unwrap)
-+/// to re-validate flags when extracting a typed [`Constructor`] from the result domain.
-+pub trait Modifiability {
-+    /// The expected value of `tx_modifiable_flags & 0x03` for this modifiability.
-+    const EXPECTED_FLAGS: u8;
-+}
-+
-+/// Modifiability marker: both inputs and outputs may be added (`tx_modifiable_flags` bits 0+1).
-+#[derive(Debug, Clone, PartialEq)]
-+pub enum BothModifiable {}
-+impl Modifiability for BothModifiable {
-+    const EXPECTED_FLAGS: u8 = 0x03;
-+}
-+
-+/// Modifiability marker: only inputs may be added (`tx_modifiable_flags` bit 0).
-+#[derive(Debug, Clone, PartialEq)]
-+pub enum InputsModifiable {}
-+impl Modifiability for InputsModifiable {
-+    const EXPECTED_FLAGS: u8 = 0x01;
-+}
-+
-+/// Modifiability marker: only outputs may be added (`tx_modifiable_flags` bit 1).
-+#[derive(Debug, Clone, PartialEq)]
-+pub enum OutputsModifiable {}
-+impl Modifiability for OutputsModifiable {
-+    const EXPECTED_FLAGS: u8 = 0x02;
-+}
-+
-+/// Check that `flags & 0x03` equals the expected value, returning
-+/// [`ConstructorError::FlagsMismatch`] if not.
-+fn validate_flags(flags: u8, expected: u8) -> Result<(), ConstructorError> {
-+    let actual = flags & 0x03;
-+    if actual == expected {
-+        Ok(())
-+    } else {
-+        Err(ConstructorError::FlagsMismatch { expected, actual })
-+    }
-+}
-+
 +/// Typed wrapper that tracks modifiability `M` and sort state `S`.
 +///
 +/// The type parameters enforce the BIP 370 constructor state machine at compile time:
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability, S> Constructor<M, S> {
++impl<M: Modifiable, S> Constructor<M, S> {
 +    /// Join with a PSBT that shares this one's global fields and holds only
 +    /// the given inputs and outputs.
 +    fn join_with(self, inputs: InputSet, outputs: OutputSet) -> ResultConstructor<M, S> {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// `tx_modifiable_flags` are not both set, or propagates lower-level
 +    /// unordered PSBT parse errors.
 +    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        validate_flags(psbt.global.tx_modifiable_flags, 0x03)?;
++        check_flags::<BothModifiable>(psbt.global.tx_modifiable_flags)?;
 +        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
 +            psbt,
 +        )?))
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// does not have bit 0 set and bit 1 clear, or propagates lower-level
 +    /// unordered PSBT parse errors.
 +    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        validate_flags(psbt.global.tx_modifiable_flags, 0x01)?;
++        check_flags::<InputsModifiable>(psbt.global.tx_modifiable_flags)?;
 +        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
 +            psbt,
 +        )?))
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Finalize inputs and transition to the [`Sorter`] for ordering.
 +    ///
 +    /// Clears bit 0 of `tx_modifiable_flags` and freezes the inputs.
-+    pub fn no_more_inputs(mut self) -> Sorter<S> {
++    pub fn no_more_inputs(mut self) -> Sorter<Unmodifiable, S> {
 +        self.0.global.tx_modifiable_flags &= !0x01;
 +        Sorter::from_unordered(self.0.freeze_unmodifiable())
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// does not have bit 1 set and bit 0 clear, or propagates lower-level
 +    /// unordered PSBT parse errors.
 +    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        validate_flags(psbt.global.tx_modifiable_flags, 0x02)?;
++        check_flags::<OutputsModifiable>(psbt.global.tx_modifiable_flags)?;
 +        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
 +            psbt,
 +        )?))
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Finalize outputs and transition to the [`Sorter`] for ordering.
 +    ///
 +    /// Clears bit 1 of `tx_modifiable_flags` and freezes the outputs.
-+    pub fn no_more_outputs(mut self) -> Sorter<S> {
++    pub fn no_more_outputs(mut self) -> Sorter<Unmodifiable, S> {
 +        self.0.global.tx_modifiable_flags &= !0x02;
 +        Sorter::from_unordered(self.0.freeze_unmodifiable())
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +mod tests {
 +    use super::*;
 +
-+    use crate::roles::constructor::{BothModifiable, InputsModifiable, OutputsModifiable};
-+
 +    type TestConstructor = Constructor<BothModifiable, Mixed>;
 +
 +    fn empty_constructor() -> TestConstructor {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +
 +            #[test]
 +            fn is_ok_agrees_with_try_unwrap(flags in 0u8..=0x03, version in any::<i32>()) {
-+                fn check<M: Modifiability>(psbt: Psbt) -> bool {
++                fn check<M: Modifiable>(psbt: Psbt) -> bool {
 +                    let result = ResultConstructor::<M, Mixed>::try_from_psbt(psbt)
 +                        .expect("an empty PSBT has no duplicate identities");
 +                    result.is_ok() == result.try_unwrap().is_ok()
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +use crate::sorter::Mixed;
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
-+use super::{Constructor, Modifiability};
++use super::{Constructor, Modifiable};
 +
 +/// Result-domain version of [`Constructor`]. Implements [`Join`] for N-way merging.
 +///
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability, S> ResultConstructor<M, S> {
++impl<M: Modifiable, S> ResultConstructor<M, S> {
 +    /// Return `true` if [`try_unwrap`](Self::try_unwrap) would succeed: every
 +    /// field is conflict-free and `tx_modifiable_flags` match `M`.
 +    pub fn is_ok(&self) -> bool {

@github-actions

Copy link
Copy Markdown
range-diff for force push 7e6e6bdbea → 199a7b165d November 14, 2026 03:29 UTC: 1 modified, 1 dropped, 1 added; 2 commits; base 8a47f49642 → fd221478f4 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 8a47f49..7e6e6bd fd22147..199a7b1

1:  9dc756c88c +890 -1 5f ! 1:  21df455085 +857 -1 5f introduce Constructor role
2:  7e6e6bdbea +262 -2 2f < -:  ----------            Constructor: allow sorting while modifiable
-:  ----------            > 2:  199a7b165d +112 -0 1f Constructor: allow sorting while modifiable
1: 9dc756c88c ! 1: 21df455085 introduce Constructor role
@@ Commit message
     psbt_v2 crate's interface for BIP 174 and 370.
 
     This currently only supports same-modifiability Constructors to be
-    joined. The logical AND of the modifiaiblity flags allows mixed
+    joined. The logical AND of the modifiability flags allows mixed
     modifiability constructors to be joined in principle, but this is not
     implemented in this commit.
 
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +use bitcoin::OutPoint;
 +
 +use crate::output::{OutputSetError, UniqueId};
++use crate::sorter::FlagsMismatch;
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
 +/// Error when constructing a [`Constructor`](super::Constructor) from a PSBT.
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +
 +impl std::error::Error for ConstructorError {}
 +
++impl From<FlagsMismatch> for ConstructorError {
++    fn from(FlagsMismatch { expected, actual }: FlagsMismatch) -> Self {
++        Self::FlagsMismatch { expected, actual }
++    }
++}
++
 +impl From<OutputSetError> for ConstructorError {
 +    fn from(error: OutputSetError) -> Self {
 +        UnorderedPsbtError::from(error).into()
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +use crate::input::InputSet;
 +use crate::lattice::join::Join;
 +use crate::output::{OutputSet, OutputUniqueIdExt, UniqueId};
-+use crate::sorter::{Deterministic, Mixed, Seeded, Sorter};
++use crate::sorter::{
++    BothModifiable, Deterministic, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
++    Sorter, Unmodifiable, check_flags,
++};
 +use crate::tx::UnorderedPsbt;
 +
 +mod error;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +pub use error::ConstructorError;
 +pub use result::ResultConstructor;
 +
-+/// Sealed trait for modifiability markers, carrying the expected `tx_modifiable_flags` value.
-+///
-+/// Used by [`ResultConstructor::try_unwrap`](ResultConstructor::try_unwrap)
-+/// to re-validate flags when extracting a typed [`Constructor`] from the result domain.
-+pub trait Modifiability {
-+    /// The expected value of `tx_modifiable_flags & 0x03` for this modifiability.
-+    const EXPECTED_FLAGS: u8;
-+}
-+
-+/// Modifiability marker: both inputs and outputs may be added (`tx_modifiable_flags` bits 0+1).
-+#[derive(Debug, Clone, PartialEq)]
-+pub enum BothModifiable {}
-+impl Modifiability for BothModifiable {
-+    const EXPECTED_FLAGS: u8 = 0x03;
-+}
-+
-+/// Modifiability marker: only inputs may be added (`tx_modifiable_flags` bit 0).
-+#[derive(Debug, Clone, PartialEq)]
-+pub enum InputsModifiable {}
-+impl Modifiability for InputsModifiable {
-+    const EXPECTED_FLAGS: u8 = 0x01;
-+}
-+
-+/// Modifiability marker: only outputs may be added (`tx_modifiable_flags` bit 1).
-+#[derive(Debug, Clone, PartialEq)]
-+pub enum OutputsModifiable {}
-+impl Modifiability for OutputsModifiable {
-+    const EXPECTED_FLAGS: u8 = 0x02;
-+}
-+
-+/// Check that `flags & 0x03` equals the expected value, returning
-+/// [`ConstructorError::FlagsMismatch`] if not.
-+fn validate_flags(flags: u8, expected: u8) -> Result<(), ConstructorError> {
-+    let actual = flags & 0x03;
-+    if actual == expected {
-+        Ok(())
-+    } else {
-+        Err(ConstructorError::FlagsMismatch { expected, actual })
-+    }
-+}
-+
 +/// Typed wrapper that tracks modifiability `M` and sort state `S`.
 +///
 +/// The type parameters enforce the BIP 370 constructor state machine at compile time:
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability, S> Constructor<M, S> {
++impl<M: Modifiable, S> Constructor<M, S> {
 +    /// Join with a PSBT that shares this one's global fields and holds only
 +    /// the given inputs and outputs.
 +    fn join_with(self, inputs: InputSet, outputs: OutputSet) -> ResultConstructor<M, S> {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// `tx_modifiable_flags` are not both set, or propagates lower-level
 +    /// unordered PSBT parse errors.
 +    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        validate_flags(psbt.global.tx_modifiable_flags, 0x03)?;
++        check_flags::<BothModifiable>(psbt.global.tx_modifiable_flags)?;
 +        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
 +            psbt,
 +        )?))
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// does not have bit 0 set and bit 1 clear, or propagates lower-level
 +    /// unordered PSBT parse errors.
 +    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        validate_flags(psbt.global.tx_modifiable_flags, 0x01)?;
++        check_flags::<InputsModifiable>(psbt.global.tx_modifiable_flags)?;
 +        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
 +            psbt,
 +        )?))
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Finalize inputs and transition to the [`Sorter`] for ordering.
 +    ///
 +    /// Clears bit 0 of `tx_modifiable_flags` and freezes the inputs.
-+    pub fn no_more_inputs(mut self) -> Sorter<S> {
++    pub fn no_more_inputs(mut self) -> Sorter<Unmodifiable, S> {
 +        self.0.global.tx_modifiable_flags &= !0x01;
 +        Sorter::from_unordered(self.0.freeze_unmodifiable())
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// does not have bit 1 set and bit 0 clear, or propagates lower-level
 +    /// unordered PSBT parse errors.
 +    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        validate_flags(psbt.global.tx_modifiable_flags, 0x02)?;
++        check_flags::<OutputsModifiable>(psbt.global.tx_modifiable_flags)?;
 +        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
 +            psbt,
 +        )?))
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Finalize outputs and transition to the [`Sorter`] for ordering.
 +    ///
 +    /// Clears bit 1 of `tx_modifiable_flags` and freezes the outputs.
-+    pub fn no_more_outputs(mut self) -> Sorter<S> {
++    pub fn no_more_outputs(mut self) -> Sorter<Unmodifiable, S> {
 +        self.0.global.tx_modifiable_flags &= !0x02;
 +        Sorter::from_unordered(self.0.freeze_unmodifiable())
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +mod tests {
 +    use super::*;
 +
-+    use crate::roles::constructor::{BothModifiable, InputsModifiable, OutputsModifiable};
-+
 +    type TestConstructor = Constructor<BothModifiable, Mixed>;
 +
 +    fn empty_constructor() -> TestConstructor {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +
 +            #[test]
 +            fn is_ok_agrees_with_try_unwrap(flags in 0u8..=0x03, version in any::<i32>()) {
-+                fn check<M: Modifiability>(psbt: Psbt) -> bool {
++                fn check<M: Modifiable>(psbt: Psbt) -> bool {
 +                    let result = ResultConstructor::<M, Mixed>::try_from_psbt(psbt)
 +                        .expect("an empty PSBT has no duplicate identities");
 +                    result.is_ok() == result.try_unwrap().is_ok()
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +use crate::sorter::Mixed;
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
-+use super::{Constructor, Modifiability};
++use super::{Constructor, Modifiable};
 +
 +/// Result-domain version of [`Constructor`]. Implements [`Join`] for N-way merging.
 +///
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability, S> ResultConstructor<M, S> {
++impl<M: Modifiable, S> ResultConstructor<M, S> {
 +    /// Return `true` if [`try_unwrap`](Self::try_unwrap) would succeed: every
 +    /// field is conflict-free and `tx_modifiable_flags` match `M`.
 +    pub fn is_ok(&self) -> bool {

@github-actions

Copy link
Copy Markdown
range-diff for force push 199a7b165d → 0a5cb0da97 November 14, 2026 04:13 UTC: 2 modified; 2 commits; base fd221478f4 → a76152e86e (diverged, 4 ahead and 4 behind)

reproduce: git range-diff fd22147..199a7b1 a76152e..0a5cb0d

1:  21df455085 +857 -1 5f ! 1:  fcd484ecff +873 -1 6f introduce Constructor role
2:  199a7b165d +112 -0 1f ! 2:  0a5cb0da97 +112 -0 1f Constructor: allow sorting while modifiable
1: 21df455085 ! 1: fcd484ecff introduce Constructor role
@@ crates/concurrent-psbt/proptest-regressions/roles/constructor/mod.txt (new)
 +# everyone who runs the test benefits from these saved cases.
 +cc 23252b5523e003b8c7ae0c402e920713559a7301fae87c9a12d0bf710f8b982c # shrinks to version = 0
 
+ ## crates/concurrent-psbt/src/psbt/tx.rs ##
+@@ crates/concurrent-psbt/src/psbt/tx.rs: fn duplicate_sort_key<'a>(mut keys: impl Iterator<Item = &'a [u8]>) -> Option<&'
+     keys.find(|key| !seen.insert(*key))
+ }
+ 
++impl UnorderedPsbt {
++    /// Clear the inputs' `tx_modifiable_flags` bit and freeze the inputs.
++    pub(crate) fn no_more_inputs(mut self) -> Self {
++        self.global.tx_modifiable_flags &= !INPUTS_MODIFIABLE;
++        self.inputs = self.inputs.freeze();
++        self
++    }
++
++    /// Clear the outputs' `tx_modifiable_flags` bit and freeze the outputs.
++    pub(crate) fn no_more_outputs(mut self) -> Self {
++        self.global.tx_modifiable_flags &= !OUTPUTS_MODIFIABLE;
++        self.outputs = self.outputs.freeze();
++        self
++    }
++}
++
+ /// The declared count and set size, if they disagree.
+ fn count_mismatch(declared: usize, len: usize) -> Option<Conflict<usize>> {
+     (declared != len).then(|| Conflict::from_values([declared, len]))
+
  ## crates/concurrent-psbt/src/roles/constructor/error.rs (new) ##
 @@
 +use std::fmt;
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +    DuplicateUniqueId(UniqueId),
 +    /// The unordered PSBT accumulated conflicting fields while parsing.
 +    Conflict(Box<ResultUnorderedPsbt>),
-+    /// The PSBT's unordered or sort flags are malformed, it is modifiable but
-+    /// not unordered, or its sort seed, a sort key, or an output's unique ID
-+    /// has an invalid size.
++    /// The PSBT is not marked unordered, its unordered or sort flags are
++    /// malformed, its sort fields break its sort mode or repeat a sort key, or
++    /// its sort seed, a sort key, or an output's unique ID has an invalid size.
 +    Unordered(UnorderedPsbtError),
 +    /// The PSBT's `tx_modifiable_flags` don't match the requested modifiability.
 +    FlagsMismatch {
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +            }
 +            UnorderedPsbtError::Conflict(result) => Self::Conflict(result),
 +            error @ (UnorderedPsbtError::InvalidUnorderedFlag(_)
-+            | UnorderedPsbtError::InvalidSortDeterministic(_)
-+            | UnorderedPsbtError::OrderedModifiable
++            | UnorderedPsbtError::InvalidSortKeyDerivation(_)
++            | UnorderedPsbtError::NotUnordered
 +            | UnorderedPsbtError::UnorderedSighashSingle
 +            | UnorderedPsbtError::SortSeedTooShort(_)
 +            | UnorderedPsbtError::InputSortKeyTooLong(_)
 +            | UnorderedPsbtError::OutputSortKeyTooLong(_)
++            | UnorderedPsbtError::UnexpectedSortSeed
++            | UnorderedPsbtError::UnexpectedInputSortKey(_)
++            | UnorderedPsbtError::UnexpectedOutputSortKey(_)
++            | UnorderedPsbtError::DuplicateSortKey(_)
 +            | UnorderedPsbtError::OutputUniqueIdTooLong(_)) => Self::Unordered(error),
 +        }
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +use crate::lattice::join::Join;
 +use crate::output::{OutputSet, OutputUniqueIdExt, UniqueId};
 +use crate::sorter::{
-+    BothModifiable, Deterministic, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
++    BothModifiable, DerivedOnly, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
 +    Sorter, Unmodifiable, check_flags,
 +};
 +use crate::tx::UnorderedPsbt;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl<M> Constructor<M, Deterministic> {
++impl<M> Constructor<M, DerivedOnly> {
 +    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
-+    pub fn set_seed(self, seed: SortSeed) -> Constructor<M, Seeded<Deterministic>> {
++    pub fn set_seed(self, seed: SortSeed) -> Constructor<M, Seeded<DerivedOnly>> {
 +        self.with_seed(seed)
 +    }
 +}
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Transition to [`OutputsModifiable`]: no more inputs will be added.
 +    ///
 +    /// Clears bit 0 of `tx_modifiable_flags` and freezes the inputs.
-+    pub fn no_more_inputs(mut self) -> Constructor<OutputsModifiable, S> {
-+        self.0.global.tx_modifiable_flags &= !0x01;
-+        Constructor(self.0.freeze_unmodifiable(), PhantomData)
++    pub fn no_more_inputs(self) -> Constructor<OutputsModifiable, S> {
++        Constructor(self.0.no_more_inputs(), PhantomData)
 +    }
 +
 +    /// Transition to [`InputsModifiable`]: no more outputs will be added.
 +    ///
 +    /// Clears bit 1 of `tx_modifiable_flags` and freezes the outputs.
-+    pub fn no_more_outputs(mut self) -> Constructor<InputsModifiable, S> {
-+        self.0.global.tx_modifiable_flags &= !0x02;
-+        Constructor(self.0.freeze_unmodifiable(), PhantomData)
++    pub fn no_more_outputs(self) -> Constructor<InputsModifiable, S> {
++        Constructor(self.0.no_more_outputs(), PhantomData)
 +    }
 +}
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Finalize inputs and transition to the [`Sorter`] for ordering.
 +    ///
 +    /// Clears bit 0 of `tx_modifiable_flags` and freezes the inputs.
-+    pub fn no_more_inputs(mut self) -> Sorter<Unmodifiable, S> {
-+        self.0.global.tx_modifiable_flags &= !0x01;
-+        Sorter::from_unordered(self.0.freeze_unmodifiable())
++    pub fn no_more_inputs(self) -> Sorter<Unmodifiable, S> {
++        Sorter::from_unordered(self.0.no_more_inputs())
 +    }
 +}
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Finalize outputs and transition to the [`Sorter`] for ordering.
 +    ///
 +    /// Clears bit 1 of `tx_modifiable_flags` and freezes the outputs.
-+    pub fn no_more_outputs(mut self) -> Sorter<Unmodifiable, S> {
-+        self.0.global.tx_modifiable_flags &= !0x02;
-+        Sorter::from_unordered(self.0.freeze_unmodifiable())
++    pub fn no_more_outputs(self) -> Sorter<Unmodifiable, S> {
++        Sorter::from_unordered(self.0.no_more_outputs())
 +    }
 +}
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +            .expect("a seeded mixed PSBT without sort keys can be sorted");
 +        assert_eq!((ordered.inputs.len(), ordered.outputs.len()), (1, 1));
 +
-+        let deterministic = Constructor::<BothModifiable, Deterministic>::from_unordered(
++        let deterministic = Constructor::<BothModifiable, DerivedOnly>::from_unordered(
 +            Constructor::<BothModifiable, Mixed>::try_from_psbt(psbt_with_flags(0x03, version))
 +                .unwrap()
 +                .into_inner(),
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +        let mut ordered = psbt_with_flags(0x03, version);
 +        ordered.global.clear_unordered();
 +        let ordered = Constructor::<BothModifiable, Mixed>::try_from_psbt(ordered)
-+            .expect_err("a modifiable PSBT must be unordered");
-+        let expected = crate::tx::UnorderedPsbtError::OrderedModifiable;
++            .expect_err("a PSBT read as unordered must be marked unordered");
++        let expected = crate::tx::UnorderedPsbtError::NotUnordered;
 +        assert_eq!(ordered.to_string(), expected.to_string());
 +        assert!(matches!(ordered, ConstructorError::Unordered(error) if error == expected));
 +
2: 199a7b165d ! 2: 0a5cb0da97 Constructor: allow sorting while modifiable
@@ Commit message
     BIP 370 constructor.
 
  ## crates/concurrent-psbt/src/roles/constructor/mod.rs ##
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M> Constructor<M, Deterministic> {
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M> Constructor<M, DerivedOnly> {
  }
  
  impl<M: Modifiable, S> Constructor<M, S> {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
      }
  
 +    fn exercise_sort_keeps_modifiability(seed: Vec<u8>, version: i32) {
-+        use crate::sorter::{Explicit, SortError};
++        use crate::sorter::{ExplicitOnly, SortError};
 +
 +        let sort_seed = SortSeed::try_from(seed).expect("test seeds are at least 16 bytes");
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +        assert_eq!(txids(&both), expected);
 +
 +        let deterministic = || {
-+            Constructor::<BothModifiable, Deterministic>::from_unordered(build().into_inner())
++            Constructor::<BothModifiable, DerivedOnly>::from_unordered(build().into_inner())
 +                .set_seed(sort_seed.clone())
 +        };
 +        let inputs = deterministic()
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +        assert_eq!(outputs.outputs.len(), 2);
 +
 +        assert!(matches!(
-+            Constructor::<BothModifiable, Explicit>::from_unordered(build().into_inner())
++            Constructor::<BothModifiable, ExplicitOnly>::from_unordered(build().into_inner())
 +                .into_sorter()
 +                .try_sort(),
 +            Err(SortError::MissingInputSortKey(_))

@github-actions

Copy link
Copy Markdown
range-diff for force push 199a7b165d → 0a5cb0da97 November 14, 2026 04:13 UTC: 2 modified; 2 commits; base fd221478f4 → a76152e86e (diverged, 4 ahead and 4 behind)

reproduce: git range-diff fd22147..199a7b1 a76152e..0a5cb0d

1:  21df455085 +857 -1 5f ! 1:  fcd484ecff +873 -1 6f introduce Constructor role
2:  199a7b165d +112 -0 1f ! 2:  0a5cb0da97 +112 -0 1f Constructor: allow sorting while modifiable
1: 21df455085 ! 1: fcd484ecff introduce Constructor role
@@ crates/concurrent-psbt/proptest-regressions/roles/constructor/mod.txt (new)
 +# everyone who runs the test benefits from these saved cases.
 +cc 23252b5523e003b8c7ae0c402e920713559a7301fae87c9a12d0bf710f8b982c # shrinks to version = 0
 
+ ## crates/concurrent-psbt/src/psbt/tx.rs ##
+@@ crates/concurrent-psbt/src/psbt/tx.rs: fn duplicate_sort_key<'a>(mut keys: impl Iterator<Item = &'a [u8]>) -> Option<&'
+     keys.find(|key| !seen.insert(*key))
+ }
+ 
++impl UnorderedPsbt {
++    /// Clear the inputs' `tx_modifiable_flags` bit and freeze the inputs.
++    pub(crate) fn no_more_inputs(mut self) -> Self {
++        self.global.tx_modifiable_flags &= !INPUTS_MODIFIABLE;
++        self.inputs = self.inputs.freeze();
++        self
++    }
++
++    /// Clear the outputs' `tx_modifiable_flags` bit and freeze the outputs.
++    pub(crate) fn no_more_outputs(mut self) -> Self {
++        self.global.tx_modifiable_flags &= !OUTPUTS_MODIFIABLE;
++        self.outputs = self.outputs.freeze();
++        self
++    }
++}
++
+ /// The declared count and set size, if they disagree.
+ fn count_mismatch(declared: usize, len: usize) -> Option<Conflict<usize>> {
+     (declared != len).then(|| Conflict::from_values([declared, len]))
+
  ## crates/concurrent-psbt/src/roles/constructor/error.rs (new) ##
 @@
 +use std::fmt;
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +    DuplicateUniqueId(UniqueId),
 +    /// The unordered PSBT accumulated conflicting fields while parsing.
 +    Conflict(Box<ResultUnorderedPsbt>),
-+    /// The PSBT's unordered or sort flags are malformed, it is modifiable but
-+    /// not unordered, or its sort seed, a sort key, or an output's unique ID
-+    /// has an invalid size.
++    /// The PSBT is not marked unordered, its unordered or sort flags are
++    /// malformed, its sort fields break its sort mode or repeat a sort key, or
++    /// its sort seed, a sort key, or an output's unique ID has an invalid size.
 +    Unordered(UnorderedPsbtError),
 +    /// The PSBT's `tx_modifiable_flags` don't match the requested modifiability.
 +    FlagsMismatch {
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +            }
 +            UnorderedPsbtError::Conflict(result) => Self::Conflict(result),
 +            error @ (UnorderedPsbtError::InvalidUnorderedFlag(_)
-+            | UnorderedPsbtError::InvalidSortDeterministic(_)
-+            | UnorderedPsbtError::OrderedModifiable
++            | UnorderedPsbtError::InvalidSortKeyDerivation(_)
++            | UnorderedPsbtError::NotUnordered
 +            | UnorderedPsbtError::UnorderedSighashSingle
 +            | UnorderedPsbtError::SortSeedTooShort(_)
 +            | UnorderedPsbtError::InputSortKeyTooLong(_)
 +            | UnorderedPsbtError::OutputSortKeyTooLong(_)
++            | UnorderedPsbtError::UnexpectedSortSeed
++            | UnorderedPsbtError::UnexpectedInputSortKey(_)
++            | UnorderedPsbtError::UnexpectedOutputSortKey(_)
++            | UnorderedPsbtError::DuplicateSortKey(_)
 +            | UnorderedPsbtError::OutputUniqueIdTooLong(_)) => Self::Unordered(error),
 +        }
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +use crate::lattice::join::Join;
 +use crate::output::{OutputSet, OutputUniqueIdExt, UniqueId};
 +use crate::sorter::{
-+    BothModifiable, Deterministic, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
++    BothModifiable, DerivedOnly, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
 +    Sorter, Unmodifiable, check_flags,
 +};
 +use crate::tx::UnorderedPsbt;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl<M> Constructor<M, Deterministic> {
++impl<M> Constructor<M, DerivedOnly> {
 +    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
-+    pub fn set_seed(self, seed: SortSeed) -> Constructor<M, Seeded<Deterministic>> {
++    pub fn set_seed(self, seed: SortSeed) -> Constructor<M, Seeded<DerivedOnly>> {
 +        self.with_seed(seed)
 +    }
 +}
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Transition to [`OutputsModifiable`]: no more inputs will be added.
 +    ///
 +    /// Clears bit 0 of `tx_modifiable_flags` and freezes the inputs.
-+    pub fn no_more_inputs(mut self) -> Constructor<OutputsModifiable, S> {
-+        self.0.global.tx_modifiable_flags &= !0x01;
-+        Constructor(self.0.freeze_unmodifiable(), PhantomData)
++    pub fn no_more_inputs(self) -> Constructor<OutputsModifiable, S> {
++        Constructor(self.0.no_more_inputs(), PhantomData)
 +    }
 +
 +    /// Transition to [`InputsModifiable`]: no more outputs will be added.
 +    ///
 +    /// Clears bit 1 of `tx_modifiable_flags` and freezes the outputs.
-+    pub fn no_more_outputs(mut self) -> Constructor<InputsModifiable, S> {
-+        self.0.global.tx_modifiable_flags &= !0x02;
-+        Constructor(self.0.freeze_unmodifiable(), PhantomData)
++    pub fn no_more_outputs(self) -> Constructor<InputsModifiable, S> {
++        Constructor(self.0.no_more_outputs(), PhantomData)
 +    }
 +}
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Finalize inputs and transition to the [`Sorter`] for ordering.
 +    ///
 +    /// Clears bit 0 of `tx_modifiable_flags` and freezes the inputs.
-+    pub fn no_more_inputs(mut self) -> Sorter<Unmodifiable, S> {
-+        self.0.global.tx_modifiable_flags &= !0x01;
-+        Sorter::from_unordered(self.0.freeze_unmodifiable())
++    pub fn no_more_inputs(self) -> Sorter<Unmodifiable, S> {
++        Sorter::from_unordered(self.0.no_more_inputs())
 +    }
 +}
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// Finalize outputs and transition to the [`Sorter`] for ordering.
 +    ///
 +    /// Clears bit 1 of `tx_modifiable_flags` and freezes the outputs.
-+    pub fn no_more_outputs(mut self) -> Sorter<Unmodifiable, S> {
-+        self.0.global.tx_modifiable_flags &= !0x02;
-+        Sorter::from_unordered(self.0.freeze_unmodifiable())
++    pub fn no_more_outputs(self) -> Sorter<Unmodifiable, S> {
++        Sorter::from_unordered(self.0.no_more_outputs())
 +    }
 +}
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +            .expect("a seeded mixed PSBT without sort keys can be sorted");
 +        assert_eq!((ordered.inputs.len(), ordered.outputs.len()), (1, 1));
 +
-+        let deterministic = Constructor::<BothModifiable, Deterministic>::from_unordered(
++        let deterministic = Constructor::<BothModifiable, DerivedOnly>::from_unordered(
 +            Constructor::<BothModifiable, Mixed>::try_from_psbt(psbt_with_flags(0x03, version))
 +                .unwrap()
 +                .into_inner(),
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +        let mut ordered = psbt_with_flags(0x03, version);
 +        ordered.global.clear_unordered();
 +        let ordered = Constructor::<BothModifiable, Mixed>::try_from_psbt(ordered)
-+            .expect_err("a modifiable PSBT must be unordered");
-+        let expected = crate::tx::UnorderedPsbtError::OrderedModifiable;
++            .expect_err("a PSBT read as unordered must be marked unordered");
++        let expected = crate::tx::UnorderedPsbtError::NotUnordered;
 +        assert_eq!(ordered.to_string(), expected.to_string());
 +        assert!(matches!(ordered, ConstructorError::Unordered(error) if error == expected));
 +
2: 199a7b165d ! 2: 0a5cb0da97 Constructor: allow sorting while modifiable
@@ Commit message
     BIP 370 constructor.
 
  ## crates/concurrent-psbt/src/roles/constructor/mod.rs ##
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M> Constructor<M, Deterministic> {
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M> Constructor<M, DerivedOnly> {
  }
  
  impl<M: Modifiable, S> Constructor<M, S> {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
      }
  
 +    fn exercise_sort_keeps_modifiability(seed: Vec<u8>, version: i32) {
-+        use crate::sorter::{Explicit, SortError};
++        use crate::sorter::{ExplicitOnly, SortError};
 +
 +        let sort_seed = SortSeed::try_from(seed).expect("test seeds are at least 16 bytes");
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +        assert_eq!(txids(&both), expected);
 +
 +        let deterministic = || {
-+            Constructor::<BothModifiable, Deterministic>::from_unordered(build().into_inner())
++            Constructor::<BothModifiable, DerivedOnly>::from_unordered(build().into_inner())
 +                .set_seed(sort_seed.clone())
 +        };
 +        let inputs = deterministic()
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +        assert_eq!(outputs.outputs.len(), 2);
 +
 +        assert!(matches!(
-+            Constructor::<BothModifiable, Explicit>::from_unordered(build().into_inner())
++            Constructor::<BothModifiable, ExplicitOnly>::from_unordered(build().into_inner())
 +                .into_sorter()
 +                .try_sort(),
 +            Err(SortError::MissingInputSortKey(_))

@github-actions

Copy link
Copy Markdown
range-diff for force push 0a5cb0da97 → eaf668d595 November 14, 2026 04:28 UTC: 2 unchanged; 2 commits; base a76152e86e → 12ff101504 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff a76152e..0a5cb0d 12ff101..eaf668d

1:  fcd484ecff +873 -1 6f = 1:  ec48d9e282 +873 -1 6f introduce Constructor role
2:  0a5cb0da97 +112 -0 1f = 2:  eaf668d595 +112 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push 0a5cb0da97 → eaf668d595 November 14, 2026 05:18 UTC: 2 unchanged; 2 commits; base a76152e86e → 12ff101504 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff a76152e..0a5cb0d 12ff101..eaf668d

1:  fcd484ecff +873 -1 6f = 1:  ec48d9e282 +873 -1 6f introduce Constructor role
2:  0a5cb0da97 +112 -0 1f = 2:  eaf668d595 +112 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push eaf668d595 → 2badec25e6 November 14, 2026 05:23 UTC: 2 modified; 2 commits; base 12ff101504 → 1a90913800 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 12ff101..eaf668d 1a90913..2badec2

1:  ec48d9e282 +873 -1 6f ! 1:  7b3df08697 +934 -1 6f introduce Constructor role
2:  eaf668d595 +112 -0 1f ! 2:  2badec25e6 +112 -0 1f Constructor: allow sorting while modifiable
1: ec48d9e282 ! 1: 7b3df08697 introduce Constructor role
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +use bitcoin::OutPoint;
 +
 +use crate::output::{OutputSetError, UniqueId};
-+use crate::sorter::FlagsMismatch;
++use crate::sorter::{FlagsMismatch, SortModeError};
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
 +/// Error when constructing a [`Constructor`](super::Constructor) from a PSBT.
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +    /// malformed, its sort fields break its sort mode or repeat a sort key, or
 +    /// its sort seed, a sort key, or an output's unique ID has an invalid size.
 +    Unordered(UnorderedPsbtError),
++    /// The PSBT's sort fields don't select the requested sort mode.
++    SortMode(SortModeError),
 +    /// The PSBT's `tx_modifiable_flags` don't match the requested modifiability.
 +    FlagsMismatch {
 +        /// The flags value required by the modifiability type.
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +            Self::DuplicateUniqueId(_) => write!(f, "two outputs share a PSBT_OUT_UNIQUE_ID"),
 +            Self::Conflict(_) => write!(f, "unordered PSBT contains conflicting fields"),
 +            Self::Unordered(error) => error.fmt(f),
++            Self::SortMode(error) => error.fmt(f),
 +            Self::FlagsMismatch { expected, actual } => {
 +                write!(
 +                    f,
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +    }
 +}
 +
++impl From<SortModeError> for ConstructorError {
++    fn from(error: SortModeError) -> Self {
++        Self::SortMode(error)
++    }
++}
++
 +impl From<OutputSetError> for ConstructorError {
 +    fn from(error: OutputSetError) -> Self {
 +        UnorderedPsbtError::from(error).into()
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 @@
 +//! The BIP 370 Constructor role: adding inputs and outputs.
 +//!
-+//! [`Constructor`] tracks modifiability in the type system.
++//! [`Constructor`] tracks modifiability and sort mode in the type system.
 +#![allow(clippy::result_large_err)]
 +
 +use std::marker::PhantomData;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +use crate::output::{OutputSet, OutputUniqueIdExt, UniqueId};
 +use crate::sorter::{
 +    BothModifiable, DerivedOnly, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
-+    Sorter, Unmodifiable, check_flags,
++    SortMode, Sorter, Unmodifiable, check_flags, check_sort_mode,
 +};
 +use crate::tx::UnorderedPsbt;
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiable, S> Constructor<M, S> {
++impl<M: Modifiable, S: SortMode> Constructor<M, S> {
++    /// Parse a v2 PSBT into a constructor.
++    ///
++    /// # Errors
++    /// Returns [`ConstructorError::FlagsMismatch`] if `tx_modifiable_flags`
++    /// does not match `M`, propagates lower-level unordered PSBT parse
++    /// errors, then returns [`ConstructorError::SortMode`] if the sort fields
++    /// do not select `S`.
++    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
++        check_flags::<M>(psbt.global.tx_modifiable_flags)?;
++        let psbt = UnorderedPsbt::try_from_psbt(psbt)?;
++        check_sort_mode::<S>(&psbt)?;
++        Ok(Constructor::from_unordered(psbt))
++    }
++
 +    /// Join with a PSBT that shares this one's global fields and holds only
 +    /// the given inputs and outputs.
-+    fn join_with(self, inputs: InputSet, outputs: OutputSet) -> ResultConstructor<M, S> {
++    fn join_with(self, inputs: InputSet, outputs: OutputSet) -> Result<Self, ConstructorError> {
 +        let other = UnorderedPsbt {
 +            global: self.0.global.clone(),
 +            inputs,
 +            outputs,
 +        };
-+        self.wrap().join(Constructor::from_unordered(other).wrap())
++        let psbt = self
++            .0
++            .wrap()
++            .join(other.wrap())
++            .try_unwrap()
++            .map_err(|result| ConstructorError::Conflict(Box::new(result)))?;
++        check_sort_mode::<S>(&psbt)?;
++        Ok(Constructor::from_unordered(psbt))
 +    }
 +
 +    /// Join with a PSBT holding only `input`. Its outputs are empty and
 +    /// modifiable, so they join cleanly with these whether or not they are
 +    /// frozen.
-+    fn add_input(self, input: Input) -> Result<Self, ResultConstructor<M, S>> {
++    fn add_input(self, input: Input) -> Result<Self, ConstructorError> {
 +        let inputs = InputSet::try_from_inputs([input]).expect("a single input cannot repeat");
-+        self.join_with(inputs, OutputSet::default()).try_unwrap()
++        self.join_with(inputs, OutputSet::default())
 +    }
 +
 +    /// Join with a PSBT holding only `output`. Its inputs are empty and
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    fn add_output(self, output: Output) -> Result<Self, ConstructorError> {
 +        let outputs = OutputSet::try_from_outputs([output])?;
 +        self.join_with(InputSet::default(), outputs)
-+            .try_unwrap()
-+            .map_err(|result| ConstructorError::Conflict(Box::new(result.0)))
-+    }
-+}
-+
-+impl Constructor<BothModifiable, Mixed> {
-+    /// Parse a v2 PSBT into a both-modifiable constructor.
-+    ///
-+    /// # Errors
-+    /// Returns [`ConstructorError::FlagsMismatch`] if bits 0 and 1 of
-+    /// `tx_modifiable_flags` are not both set, or propagates lower-level
-+    /// unordered PSBT parse errors.
-+    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        check_flags::<BothModifiable>(psbt.global.tx_modifiable_flags)?;
-+        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
-+            psbt,
-+        )?))
 +    }
 +}
 +
-+impl<S> Constructor<BothModifiable, S> {
++impl<S: SortMode> Constructor<BothModifiable, S> {
 +    /// Add an input to the PSBT.
 +    ///
 +    /// An input spending an outpoint already in the PSBT is joined with it.
 +    ///
 +    /// # Errors
-+    /// Returns the conflicting [`ResultConstructor`] if the two disagree.
-+    pub fn input(self, input: Input) -> Result<Self, ResultConstructor<BothModifiable, S>> {
++    /// Returns [`ConstructorError::Conflict`] if the two disagree, or
++    /// [`ConstructorError::SortMode`] if the input has a sort key in
++    /// [`DerivedOnly`] mode.
++    pub fn input(self, input: Input) -> Result<Self, ConstructorError> {
 +        self.add_input(input)
 +    }
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    ///
 +    /// # Errors
 +    /// Returns [`ConstructorError::MissingUniqueId`] if the output has no
-+    /// `PSBT_OUT_UNIQUE_ID`, or [`ConstructorError::Conflict`] if it
-+    /// disagrees with the output already holding that ID.
++    /// `PSBT_OUT_UNIQUE_ID`, [`ConstructorError::Conflict`] if it disagrees
++    /// with the output already holding that ID, or
++    /// [`ConstructorError::SortMode`] if it has a sort key in
++    /// [`DerivedOnly`] mode.
 +    pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
 +        self.add_output(output)
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl Constructor<InputsModifiable, Mixed> {
-+    /// Parse a v2 PSBT into an inputs-modifiable constructor.
-+    ///
-+    /// # Errors
-+    /// Returns [`ConstructorError::FlagsMismatch`] if `tx_modifiable_flags`
-+    /// does not have bit 0 set and bit 1 clear, or propagates lower-level
-+    /// unordered PSBT parse errors.
-+    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        check_flags::<InputsModifiable>(psbt.global.tx_modifiable_flags)?;
-+        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
-+            psbt,
-+        )?))
-+    }
-+}
-+
-+impl<S> Constructor<InputsModifiable, S> {
++impl<S: SortMode> Constructor<InputsModifiable, S> {
 +    /// Add an input to the PSBT.
 +    ///
 +    /// An input spending an outpoint already in the PSBT is joined with it.
 +    ///
 +    /// # Errors
-+    /// Returns the conflicting [`ResultConstructor`] if the two disagree.
-+    pub fn input(self, input: Input) -> Result<Self, ResultConstructor<InputsModifiable, S>> {
++    /// Returns [`ConstructorError::Conflict`] if the two disagree, or
++    /// [`ConstructorError::SortMode`] if the input has a sort key in
++    /// [`DerivedOnly`] mode.
++    pub fn input(self, input: Input) -> Result<Self, ConstructorError> {
 +        self.add_input(input)
 +    }
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl Constructor<OutputsModifiable, Mixed> {
-+    /// Parse a v2 PSBT into an outputs-modifiable constructor.
-+    ///
-+    /// # Errors
-+    /// Returns [`ConstructorError::FlagsMismatch`] if `tx_modifiable_flags`
-+    /// does not have bit 1 set and bit 0 clear, or propagates lower-level
-+    /// unordered PSBT parse errors.
-+    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        check_flags::<OutputsModifiable>(psbt.global.tx_modifiable_flags)?;
-+        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
-+            psbt,
-+        )?))
-+    }
-+}
-+
-+impl<S> Constructor<OutputsModifiable, S> {
++impl<S: SortMode> Constructor<OutputsModifiable, S> {
 +    /// Add an output to the PSBT.
 +    ///
 +    /// An output whose unique ID is already in the PSBT is joined with it.
 +    ///
 +    /// # Errors
 +    /// Returns [`ConstructorError::MissingUniqueId`] if the output has no
-+    /// `PSBT_OUT_UNIQUE_ID`, or [`ConstructorError::Conflict`] if it
-+    /// disagrees with the output already holding that ID.
++    /// `PSBT_OUT_UNIQUE_ID`, [`ConstructorError::Conflict`] if it disagrees
++    /// with the output already holding that ID, or
++    /// [`ConstructorError::SortMode`] if it has a sort key in
++    /// [`DerivedOnly`] mode.
 +    pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
 +        self.add_output(output)
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +        }
 +    }
 +
++    /// An empty PSBT whose sort fields select mixed, seeded mixed,
++    /// deterministic, seeded deterministic, or explicit mode.
++    fn psbt_with_mode(flags: u8, mode: usize, version: i32) -> Psbt {
++        let mut psbt = psbt_with_flags(flags, version);
++        match mode {
++            2 | 3 => psbt.global.set_sort_key_derivation(0x01),
++            4 => psbt.global.set_sort_key_derivation(0x00),
++            _ => {}
++        }
++        if mode == 1 || mode == 3 {
++            psbt.global
++                .set_sort_seed(SortSeed::try_from(vec![7; 16]).expect("16 bytes"));
++        }
++        psbt
++    }
++
 +    fn test_input(tag: u8) -> psbt_v2::v2::Input {
 +        use bitcoin::hashes::Hash;
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +            .expect("a seeded mixed PSBT without sort keys can be sorted");
 +        assert_eq!((ordered.inputs.len(), ordered.outputs.len()), (1, 1));
 +
-+        let deterministic = Constructor::<BothModifiable, DerivedOnly>::from_unordered(
-+            Constructor::<BothModifiable, Mixed>::try_from_psbt(psbt_with_flags(0x03, version))
-+                .unwrap()
-+                .into_inner(),
++        let deterministic = Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(
++            psbt_with_mode(0x03, 2, version),
 +        )
++        .unwrap()
 +        .set_seed(sort_seed)
 +        .no_more_outputs()
 +        .input(test_input(2))
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +                .unwrap();
 +
 +        input.sequence = Some(bitcoin::Sequence(2));
-+        let conflict = both
-+            .input(input)
-+            .expect_err("an outpoint spent with two sequences conflicts");
-+        assert!(!conflict.is_ok());
++        assert!(matches!(
++            both.input(input)
++                .expect_err("an outpoint spent with two sequences conflicts"),
++            ConstructorError::Conflict(_)
++        ));
 +
 +        output.amount = bitcoin::Amount::from_sat(2);
 +        let both =
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +            }
 +
 +            #[test]
-+            fn is_ok_agrees_with_try_unwrap(flags in 0u8..=0x03, version in any::<i32>()) {
-+                fn check<M: Modifiable>(psbt: Psbt) -> bool {
-+                    let result = ResultConstructor::<M, Mixed>::try_from_psbt(psbt)
++            fn unwraps_only_the_selected_typestate(
++                flags in 0u8..=0x03,
++                mode in 0usize..5,
++                version in any::<i32>(),
++            ) {
++                use crate::sorter::ExplicitOnly;
++
++                fn check<M: Modifiable, S: SortMode>(
++                    psbt: Psbt,
++                    expected: bool,
++                ) -> Result<(), TestCaseError> {
++                    let result = ResultConstructor::<M, S>::try_from_psbt(psbt.clone())
 +                        .expect("an empty PSBT has no duplicate identities");
-+                    result.is_ok() == result.try_unwrap().is_ok()
++                    prop_assert_eq!(result.is_ok(), expected);
++                    prop_assert_eq!(result.try_unwrap().is_ok(), expected);
++                    prop_assert_eq!(Constructor::<M, S>::try_from_psbt(psbt).is_ok(), expected);
++                    Ok(())
++                }
++
++                // A seeded PSBT also selects the unseeded mode it refines.
++                fn modes<M: Modifiable>(psbt: &Psbt, mode: usize) -> Result<(), TestCaseError> {
++                    let flags = psbt.global.tx_modifiable_flags == M::EXPECTED_FLAGS;
++                    check::<M, Mixed>(psbt.clone(), flags && mode <= 1)?;
++                    check::<M, Seeded<Mixed>>(psbt.clone(), flags && mode == 1)?;
++                    check::<M, DerivedOnly>(psbt.clone(), flags && (mode == 2 || mode == 3))?;
++                    check::<M, Seeded<DerivedOnly>>(psbt.clone(), flags && mode == 3)?;
++                    check::<M, ExplicitOnly>(psbt.clone(), flags && mode == 4)
 +                }
-+                prop_assert!(check::<BothModifiable>(psbt_with_flags(flags, version)));
-+                prop_assert!(check::<InputsModifiable>(psbt_with_flags(flags, version)));
-+                prop_assert!(check::<OutputsModifiable>(psbt_with_flags(flags, version)));
++
++                let psbt = psbt_with_mode(flags, mode, version);
++                modes::<BothModifiable>(&psbt, mode)?;
++                modes::<InputsModifiable>(&psbt, mode)?;
++                modes::<OutputsModifiable>(&psbt, mode)?;
++            }
++
++            #[test]
++            fn sort_fields_the_mode_ignores_are_rejected(version in any::<i32>()) {
++                use crate::input::{InputSortKeyExt, SortKey};
++                use crate::output::OutputSortKeyExt;
++                use crate::sorter::{ExplicitOnly, SortModeError};
++                use crate::tx::UnorderedPsbtError;
++
++                let deterministic = || {
++                    Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(
++                        psbt_with_mode(0x03, 2, version),
++                    )
++                    .expect("an empty deterministic PSBT")
++                };
++                let key = || SortKey::try_from(vec![1]).expect("one byte");
++                let mut input = test_input(1);
++                input.set_sort_key(key());
++                let mut output = test_output(1);
++                output.set_sort_key(key());
++                for error in [
++                    deterministic().input(input).unwrap_err(),
++                    deterministic().output(output).unwrap_err(),
++                ] {
++                    prop_assert!(error.to_string().contains("derived-only"));
++                    prop_assert!(matches!(
++                        error,
++                        ConstructorError::SortMode(SortModeError::UnexpectedSortKey)
++                    ));
++                }
++
++                // Parsing rejects a seed under explicit sort keys before the
++                // sort mode is checked.
++                let mut seeded_explicit = psbt_with_mode(0x03, 1, version);
++                seeded_explicit.global.set_sort_key_derivation(0x00);
++                prop_assert!(matches!(
++                    Constructor::<BothModifiable, ExplicitOnly>::try_from_psbt(seeded_explicit),
++                    Err(ConstructorError::Unordered(UnorderedPsbtError::UnexpectedSortSeed))
++                ));
 +            }
 +
 +            #[test]
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +use psbt_v2::v2::Psbt;
 +
 +use crate::lattice::join::Join;
-+use crate::sorter::Mixed;
++use crate::sorter::{SortMode, check_sort_mode};
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
 +use super::{Constructor, Modifiable};
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +    pub(super) PhantomData<(M, S)>,
 +);
 +
-+impl<M> ResultConstructor<M, Mixed> {
++impl<M, S> ResultConstructor<M, S> {
 +    /// Parse a v2 PSBT directly into the result domain.
 +    ///
 +    /// This is the entry point for N-way joins: parse each PSBT into
 +    /// `ResultConstructor`, then fold with `Join`.
 +    ///
 +    /// Unlike `Constructor::try_from_psbt`, this does **not** validate
-+    /// `tx_modifiable_flags`. In the result domain, PSBTs with differing
-+    /// flags are loaded as-is; flag mismatches surface as conflicts
-+    /// when joined, which is the correct behavior for N-way merges.
++    /// `tx_modifiable_flags` or the sort fields. In the result domain, PSBTs
++    /// with differing flags are loaded as-is; mismatches surface when
++    /// joined, which is the correct behavior for N-way merges.
 +    ///
 +    /// # Errors
 +    /// Returns the errors of [`ResultUnorderedPsbt::try_from_psbt`].
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiable, S> ResultConstructor<M, S> {
-+    /// Return `true` if [`try_unwrap`](Self::try_unwrap) would succeed: every
-+    /// field is conflict-free and `tx_modifiable_flags` match `M`.
++impl<M: Modifiable, S: SortMode> ResultConstructor<M, S> {
++    /// Return `true` if [`try_unwrap`](Self::try_unwrap) would succeed.
 +    pub fn is_ok(&self) -> bool {
-+        self.0.is_ok()
-+            && self
-+                .0
-+                .global
-+                .tx_modifiable_flags
-+                .as_ref()
-+                .ok()
-+                .map(|flags| flags & 0x03)
-+                == Some(M::EXPECTED_FLAGS)
-+    }
-+
-+    /// Extract a clean [`Constructor`] if no conflicts remain and
-+    /// `tx_modifiable_flags` match `M`.
++        ResultConstructor::<M, S>(self.0.clone(), PhantomData)
++            .try_unwrap()
++            .is_ok()
++    }
++
++    /// Extract a clean [`Constructor`] if no conflicts remain,
++    /// `tx_modifiable_flags` match `M`, and the sort fields select `S`.
 +    ///
 +    /// # Errors
-+    /// Returns `Err(self)` if any field contains a conflict, or if the resolved
-+    /// `tx_modifiable_flags` don't match `M::EXPECTED_FLAGS`.
++    /// Returns `Err(self)` otherwise.
 +    pub fn try_unwrap(self) -> Result<Constructor<M, S>, Self> {
 +        match self.0.try_unwrap() {
-+            Ok(psbt) => {
-+                if psbt.global.tx_modifiable_flags & 0x03 != M::EXPECTED_FLAGS {
-+                    // Flags don't match the type parameter. Wrap back and return Err.
-+                    Err(ResultConstructor(psbt.wrap(), PhantomData))
-+                } else {
-+                    Ok(Constructor(psbt, PhantomData))
-+                }
++            Ok(psbt)
++                if psbt.global.tx_modifiable_flags & 0x03 == M::EXPECTED_FLAGS
++                    && check_sort_mode::<S>(&psbt).is_ok() =>
++            {
++                Ok(Constructor(psbt, PhantomData))
 +            }
++            Ok(psbt) => Err(ResultConstructor(psbt.wrap(), PhantomData)),
 +            Err(result) => Err(ResultConstructor(result, PhantomData)),
 +        }
 +    }
2: eaf668d595 ! 2: 2badec25e6 Constructor: allow sorting while modifiable
@@ Commit message
     BIP 370 constructor.
 
  ## crates/concurrent-psbt/src/roles/constructor/mod.rs ##
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M> Constructor<M, DerivedOnly> {
- }
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M: Modifiable, S: SortMode> Constructor<M, S> {
+         Ok(Constructor::from_unordered(psbt))
+     }
  
- impl<M: Modifiable, S> Constructor<M, S> {
 +    /// Move on to the [`Sorter`] while inputs and outputs stay as modifiable
 +    /// as they are. Sorting then hands the PSBT to the BIP 370
 +    /// [`Constructor`](psbt_v2::v2::Constructor) of the same modifiability,
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M> Constructor<M, Deri
 +
      /// Join with a PSBT that shares this one's global fields and holds only
      /// the given inputs and outputs.
-     fn join_with(self, inputs: InputSet, outputs: OutputSet) -> ResultConstructor<M, S> {
+     fn join_with(self, inputs: InputSet, outputs: OutputSet) -> Result<Self, ConstructorError> {
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
          assert_eq!(ordered.inputs.len(), 1);
      }

@github-actions

Copy link
Copy Markdown
range-diff for force push eaf668d595 → 2badec25e6 November 14, 2026 05:27 UTC: 2 modified; 2 commits; base 12ff101504 → 1a90913800 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 12ff101..eaf668d 1a90913..2badec2

1:  ec48d9e282 +873 -1 6f ! 1:  7b3df08697 +934 -1 6f introduce Constructor role
2:  eaf668d595 +112 -0 1f ! 2:  2badec25e6 +112 -0 1f Constructor: allow sorting while modifiable
1: ec48d9e282 ! 1: 7b3df08697 introduce Constructor role
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +use bitcoin::OutPoint;
 +
 +use crate::output::{OutputSetError, UniqueId};
-+use crate::sorter::FlagsMismatch;
++use crate::sorter::{FlagsMismatch, SortModeError};
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
 +/// Error when constructing a [`Constructor`](super::Constructor) from a PSBT.
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +    /// malformed, its sort fields break its sort mode or repeat a sort key, or
 +    /// its sort seed, a sort key, or an output's unique ID has an invalid size.
 +    Unordered(UnorderedPsbtError),
++    /// The PSBT's sort fields don't select the requested sort mode.
++    SortMode(SortModeError),
 +    /// The PSBT's `tx_modifiable_flags` don't match the requested modifiability.
 +    FlagsMismatch {
 +        /// The flags value required by the modifiability type.
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +            Self::DuplicateUniqueId(_) => write!(f, "two outputs share a PSBT_OUT_UNIQUE_ID"),
 +            Self::Conflict(_) => write!(f, "unordered PSBT contains conflicting fields"),
 +            Self::Unordered(error) => error.fmt(f),
++            Self::SortMode(error) => error.fmt(f),
 +            Self::FlagsMismatch { expected, actual } => {
 +                write!(
 +                    f,
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +    }
 +}
 +
++impl From<SortModeError> for ConstructorError {
++    fn from(error: SortModeError) -> Self {
++        Self::SortMode(error)
++    }
++}
++
 +impl From<OutputSetError> for ConstructorError {
 +    fn from(error: OutputSetError) -> Self {
 +        UnorderedPsbtError::from(error).into()
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 @@
 +//! The BIP 370 Constructor role: adding inputs and outputs.
 +//!
-+//! [`Constructor`] tracks modifiability in the type system.
++//! [`Constructor`] tracks modifiability and sort mode in the type system.
 +#![allow(clippy::result_large_err)]
 +
 +use std::marker::PhantomData;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +use crate::output::{OutputSet, OutputUniqueIdExt, UniqueId};
 +use crate::sorter::{
 +    BothModifiable, DerivedOnly, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
-+    Sorter, Unmodifiable, check_flags,
++    SortMode, Sorter, Unmodifiable, check_flags, check_sort_mode,
 +};
 +use crate::tx::UnorderedPsbt;
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiable, S> Constructor<M, S> {
++impl<M: Modifiable, S: SortMode> Constructor<M, S> {
++    /// Parse a v2 PSBT into a constructor.
++    ///
++    /// # Errors
++    /// Returns [`ConstructorError::FlagsMismatch`] if `tx_modifiable_flags`
++    /// does not match `M`, propagates lower-level unordered PSBT parse
++    /// errors, then returns [`ConstructorError::SortMode`] if the sort fields
++    /// do not select `S`.
++    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
++        check_flags::<M>(psbt.global.tx_modifiable_flags)?;
++        let psbt = UnorderedPsbt::try_from_psbt(psbt)?;
++        check_sort_mode::<S>(&psbt)?;
++        Ok(Constructor::from_unordered(psbt))
++    }
++
 +    /// Join with a PSBT that shares this one's global fields and holds only
 +    /// the given inputs and outputs.
-+    fn join_with(self, inputs: InputSet, outputs: OutputSet) -> ResultConstructor<M, S> {
++    fn join_with(self, inputs: InputSet, outputs: OutputSet) -> Result<Self, ConstructorError> {
 +        let other = UnorderedPsbt {
 +            global: self.0.global.clone(),
 +            inputs,
 +            outputs,
 +        };
-+        self.wrap().join(Constructor::from_unordered(other).wrap())
++        let psbt = self
++            .0
++            .wrap()
++            .join(other.wrap())
++            .try_unwrap()
++            .map_err(|result| ConstructorError::Conflict(Box::new(result)))?;
++        check_sort_mode::<S>(&psbt)?;
++        Ok(Constructor::from_unordered(psbt))
 +    }
 +
 +    /// Join with a PSBT holding only `input`. Its outputs are empty and
 +    /// modifiable, so they join cleanly with these whether or not they are
 +    /// frozen.
-+    fn add_input(self, input: Input) -> Result<Self, ResultConstructor<M, S>> {
++    fn add_input(self, input: Input) -> Result<Self, ConstructorError> {
 +        let inputs = InputSet::try_from_inputs([input]).expect("a single input cannot repeat");
-+        self.join_with(inputs, OutputSet::default()).try_unwrap()
++        self.join_with(inputs, OutputSet::default())
 +    }
 +
 +    /// Join with a PSBT holding only `output`. Its inputs are empty and
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    fn add_output(self, output: Output) -> Result<Self, ConstructorError> {
 +        let outputs = OutputSet::try_from_outputs([output])?;
 +        self.join_with(InputSet::default(), outputs)
-+            .try_unwrap()
-+            .map_err(|result| ConstructorError::Conflict(Box::new(result.0)))
-+    }
-+}
-+
-+impl Constructor<BothModifiable, Mixed> {
-+    /// Parse a v2 PSBT into a both-modifiable constructor.
-+    ///
-+    /// # Errors
-+    /// Returns [`ConstructorError::FlagsMismatch`] if bits 0 and 1 of
-+    /// `tx_modifiable_flags` are not both set, or propagates lower-level
-+    /// unordered PSBT parse errors.
-+    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        check_flags::<BothModifiable>(psbt.global.tx_modifiable_flags)?;
-+        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
-+            psbt,
-+        )?))
 +    }
 +}
 +
-+impl<S> Constructor<BothModifiable, S> {
++impl<S: SortMode> Constructor<BothModifiable, S> {
 +    /// Add an input to the PSBT.
 +    ///
 +    /// An input spending an outpoint already in the PSBT is joined with it.
 +    ///
 +    /// # Errors
-+    /// Returns the conflicting [`ResultConstructor`] if the two disagree.
-+    pub fn input(self, input: Input) -> Result<Self, ResultConstructor<BothModifiable, S>> {
++    /// Returns [`ConstructorError::Conflict`] if the two disagree, or
++    /// [`ConstructorError::SortMode`] if the input has a sort key in
++    /// [`DerivedOnly`] mode.
++    pub fn input(self, input: Input) -> Result<Self, ConstructorError> {
 +        self.add_input(input)
 +    }
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    ///
 +    /// # Errors
 +    /// Returns [`ConstructorError::MissingUniqueId`] if the output has no
-+    /// `PSBT_OUT_UNIQUE_ID`, or [`ConstructorError::Conflict`] if it
-+    /// disagrees with the output already holding that ID.
++    /// `PSBT_OUT_UNIQUE_ID`, [`ConstructorError::Conflict`] if it disagrees
++    /// with the output already holding that ID, or
++    /// [`ConstructorError::SortMode`] if it has a sort key in
++    /// [`DerivedOnly`] mode.
 +    pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
 +        self.add_output(output)
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl Constructor<InputsModifiable, Mixed> {
-+    /// Parse a v2 PSBT into an inputs-modifiable constructor.
-+    ///
-+    /// # Errors
-+    /// Returns [`ConstructorError::FlagsMismatch`] if `tx_modifiable_flags`
-+    /// does not have bit 0 set and bit 1 clear, or propagates lower-level
-+    /// unordered PSBT parse errors.
-+    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        check_flags::<InputsModifiable>(psbt.global.tx_modifiable_flags)?;
-+        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
-+            psbt,
-+        )?))
-+    }
-+}
-+
-+impl<S> Constructor<InputsModifiable, S> {
++impl<S: SortMode> Constructor<InputsModifiable, S> {
 +    /// Add an input to the PSBT.
 +    ///
 +    /// An input spending an outpoint already in the PSBT is joined with it.
 +    ///
 +    /// # Errors
-+    /// Returns the conflicting [`ResultConstructor`] if the two disagree.
-+    pub fn input(self, input: Input) -> Result<Self, ResultConstructor<InputsModifiable, S>> {
++    /// Returns [`ConstructorError::Conflict`] if the two disagree, or
++    /// [`ConstructorError::SortMode`] if the input has a sort key in
++    /// [`DerivedOnly`] mode.
++    pub fn input(self, input: Input) -> Result<Self, ConstructorError> {
 +        self.add_input(input)
 +    }
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +}
 +
-+impl Constructor<OutputsModifiable, Mixed> {
-+    /// Parse a v2 PSBT into an outputs-modifiable constructor.
-+    ///
-+    /// # Errors
-+    /// Returns [`ConstructorError::FlagsMismatch`] if `tx_modifiable_flags`
-+    /// does not have bit 1 set and bit 0 clear, or propagates lower-level
-+    /// unordered PSBT parse errors.
-+    pub fn try_from_psbt(psbt: Psbt) -> Result<Self, ConstructorError> {
-+        check_flags::<OutputsModifiable>(psbt.global.tx_modifiable_flags)?;
-+        Ok(Constructor::from_unordered(UnorderedPsbt::try_from_psbt(
-+            psbt,
-+        )?))
-+    }
-+}
-+
-+impl<S> Constructor<OutputsModifiable, S> {
++impl<S: SortMode> Constructor<OutputsModifiable, S> {
 +    /// Add an output to the PSBT.
 +    ///
 +    /// An output whose unique ID is already in the PSBT is joined with it.
 +    ///
 +    /// # Errors
 +    /// Returns [`ConstructorError::MissingUniqueId`] if the output has no
-+    /// `PSBT_OUT_UNIQUE_ID`, or [`ConstructorError::Conflict`] if it
-+    /// disagrees with the output already holding that ID.
++    /// `PSBT_OUT_UNIQUE_ID`, [`ConstructorError::Conflict`] if it disagrees
++    /// with the output already holding that ID, or
++    /// [`ConstructorError::SortMode`] if it has a sort key in
++    /// [`DerivedOnly`] mode.
 +    pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
 +        self.add_output(output)
 +    }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +        }
 +    }
 +
++    /// An empty PSBT whose sort fields select mixed, seeded mixed,
++    /// deterministic, seeded deterministic, or explicit mode.
++    fn psbt_with_mode(flags: u8, mode: usize, version: i32) -> Psbt {
++        let mut psbt = psbt_with_flags(flags, version);
++        match mode {
++            2 | 3 => psbt.global.set_sort_key_derivation(0x01),
++            4 => psbt.global.set_sort_key_derivation(0x00),
++            _ => {}
++        }
++        if mode == 1 || mode == 3 {
++            psbt.global
++                .set_sort_seed(SortSeed::try_from(vec![7; 16]).expect("16 bytes"));
++        }
++        psbt
++    }
++
 +    fn test_input(tag: u8) -> psbt_v2::v2::Input {
 +        use bitcoin::hashes::Hash;
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +            .expect("a seeded mixed PSBT without sort keys can be sorted");
 +        assert_eq!((ordered.inputs.len(), ordered.outputs.len()), (1, 1));
 +
-+        let deterministic = Constructor::<BothModifiable, DerivedOnly>::from_unordered(
-+            Constructor::<BothModifiable, Mixed>::try_from_psbt(psbt_with_flags(0x03, version))
-+                .unwrap()
-+                .into_inner(),
++        let deterministic = Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(
++            psbt_with_mode(0x03, 2, version),
 +        )
++        .unwrap()
 +        .set_seed(sort_seed)
 +        .no_more_outputs()
 +        .input(test_input(2))
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +                .unwrap();
 +
 +        input.sequence = Some(bitcoin::Sequence(2));
-+        let conflict = both
-+            .input(input)
-+            .expect_err("an outpoint spent with two sequences conflicts");
-+        assert!(!conflict.is_ok());
++        assert!(matches!(
++            both.input(input)
++                .expect_err("an outpoint spent with two sequences conflicts"),
++            ConstructorError::Conflict(_)
++        ));
 +
 +        output.amount = bitcoin::Amount::from_sat(2);
 +        let both =
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +            }
 +
 +            #[test]
-+            fn is_ok_agrees_with_try_unwrap(flags in 0u8..=0x03, version in any::<i32>()) {
-+                fn check<M: Modifiable>(psbt: Psbt) -> bool {
-+                    let result = ResultConstructor::<M, Mixed>::try_from_psbt(psbt)
++            fn unwraps_only_the_selected_typestate(
++                flags in 0u8..=0x03,
++                mode in 0usize..5,
++                version in any::<i32>(),
++            ) {
++                use crate::sorter::ExplicitOnly;
++
++                fn check<M: Modifiable, S: SortMode>(
++                    psbt: Psbt,
++                    expected: bool,
++                ) -> Result<(), TestCaseError> {
++                    let result = ResultConstructor::<M, S>::try_from_psbt(psbt.clone())
 +                        .expect("an empty PSBT has no duplicate identities");
-+                    result.is_ok() == result.try_unwrap().is_ok()
++                    prop_assert_eq!(result.is_ok(), expected);
++                    prop_assert_eq!(result.try_unwrap().is_ok(), expected);
++                    prop_assert_eq!(Constructor::<M, S>::try_from_psbt(psbt).is_ok(), expected);
++                    Ok(())
++                }
++
++                // A seeded PSBT also selects the unseeded mode it refines.
++                fn modes<M: Modifiable>(psbt: &Psbt, mode: usize) -> Result<(), TestCaseError> {
++                    let flags = psbt.global.tx_modifiable_flags == M::EXPECTED_FLAGS;
++                    check::<M, Mixed>(psbt.clone(), flags && mode <= 1)?;
++                    check::<M, Seeded<Mixed>>(psbt.clone(), flags && mode == 1)?;
++                    check::<M, DerivedOnly>(psbt.clone(), flags && (mode == 2 || mode == 3))?;
++                    check::<M, Seeded<DerivedOnly>>(psbt.clone(), flags && mode == 3)?;
++                    check::<M, ExplicitOnly>(psbt.clone(), flags && mode == 4)
 +                }
-+                prop_assert!(check::<BothModifiable>(psbt_with_flags(flags, version)));
-+                prop_assert!(check::<InputsModifiable>(psbt_with_flags(flags, version)));
-+                prop_assert!(check::<OutputsModifiable>(psbt_with_flags(flags, version)));
++
++                let psbt = psbt_with_mode(flags, mode, version);
++                modes::<BothModifiable>(&psbt, mode)?;
++                modes::<InputsModifiable>(&psbt, mode)?;
++                modes::<OutputsModifiable>(&psbt, mode)?;
++            }
++
++            #[test]
++            fn sort_fields_the_mode_ignores_are_rejected(version in any::<i32>()) {
++                use crate::input::{InputSortKeyExt, SortKey};
++                use crate::output::OutputSortKeyExt;
++                use crate::sorter::{ExplicitOnly, SortModeError};
++                use crate::tx::UnorderedPsbtError;
++
++                let deterministic = || {
++                    Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(
++                        psbt_with_mode(0x03, 2, version),
++                    )
++                    .expect("an empty deterministic PSBT")
++                };
++                let key = || SortKey::try_from(vec![1]).expect("one byte");
++                let mut input = test_input(1);
++                input.set_sort_key(key());
++                let mut output = test_output(1);
++                output.set_sort_key(key());
++                for error in [
++                    deterministic().input(input).unwrap_err(),
++                    deterministic().output(output).unwrap_err(),
++                ] {
++                    prop_assert!(error.to_string().contains("derived-only"));
++                    prop_assert!(matches!(
++                        error,
++                        ConstructorError::SortMode(SortModeError::UnexpectedSortKey)
++                    ));
++                }
++
++                // Parsing rejects a seed under explicit sort keys before the
++                // sort mode is checked.
++                let mut seeded_explicit = psbt_with_mode(0x03, 1, version);
++                seeded_explicit.global.set_sort_key_derivation(0x00);
++                prop_assert!(matches!(
++                    Constructor::<BothModifiable, ExplicitOnly>::try_from_psbt(seeded_explicit),
++                    Err(ConstructorError::Unordered(UnorderedPsbtError::UnexpectedSortSeed))
++                ));
 +            }
 +
 +            #[test]
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +use psbt_v2::v2::Psbt;
 +
 +use crate::lattice::join::Join;
-+use crate::sorter::Mixed;
++use crate::sorter::{SortMode, check_sort_mode};
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
 +use super::{Constructor, Modifiable};
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +    pub(super) PhantomData<(M, S)>,
 +);
 +
-+impl<M> ResultConstructor<M, Mixed> {
++impl<M, S> ResultConstructor<M, S> {
 +    /// Parse a v2 PSBT directly into the result domain.
 +    ///
 +    /// This is the entry point for N-way joins: parse each PSBT into
 +    /// `ResultConstructor`, then fold with `Join`.
 +    ///
 +    /// Unlike `Constructor::try_from_psbt`, this does **not** validate
-+    /// `tx_modifiable_flags`. In the result domain, PSBTs with differing
-+    /// flags are loaded as-is; flag mismatches surface as conflicts
-+    /// when joined, which is the correct behavior for N-way merges.
++    /// `tx_modifiable_flags` or the sort fields. In the result domain, PSBTs
++    /// with differing flags are loaded as-is; mismatches surface when
++    /// joined, which is the correct behavior for N-way merges.
 +    ///
 +    /// # Errors
 +    /// Returns the errors of [`ResultUnorderedPsbt::try_from_psbt`].
@@ crates/concurrent-psbt/src/roles/constructor/result.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiable, S> ResultConstructor<M, S> {
-+    /// Return `true` if [`try_unwrap`](Self::try_unwrap) would succeed: every
-+    /// field is conflict-free and `tx_modifiable_flags` match `M`.
++impl<M: Modifiable, S: SortMode> ResultConstructor<M, S> {
++    /// Return `true` if [`try_unwrap`](Self::try_unwrap) would succeed.
 +    pub fn is_ok(&self) -> bool {
-+        self.0.is_ok()
-+            && self
-+                .0
-+                .global
-+                .tx_modifiable_flags
-+                .as_ref()
-+                .ok()
-+                .map(|flags| flags & 0x03)
-+                == Some(M::EXPECTED_FLAGS)
-+    }
-+
-+    /// Extract a clean [`Constructor`] if no conflicts remain and
-+    /// `tx_modifiable_flags` match `M`.
++        ResultConstructor::<M, S>(self.0.clone(), PhantomData)
++            .try_unwrap()
++            .is_ok()
++    }
++
++    /// Extract a clean [`Constructor`] if no conflicts remain,
++    /// `tx_modifiable_flags` match `M`, and the sort fields select `S`.
 +    ///
 +    /// # Errors
-+    /// Returns `Err(self)` if any field contains a conflict, or if the resolved
-+    /// `tx_modifiable_flags` don't match `M::EXPECTED_FLAGS`.
++    /// Returns `Err(self)` otherwise.
 +    pub fn try_unwrap(self) -> Result<Constructor<M, S>, Self> {
 +        match self.0.try_unwrap() {
-+            Ok(psbt) => {
-+                if psbt.global.tx_modifiable_flags & 0x03 != M::EXPECTED_FLAGS {
-+                    // Flags don't match the type parameter. Wrap back and return Err.
-+                    Err(ResultConstructor(psbt.wrap(), PhantomData))
-+                } else {
-+                    Ok(Constructor(psbt, PhantomData))
-+                }
++            Ok(psbt)
++                if psbt.global.tx_modifiable_flags & 0x03 == M::EXPECTED_FLAGS
++                    && check_sort_mode::<S>(&psbt).is_ok() =>
++            {
++                Ok(Constructor(psbt, PhantomData))
 +            }
++            Ok(psbt) => Err(ResultConstructor(psbt.wrap(), PhantomData)),
 +            Err(result) => Err(ResultConstructor(result, PhantomData)),
 +        }
 +    }
2: eaf668d595 ! 2: 2badec25e6 Constructor: allow sorting while modifiable
@@ Commit message
     BIP 370 constructor.
 
  ## crates/concurrent-psbt/src/roles/constructor/mod.rs ##
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M> Constructor<M, DerivedOnly> {
- }
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M: Modifiable, S: SortMode> Constructor<M, S> {
+         Ok(Constructor::from_unordered(psbt))
+     }
  
- impl<M: Modifiable, S> Constructor<M, S> {
 +    /// Move on to the [`Sorter`] while inputs and outputs stay as modifiable
 +    /// as they are. Sorting then hands the PSBT to the BIP 370
 +    /// [`Constructor`](psbt_v2::v2::Constructor) of the same modifiability,
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M> Constructor<M, Deri
 +
      /// Join with a PSBT that shares this one's global fields and holds only
      /// the given inputs and outputs.
-     fn join_with(self, inputs: InputSet, outputs: OutputSet) -> ResultConstructor<M, S> {
+     fn join_with(self, inputs: InputSet, outputs: OutputSet) -> Result<Self, ConstructorError> {
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
          assert_eq!(ordered.inputs.len(), 1);
      }

@yuval-block
yuval-block force-pushed the constructor branch 2 times, most recently from 06a6e9a to ded2f3f Compare November 14, 2026 07:01
@yuval-block
yuval-block force-pushed the constructor branch 2 times, most recently from 533330d to e3bd458 Compare November 14, 2026 08:10
@github-actions

Copy link
Copy Markdown
range-diff for force push 2badec25e6 → 06a6e9a687 November 14, 2026 08:29 UTC: 2 modified; 2 commits; base 1a90913800 → 9f9eadc5bf (diverged, 9 ahead and 7 behind)

reproduce: git range-diff 1a90913..2badec2 9f9eadc..06a6e9a

1:  7b3df08697 +934 -1 6f ! 1:  e2099d4f45 +962 -1 6f introduce Constructor role
2:  2badec25e6 +112 -0 1f ! 2:  06a6e9a687 +112 -0 1f Constructor: allow sorting while modifiable
1: 7b3df08697 ! 1: e2099d4f45 introduce Constructor role
@@ crates/concurrent-psbt/src/psbt/tx.rs: fn duplicate_sort_key<'a>(mut keys: impl
 +    }
 +}
 +
- /// The declared count and set size, if they disagree.
- fn count_mismatch(declared: usize, len: usize) -> Option<Conflict<usize>> {
-     (declared != len).then(|| Conflict::from_values([declared, len]))
+ impl UnorderedPsbt {
+     /// Parse a v2 PSBT into unordered representation.
+     ///
 
  ## crates/concurrent-psbt/src/roles/constructor/error.rs (new) ##
 @@
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +
 +use bitcoin::OutPoint;
 +
-+use crate::output::{OutputSetError, UniqueId};
++use crate::output::UniqueId;
 +use crate::sorter::{FlagsMismatch, SortModeError};
 +use crate::tx::{ResultUnorderedPsbt, UnorderedPsbtError};
 +
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +    DuplicateInput(OutPoint),
 +    /// Two outputs carry the same `PSBT_OUT_UNIQUE_ID`.
 +    DuplicateUniqueId(UniqueId),
-+    /// The unordered PSBT accumulated conflicting fields while parsing.
++    /// An added input or output conflicts with the one already spending that
++    /// outpoint or carrying that unique ID.
 +    Conflict(Box<ResultUnorderedPsbt>),
-+    /// The PSBT is not marked unordered, its unordered or sort flags are
-+    /// malformed, its sort fields break its sort mode or repeat a sort key, or
-+    /// its sort seed, a sort key, or an output's unique ID has an invalid size.
++    /// The PSBT's declared counts disagree with its inputs and outputs, it is
++    /// not marked unordered, its unordered or sort flags are malformed, its
++    /// sort fields break its sort mode or repeat a sort key, or its sort seed,
++    /// a sort key, or an output's unique ID has an invalid size.
 +    Unordered(UnorderedPsbtError),
 +    /// The PSBT's sort fields don't select the requested sort mode.
 +    SortMode(SortModeError),
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +    }
 +}
 +
-+impl From<OutputSetError> for ConstructorError {
-+    fn from(error: OutputSetError) -> Self {
-+        UnorderedPsbtError::from(error).into()
-+    }
-+}
-+
 +impl From<UnorderedPsbtError> for ConstructorError {
 +    fn from(error: UnorderedPsbtError) -> Self {
 +        match error {
@@ crates/concurrent-psbt/src/roles/constructor/error.rs (new)
 +            UnorderedPsbtError::DuplicateOutputUniqueId(unique_id) => {
 +                Self::DuplicateUniqueId(unique_id)
 +            }
-+            UnorderedPsbtError::Conflict(result) => Self::Conflict(result),
-+            error @ (UnorderedPsbtError::InvalidUnorderedFlag(_)
++            error @ (UnorderedPsbtError::InputCountMismatch { .. }
++            | UnorderedPsbtError::OutputCountMismatch { .. }
++            | UnorderedPsbtError::InvalidUnorderedFlag(_)
 +            | UnorderedPsbtError::InvalidSortKeyDerivation(_)
 +            | UnorderedPsbtError::NotUnordered
 +            | UnorderedPsbtError::UnorderedSighashSingle
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +
 +use std::marker::PhantomData;
 +
-+use psbt_v2::v2::{DetermineLockTimeError, Input, Output, Psbt};
++use bitcoin::{Amount, ScriptBuf};
++use psbt_v2::v2::{DetermineLockTimeError, Psbt};
 +
 +use crate::global::{GlobalSortExt, SortSeed};
-+use crate::input::InputSet;
++use crate::input::{Input, InputSet};
 +use crate::lattice::join::Join;
-+use crate::output::{OutputSet, OutputUniqueIdExt, UniqueId};
++use crate::output::{Output, OutputSet, UniqueId};
 +use crate::sorter::{
 +    BothModifiable, DerivedOnly, InputsModifiable, Mixed, Modifiable, OutputsModifiable, Seeded,
 +    SortMode, Sorter, Unmodifiable, check_flags, check_sort_mode,
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// modifiable, so they join cleanly with these whether or not they are
 +    /// frozen.
 +    fn add_output(self, output: Output) -> Result<Self, ConstructorError> {
-+        let outputs = OutputSet::try_from_outputs([output])?;
++        let outputs = OutputSet::try_from_outputs([output]).expect("a single output cannot repeat");
 +        self.join_with(InputSet::default(), outputs)
 +    }
 +}
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// An output whose unique ID is already in the PSBT is joined with it.
 +    ///
 +    /// # Errors
-+    /// Returns [`ConstructorError::MissingUniqueId`] if the output has no
-+    /// `PSBT_OUT_UNIQUE_ID`, [`ConstructorError::Conflict`] if it disagrees
-+    /// with the output already holding that ID, or
++    /// Returns [`ConstructorError::Conflict`] if it disagrees with the output
++    /// already holding that ID, or
 +    /// [`ConstructorError::SortMode`] if it has a sort key in
 +    /// [`DerivedOnly`] mode.
 +    pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
 +        self.add_output(output)
 +    }
 +
-+    /// Add an output, stamping a freshly generated [`UniqueId`].
++    /// Add an output paying `amount` to `script_pubkey`, with a freshly
++    /// generated [`UniqueId`].
 +    ///
 +    /// Each call generates a new random `PSBT_OUT_UNIQUE_ID`, so adding
 +    /// copies of the same txout yields distinct outputs.
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// # Errors
 +    /// Returns [`ConstructorError::Conflict`] if the generated ID collides
 +    /// with an output that disagrees with this one.
-+    pub fn output_with_new_uid(self, mut output: Output) -> Result<Self, ConstructorError> {
-+        output.set_unique_id(UniqueId::generate());
-+        self.output(output)
++    pub fn output_with_new_uid(
++        self,
++        amount: Amount,
++        script_pubkey: ScriptBuf,
++    ) -> Result<Self, ConstructorError> {
++        self.output(Output::new(UniqueId::generate(), amount, script_pubkey))
 +    }
 +
 +    /// Transition to [`OutputsModifiable`]: no more inputs will be added.
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// An output whose unique ID is already in the PSBT is joined with it.
 +    ///
 +    /// # Errors
-+    /// Returns [`ConstructorError::MissingUniqueId`] if the output has no
-+    /// `PSBT_OUT_UNIQUE_ID`, [`ConstructorError::Conflict`] if it disagrees
-+    /// with the output already holding that ID, or
++    /// Returns [`ConstructorError::Conflict`] if it disagrees with the output
++    /// already holding that ID, or
 +    /// [`ConstructorError::SortMode`] if it has a sort key in
 +    /// [`DerivedOnly`] mode.
 +    pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
 +        self.add_output(output)
 +    }
 +
-+    /// Add an output, stamping a freshly generated [`UniqueId`].
++    /// Add an output paying `amount` to `script_pubkey`, with a freshly
++    /// generated [`UniqueId`].
 +    ///
 +    /// Each call generates a new random `PSBT_OUT_UNIQUE_ID`, so adding
 +    /// copies of the same txout yields distinct outputs.
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    /// # Errors
 +    /// Returns [`ConstructorError::Conflict`] if the generated ID collides
 +    /// with an output that disagrees with this one.
-+    pub fn output_with_new_uid(self, mut output: Output) -> Result<Self, ConstructorError> {
-+        output.set_unique_id(UniqueId::generate());
-+        self.output(output)
++    pub fn output_with_new_uid(
++        self,
++        amount: Amount,
++        script_pubkey: ScriptBuf,
++    ) -> Result<Self, ConstructorError> {
++        self.output(Output::new(UniqueId::generate(), amount, script_pubkey))
 +    }
 +
 +    /// Finalize outputs and transition to the [`Sorter`] for ordering.
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +
 +    type TestConstructor = Constructor<BothModifiable, Mixed>;
 +
-+    fn empty_constructor() -> TestConstructor {
-+        let mut global = psbt_v2::v2::Global {
-+            tx_modifiable_flags: 0x03,
-+            ..psbt_v2::v2::Global::default()
++    /// A [`Global`](crate::global::Global) marked unordered, with these
++    /// flags and transaction version.
++    fn unordered_global(flags: u8, version: i32) -> crate::global::Global {
++        let mut global = crate::global::Global {
++            tx_modifiable_flags: flags,
++            tx_version: bitcoin::transaction::Version(version),
++            ..crate::global::Global::default()
 +        };
 +        global.set_unordered();
++        global
++    }
++
++    /// A BIP 370 PSBT with this global map, inputs and outputs.
++    fn psbt_with(
++        global: crate::global::Global,
++        inputs: Vec<psbt_v2::v2::Input>,
++        outputs: Vec<psbt_v2::v2::Output>,
++    ) -> Psbt {
++        Psbt {
++            global: global.into_v2(inputs.len(), outputs.len()),
++            inputs,
++            outputs,
++        }
++    }
++
++    /// An empty BIP 370 PSBT with this global map.
++    fn empty_psbt(global: crate::global::Global) -> Psbt {
++        psbt_with(global, vec![], vec![])
++    }
++
++    fn empty_constructor() -> TestConstructor {
 +        Constructor(
 +            UnorderedPsbt {
-+                global,
++                global: unordered_global(0x03, 2),
 +                inputs: crate::input::InputSet::default(),
 +                outputs: crate::output::OutputSet::default(),
 +            },
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +    }
 +
 +    fn psbt_with_flags(flags: u8, version: i32) -> Psbt {
-+        let mut global = psbt_v2::v2::Global {
-+            tx_modifiable_flags: flags,
-+            tx_version: bitcoin::transaction::Version(version),
-+            ..psbt_v2::v2::Global::default()
-+        };
-+        global.set_unordered();
-+        Psbt {
-+            global,
-+            inputs: vec![],
-+            outputs: vec![],
-+        }
++        empty_psbt(unordered_global(flags, version))
 +    }
 +
 +    /// An empty PSBT whose sort fields select mixed, seeded mixed,
 +    /// deterministic, seeded deterministic, or explicit mode.
 +    fn psbt_with_mode(flags: u8, mode: usize, version: i32) -> Psbt {
-+        let mut psbt = psbt_with_flags(flags, version);
++        empty_psbt(global_with_mode(flags, mode, version))
++    }
++
++    fn global_with_mode(flags: u8, mode: usize, version: i32) -> crate::global::Global {
++        let mut global = unordered_global(flags, version);
 +        match mode {
-+            2 | 3 => psbt.global.set_sort_key_derivation(0x01),
-+            4 => psbt.global.set_sort_key_derivation(0x00),
++            2 | 3 => global.set_sort_key_derivation(0x01),
++            4 => global.set_sort_key_derivation(0x00),
 +            _ => {}
 +        }
 +        if mode == 1 || mode == 3 {
-+            psbt.global
-+                .set_sort_seed(SortSeed::try_from(vec![7; 16]).expect("16 bytes"));
++            global.set_sort_seed(SortSeed::try_from(vec![7; 16]).expect("16 bytes"));
 +        }
-+        psbt
++        global
 +    }
 +
-+    fn test_input(tag: u8) -> psbt_v2::v2::Input {
++    fn test_input(tag: u8) -> Input {
 +        use bitcoin::hashes::Hash;
 +
-+        psbt_v2::v2::Input::new(&bitcoin::OutPoint {
++        Input::new(&bitcoin::OutPoint {
 +            txid: bitcoin::Txid::from_byte_array([tag; 32]),
 +            vout: u32::from(tag),
 +        })
 +    }
 +
-+    fn test_output(tag: u8) -> psbt_v2::v2::Output {
-+        use crate::output::{OutputUniqueIdExt, UniqueId};
-+
-+        let mut output = psbt_v2::v2::Output::default();
-+        output.set_unique_id(UniqueId::new(vec![tag]));
-+        output
++    fn test_output(tag: u8) -> Output {
++        Output::new(UniqueId::new(vec![tag]), Amount::ZERO, ScriptBuf::new())
 +    }
 +
 +    fn exercise_modifiability_transitions(version: i32) {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +        assert_eq!(outputs.no_more_outputs().into_inner().outputs.len(), 1);
 +
 +        // Each call stamps a fresh unique ID, so copies of one txout stay distinct.
-+        let txout = psbt_v2::v2::Output::default();
 +        let both = empty_constructor()
-+            .output_with_new_uid(txout.clone())
++            .output_with_new_uid(Amount::ZERO, ScriptBuf::new())
 +            .unwrap()
-+            .output_with_new_uid(txout.clone())
++            .output_with_new_uid(Amount::ZERO, ScriptBuf::new())
 +            .unwrap();
 +        assert_eq!(both.0.outputs.len(), 2);
-+        let outputs = both.no_more_inputs().output_with_new_uid(txout).unwrap();
++        let outputs = both
++            .no_more_inputs()
++            .output_with_new_uid(Amount::ZERO, ScriptBuf::new())
++            .unwrap();
 +        assert_eq!(outputs.0.outputs.len(), 3);
 +    }
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +        ));
 +
 +        for error in [
-+            Constructor::<BothModifiable, Mixed>::try_from_psbt({
-+                let mut psbt = psbt_with_flags(0x03, version);
-+                psbt.outputs.push(psbt_v2::v2::Output::default());
-+                psbt
-+            })
++            Constructor::<BothModifiable, Mixed>::try_from_psbt(psbt_with(
++                unordered_global(0x03, version),
++                vec![],
++                vec![psbt_v2::v2::Output::default()],
++            ))
 +            .expect_err("output identity is required"),
-+            Constructor::<InputsModifiable, Mixed>::try_from_psbt({
-+                let mut psbt = psbt_with_flags(0x01, version);
-+                psbt.outputs.push(psbt_v2::v2::Output::default());
-+                psbt
-+            })
++            Constructor::<InputsModifiable, Mixed>::try_from_psbt(psbt_with(
++                unordered_global(0x01, version),
++                vec![],
++                vec![psbt_v2::v2::Output::default()],
++            ))
 +            .expect_err("output identity is required"),
-+            Constructor::<OutputsModifiable, Mixed>::try_from_psbt({
-+                let mut psbt = psbt_with_flags(0x02, version);
-+                psbt.outputs.push(psbt_v2::v2::Output::default());
-+                psbt
-+            })
++            Constructor::<OutputsModifiable, Mixed>::try_from_psbt(psbt_with(
++                unordered_global(0x02, version),
++                vec![],
++                vec![psbt_v2::v2::Output::default()],
++            ))
 +            .expect_err("output identity is required"),
 +        ] {
 +            assert!(matches!(error, ConstructorError::MissingUniqueId(_)));
 +            assert!(error.to_string().contains("PSBT_OUT_UNIQUE_ID"));
 +        }
 +
-+        let mut duplicate_inputs = psbt_with_flags(0x03, version);
-+        duplicate_inputs.inputs = vec![test_input(4), test_input(4)];
++        let duplicate_inputs = psbt_with(
++            unordered_global(0x03, version),
++            vec![test_input(4).into(), test_input(4).into()],
++            vec![],
++        );
 +        let duplicate = Constructor::<BothModifiable, Mixed>::try_from_psbt(duplicate_inputs)
 +            .expect_err("a repeated outpoint is rejected");
 +        assert!(matches!(duplicate, ConstructorError::DuplicateInput(_)));
 +        assert!(duplicate.to_string().contains("two inputs spend"));
 +
-+        let mut duplicate_outputs = psbt_with_flags(0x03, version);
-+        duplicate_outputs.outputs = vec![test_output(4), test_output(4)];
++        let duplicate_outputs = psbt_with(
++            unordered_global(0x03, version),
++            vec![],
++            vec![test_output(4).into(), test_output(4).into()],
++        );
 +        let duplicate = Constructor::<BothModifiable, Mixed>::try_from_psbt(duplicate_outputs)
 +            .expect_err("a repeated unique ID is rejected");
 +        assert!(matches!(duplicate, ConstructorError::DuplicateUniqueId(_)));
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +
 +        let mut miscounted = psbt_with_flags(0x03, version);
 +        miscounted.global.input_count = 1;
-+        let conflict = Constructor::<BothModifiable, Mixed>::try_from_psbt(miscounted)
-+            .expect_err("a declared count that disagrees conflicts");
-+        assert!(matches!(conflict, ConstructorError::Conflict(_)));
-+        assert!(conflict.to_string().contains("conflicting fields"));
-+
-+        let mut ordered = psbt_with_flags(0x03, version);
-+        ordered.global.clear_unordered();
-+        let ordered = Constructor::<BothModifiable, Mixed>::try_from_psbt(ordered)
++        let miscounted = Constructor::<BothModifiable, Mixed>::try_from_psbt(miscounted)
++            .expect_err("a declared count that disagrees is rejected");
++        assert!(matches!(
++            miscounted,
++            ConstructorError::Unordered(crate::tx::UnorderedPsbtError::InputCountMismatch {
++                declared: 1,
++                found: 0
++            })
++        ));
++
++        let mut ordered = unordered_global(0x03, version);
++        ordered.clear_unordered();
++        let ordered = Constructor::<BothModifiable, Mixed>::try_from_psbt(empty_psbt(ordered))
 +            .expect_err("a PSBT read as unordered must be marked unordered");
 +        let expected = crate::tx::UnorderedPsbtError::NotUnordered;
 +        assert_eq!(ordered.to_string(), expected.to_string());
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +                .expect_err("a unique ID with two amounts conflicts"),
 +            ConstructorError::Conflict(_)
 +        ));
-+        assert!(matches!(
-+            Constructor::<BothModifiable, Mixed>::try_from_psbt(psbt_with_flags(0x03, version))
-+                .expect("both-modifiable flags are valid")
-+                .output(psbt_v2::v2::Output::default())
-+                .expect_err("output identity is required"),
-+            ConstructorError::MissingUniqueId(0)
-+        ));
 +    }
 +
 +    #[cfg(feature = "unit-tests")]
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +
 +                // Parsing rejects a seed under explicit sort keys before the
 +                // sort mode is checked.
-+                let mut seeded_explicit = psbt_with_mode(0x03, 1, version);
-+                seeded_explicit.global.set_sort_key_derivation(0x00);
++                let mut seeded_explicit = global_with_mode(0x03, 1, version);
++                seeded_explicit.set_sort_key_derivation(0x00);
 +                prop_assert!(matches!(
-+                    Constructor::<BothModifiable, ExplicitOnly>::try_from_psbt(seeded_explicit),
++                    Constructor::<BothModifiable, ExplicitOnly>::try_from_psbt(empty_psbt(seeded_explicit)),
 +                    Err(ConstructorError::Unordered(UnorderedPsbtError::UnexpectedSortSeed))
 +                ));
 +            }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +            fn output_without_unique_id_is_rejected(version in any::<i32>()) {
 +                let mut psbt = constructor_with_version(version).try_into_psbt().unwrap();
 +                psbt.outputs.push(psbt_v2::v2::Output::default());
-+                prop_assert!(ResultConstructor::<BothModifiable, Mixed>::try_from_psbt(psbt).is_err());
++                psbt.global.output_count += 1;
++                prop_assert!(matches!(
++                    ResultConstructor::<BothModifiable, Mixed>::try_from_psbt(psbt),
++                    Err(crate::tx::UnorderedPsbtError::MissingOutputUniqueId(0))
++                ));
 +            }
 +        }
 +    }
2: 2badec25e6 ! 2: 06a6e9a687 Constructor: allow sorting while modifiable
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +        let sort_seed = SortSeed::try_from(seed).expect("test seeds are at least 16 bytes");
 +
 +        let seeded = |flags| {
-+            let mut psbt = psbt_with_flags(flags, version);
-+            psbt.global.set_sort_seed(sort_seed.clone());
-+            psbt
++            let mut global = unordered_global(flags, version);
++            global.set_sort_seed(sort_seed.clone());
++            empty_psbt(global)
 +        };
 +        let txids = |psbt: &Psbt| {
 +            psbt.inputs
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +            .into_sorter()
 +            .try_sort()
 +            .expect("a seeded PSBT can be sorted")
-+            .input(test_input(4))
++            .input(test_input(4).into())
 +            .psbt()
 +            .expect("inputs carry no lock time requirements");
-+        assert!(!both.global.is_unordered());
++        assert!(!crate::global::Global::from(both.global.clone()).is_unordered());
 +        assert_eq!(both.global.tx_modifiable_flags & 0x03, 0x03);
 +        assert_eq!(txids(&both), expected);
 +
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +            .into_sorter()
 +            .try_sort()
 +            .unwrap()
-+            .input(test_input(4))
++            .input(test_input(4).into())
 +            .psbt()
 +            .unwrap();
 +        assert_eq!(inputs.global.tx_modifiable_flags & 0x03, 0x01);
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +            .into_sorter()
 +            .try_sort()
 +            .unwrap()
-+            .output(test_output(2))
++            .output(test_output(2).into())
 +            .psbt()
 +            .unwrap();
 +        assert_eq!(outputs.global.tx_modifiable_flags & 0x03, 0x02);
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +            .into_sorter()
 +            .try_sort()
 +            .unwrap()
-+            .input(test_input(2))
++            .input(test_input(2).into())
 +            .psbt()
 +            .unwrap();
 +        assert_eq!(inputs.global.tx_modifiable_flags & 0x03, 0x01);

@github-actions

Copy link
Copy Markdown
range-diff for force push 533330d9a2 → e3bd458414 November 14, 2026 09:08 UTC: 1 modified, 1 unchanged; 2 commits; base 4eec3a6ad7 → a288fe651f (diverged, 10 ahead and 10 behind)

reproduce: git range-diff 4eec3a6..533330d a288fe6..e3bd458

1:  6221272bfa +962 -1 6f ! 1:  43a9a7c08d +962 -1 6f introduce Constructor role
2:  533330d9a2 +116 -0 1f = 2:  e3bd458414 +116 -0 1f Constructor: allow sorting while modifiable
1: 6221272bfa ! 1: 43a9a7c08d introduce Constructor role
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +                .unwrap();
 +
 +        input.sequence = Some(bitcoin::Sequence(2));
-+        assert!(matches!(
-+            both.input(input)
-+                .expect_err("an outpoint spent with two sequences conflicts"),
-+            ConstructorError::Conflict(_)
-+        ));
++        let conflict = both
++            .input(input)
++            .expect_err("an outpoint spent with two sequences conflicts");
++        assert!(conflict.to_string().contains("conflicting fields"));
++        assert!(matches!(conflict, ConstructorError::Conflict(_)));
 +
 +        output.amount = bitcoin::Amount::from_sat(2);
 +        let both =

@github-actions

Copy link
Copy Markdown
range-diff for force push 533330d9a2 → e3bd458414 November 14, 2026 09:08 UTC: 1 modified, 1 unchanged; 2 commits; base 4eec3a6ad7 → a288fe651f (diverged, 10 ahead and 10 behind)

reproduce: git range-diff 4eec3a6..533330d a288fe6..e3bd458

1:  6221272bfa +962 -1 6f ! 1:  43a9a7c08d +962 -1 6f introduce Constructor role
2:  533330d9a2 +116 -0 1f = 2:  e3bd458414 +116 -0 1f Constructor: allow sorting while modifiable
1: 6221272bfa ! 1: 43a9a7c08d introduce Constructor role
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs (new)
 +                .unwrap();
 +
 +        input.sequence = Some(bitcoin::Sequence(2));
-+        assert!(matches!(
-+            both.input(input)
-+                .expect_err("an outpoint spent with two sequences conflicts"),
-+            ConstructorError::Conflict(_)
-+        ));
++        let conflict = both
++            .input(input)
++            .expect_err("an outpoint spent with two sequences conflicts");
++        assert!(conflict.to_string().contains("conflicting fields"));
++        assert!(matches!(conflict, ConstructorError::Conflict(_)));
 +
 +        output.amount = bitcoin::Amount::from_sat(2);
 +        let both =

@github-actions

Copy link
Copy Markdown
range-diff for force push bb9dfa0fd7 → 04dc575e48 November 15, 2026 12:51 UTC: 2 unchanged; 2 commits; base 3aa1adfcdf → 87fe755391 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 3aa1adf..bb9dfa0 87fe755..04dc575

1:  588a261cdb +1109 -1 6f = 1:  ec428fe130 +1109 -1 6f introduce Constructor role
2:  bb9dfa0fd7   +95 -0 1f = 2:  04dc575e48   +95 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push bb9dfa0fd7 → 04dc575e48 November 15, 2026 12:51 UTC: 2 unchanged; 2 commits; base 3aa1adfcdf → 87fe755391 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 3aa1adf..bb9dfa0 87fe755..04dc575

1:  588a261cdb +1109 -1 6f = 1:  ec428fe130 +1109 -1 6f introduce Constructor role
2:  bb9dfa0fd7   +95 -0 1f = 2:  04dc575e48   +95 -0 1f Constructor: allow sorting while modifiable

@github-code-quality

github-code-quality Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Code coverage overview

Languages: Rust

Rust / code-coverage/cargo-llvm-cov

sorter 5f4ab3b constructor 4407fe7 +/-
100% 100% 0%
View coverage of the 10 most impacted files.
File sorter 5f4ab3b constructor 4407fe7 +/-
crates/concurre.../src/psbt/tx.rs 0% 100% +100%
crates/concurre...bt/keyed_set.rs 0% 100% +100%
crates/concurre...s/sorter/mod.rs 0% 100% +100%
crates/concurre...structor/mod.rs 0% 100% +100%
crates/concurre.../psbt/global.rs 0% 100% +100%
crates/concurre...bt/input_set.rs 0% 100% +100%
crates/concurre...t/output_set.rs 0% 100% +100%
crates/concurre...sorter/error.rs 0% 100% +100%
crates/concurre...s/sorter/key.rs 0% 100% +100%
crates/concurre...sorter/order.rs 0% 100% +100%

ℹ️ Calculations represent line coverage. Results may change as calculations are updated.


Updated November 16, 2026 23:45 UTC

@github-actions

Copy link
Copy Markdown
range-diff for force push 04dc575e48 → 638d7d0739 November 15, 2026 23:52 UTC: 2 unchanged; 2 commits; base 87fe755391 → 4731f8255c (diverged, 12 ahead and 12 behind)

reproduce: git range-diff 87fe755..04dc575 4731f82..638d7d0

1:  ec428fe130 +1109 -1 6f = 1:  03600c6149 +1109 -1 6f introduce Constructor role
2:  04dc575e48   +95 -0 1f = 2:  638d7d0739   +95 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push 04dc575e48 → 638d7d0739 November 15, 2026 23:52 UTC: 2 unchanged; 2 commits; base 87fe755391 → 4731f8255c (diverged, 12 ahead and 12 behind)

reproduce: git range-diff 87fe755..04dc575 4731f82..638d7d0

1:  ec428fe130 +1109 -1 6f = 1:  03600c6149 +1109 -1 6f introduce Constructor role
2:  04dc575e48   +95 -0 1f = 2:  638d7d0739   +95 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push 638d7d0739 → 7c329c3e9a November 16, 2026 00:16 UTC: 2 unchanged; 2 commits; base 4731f8255c → 77c85c7473 (diverged, 9 ahead and 9 behind)

reproduce: git range-diff 4731f82..638d7d0 77c85c7..7c329c3

1:  03600c6149 +1109 -1 6f = 1:  7f5fcb2729 +1109 -1 6f introduce Constructor role
2:  638d7d0739   +95 -0 1f = 2:  7c329c3e9a   +95 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push 638d7d0739 → 7c329c3e9a November 16, 2026 00:16 UTC: 2 unchanged; 2 commits; base 4731f8255c → 77c85c7473 (diverged, 9 ahead and 9 behind)

reproduce: git range-diff 4731f82..638d7d0 77c85c7..7c329c3

1:  03600c6149 +1109 -1 6f = 1:  7f5fcb2729 +1109 -1 6f introduce Constructor role
2:  638d7d0739   +95 -0 1f = 2:  7c329c3e9a   +95 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push 7c329c3e9a → ce5df60a15 November 16, 2026 03:25 UTC: 2 unchanged; 2 commits; base 77c85c7473 → 1437300440 (diverged, 12 ahead and 12 behind)

reproduce: git range-diff 77c85c7..7c329c3 1437300..ce5df60

1:  7f5fcb2729 +1109 -1 6f = 1:  cae313c721 +1109 -1 6f introduce Constructor role
2:  7c329c3e9a   +95 -0 1f = 2:  ce5df60a15   +95 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push ce5df60a15 → 99254980d7 November 16, 2026 04:44 UTC: 2 unchanged; 2 commits; base 1437300440 → b116e2b0d0 (diverged, 12 ahead and 12 behind)

reproduce: git range-diff 1437300..ce5df60 b116e2b..9925498

1:  cae313c721 +1109 -1 6f = 1:  505a641562 +1109 -1 6f introduce Constructor role
2:  ce5df60a15   +95 -0 1f = 2:  99254980d7   +95 -0 1f Constructor: allow sorting while modifiable

@github-actions

Copy link
Copy Markdown
range-diff for force push 99254980d7 → adbd771ae0 November 16, 2026 06:07 UTC: 2 unchanged; 2 commits; base b116e2b0d0 → edd21a260c (diverged, 12 ahead and 12 behind)

reproduce: git range-diff b116e2b..9925498 edd21a2..adbd771

1:  505a641562 +1109 -1 6f = 1:  c977c184ed +1109 -1 6f introduce Constructor role
2:  99254980d7   +95 -0 1f = 2:  adbd771ae0   +95 -0 1f Constructor: allow sorting while modifiable

Add Constructor<M, S> and ResultConstructor<M, S>, which provide a
typesafe interface to unordered PSBT mutation modeled after the upstream
psbt_v2 crate's interface for BIP 174 and 370.

This currently only supports same-modifiability Constructors to be
joined. The logical AND of the modifiability flags allows mixed
modifiability constructors to be joined in principle, but this is not
implemented in this commit.
The result of sorting before the sets are frozen is just a modifiable
BIP 370 constructor.
@github-actions

Copy link
Copy Markdown
range-diff for force push adbd771ae0 → dfb127c290 November 16, 2026 18:20 UTC: 2 unchanged; 2 commits; base edd21a260c → 709312404d (diverged, 8 ahead and 8 behind)

reproduce: git range-diff edd21a2..adbd771 7093124..dfb127c

1:  c977c184ed +1109 -1 6f = 1:  5efa19cd5e +1109 -1 6f introduce Constructor role
2:  adbd771ae0   +95 -0 1f = 2:  dfb127c290   +95 -0 1f Constructor: allow sorting while modifiable

/// Move on to the [`Sorter`] while inputs and outputs stay as modifiable
/// as they are. Sorting then hands the PSBT to the BIP 370
/// [`Constructor`](psbt_v2::v2::Constructor) of the same modifiability,
/// which adds further inputs and outputs after the sorted ones.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Doc promises outputs from inputs-only handoff

into_sorter's doc says sorting hands the PSBT to the BIP 370 constructor of the same modifiability, "which adds further inputs and outputs", but InputsModifiable hands off to v2::Constructor<InputsOnlyModifiable> (only input) and OutputsModifiable to OutputsOnlyModifiable (only output). A reader of a partly modifiable constructor is promised additions the handed-off constructor cannot make.

/// is handed to: the matching BIP 370 constructor while inputs or outputs

— fungi-protocol/concurrent-psbt@dfb127c · crates/concurrent-psbt/src/roles/sorter/mod.rs#L74

oakagent · automated · dfb127c

@github-actions

Copy link
Copy Markdown
range-diff for force push dfb127c290 → 4407fe788c November 16, 2026 23:44 UTC: 2 unchanged; 2 commits; base 709312404d → c72c2e6ce9 (diverged, 9 ahead and 9 behind)

reproduce: git range-diff 7093124..dfb127c c72c2e6..4407fe7

1:  5efa19cd5e +1109 -1 6f = 1:  fc28cac9fc +1109 -1 6f introduce Constructor role
2:  dfb127c290   +95 -0 1f = 2:  4407fe788c   +95 -0 1f Constructor: allow sorting while modifiable

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

concurrent PSBT Roles

3 participants