Skip to content

introduce Sorter role - #112

Draft
yuval-block wants to merge 1 commit into
enforce-concurrent-psbt-fieldsfrom
sorter
Draft

yuval-block wants to merge 1 commit into
enforce-concurrent-psbt-fieldsfrom
sorter

Conversation

@yuval-block

@yuval-block yuval-block commented Nov 14, 2026 •

Copy link
Copy Markdown
Collaborator

This uses a typestate based approach, like the upstream psbt-v2 Constructor role, in order to implement the different sorting modes.

The sorter role converts an unordered PSBT to an ordered PSBT. If the PSBT is modifiable, then it can transition to the BIP 370 Constructor role by sorting. If it is not modifiable, then it can transitions into the BIP 174 Updater role by sorting.

@yuval-block
yuval-block added this pull request to stack #113 November 14, 2026 02:24
@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 8a47f49642 → fd221478f4 November 14, 2026 03:29 UTC: 1 modified; 1 commit; same base a0900aeb14

reproduce: git range-diff a0900ae..8a47f49 a0900ae..fd22147

1:  8a47f49642 +1080 -3 8f ! 1:  fd221478f4 +1324 -3 9f introduce Sorter role
1: 8a47f49642 ! 1: fd221478f4 introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +
 +impl std::error::Error for SortError {}
 +
++impl From<DetermineLockTimeError> for SortError {
++    fn from(error: DetermineLockTimeError) -> Self {
++        Self::UndeterminedLockTime(error)
++    }
++}
++
++impl From<std::convert::Infallible> for SortError {
++    // Uncallable: no `Infallible` value exists.
++    #[cfg_attr(coverage_nightly, coverage(off))]
++    fn from(never: std::convert::Infallible) -> Self {
++        match never {}
++    }
++}
++
++/// The PSBT's `tx_modifiable_flags` don't match the requested modifiability.
++#[derive(Debug, Clone, Copy, PartialEq, Eq)]
++pub struct FlagsMismatch {
++    /// The flags value required by the modifiability type.
++    pub expected: u8,
++    /// The actual `tx_modifiable_flags & 0x03` from the PSBT.
++    pub actual: u8,
++}
++
++impl std::fmt::Display for FlagsMismatch {
++    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
++        write!(
++            f,
++            "tx_modifiable_flags mismatch: expected 0x{:02x}, got 0x{:02x}",
++            self.expected, self.actual
++        )
++    }
++}
++
++impl std::error::Error for FlagsMismatch {}
++
 +#[cfg(all(test, feature = "prop-tests"))]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +                txid_byte in any::<u8>(),
 +                vout in any::<u32>(),
 +                duplicate_key in proptest::collection::vec(any::<u8>(), 0..=8),
++                expected in 0u8..4,
++                actual in 0u8..4,
 +            ) {
 +                let outpoint = bitcoin::OutPoint { txid: bitcoin::Txid::from_byte_array([txid_byte; 32]), vout };
 +                prop_assert!(SortError::MissingInputSortKey(outpoint).to_string().contains("missing sort key"));
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +                }
 +                .determine_lock_time()
 +                .unwrap_err();
-+                prop_assert!(SortError::UndeterminedLockTime(lock_time).to_string().contains("lock time"));
++                prop_assert!(SortError::from(lock_time).to_string().contains("lock time"));
++                prop_assert_eq!(
++                    FlagsMismatch { expected, actual }.to_string(),
++                    format!("tx_modifiable_flags mismatch: expected 0x0{expected}, got 0x0{actual}")
++                );
 +            }
 +        }
 +    }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +
 +use std::marker::PhantomData;
 +
-+use psbt_v2::v2::{DetermineLockTimeError, Psbt, Updater};
++use psbt_v2::v2::Psbt;
 +
 +use crate::global::{GlobalSortExt, SortSeed};
 +use crate::tx::UnorderedPsbt;
 +
 +mod error;
 +mod key;
++mod modifiability;
 +mod order;
 +
-+pub use error::SortError;
++pub use error::{FlagsMismatch, SortError};
 +pub use key::{SortKeyHash, SortKeyTag};
 +use key::{
 +    derived_input_sort_key, derived_output_sort_key, explicit_input_sort_key,
 +    explicit_output_sort_key, mixed_input_sort_key, mixed_output_sort_key,
 +};
++pub(crate) use modifiability::check_flags;
++pub use modifiability::{
++    BothModifiable, InputsModifiable, Modifiability, Modifiable, OutputsModifiable, Unmodifiable,
++};
 +use order::ordered_psbt;
 +
-+/// Hand an ordered PSBT to the BIP 370 [`Updater`].
-+fn updater(psbt: Psbt) -> Result<Updater, SortError> {
-+    Updater::new(psbt).map_err(SortError::UndeterminedLockTime)
++/// Hand an ordered PSBT to the role that follows sorting under `M`.
++fn hand_off<M: Modifiability>(psbt: Psbt) -> Result<M::Sorted, M::Error> {
++    <M as modifiability::sealed::Modifiability>::sorted(psbt)
 +}
 +
 +/// Sort mode: deterministic ordering seeded by a high-entropy value.
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +
 +/// Typestate wrapper that applies a sort order to an [`UnorderedPsbt`].
 +///
++/// `M` is the PSBT's [`Modifiability`], which decides the role a sorted PSBT
++/// is handed to: the matching BIP 370 constructor while inputs or outputs
++/// may still be added, the [`Updater`](psbt_v2::v2::Updater) once neither
++/// may.
++///
 +/// `S` is the sort mode: [`Mixed`], [`Deterministic`], or [`Explicit`], or
 +/// [`Seeded`] `Mixed` or `Deterministic` once the sort seed is known to be set.
-+/// Once ordering is applied, the result can be converted to a standard BIP 370 PSBT.
 +///
 +/// # Ordering
 +///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +/// intentionally non-deterministic, satisfying the spec's shuffle requirement
 +/// for unordered PSBTs. The [`Sorter`] applies a deterministic order when
 +/// transitioning to an ordered BIP 370 PSBT for signing.
-+pub struct Sorter<S>(pub(crate) UnorderedPsbt, PhantomData<S>);
++#[derive(Debug)]
++pub struct Sorter<M, S>(pub(crate) UnorderedPsbt, PhantomData<(M, S)>);
 +
-+impl<S> Sorter<S> {
-+    /// Wrap `psbt` without checking it against `S`; a [`Seeded`] mode
-+    /// requires `PSBT_GLOBAL_SORT_SEED` to be set.
++impl<M, S> Sorter<M, S> {
++    /// Wrap `psbt` without checking it against `M` and `S`; its
++    /// `tx_modifiable_flags` must match `M`, and a [`Seeded`] mode requires
++    /// `PSBT_GLOBAL_SORT_SEED` to be set.
 +    pub(crate) fn from_unordered(psbt: UnorderedPsbt) -> Self {
 +        Sorter(psbt, PhantomData)
 +    }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        self.0
 +    }
 +
-+    fn with_seed<T>(mut self, seed: SortSeed) -> Sorter<Seeded<T>> {
++    fn with_seed<T>(mut self, seed: SortSeed) -> Sorter<M, Seeded<T>> {
 +        self.0.global.set_sort_seed(seed);
 +        Sorter::from_unordered(self.0)
 +    }
 +}
 +
-+impl Sorter<Mixed> {
++impl<M: Modifiability, S> Sorter<M, S> {
++    fn try_from_unordered(psbt: UnorderedPsbt) -> Result<Self, FlagsMismatch> {
++        check_flags::<M>(psbt.global.tx_modifiable_flags)?;
++        Ok(Sorter::from_unordered(psbt))
++    }
++}
++
++impl<M: Modifiability> Sorter<M, Mixed> {
 +    /// Create a mixed-mode sorter from an [`UnorderedPsbt`].
-+    pub fn from_unordered_psbt(psbt: UnorderedPsbt) -> Self {
-+        Sorter::from_unordered(psbt)
++    ///
++    /// # Errors
++    /// Returns [`FlagsMismatch`] if `tx_modifiable_flags` don't match `M`.
++    pub fn try_from_unordered_psbt(psbt: UnorderedPsbt) -> Result<Self, FlagsMismatch> {
++        Sorter::try_from_unordered(psbt)
 +    }
 +
 +    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
-+    pub fn set_seed(self, seed: SortSeed) -> Sorter<Seeded<Mixed>> {
++    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<Mixed>> {
 +        self.with_seed(seed)
 +    }
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +
 +    /// Order the PSBT as [`try_into_ordered_psbt`](Self::try_into_ordered_psbt)
-+    /// does and hand it to the BIP 370 [`Updater`].
++    /// does and hand it to [`M::Sorted`](Modifiability::Sorted).
 +    ///
 +    /// # Errors
 +    /// Returns the errors of [`try_into_ordered_psbt`](Self::try_into_ordered_psbt),
-+    /// or [`SortError::UndeterminedLockTime`] if the inputs' lock time
-+    /// requirements conflict.
-+    pub fn try_sort(self) -> Result<Updater, SortError> {
-+        updater(self.try_into_ordered_psbt()?)
++    /// or [`SortError::UndeterminedLockTime`] if `M` is [`Unmodifiable`] and
++    /// the inputs' lock time requirements conflict.
++    pub fn try_sort(self) -> Result<M::Sorted, SortError> {
++        hand_off::<M>(self.try_into_ordered_psbt()?).map_err(Into::into)
 +    }
 +}
 +
-+impl Sorter<Seeded<Mixed>> {
++impl<M: Modifiability> Sorter<M, Seeded<Mixed>> {
 +    /// Apply mixed-mode ordering with the sort seed set.
 +    ///
 +    /// # Errors
 +    /// Returns [`SortError::DuplicateSortKey`] if two inputs (or two outputs)
 +    /// end up with the same sort key.
 +    pub fn try_into_ordered_psbt(self) -> Result<Psbt, SortError> {
-+        Sorter::<Mixed>::from_unordered(self.0).try_into_ordered_psbt()
++        Sorter::<M, Mixed>::from_unordered(self.0).try_into_ordered_psbt()
 +    }
 +
 +    /// Order the PSBT as [`try_into_ordered_psbt`](Self::try_into_ordered_psbt)
-+    /// does and hand it to the BIP 370 [`Updater`].
++    /// does and hand it to [`M::Sorted`](Modifiability::Sorted).
 +    ///
 +    /// # Errors
 +    /// Returns the errors of [`try_into_ordered_psbt`](Self::try_into_ordered_psbt),
-+    /// or [`SortError::UndeterminedLockTime`] if the inputs' lock time
-+    /// requirements conflict.
-+    pub fn try_sort(self) -> Result<Updater, SortError> {
-+        updater(self.try_into_ordered_psbt()?)
++    /// or [`SortError::UndeterminedLockTime`] if `M` is [`Unmodifiable`] and
++    /// the inputs' lock time requirements conflict.
++    pub fn try_sort(self) -> Result<M::Sorted, SortError> {
++        hand_off::<M>(self.try_into_ordered_psbt()?).map_err(Into::into)
 +    }
 +}
 +
-+impl Sorter<Deterministic> {
++impl<M: Modifiability> Sorter<M, Deterministic> {
 +    /// Create a deterministic sorter from an [`UnorderedPsbt`].
-+    pub fn from_unordered_psbt(psbt: UnorderedPsbt) -> Self {
-+        Sorter::from_unordered(psbt)
++    ///
++    /// # Errors
++    /// Returns [`FlagsMismatch`] if `tx_modifiable_flags` don't match `M`.
++    pub fn try_from_unordered_psbt(psbt: UnorderedPsbt) -> Result<Self, FlagsMismatch> {
++        Sorter::try_from_unordered(psbt)
 +    }
 +
 +    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
-+    pub fn set_seed(self, seed: SortSeed) -> Sorter<Seeded<Deterministic>> {
++    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<Deterministic>> {
 +        self.with_seed(seed)
 +    }
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    pub fn try_into_ordered_psbt(self) -> Result<Psbt, SortError> {
 +        match self.0.global.sort_seed() {
 +            Some(_) => {
-+                Ok(Sorter::<Seeded<Deterministic>>::from_unordered(self.0).into_ordered_psbt())
++                Ok(Sorter::<M, Seeded<Deterministic>>::from_unordered(self.0).into_ordered_psbt())
 +            }
 +            None => Err(SortError::MissingSortSeed),
 +        }
 +    }
 +
 +    /// Order the PSBT as [`try_into_ordered_psbt`](Self::try_into_ordered_psbt)
-+    /// does and hand it to the BIP 370 [`Updater`].
++    /// does and hand it to [`M::Sorted`](Modifiability::Sorted).
 +    ///
 +    /// # Errors
 +    /// Returns the errors of [`try_into_ordered_psbt`](Self::try_into_ordered_psbt),
-+    /// or [`SortError::UndeterminedLockTime`] if the inputs' lock time
-+    /// requirements conflict.
-+    pub fn try_sort(self) -> Result<Updater, SortError> {
-+        updater(self.try_into_ordered_psbt()?)
++    /// or [`SortError::UndeterminedLockTime`] if `M` is [`Unmodifiable`] and
++    /// the inputs' lock time requirements conflict.
++    pub fn try_sort(self) -> Result<M::Sorted, SortError> {
++        hand_off::<M>(self.try_into_ordered_psbt()?).map_err(Into::into)
 +    }
 +}
 +
-+impl Sorter<Seeded<Deterministic>> {
++impl<M: Modifiability> Sorter<M, Seeded<Deterministic>> {
 +    /// Apply deterministic ordering: derive sort keys from the seed, sort,
 +    /// and produce an ordered BIP 370 [`Psbt`].
 +    ///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +
 +    /// Order the PSBT as [`into_ordered_psbt`](Self::into_ordered_psbt) does
-+    /// and hand it to the BIP 370 [`Updater`].
++    /// and hand it to [`M::Sorted`](Modifiability::Sorted).
 +    ///
 +    /// # Errors
-+    /// Returns [`DetermineLockTimeError`] if the inputs' lock time
-+    /// requirements conflict.
-+    pub fn try_sort(self) -> Result<Updater, DetermineLockTimeError> {
-+        Updater::new(self.into_ordered_psbt())
++    /// Returns [`M::Error`](Modifiability::Error): `Infallible` while `M` is
++    /// modifiable, or [`DetermineLockTimeError`](psbt_v2::v2::DetermineLockTimeError)
++    /// if `M` is [`Unmodifiable`] and the inputs' lock time requirements
++    /// conflict.
++    pub fn try_sort(self) -> Result<M::Sorted, M::Error> {
++        hand_off::<M>(self.into_ordered_psbt())
 +    }
 +}
 +
-+impl Sorter<Explicit> {
++impl<M: Modifiability> Sorter<M, Explicit> {
 +    /// Create an explicit-mode sorter from an [`UnorderedPsbt`].
-+    pub fn from_unordered_psbt(psbt: UnorderedPsbt) -> Self {
-+        Sorter::from_unordered(psbt)
++    ///
++    /// # Errors
++    /// Returns [`FlagsMismatch`] if `tx_modifiable_flags` don't match `M`.
++    pub fn try_from_unordered_psbt(psbt: UnorderedPsbt) -> Result<Self, FlagsMismatch> {
++        Sorter::try_from_unordered(psbt)
 +    }
 +
 +    /// Apply explicit ordering: sort by the `PSBT_IN_SORT_KEY` and
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +
 +    /// Order the PSBT as [`try_into_ordered_psbt`](Self::try_into_ordered_psbt)
-+    /// does and hand it to the BIP 370 [`Updater`].
++    /// does and hand it to [`M::Sorted`](Modifiability::Sorted).
 +    ///
 +    /// # Errors
 +    /// Returns the errors of [`try_into_ordered_psbt`](Self::try_into_ordered_psbt),
-+    /// or [`SortError::UndeterminedLockTime`] if the inputs' lock time
-+    /// requirements conflict.
-+    pub fn try_sort(self) -> Result<Updater, SortError> {
-+        updater(self.try_into_ordered_psbt()?)
++    /// or [`SortError::UndeterminedLockTime`] if `M` is [`Unmodifiable`] and
++    /// the inputs' lock time requirements conflict.
++    pub fn try_sort(self) -> Result<M::Sorted, SortError> {
++        hand_off::<M>(self.try_into_ordered_psbt()?).map_err(Into::into)
 +    }
 +}
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    use crate::input::{InputSet, InputSortKeyExt, SortKey};
 +    use crate::output::{OutputSet, PSBT_OUT_UNIQUE_ID_SUBTYPE};
 +    use crate::output::{OutputSortKeyExt, OutputUniqueIdExt};
-+    use psbt_v2::v2::{Global, Input, Output};
++    use psbt_v2::v2::{Global, Input, Output, Updater};
 +
 +    fn sort_seed(bytes: Vec<u8>) -> SortSeed {
 +        SortSeed::try_from(bytes).expect("test seeds are at least 16 bytes")
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        #[test]
 +        fn deterministic_no_seed_err() {
 +            let psbt = empty_psbt();
-+            let sorter: Sorter<Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
 +            assert!(sorter.try_into_ordered_psbt().is_err());
 +        }
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt.inputs =
 +                InputSet::try_from_inputs([make_input(2, 0), make_input(1, 0), make_input(3, 0)])
 +                    .unwrap();
-+            let sorter: Sorter<Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            assert_eq!(ordered.inputs.len(), 3);
 +            // Verify deterministic: same seed, same order
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt2.inputs =
 +                InputSet::try_from_inputs([make_input(3, 0), make_input(1, 0), make_input(2, 0)])
 +                    .unwrap();
-+            let sorter2: Sorter<Deterministic> = Sorter(psbt2, PhantomData);
++            let sorter2: Sorter<Unmodifiable, Deterministic> = Sorter(psbt2, PhantomData);
 +            let ordered2 = sorter2.try_into_ordered_psbt().unwrap();
 +            for (a, b) in ordered.inputs.iter().zip(ordered2.inputs.iter()) {
 +                assert_eq!(a.previous_txid, b.previous_txid);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                OutputSet::try_from_outputs((0..8).map(|uid| make_output_with_uid(&[uid])))
 +                    .unwrap();
 +
-+            let sorter: Sorter<Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
 +            let keys: Vec<_> = sorter
 +                .try_into_ordered_psbt()
 +                .unwrap()
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            let mut i2 = make_input(2, 0);
 +            i2.set_sort_key(sort_key(vec![0x01]));
 +            psbt.inputs = InputSet::try_from_inputs([i1, i2]).unwrap();
-+            let sorter: Sorter<Explicit> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, Explicit> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            // i2 (key 0x01) should come before i1 (key 0x02)
 +            assert_eq!(
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +
 +            psbt.outputs = OutputSet::try_from_outputs([explicit_output, missing_output]).unwrap();
 +
-+            let sorter: Sorter<Mixed> = Sorter::<Mixed>::from_unordered_psbt(psbt);
++            let sorter: Sorter<Unmodifiable, Mixed> =
++                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).unwrap();
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +
 +            let ordered_inputs: Vec<_> = ordered.inputs.iter().map(|i| i.previous_txid).collect();
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        fn mixed_missing_output_sort_key_without_seed_errs() {
 +            let mut psbt = empty_psbt();
 +            psbt.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[1])]).unwrap();
-+            let sorter: Sorter<Mixed> = Sorter::<Mixed>::from_unordered_psbt(psbt);
++            let sorter: Sorter<Unmodifiable, Mixed> =
++                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).unwrap();
 +            assert!(matches!(
 +                sorter.try_into_ordered_psbt(),
 +                Err(SortError::MissingSortSeed)
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt.global.set_unordered();
 +            psbt.global.set_sort_seed(sort_seed(vec![0u8; 32]));
 +            assert!(psbt.global.is_unordered());
-+            let sorter: Sorter<Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            assert!(!ordered.global.is_unordered());
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                psbt
 +            };
 +
-+            let ordered = Sorter::<Deterministic>::from_unordered_psbt(psbt())
++            let ordered = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(psbt())
++                .unwrap()
 +                .set_seed(sort_seed(seed.clone()))
 +                .into_ordered_psbt();
-+            let updater = Sorter::<Deterministic>::from_unordered_psbt(psbt())
++            let updater = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(psbt())
++                .unwrap()
 +                .set_seed(sort_seed(seed.clone()))
 +                .try_sort()
 +                .expect("the inputs carry no lock time requirements");
 +            assert_eq!(updater.psbt(), ordered);
 +            assert!(
-+                Sorter::<Deterministic>::from_unordered_psbt(preset())
++                Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(preset())
++                    .unwrap()
 +                    .try_sort()
 +                    .is_ok()
 +            );
 +
 +            assert!(
-+                Sorter::<Mixed>::from_unordered_psbt(psbt())
++                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt())
++                    .unwrap()
 +                    .set_seed(sort_seed(seed.clone()))
 +                    .try_sort()
 +                    .is_ok()
 +            );
 +            assert!(matches!(
-+                Sorter::<Mixed>::from_unordered_psbt(psbt()).try_sort(),
++                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt())
++                    .unwrap()
++                    .try_sort(),
 +                Err(SortError::MissingSortSeed)
 +            ));
 +            assert!(matches!(
-+                Sorter::<Explicit>::from_unordered_psbt(psbt()).try_sort(),
++                Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(psbt())
++                    .unwrap()
++                    .try_sort(),
 +                Err(SortError::MissingInputSortKey(_))
 +            ));
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        #[test]
 +        fn inner_accessor() {
 +            let psbt = empty_psbt();
-+            let sorter: Sorter<Mixed> = Sorter::<Mixed>::from_unordered_psbt(psbt);
++            let sorter: Sorter<Unmodifiable, Mixed> =
++                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).unwrap();
 +            assert!(sorter.inner().inputs.is_empty());
 +        }
 +
 +        #[test]
 +        fn into_inner_accessor() {
-+            let sorter: Sorter<Mixed> = Sorter::<Mixed>::from_unordered_psbt(empty_psbt());
++            let sorter: Sorter<Unmodifiable, Mixed> =
++                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(empty_psbt()).unwrap();
 +            assert!(sorter.into_inner().inputs.is_empty());
 +        }
 +    }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    let mut psbt = empty_psbt();
 +                    psbt.global.set_sort_seed(sort_seed(seed.clone()));
 +                    psbt.inputs = InputSet::try_from_inputs([make_input(1, 0), make_input(2, 0), make_input(3, 0)]).unwrap();
-+                    let sorter: Sorter<Deterministic> = Sorter(psbt, PhantomData);
++                    let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
 +                    sorter.try_into_ordered_psbt().unwrap()
 +                };
 +                let a = make();
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let mut i2 = make_input(2, 0);
 +                i2.set_sort_key(sort_key(k2.clone()));
 +                psbt.inputs = InputSet::try_from_inputs([i1, i2]).unwrap();
-+                let sorter: Sorter<Explicit> = Sorter(psbt, PhantomData);
++                let sorter: Sorter<Unmodifiable, Explicit> = Sorter(psbt, PhantomData);
 +                let ordered = sorter.try_into_ordered_psbt().unwrap();
 +                prop_assert_eq!(ordered.inputs.len(), 2);
 +                // First input should have the lexicographically smaller key
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let txids = |psbt: &Psbt| psbt.inputs.iter().map(|input| input.previous_txid).collect::<Vec<_>>();
 +                let uids = |psbt: &Psbt| psbt.outputs.iter().map(|output| output.unique_id_bytes().map(<[u8]>::to_vec)).collect::<Vec<_>>();
 +
-+                let deterministic = Sorter::<Deterministic>::from_unordered_psbt(unseeded())
++                let deterministic = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(unseeded()).unwrap()
 +                    .set_seed(sort_seed(seed.clone()))
 +                    .into_ordered_psbt();
-+                let expected = Sorter::<Deterministic>::from_unordered_psbt(preset())
++                let expected = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(preset()).unwrap()
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
 +                prop_assert_eq!(deterministic.global.sort_seed(), Some(seed.as_slice()));
 +                prop_assert_eq!(txids(&deterministic), txids(&expected));
 +                prop_assert_eq!(uids(&deterministic), uids(&expected));
 +
-+                let mixed = Sorter::<Mixed>::from_unordered_psbt(unseeded())
++                let mixed = Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(unseeded()).unwrap()
 +                    .set_seed(sort_seed(seed.clone()))
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
-+                let expected = Sorter::<Mixed>::from_unordered_psbt(preset())
++                let expected = Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(preset()).unwrap()
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
 +                prop_assert_eq!(txids(&mixed), txids(&expected));
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                };
 +
 +                check(
-+                    Sorter::<Mixed>::from_unordered_psbt(make(false)).try_sort(),
-+                    Sorter::<Mixed>::from_unordered_psbt(make(false)).try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Mixed>::from_unordered_psbt(make(false)).set_seed(sort_seed(seed.clone())).try_sort(),
-+                    Sorter::<Mixed>::from_unordered_psbt(make(true)).try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone())).try_sort(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Deterministic>::from_unordered_psbt(make(true)).try_sort(),
-+                    Sorter::<Deterministic>::from_unordered_psbt(make(true)).try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(true)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Explicit>::from_unordered_psbt(make(false)).try_sort(),
-+                    Sorter::<Explicit>::from_unordered_psbt(make(false)).try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(make(false)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(make(false)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
-+                let seeded = Sorter::<Deterministic>::from_unordered_psbt(make(false)).set_seed(sort_seed(seed.clone()));
-+                let ordered = Sorter::<Deterministic>::from_unordered_psbt(make(false)).set_seed(sort_seed(seed.clone())).into_ordered_psbt();
++                let seeded = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone()));
++                let ordered = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone())).into_ordered_psbt();
 +                match seeded.try_sort() {
 +                    Ok(updater) => prop_assert_eq!(updater.psbt(), ordered),
 +                    Err(_) => prop_assert!(conflicting_lock_times),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            }
 +
 +            #[test]
++            fn modifiability_decides_admission_and_hand_off(
++                seed in proptest::collection::vec(any::<u8>(), 16..=32),
++                flags in 0u8..4,
++            ) {
++                fn check<M: Modifiability>(
++                    psbt: &dyn Fn() -> UnorderedPsbt,
++                    seed: &SortSeed,
++                    to_psbt: fn(M::Sorted) -> Psbt,
++                ) -> Result<(), TestCaseError>
++                where
++                    M::Error: std::fmt::Debug,
++                {
++                    let actual = psbt().global.tx_modifiable_flags;
++                    if actual != M::EXPECTED_FLAGS {
++                        let mismatch = Some(FlagsMismatch { expected: M::EXPECTED_FLAGS, actual });
++                        prop_assert_eq!(Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).err(), mismatch);
++                        prop_assert_eq!(Sorter::<M, Deterministic>::try_from_unordered_psbt(psbt()).err(), mismatch);
++                        prop_assert_eq!(Sorter::<M, Explicit>::try_from_unordered_psbt(psbt()).err(), mismatch);
++                        return Ok(());
++                    }
++                    prop_assert!(Sorter::<M, Explicit>::try_from_unordered_psbt(psbt()).is_ok());
++
++                    let mixed = || Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).unwrap();
++                    let ordered = mixed().try_into_ordered_psbt().unwrap();
++                    prop_assert_eq!(ordered.global.tx_modifiable_flags, M::EXPECTED_FLAGS);
++                    prop_assert_eq!(to_psbt(mixed().try_sort().unwrap()), ordered);
++
++                    let seeded = || {
++                        Sorter::<M, Deterministic>::try_from_unordered_psbt(psbt())
++                            .unwrap()
++                            .set_seed(seed.clone())
++                    };
++                    let ordered = seeded().into_ordered_psbt();
++                    prop_assert_eq!(to_psbt(seeded().try_sort().unwrap()), ordered);
++                    Ok(())
++                }
++
++                let seed = sort_seed(seed);
++                let psbt = || {
++                    let mut psbt = empty_psbt();
++                    psbt.global.tx_modifiable_flags = flags;
++                    psbt.global.set_sort_seed(seed.clone());
++                    psbt.inputs = InputSet::try_from_inputs([make_input(1, 0), make_input(2, 0)]).unwrap();
++                    psbt.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[1])]).unwrap();
++                    psbt
++                };
++                fn constructed<T: psbt_v2::v2::Mod>(constructor: psbt_v2::v2::Constructor<T>) -> Psbt {
++                    constructor.psbt().expect("the inputs carry no lock time requirements")
++                }
++                check::<BothModifiable>(&psbt, &seed, constructed)?;
++                check::<InputsModifiable>(&psbt, &seed, constructed)?;
++                check::<OutputsModifiable>(&psbt, &seed, constructed)?;
++                check::<Unmodifiable>(&psbt, &seed, Updater::psbt)?;
++            }
++
++            #[test]
 +            fn deterministic_orders_inputs_and_outputs(
 +                seed in proptest::collection::vec(any::<u8>(), 16..=32),
 +                first in any::<u8>(),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                psbt.inputs = InputSet::try_from_inputs([make_input(first, 0), make_input(second, 0)]).unwrap();
 +                psbt.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[first]), make_output_with_uid(&[second])]).unwrap();
 +
-+                let sorter: Sorter<Deterministic> = Sorter(psbt, PhantomData);
++                let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
 +                let ordered = sorter.try_into_ordered_psbt().unwrap();
 +                prop_assert_eq!(ordered.inputs.len(), 2);
 +                prop_assert_eq!(ordered.outputs.len(), 2);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let mut missing_input = empty_psbt();
 +                missing_input.inputs = InputSet::try_from_inputs([make_input(1, 0)]).unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Explicit>(missing_input, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, Explicit>(missing_input, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::MissingInputSortKey(_))
 +                ));
 +
 +                let mut missing_output = empty_psbt();
 +                missing_output.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[1])]).unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Explicit>(missing_output, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, Explicit>(missing_output, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::MissingOutputSortKey)
 +                ));
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                }))
 +                .unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Explicit>(duplicates, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, Explicit>(duplicates, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::DuplicateSortKey(_))
 +                ));
 +            }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                }))
 +                .unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Mixed>::from_unordered_psbt(explicit_tie).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(explicit_tie).unwrap().try_into_ordered_psbt(),
 +                    Err(SortError::DuplicateSortKey(tied)) if tied == key
 +                ));
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                mixed_tie.global.set_sort_seed(sort_seed(seed));
 +                mixed_tie.inputs = InputSet::try_from_inputs([explicit, derived]).unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Mixed>::from_unordered_psbt(mixed_tie).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(mixed_tie).unwrap().try_into_ordered_psbt(),
 +                    Err(SortError::DuplicateSortKey(tied)) if tied == derived_key
 +                ));
 +            }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let mut missing_seed = empty_psbt();
 +                missing_seed.inputs = InputSet::try_from_inputs([make_input(1, 0)]).unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Mixed>::from_unordered_psbt(missing_seed).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(missing_seed).unwrap().try_into_ordered_psbt(),
 +                    Err(SortError::MissingSortSeed)
 +                ));
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                explicit_output.set_sort_key(sort_key(vec![0]));
 +                psbt.outputs = OutputSet::try_from_outputs([explicit_output, make_output_with_uid(&[2])]).unwrap();
 +
