Skip to content

sort by explicit key, then by a key derived from the tx UUID - #120

Draft
yuval-block wants to merge 5 commits into
creatorfrom
sort-uuid
Draft

yuval-block wants to merge 5 commits into
creatorfrom
sort-uuid

Conversation

@yuval-block

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

Copy link
Copy Markdown
Collaborator

Implements the sort-rule reframe from fungi-protocol/docs#78: a required transaction UUID seeds the derived sort keys, so explicit keys no longer need to be unique.

Split into five commits for review. Each one passes the checks on its own:

  1. rename sort modes for the explicit keys they allow: a mechanical rename, with no behaviour change. DerivedOnly → ExplicitKeysForbidden, ExplicitOnly → ExplicitKeysRequired, SortKeyDerivation::Derived → ExplicitKeysForbidden, SortKeyDerivation::Explicit → ExplicitKeysRequired, and the Creator methods explicit_keys_forbidden / explicit_keys_required.
  2. add PSBT_GLOBAL_TX_UUID, set by the Creator: proprietary subtype 0x13, idempotent on join. The Creator sets a fresh random 16-byte UUID. Sorting does not read it yet.
  3. derive sort keys from the tx UUID in every mode: the core change.
    • Every mode orders by explicit sort key (a missing key counts as empty), then by derived key. With BIP-340 style tagged hashes under concurrent-psbt/:
      • h = UuidHash(uuid), and e = AuxSortSeedHash(PSBT_GLOBAL_SORT_SEED), over the empty string if the seed is unset;
      • sort seed = SortSeedHash(h || e);
      • derived key = SortKeyHash(sort seed || outpoint or unique ID).
    • Sorting fails with SortError::MissingUuid if the UUID is unset or empty.
    • The sort seed becomes auxiliary: any length, allowed in every mode. try_set_seed and set_seed keep the mode.
    • Seeded now tracks the UUID for all three modes:
      • the Creator produces Seeded modes;
      • a parsed PSBT enters an unseeded mode, and try_set_uuid on the Constructor or Sorter refines it (UuidError on an empty or different UUID);
      • parsing into a Seeded mode rejects a missing or empty UUID (SortModeError::MissingUuid);
      • Seeded<Mixed> and Seeded<ExplicitKeysForbidden> sort infallibly.
  4. allow repeated explicit sort keys: removes the duplicate-key check, DuplicateSortKey, and the linear scan on every join.
  5. require non-empty explicit sort keys under derivation 0x00: adds EmptyInputSortKey / EmptyOutputSortKey. Derivation 0x01 still forbids explicit keys.

The spec table in docs#78 still describes the old rules.

🤖 Generated with Claude Code

@github-actions

Copy link
Copy Markdown
range-diff for force push 1b475f7b35 → 9f4dce9c75 November 15, 2026 03:33 UTC: 1 modified; 1 commit; same base 3d413230fb

reproduce: git range-diff 3d41323..1b475f7 3d41323..9f4dce9

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

1:  1b475f7b35  +831 -1018 9f ! 1:  9f4dce9c75 +1205 -1045 9f sort by explicit key, then by a key derived from the tx UUID
1: 1b475f7b35 ! 1: 9f4dce9c75 sort by explicit key, then by a key derived from the tx UUID
@@ Commit message
     fresh random 16-byte UUID on every PSBT, and sorting fails with
     SortError::MissingUuid if the UUID is unset or empty.
 
+    The Seeded typestate now tracks the UUID instead of the sort seed, and
+    refines all three modes:
+    - The Creator produces Seeded modes. A parsed PSBT enters an unseeded
+      mode, and try_set_uuid on the Constructor or Sorter joins a non-empty
+      UUID and refines it; an empty or different UUID is a UuidError.
+    - try_from_psbt and try_from_unordered_psbt into a Seeded mode reject a
+      missing or empty UUID with SortModeError::MissingUuid.
+    - Seeded Mixed and DerivedOnly sort infallibly (into_ordered_psbt), and
+      Seeded ExplicitOnly fails only on a missing explicit key. Only the
+      unseeded modes can fail with SortError::MissingUuid.
+
     Every sort mode orders inputs and outputs by explicit sort key, a
     missing key counting as empty, and then by derived key. With BIP-340
     style tagged hashes under concurrent-psbt/:
     - h = UuidHash(uuid) and e = AuxSortSeedHash(PSBT_GLOBAL_SORT_SEED),
-      each over the empty string if the field is unset;
+      the latter over the empty string if the seed is unset;
     - the sort seed is SortSeedHash(h || e);
     - the derived key is SortKeyHash(sort seed || outpoint or unique ID).
     Derived keys of distinct entries differ, so explicit keys may repeat:
@@ Commit message
       marked as a conflict, as a key under 0x01 already is, and reported as
       EmptyInputSortKey or EmptyOutputSortKey.
 
-    The Seeded typestate is removed: try_set_seed and set_seed keep the
-    mode, and every Sorter sorts through one try_into_ordered_psbt.
+    try_set_seed and set_seed keep the mode, since the auxiliary seed adds
+    no guarantee.
 
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 
@@ crates/concurrent-psbt/src/roles/constructor/error.rs: impl From<UnorderedPsbtEr
      }
 
  ## crates/concurrent-psbt/src/roles/constructor/mod.rs ##
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: use crate::input::{Input, InputSet};
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: use std::marker::PhantomData;
+ use bitcoin::{Amount, ScriptBuf};
+ use psbt_v2::v2::{DetermineLockTimeError, Psbt};
+ 
+-use crate::global::SortSeed;
++use crate::global::{SortSeed, TxUuid};
+ use crate::input::{Input, InputSet};
  use crate::lattice::join::Join;
  use crate::output::{Output, OutputSet, UniqueId};
  use crate::sorter::{
 -    BothModifiable, DerivedOnly, InputsModifiable, Mixed, Modifiable, OutputsModifiable,
 -    SeedConflict, Seeded, SortMode, Sorter, Unmodifiable, check_flags, check_sort_mode, join_seed,
-+    BothModifiable, InputsModifiable, Modifiable, OutputsModifiable, SeedConflict, SortMode,
-+    Sorter, Unmodifiable, check_flags, check_sort_mode, join_seed,
++    BothModifiable, InputsModifiable, Modifiable, OutputsModifiable, SeedConflict, Seeded,
++    SortMode, Sorter, Unmodifiable, UuidError, check_flags, check_sort_mode, join_seed, join_uuid,
  };
  use crate::tx::UnorderedPsbt;
  
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod result;
 -/// [`Seeded`] by `set_seed`. Parsed PSBTs
 -/// enter as [`Mixed`].
 +/// `S` is the sort mode chosen when the constructor is created, or the one