-+                let ordered = Sorter::<Mixed>::from_unordered_psbt(psbt)
++                let ordered = Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).unwrap()
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
 +                prop_assert!(!ordered.global.is_unordered());
 +            }
 +        }
 +    }
++}
+
+ ## crates/concurrent-psbt/src/roles/sorter/modifiability.rs (new) ##
+@@
++//! Modifiability markers: which of a PSBT's inputs and outputs may still be
++//! added to, as bits 0 and 1 of `tx_modifiable_flags` record.
++
++use std::convert::Infallible;
++
++use psbt_v2::v2::{self, DetermineLockTimeError, Psbt, Updater};
++
++use super::{FlagsMismatch, SortError};
++
++pub(crate) mod sealed {
++    use psbt_v2::v2::Psbt;
++
++    pub trait Modifiability {
++        /// Hand an ordered PSBT whose flags match `Self` to the next role.
++        fn sorted(
++            psbt: Psbt,
++        ) -> Result<<Self as super::Modifiability>::Sorted, <Self as super::Modifiability>::Error>
++        where
++            Self: super::Modifiability;
++    }
++}
++
++/// Modifiability marker, carrying the `tx_modifiable_flags` it stands for
++/// and the role a sorted PSBT moves on to.
++pub trait Modifiability: sealed::Modifiability {
++    /// The value of `tx_modifiable_flags & 0x03` for this modifiability.
++    const EXPECTED_FLAGS: u8;
++
++    /// The role that takes over once the PSBT is sorted: the matching BIP 370
++    /// constructor while anything is modifiable, the [`Updater`] otherwise.
++    type Sorted;
++
++    /// Why handing a sorted PSBT to [`Sorted`](Self::Sorted) can fail.
++    type Error: Into<SortError>;
++}
++
++/// A [`Modifiability`] under which inputs or outputs may still be added:
++/// every marker but [`Unmodifiable`], which only a [`Sorter`](super::Sorter)
++/// holds.
++pub trait Modifiable: Modifiability {}
++
++/// Modifiability marker: both inputs and outputs may be added (`tx_modifiable_flags` bits 0+1).
++#[derive(Debug, Clone, PartialEq)]
++pub enum BothModifiable {}
++
++/// Modifiability marker: only inputs may be added (`tx_modifiable_flags` bit 0).
++#[derive(Debug, Clone, PartialEq)]
++pub enum InputsModifiable {}
++
++/// Modifiability marker: only outputs may be added (`tx_modifiable_flags` bit 1).
++#[derive(Debug, Clone, PartialEq)]
++pub enum OutputsModifiable {}
++
++/// Modifiability marker: neither inputs nor outputs may be added.
++#[derive(Debug, Clone, PartialEq)]
++pub enum Unmodifiable {}
++
++macro_rules! modifiable {
++    ($marker:ident, $flags:literal, $upstream:ident) => {
++        impl Modifiability for $marker {
++            const EXPECTED_FLAGS: u8 = $flags;
++            type Sorted = v2::Constructor<v2::$upstream>;
++            type Error = Infallible;
++        }
++
++        impl Modifiable for $marker {}
++
++        impl sealed::Modifiability for $marker {
++            fn sorted(psbt: Psbt) -> Result<v2::Constructor<v2::$upstream>, Infallible> {
++                Ok(v2::Constructor::<v2::$upstream>::new(psbt).expect(concat!(
++                    stringify!($marker),
++                    " PSBTs carry their modifiable flags"
++                )))
++            }
++        }
++    };
++}
++
++modifiable!(BothModifiable, 0x03, Modifiable);
++modifiable!(InputsModifiable, 0x01, InputsOnlyModifiable);
++modifiable!(OutputsModifiable, 0x02, OutputsOnlyModifiable);
++
++impl Modifiability for Unmodifiable {
++    const EXPECTED_FLAGS: u8 = 0x00;
++    type Sorted = Updater;
++    type Error = DetermineLockTimeError;
++}
++
++impl sealed::Modifiability for Unmodifiable {
++    fn sorted(psbt: Psbt) -> Result<Updater, DetermineLockTimeError> {
++        Updater::new(psbt)
++    }
++}
++
++/// Check that `flags & 0x03` matches `M`.
++pub(crate) fn check_flags<M: Modifiability>(flags: u8) -> Result<(), FlagsMismatch> {
++    let actual = flags & 0x03;
++    if actual == M::EXPECTED_FLAGS {
++        Ok(())
++    } else {
++        Err(FlagsMismatch {
++            expected: M::EXPECTED_FLAGS,
++            actual,
++        })
++    }
 +}
 
  ## crates/concurrent-psbt/src/roles/sorter/order.rs (new) ##

@github-actions

Copy link
Copy Markdown
range-diff for force push fd221478f4 → a76152e86e November 14, 2026 04:12 UTC: 1 modified; 1 commit; base a0900aeb14 → 568bc715d0 (diverged, 3 ahead and 3 behind)

reproduce: git range-diff a0900ae..fd22147 568bc71..a76152e

1:  fd221478f4 +1324 -3 9f ! 1:  a76152e86e +1324 -3 9f introduce Sorter role
1: fd221478f4 ! 1: a76152e86e introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +/// or transaction-specific nonce) so that all participants produce the
 +/// same order without revealing sort criteria to observers.
 +#[derive(Debug, Clone, PartialEq)]
-+pub enum Deterministic {}
++pub enum DerivedOnly {}
 +
 +/// Sort mode: ordering determined by explicit sort key fields on each input/output.
 +#[derive(Debug, Clone, PartialEq)]
-+pub enum Explicit {}
++pub enum ExplicitOnly {}
 +
 +/// Sort mode: explicit sort keys where present, the rest derived from the
 +/// sort seed.
 +#[derive(Debug, Clone, PartialEq)]
 +pub enum Mixed {}
 +
-+/// Sort mode refinement: [`Deterministic`] or [`Mixed`] with
++/// Sort mode refinement: [`DerivedOnly`] or [`Mixed`] with
 +/// `PSBT_GLOBAL_SORT_SEED` known to be set.
 +#[derive(Debug, Clone, PartialEq)]
 +pub struct Seeded<S>(PhantomData<S>, std::convert::Infallible);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +/// may still be added, the [`Updater`](psbt_v2::v2::Updater) once neither
 +/// may.
 +///
-+/// `S` is the sort mode: [`Mixed`], [`Deterministic`], or [`Explicit`], or
-+/// [`Seeded`] `Mixed` or `Deterministic` once the sort seed is known to be set.
++/// `S` is the sort mode: [`Mixed`], [`DerivedOnly`], or [`ExplicitOnly`], or
++/// [`Seeded`] `Mixed` or `DerivedOnly` once the sort seed is known to be set.
 +///
 +/// # Ordering
 +///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability> Sorter<M, Deterministic> {
++impl<M: Modifiability> Sorter<M, DerivedOnly> {
 +    /// Create a deterministic sorter from an [`UnorderedPsbt`].
 +    ///
 +    /// # Errors
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +
 +    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
-+    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<Deterministic>> {
++    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<DerivedOnly>> {
 +        self.with_seed(seed)
 +    }
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    pub fn try_into_ordered_psbt(self) -> Result<Psbt, SortError> {
 +        match self.0.global.sort_seed() {
 +            Some(_) => {
-+                Ok(Sorter::<M, Seeded<Deterministic>>::from_unordered(self.0).into_ordered_psbt())
++                Ok(Sorter::<M, Seeded<DerivedOnly>>::from_unordered(self.0).into_ordered_psbt())
 +            }
 +            None => Err(SortError::MissingSortSeed),
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability> Sorter<M, Seeded<Deterministic>> {
++impl<M: Modifiability> Sorter<M, Seeded<DerivedOnly>> {
 +    /// Apply deterministic ordering: derive sort keys from the seed, sort,
 +    /// and produce an ordered BIP 370 [`Psbt`].
 +    ///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability> Sorter<M, Explicit> {
++impl<M: Modifiability> Sorter<M, ExplicitOnly> {
 +    /// Create an explicit-mode sorter from an [`UnorderedPsbt`].
 +    ///
 +    /// # Errors
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        #[test]
 +        fn deterministic_no_seed_err() {
 +            let psbt = empty_psbt();
-+            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            assert!(sorter.try_into_ordered_psbt().is_err());
 +        }
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt.inputs =
 +                InputSet::try_from_inputs([make_input(2, 0), make_input(1, 0), make_input(3, 0)])
 +                    .unwrap();
-+            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            assert_eq!(ordered.inputs.len(), 3);
 +            // Verify deterministic: same seed, same order
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt2.inputs =
 +                InputSet::try_from_inputs([make_input(3, 0), make_input(1, 0), make_input(2, 0)])
 +                    .unwrap();
-+            let sorter2: Sorter<Unmodifiable, Deterministic> = Sorter(psbt2, PhantomData);
++            let sorter2: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt2, PhantomData);
 +            let ordered2 = sorter2.try_into_ordered_psbt().unwrap();
 +            for (a, b) in ordered.inputs.iter().zip(ordered2.inputs.iter()) {
 +                assert_eq!(a.previous_txid, b.previous_txid);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                OutputSet::try_from_outputs((0..8).map(|uid| make_output_with_uid(&[uid])))
 +                    .unwrap();
 +
-+            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            let keys: Vec<_> = sorter
 +                .try_into_ordered_psbt()
 +                .unwrap()
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            let mut i2 = make_input(2, 0);
 +            i2.set_sort_key(sort_key(vec![0x01]));
 +            psbt.inputs = InputSet::try_from_inputs([i1, i2]).unwrap();
-+            let sorter: Sorter<Unmodifiable, Explicit> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, ExplicitOnly> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            // i2 (key 0x01) should come before i1 (key 0x02)
 +            assert_eq!(
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt.global.set_unordered();
 +            psbt.global.set_sort_seed(sort_seed(vec![0u8; 32]));
 +            assert!(psbt.global.is_unordered());
-+            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            assert!(!ordered.global.is_unordered());
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                psbt
 +            };
 +
-+            let ordered = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(psbt())
++            let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(psbt())
 +                .unwrap()
 +                .set_seed(sort_seed(seed.clone()))
 +                .into_ordered_psbt();
-+            let updater = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(psbt())
++            let updater = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(psbt())
 +                .unwrap()
 +                .set_seed(sort_seed(seed.clone()))
 +                .try_sort()
 +                .expect("the inputs carry no lock time requirements");
 +            assert_eq!(updater.psbt(), ordered);
 +            assert!(
-+                Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(preset())
++                Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(preset())
 +                    .unwrap()
 +                    .try_sort()
 +                    .is_ok()
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                Err(SortError::MissingSortSeed)
 +            ));
 +            assert!(matches!(
-+                Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(psbt())
++                Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(psbt())
 +                    .unwrap()
 +                    .try_sort(),
 +                Err(SortError::MissingInputSortKey(_))
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    let mut psbt = empty_psbt();
 +                    psbt.global.set_sort_seed(sort_seed(seed.clone()));
 +                    psbt.inputs = InputSet::try_from_inputs([make_input(1, 0), make_input(2, 0), make_input(3, 0)]).unwrap();
-+                    let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++                    let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +                    sorter.try_into_ordered_psbt().unwrap()
 +                };
 +                let a = make();
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let mut i2 = make_input(2, 0);
 +                i2.set_sort_key(sort_key(k2.clone()));
 +                psbt.inputs = InputSet::try_from_inputs([i1, i2]).unwrap();
-+                let sorter: Sorter<Unmodifiable, Explicit> = Sorter(psbt, PhantomData);
++                let sorter: Sorter<Unmodifiable, ExplicitOnly> = Sorter(psbt, PhantomData);
 +                let ordered = sorter.try_into_ordered_psbt().unwrap();
 +                prop_assert_eq!(ordered.inputs.len(), 2);
 +                // First input should have the lexicographically smaller key
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let txids = |psbt: &Psbt| psbt.inputs.iter().map(|input| input.previous_txid).collect::<Vec<_>>();
 +                let uids = |psbt: &Psbt| psbt.outputs.iter().map(|output| output.unique_id_bytes().map(<[u8]>::to_vec)).collect::<Vec<_>>();
 +
-+                let deterministic = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(unseeded()).unwrap()
++                let deterministic = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(unseeded()).unwrap()
 +                    .set_seed(sort_seed(seed.clone()))
 +                    .into_ordered_psbt();
-+                let expected = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(preset()).unwrap()
++                let expected = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(preset()).unwrap()
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
 +                prop_assert_eq!(deterministic.global.sort_seed(), Some(seed.as_slice()));
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(true)).unwrap().try_sort(),
-+                    Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(true)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(make(false)).unwrap().try_sort(),
-+                    Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(make(false)).unwrap().try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(make(false)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(make(false)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
-+                let seeded = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone()));
-+                let ordered = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone())).into_ordered_psbt();
++                let seeded = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone()));
++                let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone())).into_ordered_psbt();
 +                match seeded.try_sort() {
 +                    Ok(updater) => prop_assert_eq!(updater.psbt(), ordered),
 +                    Err(_) => prop_assert!(conflicting_lock_times),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    if actual != M::EXPECTED_FLAGS {
 +                        let mismatch = Some(FlagsMismatch { expected: M::EXPECTED_FLAGS, actual });
 +                        prop_assert_eq!(Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).err(), mismatch);
-+                        prop_assert_eq!(Sorter::<M, Deterministic>::try_from_unordered_psbt(psbt()).err(), mismatch);
-+                        prop_assert_eq!(Sorter::<M, Explicit>::try_from_unordered_psbt(psbt()).err(), mismatch);
++                        prop_assert_eq!(Sorter::<M, DerivedOnly>::try_from_unordered_psbt(psbt()).err(), mismatch);
++                        prop_assert_eq!(Sorter::<M, ExplicitOnly>::try_from_unordered_psbt(psbt()).err(), mismatch);
 +                        return Ok(());
 +                    }
-+                    prop_assert!(Sorter::<M, Explicit>::try_from_unordered_psbt(psbt()).is_ok());
++                    prop_assert!(Sorter::<M, ExplicitOnly>::try_from_unordered_psbt(psbt()).is_ok());
 +
 +                    let mixed = || Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).unwrap();
 +                    let ordered = mixed().try_into_ordered_psbt().unwrap();
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    prop_assert_eq!(to_psbt(mixed().try_sort().unwrap()), ordered);
 +
 +                    let seeded = || {
-+                        Sorter::<M, Deterministic>::try_from_unordered_psbt(psbt())
++                        Sorter::<M, DerivedOnly>::try_from_unordered_psbt(psbt())
 +                            .unwrap()
 +                            .set_seed(seed.clone())
 +                    };
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                psbt.inputs = InputSet::try_from_inputs([make_input(first, 0), make_input(second, 0)]).unwrap();
 +                psbt.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[first]), make_output_with_uid(&[second])]).unwrap();
 +
-+                let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++                let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +                let ordered = sorter.try_into_ordered_psbt().unwrap();
 +                prop_assert_eq!(ordered.inputs.len(), 2);
 +                prop_assert_eq!(ordered.outputs.len(), 2);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let mut missing_input = empty_psbt();
 +                missing_input.inputs = InputSet::try_from_inputs([make_input(1, 0)]).unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Unmodifiable, Explicit>(missing_input, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, ExplicitOnly>(missing_input, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::MissingInputSortKey(_))
 +                ));
 +
 +                let mut missing_output = empty_psbt();
 +                missing_output.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[1])]).unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Unmodifiable, Explicit>(missing_output, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, ExplicitOnly>(missing_output, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::MissingOutputSortKey)
 +                ));
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                }))
 +                .unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Unmodifiable, Explicit>(duplicates, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, ExplicitOnly>(duplicates, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::DuplicateSortKey(_))
 +                ));
 +            }

@github-actions

Copy link
Copy Markdown
range-diff for force push fd221478f4 → a76152e86e November 14, 2026 04:15 UTC: 1 modified; 1 commit; base a0900aeb14 → 568bc715d0 (diverged, 3 ahead and 3 behind)

reproduce: git range-diff a0900ae..fd22147 568bc71..a76152e

1:  fd221478f4 +1324 -3 9f ! 1:  a76152e86e +1324 -3 9f introduce Sorter role
1: fd221478f4 ! 1: a76152e86e introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +/// or transaction-specific nonce) so that all participants produce the
 +/// same order without revealing sort criteria to observers.
 +#[derive(Debug, Clone, PartialEq)]
-+pub enum Deterministic {}
++pub enum DerivedOnly {}
 +
 +/// Sort mode: ordering determined by explicit sort key fields on each input/output.
 +#[derive(Debug, Clone, PartialEq)]
-+pub enum Explicit {}
++pub enum ExplicitOnly {}
 +
 +/// Sort mode: explicit sort keys where present, the rest derived from the
 +/// sort seed.
 +#[derive(Debug, Clone, PartialEq)]
 +pub enum Mixed {}
 +
-+/// Sort mode refinement: [`Deterministic`] or [`Mixed`] with
++/// Sort mode refinement: [`DerivedOnly`] or [`Mixed`] with
 +/// `PSBT_GLOBAL_SORT_SEED` known to be set.
 +#[derive(Debug, Clone, PartialEq)]
 +pub struct Seeded<S>(PhantomData<S>, std::convert::Infallible);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +/// may still be added, the [`Updater`](psbt_v2::v2::Updater) once neither
 +/// may.
 +///
-+/// `S` is the sort mode: [`Mixed`], [`Deterministic`], or [`Explicit`], or
-+/// [`Seeded`] `Mixed` or `Deterministic` once the sort seed is known to be set.
++/// `S` is the sort mode: [`Mixed`], [`DerivedOnly`], or [`ExplicitOnly`], or
++/// [`Seeded`] `Mixed` or `DerivedOnly` once the sort seed is known to be set.
 +///
 +/// # Ordering
 +///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability> Sorter<M, Deterministic> {
++impl<M: Modifiability> Sorter<M, DerivedOnly> {
 +    /// Create a deterministic sorter from an [`UnorderedPsbt`].
 +    ///
 +    /// # Errors
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +
 +    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
-+    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<Deterministic>> {
++    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<DerivedOnly>> {
 +        self.with_seed(seed)
 +    }
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    pub fn try_into_ordered_psbt(self) -> Result<Psbt, SortError> {
 +        match self.0.global.sort_seed() {
 +            Some(_) => {
-+                Ok(Sorter::<M, Seeded<Deterministic>>::from_unordered(self.0).into_ordered_psbt())
++                Ok(Sorter::<M, Seeded<DerivedOnly>>::from_unordered(self.0).into_ordered_psbt())
 +            }
 +            None => Err(SortError::MissingSortSeed),
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability> Sorter<M, Seeded<Deterministic>> {
++impl<M: Modifiability> Sorter<M, Seeded<DerivedOnly>> {
 +    /// Apply deterministic ordering: derive sort keys from the seed, sort,
 +    /// and produce an ordered BIP 370 [`Psbt`].
 +    ///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability> Sorter<M, Explicit> {
++impl<M: Modifiability> Sorter<M, ExplicitOnly> {
 +    /// Create an explicit-mode sorter from an [`UnorderedPsbt`].
 +    ///
 +    /// # Errors
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        #[test]
 +        fn deterministic_no_seed_err() {
 +            let psbt = empty_psbt();
-+            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            assert!(sorter.try_into_ordered_psbt().is_err());
 +        }
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt.inputs =
 +                InputSet::try_from_inputs([make_input(2, 0), make_input(1, 0), make_input(3, 0)])
 +                    .unwrap();
-+            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            assert_eq!(ordered.inputs.len(), 3);
 +            // Verify deterministic: same seed, same order
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt2.inputs =
 +                InputSet::try_from_inputs([make_input(3, 0), make_input(1, 0), make_input(2, 0)])
 +                    .unwrap();
-+            let sorter2: Sorter<Unmodifiable, Deterministic> = Sorter(psbt2, PhantomData);
++            let sorter2: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt2, PhantomData);
 +            let ordered2 = sorter2.try_into_ordered_psbt().unwrap();
 +            for (a, b) in ordered.inputs.iter().zip(ordered2.inputs.iter()) {
 +                assert_eq!(a.previous_txid, b.previous_txid);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                OutputSet::try_from_outputs((0..8).map(|uid| make_output_with_uid(&[uid])))
 +                    .unwrap();
 +
-+            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            let keys: Vec<_> = sorter
 +                .try_into_ordered_psbt()
 +                .unwrap()
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            let mut i2 = make_input(2, 0);
 +            i2.set_sort_key(sort_key(vec![0x01]));
 +            psbt.inputs = InputSet::try_from_inputs([i1, i2]).unwrap();
-+            let sorter: Sorter<Unmodifiable, Explicit> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, ExplicitOnly> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            // i2 (key 0x01) should come before i1 (key 0x02)
 +            assert_eq!(
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            psbt.global.set_unordered();
 +            psbt.global.set_sort_seed(sort_seed(vec![0u8; 32]));
 +            assert!(psbt.global.is_unordered());
-+            let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
 +            assert!(!ordered.global.is_unordered());
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                psbt
 +            };
 +
-+            let ordered = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(psbt())
++            let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(psbt())
 +                .unwrap()
 +                .set_seed(sort_seed(seed.clone()))
 +                .into_ordered_psbt();
-+            let updater = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(psbt())
++            let updater = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(psbt())
 +                .unwrap()
 +                .set_seed(sort_seed(seed.clone()))
 +                .try_sort()
 +                .expect("the inputs carry no lock time requirements");
 +            assert_eq!(updater.psbt(), ordered);
 +            assert!(
-+                Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(preset())
++                Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(preset())
 +                    .unwrap()
 +                    .try_sort()
 +                    .is_ok()
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                Err(SortError::MissingSortSeed)
 +            ));
 +            assert!(matches!(
-+                Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(psbt())
++                Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(psbt())
 +                    .unwrap()
 +                    .try_sort(),
 +                Err(SortError::MissingInputSortKey(_))
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    let mut psbt = empty_psbt();
 +                    psbt.global.set_sort_seed(sort_seed(seed.clone()));
 +                    psbt.inputs = InputSet::try_from_inputs([make_input(1, 0), make_input(2, 0), make_input(3, 0)]).unwrap();
-+                    let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++                    let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +                    sorter.try_into_ordered_psbt().unwrap()
 +                };
 +                let a = make();
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let mut i2 = make_input(2, 0);
 +                i2.set_sort_key(sort_key(k2.clone()));
 +                psbt.inputs = InputSet::try_from_inputs([i1, i2]).unwrap();
-+                let sorter: Sorter<Unmodifiable, Explicit> = Sorter(psbt, PhantomData);
++                let sorter: Sorter<Unmodifiable, ExplicitOnly> = Sorter(psbt, PhantomData);
 +                let ordered = sorter.try_into_ordered_psbt().unwrap();
 +                prop_assert_eq!(ordered.inputs.len(), 2);
 +                // First input should have the lexicographically smaller key
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let txids = |psbt: &Psbt| psbt.inputs.iter().map(|input| input.previous_txid).collect::<Vec<_>>();
 +                let uids = |psbt: &Psbt| psbt.outputs.iter().map(|output| output.unique_id_bytes().map(<[u8]>::to_vec)).collect::<Vec<_>>();
 +
-+                let deterministic = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(unseeded()).unwrap()
++                let deterministic = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(unseeded()).unwrap()
 +                    .set_seed(sort_seed(seed.clone()))
 +                    .into_ordered_psbt();
-+                let expected = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(preset()).unwrap()
++                let expected = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(preset()).unwrap()
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
 +                prop_assert_eq!(deterministic.global.sort_seed(), Some(seed.as_slice()));
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(true)).unwrap().try_sort(),
-+                    Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(true)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(make(false)).unwrap().try_sort(),
-+                    Sorter::<Unmodifiable, Explicit>::try_from_unordered_psbt(make(false)).unwrap().try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(make(false)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(make(false)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
-+                let seeded = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone()));
-+                let ordered = Sorter::<Unmodifiable, Deterministic>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone())).into_ordered_psbt();
++                let seeded = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone()));
++                let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone())).into_ordered_psbt();
 +                match seeded.try_sort() {
 +                    Ok(updater) => prop_assert_eq!(updater.psbt(), ordered),
 +                    Err(_) => prop_assert!(conflicting_lock_times),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    if actual != M::EXPECTED_FLAGS {
 +                        let mismatch = Some(FlagsMismatch { expected: M::EXPECTED_FLAGS, actual });
 +                        prop_assert_eq!(Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).err(), mismatch);
-+                        prop_assert_eq!(Sorter::<M, Deterministic>::try_from_unordered_psbt(psbt()).err(), mismatch);
-+                        prop_assert_eq!(Sorter::<M, Explicit>::try_from_unordered_psbt(psbt()).err(), mismatch);
++                        prop_assert_eq!(Sorter::<M, DerivedOnly>::try_from_unordered_psbt(psbt()).err(), mismatch);
++                        prop_assert_eq!(Sorter::<M, ExplicitOnly>::try_from_unordered_psbt(psbt()).err(), mismatch);
 +                        return Ok(());
 +                    }
-+                    prop_assert!(Sorter::<M, Explicit>::try_from_unordered_psbt(psbt()).is_ok());
++                    prop_assert!(Sorter::<M, ExplicitOnly>::try_from_unordered_psbt(psbt()).is_ok());
 +
 +                    let mixed = || Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).unwrap();
 +                    let ordered = mixed().try_into_ordered_psbt().unwrap();
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    prop_assert_eq!(to_psbt(mixed().try_sort().unwrap()), ordered);
 +
 +                    let seeded = || {
-+                        Sorter::<M, Deterministic>::try_from_unordered_psbt(psbt())
++                        Sorter::<M, DerivedOnly>::try_from_unordered_psbt(psbt())
 +                            .unwrap()
 +                            .set_seed(seed.clone())
 +                    };
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                psbt.inputs = InputSet::try_from_inputs([make_input(first, 0), make_input(second, 0)]).unwrap();
 +                psbt.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[first]), make_output_with_uid(&[second])]).unwrap();
 +
-+                let sorter: Sorter<Unmodifiable, Deterministic> = Sorter(psbt, PhantomData);
++                let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +                let ordered = sorter.try_into_ordered_psbt().unwrap();
 +                prop_assert_eq!(ordered.inputs.len(), 2);
 +                prop_assert_eq!(ordered.outputs.len(), 2);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let mut missing_input = empty_psbt();
 +                missing_input.inputs = InputSet::try_from_inputs([make_input(1, 0)]).unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Unmodifiable, Explicit>(missing_input, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, ExplicitOnly>(missing_input, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::MissingInputSortKey(_))
 +                ));
 +
 +                let mut missing_output = empty_psbt();
 +                missing_output.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[1])]).unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Unmodifiable, Explicit>(missing_output, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, ExplicitOnly>(missing_output, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::MissingOutputSortKey)
 +                ));
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                }))
 +                .unwrap();
 +                prop_assert!(matches!(
-+                    Sorter::<Unmodifiable, Explicit>(duplicates, PhantomData).try_into_ordered_psbt(),
++                    Sorter::<Unmodifiable, ExplicitOnly>(duplicates, PhantomData).try_into_ordered_psbt(),
 +                    Err(SortError::DuplicateSortKey(_))
 +                ));
 +            }