-+/// that a parsed PSBT's sort fields select.
++/// that a parsed PSBT's sort fields select. A [`Creator`](crate::roles::creator::Creator)
++/// always produces a [`Seeded`] mode; a parsed PSBT is refined to one by
++/// [`try_set_uuid`](Self::try_set_uuid).
  #[derive(Debug)]
  pub struct Constructor<M, S>(pub(crate) UnorderedPsbt, pub(crate) PhantomData<(M, S)>);
  
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M, S> Constructor<M, S
 -        seed: SortSeed,
 -    ) -> Result<Constructor<M, Seeded<Mixed>>, SeedConflict> {
 -        self.try_with_seed(seed)
--    }
--}
--
++    pub fn try_set_seed(mut self, seed: SortSeed) -> Result<Self, SeedConflict> {
++        join_seed(&mut self.0.global, seed)?;
++        Ok(self)
+     }
+ }
+ 
 -impl<M> Constructor<M, DerivedOnly> {
 -    /// Join `seed` into `PSBT_GLOBAL_SORT_SEED`: set it if unset, and keep it
 -    /// if it is already `seed`.
--    ///
--    /// # Errors
++impl<M, S> Constructor<M, S>
++where
++    Seeded<S>: SortMode,
++{
++    /// Join `uuid` into `PSBT_GLOBAL_TX_UUID`, setting it if unset, and
++    /// refine the mode to [`Seeded`].
+     ///
+     /// # Errors
 -    /// Returns [`SeedConflict`] if the PSBT has a different seed, which
--    /// replacing would not be monotone.
++    /// Returns [`UuidError::Empty`] if `uuid` is empty, or
++    /// [`UuidError::Conflict`] if the PSBT has a different UUID, which
+     /// replacing would not be monotone.
 -    pub fn try_set_seed(
 -        self,
 -        seed: SortSeed,
 -    ) -> Result<Constructor<M, Seeded<DerivedOnly>>, SeedConflict> {
 -        self.try_with_seed(seed)
-+    pub fn try_set_seed(mut self, seed: SortSeed) -> Result<Self, SeedConflict> {
-+        join_seed(&mut self.0.global, seed)?;
-+        Ok(self)
++    pub fn try_set_uuid(mut self, uuid: TxUuid) -> Result<Constructor<M, Seeded<S>>, UuidError> {
++        join_uuid(&mut self.0.global, uuid)?;
++        Ok(Constructor::from_unordered(self.0))
      }
  }
  
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 -                let sort_seed = |seed: &[u8]| SortSeed::try_from(seed.to_vec()).unwrap();
 -                let joined = if mode < 2 {
 -                    Constructor::<BothModifiable, Mixed>::try_from_psbt(psbt_with_mode(0x03, mode))
--                        .unwrap()
--                        .try_set_seed(sort_seed(&seed))
--                        .map(|constructor| constructor.0)
--                } else {
--                    Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(psbt_with_mode(0x03, mode))
 +                let sort_seed = |seed: &[u8]| SortSeed::from(seed.to_vec());
 +                fn joined<S: SortMode>(mode: usize, seed: SortSeed) -> Result<UnorderedPsbt, SeedConflict> {
 +                    Constructor::<BothModifiable, S>::try_from_psbt(psbt_with_mode(0x03, mode))
                          .unwrap()
 -                        .try_set_seed(sort_seed(&seed))
 -                        .map(|constructor| constructor.0)
+-                } else {
+-                    Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(psbt_with_mode(0x03, mode))
+-                        .unwrap()
+-                        .try_set_seed(sort_seed(&seed))
+-                        .map(|constructor| constructor.0)
 +                        .try_set_seed(seed)
 +                        .map(Constructor::into_inner)
 +                }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
                  };
                  match preset.filter(|preset| *preset != seed) {
                      None => prop_assert_eq!(
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
+                 }
+             }
+ 
++            /// Setting a non-empty UUID, whether or not the PSBT had the same
++            /// one, refines the mode to [`Seeded`]. An empty UUID, or a
++            /// different preset one, is rejected.
++            #[test]
++            fn try_set_uuid_joins_the_uuid_of_the_psbt(
++                uuid in prop_oneof![Just(vec![9; 16]), proptest::collection::vec(any::<u8>(), 0..=32)],
++                preset in any::<bool>(), // unset, or [9; 16]
++                mode in 0usize..6,
++            ) {
++                fn joined<S: SortMode>(mode: usize, preset: bool, uuid: &[u8]) -> Result<UnorderedPsbt, UuidError>
++                where
++                    Seeded<S>: SortMode,
++                {
++                    let mut global = global_with_mode(0x03, mode);
++                    if !preset {
++                        global.uuid = None;
++                    }
++                    let seeded: Constructor<BothModifiable, Seeded<S>> =
++                        Constructor::<BothModifiable, S>::try_from_psbt(empty_psbt(global))
++                            .unwrap()
++                            .try_set_uuid(TxUuid::from(uuid.to_vec()))?;
++                    Ok(seeded.into_inner())
++                }
++                let joined = match mode {
++                    0 | 1 => joined::<Mixed>(mode, preset, &uuid),
++                    2 | 3 => joined::<DerivedOnly>(mode, preset, &uuid),
++                    _ => joined::<ExplicitOnly>(mode, preset, &uuid),
++                };
++                let preset = preset.then(|| vec![9; 16]);
++                let expected = match preset.filter(|preset| *preset != uuid) {
++                    _ if uuid.is_empty() => Err(UuidError::Empty),
++                    None => Ok(Some(uuid)),
++                    Some(preset) => Err(UuidError::Conflict {
++                        existing: TxUuid::from(preset),
++                        requested: TxUuid::from(uuid),
++                    }),
++                };
++                prop_assert_eq!(
++                    joined.map(|psbt| psbt.global.uuid().map(<[u8]>::to_vec)),
++                    expected
++                );
++            }
++
+             #[test]
+             fn adding_inputs_and_outputs_keeps_one_of_each_identity(
+                 input_tags in proptest::collection::vec(0u8..4, 0..8),
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
              #[test]
              fn unwraps_only_the_selected_typestate(
                  flags in 0u8..=0x03,
 -                mode in 0usize..5,
 +                mode in 0usize..6,
++                uuid in 0u8..3, // unset, empty, or [9; 16]
              ) {
 -                use crate::sorter::ExplicitOnly;
 -
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
                  }
  
 -                // A seeded PSBT also selects the unseeded mode it refines.
-+                // A seed does not change the mode.
-                 fn modes<M: Modifiable>(psbt: &Psbt, mode: usize) -> Result<(), TestCaseError> {
+-                fn modes<M: Modifiable>(psbt: &Psbt, mode: usize) -> Result<(), TestCaseError> {
++                // A seed does not change the mode, and only a seeded mode
++                // needs a non-empty UUID.
++                fn modes<M: Modifiable>(psbt: &Psbt, mode: usize, uuid: bool) -> Result<(), TestCaseError> {
                      let flags = psbt.global.tx_modifiable_flags == M::EXPECTED_FLAGS;
 -                    check::<M, Mixed>(psbt.clone(), flags && mode <= 1)?;
 -                    check::<M, Seeded<Mixed>>(psbt.clone(), flags && mode == 1)?;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 -                    check::<M, ExplicitOnly>(psbt.clone(), flags && mode == 4)
 +                    check::<M, Mixed>(psbt.clone(), flags && mode / 2 == 0)?;
 +                    check::<M, DerivedOnly>(psbt.clone(), flags && mode / 2 == 1)?;
-+                    check::<M, ExplicitOnly>(psbt.clone(), flags && mode / 2 == 2)
++                    check::<M, ExplicitOnly>(psbt.clone(), flags && mode / 2 == 2)?;
++                    check::<M, Seeded<Mixed>>(psbt.clone(), flags && uuid && mode / 2 == 0)?;
++                    check::<M, Seeded<DerivedOnly>>(psbt.clone(), flags && uuid && mode / 2 == 1)?;
++                    check::<M, Seeded<ExplicitOnly>>(psbt.clone(), flags && uuid && mode / 2 == 2)
                  }
  
-                 let psbt = psbt_with_mode(flags, mode);
+-                let psbt = psbt_with_mode(flags, mode);
+-                modes::<BothModifiable>(&psbt, mode)?;
+-                modes::<InputsModifiable>(&psbt, mode)?;
+-                modes::<OutputsModifiable>(&psbt, mode)?;
++                let mut global = global_with_mode(flags, mode);
++                match uuid {
++                    0 => global.uuid = None,
++                    1 => global.uuid = Some(TxUuid::from(vec![])),
++                    _ => {}
++                }
++                let psbt = empty_psbt(global);
++                modes::<BothModifiable>(&psbt, mode, uuid == 2)?;
++                modes::<InputsModifiable>(&psbt, mode, uuid == 2)?;
++                modes::<OutputsModifiable>(&psbt, mode, uuid == 2)?;
+             }
+         }
+     }
 
  ## crates/concurrent-psbt/src/roles/creator.rs ##
 @@ crates/concurrent-psbt/src/roles/creator.rs: use bitcoin::locktime::absolute;
@@ crates/concurrent-psbt/src/roles/creator.rs: use bitcoin::locktime::absolute;
 +use crate::global::{Global, SortKeyDerivation, SortSeed, TxUuid};
  use crate::input::InputSet;
  use crate::output::OutputSet;
--use crate::sorter::{BothModifiable, DerivedOnly, ExplicitOnly, Mixed, Seeded};
-+use crate::sorter::{BothModifiable, DerivedOnly, ExplicitOnly, Mixed};
- use crate::tx::UnorderedPsbt;
- 
- use super::constructor::Constructor;
+ use crate::sorter::{BothModifiable, DerivedOnly, ExplicitOnly, Mixed, Seeded};
 @@ crates/concurrent-psbt/src/roles/creator.rs: use super::constructor::Constructor;
  /// Entry point for creating new unordered PSBTs: BIP 370's [`v2::Creator`]
  /// with a sort mode.
@@ crates/concurrent-psbt/src/roles/creator.rs: use super::constructor::Constructor
 -/// The PSBT is marked unordered (`PSBT_GLOBAL_TX_UNORDERED`). Unlike
 +/// The PSBT is marked unordered (`PSBT_GLOBAL_TX_UNORDERED`) and gets a fresh
 +/// random `PSBT_GLOBAL_TX_UUID`, from which the
-+/// [`Sorter`](crate::sorter::Sorter) derives sort keys. Unlike
++/// [`Sorter`](crate::sorter::Sorter) derives sort keys, so its sort mode is
++/// always [`Seeded`]. Unlike
  /// [`v2::Creator`] there is no `sighash_single`, since an unordered PSBT
  /// cannot have the `SIGHASH_SINGLE` flag. The sort mode determines how the
 -/// [`Sorter`](crate::sorter::Sorter) orders it:
@@ crates/concurrent-psbt/src/roles/creator.rs: use super::constructor::Constructor
  ///
  /// [`constructor`](Self::constructor) produces a [`Constructor`] with both
  /// inputs and outputs modifiable. A PSBT cannot be a coinbase transaction,
-@@ crates/concurrent-psbt/src/roles/creator.rs: pub struct Creator<S = Mixed> {
+ /// so it always starts out needing inputs; a constructor that will add no
+ /// outputs comes from `constructor().no_more_outputs()`.
+ #[derive(Debug, Clone, PartialEq)]
+-pub struct Creator<S = Mixed> {
++pub struct Creator<S = Seeded<Mixed>> {
+     creator: v2::Creator,
      /// `PSBT_GLOBAL_SORT_KEY_DERIVATION`, if set.
      sort_key_derivation: Option<SortKeyDerivation>,
      seed: Option<SortSeed>,
@@ crates/concurrent-psbt/src/roles/creator.rs: pub struct Creator<S = Mixed> {
      _sort: PhantomData<S>,
  }
  
- impl Creator<Mixed> {
+-impl Creator<Mixed> {
++impl Creator<Seeded<Mixed>> {
      /// Create a [`Creator`] in [`Mixed`] mode, leaving
 -    /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` unset.
 +    /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` unset, with a fresh
@@ crates/concurrent-psbt/src/roles/creator.rs: pub struct Creator<S = Mixed> {
 -    }
 -
      /// Switch to [`DerivedOnly`] mode (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x01`).
-     pub fn derived_only(self) -> Creator<DerivedOnly> {
+-    pub fn derived_only(self) -> Creator<DerivedOnly> {
++    pub fn derived_only(self) -> Creator<Seeded<DerivedOnly>> {
          self.with_sort_key_derivation(SortKeyDerivation::Derived)
-@@ crates/concurrent-psbt/src/roles/creator.rs: impl Creator<Mixed> {
+     }
+ 
+     /// Switch to [`ExplicitOnly`] mode (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x00`).
+-    pub fn explicit_only(self) -> Creator<ExplicitOnly> {
++    pub fn explicit_only(self) -> Creator<Seeded<ExplicitOnly>> {
          self.with_sort_key_derivation(SortKeyDerivation::Explicit)
      }
  
@@ crates/concurrent-psbt/src/roles/creator.rs: impl<S> Creator<S> {
          if let Some(derivation) = self.sort_key_derivation {
              global.set_sort_key_derivation(derivation);
          }
+@@ crates/concurrent-psbt/src/roles/creator.rs: impl<S> Creator<S> {
+     }
+ }
+ 
+-impl Default for Creator<Mixed> {
++impl Default for Creator<Seeded<Mixed>> {
+     fn default() -> Self {
+         Creator::new()
+     }
 @@ crates/concurrent-psbt/src/roles/creator.rs: impl Default for Creator<Mixed> {
  mod tests {
      use super::*;
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
          #[test]
          fn each_sort_mode_sets_its_sort_fields() {
              let seed = vec![7; 16];
-+            let seeded = || SortSeed::from(seed.clone());
++            let aux = || SortSeed::from(seed.clone());
  
-             // The annotations check the typestate each method returns.
-             let mixed: Creator<Mixed> = Creator::default();
+-            // The annotations check the typestate each method returns.
+-            let mixed: Creator<Mixed> = Creator::default();
 -            let seeded_mixed: Creator<Seeded<Mixed>> =
 -                Creator::new().set_seed(sort_seed(seed.clone()));
-+            let seeded_mixed: Creator<Mixed> = Creator::new().set_seed(seeded());
-             let derived: Creator<DerivedOnly> = Creator::new().derived_only();
+-            let derived: Creator<DerivedOnly> = Creator::new().derived_only();
 -            let seeded_derived: Creator<Seeded<DerivedOnly>> = Creator::new()
 -                .derived_only()
 -                .set_seed(sort_seed(seed.clone()));
-+            let seeded_derived: Creator<DerivedOnly> =
-+                Creator::new().derived_only().set_seed(seeded());
-             let explicit: Creator<ExplicitOnly> = Creator::new().explicit_only();
-+            let seeded_explicit: Creator<ExplicitOnly> =
-+                Creator::new().set_seed(seeded()).explicit_only();
+-            let explicit: Creator<ExplicitOnly> = Creator::new().explicit_only();
++            // The annotations check the typestate each method returns: a
++            // created PSBT has a UUID, so every mode is seeded.
++            let mixed: Creator<Seeded<Mixed>> = Creator::default();
++            let aux_mixed: Creator<Seeded<Mixed>> = Creator::new().set_seed(aux());
++            let derived: Creator<Seeded<DerivedOnly>> = Creator::new().derived_only();
++            let aux_derived: Creator<Seeded<DerivedOnly>> =
++                Creator::new().derived_only().set_seed(aux());
++            let explicit: Creator<Seeded<ExplicitOnly>> = Creator::new().explicit_only();
++            let aux_explicit: Creator<Seeded<ExplicitOnly>> =
++                Creator::new().set_seed(aux()).explicit_only();
  
 +            let (derived_mode, explicit_mode) = (
 +                Some(SortKeyDerivation::Derived),
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
              // name, PSBT, expected sort key derivation, expected sort seed
              let cases = [
                  ("mixed", mixed.constructor().into_inner(), None, None),
-@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
-                     "seeded mixed",
-                     seeded_mixed.constructor().into_inner(),
+                 (
+-                    "seeded mixed",
+-                    seeded_mixed.constructor().into_inner(),
++                    "mixed with aux seed",
++                    aux_mixed.constructor().into_inner(),
                      None,
 -                    Some(seed.as_slice()),
 +                    seed,
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
                      None,
                  ),
                  (
-                     "seeded derived only",
-                     seeded_derived.constructor().into_inner(),
+-                    "seeded derived only",
+-                    seeded_derived.constructor().into_inner(),
 -                    Some(SortKeyDerivation::Derived),
 -                    Some(seed.as_slice()),
++                    "derived only with aux seed",
++                    aux_derived.constructor().into_inner(),
 +                    derived_mode,
 +                    seed,
                  ),
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
                      None,
                  ),
 +                (
-+                    "seeded explicit only",
-+                    seeded_explicit.constructor().into_inner(),
++                    "explicit only with aux seed",
++                    aux_explicit.constructor().into_inner(),
 +                    explicit_mode,
 +                    seed,
 +                ),
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
 -                .set_seed(sort_seed(seed.clone()))
 +            let creator = Creator::new().derived_only();
 +            let uuid = creator.uuid.clone();
-+            let sorter: crate::sorter::Sorter<_, DerivedOnly> = creator
++            let sorter: crate::sorter::Sorter<_, Seeded<DerivedOnly>> = creator
                  .constructor()
                  .input(input())
                  .unwrap()
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
                  .unwrap()
                  .no_more_inputs()
                  .no_more_outputs();
--            let ordered = sorter.into_ordered_psbt();
-+            let ordered = sorter
-+                .try_into_ordered_psbt()
-+                .expect("a created PSBT has a UUID, so it sorts without a seed");
++            // A created PSBT is seeded, so it sorts infallibly, without an
++            // aux seed.
+             let ordered = sorter.into_ordered_psbt();
  
              let global = Global::try_from(ordered.global.clone()).expect("well-formed sort fields");
-             assert!(!global.is_unordered());
 @@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
                  global.sort_key_derivation(),
                  Some(SortKeyDerivation::Derived)
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
      }
 
  ## crates/concurrent-psbt/src/roles/sorter/error.rs ##
-@@ crates/concurrent-psbt/src/roles/sorter/error.rs: use crate::lattice::partial::Conflict;
+@@
+ use psbt_v2::v2::DetermineLockTimeError;
+ 
+-use crate::global::{SortKeyDerivation, SortSeed};
++use crate::global::{SortKeyDerivation, SortSeed, TxUuid};
+ use crate::lattice::partial::Conflict;
+ 
  /// Error type for sort operations.
  #[derive(Debug)]
  pub enum SortError {
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: use crate::lattice::partial::C
 -    DuplicateSortKey(Vec<u8>),
 -    /// Sort seed is required but not set.
 -    MissingSortSeed,
-+    /// `PSBT_GLOBAL_TX_UUID` is unset or empty, so no sort key can be
-+    /// derived.
++    /// In an unseeded mode, `PSBT_GLOBAL_TX_UUID` is unset or empty, so no
++    /// sort key can be derived.
 +    MissingUuid,
      /// The inputs' lock time requirements conflict, so the ordered PSBT
      /// cannot be handed to the [`Updater`](psbt_v2::v2::Updater).
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: pub enum SortModeError {
 -    /// The mode is [`ExplicitOnly`](super::ExplicitOnly) but `PSBT_GLOBAL_SORT_SEED`
 -    /// is set.
 -    UnexpectedSortSeed,
++    /// The mode is [`Seeded`](super::Seeded) but `PSBT_GLOBAL_TX_UUID` is
++    /// unset or empty.
++    MissingUuid,
      /// The mode is [`DerivedOnly`](super::DerivedOnly) but an input or
      /// output has a sort key.
      UnexpectedSortKey,
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: impl std::fmt::Display for Sor
 -            Self::UnexpectedSortSeed => {
 -                write!(f, "PSBT_GLOBAL_SORT_SEED is set in explicit-only sort mode")
 -            }
++            Self::MissingUuid => write!(
++                f,
++                "PSBT_GLOBAL_TX_UUID unset or empty in a seeded sort mode"
++            ),
              Self::UnexpectedSortKey => write!(f, "a sort key is set in derived-only sort mode"),
          }
      }
+@@ crates/concurrent-psbt/src/roles/sorter/error.rs: impl std::fmt::Display for SeedConflict {
+ 
+ impl std::error::Error for SeedConflict {}
+ 
++/// Error when joining a UUID into `PSBT_GLOBAL_TX_UUID`.
++#[derive(Debug, Clone, PartialEq, Eq)]
++pub enum UuidError {
++    /// The UUID to be set is empty, so no sort key could be derived.
++    Empty,
++    /// `PSBT_GLOBAL_TX_UUID` is already a different UUID. A UUID is joined
++    /// rather than replaced, so that setting one is monotone, and two
++    /// different UUIDs do not join.
++    Conflict {
++        /// The UUID the PSBT has.
++        existing: TxUuid,
++        /// The UUID that was to be set.
++        requested: TxUuid,
++    },
++}
++
++impl UuidError {
++    /// Read the UUIDs off the conflict of joining `requested` into
++    /// `existing`, which holds the two in that order.
++    pub(crate) fn from_conflict(conflict: Conflict<TxUuid>) -> Self {
++        let mut uuids = conflict.into_iter();
++        let mut next = || uuids.next().expect("joining two UUIDs conflicts on both");
++        let existing = next();
++        Self::Conflict {
++            existing,
++            requested: next(),
++        }
++    }
++}
++
++impl std::fmt::Display for UuidError {
++    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
++        match self {
++            Self::Empty => write!(f, "PSBT_GLOBAL_TX_UUID cannot be empty"),
++            Self::Conflict { .. } => {
++                write!(f, "PSBT_GLOBAL_TX_UUID is already set to a different UUID")
++            }
++        }
++    }
++}
++
++impl std::error::Error for UuidError {}
++
+ #[cfg(test)]
+ #[cfg_attr(coverage_nightly, coverage(off))]
+ mod tests {
 @@ crates/concurrent-psbt/src/roles/sorter/error.rs: mod tests {
                      "output missing sort key".to_owned(),
                  ),
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: mod tests {
                  (
 -                    SortModeError::MissingSortSeed.to_string(),
 -                    "PSBT_GLOBAL_SORT_SEED not set".to_owned(),
--                ),
--                (
++                    SorterError::from(SortModeError::UnexpectedSortKey).to_string(),
++                    "a sort key is set in derived-only sort mode".to_owned(),
+                 ),
+                 (
 -                    SorterError::from(SortModeError::UnexpectedSortSeed).to_string(),
 -                    "PSBT_GLOBAL_SORT_SEED is set in explicit-only sort mode".to_owned(),
--                ),
--                (
++                    SorterError::from(SortModeError::MissingUuid).to_string(),
++                    "PSBT_GLOBAL_TX_UUID unset or empty in a seeded sort mode".to_owned(),
+                 ),
+                 (
 -                    SortModeError::UnexpectedSortKey.to_string(),
-+                    SorterError::from(SortModeError::UnexpectedSortKey).to_string(),
-                     "a sort key is set in derived-only sort mode".to_owned(),
+-                    "a sort key is set in derived-only sort mode".to_owned(),
++                    UuidError::Empty.to_string(),
++                    "PSBT_GLOBAL_TX_UUID cannot be empty".to_owned(),
++                ),
++                (
++                    UuidError::Conflict {
++                        existing: TxUuid::from(vec![1; 16]),
++                        requested: TxUuid::from(vec![2; 16]),
++                    }
++                    .to_string(),
++                    "PSBT_GLOBAL_TX_UUID is already set to a different UUID".to_owned(),
                  ),
                  (
                      SeedConflict {
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: mod tests {
                  }),
 -                Just(SortModeError::MissingSortSeed),
 -                Just(SortModeError::UnexpectedSortSeed),
++                Just(SortModeError::MissingUuid),
                  Just(SortModeError::UnexpectedSortKey),
              ]
          }
@@ crates/concurrent-psbt/src/roles/sorter/key.rs: use bitcoin::consensus::Encodabl
  }
 
  ## crates/concurrent-psbt/src/roles/sorter/mod.rs ##
-@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod modifiability;
+@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: use std::marker::PhantomData;
+ 
+ use psbt_v2::v2::Psbt;
+ 
+-use crate::global::{Global, SortKeyDerivation, SortSeed};
++use crate::global::{Global, SortKeyDerivation, SortSeed, TxUuid};
+ use crate::lattice::partial::PartialJoin;
+ use crate::tx::UnorderedPsbt;
+ 
+@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod key;
+ mod modifiability;
  mod order;
  
- pub use error::{FlagsMismatch, SeedConflict, 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,
 -    explicit_output_sort_key, mixed_input_sort_key, mixed_output_sort_key,
++pub use error::{FlagsMismatch, SeedConflict, SortError, SortModeError, SorterError, UuidError};
 +pub use key::{
 +    AuxSortSeedHash, AuxSortSeedTag, SortKeyHash, SortKeyTag, SortSeedHash, SortSeedTag, UuidHash,
 +    UuidTag,
  };
  pub(crate) use modifiability::check_flags;
  pub use modifiability::{
-@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: fn hand_off<M: Modifiability>(psbt: Psbt) -> Result<M::Sorted, M::Error> {
+@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) fn join_seed(global: &mut Global, seed: SortSeed) -> Result<(), SeedC
+     Ok(())
+ }
+ 
++/// Whether `PSBT_GLOBAL_TX_UUID` is set and non-empty, as a [`Seeded`] mode
++/// requires.
++fn has_uuid(global: &Global) -> bool {
++    global.uuid().is_some_and(|uuid| !uuid.is_empty())
++}
++
++/// Join `uuid` into `PSBT_GLOBAL_TX_UUID`: set it if unset, and keep it if it
++/// is already `uuid`.
++///
++/// # Errors
++/// Returns [`UuidError::Empty`] if `uuid` is empty, or
++/// [`UuidError::Conflict`] if the PSBT has a different UUID.
++pub(crate) fn join_uuid(global: &mut Global, uuid: TxUuid) -> Result<(), UuidError> {
++    if uuid.as_bytes().is_empty() {
++        return Err(UuidError::Empty);
++    }
++    let uuid = match global.uuid.clone() {
++        Some(existing) => existing.try_join(uuid).map_err(UuidError::from_conflict)?,
++        None => uuid,
++    };
++    global.set_uuid(uuid);
++    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: fn hand_off<M: Modifiability>(ps
  
 -/// 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);
--
- /// Typestate wrapper that applies a sort order to an [`UnorderedPsbt`].
- ///
- /// `M` is the PSBT's [`Modifiability`], which decides the role a sorted PSBT
++/// Sort mode refinement: [`Mixed`], [`DerivedOnly`] or [`ExplicitOnly`] with
++/// `PSBT_GLOBAL_TX_UUID` known to be set and non-empty, so sort keys can be
++/// derived.
++///
++/// The [`Creator`](crate::roles::creator::Creator) always sets a UUID and produces
++/// a seeded mode. A parsed PSBT may lack one: it enters an unseeded mode and
++/// is refined by `try_set_uuid`.
+ #[derive(Debug, Clone, PartialEq)]
+ pub struct Seeded<S>(PhantomData<S>, std::convert::Infallible);
+ 
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub struct Seeded<S>(PhantomData<S>, std::convert::Infallible);
- /// may still be added, the [`Updater`](psbt_v2::v2::Updater) once neither
  /// may.
  ///
--/// `S` is the sort mode: [`Mixed`], [`DerivedOnly`], or [`ExplicitOnly`], or
+ /// `S` is the sort mode: [`Mixed`], [`DerivedOnly`], or [`ExplicitOnly`], or
 -/// [`Seeded`] `Mixed` or `DerivedOnly` once the sort seed is known to be set.
-+/// `S` is the sort mode: [`Mixed`], [`DerivedOnly`], or [`ExplicitOnly`].
++/// one of them [`Seeded`] once `PSBT_GLOBAL_TX_UUID` is known to be set.
  ///
  /// # Ordering
  ///
 +/// Every mode sorts by explicit sort key, a missing key counting as empty,
 +/// and then by derived sort key. Each hash below is a BIP 340-style tagged
-+/// hash, and an unset field hashes as empty:
++/// hash:
 +///
-+/// - `h` = [`UuidHash`] of `PSBT_GLOBAL_TX_UUID`,
-+/// - `e` = [`AuxSortSeedHash`] of `PSBT_GLOBAL_SORT_SEED`,
++/// - `h` = [`UuidHash`] of `PSBT_GLOBAL_TX_UUID`, which must be set and
++///   non-empty,
++/// - `e` = [`AuxSortSeedHash`] of `PSBT_GLOBAL_SORT_SEED`, empty if unset,
 +/// - the sort seed = [`SortSeedHash`] of `h || e`,
 +/// - a derived sort key = [`SortKeyHash`] of the sort seed, then the input's
 +///   consensus-encoded outpoint or the output's unique ID.
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub struct Seeded<S>(PhantomData
… (truncated)

@github-actions

Copy link
Copy Markdown
range-diff for force push 9f4dce9c75 → 921b57a46a November 15, 2026 03:46 UTC: 1 modified; 1 commit; same base 3d413230fb

reproduce: git range-diff 3d41323..9f4dce9 3d41323..921b57a

1:  9f4dce9c75 +1205 -1045 9f ! 1:  921b57a46a +1273 -1094 9f sort by explicit key, then by a key derived from the tx UUID
1: 9f4dce9c75 ! 1: 921b57a46a sort by explicit key, then by a key derived from the tx UUID
@@ Commit message
       UUID and refines it; an empty or different UUID is a UuidError.
     - try_from_psbt and try_from_unordered_psbt into a Seeded mode reject a
       missing or empty UUID with SortModeError::MissingUuid.
-    - Seeded Mixed and DerivedOnly sort infallibly (into_ordered_psbt), and
-      Seeded ExplicitOnly fails only on a missing explicit key. Only the
-      unseeded modes can fail with SortError::MissingUuid.
+    - Seeded Mixed and ExplicitKeysForbidden sort infallibly
+      (into_ordered_psbt), and Seeded ExplicitKeysRequired fails only on a
+      missing explicit key. Only the unseeded modes can fail with
+      SortError::MissingUuid.
 
     Every sort mode orders inputs and outputs by explicit sort key, a
     missing key counting as empty, and then by derived key. With BIP-340
@@ Commit message
     try_set_seed and set_seed keep the mode, since the auxiliary seed adds
     no guarantee.
 
+    Derived keys break ties in every mode, so the modes are renamed for the
+    explicit keys they allow: DerivedOnly becomes ExplicitKeysForbidden and
+    ExplicitOnly becomes ExplicitKeysRequired, with the Creator methods
+    explicit_keys_forbidden and explicit_keys_required.
+
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 +                    ]))),
                  ),
 -                // Seeded derivation accepts entries without explicit keys.
-+                // Derived-only accepts entries without explicit keys.
++                // Derivation 0x01 accepts entries without explicit keys.
                  (
                      v2_psbt_with(
                          global(Some(Derived), true),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                      Ok(()),
                  ),
 -                // An input and an output may share a sort key.
-+                // Explicit-only accepts a seed, missing keys, which may be
++                // Derivation 0x00 accepts a seed, missing keys, which may be
 +                // added later, and keys that repeat.
                  (
                      v2_psbt_with(
@@ crates/concurrent-psbt/src/roles/constructor/error.rs: impl From<UnorderedPsbtEr
              | UnorderedPsbtError::InvalidOutputUniqueId(_)) => Self::Unordered(error),
          }
      }
+@@ crates/concurrent-psbt/src/roles/constructor/error.rs: mod tests {
+                 ),
+                 (
+                     ConstructorError::SortMode(SortModeError::UnexpectedSortKey),
+-                    "a sort key is set in derived-only sort mode",
++                    "a sort key is set in a sort mode that forbids explicit keys",
+                 ),
+             ];
+             for (error, message) in cases {
 
  ## crates/concurrent-psbt/src/roles/constructor/mod.rs ##
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: use std::marker::PhantomData;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod result;
  pub use result::ResultConstructor;
  
 +#[cfg(doc)]
-+use crate::sorter::{DerivedOnly, ExplicitOnly};
++use crate::sorter::{ExplicitKeysForbidden, ExplicitKeysRequired};
 +
  /// Typed wrapper that tracks modifiability `M` and sort state `S`.
  ///
- /// The type parameters enforce the BIP 370 constructor state machine at compile time:
- /// `M` is one of `BothModifiable`, `InputsModifiable`, or `OutputsModifiable`.
+-/// The type parameters enforce the BIP 370 constructor state machine at compile time:
+-/// `M` is one of `BothModifiable`, `InputsModifiable`, or `OutputsModifiable`.
 -/// `S` is the sort mode chosen when the constructor is created, refined to
 -/// [`Seeded`] by `set_seed`. Parsed PSBTs
 -/// enter as [`Mixed`].
-+/// `S` is the sort mode chosen when the constructor is created, or the one
-+/// that a parsed PSBT's sort fields select. A [`Creator`](crate::roles::creator::Creator)
-+/// always produces a [`Seeded`] mode; a parsed PSBT is refined to one by
++/// The type parameters enforce the BIP 370 constructor state machine at compile
++/// time: `M` is one of `BothModifiable`, `InputsModifiable`, or
++/// `OutputsModifiable`. `S` is the sort mode chosen when the constructor is
++/// created, or the one that a parsed PSBT's sort fields select. A
++/// [`Creator`](crate::roles::creator::Creator) always produces a [`Seeded`]
++/// mode; a parsed PSBT is refined to one by
 +/// [`try_set_uuid`](Self::try_set_uuid).
  #[derive(Debug)]
  pub struct Constructor<M, S>(pub(crate) UnorderedPsbt, pub(crate) PhantomData<(M, S)>);
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<S: SortMode> Construct
      /// Returns [`ConstructorError::Conflict`] if the two disagree, or if the
 -    /// input has a sort key in [`DerivedOnly`] mode, which makes the key a
 -    /// conflict.
-+    /// input has a sort key in [`DerivedOnly`] mode or an empty one in
-+    /// [`ExplicitOnly`] mode, which makes the key a conflict.
++    /// input has a sort key in [`ExplicitKeysForbidden`] mode or an empty one
++    /// in [`ExplicitKeysRequired`] mode, which makes the key a conflict.
      pub fn input(self, input: Input) -> Result<Self, ConstructorError> {
          self.add_input(input)
      }
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<S: SortMode> Constructor<BothModifiable, S> {
+     ///
      /// # Errors
      /// Returns [`ConstructorError::Conflict`] if it disagrees with the output
-     /// already holding that ID, or if it has a sort key in [`DerivedOnly`]
+-    /// already holding that ID, or if it has a sort key in [`DerivedOnly`]
 -    /// mode, which makes the key a conflict.
-+    /// mode or an empty one in [`ExplicitOnly`] mode, which makes the key a
-+    /// conflict.
++    /// already holding that ID, or if it has a sort key in
++    /// [`ExplicitKeysForbidden`] mode or an empty one in
++    /// [`ExplicitKeysRequired`] mode, which makes the key a conflict.
      pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
          self.add_output(output)
      }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<S: SortMode> Construct
      /// Returns [`ConstructorError::Conflict`] if the two disagree, or if the
 -    /// input has a sort key in [`DerivedOnly`] mode, which makes the key a
 -    /// conflict.
-+    /// input has a sort key in [`DerivedOnly`] mode or an empty one in
-+    /// [`ExplicitOnly`] mode, which makes the key a conflict.
++    /// input has a sort key in [`ExplicitKeysForbidden`] mode or an empty one
++    /// in [`ExplicitKeysRequired`] mode, which makes the key a conflict.
      pub fn input(self, input: Input) -> Result<Self, ConstructorError> {
          self.add_input(input)
      }
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<S: SortMode> Constructor<OutputsModifiable, S> {
+     ///
      /// # Errors
      /// Returns [`ConstructorError::Conflict`] if it disagrees with the output
-     /// already holding that ID, or if it has a sort key in [`DerivedOnly`]
+-    /// already holding that ID, or if it has a sort key in [`DerivedOnly`]
 -    /// mode, which makes the key a conflict.
-+    /// mode or an empty one in [`ExplicitOnly`] mode, which makes the key a
-+    /// conflict.
++    /// already holding that ID, or if it has a sort key in
++    /// [`ExplicitKeysForbidden`] mode or an empty one in
++    /// [`ExplicitKeysRequired`] mode, which makes the key a conflict.
      pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
          self.add_output(output)
      }
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<S: SortMode> Construct
      use super::*;
 -    use crate::global::{Global, SortKeyDerivation};
 +    use crate::global::{Global, SortKeyDerivation, TxUuid};
-+    use crate::sorter::{DerivedOnly, ExplicitOnly, Mixed};
++    use crate::sorter::{ExplicitKeysForbidden, ExplicitKeysRequired, Mixed};
  
      type TestConstructor = Constructor<BothModifiable, Mixed>;
  
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 -    /// seeded mixed (1), derived-only (2), seeded derived-only (3), or
 -    /// explicit-only (4) mode.
 +    /// The global map of an empty PSBT whose sort fields select mixed (0 and
-+    /// 1), derived-only (2 and 3), or explicit-only (4 and 5) mode, with the
-+    /// sort seed `[7; 16]` if `mode` is odd.
++    /// 1), explicit-keys-forbidden (2 and 3), or explicit-keys-required (4
++    /// and 5) mode, with the sort seed `[7; 16]` if `mode` is odd.
      fn global_with_mode(flags: u8, mode: usize) -> Global {
          let mut global = unordered_global(flags);
          match mode {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
              assert_eq!(ordered.outputs.len(), 1);
  
 -            let derived_only: Constructor<BothModifiable, Seeded<DerivedOnly>> =
-+            let derived_only: Constructor<BothModifiable, DerivedOnly> =
-                 Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(psbt_with_mode(0x03, 2))
-                     .unwrap()
-                     .try_set_seed(seed())
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
+-                Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(psbt_with_mode(0x03, 2))
+-                    .unwrap()
+-                    .try_set_seed(seed())
+-                    .unwrap();
+-            let ordered = derived_only
++            let explicit_keys_forbidden: Constructor<BothModifiable, ExplicitKeysForbidden> =
++                Constructor::<BothModifiable, ExplicitKeysForbidden>::try_from_psbt(
++                    psbt_with_mode(0x03, 2),
++                )
++                .unwrap()
++                .try_set_seed(seed())
++                .unwrap();
++            let ordered = explicit_keys_forbidden
+                 .no_more_outputs()
                  .input(test_input(1))
                  .unwrap()
                  .no_more_inputs()
 -                .into_ordered_psbt();
 +                .try_into_ordered_psbt()
-+                .expect("a derived-only PSBT can be sorted");
++                .expect("a PSBT that forbids explicit keys can be sorted");
              assert_eq!(ordered.inputs.len(), 1);
          }
  
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
                      }),
                  ),
                  (
+-                    "derived-only mode needs derived key derivation",
+-                    Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(psbt_with_mode(
+-                        0x03, 0,
+-                    ))
++                    "ExplicitKeysForbidden needs derivation 0x01",
++                    Constructor::<BothModifiable, ExplicitKeysForbidden>::try_from_psbt(
++                        psbt_with_mode(0x03, 0),
++                    )
+                     .err(),
+                     ConstructorError::SortMode(SortModeError::SortKeyDerivation {
+                         expected: Some(SortKeyDerivation::Derived),
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
+                     }),
+                 ),
+                 (
 -                    "a seeded mode needs a seed",
 -                    Constructor::<BothModifiable, Seeded<Mixed>>::try_from_psbt(psbt_with_mode(
 -                        0x03, 0,
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
                  .input(test_input(4).into())
                  .psbt()
                  .expect("inputs carry no lock time requirements");
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
+         }
+ 
+         #[test]
+-        fn an_explicit_only_psbt_needs_sort_keys_to_be_sorted() {
+-            let unsorted =
+-                Constructor::<BothModifiable, ExplicitOnly>::try_from_psbt(psbt_with_mode(0x03, 4))
+-                    .unwrap()
+-                    .input(test_input(1))
+-                    .unwrap()
+-                    .into_sorter()
+-                    .try_sort();
++        fn an_explicit_keys_required_psbt_needs_sort_keys_to_be_sorted() {
++            let unsorted = Constructor::<BothModifiable, ExplicitKeysRequired>::try_from_psbt(
++                psbt_with_mode(0x03, 4),
++            )
++            .unwrap()
++            .input(test_input(1))
++            .unwrap()
++            .into_sorter()
++            .try_sort();
+             assert!(matches!(
+                 unsorted,
+                 Err(crate::sorter::SortError::MissingInputSortKey(missing)) if missing == outpoint(1)
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
+         }
+ 
+         #[test]
+-        fn a_sort_key_cannot_be_added_in_derived_only_mode() {
+-            let derived_only = || {
+-                Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(psbt_with_mode(0x03, 2))
+-                    .expect("an empty derived-only PSBT")
++        fn a_sort_key_cannot_be_added_in_explicit_keys_forbidden_mode() {
++            let explicit_keys_forbidden = || {
++                Constructor::<BothModifiable, ExplicitKeysForbidden>::try_from_psbt(psbt_with_mode(
++                    0x03, 2,
++                ))
++                .expect("an empty PSBT that forbids explicit keys")
+             };
+             let key = || SortKey::try_from(vec![1]).expect("one byte");
+             let mut input = test_input(1);
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
+                 }
+                 _ => false,
+             };
+-            assert!(marked(derived_only().input(input)));
+-            assert!(marked(derived_only().output(output)));
++            assert!(marked(explicit_keys_forbidden().input(input)));
++            assert!(marked(explicit_keys_forbidden().output(output)));
+         }
+ 
+         #[test]
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
          proptest! {
              #[test]
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 -                let sort_seed = |seed: &[u8]| SortSeed::try_from(seed.to_vec()).unwrap();
 -                let joined = if mode < 2 {
 -                    Constructor::<BothModifiable, Mixed>::try_from_psbt(psbt_with_mode(0x03, mode))
-+                let sort_seed = |seed: &[u8]| SortSeed::from(seed.to_vec());
-+                fn joined<S: SortMode>(mode: usize, seed: SortSeed) -> Result<UnorderedPsbt, SeedConflict> {
-+                    Constructor::<BothModifiable, S>::try_from_psbt(psbt_with_mode(0x03, mode))
-                         .unwrap()
+-                        .unwrap()
 -                        .try_set_seed(sort_seed(&seed))
 -                        .map(|constructor| constructor.0)
 -                } else {
 -                    Constructor::<BothModifiable, DerivedOnly>::try_from_psbt(psbt_with_mode(0x03, mode))
--                        .unwrap()
++                let sort_seed = |seed: &[u8]| SortSeed::from(seed.to_vec());
++                fn joined<S: SortMode>(mode: usize, seed: SortSeed) -> Result<UnorderedPsbt, SeedConflict> {
++                    Constructor::<BothModifiable, S>::try_from_psbt(psbt_with_mode(0x03, mode))
+                         .unwrap()
 -                        .try_set_seed(sort_seed(&seed))
 -                        .map(|constructor| constructor.0)
 +                        .try_set_seed(seed)
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +                }
 +                let joined = match mode {
 +                    0 | 1 => joined::<Mixed>(mode, sort_seed(&seed)),
-+                    2 | 3 => joined::<DerivedOnly>(mode, sort_seed(&seed)),
-+                    _ => joined::<ExplicitOnly>(mode, sort_seed(&seed)),
++                    2 | 3 => joined::<ExplicitKeysForbidden>(mode, sort_seed(&seed)),
++                    _ => joined::<ExplicitKeysRequired>(mode, sort_seed(&seed)),
                  };
                  match preset.filter(|preset| *preset != seed) {
                      None => prop_assert_eq!(
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 +                }
 +                let joined = match mode {
 +                    0 | 1 => joined::<Mixed>(mode, preset, &uuid),
-+                    2 | 3 => joined::<DerivedOnly>(mode, preset, &uuid),
-+                    _ => joined::<ExplicitOnly>(mode, preset, &uuid),
++                    2 | 3 => joined::<ExplicitKeysForbidden>(mode, preset, &uuid),
++                    _ => joined::<ExplicitKeysRequired>(mode, preset, &uuid),
 +                };
 +                let preset = preset.then(|| vec![9; 16]);
 +                let expected = match preset.filter(|preset| *preset != uuid) {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
 -                    check::<M, Seeded<DerivedOnly>>(psbt.clone(), flags && mode == 3)?;
 -                    check::<M, ExplicitOnly>(psbt.clone(), flags && mode == 4)
 +                    check::<M, Mixed>(psbt.clone(), flags && mode / 2 == 0)?;
-+                    check::<M, DerivedOnly>(psbt.clone(), flags && mode / 2 == 1)?;
-+                    check::<M, ExplicitOnly>(psbt.clone(), flags && mode / 2 == 2)?;
++                    check::<M, ExplicitKeysForbidden>(psbt.clone(), flags && mode / 2 == 1)?;
++                    check::<M, ExplicitKeysRequired>(psbt.clone(), flags && mode / 2 == 2)?;
 +                    check::<M, Seeded<Mixed>>(psbt.clone(), flags && uuid && mode / 2 == 0)?;
-+                    check::<M, Seeded<DerivedOnly>>(psbt.clone(), flags && uuid && mode / 2 == 1)?;
-+                    check::<M, Seeded<ExplicitOnly>>(psbt.clone(), flags && uuid && mode / 2 == 2)
++                    check::<M, Seeded<ExplicitKeysForbidden>>(psbt.clone(), flags && uuid && mode / 2 == 1)?;
++                    check::<M, Seeded<ExplicitKeysRequired>>(psbt.clone(), flags && uuid && mode / 2 == 2)
                  }
  
 -                let psbt = psbt_with_mode(flags, mode);
@@ crates/concurrent-psbt/src/roles/creator.rs: use bitcoin::locktime::absolute;
 +use crate::global::{Global, SortKeyDerivation, SortSeed, TxUuid};
  use crate::input::InputSet;
  use crate::output::OutputSet;
- use crate::sorter::{BothModifiable, DerivedOnly, ExplicitOnly, Mixed, Seeded};
+-use crate::sorter::{BothModifiable, DerivedOnly, ExplicitOnly, Mixed, Seeded};
++use crate::sorter::{BothModifiable, ExplicitKeysForbidden, ExplicitKeysRequired, Mixed, Seeded};
+ use crate::tx::UnorderedPsbt;
+ 
+ use super::constructor::Constructor;
 @@ crates/concurrent-psbt/src/roles/creator.rs: use super::constructor::Constructor;
  /// Entry point for creating new unordered PSBTs: BIP 370's [`v2::Creator`]
  /// with a sort mode.
@@ crates/concurrent-psbt/src/roles/creator.rs: use super::constructor::Constructor
  ///
 -/// - [`Creator::new`] selects [`Mixed`]: explicit sort keys are used where
 -///   present, and the rest are derived from the sort seed.
-+/// - [`Creator::new`] selects [`Mixed`]: inputs and outputs are ordered by
-+///   their explicit sort keys, a missing key counting as empty, then by their
-+///   derived keys.
- /// - [`derived_only`](Creator::derived_only) selects [`DerivedOnly`]:
+-/// - [`derived_only`](Creator::derived_only) selects [`DerivedOnly`]:
 -///   every sort key is derived from the sort seed.
 -/// - [`explicit_only`](Creator::explicit_only) selects [`ExplicitOnly`]: every input and
 -///   output needs an explicit sort key.
-+///   every sort key is derived.
-+/// - [`explicit_only`](Creator::explicit_only) selects [`ExplicitOnly`]: every
-+///   input and output needs a non-empty explicit sort key, and derived keys
-+///   break ties.
++/// - [`Creator::new`] selects [`Mixed`]: inputs and outputs are ordered by
++///   their explicit sort keys, a missing key counting as empty, then by their
++///   derived keys.
++/// - [`explicit_keys_forbidden`](Creator::explicit_keys_forbidden) selects
++///   [`ExplicitKeysForbidden`]: every sort key is derived.
++/// - [`explicit_keys_required`](Creator::explicit_keys_required) selects
++///   [`ExplicitKeysRequired`]: every input and output needs a non-empty
++///   explicit sort key, and derived keys break ties.
  ///
 -/// In [`Mixed`] and [`DerivedOnly`] mode, `set_seed` sets
 -/// `PSBT_GLOBAL_SORT_SEED` up front and refines the mode to [`Seeded`], so a
@@ crates/concurrent-psbt/src/roles/creator.rs: use super::constructor::Constructor
 -        self.with_seed(seed)
 -    }
 -
-     /// Switch to [`DerivedOnly`] mode (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x01`).
+-    /// Switch to [`DerivedOnly`] mode (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x01`).
 -    pub fn derived_only(self) -> Creator<DerivedOnly> {
-+    pub fn derived_only(self) -> Creator<Seeded<DerivedOnly>> {
++    /// Switch to [`ExplicitKeysForbidden`] mode
++    /// (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x01`).
++    pub fn explicit_keys_forbidden(self) -> Creator<Seeded<ExplicitKeysForbidden>> {
          self.with_sort_key_derivation(SortKeyDerivation::Derived)
      }
  
-     /// Switch to [`ExplicitOnly`] mode (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x00`).
+-    /// Switch to [`ExplicitOnly`] mode (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x00`).
 -    pub fn explicit_only(self) -> Creator<ExplicitOnly> {
-+    pub fn explicit_only(self) -> Creator<Seeded<ExplicitOnly>> {
++    /// Switch to [`ExplicitKeysRequired`] mode
++    /// (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x00`).
++    pub fn explicit_keys_required(self) -> Creator<Seeded<ExplicitKeysRequired>> {
          self.with_sort_key_derivation(SortKeyDerivation::Explicit)
      }
  
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
 +            // created PSBT has a UUID, so every mode is seeded.
 +            let mixed: Creator<Seeded<Mixed>> = Creator::default();
 +            let aux_mixed: Creator<Seeded<Mixed>> = Creator::new().set_seed(aux());
-+            let derived: Creator<Seeded<DerivedOnly>> = Creator::new().derived_only();
-+            let aux_derived: Creator<Seeded<DerivedOnly>> =
-+                Creator::new().derived_only().set_seed(aux());
-+            let explicit: Creator<Seeded<ExplicitOnly>> = Creator::new().explicit_only();
-+            let aux_explicit: Creator<Seeded<ExplicitOnly>> =
-+                Creator::new().set_seed(aux()).explicit_only();
++            let derived: Creator<Seeded<ExplicitKeysForbidden>> =
++                Creator::new().explicit_keys_forbidden();
++            let aux_derived: Creator<Seeded<ExplicitKeysForbidden>> =
++                Creator::new().explicit_keys_forbidden().set_seed(aux());
++            let explicit: Creator<Seeded<ExplicitKeysRequired>> =
++                Creator::new().explicit_keys_required();
++            let aux_explicit: Creator<Seeded<ExplicitKeysRequired>> =
++                Creator::new().set_seed(aux()).explicit_keys_required();
  
 +            let (derived_mode, explicit_mode) = (
 +                Some(SortKeyDerivation::Derived),
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
 +                    seed,
                  ),
                  (
-                     "derived only",
+-                    "derived only",
++                    "explicit keys forbidden",
                      derived.constructor().into_inner(),
 -                    Some(SortKeyDerivation::Derived),
 +                    derived_mode,
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
 -                    seeded_derived.constructor().into_inner(),
 -                    Some(SortKeyDerivation::Derived),
 -                    Some(seed.as_slice()),
-+                    "derived only with aux seed",
++                    "explicit keys forbidden with aux seed",
 +                    aux_derived.constructor().into_inner(),
 +                    derived_mode,
 +                    seed,
                  ),
                  (
-                     "explicit only",
+-                    "explicit only",
++                    "explicit keys required",
                      explicit.constructor().into_inner(),
 -                    Some(SortKeyDerivation::Explicit),
 +                    explicit_mode,
                      None,
                  ),
 +                (
-+                    "explicit only with aux seed",
++                    "explicit keys required with aux seed",
 +                    aux_explicit.constructor().into_inner(),
 +                    explicit_mode,
 +                    seed,
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
 -            let sorter: crate::sorter::Sorter<_, Seeded<DerivedOnly>> = Creator::new()
 -                .derived_only()
 -                .set_seed(sort_seed(seed.clone()))
-+            let creator = Creator::new().derived_only();
++            let creator = Creator::new().explicit_keys_forbidden();
 +            let uuid = creator.uuid.clone();
-+            let sorter: crate::sorter::Sorter<_, Seeded<DerivedOnly>> = creator
++            let sorter: crate::sorter::Sorter<_, Seeded<ExplicitKeysForbidden>> = creator
                  .constructor()
                  .input(input())
                  .unwrap()
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
                  let expected = Some(seed.as_slice());
  
                  check_forwarded(configured(), lock_time, version, None)?;
-@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
-                     expected,
-                 )?;
-                 check_forwarded(configured().explicit_only(), lock_time, version, None)?;
+                 check_forwarded(configured().set_seed(seeded()), lock_time, version, expected)?;
+-                check_forwarded(configured().derived_only(), lock_time, version, None)?;
++                check_forwarded(configured().explicit_keys_forbidden(), lock_time, version, None)?;
 +                check_forwarded(
-+                    configured().set_seed(seeded()).explicit_only(),
++                    configured().explicit_keys_forbidden().set_seed(seeded()),
 +                    lock_time,
 +                    version,
 +                    expected,
 +                )?;
++                check_forwarded(configured().explicit_keys_required(), lock_time, version, None)?;
+                 check_forwarded(
+-                    configured().derived_only().set_seed(seeded()),
++                    configured().set_seed(seeded()).explicit_keys_required(),
+                     lock_time,
+                     version,
+                     expected,
+                 )?;
+-                check_forwarded(configured().explicit_only(), lock_time, version, None)?;
              }
          }
      }
@@ crates/concurrent-psbt/src/roles/sorter/error.rs
  #[derive(Debug)]
  pub enum SortError {
 -    /// An input is missing a sort key and no seed is available to derive one.
-+    /// In [`ExplicitOnly`](super::ExplicitOnly) mode, the input spending this
-+    /// outpoint has no sort key.
++    /// In [`ExplicitKeysRequired`](super::ExplicitKeysRequired) mode, the input
++    /// spending this outpoint has no sort key.
      MissingInputSortKey(bitcoin::OutPoint),
 -    /// An output is missing a sort key and no seed is available to derive one.
-+    /// In [`ExplicitOnly`](super::ExplicitOnly) mode, an output has no sort
-+    /// key.
++    /// In [`ExplicitKeysRequired`](super::ExplicitKeysRequired) mode, an output
++    /// has no sort key.
      MissingOutputSortKey,
 -    /// Two inputs, or two outputs, have this sort key, so their relative
 -    /// order is undetermined.
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: pub enum SortModeError {
 -    /// 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.
 +    /// The mode is [`Seeded`](super::Seeded) but `PSBT_GLOBAL_TX_UUID` is
 +    /// unset or empty.
 +    MissingUuid,
-     /// The mode is [`DerivedOnly`](super::DerivedOnly) but an input or
-     /// output has a sort key.
++    /// The mode is [`ExplicitKeysForbidden`](super::ExplicitKeysForbidden) but
++    /// an input or output has a sort key.
      UnexpectedSortKey,
+ }
+ 
 @@ crates/concurrent-psbt/src/roles/sorter/error.rs: impl std::fmt::Display for SortModeError {
                  show(actual),
                  show(expected)
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: impl std::fmt::Display for Sor
 -            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"),
 +            Self::MissingUuid => write!(
 +                f,
 +                "PSBT_GLOBAL_TX_UUID unset or empty in a seeded sort mode"
 +            ),
-             Self::UnexpectedSortKey => write!(f, "a sort key is set in derived-only sort mode"),
++            Self::UnexpectedSortKey => write!(
++                f,
++                "a sort key is set in a sort mode that forbids explicit keys"
++            ),
          }
      }
+ }
 @@ crates/concurrent-psbt/src/roles/sorter/error.rs: impl std::fmt::Display for SeedConflict {
  
  impl std::error::Error for SeedConflict {}
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: mod tests {
 -                    SortModeError::MissingSortSeed.to_string(),
 -                    "PSBT_GLOBAL_SORT_SEED not set".to_owned(),
 +                    SorterError::from(SortModeError::UnexpectedSortKey).to_string(),
-+                    "a sort key is set in derived-only sort mode".to_owned(),
++                    "a sort key is set in a sort mode that forbids explicit keys".to_owned(),
++                ),
++                (
++                    SorterError::from(SortModeError::MissingUuid).to_string(),
++                    "PSBT_GLOBAL_TX_UUID unset or empty in a seeded sort mode".to_owned(),
                  ),
                  (
 -                    SorterError::from(SortModeError::UnexpectedSortSeed).to_string(),
 -                    "PSBT_GLOBAL_SORT_SEED is set in explicit-only sort mode".to_owned(),
-+                    SorterError::from(SortModeError::MissingUuid).to_string(),
-+                    "PSBT_GLOBAL_TX_UUID unset or empty in a seeded sort mode".to_owned(),
++                    UuidError::Empty.to_string(),
++                    "PSBT_GLOBAL_TX_UUID cannot be empty".to_owned(),
                  ),
                  (
 -                    SortModeError::UnexpectedSortKey.to_string(),
 -                    "a sort key is set in derived-only sort mode".to_owned(),
-+                    UuidError::Empty.to_string(),
-+                    "PSBT_GLOBAL_TX_UUID cannot be empty".to_owned(),
-+                ),
-+                (
 +                    UuidError::Conflict {
 +                        existing: TxUuid::from(vec![1; 16]),
 +                        requested: TxUuid::from(vec![2; 16]),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) fn join_seed(global:
 +/// NOT BIP 69. Derived keys hash the transaction's UUID, so all participants
 +/// produce the same order without revealing sort criteria to observers.
  #[derive(Debug, Clone, PartialEq)]
- pub enum DerivedOnly {}
+-pub enum DerivedOnly {}
++pub enum ExplicitKeysForbidden {}
  
 -/// Sort mode: ordering determined by explicit sort key fields on each input/output.
 +/// Sort mode: every input and output needs a non-empty explicit sort key.
 +/// Inputs, or outputs, with the same key are ordered by their derived keys.
  #[derive(Debug, Clone, PartialEq)]
- pub enum ExplicitOnly {}
+-pub enum ExplicitOnly {}
++pub enum ExplicitKeysRequired {}
  
 -/// Sort mode: explicit sort keys where present, the rest derived from the
 -/// sort seed.
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) fn join_seed(global:
  
 -/// Sort mode refinement: [`DerivedOnly`] or [`Mixed`] with
 -/// `PSBT_GLOBAL_SORT_SEED` known to be set.
-+/// Sort mode refinement: [`Mixed`], [`DerivedOnly`] or [`ExplicitOnly`] with
-+/// `PSBT_GLOBAL_TX_UUID` known to be set and non-empty, so sort keys can be
-+/// derived.
++/// Sort mode refinement: [`Mixed`], [`ExplicitKeysForbidden`] or
++/// [`ExplicitKeysRequired`] with `PSBT_GLOBAL_TX_UUID` known to be set and
++/// non-empty, so sort keys can be derived.
 +///
-+/// The [`Creator`](crate::roles::creator::Creator) always sets a UUID and produces
-+/// a seeded mode. A parsed PSBT may lack one: it enters an unseeded mode and
-+/// is refined by `try_set_uuid`.
++/// The [`Creator`](crate::roles::creator::Creator) always sets a UUID and
++/// produces a seeded mode. A parsed PSBT may lack one: it enters an unseeded
++/// mode and is refined by `try_set_uuid`.
  #[derive(Debug, Clone, PartialEq)]
  pub struct Seeded<S>(PhantomData<S>, std::convert::Infallible);
  
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub struct Seeded<S>(PhantomData<S>, std::convert::Infallible);
+ /// may still be added, the [`Updater`](psbt_v2::v2::Updater) once neither
  /// may.
  ///
- /// `S` is the sort mode: [`Mixed`], [`DerivedOnly`], or [`ExplicitOnly`], or
+-/// `S` is the sort mode: [`Mixed`], [`DerivedOnly`], or [`ExplicitOnly`], or
 -/// [`Seeded`] `Mixed` or `DerivedOnly` once the sort seed is known to be set.
-+/// one of them [`Seeded`] once `PSBT_GLOBAL_TX_UUID` is known to be set.
++/// `S` is the sort mode: [`Mixed`], [`ExplicitKeysForbidden`], or
++/// [`ExplicitKeysRequired`], or one of them [`Seeded`] once
++/// `PSBT_GLOBAL_TX_UUID` is known to be set.
  ///
  /// # Ordering
  ///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: impl<M: Modifiability, S: SortMo
 -    /// [`SortError::DuplicateSortKey`] if two inputs (or two outputs) end up
 -    /// with the same sort key.
 +    /// Returns [`SortError::MissingUuid`] if `PSBT_GLOBAL_TX_UUID` is unset or
-+    /// empty. In [`ExplicitOnly`] mode, then returns
++    /// empty. In [`ExplicitKeysRequired`] mode, then returns
 +    /// [`SortError::MissingInputSortKey`] or [`SortError::MissingOutputSortKey`]
 +    /// if an input or output has no sort key.
      pub fn try_into_ordered_psbt(self) -> Result<Psbt, SortError> {
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: impl<M: Modifiability> Sorter<M,
 -        )
 -        .expect("derived sort keys of distinct inputs and outputs do not collide")
 -    }
--
++infallible_sort!(Mixed, ExplicitKeysForbidden);
+ 
 -    /// Order the PSBT as [`into_ordered_psbt`](Self::into_ordered_psbt) does
 -    /// and hand it to [`M::Sorted`](Modifiability::Sorted).
 -    ///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: impl<M: Modifiability> Sorter<M,
 -        hand_off::<M>(self.into_ordered_psbt())
 -    }
 -}
-+infallible_sort!(Mixed, DerivedOnly);
- 
+-
 -impl<M: Modifiability> Sorter<M, ExplicitOnly> {
 -    /// Apply explicit ordering: sort by the `PSBT_IN_SORT_KEY` and
 -    /// `PSBT_OUT_SORT_KEY` fields, and produce an ordered BIP 370 [`Psbt`].
-+impl<M: Modifiability> Sorter<M, Seeded<ExplicitOnly>> {
++impl<M: Modifiability> Sorter<M, Seeded<ExplicitKeysRequired>> {
 +    /// Order the inputs and outputs as described [above](Sorter#ordering),
 +    /// and produce an ordered BIP 370 [`Psbt`].
      ///
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) mod sealed {
  }
  
  /// A sort mode that a PSBT's sort fields select: [`Mixed`] if
- /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is unset, [`DerivedOnly`] if it is
+-/// `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.
-+/// `0x01`, and [`ExplicitOnly`] if it is `0x00`, each [`Seeded`] if
++/// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is unset, [`ExplicitKeysForbidden`] if it
++/// is `0x01`, and [`ExplicitKeysRequired`] if it is `0x00`, each [`Seeded`] if
 +/// `PSBT_GLOBAL_TX_UUID` is set and non-empty too.
  pub trait SortMode: sealed::SortMode {}
  
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) mod sealed {
 -    Seeded<DerivedOnly> => Some(SortKeyDerivation::Derived), true;
 -    ExplicitOnly => Some(SortKeyDerivation::Explicit), false;
 +    Mixed => None;
-+    DerivedOnly => Some(SortKeyDerivation::Derived);
-+    ExplicitOnly => Some(SortKeyDerivation::Explicit);
++    ExplicitKeysForbidden => Some(SortKeyDerivation::Derived);
++    ExplicitKeysRequired => Some(SortKeyDerivation::Explicit);
  }
  
 -/// Check that `psbt`'s sort fields select sort mode `S`. Besides matching
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) mod sealed {
 -/// sort keys, since neither would be used.
 +/// Check that `psbt`'s sort fields select sort mode `S`: they match
 +/// `PSBT_GLOBAL_SORT_KEY_DERIVATION`, a [`Seeded`] mode has a non-empty
-+/// `PSBT_GLOBAL_TX_UUID`, and a [`DerivedOnly`] PSBT has no sort keys, since
-+/// they would not be used.
++/// `PSBT_GLOBAL_TX_UUID`, and an [`ExplicitKeysForbidden`] PSBT has no sort
++/// keys, since they would not be used.
  ///
  /// # Errors
  /// Returns the first [`SortModeError`] in that order.
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -        /// `DerivedOnly`, `Seeded<DerivedOnly>` and `ExplicitOnly` do with it.
 +        /// Each row is a PSBT's sort key derivation, its UUID (unset, empty or
 +        /// set) and which entry has a sort key, then what `Mixed`,
-+        /// `DerivedOnly`, `ExplicitOnly` and their [`Seeded`] refinements do
-+        /// with it. Only a seeded mode needs the UUID, and checks it after
-+        /// the derivation and before the sort keys.
++        /// `ExplicitKeysForbidden`, `ExplicitKeysRequired` and their [`Seeded`]
++        /// refinements do with it. Only a seeded mode needs the UUID, and
++        /// checks it after the derivation and before the sort keys.
          #[test]
          fn the_sort_fields_select_the_sort_mode() {
 -            use Outcome::{Admits, KeyForbidden, MissingSeed, SeedForbidden, Wants};
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -                    .err(),
 -                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(psbt).err(),
 +                    error::<Mixed>(&psbt),
-+                    error::<DerivedOnly>(&psbt),
-+                    error::<ExplicitOnly>(&psbt),
++                    error::<ExplicitKeysForbidden>(&psbt),
++                    error::<ExplicitKeysRequired>(&psbt),
 +                    error::<Seeded<Mixed>>(&psbt),
-+                    error::<Seeded<DerivedOnly>>(&psbt),
-+                    error::<Seeded<ExplicitOnly>>(&psbt),
++                    error::<Seeded<ExplicitKeysForbidden>>(&psbt),
++                    error::<Seeded<ExplicitKeysRequired>>(&psbt),
                  ];
                  let expected = outcomes.map(|outcome| {
                      let error = match outcome {
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
              psbt.inputs =
                  InputSet::try_from_inputs((1..=5).map(|txid| make_input(txid, 0))).unwrap();
              psbt.outputs =
+                 OutputSet::try_from_outputs((0..=4).map(|uid| make_output_with_uid(&[uid])))
+                     .unwrap();
+ 
+-            let ordered = Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(
++            let ordered = Sorter::<Unmodifiable, ExplicitKeysForbidden>::try_from_unordered_psbt(
+                 with_derivation(psbt, SortKeyDerivation::Derived),
+             )
+             .unwrap()
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
                  .iter()
                  .map(|input| input.previous_txid)
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -        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!(
--                missing_seed(input),
--                Err(SortError::MissingSortSeed)
--            ));
 +        fn sorting_requires_a_uuid() {
 +            for uuid in [None, Some(vec![])] {
 +                let mut psbt = empty_psbt();
 +                psbt.global.uuid = uuid.map(TxUuid::from);
 +                psbt.inputs = InputSet::try_from_inputs([make_input(1, 0)]).unwrap();
-+                let errors =
-+                    [
-+                        Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt.clone())
-+                            .unwrap()
-+                            .try_into_ordered_psbt()
-+                            .err(),
-+                        Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(
-+                            with_derivation(psbt.clone(), SortKeyDerivation::Derived),
-+                        )
-+                        .unwrap()
-+                        .try_sort()
-+                        .err(),
-+                        Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(
-+                            with_derivation(psbt, SortKeyDerivation::Explicit),
-+                        )
++                let errors = [
++                    Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt.clone())
 +                        .unwrap()
 +                        .try_into_ordered_psbt()
 +                        .err(),
-+                    ];
++                    Sorter::<Unmodifiable, ExplicitKeysForbidden>::try_from_unordered_psbt(
++                        with_derivation(psbt.clone(), SortKeyDerivation::Derived),
++                    )
++                    .unwrap()
++                    .try_sort()
++                    .err(),
++                    Sorter::<Unmodifiable, ExplicitKeysRequired>::try_from_unordered_psbt(
++                        with_derivation(psbt, SortKeyDerivation::Explicit),
++                    )
+                     .unwrap()
+                     .try_into_ordered_psbt()
+-            };
+-
+-            let mut input = empty_psbt();
+-            input.inputs = InputSet::try_from_inputs([make_input(1, 0)]).unwrap();
+-            assert!(matches!(
+-                missing_seed(input),
+-                Err(SortError::MissingSortSeed)
+-            ));
++                    .err(),
++                ];
 +                for error in errors {
 +                    assert!(matches!(error, Some(SortError::MissingUuid)), "{error:?}");
 +                }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
              assert!(matches!(
 -                missing_seed(output),
 -                Err(SortError::MissingSortSeed)
-+                Sorter::<Unmodifiable, ExplicitOnly>(missing_input, PhantomData)
++                Sorter::<Unmodifiable, ExplicitKeysRequired>(missing_input, PhantomData)
 +                    .try_into_ordered_psbt(),
 +                Err(SortError::MissingInputSortKey(_))
              ));
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
              assert!(matches!(
 -                derived_only.try_into_ordered_psbt(),
 -                Err(SortError::MissingSortSeed)
-+                Sorter::<Unmodifiable, Seeded<ExplicitOnly>>(missing_output, PhantomData)
++                Sorter::<Unmodifiable, Seeded<ExplicitKeysRequired>>(missing_output, PhantomData)
 +                    .try_into_ordered_psbt(),
 +                Err(SortError::MissingOutputSortKey)
              ));
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 +                    Sorter::try_from_unordered_psbt(psbt).unwrap()
 +                }
 +                let mixed = sorter::<Mixed>;
-+                let derived = sorter::<DerivedOnly>;
-+                let explicit = sorter::<ExplicitOnly>;
++                let derived = sorter::<ExplicitKeysForbidden>;
++                let explicit = sorter::<ExplicitKeysRequired>;
 +                let seeded_mixed = sorter::<Seeded<Mixed>>;
-+                let seeded_derived = sorter::<Seeded<DerivedOnly>>;
-+                let seeded_explicit = sorter::<Seeded<ExplicitOnly>>;
++                let seeded_derived = sorter::<Seeded<ExplicitKeysForbidden>>;
++                let seeded_explicit = sorter::<Seeded<ExplicitKeysRequired>>;
  
                  check(
                      conflicting,
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -                    derived(psbt(true, false)).try_into_ordered_psbt().unwrap(),
 +                    seeded_mixed(psbt(true)).try_sort().map_err(Into::into),
 +                    seeded_mixed(psbt(true)).into_ordered_psbt(),
-+                );
-+                check(
-+                    conflicting,
-+                    seeded_derived(psbt(false)).try_sort().map_err(Into::into),
-+                    seeded_derived(psbt(false)).into_ordered_psbt(),
                  );
                  check(
                      conflicting,
 -                    explicit(psbt(false, true)).try_sort(),
 -                    explicit(psbt(false, true)).try_into_ordered_psbt().unwrap(),
++                    seeded_derived(psbt(false)).try_sort().map_err(Into::into),
++                    seeded_derived(psbt(false)).into_ordered_psbt(),
++                );
++                check(
++                    conflicting,
 +                    seeded_explicit(psbt(true)).try_sort(),
 +                    seeded_explicit(psbt(true)).try_into_ordered_psbt().unwrap(),
                  );
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
          }
  
          /// Which sorter, and so which sort keys, a test orders with.
-@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
+         #[derive(Debug, Clone, Copy)]
+         enum Mode {
+             Mixed,
+-            DerivedOnly,
+-            ExplicitOnly,
++            ExplicitKeysForbidden,
++            ExplicitKeysRequired,
+         }
+ 
+         fn modes() -> impl Strategy<Value = Mode> {
+             prop_oneof![
+                 Just(Mode::Mixed),
+-                Just(Mode::DerivedOnly),
+-                Just(Mode::ExplicitOnly)
++                Just(Mode::ExplicitKeysForbidden),
++                Just(Mode::ExplicitKeysRequired)
              ]
          }
  
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -                Mode::ExplicitOnly => true,
 -                Mode::Mixed => carried,
 -                Mode::DerivedOnly => false,
-+                Mode::ExplicitOnly => Some([&[1u8][..], key].concat()),
++                Mode::ExplicitKeysRequired => Some([&[1u8][..], key].concat()),
 +                Mode::Mixed => carried.then(|| key.to_vec()),
-+                Mode::DerivedOnly => None,
++                Mode::ExplicitKeysForbidden => None,
              }
 -            .then(|| sort_key(key.to_vec()))
 +            .map(sort_key)
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -                    psbt.global
 -                        .set_sort_key_derivation(SortKeyDerivation::Derived);
 -                }
+-                Mode::ExplicitOnly => psbt
 +                Mode::Mixed => {}
-+                Mode::DerivedOnly => psbt
++                Mode::ExplicitKeysForbidden => psbt
 +                    .global
 +                    .set_sort_key_derivation(SortKeyDerivation::Derived),
-                 Mode::ExplicitOnly => psbt
++                Mode::ExplicitKeysRequired => psbt
                      .global
                      .set_sort_key_derivation(SortKeyDerivation::Explicit),
+             }
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
              psbt
          }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(psbt)
 -                        .unwrap()
 -                        .try_into_ordered_psbt()
+-                }
+-                Mode::ExplicitOnly => {
+-                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(psbt)
+-                        .unwrap()
+-                        .try_into_ordered_psbt()
 +        fn sorter<S: SortMode>(psbt: UnorderedPsbt) -> Sorter<Unmodifiable, S> {
 +            Sorter::try_from_unordered_psbt(psbt).unwrap()
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 +            match (mode, seeded) {
 +                (Mode::Mixed, false) => sorter::<Mixed>(psbt).try_into_ordered_psbt().unwrap(),
 +                (Mode::Mixed, true) => sorter::<Seeded<Mixed>>(psbt).into_ordered_psbt(),
-+                (Mode::DerivedOnly, false) => {
-+                    sorter::<DerivedOnly>(psbt).try_into_ordered_psbt().unwrap()
-                 }
--                Mode::ExplicitOnly => {
--                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(psbt)
--                        .unwrap()
--                        .try_into_ordered_psbt()
-+                (Mode::DerivedOnly, true) => {
-+                    sorter::<Seeded<DerivedOnly>>(psbt).into_ordered_psbt()
++                (Mode::ExplicitKeysForbidden, false) => sorter::<ExplicitKeysForbidden>(psbt)
++                    .try_into_ordered_psbt()
++                    .unwrap(),
++                (Mode::ExplicitKeysForbidden, true) => {
++                    sorter::<Seeded<ExplicitKeysForbidden>>(psbt).into_ordered_psbt()
                  }
-+                (Mode::ExplicitOnly, false) => sorter::<ExplicitOnly>(psbt)
++                (Mode::ExplicitKeysRequired, false) => sorter::<ExplicitKeysRequired>(psbt)
 +                    .try_into_ordered_psbt()
 +                    .unwrap(),
-+                (Mode::ExplicitOnly, true) => sorter::<Seeded<ExplicitOnly>>(psbt)
++                (Mode::ExplicitKeysRequired, true) => sorter::<Seeded<ExplicitKeysRequired>>(psbt)
 +                    .try_into_ordered_psbt()
 +                    .unwrap(),
              }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 +            match (mode, seeded) {
 +                (Mode::Mixed, false) => sorter::<Mixed>(psbt).try_sort().unwrap(),
 +                (Mode::Mixed, true) => sorter::<Seeded<Mixed>>(psbt).try_sort().unwrap(),
-+                (Mode::DerivedOnly, false) => sorter::<DerivedOnly>(psbt).try_sort().unwrap(),
-+                (Mode::DerivedOnly, true) => {
-+                    sorter::<Seeded<DerivedOnly>>(psbt).try_sort().unwrap()
++                (Mode::ExplicitKeysForbidden, false) => {
++                    sorter::<ExplicitKeysForbidden>(psbt).try_sort().unwrap()
                  }
 -                Mode::ExplicitOnly => {
 -                    Sorter::<Unmodifiable, ExplicitOnly>::try_from_unordered_psbt(psbt)
 -                        .unwrap()
--                        .try_sort()
-+                (Mode::ExplicitOnly, false) => sorter::<ExplicitOnly>(psbt).try_sort().unwrap(),
-+                (Mode::ExplicitOnly, true) => {
-+                    sorter::<Seeded<ExplicitOnly>>(psbt).try_sort().unwrap()
++                (Mode::ExplicitKeysForbidden, true) => {
++                    sorter::<Seeded<ExplicitKeysForbidden>>(psbt)
+                         .try_sort()
++                        .unwrap()
++                }
++                (Mode::ExplicitKeysRequired, false) => {
++                    sorter::<ExplicitKeysRequired>(psbt).try_sort().unwrap()
                  }
++                (Mode::ExplicitKeysRequired, true) => sorter::<Seeded<ExplicitKeysRequired>>(psbt)
++                    .try_sort()
++                    .unwrap(),
              }
 -            .unwrap()
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
                      psbt.inputs = InputSet::try_from_inputs((0..4).map(|txid| make_input(txid, 0))).unwrap();
                      psbt.outputs = OutputSet::try_from_outputs((0..4).map(|uid| make_output_with_uid(&[uid]))).unwrap();
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
+                 };
+                 let mixed = |seed| Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt(seed)).unwrap();
+                 let derived = |seed| {
+-                    Sorter::<Unmodifiable, DerivedOnly>::try_from_unordered_psbt(with_derivation(
++                    Sorter::<Unmodifiable, ExplicitKeysForbidden>::try_from_unordered_psbt(with_derivation(
+                         psbt(seed),
+                         SortKeyDerivation::Derived,
                      ))
                      .unwrap()
                  };
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 +                    let set = TxUuid::from(uuid.clone());
 +                    match mode {
 +                        Mode::Mixed => sorter::<Mixed>(psbt).try_set_uuid(set).map(|s| s.into_ordered_psbt()),
-+                        Mode::DerivedOnly => sorter::<DerivedOnly>(psbt).try_set_uuid(set).map(|s| s.into_ordered_psbt()),
-+                        Mode::ExplicitOnly => sorter::<ExplicitOnly>(psbt)
++                        Mode::ExplicitKeysForbidden => sorter::<ExplicitKeysForbidden>(psbt).try_set_uuid(set).map(|s| s.into_ordered_psbt()),
++                        Mode::ExplicitKeysRequired => sorter::<ExplicitKeysRequired>(psbt)
 +                            .try_set_uuid(set)
 +                            .map(|s| s.try_into_ordered_psbt().unwrap()),
 +                    }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 +                uuid in uuids(),
              ) {
 -                fn sorter<M: Modifiability>(flags: u8, seed: &[u8]) -> Sorter<M, Seeded<DerivedOnly>> {
-+                fn sorter<M: Modifiability>(flags: u8, uuid: &[u8]) -> Sorter<M, DerivedOnly> {
++                fn sorter<M: Modifiability>(flags: u8, uuid: &[u8]) -> Sorter<M, ExplicitKeysForbidden> {
                      let mut psbt = empty_psbt();
                      psbt.global.set_tx_modifiable_flags(flags);
 -                    psbt.global.set_sort_seed(sort_seed(seed.to_vec()));

/// - a derived sort key = [`SortKeyHash`] of the sort seed, then the input's
/// consensus-encoded outpoint or the output's unique ID.
///
/// Derived keys of distinct inputs, or outputs, differ, so explicit keys may

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Public sort-key docs still require distinct keys

The new rule orders entries with equal explicit keys by their derived keys and UnorderedPsbt::try_from_psbt accepts repeated keys, but the public PSBT_IN_SORT_KEY/PSBT_OUT_SORT_KEY docs still say the key must be distinct across all inputs/outputs.

sort key. Must be distinct across all inputs in a PSBT.

— fungi-protocol/concurrent-psbt@921b57a · crates/concurrent-psbt/src/psbt/input.rs#L119

sort key. Must be distinct across all outputs in a PSBT.

— fungi-protocol/concurrent-psbt@921b57a · crates/concurrent-psbt/src/psbt/output.rs#L258

oakagent · automated · 921b57a

return Err(UuidError::Empty);
}
let uuid = match global.uuid.clone() {
Some(existing) => existing.try_join(uuid).map_err(UuidError::from_conflict)?,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Empty UUID cannot be set by try_set_uuid

The decoder admits an empty PSBT_GLOBAL_TX_UUID, and has_uuid/sort_seed treat it as absent, so the PSBT enters an unseeded mode; join_uuid treats the empty value as an existing UUID, so try_set_uuid returns UuidError::Conflict and the PSBT can neither be refined to a seeded mode nor sorted.

A parsed PSBT may lack one: it enters an unseeded

— fungi-protocol/concurrent-psbt@921b57a · crates/concurrent-psbt/src/roles/sorter/mod.rs#L95

mode and is refined by try_set_uuid.

— fungi-protocol/concurrent-psbt@921b57a · crates/concurrent-psbt/src/roles/sorter/mod.rs#L96

oakagent · automated · 921b57a

/// together with the transaction's [`TxUuid`].
///
/// The UUID already makes derived keys unpredictable, so the seed may be
/// empty, or commit to extra information such as a protocol transcript. An

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Spec requires 128-bit seed under 0x01 but commit accepts empty

The spec requires a PSBT_GLOBAL_SORT_SEED of at least 128 bits under derivation 0x01 (line 139), but this commit accepts an empty seed; is that intentional?

If the global field PSBT_GLOBAL_SORT_DETERMINISTIC is set (unsigned 8 bit integer) to 0x01, then sort keys MUST NOT be set, and PSBT_GLOBAL_SORT_SEED MUST be set and contain at least 128 bits of randomness.

— fungi-protocol/docs@f2806d9 · docs/psbt-concurrent.md#L139

should only set PSBT_GLOBAL_SORT_DETERMINISTIC to 0x01, and leave PSBT_GLOBAL_SORT_SEED unset.

— fungi-protocol/docs@f2806d9 · docs/psbt-concurrent.md#L153

oak · automated · 921b57a

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

my suggestions upon which this commit is modeled say that the UUID is now mandatory, and the seed is now renamed "additional entropy", and always allowed, and always optional

@github-actions

Copy link
Copy Markdown
range-diff for force push 921b57a46a → 2ecafcff2c November 15, 2026 04:37 UTC: 1 modified, 4 added; 1 → 5 commits; same base 3d413230fb

reproduce: git range-diff 3d41323..921b57a 3d41323..2ecafcf

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

-:  ----------                > 1:  8a7ebb21cc  +200  -173 7f rename sort modes for the explicit keys they allow
-:  ----------                > 2:  818eb39301  +107    -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
1:  921b57a46a +1273 -1094 9f ! 3:  93007c2c86  +962  -958 9f sort by explicit key, then by a key derived from the tx UUID
-:  ----------                > 4:  eef5e3b673  +118  -149 5f allow repeated explicit sort keys
-:  ----------                > 5:  2ecafcff2c  +136   -51 6f require non-empty explicit sort keys under derivation 0x00
1: 921b57a46a ! 3: 93007c2c86 sort by explicit key, then by a key derived from the tx UUID
@@ Metadata
 Author: Yuval Kogman <nothingmuch@woobling.org>
 
  ## Commit message ##
-    sort by explicit key, then by a key derived from the tx UUID
+    derive sort keys from the tx UUID in every mode
 
-    Add a required PSBT_GLOBAL_TX_UUID (subtype 0x13). The Creator sets a
-    fresh random 16-byte UUID on every PSBT, and sorting fails with
-    SortError::MissingUuid if the UUID is unset or empty.
+    PSBT_GLOBAL_TX_UUID becomes the mandatory sort seed. Every sort mode
+    orders inputs and outputs by explicit sort key, a missing key counting
+    as empty, and then by derived key. With BIP-340 style tagged hashes
+    under concurrent-psbt/:
+    - h = UuidHash(uuid) and e = AuxSortSeedHash(PSBT_GLOBAL_SORT_SEED),
+      the latter over the empty string if the seed is unset;
+    - the sort seed is SortSeedHash(h || e);
+    - the derived key is SortKeyHash(sort seed || outpoint or unique ID).
+    Sorting fails with SortError::MissingUuid if the UUID is unset or
+    empty. Full keys of distinct entries differ, so the sorter's
+    DuplicateSortKey goes away, and so does MissingSortSeed.
+
+    The UUID supplies the entropy, so the sort seed becomes auxiliary: any
+    length, allowed in every mode. SortSeed::MIN_LEN, InvalidSortSeed,
+    SortSeedTooShort, UnexpectedSortSeed and SortModeError::MissingSortSeed
+    are removed. try_set_seed and set_seed keep the mode, since the
+    auxiliary seed adds no guarantee.
 
     The Seeded typestate now tracks the UUID instead of the sort seed, and
     refines all three modes:
@@ Commit message
       missing explicit key. Only the unseeded modes can fail with
       SortError::MissingUuid.
 
-    Every sort mode orders inputs and outputs by explicit sort key, a
-    missing key counting as empty, and then by derived key. With BIP-340
-    style tagged hashes under concurrent-psbt/:
-    - h = UuidHash(uuid) and e = AuxSortSeedHash(PSBT_GLOBAL_SORT_SEED),
-      the latter over the empty string if the seed is unset;
-    - the sort seed is SortSeedHash(h || e);
-    - the derived key is SortKeyHash(sort seed || outpoint or unique ID).
-    Derived keys of distinct entries differ, so explicit keys may repeat:
-    - The duplicate-key check, DuplicateSortKey and the linear scan on
-      every join are removed.
-    - The sort seed becomes auxiliary: any length, allowed in every mode.
-      SortSeed::MIN_LEN, InvalidSortSeed, SortSeedTooShort and
-      UnexpectedSortSeed are removed.
-    - Derivation 0x00 now requires non-empty explicit keys. An empty key is
-      marked as a conflict, as a key under 0x01 already is, and reported as
-      EmptyInputSortKey or EmptyOutputSortKey.
-
-    try_set_seed and set_seed keep the mode, since the auxiliary seed adds
-    no guarantee.
-
-    Derived keys break ties in every mode, so the modes are renamed for the
-    explicit keys they allow: DerivedOnly becomes ExplicitKeysForbidden and
-    ExplicitOnly becomes ExplicitKeysRequired, with the Creator methods
-    explicit_keys_forbidden and explicit_keys_required.
+    Explicit keys must still be distinct; the next commit lifts that.
 
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
-@@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
-         pub(crate) unordered: bool = TxUnorderedField,
-         pub(crate) sort_key_derivation: Option<SortKeyDerivation> = SortKeyDerivationField,
-         pub(crate) sort_seed: Option<SortSeed> = SortSeedField,
-+        pub(crate) uuid: Option<TxUuid> = TxUuidField,
-     },
- }
- 
- impl Default for Global {
-     fn default() -> Self {
--        Self::from_v2_fields(psbt_v2::v2::Global::default(), false, None, None)
-+        Self::from_v2_fields(psbt_v2::v2::Global::default(), false, None, None, None)
-     }
- }
- 
 @@ crates/concurrent-psbt/src/psbt/global.rs: pub enum InvalidGlobal {
      /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is present but its value is neither
      /// `0x00` nor `0x01`.
@@ crates/concurrent-psbt/src/psbt/global.rs: pub const PSBT_GLOBAL_TX_UNORDERED_SU
  }
  
 -/// The bytes are too short for a [`SortSeed`]; they are returned unchanged.
-+impl From<Vec<u8>> for SortSeed {
-+    fn from(bytes: Vec<u8>) -> Self {
-+        Self(bytes)
-+    }
-+}
-+
-+impl crate::values::IdempotentValue for SortSeed {}
-+
-+/// Subtype for `PSBT_GLOBAL_TX_UUID`.
-+///
-+/// Identifies the transaction being constructed, and is the mandatory input
-+/// to derived sort keys.
-+pub const PSBT_GLOBAL_TX_UUID_SUBTYPE: u8 = 0x13;
-+
-+/// A `PSBT_GLOBAL_TX_UUID` value: the identity of the transaction being
-+/// constructed.
-+///
-+/// [`Creator`](crate::roles::Creator) sets a fresh one on every PSBT. Every
-+/// derived sort key hashes it, so the order of inputs and outputs that share
-+/// an explicit sort key, or have none, is unpredictable without it. Sorting
-+/// fails if it is unset or empty. Two PSBTs with different UUIDs describe
-+/// different transactions, so they do not join.
- #[derive(Debug, Clone, PartialEq, Eq)]
+-#[derive(Debug, Clone, PartialEq, Eq)]
 -pub struct InvalidSortSeed(pub Vec<u8>);
-+pub struct TxUuid(Vec<u8>);
- 
+-
 -impl TryFrom<Vec<u8>> for SortSeed {
 -    type Error = InvalidSortSeed;
-+impl TxUuid {
-+    /// Access the raw bytes of the UUID.
-+    pub fn as_bytes(&self) -> &[u8] {
-+        &self.0
-+    }
- 
+-
 -    fn try_from(bytes: Vec<u8>) -> Result<Self, InvalidSortSeed> {
 -        if bytes.len() < Self::MIN_LEN {
 -            return Err(InvalidSortSeed(bytes));
 -        }
 -        Ok(Self(bytes))
-+    /// Generate a fresh random 16-byte UUID from the operating system's RNG,
-+    /// as [`UniqueId::generate`](crate::output::UniqueId::generate) does.
-+    ///
-+    /// # Panics
-+    /// Panics if the operating system's RNG is unavailable.
-+    pub fn generate() -> Self {
-+        use rand::{RngCore, TryRngCore, rngs::OsRng};
-+
-+        let mut bytes = [0u8; 16];
-+        OsRng.unwrap_err().fill_bytes(&mut bytes);
-+        Self(bytes.to_vec())
-     }
- }
- 
+-    }
+-}
+-
 -impl std::fmt::Display for InvalidSortSeed {
 -    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
 -        write!(
@@ crates/concurrent-psbt/src/psbt/global.rs: pub const PSBT_GLOBAL_TX_UNORDERED_SU
 -            self.0.len(),
 -            SortSeed::MIN_LEN
 -        )
-+impl From<Vec<u8>> for TxUuid {
++impl From<Vec<u8>> for SortSeed {
 +    fn from(bytes: Vec<u8>) -> Self {
 +        Self(bytes)
      }
@@ crates/concurrent-psbt/src/psbt/global.rs: pub const PSBT_GLOBAL_TX_UNORDERED_SU
  
 -impl std::error::Error for InvalidSortSeed {}
 -
--impl crate::values::IdempotentValue for SortSeed {}
-+impl crate::values::IdempotentValue for TxUuid {}
+ impl crate::values::IdempotentValue for SortSeed {}
+ 
+ /// Subtype for `PSBT_GLOBAL_TX_UUID`.
+ ///
+-/// Identifies the transaction being constructed.
++/// Identifies the transaction being constructed, and is the mandatory input
++/// to derived sort keys.
+ pub const PSBT_GLOBAL_TX_UUID_SUBTYPE: u8 = 0x13;
+ 
+ /// A `PSBT_GLOBAL_TX_UUID` value: the identity of the transaction being
+ /// constructed.
+ ///
+-/// [`Creator`](crate::roles::Creator) sets a fresh one on every PSBT. Two
+-/// PSBTs with different UUIDs describe different transactions, so they do
+-/// not join.
++/// [`Creator`](crate::roles::Creator) sets a fresh one on every PSBT. Every
++/// derived sort key hashes it, so the order of inputs and outputs without an
++/// explicit sort key is unpredictable without it. Sorting fails if it is unset
++/// or empty. Two PSBTs with different UUIDs describe
++/// different transactions, so they do not join.
+ #[derive(Debug, Clone, PartialEq, Eq)]
+ pub struct TxUuid(Vec<u8>);
+ 
+@@ crates/concurrent-psbt/src/psbt/global.rs: impl crate::values::IdempotentValue for TxUuid {}
  
  /// Subtype for `PSBT_GLOBAL_SORT_KEY_DERIVATION`.
  ///
 -/// `0x01` = sort keys derived from seed (explicit keys MUST NOT be set).
--/// `0x00` = explicit sort keys required.
-+/// `0x01` = sort keys derived only (explicit keys MUST NOT be set).
-+/// `0x00` = non-empty explicit sort keys required.
++/// `0x01` = explicit sort keys MUST NOT be set.
+ /// `0x00` = explicit sort keys required.
  pub const PSBT_GLOBAL_SORT_KEY_DERIVATION_SUBTYPE: u8 = 0x12;
  
  /// A `PSBT_GLOBAL_SORT_KEY_DERIVATION` value: where sort keys come from.
@@ crates/concurrent-psbt/src/psbt/global.rs: pub const PSBT_GLOBAL_TX_UNORDERED_SU
  pub enum SortKeyDerivation {
 -    /// `0x00`: every input and output needs an explicit sort key, and there is
 -    /// no sort seed.
-+    /// `0x00`: every input and output needs a non-empty explicit sort key.
-+    /// Inputs, or outputs, with the same explicit key are ordered by their
-+    /// derived keys.
++    /// `0x00`: every input and output needs an explicit sort key.
      Explicit,
 -    /// `0x01`: every sort key is derived from the sort seed, and explicit sort
 -    /// keys are not allowed.
 +    /// `0x01`: inputs and outputs are ordered by their derived keys alone,
 +    /// and explicit sort keys are not allowed.
-     Derived,
+     ExplicitKeysForbidden,
  }
  
 @@ crates/concurrent-psbt/src/psbt/global.rs: impl ProprietaryField for SortSeedField {
@@ crates/concurrent-psbt/src/psbt/global.rs: impl ProprietaryField for SortSeedFie
      }
  
      fn encode(seed: Self::Value) -> Option<Vec<u8>> {
-@@ crates/concurrent-psbt/src/psbt/global.rs: impl ProprietaryField for SortSeedField {
-     }
- }
- 
-+struct TxUuidField;
-+
-+impl ProprietaryField for TxUuidField {
-+    const SUBTYPE: u8 = PSBT_GLOBAL_TX_UUID_SUBTYPE;
-+    type Value = Option<TxUuid>;
-+    type Error = InvalidGlobal;
-+
-+    fn decode(value: Option<Vec<u8>>) -> Result<Self::Value, InvalidGlobal> {
-+        Ok(value.map(TxUuid))
-+    }
-+
-+    fn encode(uuid: Self::Value) -> Option<Vec<u8>> {
-+        uuid.map(|uuid| uuid.0)
-+    }
-+}
-+
- /// Accessors for the sort fields. A BIP 370 global map stores them as
- /// proprietary fields under [`PROPRIETARY_PREFIX`](crate::PROPRIETARY_PREFIX).
- impl Global {
 @@ crates/concurrent-psbt/src/psbt/global.rs: impl Global {
          self.unordered = false;
      }
@@ crates/concurrent-psbt/src/psbt/global.rs: impl Global {
      pub fn set_sort_seed(&mut self, seed: SortSeed) {
          self.sort_seed = Some(seed);
      }
- 
-+    /// Get `PSBT_GLOBAL_TX_UUID`, if set.
-+    pub fn uuid(&self) -> Option<&[u8]> {
-+        self.uuid.as_ref().map(TxUuid::as_bytes)
-+    }
-+
-+    /// Set `PSBT_GLOBAL_TX_UUID`.
-+    pub fn set_uuid(&mut self, uuid: TxUuid) {
-+        self.uuid = Some(uuid);
-+    }
-+
-     /// Get `PSBT_GLOBAL_SORT_KEY_DERIVATION`, if set.
-     pub fn sort_key_derivation(&self) -> Option<SortKeyDerivation> {
-         self.sort_key_derivation
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
              };
              let mut global = Global::default();
              global.set_unordered();
 -            global.set_sort_seed(SortSeed::try_from(vec![0xaa; 16]).unwrap());
 +            global.set_sort_seed(SortSeed::from(vec![0xaa; 16]));
-             global.set_sort_key_derivation(SortKeyDerivation::Derived);
-+            global.set_uuid(TxUuid::from(vec![0xbb; 16]));
+             global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden);
+             global.set_uuid(TxUuid::from(vec![0xbb; 16]));
              assert!(global.is_unordered());
-             assert_eq!(global.sort_seed(), Some([0xaa; 16].as_slice()));
-+            assert_eq!(global.uuid(), Some([0xbb; 16].as_slice()));
-             assert_eq!(
-                 global.sort_key_derivation(),
-                 Some(SortKeyDerivation::Derived)
-@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
-             assert_eq!(v2.proprietaries.get(&key(0x10)), Some(&vec![0x03]));
-             assert_eq!(v2.proprietaries.get(&key(0x11)), Some(&vec![0xaa; 16]));
-             assert_eq!(v2.proprietaries.get(&key(0x12)), Some(&vec![0x01]));
-+            assert_eq!(v2.proprietaries.get(&key(0x13)), Some(&vec![0xbb; 16]));
-             assert_eq!(Global::try_from(v2), Ok(global.clone()));
- 
-             global.clear_unordered();
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
                      InvalidGlobal::SortKeyDerivation(vec![2]),
                      "PSBT_GLOBAL_SORT_KEY_DERIVATION is [02], not 0x00 or 0x01",
@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
          }
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
                      Just(SortKeyDerivation::Explicit),
-                     Just(SortKeyDerivation::Derived),
+                     Just(SortKeyDerivation::ExplicitKeysForbidden),
                  ]),
 -                proptest::option::of(proptest::collection::vec(any::<u8>(), 16..=17)),
 +                proptest::option::of(proptest::collection::vec(any::<u8>(), 0..=17)),
-+                proptest::option::of(proptest::collection::vec(any::<u8>(), 0..=17)),
+                 proptest::option::of(proptest::collection::vec(any::<u8>(), 0..=17)),
                  proptest::collection::btree_map(
                      arb_proprietary_key(),
-                     proptest::collection::vec(0u8..=255, 0..=8),
-@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
-                         unordered,
-                         derivation,
-                         seed,
-+                        uuid,
-                         proprietaries,
-                         unknowns,
-                     )| {
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
                              global.set_sort_key_derivation(derivation);
                          }
@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
 -                            global
 -                                .set_sort_seed(SortSeed::try_from(seed).expect("16 bytes or more"));
 +                            global.set_sort_seed(SortSeed::from(seed));
-+                        }
-+                        if let Some(uuid) = uuid {
-+                            global.set_uuid(TxUuid::from(uuid));
                          }
-                         global
-                     },
-@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
-                     PSBT_GLOBAL_TX_UNORDERED_SUBTYPE,
-                     PSBT_GLOBAL_SORT_SEED_SUBTYPE,
-                     PSBT_GLOBAL_SORT_KEY_DERIVATION_SUBTYPE,
-+                    PSBT_GLOBAL_TX_UUID_SUBTYPE,
-                 ] {
-                     shadowed
-                         .proprietaries
+                         if let Some(uuid) = uuid {
+                             global.set_uuid(TxUuid::from(uuid));
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
              }
  
@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
 -                        prop_assert_eq!(error, InvalidGlobal::SortSeed(InvalidSortSeed(seed)));
 -                    }
 -                }
+-            }
+-
+-            #[test]
+-            fn uuid_is_any_bytes(bytes in proptest::collection::vec(any::<u8>(), 0..=24)) {
+-                let v2 = v2_with_fields(&[(PSBT_GLOBAL_TX_UUID_SUBTYPE, bytes.clone())]);
+-                let global = Global::try_from(v2).expect("any bytes are a UUID");
 +            fn sort_seed_and_uuid_are_any_bytes(bytes in proptest::collection::vec(any::<u8>(), 0..=24)) {
 +                let v2 = v2_with_fields(&[
 +                    (PSBT_GLOBAL_SORT_SEED_SUBTYPE, bytes.clone()),
@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
 +                ]);
 +                let global = Global::try_from(v2).expect("any bytes are a seed and a UUID");
 +                prop_assert_eq!(global.sort_seed(), Some(bytes.as_slice()));
-+                prop_assert_eq!(global.uuid(), Some(bytes.as_slice()));
+                 prop_assert_eq!(global.uuid(), Some(bytes.as_slice()));
              }
          }
-     }
 
  ## crates/concurrent-psbt/src/psbt/tx.rs ##
 @@ crates/concurrent-psbt/src/psbt/tx.rs: use psbt_v2::v2::Psbt;
@@ crates/concurrent-psbt/src/psbt/tx.rs: pub enum UnorderedPsbtError {
      /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is `0x01`, so every sort key is
      /// derived, but the input spending this outpoint has a `PSBT_IN_SORT_KEY`.
      UnexpectedInputSortKey(OutPoint),
-     /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is `0x01`, so every sort key is
-     /// derived, but the output with this unique ID has a `PSBT_OUT_SORT_KEY`.
-     UnexpectedOutputSortKey(UniqueId),
--    /// Two inputs, or two outputs, have this explicit sort key.
--    DuplicateSortKey(Vec<u8>),
-+    /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is `0x00`, so every explicit sort key
-+    /// must be non-empty, but the input spending this outpoint has an empty
-+    /// `PSBT_IN_SORT_KEY`.
-+    EmptyInputSortKey(OutPoint),
-+    /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` is `0x00`, so every explicit sort key
-+    /// must be non-empty, but the output with this unique ID has an empty
-+    /// `PSBT_OUT_SORT_KEY`.
-+    EmptyOutputSortKey(UniqueId),
- }
- 
- impl From<DuplicateInput> for UnorderedPsbtError {
 @@ crates/concurrent-psbt/src/psbt/tx.rs: impl From<InvalidGlobal> for UnorderedPsbtError {
          match error {
              InvalidGlobal::UnorderedFlag(value) => Self::InvalidUnorderedFlag(value),
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl fmt::Display for UnorderedPsbtError
              Self::UnexpectedInputSortKey(outpoint) => write!(
                  f,
                  "the input spending {outpoint} has a sort key but PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x01"
-@@ crates/concurrent-psbt/src/psbt/tx.rs: impl fmt::Display for UnorderedPsbtError {
-                 "the output with unique ID {:02x?} has a sort key but PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x01",
-                 unique_id.as_bytes()
-             ),
--            Self::DuplicateSortKey(key) => write!(f, "duplicate sort key {key:02x?}"),
-+            Self::EmptyInputSortKey(outpoint) => write!(
-+                f,
-+                "the input spending {outpoint} has an empty sort key but PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x00"
-+            ),
-+            Self::EmptyOutputSortKey(unique_id) => write!(
-+                f,
-+                "the output with unique ID {:02x?} has an empty sort key but PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x00",
-+                unique_id.as_bytes()
-+            ),
-         }
-     }
- }
-@@ crates/concurrent-psbt/src/psbt/tx.rs: fn mark<V: PartialJoin>(field: &mut Option<JoinResult<V>>) {
- }
- 
- /// Mark every sort key if `derived`, since then no key may be explicit, and
--/// otherwise every key that another of the entries may also have. Return
--/// `true` if a key was marked.
--///
--/// A linear scan for each key: the entries are few, and the sets are private,
--/// so a lookup structure can replace it without changing callers.
-+/// every key that may be empty if `explicit`, since then every key must be
-+/// non-empty. Return `true` if a key was marked.
- fn mark_sort_keys<'a>(
-     keys: impl Iterator<Item = &'a mut Option<JoinResult<SortKey>>>,
-     derived: bool,
-+    explicit: bool,
- ) -> bool {
--    let mut keys: Vec<_> = keys.filter(|key| key.is_some()).collect();
--    let broken: Vec<bool> = (0..keys.len())
--        .map(|i| {
--            derived
--                || (0..keys.len()).any(|j| {
--                    j != i && values(keys[i]).any(|key| values(keys[j]).any(|other| key == other))
--                })
--        })
--        .collect();
-     let mut marked = false;
--    for (key, broken) in keys.iter_mut().zip(broken) {
--        if broken {
-+    for key in keys {
-+        let empty = || values(key).any(|key| key.as_bytes().is_empty());
-+        if key.is_some() && (derived || explicit && empty()) {
-             mark(key);
-             marked = true;
-         }
-@@ crates/concurrent-psbt/src/psbt/tx.rs: fn mark_sort_keys<'a>(
-     marked
- }
- 
--/// The entries whose sort keys are conflicts, with one of the values of each.
-+/// The entries whose sort keys are conflicts.
- fn marked_sort_keys<'a, K: 'a>(
-     entries: impl Iterator<Item = (&'a K, &'a Option<JoinResult<SortKey>>)>,
--) -> impl Iterator<Item = (&'a K, &'a [u8])> {
--    entries.filter_map(|(key, sort_key)| match sort_key {
--        Some(Err(conflict)) => conflict
--            .into_iter()
--            .next()
--            .map(|sort_key| (key, sort_key.as_bytes())),
--        _ => None,
--    })
-+) -> impl Iterator<Item = &'a K> {
-+    entries.filter_map(|(key, sort_key)| matches!(sort_key, Some(Err(_))).then_some(key))
- }
- 
- impl UnorderedPsbt {
 @@ crates/concurrent-psbt/src/psbt/tx.rs: impl UnorderedPsbt {
      /// joining it would leave conflicts.
      ///
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl UnorderedPsbt {
      /// [`UnorderedPsbtError::UnexpectedInputSortKey`] for the smallest outpoint
      /// whose input has a sort key, or
      /// [`UnorderedPsbtError::UnexpectedOutputSortKey`] for the smallest unique
--    /// ID whose output has one. Otherwise returns
--    /// [`UnorderedPsbtError::DuplicateSortKey`] for the smallest sort key that
--    /// repeats among the inputs, then among the outputs.
-+    /// ID whose output has one. Under derivation `0x00`, returns
-+    /// [`UnorderedPsbtError::EmptyInputSortKey`] for the smallest outpoint
-+    /// whose input has an empty sort key, or
-+    /// [`UnorderedPsbtError::EmptyOutputSortKey`] for the smallest unique ID
-+    /// whose output has one.
-     pub fn try_from_psbt(psbt: Psbt) -> Result<Self, UnorderedPsbtError> {
-         ResultUnorderedPsbt::try_from_psbt(psbt)?
-             .try_unwrap()
 @@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
      }
  
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
 -    /// have. The derivation is marked with them, since together they are
 -    /// invalid.
 +    /// `PSBT_GLOBAL_SORT_KEY_DERIVATION` as conflicts: every explicit sort key
-+    /// if it may be `0x01`, and every empty one if it may be `0x00`. The
-+    /// derivation is marked with them, since together they are invalid.
++    /// if it may be `0x01`, and an explicit sort key that another input, or
++    /// another output, may also have. The derivation is marked with them, since
++    /// together they are invalid.
      ///
      /// The rules read the values a field may hold, which joins only add to, so
      /// a marked field stays marked under later joins. Marking keeps the values,
 @@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
          let may_be =
              |derivation| values(&self.global.sort_key_derivation).any(|value| *value == derivation);
-         let derived = may_be(SortKeyDerivation::Derived);
+         let derived = may_be(SortKeyDerivation::ExplicitKeysForbidden);
 -        let seed_broken = may_be(SortKeyDerivation::Explicit) && self.global.sort_seed.is_some();
 -        if seed_broken {
 -            mark(&mut self.global.sort_seed);
 -        }
-+        let explicit = may_be(SortKeyDerivation::Explicit);
          let inputs_broken = mark_sort_keys(
              self.inputs
                  .0
-                 .entries_mut()
-                 .map(|(_, input)| &mut input.sort_key),
-             derived,
-+            explicit,
-         );
-         let outputs_broken = mark_sort_keys(
-             self.outputs
 @@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
-                 .entries_mut()
                  .map(|(_, output)| &mut output.sort_key),
              derived,
-+            explicit,
          );
 -        if seed_broken || inputs_broken || outputs_broken {
 +        if inputs_broken || outputs_broken {
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
 -        if matches!(self.global.sort_seed, Some(Err(_))) {
 -            return UnorderedPsbtError::UnexpectedSortSeed;
 -        }
--        let inputs = || {
--            marked_sort_keys(
--                self.inputs
--                    .0
--                    .entries()
--                    .map(|(outpoint, input)| (outpoint, &input.sort_key)),
--            )
--        };
--        let outputs = || {
-+        let outpoint = marked_sort_keys(
-+            self.inputs
-+                .0
-+                .entries()
-+                .map(|(outpoint, input)| (outpoint, &input.sort_key)),
-+        )
-+        .min()
-+        .copied();
-+        let unique_id = || {
+         let inputs = || {
              marked_sort_keys(
-                 self.outputs
-                     .0
-                     .entries()
-                     .map(|(unique_id, output)| (unique_id, &output.sort_key)),
-             )
-+            .min_by_key(|unique_id| unique_id.as_bytes())
-+            .expect("a sort key was marked")
-+            .clone()
-         };
--        if values(&self.global.sort_key_derivation)
--            .any(|value| *value == SortKeyDerivation::Derived)
--        {
--            return match inputs().map(|(outpoint, _)| *outpoint).min() {
--                Some(outpoint) => UnorderedPsbtError::UnexpectedInputSortKey(outpoint),
--                None => UnorderedPsbtError::UnexpectedOutputSortKey(
--                    outputs()
--                        .map(|(unique_id, _)| unique_id)
--                        .min_by_key(|unique_id| unique_id.as_bytes())
--                        .expect("a sort key under derivation 0x01 was marked")
--                        .clone(),
--                ),
--            };
-+        let derived = values(&self.global.sort_key_derivation)
-+            .any(|value| *value == SortKeyDerivation::Derived);
-+        match (derived, outpoint) {
-+            (true, Some(outpoint)) => UnorderedPsbtError::UnexpectedInputSortKey(outpoint),
-+            (true, None) => UnorderedPsbtError::UnexpectedOutputSortKey(unique_id()),
-+            (false, Some(outpoint)) => UnorderedPsbtError::EmptyInputSortKey(outpoint),
-+            (false, None) => UnorderedPsbtError::EmptyOutputSortKey(unique_id()),
-         }
--        let smallest = |keys: &mut dyn Iterator<Item = &[u8]>| keys.min().map(<[u8]>::to_vec);
--        UnorderedPsbtError::DuplicateSortKey(
--            smallest(&mut inputs().map(|(_, key)| key))
--                .or_else(|| smallest(&mut outputs().map(|(_, key)| key)))
--                .expect("a repeated sort key was marked"),
--        )
-     }
- 
-     /// Return `true` if every field across global, inputs, and outputs is conflict-free.
+                 self.inputs
 @@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
  #[cfg_attr(coverage_nightly, coverage(off))]
  mod tests {
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                  (
                      UnorderedPsbtError::UnexpectedInputSortKey(outpoint(1)),
                      format!(
-@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
-                         .to_string(),
-                 ),
-                 (
--                    UnorderedPsbtError::DuplicateSortKey(vec![0xab]),
--                    "duplicate sort key [ab]".to_string(),
-+                    UnorderedPsbtError::EmptyInputSortKey(outpoint(1)),
-+                    format!(
-+                        "the input spending {} has an empty sort key but PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x00",
-+                        outpoint(1)
-+                    ),
-+                ),
-+                (
-+                    UnorderedPsbtError::EmptyOutputSortKey(UniqueId::new(vec![0xab])),
-+                    "the output with unique ID [ab] has an empty sort key but PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x00"
-+                        .to_string(),
-                 ),
-             ];
-             for (error, message) in cases {
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                      ),
                      UnorderedPsbtError::InvalidSortKeyDerivation(vec![2]),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                  }
                  global
              };
--            let input = |txid_byte, sort_key: Option<u8>| {
-+            let input = |txid_byte, sort_key: Option<&[u8]>| {
-                 let mut input = Input::new(&outpoint(txid_byte));
-                 if let Some(key) = sort_key {
--                    input.set_sort_key(SortKey::try_from(vec![key]).unwrap());
-+                    input.set_sort_key(SortKey::try_from(key.to_vec()).unwrap());
-                 }
-                 psbt_v2::v2::Input::from(input)
-             };
--            let output = |uid, sort_key: Option<u8>| {
-+            let output = |uid, sort_key: Option<&[u8]>| {
-                 let mut output =
-                     Output::new(UniqueId::new(vec![uid]), Amount::ZERO, ScriptBuf::new());
-                 if let Some(key) = sort_key {
--                    output.set_sort_key(SortKey::try_from(vec![key]).unwrap());
-+                    output.set_sort_key(SortKey::try_from(key.to_vec()).unwrap());
-                 }
-                 psbt_v2::v2::Output::from(output)
-             };
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                      v2_psbt_with(sighash_single, vec![], vec![]),
                      Err(UnorderedPsbtError::UnorderedSighashSingle),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 -                ),
                  (
                      v2_psbt_with(
-                         global(Some(Derived), true),
--                        vec![input(1, None), input(2, Some(0))],
--                        vec![],
-+                        vec![input(1, None), input(2, Some(&[0])), input(3, Some(&[]))],
-+                        vec![output(1, Some(&[0]))],
-                     ),
-                     Err(UnorderedPsbtError::UnexpectedInputSortKey(outpoint(2))),
-                 ),
-                 (
-                     v2_psbt_with(
--                        global(Some(Derived), true),
-+                        global(Some(Derived), false),
-                         vec![],
--                        vec![output(1, None), output(2, Some(0))],
-+                        vec![output(1, None), output(2, Some(&[]))],
-                     ),
-                     Err(UnorderedPsbtError::UnexpectedOutputSortKey(UniqueId::new(
-                         vec![2],
-@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
-                 (
-                     v2_psbt_with(
-                         global(Some(Explicit), false),
--                        vec![input(1, Some(0)), input(2, Some(0))],
--                        vec![],
-+                        vec![
-+                            input(1, Some(&[0])),
-+                            input(2, Some(&[])),
-+                            input(3, Some(&[])),
-+                        ],
-+                        vec![output(1, Some(&[]))],
-                     ),
--                    Err(UnorderedPsbtError::DuplicateSortKey(vec![0])),
-+                    Err(UnorderedPsbtError::EmptyInputSortKey(outpoint(2))),
-                 ),
-                 (
-                     v2_psbt_with(
--                        global(Some(Explicit), false),
--                        vec![],
--                        vec![output(1, Some(0)), output(2, Some(0))],
-+                        global(Some(Explicit), true),
-+                        vec![input(1, Some(&[0]))],
-+                        vec![
-+                            output(1, Some(&[0])),
-+                            output(3, Some(&[])),
-+                            output(2, Some(&[])),
-+                        ],
-                     ),
--                    Err(UnorderedPsbtError::DuplicateSortKey(vec![0])),
-+                    Err(UnorderedPsbtError::EmptyOutputSortKey(UniqueId::new(vec![
-+                        2,
-+                    ]))),
-                 ),
--                // Seeded derivation accepts entries without explicit keys.
-+                // Derivation 0x01 accepts entries without explicit keys.
-                 (
-                     v2_psbt_with(
-                         global(Some(Derived), true),
+                         global(Some(ExplicitKeysForbidden), true),
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                      ),
                      Ok(()),
                  ),
 -                // An input and an output may share a sort key.
-+                // Derivation 0x00 accepts a seed, missing keys, which may be
-+                // added later, and keys that repeat.
++                // Derivation 0x00 accepts a seed, and an input and an output
++                // may share a sort key.
                  (
                      v2_psbt_with(
 -                        global(Some(Explicit), false),
--                        vec![input(1, Some(0))],
--                        vec![output(1, Some(0))],
 +                        global(Some(Explicit), true),
-+                        vec![input(1, Some(&[0])), input(2, Some(&[0])), input(3, None)],
-+                        vec![output(1, Some(&[0])), output(2, Some(&[0]))],
-+                    ),
-+                    Ok(()),
-+                ),
-+                // Without a derivation, keys may be empty or repeat.
-+                (
-+                    v2_psbt_with(
-+                        global(None, true),
-+                        vec![input(1, Some(&[])), input(2, Some(&[]))],
-+                        vec![output(1, Some(&[]))],
+                         vec![input(1, Some(0))],
+                         vec![output(1, Some(0))],
                      ),
-                     Ok(()),
-                 ),
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
  
          #[test]
          fn joins_that_break_the_sort_rules_mark_the_fields_that_break_them() {
-+            let empty_key = SortKey::try_from(vec![]).unwrap();
-+            let keyed = |byte, key: &SortKey| {
-+                let mut input = Input::new(&outpoint(byte));
-+                input.set_sort_key(key.clone());
-+                let mut psbt = singleton(byte);
-+                psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
-+                psbt
-+            };
-             let explicit = {
+-            let explicit = {
 -                let mut psbt = singleton(1);
-+                let mut psbt = singleton(2);
-                 psbt.global
-                     .set_sort_key_derivation(SortKeyDerivation::Explicit);
-                 psbt.wrap()
-             };
+-                psbt.global
+-                    .set_sort_key_derivation(SortKeyDerivation::Explicit);
+-                psbt.wrap()
+-            };
 -            let seed = SortSeed::try_from(vec![0; 16]).unwrap();
 -            let seeded = {
 -                let mut psbt = singleton(1);
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 -                psbt.wrap()
 -            };
 -            let joined = explicit.join(seeded);
-+            let joined = explicit.join(keyed(1, &empty_key).wrap());
-             assert_eq!(
-                 joined.global.sort_key_derivation,
-                 Some(Err(Conflict::from_values([SortKeyDerivation::Explicit])))
-             );
+-            assert_eq!(
+-                joined.global.sort_key_derivation,
+-                Some(Err(Conflict::from_values([SortKeyDerivation::Explicit])))
+-            );
 -            assert_eq!(
 -                joined.global.sort_seed,
 -                Some(Err(Conflict::from_values([seed])))
 -            );
+-            assert!(joined.clone().try_unwrap().is_err());
+-
+-            // Without a derivation, only the repeated keys are marked.
+             let key = SortKey::try_from(vec![0]).unwrap();
+             let keyed = |byte| {
+                 let mut input = Input::new(&outpoint(byte));
+                 input.set_sort_key(key.clone());
+                 let mut psbt = singleton(byte);
+                 psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
++                psbt
++            };
++            let derived = {
++                let mut psbt = singleton(2);
++                psbt.global
++                    .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden);
+                 psbt.wrap()
+             };
+-            let joined = keyed(1).join(keyed(2));
++            let joined = derived.join(keyed(1).wrap());
++            assert_eq!(
++                joined.global.sort_key_derivation,
++                Some(Err(Conflict::from_values([
++                    SortKeyDerivation::ExplicitKeysForbidden
++                ])))
++            );
 +            for (spent, input) in joined.inputs.0.entries() {
-+                let expected = (*spent == outpoint(1))
-+                    .then(|| Err(Conflict::from_values([empty_key.clone()])));
++                let expected =
++                    (*spent == outpoint(1)).then(|| Err(Conflict::from_values([key.clone()])));
 +                assert_eq!(input.sort_key, expected);
 +            }
-             assert!(joined.clone().try_unwrap().is_err());
- 
--            // Without a derivation, only the repeated keys are marked.
--            let key = SortKey::try_from(vec![0]).unwrap();
--            let keyed = |byte| {
--                let mut input = Input::new(&outpoint(byte));
--                input.set_sort_key(key.clone());
--                let mut psbt = singleton(byte);
--                psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
--                psbt.wrap()
--            };
--            let joined = keyed(1).join(keyed(2));
--            assert_eq!(joined.global.sort_key_derivation, None);
--            for (_, input) in joined.inputs.0.entries() {
--                assert_eq!(
--                    input.sort_key,
--                    Some(Err(Conflict::from_values([key.clone()])))
--                );
--            }
--            assert!(!joined.is_ok());
-+            // Without a derivation, nothing is marked: keys may be empty or
-+            // repeat, and a seed is allowed.
-+            let mut seeded = keyed(2, &empty_key);
++            assert!(joined.clone().try_unwrap().is_err());
++
++            // Without a derivation, only the repeated keys are marked, and a
++            // seed is allowed.
++            let mut seeded = keyed(2);
 +            seeded.global.set_sort_seed(SortSeed::from(vec![0; 16]));
-+            let joined = keyed(1, &empty_key).wrap().join(seeded.wrap());
-+            assert!(joined.is_ok());
-         }
- 
-         #[test]
++            let joined = keyed(1).wrap().join(seeded.wrap());
+             assert_eq!(joined.global.sort_key_derivation, None);
++            assert_eq!(
++                joined.global.sort_seed,
++                Some(Ok(SortSeed::from(vec![0; 16])))
++            );
+             for (_, input) in joined.inputs.0.entries() {
+                 assert_eq!(
+                     input.sort_key,
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
      #[cfg(feature = "prop-tests")]
      mod prop {
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
          use bitcoin::transaction;
          use proptest::prelude::*;
  
-@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
-             arb_psbt(true)
-         }
- 
--        /// Drop the keys of `keep_none`, and each key already kept.
--        fn distinct_keys(keep_none: bool) -> impl FnMut(Option<u8>) -> Option<SortKey> {
--            let mut seen = std::collections::HashSet::new();
-+        /// The sort key drawn as `key`, empty for `0`, if `derivation` allows
-+        /// it: none under `0x01`, and no empty one under `0x00`.
-+        fn allowed_key(
-+            sort_fields: bool,
-+            derivation: Option<SortKeyDerivation>,
-+        ) -> impl Fn(Option<u8>) -> Option<SortKey> {
-             move |key| {
--                key.filter(|key| !keep_none && seen.insert(*key))
--                    .map(|key| SortKey::try_from(vec![key]).expect("one byte"))
-+                let key = key
-+                    .filter(|_| sort_fields && derivation != Some(SortKeyDerivation::Derived))
-+                    .map(|key| if key == 0 { vec![] } else { vec![key] })?;
-+                let empty_forbidden = derivation == Some(SortKeyDerivation::Explicit);
-+                (!(empty_forbidden && key.is_empty()))
-+                    .then(|| SortKey::try_from(key).expect("at most one byte"))
-             }
-         }
- 
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                      Just(SortKeyDerivation::Explicit),
-                     Just(SortKeyDerivation::Derived),
+                     Just(SortKeyDerivation::ExplicitKeysForbidden),
                  ]),
 -                proptest::option::of(0u8..2), // sort seed byte
 +                proptest::option::of(0u8..2), // sort seed: empty or 16 bytes
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                          use bitcoin::hashes::Hash;
  
                          let derivation = derivation.filter(|_| sort_fields);
--                        let no_keys =
--                            !sort_fields || derivation == Some(SortKeyDerivation::Derived);
--
--                        let mut input_key = distinct_keys(no_keys);
-+                        let input_key = allowed_key(sort_fields, derivation);
-                         let inputs = InputSet::try_from_inputs(input_specs.into_iter().map(
-                             |((txid_byte, vout), key)| {
-                                 let mut input = Input::new(&bitcoin::OutPoint {
-@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
-                         ))
-                         .expect("distinct outpoints");
- 
--                        let mut output_key = distinct_keys(no_keys);
-+                        let output_key = allowed_key(sort_fields, derivation);
-                         let outputs = OutputSet::try_from_outputs(output_specs.into_iter().map(
-                             |(uid_byte, key)| {
-                                 let mut output = Output::new(
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                          if let Some(derivation) = derivation {
                              global.set_sort_key_derivation(derivation);
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 -                    (UnorderedPsbtError::UnexpectedSortSeed, None),
                      (UnorderedPsbtError::UnexpectedInputSortKey(outpoint), Some(outpoint.to_string())),
                      (UnorderedPsbtError::UnexpectedOutputSortKey(UniqueId::new(value.clone())), Some(bytes.clone())),
--                    (UnorderedPsbtError::DuplicateSortKey(value.clone()), Some(format!("{value:02x?}"))),
-+                    (UnorderedPsbtError::EmptyInputSortKey(outpoint), Some(outpoint.to_string())),
-+                    (UnorderedPsbtError::EmptyOutputSortKey(UniqueId::new(value.clone())), Some(bytes.clone())),
-                     // The unique ID is opaque bytes, so the message leaves it out.
-                     (UnorderedPsbtError::DuplicateOutputUniqueId(UniqueId::new(value)), None),
-                 ];
+                     (UnorderedPsbtError::DuplicateSortKey(value.clone()), Some(format!("{value:02x?}"))),
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
              fn malformed_sort_fields_reject_the_psbt(
                  a in arb_unordered_psbt(),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                  );
              }
  
-@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
-                 prop_assert_eq!(ResultUnorderedPsbt::try_from_psbt(psbt).map(|_| ()), expected);
-             }
- 
-+            /// Under derivation `0x01` the smallest entry with a sort key, and
-+            /// under `0x00` the smallest with an empty one, is rejected. Keys
-+            /// may repeat, and without a derivation anything goes. Entry `i`
-+            /// spends output `i` of the null txid or has unique ID `[i]`, so the
-+            /// smallest is the first.
-             #[test]
--            fn try_from_psbt_rejects_the_smallest_repeated_sort_key(
--                keys in proptest::collection::vec(0u8..4, 0..=5),
-+            fn try_from_psbt_rejects_the_smallest_entry_breaking_the_sort_rules(
-+                keys in proptest::collection::vec(proptest::option::of(0usize..=2), 0..=5),
-+                derivation in proptest::option::of(prop_oneof![
-+                    Just(SortKeyDerivation::Explicit),
-+                    Just(SortKeyDerivation::Derived),
-+                ]),
-                 on_outputs in proptest::bool::ANY,
-             ) {
--                let repeated = keys
--                    .iter()
--                    .filter(|key| keys.iter().filter(|other| other == key).count() > 1)
--                    .min()
--                    .copied();
--                let sort_key = |key| SortKey::try_from(vec![key]).expect("one byte");
-+                let breaks = |key: &Option<usize>| match derivation {
-+                    Some(SortKeyDerivation::Derived) => key.is_some(),
-+                    Some(SortKeyDerivation::Explicit) => *key == Some(0),
-+                    None => false,
-+                };
-+                let first = keys.iter().position(breaks);
-+                let sort_key = |len| SortKey::try_from(vec![7; len]).expect("at most two bytes");
-                 let entries = (0u8..).zip(keys);
--                let psbt = if on_outputs {
-+                let mut global = unordered_global();
-+                if let Some(derivation) = derivation {
-+                    global.set_sort_key_derivation(derivation);
-+                }
-+                let (psbt, expected) = if on_outputs {
-                     let outputs = entries
-                         .map(|(uid, key)| {
-                             let mut output = Output::new(
-@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
-                                 bitcoin::Amount::ZERO,
-                                 bitcoin::ScriptBuf::new(),
-                             );
--                            output.set_sort_key(sort_key(key));
-+                            if let Some(len) = key {
-+                                output.set_sort_key(sort_key(len));
-+                            }
-                             output.into()
-                         })
-                         .collect();
--                    v2_psbt(vec![], outputs)
-+                    let expected = first.map(|index| {
-+                        let unique_id = UniqueId::new(vec![index as u8]);
-+                        match derivation {
-+                            Some(SortKeyDerivation::Derived) => UnorderedPsbtError::UnexpectedOutputSortKey(unique_id),
-+                            _ => UnorderedPsbtError::EmptyOutputSortKey(unique_id),
-+                        }
-+                    });
-+                    (v2_psbt_with(global, vec![], outputs), expected)
-                 } else {
-                     let inputs = entries
-                         .map(|(vout, key)| {
-                             let mut input = Input::new(&OutPoint { vout: vout.into(), ..OutPoint::null() });
--                            input.set_sort_key(sort_key(key));
-+                            if let Some(len) = key {
-+                                input.set_sort_key(sort_key(len));
-+                            }
-                             input.into()
-                         })
-                         .collect();
--                    v2_psbt(inputs, vec![])
-+                    let expected = first.map(|index| {
-+                        let outpoint = OutPoint { vout: index as u32, ..OutPoint::null() };
-+                        match derivation {
-+                            Some(SortKeyDerivation::Derived) => UnorderedPsbtError::UnexpectedInputSortKey(outpoint),
-+                            _ => UnorderedPsbtError::EmptyInputSortKey(outpoint),
-+                        }
-+                    });
-+                    (v2_psbt_with(global, inputs, vec![]), expected)
-                 };
-                 prop_assert_eq!(
-                     UnorderedPsbt::try_from_psbt(psbt).map(|_| ()),
--                    repeated.map_or(Ok(()), |key| Err(UnorderedPsbtError::DuplicateSortKey(vec![key])))
-+                    expected.map_or(Ok(()), Err)
-                 );
-             }
- 
 
  ## crates/concurrent-psbt/src/roles/constructor/error.rs ##
 @@ crates/concurrent-psbt/src/roles/constructor/error.rs: pub enum ConstructorError {
@@ crates/concurrent-psbt/src/roles/constructor/error.rs: pub enum ConstructorError
      /// not marked unordered, its unordered or sort flags are malformed, its
 -    /// sort fields break its sort mode or repeat a sort key, or its sort seed,
 -    /// a sort key, or an output's unique ID has an invalid size.
-+    /// sort keys break its sort key derivation, or a sort key or an output's
-+    /// unique ID has an invalid size.
++    /// sort keys break its sort key derivation or repeat, or a sort key or an
++    /// output's unique ID has an invalid size.
      Unordered(UnorderedPsbtError),
      /// The PSBT's sort fields don't select the requested sort mode.
      SortMode(SortModeError),
@@ crates/concurrent-psbt/src/roles/constructor/error.rs: impl From<UnorderedPsbtEr
 -            | UnorderedPsbtError::UnexpectedSortSeed
              | UnorderedPsbtError::UnexpectedInputSortKey(_)
              | UnorderedPsbtError::UnexpectedOutputSortKey(_)
--            | UnorderedPsbtError::DuplicateSortKey(_)
-+            | UnorderedPsbtError::EmptyInputSortKey(_)
-+            | UnorderedPsbtError::EmptyOutputSortKey(_)
-             | UnorderedPsbtError::InvalidOutputUniqueId(_)) => Self::Unordered(error),
-         }
-     }
-@@ crates/concurrent-psbt/src/roles/constructor/error.rs: mod tests {
-                 ),
-                 (
-                     ConstructorError::SortMode(SortModeError::UnexpectedSortKey),
--                    "a sort key is set in derived-only sort mode",
-+                    "a sort key is set in a sort mode that forbids explicit keys",
-                 ),
-             ];
-             for (error, message) in cases {
+             | UnorderedPsbtError::DuplicateSortKey(_)
 
  ## crates/concurrent-psbt/src/roles/constructor/mod.rs ##
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: use std::marker::PhantomData;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: use std::marker::PhantomDat
  use crate::lattice::join::Join;
  use crate::output::{Output, OutputSet, UniqueId};
  use crate::sorter::{
--    BothModifiable, DerivedOnly, InputsModifiable, Mixed, Modifiable, OutputsModifiable,
+-    BothModifiable, ExplicitKeysForbidden, InputsModifiable, Mixed, Modifiable, OutputsModifiable,
 -    SeedConflict, Seeded, SortMode, Sorter, Unmodifiable, check_flags, check_sort_mode, join_seed,
 +    BothModifiable, InputsModifiable, Modifiable, OutputsModifiable, SeedConflict, Seeded,
 +    SortMode, Sorter, Unmodifiable, UuidError, check_flags, check_sort_mode, join_seed, join_uuid,
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M, S> Constructor<M, S
      }
  }
  
--impl<M> Constructor<M, DerivedOnly> {
+-impl<M> Constructor<M, ExplicitKeysForbidden> {
 -    /// Join `seed` into `PSBT_GLOBAL_SORT_SEED`: set it if unset, and keep it
 -    /// if it is already `seed`.
 +impl<M, S> Constructor<M, S>
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M, S> Constructor<M, S
 -    pub fn try_set_seed(
 -        self,
 -        seed: SortSeed,
--    ) -> Result<Constructor<M, Seeded<DerivedOnly>>, SeedConflict> {
+-    ) -> Result<Constructor<M, Seeded<ExplicitKeysForbidden>>, SeedConflict> {
 -        self.try_with_seed(seed)
 +    pub fn try_set_uuid(mut self, uuid: TxUuid) -> Result<Constructor<M, Seeded<S>>, UuidError> {
 +        join_uuid(&mut self.0.global, uuid)?;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<M, S> Constructor<M, S
      }
  }
  
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<S: SortMode> Constructor<BothModifiable, S> {
-     ///
-     /// # Errors
-     /// Returns [`ConstructorError::Conflict`] if the two disagree, or if the
--    /// input has a sort key in [`DerivedOnly`] mode, which makes the key a
--    /// conflict.
-+    /// input has a sort key in [`ExplicitKeysForbidden`] mode or an empty one
-+    /// in [`ExplicitKeysRequired`] mode, which makes the key a conflict.
-     pub fn input(self, input: Input) -> Result<Self, ConstructorError> {
-         self.add_input(input)
-     }
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<S: SortMode> Constructor<BothModifiable, S> {
-     ///
-     /// # Errors
-     /// Returns [`ConstructorError::Conflict`] if it disagrees with the output
--    /// already holding that ID, or if it has a sort key in [`DerivedOnly`]
--    /// mode, which makes the key a conflict.
-+    /// already holding that ID, or if it has a sort key in
-+    /// [`ExplicitKeysForbidden`] mode or an empty one in
-+    /// [`ExplicitKeysRequired`] mode, which makes the key a conflict.
-     pub fn output(self, output: Output) -> Result<Self, ConstructorError> {
-         self.add_output(output)
-     }
-@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: impl<S: SortMode> Constructor<InputsModifiable, S> {
-     ///
-     /// # Errors
… (truncated)

///
/// # Ordering
///
/// Every mode sorts by explicit sort key, a missing key counting as empty,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Explicit mode does not treat missing keys as empty

ExplicitKeysRequired sorts with explicit = true, so input_sort_key and output_sort_key return MissingInputSortKey or MissingOutputSortKey when a key is absent; the Sorter doc's "every mode sorts by explicit sort key, a missing key counting as empty" is false for this mode.

oakagent · automated · 2ecafcf

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

these requirements are independent, sorting by empty sort keys makes sense in mixed mode

the restriction on the explicit keys themselves, required to be all empty or all non-empty changes the meaning of the sorting but can be checked independently as a precondition before using the same exact sorting procedure, ignoring explicit sort keys when those are specified to be forbidden is an optimization not a correctness issue

pub struct UuidTag = hash_str("concurrent-psbt/uuid");

/// A sort key derived via tagged hash: `H(seed || identifier)`.
/// The tagged hash of `PSBT_GLOBAL_TX_UUID`, empty if unset.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

UuidHash doc says empty when unset, but sorting errors

sort_seed returns MissingUuid when PSBT_GLOBAL_TX_UUID is unset or empty, so the UuidHash doc's "empty if unset" is wrong: an unset UUID is an error, not an empty hash.

Returns [SortError::MissingUuid] if the UUID is unset or empty.

— fungi-protocol/concurrent-psbt@93007c2 · crates/concurrent-psbt/src/roles/sorter/key.rs#L51

The tagged hash of PSBT_GLOBAL_SORT_SEED, empty if unset.

— fungi-protocol/concurrent-psbt@93007c2 · crates/concurrent-psbt/src/roles/sorter/key.rs#L21

oakagent · automated · 2ecafcf

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

my suggestion is to treat that is required for sorting

we could make sorting generate a random UUID if it's not already set which would not be consistent across replicas, this seems reasonable since deriving a consistent order at that point would require transmitting either the seed or the sort order to the other replicas prior to signing

creator: v2::Creator::new(),
sort_key_derivation: None,
seed: None,
uuid: TxUuid::generate(),

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Cloned Creator breaks fresh-UUID guarantee

Creator derives Clone, but TxUuid::generate() is called in new, so PSBTs built from clones carry the same UUID; the doc's "fresh one on every PSBT" is false.

oakagent · automated · 2ecafcf

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

it doesn't really make sense to use Clone but regardless that is intentional, if a creator was generated, and multiple copies of "the same" PSBT are then allowed to diverge, they should always be mergeable and in that sense the UUID refers to the same shared mutable state

@github-actions

Copy link
Copy Markdown
range-diff for force push 2ecafcff2c → ae9b191a62 November 15, 2026 10:20 UTC: 3 modified, 2 unchanged; 5 commits; same base 3d413230fb

reproduce: git range-diff 3d41323..2ecafcf 3d41323..ae9b191

1:  8a7ebb21cc +200 -173 7f = 1:  8a7ebb21cc +200 -173 7f rename sort modes for the explicit keys they allow
2:  818eb39301 +107   -7 2f = 2:  818eb39301 +107   -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  93007c2c86 +962 -958 9f ! 3:  75aaae7a7d +965 -960 9f derive sort keys from the tx UUID in every mode
4:  eef5e3b673 +118 -149 5f ! 4:  ca3528a45b +121 -152 5f allow repeated explicit sort keys
5:  2ecafcff2c +136  -51 6f ! 5:  ae9b191a62 +136  -51 6f require non-empty explicit sort keys under derivation 0x00
3: 93007c2c86 ! 3: 75aaae7a7d derive sort keys from the tx UUID in every mode
@@ crates/concurrent-psbt/src/roles/sorter/order.rs
      apply_permutation(&mut inputs, &mut input_keys);
      apply_permutation(&mut outputs, &mut output_keys);
  
+@@ crates/concurrent-psbt/src/roles/sorter/order.rs: where
+ ///
+ /// 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;
4: eef5e3b673 ! 4: ca3528a45b allow repeated explicit sort keys
@@ Commit message
     duplicate-key check: UnorderedPsbtError::DuplicateSortKey, and the
     linear scan it ran on every join.
 
+    A key is now marked only under a derivation, so mark is never handed
+    an unset field. It becomes a single Option::map, leaving no unreachable
+    arm for coverage to miss.
+
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl fmt::Display for UnorderedPsbtError
          }
      }
  }
-@@ crates/concurrent-psbt/src/psbt/tx.rs: fn mark<V: PartialJoin>(field: &mut Option<JoinResult<V>>) {
-     }
+@@ crates/concurrent-psbt/src/psbt/tx.rs: fn values<V: PartialJoin>(field: &Option<JoinResult<V>>) -> std::slice::Iter<'_,
+ /// later join. This is the join with the empty conflict, so marking a field
+ /// twice is marking it once.
+ fn mark<V: PartialJoin>(field: &mut Option<JoinResult<V>>) {
+-    if let Some(result) = field.take() {
+-        *field = Some(result.join(Err(Conflict::from_values([]))));
+-    }
++    *field = field
++        .take()
++        .map(|result| result.join(Err(Conflict::from_values([]))));
  }
  
 -/// Mark every sort key if `derived`, since then no key may be explicit, and
5: 2ecafcff2c ! 5: ae9b191a62 require non-empty explicit sort keys under derivation 0x00
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl fmt::Display for UnorderedPsbtError
      }
  }
 @@ crates/concurrent-psbt/src/psbt/tx.rs: fn mark<V: PartialJoin>(field: &mut Option<JoinResult<V>>) {
-     }
+         .map(|result| result.join(Err(Conflict::from_values([]))));
  }
  
 -/// Mark every sort key if `derived`, since then no key may be explicit.

@github-actions

Copy link
Copy Markdown
range-diff for force push ae9b191a62 → 62c63bea9a November 15, 2026 12:51 UTC: 1 modified, 4 unchanged; 5 commits; base 3d413230fb → f330b6a12f (diverged, 4 ahead and 4 behind)

reproduce: git range-diff 3d41323..ae9b191 f330b6a..62c63be

1:  8a7ebb21cc +200 -173 7f = 1:  a6aee228c8 +200 -173 7f rename sort modes for the explicit keys they allow
2:  818eb39301 +107   -7 2f = 2:  1fbef59f6e +107   -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  75aaae7a7d +965 -960 9f ! 3:  5babe1a6d2 +962 -958 9f derive sort keys from the tx UUID in every mode
4:  ca3528a45b +121 -152 5f = 4:  d845c46319 +121 -152 5f allow repeated explicit sort keys
5:  ae9b191a62 +136  -51 6f = 5:  62c63bea9a +136  -51 6f require non-empty explicit sort keys under derivation 0x00
3: 75aaae7a7d ! 3: 5babe1a6d2 derive sort keys from the tx UUID in every mode
@@ crates/concurrent-psbt/src/roles/sorter/order.rs
      apply_permutation(&mut inputs, &mut input_keys);
      apply_permutation(&mut outputs, &mut output_keys);
  
-@@ crates/concurrent-psbt/src/roles/sorter/order.rs: where
- ///
- /// 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-actions

Copy link
Copy Markdown
range-diff for force push ae9b191a62 → 62c63bea9a November 15, 2026 12:51 UTC: 1 modified, 4 unchanged; 5 commits; base 3d413230fb → f330b6a12f (diverged, 4 ahead and 4 behind)

reproduce: git range-diff 3d41323..ae9b191 f330b6a..62c63be

1:  8a7ebb21cc +200 -173 7f = 1:  a6aee228c8 +200 -173 7f rename sort modes for the explicit keys they allow
2:  818eb39301 +107   -7 2f = 2:  1fbef59f6e +107   -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  75aaae7a7d +965 -960 9f ! 3:  5babe1a6d2 +962 -958 9f derive sort keys from the tx UUID in every mode
4:  ca3528a45b +121 -152 5f = 4:  d845c46319 +121 -152 5f allow repeated explicit sort keys
5:  ae9b191a62 +136  -51 6f = 5:  62c63bea9a +136  -51 6f require non-empty explicit sort keys under derivation 0x00
3: 75aaae7a7d ! 3: 5babe1a6d2 derive sort keys from the tx UUID in every mode
@@ crates/concurrent-psbt/src/roles/sorter/order.rs
      apply_permutation(&mut inputs, &mut input_keys);
      apply_permutation(&mut outputs, &mut output_keys);
  
-@@ crates/concurrent-psbt/src/roles/sorter/order.rs: where
- ///
- /// 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

creator 5f4ab3b sort-uuid 000109c +/-
100% 100% 0%
View coverage of the 10 most impacted files.
File creator 5f4ab3b sort-uuid 000109c +/-
crates/concurre.../src/psbt/tx.rs 0% 100% +100%
crates/concurre...bt/keyed_set.rs 0% 100% +100%
crates/concurre.../psbt/global.rs 0% 100% +100%
crates/concurre...structor/mod.rs 0% 100% +100%
crates/concurre...s/sorter/mod.rs 0% 100% +100%
crates/concurre...sorter/error.rs 0% 100% +100%
crates/concurre...bt/input_set.rs 0% 100% +100%
crates/concurre...t/output_set.rs 0% 100% +100%
crates/concurre...oles/creator.rs 0% 100% +100%
crates/concurre...s/sorter/key.rs 0% 100% +100%

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


Updated November 16, 2026 23:47 UTC

@github-actions

Copy link
Copy Markdown
range-diff for force push 62c63bea9a → 23287ff1ed November 15, 2026 17:56 UTC: 4 modified, 1 unchanged; 5 commits; same base f330b6a12f

reproduce: git range-diff f330b6a..62c63be f330b6a..23287ff

1:  a6aee228c8 +200 -173 7f ! 1:  12d69fe0fe +232 -199 7f rename sort modes for the explicit keys they allow
2:  1fbef59f6e +107   -7 2f = 2:  5ea1c24c7c +107   -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  5babe1a6d2 +962 -958 9f ! 3:  867452829a +960 -962 9f derive sort keys from the tx UUID in every mode
4:  d845c46319 +121 -152 5f ! 4:  af42f08545 +121 -152 5f allow repeated explicit sort keys
5:  62c63bea9a +136  -51 6f ! 5:  23287ff1ed +136  -49 6f require non-empty explicit sort keys under derivation 0x00
1: a6aee228c8 ! 1: 12d69fe0fe rename sort modes for the explicit keys they allow
@@ Commit message
 
     DerivedOnly becomes ExplicitKeysForbidden and ExplicitOnly becomes
     ExplicitKeysRequired, with the Creator methods explicit_keys_forbidden
-    and explicit_keys_required, and SortKeyDerivation::Derived becomes
-    ExplicitKeysForbidden.
+    and explicit_keys_required. SortKeyDerivation::Derived and Explicit become
+    ExplicitKeysForbidden and ExplicitKeysRequired.
 
     The following commits derive a key for every input and output in every
     mode, to break ties between explicit keys, so "derived only" no longer
@@ Commit message
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
-@@ crates/concurrent-psbt/src/psbt/global.rs: pub enum SortKeyDerivation {
-     Explicit,
+@@ crates/concurrent-psbt/src/psbt/global.rs: pub const PSBT_GLOBAL_SORT_KEY_DERIVATION_SUBTYPE: u8 = 0x12;
+ pub enum SortKeyDerivation {
+     /// `0x00`: every input and output needs an explicit sort key, and there is
+     /// no sort seed.
+-    Explicit,
++    ExplicitKeysRequired,
      /// `0x01`: every sort key is derived from the sort seed, and explicit sort
      /// keys are not allowed.
 -    Derived,
@@ crates/concurrent-psbt/src/psbt/global.rs: pub enum SortKeyDerivation {
  
  impl SortKeyDerivation {
 @@ crates/concurrent-psbt/src/psbt/global.rs: impl SortKeyDerivation {
+     /// `0x01`.
      fn from_value(value: Vec<u8>) -> Result<Self, Vec<u8>> {
          match value.as_slice() {
-             [0x00] => Ok(Self::Explicit),
+-            [0x00] => Ok(Self::Explicit),
 -            [0x01] => Ok(Self::Derived),
++            [0x00] => Ok(Self::ExplicitKeysRequired),
 +            [0x01] => Ok(Self::ExplicitKeysForbidden),
              _ => Err(value),
          }
      }
-@@ crates/concurrent-psbt/src/psbt/global.rs: impl SortKeyDerivation {
+ 
      pub(crate) fn to_byte(self) -> u8 {
          match self {
-             Self::Explicit => 0x00,
+-            Self::Explicit => 0x00,
 -            Self::Derived => 0x01,
++            Self::ExplicitKeysRequired => 0x00,
 +            Self::ExplicitKeysForbidden => 0x01,
          }
      }
@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
              let v2 = global.clone().into_v2(0, 0);
              assert_eq!(v2.proprietaries.get(&key(0x10)), Some(&vec![0x03]));
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
+             assert_eq!(Global::try_from(v2), Ok(global.clone()));
+ 
+             global.clear_unordered();
+-            global.set_sort_key_derivation(SortKeyDerivation::Explicit);
++            global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired);
+             assert!(!global.is_unordered());
+             let v2 = global.into_v2(0, 0);
+             assert!(!v2.proprietaries.contains_key(&key(0x10)));
+@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
+                 proptest::option::of(0u8..2),
                  proptest::bool::ANY,
                  proptest::option::of(prop_oneof![
-                     Just(SortKeyDerivation::Explicit),
+-                    Just(SortKeyDerivation::Explicit),
 -                    Just(SortKeyDerivation::Derived),
++                    Just(SortKeyDerivation::ExplicitKeysRequired),
 +                    Just(SortKeyDerivation::ExplicitKeysForbidden),
                  ]),
                  proptest::option::of(proptest::collection::vec(any::<u8>(), 16..=17)),
                  proptest::collection::btree_map(
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
+             ) {
                  let v2 = v2_with_fields(&[(PSBT_GLOBAL_SORT_KEY_DERIVATION_SUBTYPE, value.clone())]);
                  let derivation = match value.as_slice() {
-                     [0x00] => SortKeyDerivation::Explicit,
+-                    [0x00] => SortKeyDerivation::Explicit,
 -                    [0x01] => SortKeyDerivation::Derived,
++                    [0x00] => SortKeyDerivation::ExplicitKeysRequired,
 +                    [0x01] => SortKeyDerivation::ExplicitKeysForbidden,
                      _ => {
                          let error = Global::try_from(v2).unwrap_err();
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
          let may_be =
              |derivation| values(&self.global.sort_key_derivation).any(|value| *value == derivation);
 -        let derived = may_be(SortKeyDerivation::Derived);
+-        let seed_broken = may_be(SortKeyDerivation::Explicit) && self.global.sort_seed.is_some();
 +        let derived = may_be(SortKeyDerivation::ExplicitKeysForbidden);
-         let seed_broken = may_be(SortKeyDerivation::Explicit) && self.global.sort_seed.is_some();
++        let seed_broken =
++            may_be(SortKeyDerivation::ExplicitKeysRequired) && self.global.sort_seed.is_some();
          if seed_broken {
              mark(&mut self.global.sort_seed);
+         }
 @@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
              )
          };
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
          #[test]
          fn psbts_that_break_the_sort_rules_are_rejected() {
 -            use SortKeyDerivation::{Derived, Explicit};
-+            use SortKeyDerivation::{Explicit, ExplicitKeysForbidden};
++            use SortKeyDerivation::{ExplicitKeysForbidden, ExplicitKeysRequired};
  
              let global = |derivation: Option<SortKeyDerivation>, seeded: bool| {
                  let mut global = unordered_global();
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+                     Err(UnorderedPsbtError::UnorderedSighashSingle),
+                 ),
+                 (
+-                    v2_psbt_with(global(Some(Explicit), true), vec![], vec![]),
++                    v2_psbt_with(global(Some(ExplicitKeysRequired), true), vec![], vec![]),
+                     Err(UnorderedPsbtError::UnexpectedSortSeed),
                  ),
                  (
                      v2_psbt_with(
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                          vec![],
                          vec![output(1, None), output(2, Some(0))],
                      ),
+@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+                 ),
+                 (
+                     v2_psbt_with(
+-                        global(Some(Explicit), false),
++                        global(Some(ExplicitKeysRequired), false),
+                         vec![input(1, Some(0)), input(2, Some(0))],
+                         vec![],
+                     ),
+@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+                 ),
+                 (
+                     v2_psbt_with(
+-                        global(Some(Explicit), false),
++                        global(Some(ExplicitKeysRequired), false),
+                         vec![],
+                         vec![output(1, Some(0)), output(2, Some(0))],
+                     ),
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                  // Seeded derivation accepts entries without explicit keys.
                  (
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                          vec![output(1, None)],
                      ),
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+                 // An input and an output may share a sort key.
+                 (
+                     v2_psbt_with(
+-                        global(Some(Explicit), false),
++                        global(Some(ExplicitKeysRequired), false),
+                         vec![input(1, Some(0))],
+                         vec![output(1, Some(0))],
+                     ),
+@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+             let explicit = {
+                 let mut psbt = singleton(1);
+                 psbt.global
+-                    .set_sort_key_derivation(SortKeyDerivation::Explicit);
++                    .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired);
+                 psbt.wrap()
+             };
+             let seed = SortSeed::try_from(vec![0; 16]).unwrap();
+@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+             let joined = explicit.join(seeded);
+             assert_eq!(
+                 joined.global.sort_key_derivation,
+-                Some(Err(Conflict::from_values([SortKeyDerivation::Explicit])))
++                Some(Err(Conflict::from_values([
++                    SortKeyDerivation::ExplicitKeysRequired
++                ])))
+             );
+             assert_eq!(
+                 joined.global.sort_seed,
+@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+                 // outputs: uid_byte to sort key
                  proptest::collection::hash_map(0u8..10, proptest::option::of(0u8..3), 0..=3),
                  proptest::option::of(prop_oneof![
-                     Just(SortKeyDerivation::Explicit),
+-                    Just(SortKeyDerivation::Explicit),
 -                    Just(SortKeyDerivation::Derived),
++                    Just(SortKeyDerivation::ExplicitKeysRequired),
 +                    Just(SortKeyDerivation::ExplicitKeysForbidden),
                  ]),
                  proptest::option::of(0u8..2), // sort seed byte
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
  
                          let mut input_key = distinct_keys(no_keys);
                          let inputs = InputSet::try_from_inputs(input_specs.into_iter().map(
+@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+                             global.set_sort_key_derivation(derivation);
+                         }
+                         let seed = seed.filter(|_| {
+-                            sort_fields && derivation != Some(SortKeyDerivation::Explicit)
++                            sort_fields
++                                && derivation != Some(SortKeyDerivation::ExplicitKeysRequired)
+                         });
+                         if let Some(byte) = seed {
+                             global.set_sort_seed(
 
  ## crates/concurrent-psbt/src/roles/constructor/error.rs ##
 @@ crates/concurrent-psbt/src/roles/constructor/error.rs: mod tests {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
          let mut global = unordered_global(flags);
          match mode {
 -            2 | 3 => global.set_sort_key_derivation(SortKeyDerivation::Derived),
+-            4 => global.set_sort_key_derivation(SortKeyDerivation::Explicit),
 +            2 | 3 => global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden),
-             4 => global.set_sort_key_derivation(SortKeyDerivation::Explicit),
++            4 => global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired),
              _ => {}
          }
+         if mode == 1 || mode == 3 {
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
          use super::*;
          use crate::input::SortKey;
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
                  .no_more_outputs()
                  .input(test_input(1))
                  .unwrap()
+@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
+             let mut miscounted = flags_psbt(0x03);
+             miscounted.global.input_count = 1;
+             let mut explicit_with_seed = global_with_mode(0x03, 1);
+-            explicit_with_seed.set_sort_key_derivation(SortKeyDerivation::Explicit);
++            explicit_with_seed.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired);
+ 
+             let cases = [
+                 (
 @@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
                      }),
                  ),
@@ crates/concurrent-psbt/src/roles/creator.rs: impl Creator<Mixed> {
  
 -    /// Switch to [`ExplicitOnly`] mode (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x00`).
 -    pub fn explicit_only(self) -> Creator<ExplicitOnly> {
+-        self.with_sort_key_derivation(SortKeyDerivation::Explicit)
 +    /// Switch to [`ExplicitKeysRequired`] mode
 +    /// (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x00`).
 +    pub fn explicit_keys_required(self) -> Creator<ExplicitKeysRequired> {
-         self.with_sort_key_derivation(SortKeyDerivation::Explicit)
++        self.with_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired)
      }
  
+     fn with_sort_key_derivation<T>(mut self, derivation: SortKeyDerivation) -> Creator<T> {
 @@ crates/concurrent-psbt/src/roles/creator.rs: impl Creator<Mixed> {
      }
  }
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
 -                    "explicit only",
 +                    "explicit keys required",
                      explicit.constructor().into_inner(),
-                     Some(SortKeyDerivation::Explicit),
+-                    Some(SortKeyDerivation::Explicit),
++                    Some(SortKeyDerivation::ExplicitKeysRequired),
                      None,
+                 ),
+             ];
 @@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
          }
  
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: mod tests {
          #[test]
          fn a_derivation_mismatch_names_both_values() {
 -            use SortKeyDerivation::{Derived, Explicit};
-+            use SortKeyDerivation::{Explicit, ExplicitKeysForbidden};
++            use SortKeyDerivation::{ExplicitKeysForbidden, ExplicitKeysRequired};
  
              let examples = [
                  (
@@ crates/concurrent-psbt/src/roles/sorter/error.rs: mod tests {
                      "PSBT_GLOBAL_SORT_KEY_DERIVATION is unset, expected 0x01",
                  ),
                  (
-@@ crates/concurrent-psbt/src/roles/sorter/error.rs: mod tests {
+-                    Some(Explicit),
++                    Some(ExplicitKeysRequired),
+                     None,
                      "PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x00, expected unset",
                  ),
                  (
 -                    Some(Derived),
+-                    Some(Explicit),
 +                    Some(ExplicitKeysForbidden),
-                     Some(Explicit),
++                    Some(ExplicitKeysRequired),
                      "PSBT_GLOBAL_SORT_KEY_DERIVATION is 0x01, expected 0x00",
                  ),
+             ];
 @@ crates/concurrent-psbt/src/roles/sorter/error.rs: mod tests {
+ 
          fn derivation() -> impl Strategy<Value = Option<SortKeyDerivation>> {
              proptest::option::of(prop_oneof![
-                 Just(SortKeyDerivation::Explicit),
+-                Just(SortKeyDerivation::Explicit),
 -                Just(SortKeyDerivation::Derived)
++                Just(SortKeyDerivation::ExplicitKeysRequired),
 +                Just(SortKeyDerivation::ExplicitKeysForbidden)
              ])
          }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: macro_rules! sort_mode {
 -    ExplicitOnly => Some(SortKeyDerivation::Explicit), false;
 +    ExplicitKeysForbidden => Some(SortKeyDerivation::ExplicitKeysForbidden), false;
 +    Seeded<ExplicitKeysForbidden> => Some(SortKeyDerivation::ExplicitKeysForbidden), true;
-+    ExplicitKeysRequired => Some(SortKeyDerivation::Explicit), false;
++    ExplicitKeysRequired => Some(SortKeyDerivation::ExplicitKeysRequired), false;
  }
  
  /// Check that `psbt`'s sort fields select sort mode `S`. Besides matching
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: macro_rules! sort_mode {
  /// # Errors
  /// Returns the first [`SortModeError`] in that order.
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) fn check_sort_mode<S: SortMode>(psbt: &UnorderedPsbt) -> Result<(), S
+     };
      match S::SORT_KEY_DERIVATION {
          _ if S::SEEDED && !seeded => Err(SortModeError::MissingSortSeed),
-         Some(SortKeyDerivation::Explicit) if seeded => Err(SortModeError::UnexpectedSortSeed),
+-        Some(SortKeyDerivation::Explicit) if seeded => Err(SortModeError::UnexpectedSortSeed),
 -        Some(SortKeyDerivation::Derived) if sort_keyed() => Err(SortModeError::UnexpectedSortKey),
++        Some(SortKeyDerivation::ExplicitKeysRequired) if seeded => {
++            Err(SortModeError::UnexpectedSortSeed)
++        }
 +        Some(SortKeyDerivation::ExplicitKeysForbidden) if sort_keyed() => {
 +            Err(SortModeError::UnexpectedSortKey)
 +        }
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
              use SortKeyOn as K;
              const U: Option<SortKeyDerivation> = None;
 -            const D: Option<SortKeyDerivation> = Some(SortKeyDerivation::Derived);
+-            const E: Option<SortKeyDerivation> = Some(SortKeyDerivation::Explicit);
 +            const D: Option<SortKeyDerivation> = Some(SortKeyDerivation::ExplicitKeysForbidden);
-             const E: Option<SortKeyDerivation> = Some(SortKeyDerivation::Explicit);
++            const E: Option<SortKeyDerivation> = Some(SortKeyDerivation::ExplicitKeysRequired);
  
              #[rustfmt::skip]
+             let rows = [
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
                      Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt.clone()).err(),
                      Sorter::<Unmodifiable, Seeded<Mixed>>::try_from_unordered_psbt(psbt.clone())
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
                  let expected = outcomes.map(|outcome| {
                      let error = match outcome {
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
+ 
+         #[test]
+         fn invalid_flags_are_reported_before_an_invalid_sort_mode() {
+-            let mut psbt = with_derivation(empty_psbt(), SortKeyDerivation::Explicit);
++            let mut psbt = with_derivation(empty_psbt(), SortKeyDerivation::ExplicitKeysRequired);
+             psbt.global.set_tx_modifiable_flags(0x01);
+             assert_eq!(
+                 Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt).err(),
+@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
                  OutputSet::try_from_outputs((0..=4).map(|uid| make_output_with_uid(&[uid])))
                      .unwrap();
  
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -                        SortKeyDerivation::Explicit,
 -                    ))
 +                    Sorter::<Unmodifiable, ExplicitKeysRequired>::try_from_unordered_psbt(
-+                        with_derivation(psbt, SortKeyDerivation::Explicit),
++                        with_derivation(psbt, SortKeyDerivation::ExplicitKeysRequired),
 +                    )
                      .unwrap()
                  };
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -                Mode::ExplicitOnly => psbt
 +                Mode::ExplicitKeysRequired => psbt
                      .global
-                     .set_sort_key_derivation(SortKeyDerivation::Explicit),
+-                    .set_sort_key_derivation(SortKeyDerivation::Explicit),
++                    .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired),
              }
+             psbt.inputs = InputSet::try_from_inputs(inputs).unwrap();
+             psbt.outputs = OutputSet::try_from_outputs(outputs).unwrap();
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
                  Mode::Mixed => Sorter::<Unmodifiable, Mixed>::try_from_unordered_psbt(psbt)
                      .unwrap()
3: 5babe1a6d2 ! 3: 867452829a derive sort keys from the tx UUID in every mode
@@ crates/concurrent-psbt/src/psbt/global.rs: impl crate::values::IdempotentValue f
 -    /// `0x00`: every input and output needs an explicit sort key, and there is
 -    /// no sort seed.
 +    /// `0x00`: every input and output needs an explicit sort key.
-     Explicit,
+     ExplicitKeysRequired,
 -    /// `0x01`: every sort key is derived from the sort seed, and explicit sort
 -    /// keys are not allowed.
 +    /// `0x01`: inputs and outputs are ordered by their derived keys alone,
@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
              );
          }
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
-                     Just(SortKeyDerivation::Explicit),
+                     Just(SortKeyDerivation::ExplicitKeysRequired),
                      Just(SortKeyDerivation::ExplicitKeysForbidden),
                  ]),
 -                proptest::option::of(proptest::collection::vec(any::<u8>(), 16..=17)),
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
          let may_be =
              |derivation| values(&self.global.sort_key_derivation).any(|value| *value == derivation);
          let derived = may_be(SortKeyDerivation::ExplicitKeysForbidden);
--        let seed_broken = may_be(SortKeyDerivation::Explicit) && self.global.sort_seed.is_some();
+-        let seed_broken =
+-            may_be(SortKeyDerivation::ExplicitKeysRequired) && self.global.sort_seed.is_some();
 -        if seed_broken {
 -            mark(&mut self.global.sort_seed);
 -        }
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                      Err(UnorderedPsbtError::UnorderedSighashSingle),
                  ),
 -                (
--                    v2_psbt_with(global(Some(Explicit), true), vec![], vec![]),
+-                    v2_psbt_with(global(Some(ExplicitKeysRequired), true), vec![], vec![]),
 -                    Err(UnorderedPsbtError::UnexpectedSortSeed),
 -                ),
                  (
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 +                // may share a sort key.
                  (
                      v2_psbt_with(
--                        global(Some(Explicit), false),
-+                        global(Some(Explicit), true),
+-                        global(Some(ExplicitKeysRequired), false),
++                        global(Some(ExplicitKeysRequired), true),
                          vec![input(1, Some(0))],
                          vec![output(1, Some(0))],
                      ),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 -            let explicit = {
 -                let mut psbt = singleton(1);
 -                psbt.global
--                    .set_sort_key_derivation(SortKeyDerivation::Explicit);
+-                    .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired);
 -                psbt.wrap()
--            };
++            let key = SortKey::try_from(vec![0]).unwrap();
++            let keyed = |byte| {
++                let mut input = Input::new(&outpoint(byte));
++                input.set_sort_key(key.clone());
++                let mut psbt = singleton(byte);
++                psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
++                psbt
+             };
 -            let seed = SortSeed::try_from(vec![0; 16]).unwrap();
 -            let seeded = {
 -                let mut psbt = singleton(1);
 -                psbt.global.set_sort_seed(seed.clone());
--                psbt.wrap()
--            };
--            let joined = explicit.join(seeded);
--            assert_eq!(
--                joined.global.sort_key_derivation,
--                Some(Err(Conflict::from_values([SortKeyDerivation::Explicit])))
--            );
--            assert_eq!(
--                joined.global.sort_seed,
--                Some(Err(Conflict::from_values([seed])))
--            );
--            assert!(joined.clone().try_unwrap().is_err());
--
--            // Without a derivation, only the repeated keys are marked.
-             let key = SortKey::try_from(vec![0]).unwrap();
-             let keyed = |byte| {
-                 let mut input = Input::new(&outpoint(byte));
-                 input.set_sort_key(key.clone());
-                 let mut psbt = singleton(byte);
-                 psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
-+                psbt
-+            };
 +            let derived = {
 +                let mut psbt = singleton(2);
 +                psbt.global
 +                    .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden);
                  psbt.wrap()
              };
--            let joined = keyed(1).join(keyed(2));
+-            let joined = explicit.join(seeded);
 +            let joined = derived.join(keyed(1).wrap());
-+            assert_eq!(
-+                joined.global.sort_key_derivation,
-+                Some(Err(Conflict::from_values([
+             assert_eq!(
+                 joined.global.sort_key_derivation,
+                 Some(Err(Conflict::from_values([
+-                    SortKeyDerivation::ExplicitKeysRequired
 +                    SortKeyDerivation::ExplicitKeysForbidden
-+                ])))
-+            );
+                 ])))
+             );
+-            assert_eq!(
+-                joined.global.sort_seed,
+-                Some(Err(Conflict::from_values([seed])))
+-            );
 +            for (spent, input) in joined.inputs.0.entries() {
 +                let expected =
 +                    (*spent == outpoint(1)).then(|| Err(Conflict::from_values([key.clone()])));
 +                assert_eq!(input.sort_key, expected);
 +            }
-+            assert!(joined.clone().try_unwrap().is_err());
-+
+             assert!(joined.clone().try_unwrap().is_err());
+ 
+-            // Without a derivation, only the repeated keys are marked.
+-            let key = SortKey::try_from(vec![0]).unwrap();
+-            let keyed = |byte| {
+-                let mut input = Input::new(&outpoint(byte));
+-                input.set_sort_key(key.clone());
+-                let mut psbt = singleton(byte);
+-                psbt.inputs = InputSet::try_from_inputs([input]).unwrap();
+-                psbt.wrap()
+-            };
+-            let joined = keyed(1).join(keyed(2));
 +            // Without a derivation, only the repeated keys are marked, and a
 +            // seed is allowed.
 +            let mut seeded = keyed(2);
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
          use proptest::prelude::*;
  
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
-                     Just(SortKeyDerivation::Explicit),
+                     Just(SortKeyDerivation::ExplicitKeysRequired),
                      Just(SortKeyDerivation::ExplicitKeysForbidden),
                  ]),
 -                proptest::option::of(0u8..2), // sort seed byte
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                              global.set_sort_key_derivation(derivation);
                          }
 -                        let seed = seed.filter(|_| {
--                            sort_fields && derivation != Some(SortKeyDerivation::Explicit)
+-                            sort_fields
+-                                && derivation != Some(SortKeyDerivation::ExplicitKeysRequired)
 -                        });
 -                        if let Some(byte) = seed {
 -                            global.set_sort_seed(
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
          let mut global = unordered_global(flags);
          match mode {
              2 | 3 => global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden),
--            4 => global.set_sort_key_derivation(SortKeyDerivation::Explicit),
-+            4 | 5 => global.set_sort_key_derivation(SortKeyDerivation::Explicit),
+-            4 => global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired),
++            4 | 5 => global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired),
              _ => {}
          }
 -        if mode == 1 || mode == 3 {
@@ crates/concurrent-psbt/src/roles/constructor/mod.rs: mod tests {
              let mut miscounted = flags_psbt(0x03);
              miscounted.global.input_count = 1;
 -            let mut explicit_with_seed = global_with_mode(0x03, 1);
--            explicit_with_seed.set_sort_key_derivation(SortKeyDerivation::Explicit);
+-            explicit_with_seed.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired);
 +            let mut keyed = test_input(1);
 +            keyed.set_sort_key(SortKey::try_from(vec![1]).unwrap());
 +            let derived_with_key = Psbt {
@@ crates/concurrent-psbt/src/roles/creator.rs: impl Creator<Mixed> {
      /// (`PSBT_GLOBAL_SORT_KEY_DERIVATION = 0x00`).
 -    pub fn explicit_keys_required(self) -> Creator<ExplicitKeysRequired> {
 +    pub fn explicit_keys_required(self) -> Creator<Seeded<ExplicitKeysRequired>> {
-         self.with_sort_key_derivation(SortKeyDerivation::Explicit)
+         self.with_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired)
      }
  
 -    fn with_sort_key_derivation<T>(mut self, derivation: SortKeyDerivation) -> Creator<T> {
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
  
 +            let (derived_mode, explicit_mode) = (
 +                Some(SortKeyDerivation::ExplicitKeysForbidden),
-+                Some(SortKeyDerivation::Explicit),
++                Some(SortKeyDerivation::ExplicitKeysRequired),
 +            );
 +            let seed = Some(seed.as_slice());
              // name, PSBT, expected sort key derivation, expected sort seed
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
                  (
                      "explicit keys required",
                      explicit.constructor().into_inner(),
--                    Some(SortKeyDerivation::Explicit),
+-                    Some(SortKeyDerivation::ExplicitKeysRequired),
 +                    explicit_mode,
                      None,
                  ),
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: impl<M: Modifiability, S: SortMo
              self.0,
 -            |input| mixed_input_sort_key(seed.as_deref(), input),
 -            |output| mixed_output_sort_key(seed.as_deref(), output),
-+            S::SORT_KEY_DERIVATION == Some(SortKeyDerivation::Explicit),
++            S::SORT_KEY_DERIVATION == Some(SortKeyDerivation::ExplicitKeysRequired),
          )
      }
  
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) mod sealed {
 -    Seeded<Mixed> => None, true;
 -    ExplicitKeysForbidden => Some(SortKeyDerivation::ExplicitKeysForbidden), false;
 -    Seeded<ExplicitKeysForbidden> => Some(SortKeyDerivation::ExplicitKeysForbidden), true;
--    ExplicitKeysRequired => Some(SortKeyDerivation::Explicit), false;
+-    ExplicitKeysRequired => Some(SortKeyDerivation::ExplicitKeysRequired), false;
 +    Mixed => None;
 +    ExplicitKeysForbidden => Some(SortKeyDerivation::ExplicitKeysForbidden);
-+    ExplicitKeysRequired => Some(SortKeyDerivation::Explicit);
++    ExplicitKeysRequired => Some(SortKeyDerivation::ExplicitKeysRequired);
  }
  
 -/// Check that `psbt`'s sort fields select sort mode `S`. Besides matching
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: pub(crate) fn check_sort_mode<S:
      };
      match S::SORT_KEY_DERIVATION {
 -        _ if S::SEEDED && !seeded => Err(SortModeError::MissingSortSeed),
--        Some(SortKeyDerivation::Explicit) if seeded => Err(SortModeError::UnexpectedSortSeed),
+-        Some(SortKeyDerivation::ExplicitKeysRequired) if seeded => {
+-            Err(SortModeError::UnexpectedSortSeed)
+-        }
 +        _ if S::SEEDED && !has_uuid(&psbt.global) => Err(SortModeError::MissingUuid),
          Some(SortKeyDerivation::ExplicitKeysForbidden) if sort_keyed() => {
              Err(SortModeError::UnexpectedSortKey)
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
              use SortKeyOn as K;
              const U: Option<SortKeyDerivation> = None;
              const D: Option<SortKeyDerivation> = Some(SortKeyDerivation::ExplicitKeysForbidden);
-             const E: Option<SortKeyDerivation> = Some(SortKeyDerivation::Explicit);
+             const E: Option<SortKeyDerivation> = Some(SortKeyDerivation::ExplicitKeysRequired);
 +            const SET: Option<&[u8]> = Some(&[13; 16]);
 +            const EMPTY: Option<&[u8]> = Some(&[]);
  
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 +                    .try_sort()
 +                    .err(),
 +                    Sorter::<Unmodifiable, ExplicitKeysRequired>::try_from_unordered_psbt(
-+                        with_derivation(psbt, SortKeyDerivation::Explicit),
++                        with_derivation(psbt, SortKeyDerivation::ExplicitKeysRequired),
 +                    )
                      .unwrap()
                      .try_into_ordered_psbt()
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 -                };
 -                let explicit = |psbt| {
 -                    Sorter::<Unmodifiable, ExplicitKeysRequired>::try_from_unordered_psbt(
--                        with_derivation(psbt, SortKeyDerivation::Explicit),
+-                        with_derivation(psbt, SortKeyDerivation::ExplicitKeysRequired),
 -                    )
 -                    .unwrap()
 -                };
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
 +                    .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden),
                  Mode::ExplicitKeysRequired => psbt
                      .global
-                     .set_sort_key_derivation(SortKeyDerivation::Explicit),
+                     .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired),
 @@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
              psbt
          }
4: d845c46319 ! 4: af42f08545 allow repeated explicit sort keys
@@ crates/concurrent-psbt/src/psbt/global.rs: pub const PSBT_GLOBAL_SORT_KEY_DERIVA
      /// `0x00`: every input and output needs an explicit sort key.
 +    /// Inputs, or outputs, with the same explicit key are ordered by their
 +    /// derived keys.
-     Explicit,
+     ExplicitKeysRequired,
      /// `0x01`: inputs and outputs are ordered by their derived keys alone,
      /// and explicit sort keys are not allowed.
 
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                  ),
 -                (
 -                    v2_psbt_with(
--                        global(Some(Explicit), false),
+-                        global(Some(ExplicitKeysRequired), false),
 -                        vec![input(1, Some(0)), input(2, Some(0))],
 -                        vec![],
 -                    ),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 -                ),
 -                (
 -                    v2_psbt_with(
--                        global(Some(Explicit), false),
+-                        global(Some(ExplicitKeysRequired), false),
 -                        vec![],
 -                        vec![output(1, Some(0)), output(2, Some(0))],
 -                    ),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 +                // added later, empty keys, and keys that repeat.
                  (
                      v2_psbt_with(
-                         global(Some(Explicit), true),
+                         global(Some(ExplicitKeysRequired), true),
 -                        vec![input(1, Some(0))],
 -                        vec![output(1, Some(0))],
 +                        vec![input(1, Some(&[0])), input(2, Some(&[0])), input(3, None)],
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 +            fn try_from_psbt_rejects_the_smallest_entry_breaking_the_sort_rules(
 +                keys in proptest::collection::vec(proptest::option::of(0usize..=2), 0..=5),
 +                derivation in proptest::option::of(prop_oneof![
-+                    Just(SortKeyDerivation::Explicit),
++                    Just(SortKeyDerivation::ExplicitKeysRequired),
 +                    Just(SortKeyDerivation::ExplicitKeysForbidden),
 +                ]),
                  on_outputs in proptest::bool::ANY,
5: 62c63bea9a ! 5: 23287ff1ed require non-empty explicit sort keys under derivation 0x00
@@ crates/concurrent-psbt/src/psbt/global.rs: impl crate::values::IdempotentValue f
 +    /// `0x00`: every input and output needs a non-empty explicit sort key.
      /// Inputs, or outputs, with the same explicit key are ordered by their
      /// derived keys.
-     Explicit,
+     ExplicitKeysRequired,
 
  ## crates/concurrent-psbt/src/psbt/tx.rs ##
 @@ crates/concurrent-psbt/src/psbt/tx.rs: pub enum UnorderedPsbtError {
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
          let may_be =
              |derivation| values(&self.global.sort_key_derivation).any(|value| *value == derivation);
          let derived = may_be(SortKeyDerivation::ExplicitKeysForbidden);
-+        let explicit = may_be(SortKeyDerivation::Explicit);
++        let explicit = may_be(SortKeyDerivation::ExplicitKeysRequired);
          let inputs_broken = mark_sort_keys(
              self.inputs
                  .0
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                  ),
 +                (
 +                    v2_psbt_with(
-+                        global(Some(Explicit), false),
++                        global(Some(ExplicitKeysRequired), false),
 +                        vec![
 +                            input(1, Some(&[0])),
 +                            input(2, Some(&[])),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 +                ),
 +                (
 +                    v2_psbt_with(
-+                        global(Some(Explicit), true),
++                        global(Some(ExplicitKeysRequired), true),
 +                        vec![input(1, Some(&[0]))],
 +                        vec![
 +                            output(1, Some(&[0])),
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 +                // added later, and keys that repeat.
                  (
                      v2_psbt_with(
-                         global(Some(Explicit), true),
+                         global(Some(ExplicitKeysRequired), true),
                          vec![input(1, Some(&[0])), input(2, Some(&[0])), input(3, None)],
 -                        vec![output(1, Some(&[])), output(2, Some(&[]))],
 +                        vec![output(1, Some(&[0])), output(2, Some(&[0]))],
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                  let mut psbt = singleton(2);
                  psbt.global
 -                    .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden);
-+                    .set_sort_key_derivation(SortKeyDerivation::Explicit);
++                    .set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired);
                  psbt.wrap()
              };
 -            let joined = derived.join(keyed(1, &empty_key).wrap());
 +            let joined = explicit.join(keyed(1, &empty_key).wrap());
              assert_eq!(
                  joined.global.sort_key_derivation,
--                Some(Err(Conflict::from_values([
+                 Some(Err(Conflict::from_values([
 -                    SortKeyDerivation::ExplicitKeysForbidden
--                ])))
-+                Some(Err(Conflict::from_values([SortKeyDerivation::Explicit])))
++                    SortKeyDerivation::ExplicitKeysRequired
+                 ])))
              );
              for (spent, input) in joined.inputs.0.entries() {
-                 let expected = (*spent == outpoint(1))
 @@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
          }
  
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
                      })
                      .map(|key| if key == 0 { vec![] } else { vec![key] })?;
 -                Some(SortKey::try_from(key).expect("at most one byte"))
-+                let empty_forbidden = derivation == Some(SortKeyDerivation::Explicit);
++                let empty_forbidden = derivation == Some(SortKeyDerivation::ExplicitKeysRequired);
 +                (!(empty_forbidden && key.is_empty()))
 +                    .then(|| SortKey::try_from(key).expect("at most one byte"))
              }
@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
 -                    derivation == Some(SortKeyDerivation::ExplicitKeysForbidden) && key.is_some()
 +                let breaks = |key: &Option<usize>| match derivation {
 +                    Some(SortKeyDerivation::ExplicitKeysForbidden) => key.is_some(),
-+                    Some(SortKeyDerivation::Explicit) => *key == Some(0),
++                    Some(SortKeyDerivation::ExplicitKeysRequired) => *key == Some(0),
 +                    None => false,
                  };
                  let first = keys.iter().position(breaks);

@github-actions

Copy link
Copy Markdown
range-diff for force push 23287ff1ed → 918602e8a1 November 15, 2026 23:52 UTC: 5 unchanged; 5 commits; base f330b6a12f → ea78d3fd3c (diverged, 15 ahead and 15 behind)

reproduce: git range-diff f330b6a..23287ff ea78d3f..918602e

1:  12d69fe0fe +232 -199 7f = 1:  0be01a9779 +232 -199 7f rename sort modes for the explicit keys they allow
2:  5ea1c24c7c +107   -7 2f = 2:  e3b85cbc33 +107   -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  867452829a +960 -962 9f = 3:  61fcba7b4c +960 -962 9f derive sort keys from the tx UUID in every mode
4:  af42f08545 +121 -152 5f = 4:  99484a5ff0 +121 -152 5f allow repeated explicit sort keys
5:  23287ff1ed +136  -49 6f = 5:  918602e8a1 +136  -49 6f require non-empty explicit sort keys under derivation 0x00

@github-actions

Copy link
Copy Markdown
range-diff for force push 23287ff1ed → 918602e8a1 November 15, 2026 23:52 UTC: 5 unchanged; 5 commits; base f330b6a12f → ea78d3fd3c (diverged, 15 ahead and 15 behind)

reproduce: git range-diff f330b6a..23287ff ea78d3f..918602e

1:  12d69fe0fe +232 -199 7f = 1:  0be01a9779 +232 -199 7f rename sort modes for the explicit keys they allow
2:  5ea1c24c7c +107   -7 2f = 2:  e3b85cbc33 +107   -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  867452829a +960 -962 9f = 3:  61fcba7b4c +960 -962 9f derive sort keys from the tx UUID in every mode
4:  af42f08545 +121 -152 5f = 4:  99484a5ff0 +121 -152 5f allow repeated explicit sort keys
5:  23287ff1ed +136  -49 6f = 5:  918602e8a1 +136  -49 6f require non-empty explicit sort keys under derivation 0x00

@github-actions

Copy link
Copy Markdown
range-diff for force push 918602e8a1 → 0c154de312 November 16, 2026 00:22 UTC: 5 unchanged; 5 commits; base ea78d3fd3c → d41b04f068 (diverged, 12 ahead and 12 behind)

reproduce: git range-diff ea78d3f..918602e d41b04f..0c154de

1:  0be01a9779 +232 -199 7f = 1:  0e6d0e5eb9 +232 -199 7f rename sort modes for the explicit keys they allow
2:  e3b85cbc33 +107   -7 2f = 2:  5525dbe65d +107   -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  61fcba7b4c +960 -962 9f = 3:  0597d32f79 +960 -962 9f derive sort keys from the tx UUID in every mode
4:  99484a5ff0 +121 -152 5f = 4:  681474a6d3 +121 -152 5f allow repeated explicit sort keys
5:  918602e8a1 +136  -49 6f = 5:  0c154de312 +136  -49 6f require non-empty explicit sort keys under derivation 0x00

@github-actions

Copy link
Copy Markdown
range-diff for force push 918602e8a1 → 0c154de312 November 16, 2026 00:23 UTC: 5 unchanged; 5 commits; base ea78d3fd3c → d41b04f068 (diverged, 12 ahead and 12 behind)

reproduce: git range-diff ea78d3f..918602e d41b04f..0c154de

1:  0be01a9779 +232 -199 7f = 1:  0e6d0e5eb9 +232 -199 7f rename sort modes for the explicit keys they allow
2:  e3b85cbc33 +107   -7 2f = 2:  5525dbe65d +107   -7 2f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  61fcba7b4c +960 -962 9f = 3:  0597d32f79 +960 -962 9f derive sort keys from the tx UUID in every mode
4:  99484a5ff0 +121 -152 5f = 4:  681474a6d3 +121 -152 5f allow repeated explicit sort keys
5:  918602e8a1 +136  -49 6f = 5:  0c154de312 +136  -49 6f require non-empty explicit sort keys under derivation 0x00

@github-actions

Copy link
Copy Markdown
range-diff for force push 0c154de312 → bd4f1dc8f3 November 16, 2026 03:27 UTC: 3 modified, 2 unchanged; 5 commits; base d41b04f068 → 08b4b8fdbf (diverged, 15 ahead and 15 behind)

reproduce: git range-diff d41b04f..0c154de 08b4b8f..bd4f1dc

1:  0e6d0e5eb9 +232 -199  7f ! 1:  60572cff53 +234 -201  8f rename sort modes for the explicit keys they allow
2:  5525dbe65d +107   -7  2f ! 2:  1a07a11fdd +130   -7  3f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  0597d32f79 +960 -962  9f ! 3:  d9a74d3f90 +962 -964 10f derive sort keys from the tx UUID in every mode
4:  681474a6d3 +121 -152  5f = 4:  38cddae543 +121 -152  5f allow repeated explicit sort keys
5:  0c154de312 +136  -49  6f = 5:  bd4f1dc8f3 +136  -49  6f require non-empty explicit sort keys under derivation 0x00
1: 0e6d0e5eb9 ! 1: 60572cff53 rename sort modes for the explicit keys they allow
@@ crates/concurrent-psbt/src/roles/sorter/mod.rs: mod tests {
                      Err(SortError::DuplicateSortKey(_))
                  ));
              }
+
+ ## crates/concurrent-psbt/tests/conflicts.rs ##
+@@ crates/concurrent-psbt/tests/conflicts.rs: fn proprietary_sort_fields_keep_their_typed_paths() {
+ 
+     let mut global = Global::default();
+     global.set_sort_seed(SortSeed::try_from(vec![1; 16]).unwrap());
+-    global.set_sort_key_derivation(SortKeyDerivation::Explicit);
++    global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired);
+     let mut other = global.clone();
+     other.set_unordered();
+     other.set_sort_seed(SortSeed::try_from(vec![2; 16]).unwrap());
+-    other.set_sort_key_derivation(SortKeyDerivation::Derived);
++    other.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden);
+     let joined = global.wrap().join(other.wrap());
+     assert_eq!(
+         joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(),
2: 5525dbe65d ! 2: 1a07a11fdd add PSBT_GLOBAL_TX_UUID, set by the Creator
@@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
      },
  }
  
+@@ crates/concurrent-psbt/src/psbt/global.rs: record_conflicts! {
+     Unordered => unordered: bool,
+     SortKeyDerivation => sort_key_derivation: SortKeyDerivation,
+     SortSeed => sort_seed: SortSeed,
++    TxUuid => uuid: TxUuid,
+     }
+ }
+ 
  impl Default for Global {
      fn default() -> Self {
 -        Self::from_v2_fields(psbt_v2::v2::Global::default(), false, None, None)
@@ crates/concurrent-psbt/src/roles/creator.rs: mod tests {
              assert_eq!(ordered.inputs.len(), 1);
              assert_eq!(ordered.outputs.len(), 1);
          }
+
+ ## crates/concurrent-psbt/tests/conflicts.rs ##
+@@ crates/concurrent-psbt/tests/conflicts.rs: fn proprietary_sort_fields_keep_their_typed_paths() {
+         }]
+     );
+ }
++
++#[test]
++#[cfg_attr(coverage_nightly, coverage(off))]
++fn transaction_uuid_conflict_retains_both_identities() {
++    use concurrent_psbt::global::{Global, TxUuid};
++    let mut a = Global::default();
++    a.set_uuid(TxUuid::from(vec![1; 16]));
++    let mut b = Global::default();
++    b.set_uuid(TxUuid::from(vec![2; 16]));
++    let joined = a.wrap().join(b.wrap());
++    let mut conflicts = joined.conflicts();
++    let conflict = conflicts.next().unwrap();
++    assert_eq!(conflict.path(), GlobalField::TxUuid);
++    let GlobalConflict::TxUuid { values } = conflict else {
++        panic!("transaction UUID conflict");
++    };
++    assert_eq!(
++        values.into_iter().map(TxUuid::as_bytes).collect::<Vec<_>>(),
++        [vec![1; 16], vec![2; 16]]
++    );
++    assert!(conflicts.next().is_none());
++}
3: 0597d32f79 ! 3: d9a74d3f90 derive sort keys from the tx UUID in every mode
@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
          }
 
  ## crates/concurrent-psbt/src/psbt/tx.rs ##
-@@ crates/concurrent-psbt/src/psbt/tx.rs: use psbt_v2::v2::Psbt;
- use crate::lattice::join::Join;
- use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
+@@ crates/concurrent-psbt/src/psbt/tx.rs: use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
+ use crate::{Conflicts, Lift, ResultWrapped};
  
+ use super::conflicts::PsbtConflict;
 -use super::global::{Global, InvalidGlobal, ResultGlobal, SortKeyDerivation, SortSeed};
 +use super::global::{Global, InvalidGlobal, ResultGlobal, SortKeyDerivation};
  use super::input::{DuplicateInput, Input, InputSet, ResultInputSet, SortKey};
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
          let inputs = || {
              marked_sort_keys(
                  self.inputs
-@@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
+@@ crates/concurrent-psbt/src/psbt/tx.rs: impl Conflicts for ResultUnorderedPsbt {
  #[cfg_attr(coverage_nightly, coverage(off))]
  mod tests {
      use super::*;
@@ crates/concurrent-psbt/src/roles/sorter/order.rs
      apply_permutation(&mut inputs, &mut input_keys);
      apply_permutation(&mut outputs, &mut output_keys);
  
+
+ ## crates/concurrent-psbt/tests/conflicts.rs ##
+@@ crates/concurrent-psbt/tests/conflicts.rs: fn proprietary_sort_fields_keep_their_typed_paths() {
+     use concurrent_psbt::output::OutputField;
+ 
+     let mut global = Global::default();
+-    global.set_sort_seed(SortSeed::try_from(vec![1; 16]).unwrap());
++    global.set_sort_seed(SortSeed::from(vec![1; 16]));
+     global.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysRequired);
+     let mut other = global.clone();
+     other.set_unordered();
+-    other.set_sort_seed(SortSeed::try_from(vec![2; 16]).unwrap());
++    other.set_sort_seed(SortSeed::from(vec![2; 16]));
+     other.set_sort_key_derivation(SortKeyDerivation::ExplicitKeysForbidden);
+     let joined = global.wrap().join(other.wrap());
+     assert_eq!(

@github-actions

Copy link
Copy Markdown
range-diff for force push bd4f1dc8f3 → 70a89f49f2 November 16, 2026 04:47 UTC: 2 modified, 3 unchanged; 5 commits; base 08b4b8fdbf → 3febc3f0ab (diverged, 15 ahead and 15 behind)

reproduce: git range-diff 08b4b8f..bd4f1dc 3febc3f..70a89f4

1:  60572cff53 +234 -201  8f = 1:  3d9e453f54 +234 -201  8f rename sort modes for the explicit keys they allow
2:  1a07a11fdd +130   -7  3f ! 2:  6a5000a0b9 +129   -7  3f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  d9a74d3f90 +962 -964 10f ! 3:  2d5c32d98a +962 -964 10f derive sort keys from the tx UUID in every mode
4:  38cddae543 +121 -152  5f = 4:  6fbf42698e +121 -152  5f allow repeated explicit sort keys
5:  bd4f1dc8f3 +136  -49  6f = 5:  70a89f49f2 +136  -49  6f require non-empty explicit sort keys under derivation 0x00
2: 1a07a11fdd ! 2: 6a5000a0b9 add PSBT_GLOBAL_TX_UUID, set by the Creator
@@ Commit message
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
 @@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
-         pub(crate) unordered: bool = TxUnorderedField,
-         pub(crate) sort_key_derivation: Option<SortKeyDerivation> = SortKeyDerivationField,
-         pub(crate) sort_seed: Option<SortSeed> = SortSeedField,
-+        pub(crate) uuid: Option<TxUuid> = TxUuidField,
+         pub(crate) unordered: bool = TxUnorderedField => Unordered,
+         pub(crate) sort_key_derivation: Option<SortKeyDerivation> = SortKeyDerivationField => SortKeyDerivation(SortKeyDerivation),
+         pub(crate) sort_seed: Option<SortSeed> = SortSeedField => SortSeed(SortSeed),
++        pub(crate) uuid: Option<TxUuid> = TxUuidField => TxUuid(TxUuid),
      },
  }
  
-@@ crates/concurrent-psbt/src/psbt/global.rs: record_conflicts! {
-     Unordered => unordered: bool,
-     SortKeyDerivation => sort_key_derivation: SortKeyDerivation,
-     SortSeed => sort_seed: SortSeed,
-+    TxUuid => uuid: TxUuid,
-     }
- }
- 
  impl Default for Global {
      fn default() -> Self {
 -        Self::from_v2_fields(psbt_v2::v2::Global::default(), false, None, None)
3: d9a74d3f90 ! 3: 2d5c32d98a derive sort keys from the tx UUID in every mode
@@ crates/concurrent-psbt/src/psbt/tx.rs: impl ResultUnorderedPsbt {
          let inputs = || {
              marked_sort_keys(
                  self.inputs
-@@ crates/concurrent-psbt/src/psbt/tx.rs: impl Conflicts for ResultUnorderedPsbt {
- #[cfg_attr(coverage_nightly, coverage(off))]
- mod tests {
+@@ crates/concurrent-psbt/src/psbt/tx.rs: mod tests {
+         }
+     }
      use super::*;
 +    use crate::global::SortSeed;
      use crate::lattice::join::Join;

@github-actions

Copy link
Copy Markdown
range-diff for force push 70a89f49f2 → 0934730995 November 16, 2026 06:07 UTC: 5 unchanged; 5 commits; base 3febc3f0ab → f2148b34d6 (diverged, 15 ahead and 15 behind)

reproduce: git range-diff 3febc3f..70a89f4 f2148b3..0934730

1:  3d9e453f54 +234 -201  8f = 1:  25892ca4e5 +234 -201  8f rename sort modes for the explicit keys they allow
2:  6a5000a0b9 +129   -7  3f = 2:  89c3ea699b +129   -7  3f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  2d5c32d98a +962 -964 10f = 3:  bf4ed02474 +962 -964 10f derive sort keys from the tx UUID in every mode
4:  6fbf42698e +121 -152  5f = 4:  49f793db06 +121 -152  5f allow repeated explicit sort keys
5:  70a89f49f2 +136  -49  6f = 5:  0934730995 +136  -49  6f require non-empty explicit sort keys under derivation 0x00

nothingmuch and others added 5 commits November 16, 2026 18:06
DerivedOnly becomes ExplicitKeysForbidden and ExplicitOnly becomes
ExplicitKeysRequired, with the Creator methods explicit_keys_forbidden
and explicit_keys_required. SortKeyDerivation::Derived and Explicit become
ExplicitKeysForbidden and ExplicitKeysRequired.

The following commits derive a key for every input and output in every
mode, to break ties between explicit keys, so "derived only" no longer
tells the modes apart. What tells them apart is whether explicit keys
are forbidden, required, or optional.

A mechanical rename, with comments reflowed: no behaviour changes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add PSBT_GLOBAL_TX_UUID (subtype 0x13): opaque bytes identifying the
transaction being constructed, with Global::uuid and Global::set_uuid.
It joins as an idempotent value, so two PSBTs with different UUIDs
describe different transactions and do not join.

The Creator sets a fresh random 16-byte UUID on every PSBT. Sorting
does not read it yet. The next commit derives sort keys from it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
PSBT_GLOBAL_TX_UUID becomes the mandatory sort seed. Every sort mode
orders inputs and outputs by explicit sort key, a missing key counting
as empty, and then by derived key. With BIP-340 style tagged hashes
under concurrent-psbt/:
- h = UuidHash(uuid) and e = AuxSortSeedHash(PSBT_GLOBAL_SORT_SEED),
  the latter over the empty string if the seed is unset;
- the sort seed is SortSeedHash(h || e);
- the derived key is SortKeyHash(sort seed || outpoint or unique ID).
Sorting fails with SortError::MissingUuid if the UUID is unset or
empty. Full keys of distinct entries differ, so the sorter's
DuplicateSortKey goes away, and so does MissingSortSeed.

The UUID supplies the entropy, so the sort seed becomes auxiliary: any
length, allowed in every mode. SortSeed::MIN_LEN, InvalidSortSeed,
SortSeedTooShort, UnexpectedSortSeed and SortModeError::MissingSortSeed
are removed. try_set_seed and set_seed keep the mode, since the
auxiliary seed adds no guarantee.

The Seeded typestate now tracks the UUID instead of the sort seed, and
refines all three modes:
- The Creator produces Seeded modes. A parsed PSBT enters an unseeded
  mode, and try_set_uuid on the Constructor or Sorter joins a non-empty
  UUID and refines it; an empty or different UUID is a UuidError.
- try_from_psbt and try_from_unordered_psbt into a Seeded mode reject a
  missing or empty UUID with SortModeError::MissingUuid.
- Seeded Mixed and ExplicitKeysForbidden sort infallibly
  (into_ordered_psbt), and Seeded ExplicitKeysRequired fails only on a
  missing explicit key. Only the unseeded modes can fail with
  SortError::MissingUuid.

Explicit keys must still be distinct; the next commit lifts that.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Derived keys break ties between equal explicit keys, so a repeated
explicit key no longer leaves the order undetermined. Remove the
duplicate-key check: UnorderedPsbtError::DuplicateSortKey, and the
linear scan it ran on every join.

A key is now marked only under a derivation, so mark is never handed
an unset field. It becomes a single Option::map, leaving no unreachable
arm for coverage to miss.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Derivation 0x00 now requires every explicit key to be non-empty. An
empty key is marked as a conflict, as a key under 0x01 already is, and
reported as UnorderedPsbtError::EmptyInputSortKey or
EmptyOutputSortKey. Without a derivation, an empty key is still
allowed, and sorts with the missing ones.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown
range-diff for force push 0934730995 → ed2bcaa7d8 November 16, 2026 18:22 UTC: 5 unchanged; 5 commits; base f2148b34d6 → ad38b7ff84 (diverged, 11 ahead and 11 behind)

reproduce: git range-diff f2148b3..0934730 ad38b7f..ed2bcaa

1:  25892ca4e5 +234 -201  8f = 1:  b517090396 +234 -201  8f rename sort modes for the explicit keys they allow
2:  89c3ea699b +129   -7  3f = 2:  ec8af3a512 +129   -7  3f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  bf4ed02474 +962 -964 10f = 3:  e5e15344a9 +962 -964 10f derive sort keys from the tx UUID in every mode
4:  49f793db06 +121 -152  5f = 4:  16a58eb653 +121 -152  5f allow repeated explicit sort keys
5:  0934730995 +136  -49  6f = 5:  ed2bcaa7d8 +136  -49  6f require non-empty explicit sort keys under derivation 0x00

@github-actions

Copy link
Copy Markdown
range-diff for force push ed2bcaa7d8 → 000109cd49 November 16, 2026 23:45 UTC: 5 unchanged; 5 commits; base ad38b7ff84 → a5b62c8b49 (diverged, 12 ahead and 12 behind)

reproduce: git range-diff ad38b7f..ed2bcaa a5b62c8..000109c

1:  b517090396 +234 -201  8f = 1:  a6bf4807f6 +234 -201  8f rename sort modes for the explicit keys they allow
2:  ec8af3a512 +129   -7  3f = 2:  373335b022 +129   -7  3f add PSBT_GLOBAL_TX_UUID, set by the Creator
3:  e5e15344a9 +962 -964 10f = 3:  faa816fb0d +962 -964 10f derive sort keys from the tx UUID in every mode
4:  16a58eb653 +121 -152  5f = 4:  b2cd0cf6e0 +121 -152  5f allow repeated explicit sort keys
5:  ed2bcaa7d8 +136  -49  6f = 5:  000109cd49 +136  -49  6f require non-empty explicit sort keys under derivation 0x00

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.

3 participants