@github-actions

Copy link
Copy Markdown
range-diff for force push a76152e86e → 12ff101504 November 14, 2026 04:23 UTC: 1 modified; 1 commit; same base 568bc715d0

reproduce: git range-diff 568bc71..a76152e 568bc71..12ff101

1:  a76152e86e +1324 -3 9f ! 1:  12ff101504 +1325 -3 9f introduce Sorter role
1: a76152e86e ! 1: 12ff101504 introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    use crate::input::{InputSet, InputSortKeyExt, SortKey};
 +    use crate::output::{OutputSet, PSBT_OUT_UNIQUE_ID_SUBTYPE};
 +    use crate::output::{OutputSortKeyExt, OutputUniqueIdExt};
-+    use psbt_v2::v2::{Global, Input, Output, Updater};
++    use psbt_v2::v2::{Global, Input, Output};
 +
 +    fn sort_seed(bytes: Vec<u8>) -> SortSeed {
 +        SortSeed::try_from(bytes).expect("test seeds are at least 16 bytes")
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    mod prop {
 +        use super::*;
 +        use proptest::prelude::*;
++        use psbt_v2::v2::Updater;
 +
 +        proptest! {
 +            #[test]

@github-actions

Copy link
Copy Markdown
range-diff for force push 12ff101504 → 1a90913800 November 14, 2026 05:22 UTC: 1 modified; 1 commit; same base 568bc715d0

reproduce: git range-diff 568bc71..12ff101 568bc71..1a90913

1:  12ff101504 +1325 -3  9f ! 1:  1a90913800 +1514 -3 13f introduce Sorter role
1: 12ff101504 ! 1: 1a90913800 introduce Sorter role
@@ Commit message
     This uses a typestate based approach, like the upstream psbt-v2
     Constructor role, in order to implement the different sorting modes.
 
+ ## crates/concurrent-psbt/proptest-regressions/roles/sorter/mod.txt (new) ##
+@@
++# Seeds for failure cases proptest has generated in the past. It is
++# automatically read and these particular cases re-run before any
++# novel cases are generated.
++#
++# It is recommended to check this file in to source control so that
++# everyone who runs the test benefits from these saved cases.
++cc 39728d98d282d3d81bf1a5783f5f58504b398271ad6720f9787409954e59bca8 # shrinks to seed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
++cc a94a4865ad316811f11cd786fc248d1012b45e08bebd86d20cdf91acd3c7b934 # shrinks to seed = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], conflicting_lock_times = false
+
  ## crates/concurrent-psbt/src/lib.rs ##
 @@ crates/concurrent-psbt/src/lib.rs: mod values;
  mod collections;
@@ crates/concurrent-psbt/src/lib.rs: mod values;
  pub use lattice::join::{Join, JoinMut};
  pub use lattice::partial::{Conflict, JoinResult, PartialJoin};
 
+ ## crates/concurrent-psbt/src/psbt/input_set.rs ##
+@@ crates/concurrent-psbt/src/psbt/input_set.rs: impl InputSet {
+         self.0.set().is_empty()
+     }
+ 
++    /// Iterate over the inputs, in no particular order.
++    pub(crate) fn values(&self) -> impl Iterator<Item = &Input> {
++        self.0.set().values()
++    }
++
+     /// Return `true` if the set contains an input spending the given outpoint.
+     pub fn spends_outpoint(&self, op: &OutPoint) -> bool {
+         self.0.set().contains_key(op)
+
+ ## crates/concurrent-psbt/src/psbt/keyed_set.rs ##
+@@ crates/concurrent-psbt/src/psbt/keyed_set.rs: impl<K: Hash + Eq, V> KeyedSet<K, V> {
+     pub(crate) fn contains_key(&self, key: &K) -> bool {
+         self.0.contains_key(key)
+     }
++
++    /// Iterate over the entries' values, in no particular order.
++    pub(crate) fn values(&self) -> impl Iterator<Item = &V> {
++        self.0.values()
++    }
+ }
+ 
+ impl<K, V> IntoIterator for KeyedSet<K, V> {
+
  ## crates/concurrent-psbt/src/psbt/output.rs ##
 @@ crates/concurrent-psbt/src/psbt/output.rs: pub const PSBT_OUT_UNIQUE_ID_SUBTYPE: u8 = 0x01;
  /// Extension trait on [`psbt_v2::v2::Output`] for accessing the unique-ID proprietary field.
@@ crates/concurrent-psbt/src/psbt/output.rs: pub trait OutputUniqueIdExt {
  
      fn set_unique_id(&mut self, id: UniqueId) {
 
+ ## crates/concurrent-psbt/src/psbt/output_set.rs ##
+@@ crates/concurrent-psbt/src/psbt/output_set.rs: impl OutputSet {
+         self.0.set().is_empty()
+     }
+ 
++    /// Iterate over the outputs, in no particular order.
++    pub(crate) fn values(&self) -> impl Iterator<Item = &Output> {
++        self.0.set().values()
++    }
++
+     pub fn wrap(self) -> ResultOutputSet {
+         ResultOutputSet(self.0.wrap(OutputExt::wrap))
+     }
+
  ## crates/concurrent-psbt/src/roles/mod.rs (new) ##
 @@
 +//! BIP 370 PSBT roles.
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +
 +impl std::error::Error for FlagsMismatch {}
 +
++/// Error when a PSBT's sort fields do not describe the expected
++/// [`SortMode`](super::SortMode).
++#[derive(Debug, Clone, PartialEq)]
++pub enum SortModeError {
++    /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is not the mode's value.
++    SortKeyDerivation {
++        /// The mode's value, `None` for unset.
++        expected: Option<u8>,
++        /// The PSBT's value, `None` for unset.
++        actual: Option<u8>,
++    },
++    /// The mode is [`Seeded`](super::Seeded) but `PSBT_GLOBAL_SORT_SEED` is
++    /// not set.
++    MissingSortSeed,
++    /// The mode is [`ExplicitOnly`](super::ExplicitOnly) but `PSBT_GLOBAL_SORT_SEED`
++    /// is set.
++    UnexpectedSortSeed,
++    /// The mode is [`DerivedOnly`](super::DerivedOnly) but an input or
++    /// output has a sort key.
++    UnexpectedSortKey,
++}
++
++impl std::fmt::Display for SortModeError {
++    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
++        let show = |value: &Option<u8>| value.map_or("unset".to_owned(), |v| format!("0x{v:02x}"));
++        match self {
++            Self::SortKeyDerivation { expected, actual } => write!(
++                f,
++                "PSBT_GLOBAL_SORT_KEY_DERIVATION is {}, expected {}",
++                show(actual),
++                show(expected)
++            ),
++            Self::MissingSortSeed => write!(f, "PSBT_GLOBAL_SORT_SEED not set"),
++            Self::UnexpectedSortSeed => {
++                write!(f, "PSBT_GLOBAL_SORT_SEED is set in explicit-only sort mode")
++            }
++            Self::UnexpectedSortKey => write!(f, "a sort key is set in derived-only sort mode"),
++        }
++    }
++}
++
++impl std::error::Error for SortModeError {}
++
++/// Error when an [`UnorderedPsbt`](crate::tx::UnorderedPsbt) cannot enter a
++/// [`Sorter`](super::Sorter) of the requested modifiability and sort mode.
++#[derive(Debug, Clone, PartialEq)]
++pub enum SorterError {
++    /// `tx_modifiable_flags` don't match the modifiability.
++    Flags(FlagsMismatch),
++    /// The sort fields don't select the sort mode.
++    SortMode(SortModeError),
++}
++
++impl std::fmt::Display for SorterError {
++    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
++        match self {
++            Self::Flags(error) => error.fmt(f),
++            Self::SortMode(error) => error.fmt(f),
++        }
++    }
++}
++
++impl std::error::Error for SorterError {}
++
++impl From<FlagsMismatch> for SorterError {
++    fn from(error: FlagsMismatch) -> Self {
++        Self::Flags(error)
++    }
++}
++
++impl From<SortModeError> for SorterError {
++    fn from(error: SortModeError) -> Self {
++        Self::SortMode(error)
++    }
++}
++
 +#[cfg(all(test, feature = "prop-tests"))]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +                    format!("tx_modifiable_flags mismatch: expected 0x0{expected}, got 0x0{actual}")
 +                );
 +            }
++
++            #[test]
++            fn sort_mode_error_displays_cover_every_variant(
++                expected in proptest::option::of(any::<u8>()),
++                actual in proptest::option::of(any::<u8>()),
++                flags_expected in 0u8..4,
++                flags_actual in 0u8..4,
++            ) {
++                let error = SortModeError::SortKeyDerivation { expected, actual };
++                let shown = error.to_string();
++                for value in [actual, expected] {
++                    let expected = value.map_or("unset".to_owned(), |v| format!("0x{v:02x}"));
++                    prop_assert!(shown.contains(&expected));
++                }
++                prop_assert_eq!(SorterError::from(error).to_string(), shown);
++                let mismatch = FlagsMismatch { expected: flags_expected, actual: flags_actual };
++                prop_assert_eq!(SorterError::from(mismatch).to_string(), mismatch.to_string());
++                prop_assert!(SortModeError::MissingSortSeed.to_string().contains("not set"));
++                prop_assert!(SortModeError::UnexpectedSortSeed.to_string().contains("explicit"));
++                prop_assert!(SortModeError::UnexpectedSortKey.to_string().contains("derived-only"));
++            }
 +        }
 +    }
 +}
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +use psbt_v2::v2::Psbt;
 +
 +use crate::global::{GlobalSortExt, SortSeed};
++use crate::input::InputSortKeyExt;
++use crate::output::OutputSortKeyExt;
 +use crate::tx::UnorderedPsbt;
 +
 +mod error;
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +mod modifiability;
 +mod order;
 +
-+pub use error::{FlagsMismatch, SortError};
++pub use error::{FlagsMismatch, SortError, SortModeError, SorterError};
 +pub use key::{SortKeyHash, SortKeyTag};
 +use key::{
 +    derived_input_sort_key, derived_output_sort_key, explicit_input_sort_key,
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +}
 +
-+impl<M: Modifiability, S> Sorter<M, S> {
-+    fn try_from_unordered(psbt: UnorderedPsbt) -> Result<Self, FlagsMismatch> {
++impl<M: Modifiability, S: SortMode> Sorter<M, S> {
++    /// Create a sorter from an [`UnorderedPsbt`] of any modifiability.
++    ///
++    /// # Errors
++    /// Returns [`SorterError::Flags`] if `tx_modifiable_flags` don't match
++    /// `M`, or [`SorterError::SortMode`] if the sort fields don't select `S`.
++    pub fn try_from_unordered_psbt(psbt: UnorderedPsbt) -> Result<Self, SorterError> {
 +        check_flags::<M>(psbt.global.tx_modifiable_flags)?;
++        check_sort_mode::<S>(&psbt)?;
 +        Ok(Sorter::from_unordered(psbt))
 +    }
 +}
 +
 +impl<M: Modifiability> Sorter<M, Mixed> {
-+    /// Create a mixed-mode sorter from an [`UnorderedPsbt`].
-+    ///
-+    /// # Errors
-+    /// Returns [`FlagsMismatch`] if `tx_modifiable_flags` don't match `M`.
-+    pub fn try_from_unordered_psbt(psbt: UnorderedPsbt) -> Result<Self, FlagsMismatch> {
-+        Sorter::try_from_unordered(psbt)
-+    }
-+
 +    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
 +    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<Mixed>> {
 +        self.with_seed(seed)
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +}
 +
 +impl<M: Modifiability> Sorter<M, DerivedOnly> {
-+    /// Create a deterministic sorter from an [`UnorderedPsbt`].
-+    ///
-+    /// # Errors
-+    /// Returns [`FlagsMismatch`] if `tx_modifiable_flags` don't match `M`.
-+    pub fn try_from_unordered_psbt(psbt: UnorderedPsbt) -> Result<Self, FlagsMismatch> {
-+        Sorter::try_from_unordered(psbt)
-+    }
-+
 +    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
 +    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<DerivedOnly>> {
 +        self.with_seed(seed)
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +}
 +
 +impl<M: Modifiability> Sorter<M, ExplicitOnly> {
-+    /// Create an explicit-mode sorter from an [`UnorderedPsbt`].
-+    ///
-+    /// # Errors
-+    /// Returns [`FlagsMismatch`] if `tx_modifiable_flags` don't match `M`.
-+    pub fn try_from_unordered_psbt(psbt: UnorderedPsbt) -> Result<Self, FlagsMismatch> {
-+        Sorter::try_from_unordered(psbt)
-+    }
-+
 +    /// Apply explicit ordering: sort by the `PSBT_IN_SORT_KEY` and
 +    /// `PSBT_OUT_SORT_KEY` fields, and produce an ordered BIP 370 [`Psbt`].
 +    ///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +}
 +
++pub(crate) mod sealed {
++    pub trait SortMode {
++        /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` in this mode.
++        const SORT_KEY_DERIVATION: Option<u8>;
++        /// Whether this mode requires `PSBT_GLOBAL_SORT_SEED`.
++        const SEEDED: bool;
++    }
++}
++
++/// A sort mode that a PSBT's sort fields select: [`Mixed`] if
++/// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is unset, [`DerivedOnly`] if it is
++/// `0x01`, [`ExplicitOnly`] if it is `0x00`, and [`Seeded`] [`Mixed`] or
++/// [`DerivedOnly`] if `PSBT_GLOBAL_SORT_SEED` is set too.
++pub trait SortMode: sealed::SortMode {}
++
++macro_rules! sort_mode {
++    ($($mode:ty => $sort_key_derivation:expr, $seeded:expr;)*) => {$(
++        impl SortMode for $mode {}
++
++        impl sealed::SortMode for $mode {
++            const SORT_KEY_DERIVATION: Option<u8> = $sort_key_derivation;
++            const SEEDED: bool = $seeded;
++        }
++    )*};
++}
++
++sort_mode! {
++    Mixed => None, false;
++    Seeded<Mixed> => None, true;
++    DerivedOnly => Some(0x01), false;
++    Seeded<DerivedOnly> => Some(0x01), true;
++    ExplicitOnly => Some(0x00), false;
++}
++
++/// Check that `psbt`'s sort fields select sort mode `S`. Besides matching
++/// `PSBT_GLOBAL_SORT_KEY_DERIVATION` and requiring a seed in a [`Seeded`] mode,
++/// an [`ExplicitOnly`] PSBT must have no sort seed and a [`DerivedOnly`] one no
++/// sort keys, since neither would be used.
++///
++/// # Errors
++/// Returns the first [`SortModeError`] in that order.
++pub(crate) fn check_sort_mode<S: SortMode>(psbt: &UnorderedPsbt) -> Result<(), SortModeError> {
++    let actual = psbt.global.sort_key_derivation();
++    if actual != S::SORT_KEY_DERIVATION {
++        return Err(SortModeError::SortKeyDerivation {
++            expected: S::SORT_KEY_DERIVATION,
++            actual,
++        });
++    }
++    let seeded = psbt.global.sort_seed().is_some();
++    let sort_keyed = || {
++        psbt.inputs.values().any(|input| input.sort_key().is_some())
++            || psbt
++                .outputs
++                .values()
++                .any(|output| output.sort_key().is_some())
++    };
++    match S::SORT_KEY_DERIVATION {
++        _ if S::SEEDED && !seeded => Err(SortModeError::MissingSortSeed),
++        Some(0x00) if seeded => Err(SortModeError::UnexpectedSortSeed),
++        Some(0x01) if sort_keyed() => Err(SortModeError::UnexpectedSortKey),
++        _ => Ok(()),
++    }
++}
++
 +#[cfg(test)]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        output
 +    }
 +
++    /// `psbt` with `PSBT_GLOBAL_SORT_KEY_DERIVATION` set to `mode`.
++    fn with_derivation(mut psbt: UnorderedPsbt, mode: u8) -> UnorderedPsbt {
++        psbt.global.set_sort_key_derivation(mode);
++        psbt
++    }
++
 +    fn empty_psbt() -> UnorderedPsbt {
 +        UnorderedPsbt {
 +            global: Global::default(),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                psbt
 +            };
 +
-+            let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(psbt())
-+                .unwrap()
-+                .set_seed(sort_seed(seed.clone()))
-+                .into_ordered_psbt();
-+            let updater = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(psbt())
-+                .unwrap()
-+                .set_seed(sort_seed(seed.clone()))
-+                .try_sort()
-+                .expect("the inputs carry no lock time requirements");
++            let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(
++                with_derivation(psbt(), 0x01),
++            )
++            .unwrap()
++            .set_seed(sort_seed(seed.clone()))
++            .into_ordered_psbt();
++            let updater = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(
++                with_derivation(psbt(), 0x01),
++            )
++            .unwrap()
++            .set_seed(sort_seed(seed.clone()))
++            .try_sort()
++            .expect("the inputs carry no lock time requirements");
 +            assert_eq!(updater.psbt(), ordered);
 +            assert!(
-+                Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(preset())
-+                    .unwrap()
-+                    .try_sort()
-+                    .is_ok()
++                Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(
++                    preset(),
++                    0x01
++                ))
++                .unwrap()
++                .try_sort()
++                .is_ok()
 +            );
 +
 +            assert!(
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                Err(SortError::MissingSortSeed)
 +            ));
 +            assert!(matches!(
-+                Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(psbt())
-+                    .unwrap()
-+                    .try_sort(),
++                Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(with_derivation(
++                    psbt(),
++                    0x00
++                ))
++                .unwrap()
++                .try_sort(),
 +                Err(SortError::MissingInputSortKey(_))
 +            ));
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let txids = |psbt: &Psbt| psbt.inputs.iter().map(|input| input.previous_txid).collect::<Vec<_>>();
 +                let uids = |psbt: &Psbt| psbt.outputs.iter().map(|output| output.unique_id_bytes().map(<[u8]>::to_vec)).collect::<Vec<_>>();
 +
-+                let deterministic = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(unseeded()).unwrap()
++                let deterministic = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(unseeded(), 0x01)).unwrap()
 +                    .set_seed(sort_seed(seed.clone()))
 +                    .into_ordered_psbt();
-+                let expected = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(preset()).unwrap()
++                let expected = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(preset(), 0x01)).unwrap()
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
 +                prop_assert_eq!(deterministic.global.sort_seed(), Some(seed.as_slice()));
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                seed in proptest::collection::vec(any::<u8>(), 16..=32),
 +                conflicting_lock_times in any::<bool>(),
 +            ) {
-+                let make = |seeded: bool| {
++                let make = |seeded: bool, keyed: bool| {
 +                    let mut psbt = empty_psbt();
 +                    if seeded {
 +                        psbt.global.set_sort_seed(sort_seed(seed.clone()));
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    if !conflicting_lock_times {
 +                        inputs[0].min_time = None;
 +                    }
-+                    for (key, input) in inputs.iter_mut().enumerate() {
-+                        input.set_sort_key(sort_key(vec![key as u8]));
++                    if keyed {
++                        for (key, input) in inputs.iter_mut().enumerate() {
++                            input.set_sort_key(sort_key(vec![key as u8]));
++                        }
 +                    }
 +                    psbt.inputs = InputSet::try_from_inputs(inputs).unwrap();
 +                    psbt
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                };
 +
 +                check(
-+                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false)).unwrap().try_sort(),
-+                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false)).unwrap().try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false, true)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false, true)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone())).try_sort(),
-+                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(false, true)).unwrap().set_seed(sort_seed(seed.clone())).try_sort(),
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(make(true, true)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(true)).unwrap().try_sort(),
-+                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(true)).unwrap().try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(make(true, false), 0x01)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(make(true, false), 0x01)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
 +                check(
-+                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(make(false)).unwrap().try_sort(),
-+                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(make(false)).unwrap().try_into_ordered_psbt().unwrap(),
++                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(with_derivation(make(false, true), 0x00)).unwrap().try_sort(),
++                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(with_derivation(make(false, true), 0x00)).unwrap().try_into_ordered_psbt().unwrap(),
 +                )?;
-+                let seeded = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone()));
-+                let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(make(false)).unwrap().set_seed(sort_seed(seed.clone())).into_ordered_psbt();
++                let seeded = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(make(false, false), 0x01)).unwrap().set_seed(sort_seed(seed.clone()));
++                let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(make(false, false), 0x01)).unwrap().set_seed(sort_seed(seed.clone())).into_ordered_psbt();
 +                match seeded.try_sort() {
 +                    Ok(updater) => prop_assert_eq!(updater.psbt(), ordered),
 +                    Err(_) => prop_assert!(conflicting_lock_times),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                {
 +                    let actual = psbt().global.tx_modifiable_flags;
 +                    if actual != M::EXPECTED_FLAGS {
-+                        let mismatch = Some(FlagsMismatch { expected: M::EXPECTED_FLAGS, actual });
-+                        prop_assert_eq!(Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).err(), mismatch);
-+                        prop_assert_eq!(Sorter::<M, DerivedOnly>::try_from_unordered_psbt(psbt()).err(), mismatch);
-+                        prop_assert_eq!(Sorter::<M, ExplicitOnly>::try_from_unordered_psbt(psbt()).err(), mismatch);
++                        // Flags are checked before the sort mode.
++                        let mismatch = Some(SorterError::Flags(FlagsMismatch { expected: M::EXPECTED_FLAGS, actual }));
++                        prop_assert_eq!(Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).err(), mismatch.clone());
++                        prop_assert_eq!(Sorter::<M, DerivedOnly>::try_from_unordered_psbt(with_derivation(psbt(), 0x01)).err(), mismatch.clone());
++                        prop_assert_eq!(Sorter::<M, ExplicitOnly>::try_from_unordered_psbt(with_derivation(psbt(), 0x00)).err(), mismatch);
 +                        return Ok(());
 +                    }
-+                    prop_assert!(Sorter::<M, ExplicitOnly>::try_from_unordered_psbt(psbt()).is_ok());
 +
 +                    let mixed = || Sorter::<M, Mixed>::try_from_unordered_psbt(psbt()).unwrap();
 +                    let ordered = mixed().try_into_ordered_psbt().unwrap();
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    prop_assert_eq!(to_psbt(mixed().try_sort().unwrap()), ordered);
 +
 +                    let seeded = || {
-+                        Sorter::<M, DerivedOnly>::try_from_unordered_psbt(psbt())
++                        let mut psbt = psbt();
++                        psbt.global.set_sort_key_derivation(0x01);
++                        Sorter::<M, DerivedOnly>::try_from_unordered_psbt(psbt)
 +                            .unwrap()
 +                            .set_seed(seed.clone())
 +                    };

@github-actions

Copy link
Copy Markdown
range-diff for force push 1a90913800 → 9f9eadc5bf November 14, 2026 08:51 UTC: 1 modified; 1 commit; base 568bc715d0 → 4bf7243953 (diverged, 8 ahead and 6 behind)

reproduce: git range-diff 568bc71..1a90913 4bf7243..9f9eadc

1:  1a90913800 +1514 -3 13f ! 1:  9f9eadc5bf +1508 -0 12f introduce Sorter role
1: 1a90913800 ! 1: 9f9eadc5bf introduce Sorter role
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs: impl<K: Hash + Eq, V> KeyedSet<K,
  
  impl<K, V> IntoIterator for KeyedSet<K, V> {
 
- ## crates/concurrent-psbt/src/psbt/output.rs ##
-@@ crates/concurrent-psbt/src/psbt/output.rs: pub const PSBT_OUT_UNIQUE_ID_SUBTYPE: u8 = 0x01;
- /// Extension trait on [`psbt_v2::v2::Output`] for accessing the unique-ID proprietary field.
- pub trait OutputUniqueIdExt {
-     /// Return the [`UniqueId`] stored in the `PSBT_OUT_UNIQUE_ID` proprietary field, if present.
--    fn unique_id(&self) -> Option<UniqueId>;
-+    fn unique_id(&self) -> Option<UniqueId> {
-+        self.unique_id_bytes().map(|bytes| UniqueId(bytes.to_vec()))
-+    }
-+    /// Borrow the bytes of the `PSBT_OUT_UNIQUE_ID` proprietary field, if present.
-+    fn unique_id_bytes(&self) -> Option<&[u8]>;
-     /// Return `true` if this output carries a [`UniqueId`].
-     fn has_unique_id(&self) -> bool {
-         self.unique_id().is_some()
-@@ crates/concurrent-psbt/src/psbt/output.rs: pub trait OutputUniqueIdExt {
- }
- 
- impl OutputUniqueIdExt for Output {
--    fn unique_id(&self) -> Option<UniqueId> {
-+    fn unique_id_bytes(&self) -> Option<&[u8]> {
-         let key = psbt_v2::raw::ProprietaryKey {
-             prefix: b"concurrent-psbt".to_vec(),
-             subtype: PSBT_OUT_UNIQUE_ID_SUBTYPE,
-             key: vec![],
-         };
--        self.proprietaries.get(&key).map(|v| UniqueId(v.clone()))
-+        self.proprietaries.get(&key).map(Vec::as_slice)
-     }
- 
-     fn set_unique_id(&mut self, id: UniqueId) {
-
  ## crates/concurrent-psbt/src/psbt/output_set.rs ##
 @@ crates/concurrent-psbt/src/psbt/output_set.rs: impl OutputSet {
          self.0.set().is_empty()
@@ crates/concurrent-psbt/src/psbt/output_set.rs: impl OutputSet {
 +    }
 +
      pub fn wrap(self) -> ResultOutputSet {
-         ResultOutputSet(self.0.wrap(OutputExt::wrap))
+         ResultOutputSet(self.0.wrap(Output::wrap))
      }
 
  ## crates/concurrent-psbt/src/roles/mod.rs (new) ##
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +                prop_assert_eq!(SortError::MissingOutputSortKey.to_string(), "output missing sort key");
 +                prop_assert!(SortError::DuplicateSortKey(duplicate_key).to_string().starts_with("duplicate sort key: "));
 +                prop_assert!(SortError::MissingSortSeed.to_string().contains("SORT_SEED"));
++                let inputs = crate::test_support::conflicting_lock_time_inputs().map(Into::into);
 +                let lock_time = psbt_v2::v2::Psbt {
-+                    global: psbt_v2::v2::Global::default(),
-+                    inputs: crate::test_support::conflicting_lock_time_inputs().to_vec(),
++                    global: crate::global::Global::default().into_v2(inputs.len(), 0),
++                    inputs: inputs.to_vec(),
 +                    outputs: vec![],
 +                }
 +                .determine_lock_time()
@@ crates/concurrent-psbt/src/roles/sorter/key.rs (new)
 +use bitcoin::hashes::{Hash, HashEngine, sha256, sha256t_hash_newtype};
 +
 +use super::SortError;
-+use crate::input::{InputSortKeyExt, out_point};
-+use crate::output::{OutputSortKeyExt, OutputUniqueIdExt};
++use crate::input::{Input, InputSortKeyExt, out_point};
++use crate::output::{Output, OutputSortKeyExt};
 +
 +sha256t_hash_newtype! {
 +    /// Tag for the BIP 341-style tagged hash used to derive sort keys.
@@ crates/concurrent-psbt/src/roles/sorter/key.rs (new)
 +}
 +
 +/// Write the input's identifier, the consensus encoding of its outpoint.
-+pub(super) fn write_input_sort_identifier(
-+    input: &psbt_v2::v2::Input,
-+    engine: &mut sha256::HashEngine,
-+) {
++pub(super) fn write_input_sort_identifier(input: &Input, engine: &mut sha256::HashEngine) {
 +    out_point(input)
 +        .consensus_encode(engine)
 +        .expect("writing to a hash engine cannot fail");
 +}
 +
-+/// Write the output's identifier, its unique ID (nothing if it has none).
-+pub(super) fn write_output_sort_identifier(
-+    output: &psbt_v2::v2::Output,
-+    engine: &mut sha256::HashEngine,
-+) {
-+    engine.input(output.unique_id_bytes().unwrap_or_default());
++/// Write the output's identifier, its unique ID.
++pub(super) fn write_output_sort_identifier(output: &Output, engine: &mut sha256::HashEngine) {
++    engine.input(output.unique_id().as_bytes());
 +}
 +
 +pub(super) fn derived_input_sort_key(
 +    seed: Option<&[u8]>,
-+    input: &psbt_v2::v2::Input,
++    input: &Input,
 +) -> Result<Vec<u8>, SortError> {
 +    let seed = seed.ok_or(SortError::MissingSortSeed)?;
 +    Ok(derive_sort_key(seed, |engine| write_input_sort_identifier(input, engine)).to_vec())
@@ crates/concurrent-psbt/src/roles/sorter/key.rs (new)
 +
 +pub(super) fn derived_output_sort_key(
 +    seed: Option<&[u8]>,
-+    output: &psbt_v2::v2::Output,
++    output: &Output,
 +) -> Result<Vec<u8>, SortError> {
 +    let seed = seed.ok_or(SortError::MissingSortSeed)?;
 +    Ok(derive_sort_key(seed, |engine| write_output_sort_identifier(output, engine)).to_vec())
 +}
 +
-+pub(super) fn explicit_input_sort_key(input: &psbt_v2::v2::Input) -> Result<Vec<u8>, SortError> {
++pub(super) fn explicit_input_sort_key(input: &Input) -> Result<Vec<u8>, SortError> {
 +    input
 +        .sort_key()
 +        .ok_or(SortError::MissingInputSortKey(out_point(input)))
 +        .map(|key| key.to_vec())
 +}
 +
-+pub(super) fn explicit_output_sort_key(output: &psbt_v2::v2::Output) -> Result<Vec<u8>, SortError> {
++pub(super) fn explicit_output_sort_key(output: &Output) -> Result<Vec<u8>, SortError> {
 +    output
 +        .sort_key()
 +        .ok_or(SortError::MissingOutputSortKey)
@@ crates/concurrent-psbt/src/roles/sorter/key.rs (new)
 +
 +pub(super) fn mixed_input_sort_key(
 +    seed: Option<&[u8]>,
-+    input: &psbt_v2::v2::Input,
++    input: &Input,
 +) -> Result<Vec<u8>, SortError> {
 +    explicit_input_sort_key(input).or_else(|_| derived_input_sort_key(seed, input))
 +}
 +
 +pub(super) fn mixed_output_sort_key(
 +    seed: Option<&[u8]>,
-+    output: &psbt_v2::v2::Output,
++    output: &Output,
 +) -> Result<Vec<u8>, SortError> {
 +    explicit_output_sort_key(output).or_else(|_| derived_output_sort_key(seed, output))
 +}
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +mod tests {
 +    use super::key::{derive_sort_key, write_input_sort_identifier};
 +    use super::*;
-+    use crate::input::{InputSet, InputSortKeyExt, SortKey};
-+    use crate::output::{OutputSet, PSBT_OUT_UNIQUE_ID_SUBTYPE};
-+    use crate::output::{OutputSortKeyExt, OutputUniqueIdExt};
-+    use psbt_v2::v2::{Global, Input, Output};
++    use crate::global::Global;
++    use crate::input::{Input, InputSet, SortKey};
++    use crate::output::{Output, OutputSet, UniqueId};
 +
 +    fn sort_seed(bytes: Vec<u8>) -> SortSeed {
 +        SortSeed::try_from(bytes).expect("test seeds are at least 16 bytes")
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    }
 +
 +    fn make_output_with_uid(uid: &[u8]) -> Output {
-+        let mut output = Output::default();
-+        let key = psbt_v2::raw::ProprietaryKey {
-+            prefix: crate::PROPRIETARY_PREFIX.to_vec(),
-+            subtype: PSBT_OUT_UNIQUE_ID_SUBTYPE,
-+            key: vec![],
-+        };
-+        output.proprietaries.insert(key, uid.to_vec());
-+        output
++        Output::new(
++            UniqueId::new(uid.to_vec()),
++            bitcoin::Amount::ZERO,
++            bitcoin::ScriptBuf::new(),
++        )
++    }
++
++    /// Read back an output of an ordered PSBT.
++    fn read_output(output: &psbt_v2::v2::Output) -> Output {
++        Output::try_from(output.clone()).expect("sorting keeps the unique IDs")
++    }
++
++    /// Read back the global map of an ordered PSBT.
++    fn read_global(psbt: &Psbt) -> Global {
++        psbt.global.clone().into()
 +    }
 +
 +    /// `psbt` with `PSBT_GLOBAL_SORT_KEY_DERIVATION` set to `mode`.
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                .iter()
 +                .map(|output| {
 +                    derive_sort_key(&seed, |engine| {
-+                        engine.input(output.unique_id_bytes().unwrap())
++                        engine.input(read_output(output).unique_id().as_bytes())
 +                    })
 +                })
 +                .collect();
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                .outputs
 +                .iter()
 +                .map(|output| {
-+                    if output.sort_key() == Some([0xfe].as_slice()) {
++                    if read_output(output).sort_key() == Some([0xfe].as_slice()) {
 +                        0
 +                    } else {
 +                        1
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            assert!(psbt.global.is_unordered());
 +            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
 +            let ordered = sorter.try_into_ordered_psbt().unwrap();
-+            assert!(!ordered.global.is_unordered());
++            assert!(!read_global(&ordered).is_unordered());
 +        }
 +
 +        #[test]
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    psbt
 +                };
 +                let txids = |psbt: &Psbt| psbt.inputs.iter().map(|input| input.previous_txid).collect::<Vec<_>>();
-+                let uids = |psbt: &Psbt| psbt.outputs.iter().map(|output| output.unique_id_bytes().map(<[u8]>::to_vec)).collect::<Vec<_>>();
++                let uids = |psbt: &Psbt| psbt.outputs.iter().map(|output| read_output(output).unique_id().clone()).collect::<Vec<_>>();
 +
 +                let deterministic = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(unseeded(), 0x01)).unwrap()
 +                    .set_seed(sort_seed(seed.clone()))
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let expected = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(preset(), 0x01)).unwrap()
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
-+                prop_assert_eq!(deterministic.global.sort_seed(), Some(seed.as_slice()));
++                prop_assert_eq!(read_global(&deterministic).sort_seed().map(<[u8]>::to_vec), Some(seed.clone()));
 +                prop_assert_eq!(txids(&deterministic), txids(&expected));
 +                prop_assert_eq!(uids(&deterministic), uids(&expected));
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                let ordered = Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).unwrap()
 +                    .try_into_ordered_psbt()
 +                    .unwrap();
-+                prop_assert!(!ordered.global.is_unordered());
++                prop_assert!(!read_global(&ordered).is_unordered());
 +            }
 +        }
 +    }
@@ crates/concurrent-psbt/src/roles/sorter/order.rs (new)
 +
 +use super::SortError;
 +use crate::global::GlobalSortExt;
++use crate::input::Input;
++use crate::output::Output;
 +use crate::tx::UnorderedPsbt;
 +
 +pub(super) fn ordered_psbt<I, O>(
@@ crates/concurrent-psbt/src/roles/sorter/order.rs (new)
 +    mut output_key: O,
 +) -> Result<Psbt, SortError>
 +where
-+    I: FnMut(&psbt_v2::v2::Input) -> Result<Vec<u8>, SortError>,
-+    O: FnMut(&psbt_v2::v2::Output) -> Result<Vec<u8>, SortError>,
++    I: FnMut(&Input) -> Result<Vec<u8>, SortError>,
++    O: FnMut(&Output) -> Result<Vec<u8>, SortError>,
 +{
 +    let mut inputs: Vec<_> = psbt.inputs.into_iter().collect();
 +    let mut outputs: Vec<_> = psbt.outputs.into_iter().collect();
@@ crates/concurrent-psbt/src/roles/sorter/order.rs (new)
 +
 +    let mut global = psbt.global;
 +    global.clear_unordered();
-+    global.input_count = inputs.len();
-+    global.output_count = outputs.len();
 +
 +    Ok(Psbt {
-+        global,
-+        inputs,
-+        outputs,
++        global: global.into_v2(inputs.len(), outputs.len()),
++        inputs: inputs.into_iter().map(Into::into).collect(),
++        outputs: outputs.into_iter().map(Into::into).collect(),
 +    })
 +}
 +
@@ crates/concurrent-psbt/src/test_support.rs (new)
 @@
 +//! Fixtures shared by tests in several modules.
 +
++use crate::input::Input;
 +use bitcoin::absolute::{Height, Time};
 +use bitcoin::hashes::Hash;
-+use psbt_v2::v2::Input;
 +
 +/// Two inputs whose lock time requirements conflict: the first requires a
 +/// time-based lock time and the second a height-based one.

@github-actions

Copy link
Copy Markdown
range-diff for force push 4eec3a6ad7 → a288fe651f November 14, 2026 09:05 UTC: 1 modified; 1 commit; base 49b7b304df → bd05b74787 (diverged, 9 ahead and 9 behind)

reproduce: git range-diff 49b7b30..4eec3a6 bd05b74..a288fe6

1:  4eec3a6ad7 +1523 -1 13f ! 1:  a288fe651f +1627 -1 13f introduce Sorter role
1: 4eec3a6ad7 ! 1: a288fe651f introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        use super::*;
 +        use bitcoin::hashes::HashEngine;
 +
++        /// Every combination of flags and sort fields, against every
++        /// modifiability and sort mode: flags are checked first, then the sort
++        /// fields in the order `check_sort_mode` documents, and each error
++        /// renders to its own message.
++        #[test]
++        fn try_from_unordered_psbt_checks_flags_then_sort_mode() {
++            fn expected<M: Modifiability, S: SortMode>(
++                flags: u8,
++                derivation: Option<SortKeyDerivation>,
++                seeded: bool,
++                sort_keyed: bool,
++            ) -> Option<SorterError> {
++                if flags != M::EXPECTED_FLAGS {
++                    let expected = M::EXPECTED_FLAGS;
++                    return Some(
++                        FlagsMismatch {
++                            expected,
++                            actual: flags,
++                        }
++                        .into(),
++                    );
++                }
++                let error = if derivation != S::SORT_KEY_DERIVATION {
++                    let expected = S::SORT_KEY_DERIVATION;
++                    SortModeError::SortKeyDerivation {
++                        expected,
++                        actual: derivation,
++                    }
++                } else if S::SEEDED && !seeded {
++                    SortModeError::MissingSortSeed
++                } else if derivation == Some(SortKeyDerivation::Explicit) && seeded {
++                    SortModeError::UnexpectedSortSeed
++                } else if derivation == Some(SortKeyDerivation::Derived) && sort_keyed {
++                    SortModeError::UnexpectedSortKey
++                } else {
++                    return None;
++                };
++                Some(error.into())
++            }
++
++            fn check<M: Modifiability, S: SortMode>(
++                psbt: &UnorderedPsbt,
++                fields: (u8, Option<SortKeyDerivation>, bool, bool),
++                messages: &mut std::collections::HashMap<String, SorterError>,
++            ) {
++                let (flags, derivation, seeded, sort_keyed) = fields;
++                let actual = Sorter::<M, S>::try_from_unordered_psbt(psbt.clone()).err();
++                assert_eq!(
++                    actual,
++                    expected::<M, S>(flags, derivation, seeded, sort_keyed),
++                    "{fields:?}"
++                );
++                if let Some(error) = actual {
++                    let previous = messages.insert(error.to_string(), error.clone());
++                    assert!(previous.is_none_or(|previous| previous == error), "{error}");
++                }
++            }
++
++            fn check_modes<M: Modifiability>(
++                psbt: &UnorderedPsbt,
++                fields: (u8, Option<SortKeyDerivation>, bool, bool),
++                messages: &mut std::collections::HashMap<String, SorterError>,
++            ) {
++                check::<M, Mixed>(psbt, fields, messages);
++                check::<M, Seeded<Mixed>>(psbt, fields, messages);
++                check::<M, DerivedOnly>(psbt, fields, messages);
++                check::<M, Seeded<DerivedOnly>>(psbt, fields, messages);
++                check::<M, ExplicitOnly>(psbt, fields, messages);
++            }
++
++            let mut messages = std::collections::HashMap::new();
++            let derivations = [
++                None,
++                Some(SortKeyDerivation::Explicit),
++                Some(SortKeyDerivation::Derived),
++            ];
++            for flags in 0u8..4 {
++                for derivation in derivations {
++                    for seeded in [false, true] {
++                        for sort_keyed in [false, true] {
++                            let mut psbt = empty_psbt();
++                            psbt.global.tx_modifiable_flags = flags;
++                            if let Some(derivation) = derivation {
++                                psbt.global.set_sort_key_derivation(derivation);
++                            }
++                            if seeded {
++                                psbt.global.set_sort_seed(sort_seed(vec![0; 16]));
++                            }
++                            let mut input = make_input(1, 0);
++                            if sort_keyed {
++                                input.set_sort_key(sort_key(vec![1]));
++                            }
++                            psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
++                            let fields = (flags, derivation, seeded, sort_keyed);
++                            check_modes::<Unmodifiable>(&psbt, fields, &mut messages);
++                            check_modes::<BothModifiable>(&psbt, fields, &mut messages);
++                            check_modes::<InputsModifiable>(&psbt, fields, &mut messages);
++                            check_modes::<OutputsModifiable>(&psbt, fields, &mut messages);
++                        }
++                    }
++                }
++            }
++        }
++
 +        #[test]
 +        fn deterministic_no_seed_err() {
 +            let psbt = empty_psbt();

@github-actions

Copy link
Copy Markdown
range-diff for force push 4eec3a6ad7 → a288fe651f November 14, 2026 09:08 UTC: 1 modified; 1 commit; base 49b7b304df → bd05b74787 (diverged, 9 ahead and 9 behind)

reproduce: git range-diff 49b7b30..4eec3a6 bd05b74..a288fe6

1:  4eec3a6ad7 +1523 -1 13f ! 1:  a288fe651f +1627 -1 13f introduce Sorter role
1: 4eec3a6ad7 ! 1: a288fe651f introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        use super::*;
 +        use bitcoin::hashes::HashEngine;
 +
++        /// Every combination of flags and sort fields, against every
++        /// modifiability and sort mode: flags are checked first, then the sort
++        /// fields in the order `check_sort_mode` documents, and each error
++        /// renders to its own message.
++        #[test]
++        fn try_from_unordered_psbt_checks_flags_then_sort_mode() {
++            fn expected<M: Modifiability, S: SortMode>(
++                flags: u8,
++                derivation: Option<SortKeyDerivation>,
++                seeded: bool,
++                sort_keyed: bool,
++            ) -> Option<SorterError> {
++                if flags != M::EXPECTED_FLAGS {
++                    let expected = M::EXPECTED_FLAGS;
++                    return Some(
++                        FlagsMismatch {
++                            expected,
++                            actual: flags,
++                        }
++                        .into(),
++                    );
++                }
++                let error = if derivation != S::SORT_KEY_DERIVATION {
++                    let expected = S::SORT_KEY_DERIVATION;
++                    SortModeError::SortKeyDerivation {
++                        expected,
++                        actual: derivation,
++                    }
++                } else if S::SEEDED && !seeded {
++                    SortModeError::MissingSortSeed
++                } else if derivation == Some(SortKeyDerivation::Explicit) && seeded {
++                    SortModeError::UnexpectedSortSeed
++                } else if derivation == Some(SortKeyDerivation::Derived) && sort_keyed {
++                    SortModeError::UnexpectedSortKey
++                } else {
++                    return None;
++                };
++                Some(error.into())
++            }
++
++            fn check<M: Modifiability, S: SortMode>(
++                psbt: &UnorderedPsbt,
++                fields: (u8, Option<SortKeyDerivation>, bool, bool),
++                messages: &mut std::collections::HashMap<String, SorterError>,
++            ) {
++                let (flags, derivation, seeded, sort_keyed) = fields;
++                let actual = Sorter::<M, S>::try_from_unordered_psbt(psbt.clone()).err();
++                assert_eq!(
++                    actual,
++                    expected::<M, S>(flags, derivation, seeded, sort_keyed),
++                    "{fields:?}"
++                );
++                if let Some(error) = actual {
++                    let previous = messages.insert(error.to_string(), error.clone());
++                    assert!(previous.is_none_or(|previous| previous == error), "{error}");
++                }
++            }
++
++            fn check_modes<M: Modifiability>(
++                psbt: &UnorderedPsbt,
++                fields: (u8, Option<SortKeyDerivation>, bool, bool),
++                messages: &mut std::collections::HashMap<String, SorterError>,
++            ) {
++                check::<M, Mixed>(psbt, fields, messages);
++                check::<M, Seeded<Mixed>>(psbt, fields, messages);
++                check::<M, DerivedOnly>(psbt, fields, messages);
++                check::<M, Seeded<DerivedOnly>>(psbt, fields, messages);
++                check::<M, ExplicitOnly>(psbt, fields, messages);
++            }
++
++            let mut messages = std::collections::HashMap::new();
++            let derivations = [
++                None,
++                Some(SortKeyDerivation::Explicit),
++                Some(SortKeyDerivation::Derived),
++            ];
++            for flags in 0u8..4 {
++                for derivation in derivations {
++                    for seeded in [false, true] {
++                        for sort_keyed in [false, true] {
++                            let mut psbt = empty_psbt();
++                            psbt.global.tx_modifiable_flags = flags;
++                            if let Some(derivation) = derivation {
++                                psbt.global.set_sort_key_derivation(derivation);
++                            }
++                            if seeded {
++                                psbt.global.set_sort_seed(sort_seed(vec![0; 16]));
++                            }
++                            let mut input = make_input(1, 0);
++                            if sort_keyed {
++                                input.set_sort_key(sort_key(vec![1]));
++                            }
++                            psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
++                            let fields = (flags, derivation, seeded, sort_keyed);
++                            check_modes::<Unmodifiable>(&psbt, fields, &mut messages);
++                            check_modes::<BothModifiable>(&psbt, fields, &mut messages);
++                            check_modes::<InputsModifiable>(&psbt, fields, &mut messages);
++                            check_modes::<OutputsModifiable>(&psbt, fields, &mut messages);
++                        }
++                    }
++                }
++            }
++        }
++
 +        #[test]
 +        fn deterministic_no_seed_err() {
 +            let psbt = empty_psbt();

@github-actions

Copy link
Copy Markdown
range-diff for force push a288fe651f → 9e0f1f5af9 November 14, 2026 11:02 UTC: 1 unchanged; 1 commit; base bd05b74787 → a9581c5710 (diverged, 11 ahead and 10 behind)

reproduce: git range-diff bd05b74..a288fe6 a9581c5..9e0f1f5

1:  a288fe651f +1627 -1 13f = 1:  9e0f1f5af9 +1627 -1 13f introduce Sorter role

@github-actions

Copy link
Copy Markdown
range-diff for force push 9e0f1f5af9 → f932026e22 November 14, 2026 12:21 UTC: 1 modified; 1 commit; base a9581c5710 → 6a0b965918 (diverged, 9 ahead and 9 behind)

reproduce: git range-diff a9581c5..9e0f1f5 6a0b965..f932026

Some interdiffs were truncated to fit; the full range-diff is in the job summary.

1:  9e0f1f5af9 +1627 -1 13f ! 1:  f932026e22 +1782 -1 13f introduce Sorter role
1: 9e0f1f5af9 ! 1: f932026e22 introduce Sorter role
@@ crates/concurrent-psbt/src/lib.rs: mod values;
  #[macro_use]
  mod psbt;
 +pub mod roles;
-+#[cfg(all(test, feature = "prop-tests"))]
++#[cfg(all(test, feature = "unit-tests"))]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod test_support;
 +
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +    }
 +}
 +
-+#[cfg(all(test, feature = "prop-tests"))]
++#[cfg(test)]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {
 +    use super::*;
 +    use bitcoin::hashes::Hash;
 +
++    #[cfg(feature = "unit-tests")]
++    mod unit {
++        use super::*;
++
++        /// The error `Psbt::determine_lock_time` returns for these inputs.
++        fn lock_time_error() -> DetermineLockTimeError {
++            let inputs = crate::test_support::conflicting_lock_time_inputs().map(Into::into);
++            psbt_v2::v2::Psbt {
++                global: crate::global::Global::default().into_v2(inputs.len(), 0),
++                inputs: inputs.to_vec(),
++                outputs: vec![],
++            }
++            .determine_lock_time()
++            .unwrap_err()
++        }
++
++        #[test]
++        fn errors_display_the_values_they_carry() {
++            let outpoint = bitcoin::OutPoint {
++                txid: bitcoin::Txid::from_byte_array([0xab; 32]),
++                vout: 7,
++            };
++            let flags = FlagsMismatch {
++                expected: 0x01,
++                actual: 0x02,
++            };
++            let lock_time = lock_time_error();
++            let examples = [
++                (
++                    SortError::MissingInputSortKey(outpoint).to_string(),
++                    format!("input {}:7 missing sort key", "ab".repeat(32)),
++                ),
++                (
++                    SortError::MissingOutputSortKey.to_string(),
++                    "output missing sort key".to_owned(),
++                ),
++                (
++                    SortError::DuplicateSortKey(vec![0x00, 0x0f, 0xff]).to_string(),
++                    "duplicate sort key: 000fff".to_owned(),
++                ),
++                (
++                    SortError::MissingSortSeed.to_string(),
++                    "PSBT_GLOBAL_SORT_SEED not set".to_owned(),
++                ),
++                (
++                    SortError::from(lock_time.clone()).to_string(),
++                    lock_time.to_string(),
++                ),
++                (
++                    flags.to_string(),
++                    "tx_modifiable_flags mismatch: expected 0x01, got 0x02".to_owned(),
++                ),
++                (
++                    SorterError::from(flags).to_string(),
++                    "tx_modifiable_flags mismatch: expected 0x01, got 0x02".to_owned(),
++                ),
++                (
++                    SortModeError::MissingSortSeed.to_string(),
++                    "PSBT_GLOBAL_SORT_SEED not set".to_owned(),
++                ),
++                (
++                    SorterError::from(SortModeError::UnexpectedSortSeed).to_string(),
++                    "PSBT_GLOBAL_SORT_SEED is set in explicit-only sort mode".to_owned(),
++                ),
++                (
++                    SortModeError::UnexpectedSortKey.to_string(),
++                    "a sort key is set in derived-only sort mode".to_owned(),
++                ),
++            ];
++            for (shown, expected) in examples {
++                assert_eq!(shown, expected);
++            }
++        }
++
++        #[test]
++        fn a_derivation_mismatch_names_both_values() {
++            use SortKeyDerivation::{Derived, Explicit};
++
++            let examples = [
++                (
++                    None,
++                    Some(Derived),
++                    "PSBT_GLOBAL_SORT_KEY_DERIVATION is unset, expected 0x01",
++                ),
++                (
++                    Some(Explicit),
++                    None,
++                    "PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x00, expected unset",
++                ),
++                (
++                    Some(Derived),
++                    Some(Explicit),
++                    "PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x01, expected 0x00",
++                ),
++            ];
++            for (actual, expected, message) in examples {
++                let error = SortModeError::SortKeyDerivation { expected, actual };
++                assert_eq!(error.to_string(), message);
++                assert_eq!(SorterError::from(error).to_string(), message);
++            }
++        }
++    }
++
++    #[cfg(feature = "prop-tests")]
 +    mod prop {
 +        use super::*;
++        use bitcoin::hex::DisplayHex;
 +        use proptest::prelude::*;
 +
-+        fn derivation() -> impl Strategy<Value = SortKeyDerivation> {
-+            prop_oneof![
++        fn derivation() -> impl Strategy<Value = Option<SortKeyDerivation>> {
++            proptest::option::of(prop_oneof![
 +                Just(SortKeyDerivation::Explicit),
 +                Just(SortKeyDerivation::Derived)
++            ])
++        }
++
++        fn sort_mode_errors() -> impl Strategy<Value = SortModeError> {
++            prop_oneof![
++                (derivation(), derivation()).prop_map(|(expected, actual)| {
++                    SortModeError::SortKeyDerivation { expected, actual }
++                }),
++                Just(SortModeError::MissingSortSeed),
++                Just(SortModeError::UnexpectedSortSeed),
++                Just(SortModeError::UnexpectedSortKey),
 +            ]
 +        }
 +
 +        proptest! {
 +            #[test]
-+            fn error_displays_cover_every_variant(
++            fn sort_errors_name_the_offending_input_or_key(
 +                txid_byte in any::<u8>(),
 +                vout in any::<u32>(),
-+                duplicate_key in proptest::collection::vec(any::<u8>(), 0..=8),
-+                expected in 0u8..4,
-+                actual in 0u8..4,
++                key in proptest::collection::vec(any::<u8>(), 0..=8),
 +            ) {
-+                let outpoint = bitcoin::OutPoint { txid: bitcoin::Txid::from_byte_array([txid_byte; 32]), vout };
-+                prop_assert!(SortError::MissingInputSortKey(outpoint).to_string().contains("missing sort key"));
-+                prop_assert_eq!(SortError::MissingOutputSortKey.to_string(), "output missing sort key");
-+                prop_assert!(SortError::DuplicateSortKey(duplicate_key).to_string().starts_with("duplicate sort key: "));
-+                prop_assert!(SortError::MissingSortSeed.to_string().contains("SORT_SEED"));
-+                let inputs = crate::test_support::conflicting_lock_time_inputs().map(Into::into);
-+                let lock_time = psbt_v2::v2::Psbt {
-+                    global: crate::global::Global::default().into_v2(inputs.len(), 0),
-+                    inputs: inputs.to_vec(),
-+                    outputs: vec![],
-+                }
-+                .determine_lock_time()
-+                .unwrap_err();
-+                prop_assert!(SortError::from(lock_time).to_string().contains("lock time"));
++                let outpoint = bitcoin::OutPoint {
++                    txid: bitcoin::Txid::from_byte_array([txid_byte; 32]),
++                    vout,
++                };
++                let txid = format!("{txid_byte:02x}").repeat(32);
 +                prop_assert_eq!(
-+                    FlagsMismatch { expected, actual }.to_string(),
-+                    format!("tx_modifiable_flags mismatch: expected 0x0{expected}, got 0x0{actual}")
++                    SortError::MissingInputSortKey(outpoint).to_string(),
++                    format!("input {txid}:{vout} missing sort key")
++                );
++                let hex = key.to_lower_hex_string();
++                prop_assert_eq!(
++                    SortError::DuplicateSortKey(key).to_string(),
++                    format!("duplicate sort key: {hex}")
 +                );
 +            }
 +
 +            #[test]
-+            fn sort_mode_error_displays_cover_every_variant(
-+                expected in proptest::option::of(derivation()),
-+                actual in proptest::option::of(derivation()),
-+                flags_expected in 0u8..4,
-+                flags_actual in 0u8..4,
++            fn sorter_error_displays_the_error_it_wraps(
++                expected in any::<u8>(),
++                actual in any::<u8>(),
++                error in sort_mode_errors(),
 +            ) {
-+                let error = SortModeError::SortKeyDerivation { expected, actual };
-+                let shown = error.to_string();
-+                for value in [actual, expected] {
-+                    let expected = match value {
-+                        None => "unset",
-+                        Some(SortKeyDerivation::Explicit) => "0x00",
-+                        Some(SortKeyDerivation::Derived) => "0x01",
-+                    };
-+                    prop_assert!(shown.contains(expected));
-+                }
-+                prop_assert_eq!(SorterError::from(error).to_string(), shown);
-+                let mismatch = FlagsMismatch { expected: flags_expected, actual: flags_actual };
++                let mismatch = FlagsMismatch { expected, actual };
 +                prop_assert_eq!(SorterError::from(mismatch).to_string(), mismatch.to_string());
-+                prop_assert!(SortModeError::MissingSortSeed.to_string().contains("not set"));
-+                prop_assert!(SortModeError::UnexpectedSortSeed.to_string().contains("explicit"));
-+                prop_assert!(SortModeError::UnexpectedSortKey.to_string().contains("derived-only"));
++                prop_assert_eq!(SorterError::from(error.clone()).to_string(), error.to_string());
 +            }
 +        }
 +    }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +#[cfg(test)]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {
-+    use super::key::{derive_sort_key, write_input_sort_identifier};
 +    use super::*;
 +    use crate::global::Global;
 +    use crate::input::{Input, InputSet, SortKey};
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        Output::try_from(output.clone()).expect("sorting keeps the unique IDs")
 +    }
 +
-+    /// Read back the global map of an ordered PSBT.
-+    fn read_global(psbt: &Psbt) -> Global {
-+        Global::try_from(psbt.global.clone()).expect("sorting keeps the sort fields")
-+    }
-+
 +    /// `psbt` with `PSBT_GLOBAL_SORT_KEY_DERIVATION` set to `derivation`.
 +    fn with_derivation(mut psbt: UnorderedPsbt, derivation: SortKeyDerivation) -> UnorderedPsbt {
 +        psbt.global.set_sort_key_derivation(derivation);
 +        psbt
 +    }
 +
++    /// The error of a [`Mixed`] sorter for `flags` under modifiability `M`.
++    fn flags_error<M: Modifiability>(flags: u8) -> Option<SorterError> {
++        let mut psbt = empty_psbt();
++        psbt.global.tx_modifiable_flags = flags;
++        Sorter::<M, Mixed>::try_from_unordered_psbt(psbt).err()
++    }
++
 +    fn empty_psbt() -> UnorderedPsbt {
 +        UnorderedPsbt {
 +            global: Global::default(),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +    #[cfg(feature = "unit-tests")]
 +    mod unit {
 +        use super::*;
-+        use bitcoin::hashes::HashEngine;
++        use psbt_v2::v2::Updater;
 +
-+        /// Every combination of flags and sort fields, against every
-+        /// modifiability and sort mode: flags are checked first, then the sort
-+        /// fields in the order `check_sort_mode` documents, and each error
-+        /// renders to its own message.
++        /// Each row is the PSBT's flags and, for `Unmodifiable`,
++        /// `InputsModifiable`, `OutputsModifiable` and `BothModifiable`, the
++        /// flags that sorter expects, or `None` if it admits the PSBT.
 +        #[test]
-+        fn try_from_unordered_psbt_checks_flags_then_sort_mode() {
-+            fn expected<M: Modifiability, S: SortMode>(
-+                flags: u8,
-+                derivation: Option<SortKeyDerivation>,
-+                seeded: bool,
-+                sort_keyed: bool,
-+            ) -> Option<SorterError> {
-+                if flags != M::EXPECTED_FLAGS {
-+                    let expected = M::EXPECTED_FLAGS;
-+                    return Some(
-+                        FlagsMismatch {
-+                            expected,
-+                            actual: flags,
-+                        }
-+                        .into(),
-+                    );
-+                }
-+                let error = if derivation != S::SORT_KEY_DERIVATION {
-+                    let expected = S::SORT_KEY_DERIVATION;
-+                    SortModeError::SortKeyDerivation {
-+                        expected,
-+                        actual: derivation,
-+                    }
-+                } else if S::SEEDED && !seeded {
-+                    SortModeError::MissingSortSeed
-+                } else if derivation == Some(SortKeyDerivation::Explicit) && seeded {
-+                    SortModeError::UnexpectedSortSeed
-+                } else if derivation == Some(SortKeyDerivation::Derived) && sort_keyed {
-+                    SortModeError::UnexpectedSortKey
-+                } else {
-+                    return None;
++        fn only_the_matching_flags_are_admitted() {
++            let rows = [
++                (0x00, [None, Some(0x01), Some(0x02), Some(0x03)]),
++                (0x01, [Some(0x00), None, Some(0x02), Some(0x03)]),
++                (0x02, [Some(0x00), Some(0x01), None, Some(0x03)]),
++                (0x03, [Some(0x00), Some(0x01), Some(0x02), None]),
++            ];
++            for (actual, expected) in rows {
++                let mismatch = |expected: Option<u8>| {
++                    expected.map(|expected| SorterError::from(FlagsMismatch { expected, actual }))
 +                };
-+                Some(error.into())
-+            }
-+
-+            fn check<M: Modifiability, S: SortMode>(
-+                psbt: &UnorderedPsbt,
-+                fields: (u8, Option<SortKeyDerivation>, bool, bool),
-+                messages: &mut std::collections::HashMap<String, SorterError>,
-+            ) {
-+                let (flags, derivation, seeded, sort_keyed) = fields;
-+                let actual = Sorter::<M, S>::try_from_unordered_psbt(psbt.clone()).err();
++                assert_eq!(flags_error::<Unmodifiable>(actual), mismatch(expected[0]));
 +                assert_eq!(
-+                    actual,
-+                    expected::<M, S>(flags, derivation, seeded, sort_keyed),
-+                    "{fields:?}"
++                    flags_error::<InputsModifiable>(actual),
++                    mismatch(expected[1])
 +                );
-+                if let Some(error) = actual {
-+                    let previous = messages.insert(error.to_string(), error.clone());
-+                    assert!(previous.is_none_or(|previous| previous == error), "{error}");
-+                }
++                assert_eq!(
++                    flags_error::<OutputsModifiable>(actual),
++                    mismatch(expected[2])
++                );
++                assert_eq!(flags_error::<BothModifiable>(actual), mismatch(expected[3]));
 +            }
++        }
 +
-+            fn check_modes<M: Modifiability>(
-+                psbt: &UnorderedPsbt,
-+                fields: (u8, Option<SortKeyDerivation>, bool, bool),
-+                messages: &mut std::collections::HashMap<String, SorterError>,
-+            ) {
-+                check::<M, Mixed>(psbt, fields, messages);
-+                check::<M, Seeded<Mixed>>(psbt, fields, messages);
-+                check::<M, DerivedOnly>(psbt, fields, messages);
-+                check::<M, Seeded<DerivedOnly>>(psbt, fields, messages);
-+                check::<M, ExplicitOnly>(psbt, fields, messages);
-+            }
++        /// Which entry of a PSBT in [`the_sort_fields_select_the_sort_mode`]
++        /// has a sort key.
++        #[derive(Debug, Clone, Copy)]
++        enum SortKeyOn {
++            Neither,
++            Input,
++            Output,
++        }
++
++        /// What a sort mode does with a PSBT.
++        #[derive(Clone, Copy)]
++        enum Outcome {
++            Admits,
++            MissingSeed,
++            SeedForbidden,
++            KeyForbidden,
++            /// The sort key derivation does not match the one in here.
++            Wants(Option<SortKeyDerivation>),
++        }
 +
-+            let mut messages = std::collections::HashMap::new();
-+            let derivations = [
-+                None,
-+                Some(SortKeyDerivation::Explicit),
-+                Some(SortKeyDerivation::Derived),
++        /// Each row is a PSBT's sort key derivation, whether it has a seed and
++        /// which entry has a sort key, then what `Mixed`, `Seeded<Mixed>`,
++        /// `DerivedOnly`, `Seeded<DerivedOnly>` and `ExplicitOnly` do with it.
++        #[test]
++        fn the_sort_fields_select_the_sort_mode() {
++            use Outcome::{Admits, KeyForbidden, MissingSeed, SeedForbidden, Wants};
++            use SortKeyOn as K;
++            const U: Option<SortKeyDerivation> = None;
++            const D: Option<SortKeyDerivation> = Some(SortKeyDerivation::Derived);
++            const E: Option<SortKeyDerivation> = Some(SortKeyDerivation::Explicit);
++
++            #[rustfmt::skip]
++            let rows = [
++                (U, false, K::Neither, [Admits, MissingSeed, Wants(D), Wants(D), Wants(E)]),
++                (U, false, K::Input,   [Admits, MissingSeed, Wants(D), Wants(D), Wants(E)]),
++                (U, true,  K::Neither, [Admits, Admits, Wants(D), Wants(D), Wants(E)]),
++                (U, true,  K::Output,  [Admits, Admits, Wants(D), Wants(D), Wants(E)]),
++                (D, false, K::Neither, [Wants(U), Wants(U), Admits, MissingSeed, Wants(E)]),
++                (D, true,  K::Neither, [Wants(U), Wants(U), Admits, Admits, Wants(E)]),
++                (D, true,  K::Input,   [Wants(U), Wants(U), KeyForbidden, KeyForbidden, Wants(E)]),
++                (D, true,  K::Output,  [Wants(U), Wants(U), KeyForbidden, KeyForbidden, Wants(E)]),
++                (E, false, K::Neither, [Wants(U), Wants(U), Wants(D), Wants(D), Admits]),
++                (E, false, K::Input,   [Wants(U), Wants(U), Wants(D), Wants(D), Admits]),
++                (E, false, K::Output,  [Wants(U), Wants(U), Wants(D), Wants(D), Admits]),
++                (E, true,  K::Input,   [Wants(U), Wants(U), Wants(D), Wants(D), SeedForbidden]),
 +            ];
-+            for flags in 0u8..4 {
-+                for derivation in derivations {
-+                    for seeded in [false, true] {
-+                        for sort_keyed in [false, true] {
-+                            let mut psbt = empty_psbt();
-+                            psbt.global.tx_modifiable_flags = flags;
-+                            if let Some(derivation) = derivation {
-+                                psbt.global.set_sort_key_derivation(derivation);
-+                            }
-+                            if seeded {
-+                                psbt.global.set_sort_seed(sort_seed(vec![0; 16]));
-+                            }
-+                            let mut input = make_input(1, 0);
-+                            if sort_keyed {
-+                                input.set_sort_key(sort_key(vec![1]));
-+                            }
-+                            psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
-+                            let fields = (flags, derivation, seeded, sort_keyed);
-+                            check_modes::<Unmodifiable>(&psbt, fields, &mut messages);
-+                            check_modes::<BothModifiable>(&psbt, fields, &mut messages);
-+                            check_modes::<InputsModifiable>(&psbt, fields, &mut messages);
-+                            check_modes::<OutputsModifiable>(&psbt, fields, &mut messages);
-+                        }
-+                    }
++            for (derivation, seeded, sort_key_on, outcomes) in rows {
++                let mut psbt = empty_psbt();
++                if let Some(derivation) = derivation {
++                    psbt.global.set_sort_key_derivation(derivation);
++                }
++                if seeded {
++                    psbt.global.set_sort_seed(sort_seed(vec![0; 16]));
 +                }
++                let mut input = make_input(1, 0);
++                let mut output = make_output_with_uid(&[1]);
++                match sort_key_on {
++                    K::Neither => {}
++                    K::Input => input.set_sort_key(sort_key(vec![1])),
++                    K::Output => output.set_sort_key(sort_key(vec![1])),
++                }
++                psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
++                psbt.outputs = OutputSet::try_from_outputs([output]).unwrap();
++
++                let errors = [
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt.clone()).err(),
++                    Sorter::<Unmodifiable, Seeded<Mixed>>::try_from_unordered_psbt(psbt.clone())
++                        .err(),
++                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(psbt.clone())
++                        .err(),
++                    Sorter::<Unmodifiable, Seeded<DerivedOnly>>::try_from_unordered_psbt(
++                        psbt.clone(),
++                    )
++                    .err(),
++                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(psbt).err(),
++                ];
++                let expected = outcomes.map(|outcome| {
++                    let error = match outcome {
++                        Admits => return None,
++                        MissingSeed => SortModeError::MissingSortSeed,
++                        SeedForbidden => SortModeError::UnexpectedSortSeed,
++                        KeyForbidden => SortModeError::UnexpectedSortKey,
++                        Wants(expected) => SortModeError::SortKeyDerivation {
++                            expected,
++                            actual: derivation,
++                        },
++                    };
++                    Some(SorterError::from(error))
++                });
++                assert_eq!(
++                    errors, expected,
++                    "{derivation:?}, seeded: {seeded}, {sort_key_on:?}"
++                );
 +            }
 +        }
 +
 +        #[test]
-+        fn deterministic_no_seed_err() {
-+            let psbt = empty_psbt();
-+            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
-+            assert!(sorter.try_into_ordered_psbt().is_err());
++        fn invalid_flags_are_reported_before_an_invalid_sort_mode() {
++            let mut psbt = with_derivation(empty_psbt(), SortKeyDerivation::Explicit);
++            psbt.global.tx_modifiable_flags = 0x01;
++            assert_eq!(
++                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).err(),
++                Some(SorterError::Flags(FlagsMismatch {
++                    expected: 0x00,
++                    actual: 0x01
++                }))
++            );
 +        }
 +
++        /// The orders are those of `SHA-256(tag || tag || seed || identifier)`
++        /// for `tag = SHA-256("concurrent-psbt/deterministic-ordering")`,
++        /// computed outside this crate.
 +        #[test]
-+        fn deterministic_sorts_inputs() {
++        fn derived_order_follows_the_tagged_hash_of_seed_and_identifier() {
 +            let mut psbt = empty_psbt();
-+            psbt.global.set_sort_seed(sort_seed(vec![42u8; 32]));
++            psbt.global.set_sort_seed(sort_seed(vec![42; 32]));
 +            psbt.inputs =
-+                InputSet::try_from_inputs([make_input(2, 0), make_input(1, 0), make_input(3, 0)])
-+                    .unwrap();
-+            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
-+            let ordered = sorter.try_into_ordered_psbt().unwrap();
-+            assert_eq!(ordered.inputs.len(), 3);
-+            // Verify deterministic: same seed, same order
-+            let mut psbt2 = empty_psbt();
-+            psbt2.global.set_sort_seed(sort_seed(vec![42u8; 32]));
-+            psbt2.inputs =
-+                InputSet::try_from_inputs([make_input(3, 0), make_input(1, 0), make_input(2, 0)])
-+                    .unwrap();
-+            let sorter2: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt2, PhantomData);
-+            let ordered2 = sorter2.try_into_ordered_psbt().unwrap();
-+            for (a, b) in ordered.inputs.iter().zip(ordered2.inputs.iter()) {
-+                assert_eq!(a.previous_txid, b.previous_txid);
-+            }
-+        }
-+
-+        #[test]
-+        fn deterministic_sorts_outputs_by_key_derived_from_unique_id() {
-+            let seed = vec![42; 32];
-+            let mut psbt = empty_psbt();
-+            psbt.global.set_sort_seed(sort_seed(seed.clone()));
++                InputSet::try_from_inputs((1..=5).map(|txid| make_input(txid, 0))).unwrap();
 +            psbt.outputs =
-+                OutputSet::try_from_outputs((0..8).map(|uid| make_output_with_uid(&[uid])))
++                OutputSet::try_from_outputs((0..=4).map(|uid| make_output_with_uid(&[uid])))
 +                    .unwrap();
 +
-+            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
-+            let keys: Vec<_> = sorter
-+                .try_into_ordered_psbt()
-+                .unwrap()
++            let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(
++                with_derivation(psbt, SortKeyDerivation::Derived),
++            )
++            .unwrap()
++            .try_into_ordered_psbt()
++            .unwrap();
++
++            let txids: Vec<_> = ordered
++                .inputs
++                .iter()
++                .map(|input| input.previous_txid)
++                .collect();
++            let expected_txids = [1, 5, 3, 4, 2].map(|txid| make_input(txid, 0).previous_txid);
++            assert_eq!(txids, expected_txids);
++            let uids: Vec<_> = ordered
 +                .outputs
 +                .iter()
-+                .map(|output| {
-+                    derive_sort_key(&seed, |engine| {
-+                        engine.input(read_output(output).unique_id().as_bytes())
-+                    })
-+                })
++                .map(|output| read_output(output).unique_id().as_bytes().to_vec())
 +                .collect();
-+            assert!(keys.is_sorted());
-+        }
-+
-+        #[test]
-+        fn explicit_sorts_by_key() {
-+            let mut psbt = empty_psbt();
-+            let mut i1 = make_input(1, 0);
-+            i1.set_sort_key(sort_key(vec![0x02]));
-+            let mut i2 = make_input(2, 0);
-+            i2.set_sort_key(sort_key(vec![0x01]));
-+            psbt.inputs = InputSet::try_from_inputs([i1, i2]).unwrap();
-+            let sorter: Sorter<Unmodifiable, ExplicitOnly> = Sorter(psbt, PhantomData);
-+            let ordered = sorter.try_into_ordered_psbt().unwrap();
-+            // i2 (key 0x01) should come before i1 (key 0x02)
-+            assert_eq!(
-+                ordered.inputs[0].previous_txid,
-+                make_input(2, 0).previous_txid
-+            );
-+            assert_eq!(
-+                ordered.inputs[1].previous_txid,
-+                make_input(1, 0).previous_txid
-+            );
++            assert_eq!(uids, [0, 1, 4, 2, 3].map(|uid| vec![uid]));
 +        }
 +
++        /// Without explicit keys the derived order of these inputs is 1, 3, 2
++        /// and of these outputs 1, 2.
 +        #[test]
-+        fn mixed_uses_explicit_keys_and_derives_missing_keys() {
-+            let seed = vec![7u8; 32];
++        fn mixed_orders_explicit_keys_among_derived_ones() {
 +            let mut psbt = empty_psbt();
-+            psbt.global.set_sort_seed(sort_seed(seed.clone()));
-+
-+            let mut explicit_high = make_input(1, 0);
-+            explicit_high.set_sort_key(sort_key(vec![0xff]));
-+            let missing = make_input(2, 0);
-+            let mut explicit_low = make_input(3, 0);
-+            explicit_low.set_sort_key(sort_key(vec![0x00]));
-+
-+            let mut expected_inputs = vec![
-+                (
-+                    explicit_high.sort_key().unwrap().to_vec(),
-+                    explicit_high.previous_txid,
-+                ),
-+                (
-+                    derive_sort_key(&seed, |engine| {
-+                        write_input_sort_identifier(&missing, engine)
-+                    })
-+                    .to_vec(),
-+                    missing.previous_txid,
-+                ),
-+                (
-+                    explicit_low.sort_key().unwrap().to_vec(),
-+                    explicit_low.previous_txid,
-+                ),
-+            ];
-+            expected_inputs.sort_by_key(|(key, _)| key.clone());
-+
-+            psbt.inputs =
-+                InputSet::try_from_inputs([explicit_high, missing, explicit_low]).unwrap();
-+
-+            let mut explicit_output = make_output_with_uid(&[0x01]);
-+            explicit_output.set_sort_key(sort_key(vec![0xfe]));
-+            let missing_output = make_output_with_uid(&[0x02]);
-+            let mut expected_outputs = vec![
-+                (explicit_output.sort_key().unwrap().to_vec(), 0usize),
-+                (
-+                    derive_sort_key(&seed, |engine| engine.input(&[0x02])).to_vec(),
-+                    1usize,
-+                ),
-+            ];
-+            expected_outputs.sort_by_key(|(key, _)| key.clone());
-+
-+            psbt.outputs = OutputSet::try_from_outputs([explicit_output, missing_output]).unwrap();
-+
-+            let sorter: Sorter<Unmodifiable, Mixed> =
-+                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).unwrap();
-+            let ordered = sorter.try_into_ordered_psbt().unwrap();
++            psbt.global.set_sort_seed(sort_seed(vec![42; 32]));
++            let [mut high, derived, mut low] = [1, 2, 3].map(|txid| make_input(txid, 0));
++            high.set_sort_key(sort_key(vec![0xff]));
++            low.set_sort_key(sort_key(vec![0x00]));
++            psbt.inputs = InputSet::try_from_inputs([high, derived, low]).unwrap();
++            let mut explicit = make_output_with_uid(&[1]);
++            explicit.set_sort_key(sort_key(vec![0xfe]));
++            psbt.outputs =
++                OutputSet::try_from_outputs([explicit, make_output_with_uid(&[2])]).unwrap();
 +
-+            let ordered_inputs: Vec<_> = ordered.inputs.iter().map(|i| i.previous_txid).collect();
-+            let expected_inputs: Vec<_> =
-+                expected_inputs.into_iter().map(|(_, txid)| txid).collect();
-+            assert_eq!(ordered_inputs, expected_inputs);
++            let ordered = Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt)
++                .unwrap()
++                .try_into_ordered_psbt()
++                .unwrap();
 +
-+            let ordered_output_indexes: Vec<_> = ordered
-+                .outputs
++            let txids: Vec<_> = ordered
++                .inputs
 +                .iter()
-+                .map(|output| {
-+                    if read_output(output).sort_key() == Some([0xfe].as_slice()) {
-+                        0
-+                    } else {
-+                        1
-+                    }
-+                })
++                .map(|input| input.previous_txid)
 +                .collect();
-+            let expected_output_indexes: Vec<_> = expected_outputs
-+                .into_iter()
-+                .map(|(_, index)| index)
++            assert_eq!(
++                txids,
++                [3, 2, 1].map(|txid| make_input(txid, 0).previous_txid)
++            );
++            let uids: Vec<_> = ordered
++                .outputs
++                .iter()
++                .map(|output| read_output(output).unique_id().as_bytes().to_vec())
 +                .collect();
-+            assert_eq!(ordered_output_indexes, expected_output_indexes);
++            assert_eq!(uids, [vec![2], vec![1]]);
 +        }
 +
 +        #[test]
-+        fn mixed_missing_output_sort_key_without_seed_errs() {
-+            let mut psbt = empty_psbt();
-+            psbt.outputs = OutputSet::try_from_outputs([make_output_with_uid(&[1])]).unwrap();
-+            let sorter: Sorter<Unmodifiable, Mixed> =
-+                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).unwrap();
++        fn deriving_keys_requires_a_seed() {
++            let missing_seed = |psbt: UnorderedPsbt| {
++                Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt)
++                    .unwrap()
++                    .try_into_ordered_psbt()
++            };
++
++            let mut input = empty_psbt();
++            input.inputs = InputSet::try_from_inputs([make_input(1, 0)]).unwrap();
 +            assert!(matches!(
-+                sorter.try_into_ordered_psbt(),
++                missing_seed(input),
 +                Err(SortError::MissingSortSeed)
 +            ));
-+        }
-+
-+        #[test]
-+        fn clears_unordered_flag() {
-+            let mut psbt = empty_psbt();
-+            psbt.global.set_unordered();
-+            psbt.global.set_sort_seed(sort_seed(vec![0u8; 32]));
-+            assert!(psbt.global.is_unordered());
-+            let sorter: Sorter<Unmodifiable, DerivedOnly> = Sorter(psbt, PhantomData);
-+            let ordered = sorter.try_into_ordered_psbt().unwrap();
-+            assert!(!read_global(&ordered).is_unordered());
-+        }
-+
-+        #[test]
… (truncated)

@github-actions

Copy link
Copy Markdown
range-diff for force push f932026e22 → bae975ef12 November 14, 2026 12:39 UTC: 1 modified; 1 commit; same base 6a0b965918

reproduce: git range-diff 6a0b965..f932026 6a0b965..bae975e

1:  f932026e22 +1782 -1 13f ! 1:  bae975ef12 +1783 -1 13f introduce Sorter role
1: f932026e22 ! 1: bae975ef12 introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                (U, true,  K::Neither, [Admits, Admits, Wants(D), Wants(D), Wants(E)]),
 +                (U, true,  K::Output,  [Admits, Admits, Wants(D), Wants(D), Wants(E)]),
 +                (D, false, K::Neither, [Wants(U), Wants(U), Admits, MissingSeed, Wants(E)]),
++                (D, false, K::Input,   [Wants(U), Wants(U), KeyForbidden, MissingSeed, Wants(E)]),
 +                (D, true,  K::Neither, [Wants(U), Wants(U), Admits, Admits, Wants(E)]),
 +                (D, true,  K::Input,   [Wants(U), Wants(U), KeyForbidden, KeyForbidden, Wants(E)]),
 +                (D, true,  K::Output,  [Wants(U), Wants(U), KeyForbidden, KeyForbidden, Wants(E)]),

@github-actions

Copy link
Copy Markdown
range-diff for force push e6f5579a09 → 8c67fbd6b1 November 15, 2026 00:53 UTC: 1 modified; 1 commit; same base d28748fca8

reproduce: git range-diff d28748f..e6f5579 d28748f..8c67fbd

1:  e6f5579a09 +1783 -1 13f ! 1:  8c67fbd6b1 +1884 -1 13f introduce Sorter role
1: e6f5579a09 ! 1: 8c67fbd6b1 introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 @@
 +use psbt_v2::v2::DetermineLockTimeError;
 +
-+use crate::global::SortKeyDerivation;
++use crate::global::{SortKeyDerivation, SortSeed};
++use crate::lattice::partial::Conflict;
 +
 +/// Error type for sort operations.
 +#[derive(Debug)]
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +    }
 +}
 +
++/// `PSBT_GLOBAL_SORT_SEED` is already a different seed. A seed is joined
++/// rather than replaced, so that setting one is monotone, and two different
++/// seeds do not join.
++#[derive(Debug, Clone, PartialEq, Eq)]
++pub struct SeedConflict {
++    /// The seed the PSBT has.
++    pub existing: SortSeed,
++    /// The seed that was to be set.
++    pub requested: SortSeed,
++}
++
++impl SeedConflict {
++    /// Read the seeds off the conflict of joining `requested` into
++    /// `existing`, which holds the two in that order.
++    pub(crate) fn from_conflict(conflict: Conflict<SortSeed>) -> Self {
++        let mut seeds = conflict.into_iter();
++        let mut next = || seeds.next().expect("joining two seeds conflicts on both");
++        let existing = next();
++        Self {
++            existing,
++            requested: next(),
++        }
++    }
++}
++
++impl std::fmt::Display for SeedConflict {
++    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
++        write!(
++            f,
++            "PSBT_GLOBAL_SORT_SEED is already set to a different seed"
++        )
++    }
++}
++
++impl std::error::Error for SeedConflict {}
++
 +#[cfg(test)]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {
@@ crates/concurrent-psbt/src/roles/sorter/error.rs (new)
 +                    SortModeError::UnexpectedSortKey.to_string(),
 +                    "a sort key is set in derived-only sort mode".to_owned(),
 +                ),
++                (
++                    SeedConflict {
++                        existing: SortSeed::try_from(vec![1; 16]).unwrap(),
++                        requested: SortSeed::try_from(vec![2; 16]).unwrap(),
++                    }
++                    .to_string(),
++                    "PSBT_GLOBAL_SORT_SEED is already set to a different seed".to_owned(),
++                ),
 +            ];
 +            for (shown, expected) in examples {
 +                assert_eq!(shown, expected);
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +
 +use psbt_v2::v2::Psbt;
 +
-+use crate::global::{SortKeyDerivation, SortSeed};
++use crate::global::{Global, SortKeyDerivation, SortSeed};
++use crate::lattice::partial::PartialJoin;
 +use crate::tx::UnorderedPsbt;
 +
 +mod error;
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +mod modifiability;
 +mod order;
 +
-+pub use error::{FlagsMismatch, SortError, SortModeError, SorterError};
++pub use error::{FlagsMismatch, SeedConflict, SortError, SortModeError, SorterError};
 +pub use key::{SortKeyHash, SortKeyTag};
 +use key::{
 +    derived_input_sort_key, derived_output_sort_key, explicit_input_sort_key,
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +};
 +use order::ordered_psbt;
 +
++/// Join `seed` into `PSBT_GLOBAL_SORT_SEED`: set it if unset, and keep it if
++/// it is already `seed`.
++///
++/// # Errors
++/// Returns [`SeedConflict`] if the PSBT has a different seed.
++pub(crate) fn join_seed(global: &mut Global, seed: SortSeed) -> Result<(), SeedConflict> {
++    let seed = match global.sort_seed.clone() {
++        Some(existing) => existing
++            .try_join(seed)
++            .map_err(SeedConflict::from_conflict)?,
++        None => seed,
++    };
++    global.set_sort_seed(seed);
++    Ok(())
++}
++
 +/// Hand an ordered PSBT to the role that follows sorting under `M`.
 +fn hand_off<M: Modifiability>(psbt: Psbt) -> Result<M::Sorted, M::Error> {
 +    <M as modifiability::sealed::Modifiability>::sorted(psbt)
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +        self.0
 +    }
 +
-+    fn with_seed<T>(mut self, seed: SortSeed) -> Sorter<M, Seeded<T>> {
-+        self.0.global.set_sort_seed(seed);
-+        Sorter::from_unordered(self.0)
++    fn try_with_seed<T>(mut self, seed: SortSeed) -> Result<Sorter<M, Seeded<T>>, SeedConflict> {
++        join_seed(&mut self.0.global, seed)?;
++        Ok(Sorter::from_unordered(self.0))
 +    }
 +}
 +
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +}
 +
 +impl<M: Modifiability> Sorter<M, Mixed> {
-+    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
-+    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<Mixed>> {
-+        self.with_seed(seed)
++    /// Join `seed` into `PSBT_GLOBAL_SORT_SEED`: set it if unset, and keep it
++    /// if it is already `seed`.
++    ///
++    /// # Errors
++    /// Returns [`SeedConflict`] if the PSBT has a different seed, which
++    /// replacing would not be monotone.
++    pub fn try_set_seed(self, seed: SortSeed) -> Result<Sorter<M, Seeded<Mixed>>, SeedConflict> {
++        self.try_with_seed(seed)
 +    }
 +
 +    /// Apply mixed-mode ordering.
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +}
 +
 +impl<M: Modifiability> Sorter<M, DerivedOnly> {
-+    /// Set `PSBT_GLOBAL_SORT_SEED`, replacing any existing seed.
-+    pub fn set_seed(self, seed: SortSeed) -> Sorter<M, Seeded<DerivedOnly>> {
-+        self.with_seed(seed)
++    /// Join `seed` into `PSBT_GLOBAL_SORT_SEED`: set it if unset, and keep it
++    /// if it is already `seed`.
++    ///
++    /// # Errors
++    /// Returns [`SeedConflict`] if the PSBT has a different seed, which
++    /// replacing would not be monotone.
++    pub fn try_set_seed(
++        self,
++        seed: SortSeed,
++    ) -> Result<Sorter<M, Seeded<DerivedOnly>>, SeedConflict> {
++        self.try_with_seed(seed)
 +    }
 +
 +    /// Apply deterministic ordering if the PSBT carries a sort seed.
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                check(
 +                    conflicting,
 +                    mixed(psbt(false, true))
-+                        .set_seed(sort_seed(vec![9; 16]))
++                        .try_set_seed(sort_seed(vec![9; 16]))
++                        .unwrap()
 +                        .try_sort(),
 +                    mixed(psbt(true, true)).try_into_ordered_psbt().unwrap(),
 +                );
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                check(
 +                    conflicting,
 +                    derived(psbt(false, false))
-+                        .set_seed(sort_seed(vec![9; 16]))
++                        .try_set_seed(sort_seed(vec![9; 16]))
++                        .unwrap()
 +                        .try_sort(),
 +                    derived(psbt(true, false)).try_into_ordered_psbt().unwrap(),
 +                );
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +            /// Setting the seed, whether or not the PSBT had another one,
 +            /// orders like a PSBT that carries the seed.
 +            #[test]
-+            fn set_seed_matches_a_preset_seed(
++            fn try_set_seed_joins_a_preset_seed(
 +                seed in seeds(),
-+                old_seed in proptest::option::of(seeds()),
++                other in seeds(),
++                preset in 0u8..3, // unset, the same seed, or another seed
 +            ) {
++                let old_seed = match preset {
++                    0 => None,
++                    1 => Some(&seed),
++                    _ => Some(&other),
++                };
 +                let psbt = |seed: Option<&Vec<u8>>| {
 +                    let mut psbt = empty_psbt();
 +                    if let Some(seed) = seed {
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs (new)
 +                    .unwrap()
 +                };
 +
-+                prop_assert_eq!(
-+                    mixed(old_seed.as_ref()).set_seed(sort_seed(seed.clone())).try_into_ordered_psbt().unwrap(),
-+                    mixed(Some(&seed)).try_into_ordered_psbt().unwrap()
-+                );
-+                prop_assert_eq!(
-+                    mixed(old_seed.as_ref()).set_seed(sort_seed(seed.clone())).try_sort().unwrap().psbt(),
-+                    mixed(Some(&seed)).try_into_ordered_psbt().unwrap()
-+                );
-+                prop_assert_eq!(
-+                    derived(old_seed.as_ref()).set_seed(sort_seed(seed.clone())).into_ordered_psbt(),
-+                    derived(Some(&seed)).try_into_ordered_psbt().unwrap()
-+                );
++                match old_seed.filter(|old| **old != seed) {
++                    None => {
++                        prop_assert_eq!(
++                            mixed(old_seed).try_set_seed(sort_seed(seed.clone())).unwrap().try_into_ordered_psbt().unwrap(),
++                            mixed(Some(&seed)).try_into_ordered_psbt().unwrap()
++                        );
++                        prop_assert_eq!(
++                            mixed(old_seed).try_set_seed(sort_seed(seed.clone())).unwrap().try_sort().unwrap().psbt(),
++                            mixed(Some(&seed)).try_into_ordered_psbt().unwrap()
++                        );
++                        prop_assert_eq!(
++                            derived(old_seed).try_set_seed(sort_seed(seed.clone())).unwrap().into_ordered_psbt(),
++                            derived(Some(&seed)).try_into_ordered_psbt().unwrap()
++                        );
++                    }
++                    Some(old) => {
++                        let conflict = SeedConflict {
++                            existing: sort_seed(old.clone()),
++                            requested: sort_seed(seed.clone()),
++                        };
++                        prop_assert_eq!(
++                            mixed(old_seed).try_set_seed(sort_seed(seed.clone())).err(),
++                            Some(conflict.clone())
++                        );
++                        prop_assert_eq!(
++                            derived(old_seed).try_set_seed(sort_seed(seed.clone())).err(),
++                            Some(conflict)
++                        );
++                    }
++                }
 +            }
 +
 +            /// `try_sort` hands the ordered PSBT, with its flags, to the role

@github-actions

Copy link
Copy Markdown
range-diff for force push 8c67fbd6b1 → 3aa1adfcdf November 15, 2026 02:13 UTC: 1 unchanged; 1 commit; base d28748fca8 → a69dec9481 (diverged, 11 ahead and 11 behind)

reproduce: git range-diff d28748f..8c67fbd a69dec9..3aa1adf

1:  8c67fbd6b1 +1884 -1 13f = 1:  3aa1adfcdf +1884 -1 13f introduce Sorter role

@github-actions

Copy link
Copy Markdown
range-diff for force push 8c67fbd6b1 → 3aa1adfcdf November 15, 2026 02:13 UTC: 1 unchanged; 1 commit; base d28748fca8 → a69dec9481 (diverged, 11 ahead and 11 behind)

reproduce: git range-diff d28748f..8c67fbd a69dec9..3aa1adf

1:  8c67fbd6b1 +1884 -1 13f = 1:  3aa1adfcdf +1884 -1 13f introduce Sorter role

@github-actions

Copy link
Copy Markdown
range-diff for force push 3aa1adfcdf → 87fe755391 November 15, 2026 12:51 UTC: 1 modified; 1 commit; same base a69dec9481

reproduce: git range-diff a69dec9..3aa1adf a69dec9..87fe755

1:  3aa1adfcdf +1884 -1 13f ! 1:  87fe755391 +1885 -1 13f introduce Sorter role
1: 3aa1adfcdf ! 1: 87fe755391 introduce Sorter role
@@ crates/concurrent-psbt/src/roles/sorter/order.rs (new)
 +///
 +/// Each cycle of the permutation is followed once with swaps. Visited
 +/// positions are marked by overwriting their index with the position itself,
-+/// so `order` no longer describes the permutation afterwards.
++/// so `order` no longer describes the permutation afterwards. A cycle has at
++/// most `order.len()` positions, which bounds the walk.
 +fn apply_permutation<T, K>(items: &mut [T], order: &mut [(K, usize)]) {
 +    for start in 0..order.len() {
 +        let mut position = start;
-+        loop {
++        for _ in 0..order.len() {
 +            let source = std::mem::replace(&mut order[position].1, position);
 +            if source == start {
 +                break;

@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

enforce-concurrent-p... 5f4ab3b sorter 7093124 +/-
100% 100% 0%
View coverage of the 10 most impacted files.
File enforce-concurrent-p... 5f4ab3b sorter 7093124 +/-
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.../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%
crates/concurre...c/psbt/input.rs 0% 100% +100%

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


Updated November 16, 2026 20:01 UTC

@github-actions

Copy link
Copy Markdown
range-diff for force push 87fe755391 → 4731f8255c November 15, 2026 23:52 UTC: 1 unchanged; 1 commit; base a69dec9481 → 496f7b9cd8 (diverged, 11 ahead and 11 behind)

reproduce: git range-diff a69dec9..87fe755 496f7b9..4731f82

1:  87fe755391 +1885 -1 13f = 1:  4731f8255c +1885 -1 13f introduce Sorter role

@github-actions

Copy link
Copy Markdown
range-diff for force push 87fe755391 → 4731f8255c November 15, 2026 23:52 UTC: 1 unchanged; 1 commit; base a69dec9481 → 496f7b9cd8 (diverged, 11 ahead and 11 behind)

reproduce: git range-diff a69dec9..87fe755 496f7b9..4731f82

1:  87fe755391 +1885 -1 13f = 1:  4731f8255c +1885 -1 13f introduce Sorter role

@github-actions

Copy link
Copy Markdown
range-diff for force push 4731f8255c → 77c85c7473 November 16, 2026 00:16 UTC: 1 unchanged; 1 commit; base 496f7b9cd8 → f1e8135717 (diverged, 8 ahead and 8 behind)

reproduce: git range-diff 496f7b9..4731f82 f1e8135..77c85c7

1:  4731f8255c +1885 -1 13f = 1:  77c85c7473 +1885 -1 13f introduce Sorter role

@github-actions

Copy link
Copy Markdown
range-diff for force push 4731f8255c → 77c85c7473 November 16, 2026 00:16 UTC: 1 unchanged; 1 commit; base 496f7b9cd8 → f1e8135717 (diverged, 8 ahead and 8 behind)

reproduce: git range-diff 496f7b9..4731f82 f1e8135..77c85c7

1:  4731f8255c +1885 -1 13f = 1:  77c85c7473 +1885 -1 13f introduce Sorter role

@github-actions

Copy link
Copy Markdown
range-diff for force push 77c85c7473 → 1437300440 November 16, 2026 03:24 UTC: 1 modified; 1 commit; base f1e8135717 → 3898b66476 (diverged, 11 ahead and 11 behind)

reproduce: git range-diff f1e8135..77c85c7 3898b66..1437300

1:  77c85c7473 +1885 -1 13f ! 1:  1437300440 +1885 -1 13f introduce Sorter role
1: 77c85c7473 ! 1: 1437300440 introduce Sorter role
@@ crates/concurrent-psbt/src/psbt/output_set.rs: impl OutputSet {
 +    }
 +
      pub fn wrap(self) -> ResultOutputSet {
-         ResultOutputSet(self.0.wrap(Output::wrap))
+         ResultOutputSet(self.0.wrap())
      }
 
  ## crates/concurrent-psbt/src/roles/mod.rs (new) ##

@github-actions

Copy link
Copy Markdown
range-diff for force push 1437300440 → b116e2b0d0 November 16, 2026 04:43 UTC: 1 unchanged; 1 commit; base 3898b66476 → 42aa094bc9 (diverged, 11 ahead and 11 behind)

reproduce: git range-diff 3898b66..1437300 42aa094..b116e2b

1:  1437300440 +1885 -1 13f = 1:  b116e2b0d0 +1885 -1 13f introduce Sorter role

@github-actions

Copy link
Copy Markdown
range-diff for force push b116e2b0d0 → edd21a260c November 16, 2026 06:07 UTC: 1 unchanged; 1 commit; base 42aa094bc9 → 6f5ebba138 (diverged, 11 ahead and 11 behind)

reproduce: git range-diff 42aa094..b116e2b 6f5ebba..edd21a2

1:  b116e2b0d0 +1885 -1 13f = 1:  edd21a260c +1885 -1 13f introduce Sorter role

This uses a typestate based approach, like the upstream psbt-v2
Constructor role, in order to implement the different sorting modes.
@github-actions

Copy link
Copy Markdown
range-diff for force push edd21a260c → 709312404d November 16, 2026 18:19 UTC: 1 unchanged; 1 commit; base 6f5ebba138 → 925002f20c (diverged, 7 ahead and 7 behind)

reproduce: git range-diff 6f5ebba..edd21a2 925002f..7093124

1:  edd21a260c +1885 -1 13f = 1:  709312404d +1885 -1 13f introduce Sorter role

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