Skip to content

Introduce keyed set structures for inputs and outputs - #109

Open
yuval-block wants to merge 1 commit into
own-psbt-structsfrom
keyed-set
Open

yuval-block wants to merge 1 commit into
own-psbt-structsfrom
keyed-set

Conversation

@yuval-block

Copy link
Copy Markdown
Collaborator

This abstraction stores a set of inputs or outputs, keyed by their identifier.

This this behaves like the set of identifiers that can union or conflict when joined depending on whether or not it is frozen.

Additionally, with each identifier is also associated a value, so this also works like a hashmap. These values are joined recursively, so a set being frozen only means its identifier set is immutable.

@github-actions

This comment has been minimized.

@github-code-quality

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

Copy link
Copy Markdown

Code coverage overview

Languages: Rust

Rust / code-coverage/cargo-llvm-cov

own-psbt-structs 5f4ab3b keyed-set 8393653 +/-
100% 100% 0%
View coverage of the 10 most impacted files.
File own-psbt-structs 5f4ab3b keyed-set 8393653 +/-
crates/concurre...ons/btreemap.rs 100% 100% 0%
crates/concurre...ions/hashmap.rs 100% 100% 0%
crates/concurre...tions/option.rs 100% 100% 0%
crates/concurre...bt/keyed_set.rs 0% 100% +100%
crates/concurre...bt/conflicts.rs 0% 100% +100%
crates/concurre.../psbt/global.rs 0% 100% +100%
crates/concurre...lattice/lift.rs 0% 100% +100%
crates/concurre...c/psbt/input.rs 0% 100% +100%
crates/concurre.../proprietary.rs 0% 100% +100%
crates/concurre...ce/conflicts.rs 0% 100% +100%

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


Updated November 16, 2026 23:59 UTC

@yuval-block

Copy link
Copy Markdown
Collaborator Author

@xstoicunicornx iirc you had some concerns about representing conflicts between the sets in a previous iteration, i bit the bullet and made this representation more explicit, i thought it would complicate things but having implemented it's simpler than i expected

@github-actions

Copy link
Copy Markdown
range-diff for force push bd1ba6d1de → 3752992766 November 14, 2026 00:52 UTC: 1 modified; 1 commit; same base 933eca83ff

reproduce: git range-diff 933eca8..bd1ba6d 933eca8..3752992

1:  bd1ba6d1de +548 -0 2f ! 1:  3752992766 +547 -0 2f Introduce keyed set structures for inputs and outputs
1: bd1ba6d1de ! 1: 3752992766 Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    }
 +}
 +
-+/// Join of keyed sets of result-domain entries, some of which may be frozen.
++/// The join of any number of [`Freezable`] keyed sets, in the result domain.
 +///
-+/// Entries with the same key are joined and the rest are unioned, whether or
-+/// not their sets are frozen. A frozen set's keys are fixed, so the join also
-+/// keeps each distinct set of frozen keys. It is clean only if there is at
-+/// most one, and it holds the key of every entry: a frozen set joins frozen
-+/// sets with the same keys, and modifiable sets whose keys it holds.
++/// Entries with the same key are joined, and the rest are unioned. A frozen
++/// set's keys are fixed, so each distinct set of frozen keys is also kept.
++/// The join is clean only if there is at most one, and it equals the keys of
++/// the entries. So a frozen set joins cleanly with frozen sets of the same
++/// keys, and with modifiable sets whose keys it already has.
 +///
-+/// The default is the empty modifiable set, which is the identity of the
-+/// join.
++/// The default, the empty modifiable set, is the identity of the join.
 +#[derive(Debug, Clone)]
 +pub(crate) struct ResultKeyedSet<K, V> {
-+    /// Join of the entries of every set.
++    /// Every joined set's entries, with those sharing a key joined into one.
 +    entries: KeyedSet<K, V>,
 +
 +    /// The distinct key sets of the frozen sets, in the order first joined. If any key set is

@github-actions

Copy link
Copy Markdown
range-diff for force push 1f619ad941 → ba82f99d44 November 14, 2026 09:05 UTC: 2 modified, 1 unchanged; 3 commits; same base 19a23f490a

reproduce: git range-diff 19a23f4..1f619ad 19a23f4..ba82f99

1:  d9a908e9b1 +290 -362 10f ! 1:  d14a98c35f +301 -368 10f lift joinable_struct fields by type, not by token
2:  601ce48384 +184 -191  6f ! 2:  7cfd16a301 +183 -191  6f generate v2 conversions from the field lists
3:  1f619ad941 +548   -0  2f = 3:  ba82f99d44 +548   -0  2f Introduce keyed set structures for inputs and outputs
1: d9a908e9b1 ! 1: d14a98c35f lift joinable_struct fields by type, not by token
@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
 -            );
 +            let conflict = Some(Foo(0)).lift().join(Some(Foo(1)).lift());
 +            assert_eq!(conflict.clone().try_unwrap(), Err(conflict));
-+        }
-+
-+        #[test]
-+        fn visits_only_some_conflicts() {
-+            let mut visited = Vec::new();
-+            for value in [
-+                None,
-+                Some(Foo(0)).lift(),
-+                Some(Foo(0)).lift().join(Some(Foo(1)).lift()),
-+            ] {
-+                value.visit_conflicts(&mut |key, conflict| {
-+                    visited.push((key.is_none(), format!("{conflict:?}")));
-+                });
-+            }
-+            assert_eq!(visited.len(), 1);
-+            assert!(visited[0].0);
          }
      }
  
@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
                  proptest::collection::hash_set(arb_foo(), 1..=3)
                      .prop_map(|s| Some(Err(Conflict::from_values(s)))),
              ]
+@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
+             fn is_ok_consistent_with_try_unwrap(a in arb_option_join_result()) {
+                 prop_assert_eq!(a.clone().is_ok(), a.try_unwrap().is_ok());
+             }
++
++            #[test]
++            fn visits_the_conflict_inside_some(a in arb_option_join_result()) {
++                let mut visited = Vec::new();
++                a.visit_conflicts(&mut |key, conflict| {
++                    visited.push((key.is_none(), format!("{conflict:?}")));
++                });
++                let expected = match &a {
++                    Some(Err(conflict)) => vec![(true, format!("{conflict:?}"))],
++                    _ => vec![],
++                };
++                prop_assert_eq!(visited, expected);
++            }
+         }
+     }
+ }
 
  ## crates/concurrent-psbt/src/lattice/lift.rs (new) ##
 @@
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 -    };
  
 -    // --- Type rules ---
-+        impl $crate::lattice::lift::ResultValue for $Result {
-+            type Clean = $Source;
- 
+-
 -    (@source_type scalar $T:ty) => {
 -        $T
 -    };
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 -    (@result_type map [$K:ty => $V:ty]) => {
 -        std::collections::BTreeMap<$K, $crate::lattice::partial::JoinResult<$V>>
 -    };
--
++        impl $crate::lattice::lift::ResultValue for $Result {
++            type Clean = $Source;
+ 
 -    // --- Wrap rules ---
 -
 -    (@wrap scalar $self:ident . $field:ident) => {
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 -    };
  }
  
++/// A struct for the tests, outside their `coverage(off)` module so that its
++/// expansion counts towards the macro's coverage.
  #[cfg(all(test, feature = "unit-tests"))]
-@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: mod tests {
+-#[cfg_attr(coverage_nightly, coverage(off))]
+-mod tests {
++mod sample {
      use std::collections::BTreeMap;
  
-     use crate::lattice::join::Join;
-+    use crate::lattice::lift::ResultValue;
- 
+-    use crate::lattice::join::Join;
+-
      joinable_struct! {
 -        /// One field per category.
 +        /// One field per kind of lifting, the option spelled as a path.
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: mod tests {
          /// Result-domain form of [`Sample`].
          result: ResultSample,
          fields: {
-             scalar: u8,
+-            scalar: u8,
 -            option: Option<u8>,
-+            option: std::option::Option<u8>,
-             map: BTreeMap<u8, u8>,
+-            map: BTreeMap<u8, u8>,
++            pub scalar: u8,
++            pub option: std::option::Option<u8>,
++            pub map: BTreeMap<u8, u8>,
          }
      }
++}
++
++#[cfg(all(test, feature = "unit-tests"))]
++#[cfg_attr(coverage_nightly, coverage(off))]
++mod tests {
++    use std::collections::BTreeMap;
++
++    use super::sample::Sample;
++    use crate::lattice::join::Join;
++    use crate::lattice::lift::ResultValue;
+ 
+     fn sample(scalar: u8, option: u8, value: u8) -> Sample {
+         Sample {
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: mod tests {
      #[test]
      fn equal_structs_join_and_unwrap() {
2: 601ce48384 ! 2: 7cfd16a301 generate v2 conversions from the field lists
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +                        <$Codec as $crate::psbt::proprietary::ProprietaryField>::SUBTYPE,
 +                    );
 +                    base.proprietaries.remove(&key);
-+                    if let Some(value) =
++                    base.proprietaries.extend(
 +                        <$Codec as $crate::psbt::proprietary::ProprietaryField>::encode(
 +                            self.$proprietary,
 +                        )
-+                    {
-+                        base.proprietaries.insert(key, value);
-+                    }
++                        .map(|value| (key, value)),
++                    );
 +                )*
 +                base
 +            }

@github-actions

Copy link
Copy Markdown
range-diff for force push ba82f99d44 → 1b40522363 November 14, 2026 09:38 UTC: 3 modified; 3 commits; base 19a23f490a → 83c0bbb0a0 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 19a23f4..ba82f99 83c0bbb..1b40522

1:  d14a98c35f +301 -368 10f ! 1:  196853c5b3 +324 -590 10f lift joinable_struct fields by type, not by token
2:  7cfd16a301 +183 -191  6f ! 2:  f86b18d263 +241 -208  7f generate v2 conversions from the field lists
3:  ba82f99d44 +548   -0  2f ! 3:  1b40522363 +545   -0  2f Introduce keyed set structures for inputs and outputs
1: d14a98c35f ! 1: 196853c5b3 lift joinable_struct fields by type, not by token
@@ Metadata
  ## Commit message ##
     lift joinable_struct fields by type, not by token
 
-    joinable_struct classified each field by how its type was spelled: bare
-    `Option<..>` and `BTreeMap<..>` selected their rules, and anything else,
-    paths and aliases included, was a scalar. Each operation then had a rule
-    per class.
+    joinable_struct chose each field's rules by matching the spelling of its
+    type: `Option<..>` and `BTreeMap<..>` had their own rules, and every
+    other type was treated as a scalar, including paths to and aliases of
+    those two. Each operation had one rule per kind of field.
 
-    A `Lift` trait now gives each clean type its result-domain counterpart:
-    a `PartialJoin` scalar lifts into a `JoinResult`, and `Option` and
-    `BTreeMap` lift their contents. `ResultValue` (formerly
-    `HashMapResultValue`) checks and extracts, and `VisitConflicts` reports
-    conflicts with their map keys. The macro types each result field as
-    `<T as Lift>::Result` and calls the traits, so it no longer munches
-    tokens, and it implements `ResultValue` for the result struct.
+    The new `Lift` trait maps each clean type to its result-domain type. A
+    `PartialJoin` scalar lifts into a `JoinResult`, and `Option` and
+    `BTreeMap` lift their contents. `ResultValue`, renamed from
+    `HashMapResultValue`, checks for conflicts and extracts the clean value.
+    `VisitConflicts` reports each conflict with its map key. The macro gives
+    each result field the type `<T as Lift>::Result` and calls these traits,
+    so it no longer matches on type tokens. It also implements `ResultValue`
+    for the result struct.
 
-    The extension traits these replace are gone. Extracting an `Option`
-    with a conflict now returns the option rather than the bare conflict,
-    like the other containers.
+    The extension traits that these replace are removed. `try_unwrap` on an
+    `Option` holding a conflict now returns the whole `Option`, as the other
+    containers do, instead of the bare conflict.
 
     Suggested-by: Codex
+
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 
  ## crates/concurrent-psbt/src/collections/btreemap.rs ##
@@ crates/concurrent-psbt/src/collections/btreemap.rs
 -impl<K: Ord, V: PartialJoin> ResultBTreeMapExt for BTreeMap<K, JoinResult<V>> {
 -    type Key = K;
 -    type Value = V;
-+/// A map has no conflicts when none of its values do; extracting it returns
-+/// the whole map if any does.
++/// A map has no conflicts if none of its values have any. Otherwise
++/// `try_unwrap` returns the whole map.
 +impl<K: Ord, R: ResultValue> ResultValue for BTreeMap<K, R> {
 +    type Clean = BTreeMap<K, R::Clean>;
  
@@ crates/concurrent-psbt/src/collections/mod.rs
  //! Each collection type provides crate-internal joins for the result domain,
 -//! plus helper traits for lifting (`wrap`) and lowering (`try_unwrap`) between
 -//! clean and result representations.
-+//! and `Option` and `BTreeMap` implement [`Lift`](crate::lattice::lift::Lift)
-+//! and its companion traits by lifting their contents.
++//! and `Option` and `BTreeMap` implement [`Lift`](crate::lattice::lift::Lift),
++//! [`ResultValue`](crate::lattice::lift::ResultValue) and
++//! [`VisitConflicts`](crate::lattice::lift::VisitConflicts) by lifting their
++//! contents.
  
  pub(crate) mod btreemap;
  pub(crate) mod hashmap;
@@ crates/concurrent-psbt/src/psbt/input.rs
  use bitcoin::bip32::KeySource;
  use bitcoin::hashes::{hash160, ripemd160, sha256, sha256d};
  use bitcoin::key::{PublicKey, XOnlyPublicKey};
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+     #[cfg(feature = "unit-tests")]
+     mod unit {
+         use super::*;
+-        use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
+         use bitcoin::hashes::Hash;
+-        use bitcoin::secp256k1::{Secp256k1, SecretKey};
+-
+-        const ALL_CONFLICT_FIELDS: &[&str] = &[
+-            "previous_txid",
+-            "spent_output_index",
+-            "sequence",
+-            "min_time",
+-            "min_height",
+-            "non_witness_utxo",
+-            "witness_utxo",
+-            "partial_sigs",
+-            "sighash_type",
+-            "redeem_script",
+-            "witness_script",
+-            "bip32_derivations",
+-            "final_script_sig",
+-            "final_script_witness",
+-            "ripemd160_preimages",
+-            "sha256_preimages",
+-            "hash160_preimages",
+-            "hash256_preimages",
+-            "tap_key_sig",
+-            "tap_script_sigs",
+-            "tap_scripts",
+-            "tap_key_origins",
+-            "tap_internal_key",
+-            "tap_merkle_root",
+-            "proprietaries",
+-            "unknowns",
+-        ];
+-
+-        fn empty_conflict<T: PartialJoin>() -> JoinResult<T> {
+-            Err(Conflict::from_values([]))
+-        }
+-
+-        fn all_fields_conflict(seed: u8) -> ResultInput {
+-            let outpoint = OutPoint {
+-                txid: Txid::from_byte_array([seed; 32]),
+-                vout: u32::from(seed),
+-            };
+-            let mut result = Input::new(&outpoint).wrap();
+-
+-            result.previous_txid = empty_conflict();
+-            result.spent_output_index = empty_conflict();
+-            result.sequence = Some(empty_conflict());
+-            result.min_time = Some(empty_conflict());
+-            result.min_height = Some(empty_conflict());
+-            result.non_witness_utxo = Some(empty_conflict());
+-            result.witness_utxo = Some(empty_conflict());
+-            result.sighash_type = Some(empty_conflict());
+-            result.redeem_script = Some(empty_conflict());
+-            result.witness_script = Some(empty_conflict());
+-            result.final_script_sig = Some(empty_conflict());
+-            result.final_script_witness = Some(empty_conflict());
+-            result.tap_key_sig = Some(empty_conflict());
+-            result.tap_internal_key = Some(empty_conflict());
+-            result.tap_merkle_root = Some(empty_conflict());
+-
+-            let secret_key = SecretKey::from_slice(&[seed; 32]).expect("bounded nonzero seed");
+-            let secp_public_key =
+-                bitcoin::secp256k1::PublicKey::from_secret_key(&Secp256k1::new(), &secret_key);
+-            let public_key = PublicKey::new(secp_public_key);
+-            let (x_only_public_key, _) = secp_public_key.x_only_public_key();
+-            let mut control_block = vec![0xc0];
+-            control_block.extend(x_only_public_key.serialize());
+-            let control_block = ControlBlock::decode(&control_block).expect("valid control block");
+-
+-            result.partial_sigs.insert(public_key, empty_conflict());
+-            result
+-                .bip32_derivations
+-                .insert(public_key, empty_conflict());
+-            result.ripemd160_preimages.insert(
+-                ripemd160::Hash::from_byte_array([seed; 20]),
+-                empty_conflict(),
+-            );
+-            result
+-                .sha256_preimages
+-                .insert(sha256::Hash::from_byte_array([seed; 32]), empty_conflict());
+-            result
+-                .hash160_preimages
+-                .insert(hash160::Hash::from_byte_array([seed; 20]), empty_conflict());
+-            result
+-                .hash256_preimages
+-                .insert(sha256d::Hash::from_byte_array([seed; 32]), empty_conflict());
+-            result.tap_script_sigs.insert(
+-                (x_only_public_key, TapLeafHash::from_byte_array([seed; 32])),
+-                empty_conflict(),
+-            );
+-            result.tap_scripts.insert(control_block, empty_conflict());
+-            result
+-                .tap_key_origins
+-                .insert(x_only_public_key, empty_conflict());
+-            result.proprietaries.insert(
+-                raw::ProprietaryKey {
+-                    prefix: vec![seed],
+-                    subtype: seed,
+-                    key: vec![seed],
+-                },
+-                empty_conflict(),
+-            );
+-            result.unknowns.insert(
+-                raw::Key {
+-                    type_value: seed,
+-                    key: vec![seed],
+-                },
+-                empty_conflict(),
+-            );
+-
+-            result
+-        }
+ 
+         fn make_input(txid_byte: u8, vout: u32) -> Input {
+             let txid = bitcoin::Txid::from_byte_array([txid_byte; 32]);
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+         }
+ 
+         #[test]
+-        fn try_unwrap_conflicting_returns_err() {
+-            assert!(
+-                make_input(1, 0)
+-                    .wrap()
+-                    .join(make_input(2, 0).wrap())
+-                    .try_unwrap()
+-                    .is_err()
+-            );
+-        }
+-
+-        #[test]
+-        fn for_each_conflict_reports_every_conflicted_field() {
+-            let result = all_fields_conflict(1);
++        fn inputs_spending_different_outpoints_conflict() {
++            let joined = make_input(1, 0).wrap().join(make_input(2, 0).wrap());
+             let mut fields = Vec::new();
+-            result.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
+-
+-            assert_eq!(fields, ALL_CONFLICT_FIELDS);
++            joined.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
++            assert_eq!(fields, ["previous_txid"]);
++            assert_eq!(joined.clone().try_unwrap(), Err(joined));
+         }
+ 
+         #[test]
+-        fn v2_conversion_keeps_every_field() {
++        fn v2_conversion_round_trips_a_populated_input() {
+             let mut input = make_input(1, 2);
+             input.sequence = Some(Sequence(3));
+             input.proprietaries.insert(
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+         proptest! {
+             #[test]
+             fn wrap_try_unwrap_roundtrip(i in arb_input()) {
+-                let wrapped = i.wrap();
+-                prop_assert!(wrapped.is_ok());
+-                prop_assert!(wrapped.try_unwrap().is_ok());
++                prop_assert_eq!(i.clone().wrap().try_unwrap(), Ok(i));
+             }
+ 
+             #[test]
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+             }
+ 
+             #[test]
+-            fn is_ok_try_unwrap_consistent(r in arb_result_input()) {
+-                if r.is_ok() {
+-                    prop_assert!(r.try_unwrap().is_ok());
+-                } else {
+-                    prop_assert!(r.try_unwrap().is_err());
+-                }
++            fn is_ok_iff_try_unwrap_succeeds(r in arb_result_input()) {
++                prop_assert_eq!(r.is_ok(), r.try_unwrap().is_ok());
+             }
+ 
+         }
 
  ## crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs ##
 @@
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
  
              /// Visit each conflicted field, calling `f(field_name, key, &conflict)`.
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
+             /// callers can tell which entry conflicts. For scalar and option
+             /// fields `key` is `None`.
+             #[cfg_attr(
+-                not(test),
+-                expect(dead_code, reason = "only tests enumerate conflicted fields so far")
++                not(all(test, feature = "unit-tests")),
++                expect(dead_code, reason = "only unit tests enumerate conflicted fields until #44 settles conflict iteration")
+             )]
+             pub(crate) fn for_each_conflict(
+                 &self,
                  mut f: impl FnMut(&str, Option<&dyn std::fmt::Debug>, &dyn std::fmt::Debug),
              ) {
                  $(
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 -    };
  }
  
-+/// A struct for the tests, outside their `coverage(off)` module so that its
-+/// expansion counts towards the macro's coverage.
++// Outside the `coverage(off)` test module, so that this expansion of the
++// macro counts towards coverage.
  #[cfg(all(test, feature = "unit-tests"))]
 -#[cfg_attr(coverage_nightly, coverage(off))]
 -mod tests {
@@ crates/concurrent-psbt/src/psbt/output.rs
 +
  use bitcoin::bip32::KeySource;
  use bitcoin::key::{PublicKey, XOnlyPublicKey};
- use bitcoin::taproot::{TapLeafHash, TapTree};
+ use bitcoin::taproot::TapTree;
+@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
+     #[cfg(feature = "unit-tests")]
+     mod unit {
+         use super::*;
+-        use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
+-        use bitcoin::secp256k1::{Secp256k1, SecretKey};
+-
+-        const ALL_CONFLICT_FIELDS: &[&str] = &[
+-            "unique_id",
+-            "amount",
+-            "script_pubkey",
+-            "redeem_script",
+-            "witness_script",
+-            "bip32_derivations",
+-            "tap_internal_key",
+-            "tap_tree",
+-            "tap_key_origins",
+-            "proprietaries",
+-            "unknowns",
+-        ];
+-
+-        fn empty_conflict<T: PartialJoin>() -> JoinResult<T> {
+-            Err(Conflict::from_values([]))
+-        }
+-
+-        fn all_fields_conflict(seed: u8) -> ResultOutput {
+-            let mut result = output(seed).wrap();
+-            result.unique_id = empty_conflict();
+-            result.amount = empty_conflict();
+-            result.script_pubkey = empty_conflict();
+-            result.redeem_script = Some(empty_conflict());
+-            result.witness_script = Some(empty_conflict());
+-            result.tap_internal_key = Some(empty_conflict());
+-            result.tap_tree = Some(empty_conflict());
+-
+-            let secret_key = SecretKey::from_slice(&[seed; 32]).expect("bounded nonzero seed");
+-            let secp_public_key =
+-                bitcoin::secp256k1::PublicKey::from_secret_key(&Secp256k1::new(), &secret_key);
+-            let public_key = PublicKey::new(secp_public_key);
+-            let (x_only_public_key, _) = secp_public_key.x_only_public_key();
+-            result
+-                .bip32_derivations
+-                .insert(public_key, empty_conflict());
+-            result
+-                .tap_key_origins
+-                .insert(x_only_public_key, empty_conflict());
+-            result.proprietaries.insert(
+-                raw::ProprietaryKey {
+-                    prefix: vec![seed],
+-                    subtype: seed,
+-                    key: vec![seed],
+-                },
+-                empty_conflict(),
+-            );
+-            result.unknowns.insert(
+-                raw::Key {
+-                    type_value: seed,
+-                    key: vec![seed],
+-                },
+-                empty_conflict(),
+-            );
+-            result
+-        }
+ 
+         #[test]
+-        fn try_unwrap_conflicting_returns_err() {
+-            let a = Output {
+-                amount: bitcoin::Amount::from_sat(100),
++        fn outputs_with_different_amounts_conflict() {
++            let with_amount = |sats| Output {
++                amount: Amount::from_sat(sats),
+                 ..output(1)
+             };
+-            let b = Output {
+-                amount: bitcoin::Amount::from_sat(200),
+-                ..output(1)
+-            };
+-            assert!(a.wrap().join(b.wrap()).try_unwrap().is_err());
+-        }
+-
+-        #[test]
+-        fn for_each_conflict_reports_every_conflicted_field() {
+-            let result = all_fields_conflict(1);
++            let joined = with_amount(100).wrap().join(with_amount(200).wrap());
+             let mut fields = Vec::new();
+-            result.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
+-            assert_eq!(fields, ALL_CONFLICT_FIELDS);
++            joined.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
++            assert_eq!(fields, ["amount"]);
++            assert_eq!(joined.clone().try_unwrap(), Err(joined));
+         }
+     }
+ 
+@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
+         proptest! {
+             #[test]
+             fn wrap_try_unwrap_roundtrip(o in arb_output()) {
+-                let wrapped = o.wrap();
+-                prop_assert!(wrapped.is_ok());
+-                prop_assert!(wrapped.try_unwrap().is_ok());
++                prop_assert_eq!(o.clone().wrap().try_unwrap(), Ok(o));
+             }
+ 
+             #[test]
+-            fn is_ok_reflects_content(r in arb_result_output()) {
+-                if r.is_ok() {
+-                    prop_assert!(r.try_unwrap().is_ok());
+-                } else {
+-                    prop_assert!(r.try_unwrap().is_err());
+-                }
++            fn is_ok_iff_try_unwrap_succeeds(r in arb_result_output()) {
++                prop_assert_eq!(r.is_ok(), r.try_unwrap().is_ok());
+             }
+ 
+         }
2: 7cfd16a301 ! 2: f86b18d263 generate v2 conversions from the field lists
@@ Metadata
  ## Commit message ##
     generate v2 conversions from the field lists
 
-    Global, Input and Output each named their fields four times: in the
-    struct, then destructuring a psbt_v2 value, building the struct, and
-    building the psbt_v2 value back. Output also read and wrote its unique
-    ID by hand.
+    Global, Input and Output each listed their fields four times: in the
+    struct definition, when destructuring a psbt_v2 value, when building the
+    struct, and when building the psbt_v2 value back. Output also read and
+    wrote its unique ID by hand.
 
-    joinable_struct now takes the psbt_v2 type and two field lists. `fields`
-    mirror the psbt_v2 fields of the same names. `proprietary` fields each
-    name a `ProprietaryField` codec, which holds the key's subtype and the
-    encoding, so a field keeps its type and join if it is later assigned a
-    standard key. The macro generates:
+    joinable_struct now takes the psbt_v2 type and two field lists. Each
+    entry in `fields` mirrors the psbt_v2 field of the same name. Each entry
+    in `proprietary` names a `ProprietaryField` codec, which defines the
+    field's key subtype and encoding. Changing the key later does not change
+    the field's type or join. The macro generates:
 
-    - `from_v2_fields`, which moves the mirrored fields and takes the
-      proprietary ones as given;
-    - `decode_v2`, which decodes the proprietary fields in order, removing
+    - `from_v2_fields`, which moves the mirrored fields out of a psbt_v2
+      value and takes the proprietary fields as arguments;
+    - `decode_v2`, which decodes the proprietary fields in order and removes
       their keys;
-    - `encode_v2`, which moves the mirrored fields into a base value and
-      encodes the proprietary ones.
+    - `encode_v2`, which moves the mirrored fields into a psbt_v2 value and
+      encodes the proprietary fields into it.
 
-    The conversions keep only what differs: Global derives its version and
-    counts, Input starts from its outpoint, and Output's unique ID is a
-    required proprietary field. The encoders assign fields one by one, so
-    psbt_v2 fields this crate does not mirror keep their base values without
-    a `needless_update` expectation.
+    If a mirrored field's type differs from the psbt_v2 field's, an `=`
+    after the type names a `MirroredField` that converts between them.
+    tap_key_origins uses this to convert each key's leaf hashes to and from
+    TapLeafHashes.
+
+    The hand-written conversions now handle only the fields that the macro
+    does not. Global sets the version and the counts, Input starts from its
+    outpoint, and Output lists its unique ID as a proprietary field.
+    encode_v2 assigns the fields one at a time, so psbt_v2 fields that this
+    crate does not mirror keep their values, and the `needless_update`
+    expectations are removed.
 
     Suggested-by: Codex
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
      }
  }
  
-@@ crates/concurrent-psbt/src/psbt/global.rs: impl Default for Global {
- /// derives.
+ /// Drops the version and the input and output counts.
  impl From<psbt_v2::v2::Global> for Global {
      fn from(global: psbt_v2::v2::Global) -> Self {
 -        let psbt_v2::v2::Global {
@@ crates/concurrent-psbt/src/psbt/global.rs: impl Default for Global {
  
 
  ## crates/concurrent-psbt/src/psbt/input.rs ##
+@@ crates/concurrent-psbt/src/psbt/input.rs: use bitcoin::{OutPoint, ScriptBuf, Sequence, Transaction, TxOut, Txid, Witness,
+ use psbt_v2::PsbtSighashType;
+ use psbt_v2::raw;
+ 
+-use super::tap_leaf_hashes::{TapLeafHashes, tap_key_origins_from_v2, tap_key_origins_into_v2};
++use super::tap_leaf_hashes::{TapKeyOrigins, TapLeafHashes};
+ 
+ joinable_struct! {
+     /// A PSBT input, mirroring the BIP 370 per-input map.
 @@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
-     /// lift a clean [`Input`] into this type, and [`ResultInput::try_unwrap`]
-     /// to recover the clean value once all conflicts are resolved.
+     /// [`Input`] into this type, and [`ResultInput::try_unwrap`] returns it if
+     /// no field conflicts.
      result: ResultInput,
 +    v2: psbt_v2::v2::Input,
      fields: {
          pub previous_txid: Txid,
          pub spent_output_index: u32,
 @@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
+         pub tap_key_sig: Option<taproot::Signature>,
+         pub tap_script_sigs: BTreeMap<(XOnlyPublicKey, TapLeafHash), taproot::Signature>,
+         pub tap_scripts: BTreeMap<ControlBlock, (ScriptBuf, LeafVersion)>,
+-        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)>,
++        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins,
+         pub tap_internal_key: Option<XOnlyPublicKey>,
          pub tap_merkle_root: Option<TapNodeHash>,
          pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
          pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
 -            tap_key_sig,
 -            tap_script_sigs,
 -            tap_scripts,
--            tap_key_origins,
+-            tap_key_origins: tap_key_origins_from_v2(tap_key_origins),
 -            tap_internal_key,
 -            tap_merkle_root,
 -            proprietaries,
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
 -            tap_key_sig: input.tap_key_sig,
 -            tap_script_sigs: input.tap_script_sigs,
 -            tap_scripts: input.tap_scripts,
--            tap_key_origins: input.tap_key_origins,
+-            tap_key_origins: tap_key_origins_into_v2(input.tap_key_origins),
 -            tap_internal_key: input.tap_internal_key,
 -            tap_merkle_root: input.tap_merkle_root,
 -            proprietaries: input.proprietaries,
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
  
 
  ## crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs ##
+@@
++/// Converts a mirrored field whose type differs from the psbt-v2 field of the
++/// same name.
++pub(crate) trait MirroredField {
++    /// The psbt-v2 field's type.
++    type V2;
++    /// The field's type.
++    type Value;
++    /// Convert from the psbt-v2 field.
++    fn from_v2(value: Self::V2) -> Self::Value;
++    /// Convert into the psbt-v2 field.
++    fn into_v2(value: Self::Value) -> Self::V2;
++}
++
+ /// Generate a product type, its result-domain counterpart, and their lattice
+ /// operations from a single field list using standard Rust type syntax.
+ ///
 @@
  /// 4. `Join for $Result`
  /// 5. `$Result::is_ok`, `$Result::for_each_conflict` and `$Result::try_unwrap`
  /// 6. `ResultValue for $Result`
 +///
-+/// Given a `v2` type, `fields` mirror its fields of the same names, and
-+/// `proprietary` fields are stored in its proprietary keys, each through the
-+/// [`ProprietaryField`](crate::psbt::proprietary::ProprietaryField) codec
-+/// named after its `=`. The struct then has private conversions:
++/// Each entry in `fields` mirrors the field of the same name in the `v2` type.
++/// If the two types differ, an `=` after the type names the [`MirroredField`]
++/// that converts between them. Each entry in `proprietary` is written
++/// `name: Type = Codec`, and is stored in a proprietary key of `v2` by the
++/// [`ProprietaryField`](crate::psbt::proprietary::ProprietaryField) impl
++/// `Codec`. The struct then has private conversions:
 +///
 +/// - `from_v2_fields(v2, proprietary...)` moves the mirrored fields out of
 +///   `v2` and takes the proprietary fields as given;
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +        result: $Result:ident,
 +        v2: $V2:path,
 +        fields: {
-+            $( $(#[$field_meta:meta])* $vis:vis $field:ident : $T:ty ),+ $(,)?
++            $(
++                $(#[$field_meta:meta])* $vis:vis
++                $field:ident : $T:ty $( = $Conversion:ty )?
++            ),+ $(,)?
 +        },
 +        proprietary: {
 +            $(
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +            /// The mirrored fields of `v2`, with these proprietary fields.
 +            fn from_v2_fields(v2: $V2, $( $proprietary: $P ),*) -> Self {
 +                Self {
-+                    $( $field: v2.$field, )+
++                    $( $field: joinable_struct!(@from_v2 v2.$field $(, $Conversion)?), )+
 +                    $( $proprietary, )*
 +                }
 +            }
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +            /// move its mirrored fields.
 +            ///
 +            /// # Errors
-+            /// Returns the first proprietary field that does not decode.
++            /// Returns the error of the first proprietary field that does not
++            /// decode.
 +            fn decode_v2<E>(v2: $V2) -> Result<Self, E>
 +            where
 +                $( E: From<<$Codec as $crate::psbt::proprietary::ProprietaryField>::Error>, )*
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +            /// Move the mirrored fields into `base`, and encode the proprietary
 +            /// fields into its proprietary keys.
 +            ///
-+            /// The proprietary fields own their keys: a key that a field leaves
-+            /// out is removed, even if `self.proprietaries` holds it.
++            /// If a proprietary field encodes to `None`, its key is removed from
++            /// `base`, even if `self.proprietaries` has it.
 +            fn encode_v2(self, mut base: $V2) -> $V2 {
-+                $( base.$field = self.$field; )+
++                $( base.$field = joinable_struct!(@into_v2 self.$field $(, $Conversion)?); )+
 +                $(
 +                    let key = $crate::psbt::proprietary::key(
 +                        <$Codec as $crate::psbt::proprietary::ProprietaryField>::SUBTYPE,
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +        }
 +    };
 +
++    (@from_v2 $value:expr) => {
++        $value
++    };
++
++    (@from_v2 $value:expr, $Conversion:ty) => {
++        <$Conversion as $crate::psbt::joinable_struct_macro::MirroredField>::from_v2($value)
++    };
++
++    (@into_v2 $value:expr) => {
++        $value
++    };
++
++    (@into_v2 $value:expr, $Conversion:ty) => {
++        <$Conversion as $crate::psbt::joinable_struct_macro::MirroredField>::into_v2($value)
++    };
++
 +    (@decode $v2:ident []) => {
 +        Ok(Self::from_v2_fields($v2))
 +    };
@@ crates/concurrent-psbt/src/psbt/mod.rs: mod joinable_struct_macro;
  pub mod input;
  pub mod output;
 +pub(crate) mod proprietary;
+ mod tap_leaf_hashes;
  mod values;
+ 
 
  ## crates/concurrent-psbt/src/psbt/output.rs ##
-@@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::taproot::{TapLeafHash, TapTree};
+@@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::taproot::TapTree;
  use bitcoin::{Amount, ScriptBuf};
  use psbt_v2::raw;
  
+-use super::tap_leaf_hashes::{TapLeafHashes, tap_key_origins_from_v2, tap_key_origins_into_v2};
 +use super::proprietary::ProprietaryField;
-+
++use super::tap_leaf_hashes::{TapKeyOrigins, TapLeafHashes};
+ 
  joinable_struct! {
      /// A PSBT output, mirroring the BIP 370 per-output map, identified by its
-     /// [`UniqueId`].
 @@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
-     /// Each field is represented in the internal result domain, recording
-     /// either a clean value or an accumulated conflict.
+     ///
+     /// Each field holds a clean value or a conflict.
      result: ResultOutput,
 +    v2: psbt_v2::v2::Output,
      fields: {
@@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
          pub script_pubkey: ScriptBuf,
          pub redeem_script: Option<ScriptBuf>,
 @@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
-         pub tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>,
+         pub bip32_derivations: BTreeMap<PublicKey, KeySource>,
+         pub tap_internal_key: Option<XOnlyPublicKey>,
+         pub tap_tree: Option<TapTree>,
+-        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)>,
++        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins,
          pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
          pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
 -    }
@@ crates/concurrent-psbt/src/psbt/output.rs: impl Output {
 -            bip32_derivations,
 -            tap_internal_key,
 -            tap_tree,
--            tap_key_origins,
+-            tap_key_origins: tap_key_origins_from_v2(tap_key_origins),
 -            proprietaries,
 -            unknowns,
 -        }
@@ crates/concurrent-psbt/src/psbt/output.rs: impl TryFrom<psbt_v2::v2::Output> for
 -            bip32_derivations: output.bip32_derivations,
 -            tap_internal_key: output.tap_internal_key,
 -            tap_tree: output.tap_tree,
--            tap_key_origins: output.tap_key_origins,
+-            tap_key_origins: tap_key_origins_into_v2(output.tap_key_origins),
 -            proprietaries,
 -            unknowns: output.unknowns,
 -            ..psbt_v2::v2::Output::default()
@@ crates/concurrent-psbt/src/psbt/output.rs: impl std::error::Error for InvalidUni
 -        prefix: b"concurrent-psbt".to_vec(),
 -        subtype: PSBT_OUT_UNIQUE_ID_SUBTYPE,
 -        key: vec![],
-+/// `PSBT_OUT_UNIQUE_ID`, which every [`Output`] has.
++/// Stores an output's unique ID in `PSBT_OUT_UNIQUE_ID`.
 +struct UniqueIdField;
 +
 +impl ProprietaryField for UniqueIdField {
@@ crates/concurrent-psbt/src/psbt/output.rs: pub(crate) trait OutputUniqueIdExt {
      }
  }
  
-@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
-         use bitcoin::secp256k1::{Secp256k1, SecretKey};
- 
-         const ALL_CONFLICT_FIELDS: &[&str] = &[
--            "unique_id",
-             "amount",
-             "script_pubkey",
-             "redeem_script",
-@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
-             "tap_key_origins",
-             "proprietaries",
-             "unknowns",
-+            "unique_id",
-         ];
- 
-         fn empty_conflict<T: PartialJoin>() -> JoinResult<T> {
 
  ## crates/concurrent-psbt/src/psbt/proprietary.rs (new) ##
 @@
@@ crates/concurrent-psbt/src/psbt/proprietary.rs (new)
 +
 +/// How a field this crate defines is stored in a proprietary key.
 +///
-+/// The key and encoding belong to the codec rather than the field, so a field
-+/// keeps its type and join when its key changes.
++/// A field's key and encoding are defined by its codec, so changing them does
++/// not change the field's type or join.
 +pub(crate) trait ProprietaryField {
 +    /// The subtype of the field's key under [`PREFIX`].
 +    const SUBTYPE: u8;
@@ crates/concurrent-psbt/src/psbt/proprietary.rs (new)
 +    /// Encode the field as its key's value, or `None` to leave the key out.
 +    fn encode(value: Self::Value) -> Option<Vec<u8>>;
 +}
+
+ ## crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs ##
+@@ crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs: use bitcoin::TapLeafHash;
+ use bitcoin::bip32::KeySource;
+ use bitcoin::secp256k1::XOnlyPublicKey;
+ 
++use super::joinable_struct_macro::MirroredField;
+ use crate::values::IdempotentValue;
+ 
+ /// The leaf hashes of a taproot key in `PSBT_{IN,OUT}_TAP_BIP32_DERIVATION`.
+@@ crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs: impl IdempotentValue for (TapLeafHashes, KeySource) {}
+ /// `PSBT_{IN,OUT}_TAP_BIP32_DERIVATION` as psbt-v2 stores it.
+ type V2TapKeyOrigins = BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>;
+ 
+-/// `PSBT_{IN,OUT}_TAP_BIP32_DERIVATION` with set equality on the leaf hashes.
+-type TapKeyOrigins = BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)>;
++/// Converts `tap_key_origins` between psbt-v2's leaf hash lists and
++/// [`TapLeafHashes`].
++pub(crate) enum TapKeyOrigins {}
+ 
+-pub(crate) fn tap_key_origins_from_v2(origins: V2TapKeyOrigins) -> TapKeyOrigins {
+-    origins
+-        .into_iter()
+-        .map(|(key, (leaves, source))| (key, (leaves.into(), source)))
+-        .collect()
+-}
++impl MirroredField for TapKeyOrigins {
++    type V2 = V2TapKeyOrigins;
++    type Value = BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)>;
++
++    fn from_v2(origins: Self::V2) -> Self::Value {
++        origins
++            .into_iter()
++            .map(|(key, (leaves, source))| (key, (leaves.into(), source)))
++            .collect()
++    }
+ 
+-pub(crate) fn tap_key_origins_into_v2(origins: TapKeyOrigins) -> V2TapKeyOrigins {
+-    origins
+-        .into_iter()
+-        .map(|(key, (leaves, source))| (key, (leaves.into(), source)))
+-        .collect()
++    fn into_v2(origins: Self::Value) -> Self::V2 {
++        origins
++            .into_iter()
++            .map(|(key, (leaves, source))| (key, (leaves.into(), source)))
++            .collect()
++    }
+ }
+ 
+ #[cfg(all(test, feature = "prop-tests"))]
+@@ crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs: mod tests {
+ 
+         #[test]
+         fn v2_round_trip_keeps_the_lists(origins in arb_v2_tap_key_origins()) {
+-            prop_assert_eq!(tap_key_origins_into_v2(tap_key_origins_from_v2(origins.clone())), origins);
++            prop_assert_eq!(TapKeyOrigins::into_v2(TapKeyOrigins::from_v2(origins.clone())), origins);
+         }
+     }
+ }
3: ba82f99d44 ! 3: 1b40522363 Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 @@
 +//! Keyed sets of PSBT entries, some of which may be frozen.
 +//!
-+//! A [`KeyedSet`] holds entries with distinct keys, namely inputs keyed by their outpoints and
-+//! outputs keyed by their unique id. Its result-domain counterpart, [`ResultKeyedSet`], joins sets
-+//! entry by entry.
++//! A [`KeyedSet`] holds entries with distinct keys: inputs keyed by their outpoints, or outputs
++//! keyed by their unique IDs. A [`ResultKeyedSet`] is the join of any number of [`Freezable`]
++//! keyed sets, and joins the entries that share a key.
 +//!
-+//! For handling (non-)modifiability in a consistent manner (respecting idempotence, commutativity
-+//! and associativity), a set can be [`Frozen`](Freezable::Frozen), as a PSBT's inputs or outputs
-+//! are once the either set is no longer modifiable. This fixes the set of keys for that particular element, allowing the
-+//! values associated with these entries to still be joined to accumulate additional information
-+//! associated with the inputs or outputs, without changing the set of spent or created coins
-+//! itself. Conflicts about membership are represented as conflicting sets of identifiers.
++//! A PSBT's inputs or outputs are [`Frozen`](Freezable::Frozen) once they are no longer
++//! modifiable. The keys of a frozen set are fixed, so no input or output can be added or removed,
++//! but its entries can still be joined with entries that add information to them. A
++//! [`ResultKeyedSet`] keeps every distinct frozen key set it joins, which keeps the join
++//! idempotent, commutative and associative. It is clean only if the keys of its entries match
++//! the frozen key sets.
 +
 +use std::collections::hash_map::{Entry, IntoValues};
 +use std::collections::{HashMap, HashSet};
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +
 +/// A [`KeyedSet`] whose keys may be frozen.
 +///
-+/// A PSBT's inputs or outputs are frozen once they are no longer modifiable. In a given PSBT this
-+/// enum tag must track the `tx_modifiable_flags` in the `Global` struct.
++/// A PSBT's inputs or outputs are `Frozen` when the matching bit of `tx_modifiable_flags` is
++/// clear.
 +#[derive(Debug, Clone)]
 +pub(crate) enum Freezable<K, V> {
 +    /// Modifiable sets can be joined, unioning their keys and joining values
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +///
 +/// Entries with the same key are joined, and the rest are unioned. A frozen
 +/// set's keys are fixed, so each distinct set of frozen keys is also kept.
-+/// The join is clean only if there is at most one, and it equals the keys of
-+/// the entries. So a frozen set joins cleanly with frozen sets of the same
-+/// keys, and with modifiable sets whose keys it already has.
++/// The join is clean only if there is at most one distinct frozen key set and
++/// it equals the keys of the entries. So a frozen set joins cleanly with
++/// frozen sets of the same keys, and with modifiable sets whose keys it
++/// already has.
 +///
 +/// The default, the empty modifiable set, is the identity of the join.
 +#[derive(Debug, Clone)]
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    /// Every joined set's entries, with those sharing a key joined into one.
 +    entries: KeyedSet<K, V>,
 +
-+    /// The distinct key sets of the frozen sets, in the order first joined. If any key set is
-+    /// frozen, then it must exactly match the keys of the entries, otherwise the entire
-+    /// ResultKeyedSet is in a conflicted state.
++    /// The distinct key sets of the frozen sets, in the order first joined.
 +    frozen: Vec<HashSet<K>>,
 +}
 +
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    /// Return the number of entries, or the conflicting sizes of the frozen
 +    /// key sets and the entries.
 +    ///
-+    /// Each frozen set's keys are among the entries', so the sizes all agree
-+    /// exactly when the keys agree with the frozen sets.
++    /// Every frozen key set is a subset of the keys of the entries, so the
++    /// sizes are all equal only if the keys agree with the frozen sets.
 +    pub(crate) fn len(&self) -> JoinResult<usize> {
 +        self.frozen
 +            .iter()
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +        self.entries.is_empty()
 +    }
 +
-+    /// Return `true` if at most one set of frozen keys remains, and it holds
-+    /// the key of every entry: exactly when [`len`](Self::len) is `Ok`.
++    /// Return `true` if there is at most one frozen key set and it holds the
++    /// key of every entry, which is when [`len`](Self::len) is `Ok`.
 +    fn keys_agree(&self) -> bool {
 +        self.len().is_ok()
 +    }
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +
 +        proptest! {
 +            #[test]
-+            fn try_from_entries_reports_the_first_error_or_repeat(
-+                entries in proptest::collection::vec(
-+                    prop_oneof![
-+                        3 => (0u8..4, any::<u8>()).prop_map(Ok),
-+                        1 => (4u8..8).prop_map(Err),
-+                    ],
-+                    0..=5,
++            fn try_from_entries_stops_at_the_first_failure(
++                keys in proptest::collection::hash_set(0u8..8, 1..=4),
++                repeat in any::<proptest::sample::Index>(),
++                error in proptest::option::of(200u8..),
++                tail in proptest::collection::vec(
++                    prop_oneof![(0u8..8, any::<u8>()).prop_map(Ok), (200u8..).prop_map(Err)],
++                    0..=3,
 +                ),
 +            ) {
-+                let mut seen = HashSet::new();
-+                let expected = entries.iter().find_map(|entry| match entry {
-+                    Ok((key, _)) => (!seen.insert(*key)).then_some(key + 100),
-+                    Err(error) => Some(*error),
-+                });
-+                match (collect(entries.clone()), expected) {
-+                    (Ok(set), None) => {
-+                        prop_assert_eq!(set.len(), entries.len());
-+                        prop_assert_eq!(set.is_empty(), entries.is_empty());
-+                        for (key, _) in entries.iter().flatten() {
-+                            prop_assert!(set.contains_key(key));
-+                        }
++                let keys: Vec<u8> = keys.into_iter().collect();
++                let distinct: Vec<_> = keys.iter().map(|&key| Ok((key, key))).collect();
++                let set = collect(distinct.clone()).expect("distinct keys");
++                prop_assert_eq!(set.len(), keys.len());
++                prop_assert!(keys.iter().all(|key| set.contains_key(key)));
++
++                // A failure after distinct keys: an error, or a repeated key.
++                let (failure, expected) = match error {
++                    Some(error) => (Err(error), error),
++                    None => {
++                        let key = keys[repeat.index(keys.len())];
++                        (Ok((key, 0)), key + 100)
 +                    }
-+                    (Err(error), Some(expected)) => prop_assert_eq!(error, expected),
-+                    (result, expected) => {
-+                        prop_assert!(false, "{result:?} disagrees with {expected:?}");
-+                    }
-+                }
++                };
++                let entries = distinct.into_iter().chain([failure]).chain(tail).collect();
++                prop_assert_eq!(collect(entries), Err(expected));
 +            }
 +
 +            #[test]
@@ crates/concurrent-psbt/src/psbt/mod.rs
 +mod keyed_set;
  pub mod output;
  pub(crate) mod proprietary;
- mod values;
+ mod tap_leaf_hashes;

1 similar comment
@github-actions

Copy link
Copy Markdown
range-diff for force push ba82f99d44 → 1b40522363 November 14, 2026 09:38 UTC: 3 modified; 3 commits; base 19a23f490a → 83c0bbb0a0 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 19a23f4..ba82f99 83c0bbb..1b40522

1:  d14a98c35f +301 -368 10f ! 1:  196853c5b3 +324 -590 10f lift joinable_struct fields by type, not by token
2:  7cfd16a301 +183 -191  6f ! 2:  f86b18d263 +241 -208  7f generate v2 conversions from the field lists
3:  ba82f99d44 +548   -0  2f ! 3:  1b40522363 +545   -0  2f Introduce keyed set structures for inputs and outputs
1: d14a98c35f ! 1: 196853c5b3 lift joinable_struct fields by type, not by token
@@ Metadata
  ## Commit message ##
     lift joinable_struct fields by type, not by token
 
-    joinable_struct classified each field by how its type was spelled: bare
-    `Option<..>` and `BTreeMap<..>` selected their rules, and anything else,
-    paths and aliases included, was a scalar. Each operation then had a rule
-    per class.
+    joinable_struct chose each field's rules by matching the spelling of its
+    type: `Option<..>` and `BTreeMap<..>` had their own rules, and every
+    other type was treated as a scalar, including paths to and aliases of
+    those two. Each operation had one rule per kind of field.
 
-    A `Lift` trait now gives each clean type its result-domain counterpart:
-    a `PartialJoin` scalar lifts into a `JoinResult`, and `Option` and
-    `BTreeMap` lift their contents. `ResultValue` (formerly
-    `HashMapResultValue`) checks and extracts, and `VisitConflicts` reports
-    conflicts with their map keys. The macro types each result field as
-    `<T as Lift>::Result` and calls the traits, so it no longer munches
-    tokens, and it implements `ResultValue` for the result struct.
+    The new `Lift` trait maps each clean type to its result-domain type. A
+    `PartialJoin` scalar lifts into a `JoinResult`, and `Option` and
+    `BTreeMap` lift their contents. `ResultValue`, renamed from
+    `HashMapResultValue`, checks for conflicts and extracts the clean value.
+    `VisitConflicts` reports each conflict with its map key. The macro gives
+    each result field the type `<T as Lift>::Result` and calls these traits,
+    so it no longer matches on type tokens. It also implements `ResultValue`
+    for the result struct.
 
-    The extension traits these replace are gone. Extracting an `Option`
-    with a conflict now returns the option rather than the bare conflict,
-    like the other containers.
+    The extension traits that these replace are removed. `try_unwrap` on an
+    `Option` holding a conflict now returns the whole `Option`, as the other
+    containers do, instead of the bare conflict.
 
     Suggested-by: Codex
+
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 
  ## crates/concurrent-psbt/src/collections/btreemap.rs ##
@@ crates/concurrent-psbt/src/collections/btreemap.rs
 -impl<K: Ord, V: PartialJoin> ResultBTreeMapExt for BTreeMap<K, JoinResult<V>> {
 -    type Key = K;
 -    type Value = V;
-+/// A map has no conflicts when none of its values do; extracting it returns
-+/// the whole map if any does.
++/// A map has no conflicts if none of its values have any. Otherwise
++/// `try_unwrap` returns the whole map.
 +impl<K: Ord, R: ResultValue> ResultValue for BTreeMap<K, R> {
 +    type Clean = BTreeMap<K, R::Clean>;
  
@@ crates/concurrent-psbt/src/collections/mod.rs
  //! Each collection type provides crate-internal joins for the result domain,
 -//! plus helper traits for lifting (`wrap`) and lowering (`try_unwrap`) between
 -//! clean and result representations.
-+//! and `Option` and `BTreeMap` implement [`Lift`](crate::lattice::lift::Lift)
-+//! and its companion traits by lifting their contents.
++//! and `Option` and `BTreeMap` implement [`Lift`](crate::lattice::lift::Lift),
++//! [`ResultValue`](crate::lattice::lift::ResultValue) and
++//! [`VisitConflicts`](crate::lattice::lift::VisitConflicts) by lifting their
++//! contents.
  
  pub(crate) mod btreemap;
  pub(crate) mod hashmap;
@@ crates/concurrent-psbt/src/psbt/input.rs
  use bitcoin::bip32::KeySource;
  use bitcoin::hashes::{hash160, ripemd160, sha256, sha256d};
  use bitcoin::key::{PublicKey, XOnlyPublicKey};
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+     #[cfg(feature = "unit-tests")]
+     mod unit {
+         use super::*;
+-        use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
+         use bitcoin::hashes::Hash;
+-        use bitcoin::secp256k1::{Secp256k1, SecretKey};
+-
+-        const ALL_CONFLICT_FIELDS: &[&str] = &[
+-            "previous_txid",
+-            "spent_output_index",
+-            "sequence",
+-            "min_time",
+-            "min_height",
+-            "non_witness_utxo",
+-            "witness_utxo",
+-            "partial_sigs",
+-            "sighash_type",
+-            "redeem_script",
+-            "witness_script",
+-            "bip32_derivations",
+-            "final_script_sig",
+-            "final_script_witness",
+-            "ripemd160_preimages",
+-            "sha256_preimages",
+-            "hash160_preimages",
+-            "hash256_preimages",
+-            "tap_key_sig",
+-            "tap_script_sigs",
+-            "tap_scripts",
+-            "tap_key_origins",
+-            "tap_internal_key",
+-            "tap_merkle_root",
+-            "proprietaries",
+-            "unknowns",
+-        ];
+-
+-        fn empty_conflict<T: PartialJoin>() -> JoinResult<T> {
+-            Err(Conflict::from_values([]))
+-        }
+-
+-        fn all_fields_conflict(seed: u8) -> ResultInput {
+-            let outpoint = OutPoint {
+-                txid: Txid::from_byte_array([seed; 32]),
+-                vout: u32::from(seed),
+-            };
+-            let mut result = Input::new(&outpoint).wrap();
+-
+-            result.previous_txid = empty_conflict();
+-            result.spent_output_index = empty_conflict();
+-            result.sequence = Some(empty_conflict());
+-            result.min_time = Some(empty_conflict());
+-            result.min_height = Some(empty_conflict());
+-            result.non_witness_utxo = Some(empty_conflict());
+-            result.witness_utxo = Some(empty_conflict());
+-            result.sighash_type = Some(empty_conflict());
+-            result.redeem_script = Some(empty_conflict());
+-            result.witness_script = Some(empty_conflict());
+-            result.final_script_sig = Some(empty_conflict());
+-            result.final_script_witness = Some(empty_conflict());
+-            result.tap_key_sig = Some(empty_conflict());
+-            result.tap_internal_key = Some(empty_conflict());
+-            result.tap_merkle_root = Some(empty_conflict());
+-
+-            let secret_key = SecretKey::from_slice(&[seed; 32]).expect("bounded nonzero seed");
+-            let secp_public_key =
+-                bitcoin::secp256k1::PublicKey::from_secret_key(&Secp256k1::new(), &secret_key);
+-            let public_key = PublicKey::new(secp_public_key);
+-            let (x_only_public_key, _) = secp_public_key.x_only_public_key();
+-            let mut control_block = vec![0xc0];
+-            control_block.extend(x_only_public_key.serialize());
+-            let control_block = ControlBlock::decode(&control_block).expect("valid control block");
+-
+-            result.partial_sigs.insert(public_key, empty_conflict());
+-            result
+-                .bip32_derivations
+-                .insert(public_key, empty_conflict());
+-            result.ripemd160_preimages.insert(
+-                ripemd160::Hash::from_byte_array([seed; 20]),
+-                empty_conflict(),
+-            );
+-            result
+-                .sha256_preimages
+-                .insert(sha256::Hash::from_byte_array([seed; 32]), empty_conflict());
+-            result
+-                .hash160_preimages
+-                .insert(hash160::Hash::from_byte_array([seed; 20]), empty_conflict());
+-            result
+-                .hash256_preimages
+-                .insert(sha256d::Hash::from_byte_array([seed; 32]), empty_conflict());
+-            result.tap_script_sigs.insert(
+-                (x_only_public_key, TapLeafHash::from_byte_array([seed; 32])),
+-                empty_conflict(),
+-            );
+-            result.tap_scripts.insert(control_block, empty_conflict());
+-            result
+-                .tap_key_origins
+-                .insert(x_only_public_key, empty_conflict());
+-            result.proprietaries.insert(
+-                raw::ProprietaryKey {
+-                    prefix: vec![seed],
+-                    subtype: seed,
+-                    key: vec![seed],
+-                },
+-                empty_conflict(),
+-            );
+-            result.unknowns.insert(
+-                raw::Key {
+-                    type_value: seed,
+-                    key: vec![seed],
+-                },
+-                empty_conflict(),
+-            );
+-
+-            result
+-        }
+ 
+         fn make_input(txid_byte: u8, vout: u32) -> Input {
+             let txid = bitcoin::Txid::from_byte_array([txid_byte; 32]);
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+         }
+ 
+         #[test]
+-        fn try_unwrap_conflicting_returns_err() {
+-            assert!(
+-                make_input(1, 0)
+-                    .wrap()
+-                    .join(make_input(2, 0).wrap())
+-                    .try_unwrap()
+-                    .is_err()
+-            );
+-        }
+-
+-        #[test]
+-        fn for_each_conflict_reports_every_conflicted_field() {
+-            let result = all_fields_conflict(1);
++        fn inputs_spending_different_outpoints_conflict() {
++            let joined = make_input(1, 0).wrap().join(make_input(2, 0).wrap());
+             let mut fields = Vec::new();
+-            result.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
+-
+-            assert_eq!(fields, ALL_CONFLICT_FIELDS);
++            joined.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
++            assert_eq!(fields, ["previous_txid"]);
++            assert_eq!(joined.clone().try_unwrap(), Err(joined));
+         }
+ 
+         #[test]
+-        fn v2_conversion_keeps_every_field() {
++        fn v2_conversion_round_trips_a_populated_input() {
+             let mut input = make_input(1, 2);
+             input.sequence = Some(Sequence(3));
+             input.proprietaries.insert(
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+         proptest! {
+             #[test]
+             fn wrap_try_unwrap_roundtrip(i in arb_input()) {
+-                let wrapped = i.wrap();
+-                prop_assert!(wrapped.is_ok());
+-                prop_assert!(wrapped.try_unwrap().is_ok());
++                prop_assert_eq!(i.clone().wrap().try_unwrap(), Ok(i));
+             }
+ 
+             #[test]
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+             }
+ 
+             #[test]
+-            fn is_ok_try_unwrap_consistent(r in arb_result_input()) {
+-                if r.is_ok() {
+-                    prop_assert!(r.try_unwrap().is_ok());
+-                } else {
+-                    prop_assert!(r.try_unwrap().is_err());
+-                }
++            fn is_ok_iff_try_unwrap_succeeds(r in arb_result_input()) {
++                prop_assert_eq!(r.is_ok(), r.try_unwrap().is_ok());
+             }
+ 
+         }
 
  ## crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs ##
 @@
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
  
              /// Visit each conflicted field, calling `f(field_name, key, &conflict)`.
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
+             /// callers can tell which entry conflicts. For scalar and option
+             /// fields `key` is `None`.
+             #[cfg_attr(
+-                not(test),
+-                expect(dead_code, reason = "only tests enumerate conflicted fields so far")
++                not(all(test, feature = "unit-tests")),
++                expect(dead_code, reason = "only unit tests enumerate conflicted fields until #44 settles conflict iteration")
+             )]
+             pub(crate) fn for_each_conflict(
+                 &self,
                  mut f: impl FnMut(&str, Option<&dyn std::fmt::Debug>, &dyn std::fmt::Debug),
              ) {
                  $(
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 -    };
  }
  
-+/// A struct for the tests, outside their `coverage(off)` module so that its
-+/// expansion counts towards the macro's coverage.
++// Outside the `coverage(off)` test module, so that this expansion of the
++// macro counts towards coverage.
  #[cfg(all(test, feature = "unit-tests"))]
 -#[cfg_attr(coverage_nightly, coverage(off))]
 -mod tests {
@@ crates/concurrent-psbt/src/psbt/output.rs
 +
  use bitcoin::bip32::KeySource;
  use bitcoin::key::{PublicKey, XOnlyPublicKey};
- use bitcoin::taproot::{TapLeafHash, TapTree};
+ use bitcoin::taproot::TapTree;
+@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
+     #[cfg(feature = "unit-tests")]
+     mod unit {
+         use super::*;
+-        use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
+-        use bitcoin::secp256k1::{Secp256k1, SecretKey};
+-
+-        const ALL_CONFLICT_FIELDS: &[&str] = &[
+-            "unique_id",
+-            "amount",
+-            "script_pubkey",
+-            "redeem_script",
+-            "witness_script",
+-            "bip32_derivations",
+-            "tap_internal_key",
+-            "tap_tree",
+-            "tap_key_origins",
+-            "proprietaries",
+-            "unknowns",
+-        ];
+-
+-        fn empty_conflict<T: PartialJoin>() -> JoinResult<T> {
+-            Err(Conflict::from_values([]))
+-        }
+-
+-        fn all_fields_conflict(seed: u8) -> ResultOutput {
+-            let mut result = output(seed).wrap();
+-            result.unique_id = empty_conflict();
+-            result.amount = empty_conflict();
+-            result.script_pubkey = empty_conflict();
+-            result.redeem_script = Some(empty_conflict());
+-            result.witness_script = Some(empty_conflict());
+-            result.tap_internal_key = Some(empty_conflict());
+-            result.tap_tree = Some(empty_conflict());
+-
+-            let secret_key = SecretKey::from_slice(&[seed; 32]).expect("bounded nonzero seed");
+-            let secp_public_key =
+-                bitcoin::secp256k1::PublicKey::from_secret_key(&Secp256k1::new(), &secret_key);
+-            let public_key = PublicKey::new(secp_public_key);
+-            let (x_only_public_key, _) = secp_public_key.x_only_public_key();
+-            result
+-                .bip32_derivations
+-                .insert(public_key, empty_conflict());
+-            result
+-                .tap_key_origins
+-                .insert(x_only_public_key, empty_conflict());
+-            result.proprietaries.insert(
+-                raw::ProprietaryKey {
+-                    prefix: vec![seed],
+-                    subtype: seed,
+-                    key: vec![seed],
+-                },
+-                empty_conflict(),
+-            );
+-            result.unknowns.insert(
+-                raw::Key {
+-                    type_value: seed,
+-                    key: vec![seed],
+-                },
+-                empty_conflict(),
+-            );
+-            result
+-        }
+ 
+         #[test]
+-        fn try_unwrap_conflicting_returns_err() {
+-            let a = Output {
+-                amount: bitcoin::Amount::from_sat(100),
++        fn outputs_with_different_amounts_conflict() {
++            let with_amount = |sats| Output {
++                amount: Amount::from_sat(sats),
+                 ..output(1)
+             };
+-            let b = Output {
+-                amount: bitcoin::Amount::from_sat(200),
+-                ..output(1)
+-            };
+-            assert!(a.wrap().join(b.wrap()).try_unwrap().is_err());
+-        }
+-
+-        #[test]
+-        fn for_each_conflict_reports_every_conflicted_field() {
+-            let result = all_fields_conflict(1);
++            let joined = with_amount(100).wrap().join(with_amount(200).wrap());
+             let mut fields = Vec::new();
+-            result.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
+-            assert_eq!(fields, ALL_CONFLICT_FIELDS);
++            joined.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
++            assert_eq!(fields, ["amount"]);
++            assert_eq!(joined.clone().try_unwrap(), Err(joined));
+         }
+     }
+ 
+@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
+         proptest! {
+             #[test]
+             fn wrap_try_unwrap_roundtrip(o in arb_output()) {
+-                let wrapped = o.wrap();
+-                prop_assert!(wrapped.is_ok());
+-                prop_assert!(wrapped.try_unwrap().is_ok());
++                prop_assert_eq!(o.clone().wrap().try_unwrap(), Ok(o));
+             }
+ 
+             #[test]
+-            fn is_ok_reflects_content(r in arb_result_output()) {
+-                if r.is_ok() {
+-                    prop_assert!(r.try_unwrap().is_ok());
+-                } else {
+-                    prop_assert!(r.try_unwrap().is_err());
+-                }
++            fn is_ok_iff_try_unwrap_succeeds(r in arb_result_output()) {
++                prop_assert_eq!(r.is_ok(), r.try_unwrap().is_ok());
+             }
+ 
+         }
2: 7cfd16a301 ! 2: f86b18d263 generate v2 conversions from the field lists
@@ Metadata
  ## Commit message ##
     generate v2 conversions from the field lists
 
-    Global, Input and Output each named their fields four times: in the
-    struct, then destructuring a psbt_v2 value, building the struct, and
-    building the psbt_v2 value back. Output also read and wrote its unique
-    ID by hand.
+    Global, Input and Output each listed their fields four times: in the
+    struct definition, when destructuring a psbt_v2 value, when building the
+    struct, and when building the psbt_v2 value back. Output also read and
+    wrote its unique ID by hand.
 
-    joinable_struct now takes the psbt_v2 type and two field lists. `fields`
-    mirror the psbt_v2 fields of the same names. `proprietary` fields each
-    name a `ProprietaryField` codec, which holds the key's subtype and the
-    encoding, so a field keeps its type and join if it is later assigned a
-    standard key. The macro generates:
+    joinable_struct now takes the psbt_v2 type and two field lists. Each
+    entry in `fields` mirrors the psbt_v2 field of the same name. Each entry
+    in `proprietary` names a `ProprietaryField` codec, which defines the
+    field's key subtype and encoding. Changing the key later does not change
+    the field's type or join. The macro generates:
 
-    - `from_v2_fields`, which moves the mirrored fields and takes the
-      proprietary ones as given;
-    - `decode_v2`, which decodes the proprietary fields in order, removing
+    - `from_v2_fields`, which moves the mirrored fields out of a psbt_v2
+      value and takes the proprietary fields as arguments;
+    - `decode_v2`, which decodes the proprietary fields in order and removes
       their keys;
-    - `encode_v2`, which moves the mirrored fields into a base value and
-      encodes the proprietary ones.
+    - `encode_v2`, which moves the mirrored fields into a psbt_v2 value and
+      encodes the proprietary fields into it.
 
-    The conversions keep only what differs: Global derives its version and
-    counts, Input starts from its outpoint, and Output's unique ID is a
-    required proprietary field. The encoders assign fields one by one, so
-    psbt_v2 fields this crate does not mirror keep their base values without
-    a `needless_update` expectation.
+    If a mirrored field's type differs from the psbt_v2 field's, an `=`
+    after the type names a `MirroredField` that converts between them.
+    tap_key_origins uses this to convert each key's leaf hashes to and from
+    TapLeafHashes.
+
+    The hand-written conversions now handle only the fields that the macro
+    does not. Global sets the version and the counts, Input starts from its
+    outpoint, and Output lists its unique ID as a proprietary field.
+    encode_v2 assigns the fields one at a time, so psbt_v2 fields that this
+    crate does not mirror keep their values, and the `needless_update`
+    expectations are removed.
 
     Suggested-by: Codex
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
      }
  }
  
-@@ crates/concurrent-psbt/src/psbt/global.rs: impl Default for Global {
- /// derives.
+ /// Drops the version and the input and output counts.
  impl From<psbt_v2::v2::Global> for Global {
      fn from(global: psbt_v2::v2::Global) -> Self {
 -        let psbt_v2::v2::Global {
@@ crates/concurrent-psbt/src/psbt/global.rs: impl Default for Global {
  
 
  ## crates/concurrent-psbt/src/psbt/input.rs ##
+@@ crates/concurrent-psbt/src/psbt/input.rs: use bitcoin::{OutPoint, ScriptBuf, Sequence, Transaction, TxOut, Txid, Witness,
+ use psbt_v2::PsbtSighashType;
+ use psbt_v2::raw;
+ 
+-use super::tap_leaf_hashes::{TapLeafHashes, tap_key_origins_from_v2, tap_key_origins_into_v2};
++use super::tap_leaf_hashes::{TapKeyOrigins, TapLeafHashes};
+ 
+ joinable_struct! {
+     /// A PSBT input, mirroring the BIP 370 per-input map.
 @@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
-     /// lift a clean [`Input`] into this type, and [`ResultInput::try_unwrap`]
-     /// to recover the clean value once all conflicts are resolved.
+     /// [`Input`] into this type, and [`ResultInput::try_unwrap`] returns it if
+     /// no field conflicts.
      result: ResultInput,
 +    v2: psbt_v2::v2::Input,
      fields: {
          pub previous_txid: Txid,
          pub spent_output_index: u32,
 @@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
+         pub tap_key_sig: Option<taproot::Signature>,
+         pub tap_script_sigs: BTreeMap<(XOnlyPublicKey, TapLeafHash), taproot::Signature>,
+         pub tap_scripts: BTreeMap<ControlBlock, (ScriptBuf, LeafVersion)>,
+-        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)>,
++        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins,
+         pub tap_internal_key: Option<XOnlyPublicKey>,
          pub tap_merkle_root: Option<TapNodeHash>,
          pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
          pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
 -            tap_key_sig,
 -            tap_script_sigs,
 -            tap_scripts,
--            tap_key_origins,
+-            tap_key_origins: tap_key_origins_from_v2(tap_key_origins),
 -            tap_internal_key,
 -            tap_merkle_root,
 -            proprietaries,
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
 -            tap_key_sig: input.tap_key_sig,
 -            tap_script_sigs: input.tap_script_sigs,
 -            tap_scripts: input.tap_scripts,
--            tap_key_origins: input.tap_key_origins,
+-            tap_key_origins: tap_key_origins_into_v2(input.tap_key_origins),
 -            tap_internal_key: input.tap_internal_key,
 -            tap_merkle_root: input.tap_merkle_root,
 -            proprietaries: input.proprietaries,
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
  
 
  ## crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs ##
+@@
++/// Converts a mirrored field whose type differs from the psbt-v2 field of the
++/// same name.
++pub(crate) trait MirroredField {
++    /// The psbt-v2 field's type.
++    type V2;
++    /// The field's type.
++    type Value;
++    /// Convert from the psbt-v2 field.
++    fn from_v2(value: Self::V2) -> Self::Value;
++    /// Convert into the psbt-v2 field.
++    fn into_v2(value: Self::Value) -> Self::V2;
++}
++
+ /// Generate a product type, its result-domain counterpart, and their lattice
+ /// operations from a single field list using standard Rust type syntax.
+ ///
 @@
  /// 4. `Join for $Result`
  /// 5. `$Result::is_ok`, `$Result::for_each_conflict` and `$Result::try_unwrap`
  /// 6. `ResultValue for $Result`
 +///
-+/// Given a `v2` type, `fields` mirror its fields of the same names, and
-+/// `proprietary` fields are stored in its proprietary keys, each through the
-+/// [`ProprietaryField`](crate::psbt::proprietary::ProprietaryField) codec
-+/// named after its `=`. The struct then has private conversions:
++/// Each entry in `fields` mirrors the field of the same name in the `v2` type.
++/// If the two types differ, an `=` after the type names the [`MirroredField`]
++/// that converts between them. Each entry in `proprietary` is written
++/// `name: Type = Codec`, and is stored in a proprietary key of `v2` by the
++/// [`ProprietaryField`](crate::psbt::proprietary::ProprietaryField) impl
++/// `Codec`. The struct then has private conversions:
 +///
 +/// - `from_v2_fields(v2, proprietary...)` moves the mirrored fields out of
 +///   `v2` and takes the proprietary fields as given;
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +        result: $Result:ident,
 +        v2: $V2:path,
 +        fields: {
-+            $( $(#[$field_meta:meta])* $vis:vis $field:ident : $T:ty ),+ $(,)?
++            $(
++                $(#[$field_meta:meta])* $vis:vis
++                $field:ident : $T:ty $( = $Conversion:ty )?
++            ),+ $(,)?
 +        },
 +        proprietary: {
 +            $(
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +            /// The mirrored fields of `v2`, with these proprietary fields.
 +            fn from_v2_fields(v2: $V2, $( $proprietary: $P ),*) -> Self {
 +                Self {
-+                    $( $field: v2.$field, )+
++                    $( $field: joinable_struct!(@from_v2 v2.$field $(, $Conversion)?), )+
 +                    $( $proprietary, )*
 +                }
 +            }
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +            /// move its mirrored fields.
 +            ///
 +            /// # Errors
-+            /// Returns the first proprietary field that does not decode.
++            /// Returns the error of the first proprietary field that does not
++            /// decode.
 +            fn decode_v2<E>(v2: $V2) -> Result<Self, E>
 +            where
 +                $( E: From<<$Codec as $crate::psbt::proprietary::ProprietaryField>::Error>, )*
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +            /// Move the mirrored fields into `base`, and encode the proprietary
 +            /// fields into its proprietary keys.
 +            ///
-+            /// The proprietary fields own their keys: a key that a field leaves
-+            /// out is removed, even if `self.proprietaries` holds it.
++            /// If a proprietary field encodes to `None`, its key is removed from
++            /// `base`, even if `self.proprietaries` has it.
 +            fn encode_v2(self, mut base: $V2) -> $V2 {
-+                $( base.$field = self.$field; )+
++                $( base.$field = joinable_struct!(@into_v2 self.$field $(, $Conversion)?); )+
 +                $(
 +                    let key = $crate::psbt::proprietary::key(
 +                        <$Codec as $crate::psbt::proprietary::ProprietaryField>::SUBTYPE,
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +        }
 +    };
 +
++    (@from_v2 $value:expr) => {
++        $value
++    };
++
++    (@from_v2 $value:expr, $Conversion:ty) => {
++        <$Conversion as $crate::psbt::joinable_struct_macro::MirroredField>::from_v2($value)
++    };
++
++    (@into_v2 $value:expr) => {
++        $value
++    };
++
++    (@into_v2 $value:expr, $Conversion:ty) => {
++        <$Conversion as $crate::psbt::joinable_struct_macro::MirroredField>::into_v2($value)
++    };
++
 +    (@decode $v2:ident []) => {
 +        Ok(Self::from_v2_fields($v2))
 +    };
@@ crates/concurrent-psbt/src/psbt/mod.rs: mod joinable_struct_macro;
  pub mod input;
  pub mod output;
 +pub(crate) mod proprietary;
+ mod tap_leaf_hashes;
  mod values;
+ 
 
  ## crates/concurrent-psbt/src/psbt/output.rs ##
-@@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::taproot::{TapLeafHash, TapTree};
+@@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::taproot::TapTree;
  use bitcoin::{Amount, ScriptBuf};
  use psbt_v2::raw;
  
+-use super::tap_leaf_hashes::{TapLeafHashes, tap_key_origins_from_v2, tap_key_origins_into_v2};
 +use super::proprietary::ProprietaryField;
-+
++use super::tap_leaf_hashes::{TapKeyOrigins, TapLeafHashes};
+ 
  joinable_struct! {
      /// A PSBT output, mirroring the BIP 370 per-output map, identified by its
-     /// [`UniqueId`].
 @@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
-     /// Each field is represented in the internal result domain, recording
-     /// either a clean value or an accumulated conflict.
+     ///
+     /// Each field holds a clean value or a conflict.
      result: ResultOutput,
 +    v2: psbt_v2::v2::Output,
      fields: {
@@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
          pub script_pubkey: ScriptBuf,
          pub redeem_script: Option<ScriptBuf>,
 @@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
-         pub tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>,
+         pub bip32_derivations: BTreeMap<PublicKey, KeySource>,
+         pub tap_internal_key: Option<XOnlyPublicKey>,
+         pub tap_tree: Option<TapTree>,
+-        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)>,
++        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins,
          pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
          pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
 -    }
@@ crates/concurrent-psbt/src/psbt/output.rs: impl Output {
 -            bip32_derivations,
 -            tap_internal_key,
 -            tap_tree,
--            tap_key_origins,
+-            tap_key_origins: tap_key_origins_from_v2(tap_key_origins),
 -            proprietaries,
 -            unknowns,
 -        }
@@ crates/concurrent-psbt/src/psbt/output.rs: impl TryFrom<psbt_v2::v2::Output> for
 -            bip32_derivations: output.bip32_derivations,
 -            tap_internal_key: output.tap_internal_key,
 -            tap_tree: output.tap_tree,
--            tap_key_origins: output.tap_key_origins,
+-            tap_key_origins: tap_key_origins_into_v2(output.tap_key_origins),
 -            proprietaries,
 -            unknowns: output.unknowns,
 -            ..psbt_v2::v2::Output::default()
@@ crates/concurrent-psbt/src/psbt/output.rs: impl std::error::Error for InvalidUni
 -        prefix: b"concurrent-psbt".to_vec(),
 -        subtype: PSBT_OUT_UNIQUE_ID_SUBTYPE,
 -        key: vec![],
-+/// `PSBT_OUT_UNIQUE_ID`, which every [`Output`] has.
++/// Stores an output's unique ID in `PSBT_OUT_UNIQUE_ID`.
 +struct UniqueIdField;
 +
 +impl ProprietaryField for UniqueIdField {
@@ crates/concurrent-psbt/src/psbt/output.rs: pub(crate) trait OutputUniqueIdExt {
      }
  }
  
-@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
-         use bitcoin::secp256k1::{Secp256k1, SecretKey};
- 
-         const ALL_CONFLICT_FIELDS: &[&str] = &[
--            "unique_id",
-             "amount",
-             "script_pubkey",
-             "redeem_script",
-@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
-             "tap_key_origins",
-             "proprietaries",
-             "unknowns",
-+            "unique_id",
-         ];
- 
-         fn empty_conflict<T: PartialJoin>() -> JoinResult<T> {
 
  ## crates/concurrent-psbt/src/psbt/proprietary.rs (new) ##
 @@
@@ crates/concurrent-psbt/src/psbt/proprietary.rs (new)
 +
 +/// How a field this crate defines is stored in a proprietary key.
 +///
-+/// The key and encoding belong to the codec rather than the field, so a field
-+/// keeps its type and join when its key changes.
++/// A field's key and encoding are defined by its codec, so changing them does
++/// not change the field's type or join.
 +pub(crate) trait ProprietaryField {
 +    /// The subtype of the field's key under [`PREFIX`].
 +    const SUBTYPE: u8;
@@ crates/concurrent-psbt/src/psbt/proprietary.rs (new)
 +    /// Encode the field as its key's value, or `None` to leave the key out.
 +    fn encode(value: Self::Value) -> Option<Vec<u8>>;
 +}
+
+ ## crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs ##
+@@ crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs: use bitcoin::TapLeafHash;
+ use bitcoin::bip32::KeySource;
+ use bitcoin::secp256k1::XOnlyPublicKey;
+ 
++use super::joinable_struct_macro::MirroredField;
+ use crate::values::IdempotentValue;
+ 
+ /// The leaf hashes of a taproot key in `PSBT_{IN,OUT}_TAP_BIP32_DERIVATION`.
+@@ crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs: impl IdempotentValue for (TapLeafHashes, KeySource) {}
+ /// `PSBT_{IN,OUT}_TAP_BIP32_DERIVATION` as psbt-v2 stores it.
+ type V2TapKeyOrigins = BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>;
+ 
+-/// `PSBT_{IN,OUT}_TAP_BIP32_DERIVATION` with set equality on the leaf hashes.
+-type TapKeyOrigins = BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)>;
++/// Converts `tap_key_origins` between psbt-v2's leaf hash lists and
++/// [`TapLeafHashes`].
++pub(crate) enum TapKeyOrigins {}
+ 
+-pub(crate) fn tap_key_origins_from_v2(origins: V2TapKeyOrigins) -> TapKeyOrigins {
+-    origins
+-        .into_iter()
+-        .map(|(key, (leaves, source))| (key, (leaves.into(), source)))
+-        .collect()
+-}
++impl MirroredField for TapKeyOrigins {
++    type V2 = V2TapKeyOrigins;
++    type Value = BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)>;
++
++    fn from_v2(origins: Self::V2) -> Self::Value {
++        origins
++            .into_iter()
++            .map(|(key, (leaves, source))| (key, (leaves.into(), source)))
++            .collect()
++    }
+ 
+-pub(crate) fn tap_key_origins_into_v2(origins: TapKeyOrigins) -> V2TapKeyOrigins {
+-    origins
+-        .into_iter()
+-        .map(|(key, (leaves, source))| (key, (leaves.into(), source)))
+-        .collect()
++    fn into_v2(origins: Self::Value) -> Self::V2 {
++        origins
++            .into_iter()
++            .map(|(key, (leaves, source))| (key, (leaves.into(), source)))
++            .collect()
++    }
+ }
+ 
+ #[cfg(all(test, feature = "prop-tests"))]
+@@ crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs: mod tests {
+ 
+         #[test]
+         fn v2_round_trip_keeps_the_lists(origins in arb_v2_tap_key_origins()) {
+-            prop_assert_eq!(tap_key_origins_into_v2(tap_key_origins_from_v2(origins.clone())), origins);
++            prop_assert_eq!(TapKeyOrigins::into_v2(TapKeyOrigins::from_v2(origins.clone())), origins);
+         }
+     }
+ }
3: ba82f99d44 ! 3: 1b40522363 Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 @@
 +//! Keyed sets of PSBT entries, some of which may be frozen.
 +//!
-+//! A [`KeyedSet`] holds entries with distinct keys, namely inputs keyed by their outpoints and
-+//! outputs keyed by their unique id. Its result-domain counterpart, [`ResultKeyedSet`], joins sets
-+//! entry by entry.
++//! A [`KeyedSet`] holds entries with distinct keys: inputs keyed by their outpoints, or outputs
++//! keyed by their unique IDs. A [`ResultKeyedSet`] is the join of any number of [`Freezable`]
++//! keyed sets, and joins the entries that share a key.
 +//!
-+//! For handling (non-)modifiability in a consistent manner (respecting idempotence, commutativity
-+//! and associativity), a set can be [`Frozen`](Freezable::Frozen), as a PSBT's inputs or outputs
-+//! are once the either set is no longer modifiable. This fixes the set of keys for that particular element, allowing the
-+//! values associated with these entries to still be joined to accumulate additional information
-+//! associated with the inputs or outputs, without changing the set of spent or created coins
-+//! itself. Conflicts about membership are represented as conflicting sets of identifiers.
++//! A PSBT's inputs or outputs are [`Frozen`](Freezable::Frozen) once they are no longer
++//! modifiable. The keys of a frozen set are fixed, so no input or output can be added or removed,
++//! but its entries can still be joined with entries that add information to them. A
++//! [`ResultKeyedSet`] keeps every distinct frozen key set it joins, which keeps the join
++//! idempotent, commutative and associative. It is clean only if the keys of its entries match
++//! the frozen key sets.
 +
 +use std::collections::hash_map::{Entry, IntoValues};
 +use std::collections::{HashMap, HashSet};
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +
 +/// A [`KeyedSet`] whose keys may be frozen.
 +///
-+/// A PSBT's inputs or outputs are frozen once they are no longer modifiable. In a given PSBT this
-+/// enum tag must track the `tx_modifiable_flags` in the `Global` struct.
++/// A PSBT's inputs or outputs are `Frozen` when the matching bit of `tx_modifiable_flags` is
++/// clear.
 +#[derive(Debug, Clone)]
 +pub(crate) enum Freezable<K, V> {
 +    /// Modifiable sets can be joined, unioning their keys and joining values
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +///
 +/// Entries with the same key are joined, and the rest are unioned. A frozen
 +/// set's keys are fixed, so each distinct set of frozen keys is also kept.
-+/// The join is clean only if there is at most one, and it equals the keys of
-+/// the entries. So a frozen set joins cleanly with frozen sets of the same
-+/// keys, and with modifiable sets whose keys it already has.
++/// The join is clean only if there is at most one distinct frozen key set and
++/// it equals the keys of the entries. So a frozen set joins cleanly with
++/// frozen sets of the same keys, and with modifiable sets whose keys it
++/// already has.
 +///
 +/// The default, the empty modifiable set, is the identity of the join.
 +#[derive(Debug, Clone)]
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    /// Every joined set's entries, with those sharing a key joined into one.
 +    entries: KeyedSet<K, V>,
 +
-+    /// The distinct key sets of the frozen sets, in the order first joined. If any key set is
-+    /// frozen, then it must exactly match the keys of the entries, otherwise the entire
-+    /// ResultKeyedSet is in a conflicted state.
++    /// The distinct key sets of the frozen sets, in the order first joined.
 +    frozen: Vec<HashSet<K>>,
 +}
 +
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    /// Return the number of entries, or the conflicting sizes of the frozen
 +    /// key sets and the entries.
 +    ///
-+    /// Each frozen set's keys are among the entries', so the sizes all agree
-+    /// exactly when the keys agree with the frozen sets.
++    /// Every frozen key set is a subset of the keys of the entries, so the
++    /// sizes are all equal only if the keys agree with the frozen sets.
 +    pub(crate) fn len(&self) -> JoinResult<usize> {
 +        self.frozen
 +            .iter()
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +        self.entries.is_empty()
 +    }
 +
-+    /// Return `true` if at most one set of frozen keys remains, and it holds
-+    /// the key of every entry: exactly when [`len`](Self::len) is `Ok`.
++    /// Return `true` if there is at most one frozen key set and it holds the
++    /// key of every entry, which is when [`len`](Self::len) is `Ok`.
 +    fn keys_agree(&self) -> bool {
 +        self.len().is_ok()
 +    }
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +
 +        proptest! {
 +            #[test]
-+            fn try_from_entries_reports_the_first_error_or_repeat(
-+                entries in proptest::collection::vec(
-+                    prop_oneof![
-+                        3 => (0u8..4, any::<u8>()).prop_map(Ok),
-+                        1 => (4u8..8).prop_map(Err),
-+                    ],
-+                    0..=5,
++            fn try_from_entries_stops_at_the_first_failure(
++                keys in proptest::collection::hash_set(0u8..8, 1..=4),
++                repeat in any::<proptest::sample::Index>(),
++                error in proptest::option::of(200u8..),
++                tail in proptest::collection::vec(
++                    prop_oneof![(0u8..8, any::<u8>()).prop_map(Ok), (200u8..).prop_map(Err)],
++                    0..=3,
 +                ),
 +            ) {
-+                let mut seen = HashSet::new();
-+                let expected = entries.iter().find_map(|entry| match entry {
-+                    Ok((key, _)) => (!seen.insert(*key)).then_some(key + 100),
-+                    Err(error) => Some(*error),
-+                });
-+                match (collect(entries.clone()), expected) {
-+                    (Ok(set), None) => {
-+                        prop_assert_eq!(set.len(), entries.len());
-+                        prop_assert_eq!(set.is_empty(), entries.is_empty());
-+                        for (key, _) in entries.iter().flatten() {
-+                            prop_assert!(set.contains_key(key));
-+                        }
++                let keys: Vec<u8> = keys.into_iter().collect();
++                let distinct: Vec<_> = keys.iter().map(|&key| Ok((key, key))).collect();
++                let set = collect(distinct.clone()).expect("distinct keys");
++                prop_assert_eq!(set.len(), keys.len());
++                prop_assert!(keys.iter().all(|key| set.contains_key(key)));
++
++                // A failure after distinct keys: an error, or a repeated key.
++                let (failure, expected) = match error {
++                    Some(error) => (Err(error), error),
++                    None => {
++                        let key = keys[repeat.index(keys.len())];
++                        (Ok((key, 0)), key + 100)
 +                    }
-+                    (Err(error), Some(expected)) => prop_assert_eq!(error, expected),
-+                    (result, expected) => {
-+                        prop_assert!(false, "{result:?} disagrees with {expected:?}");
-+                    }
-+                }
++                };
++                let entries = distinct.into_iter().chain([failure]).chain(tail).collect();
++                prop_assert_eq!(collect(entries), Err(expected));
 +            }
 +
 +            #[test]
@@ crates/concurrent-psbt/src/psbt/mod.rs
 +mod keyed_set;
  pub mod output;
  pub(crate) mod proprietary;
- mod values;
+ mod tap_leaf_hashes;

@github-actions

Copy link
Copy Markdown
range-diff for force push 1b40522363 → a6d7b49f63 November 14, 2026 09:55 UTC: 3 unchanged; 3 commits; base 83c0bbb0a0 → e10fb51e3d (diverged, 2 ahead and 1 behind)

reproduce: git range-diff 83c0bbb..1b40522 e10fb51..a6d7b49

1:  196853c5b3 +324 -590 10f = 1:  4e1cb3e74b +324 -590 10f lift joinable_struct fields by type, not by token
2:  f86b18d263 +241 -208  7f = 2:  c4a9e4cc97 +241 -208  7f generate v2 conversions from the field lists
3:  1b40522363 +545   -0  2f = 3:  a6d7b49f63 +545   -0  2f Introduce keyed set structures for inputs and outputs

@github-actions

Copy link
Copy Markdown
range-diff for force push 1b40522363 → a6d7b49f63 November 14, 2026 09:59 UTC: 3 unchanged; 3 commits; base 83c0bbb0a0 → e10fb51e3d (diverged, 2 ahead and 1 behind)

reproduce: git range-diff 83c0bbb..1b40522 e10fb51..a6d7b49

1:  196853c5b3 +324 -590 10f = 1:  4e1cb3e74b +324 -590 10f lift joinable_struct fields by type, not by token
2:  f86b18d263 +241 -208  7f = 2:  c4a9e4cc97 +241 -208  7f generate v2 conversions from the field lists
3:  1b40522363 +545   -0  2f = 3:  a6d7b49f63 +545   -0  2f Introduce keyed set structures for inputs and outputs

@github-actions

Copy link
Copy Markdown
range-diff for force push a6d7b49f63 → 0b8384fb5c November 14, 2026 12:21 UTC: 1 modified, 2 unchanged; 3 commits; same base e10fb51e3d

reproduce: git range-diff e10fb51..a6d7b49 e10fb51..0b8384f

1:  4e1cb3e74b +324 -590 10f ! 1:  f3a2a403c4 +326 -592 10f lift joinable_struct fields by type, not by token
2:  c4a9e4cc97 +241 -208  7f = 2:  dd5bf89916 +241 -208  7f generate v2 conversions from the field lists
3:  a6d7b49f63 +545   -0  2f = 3:  0b8384fb5c +545   -0  2f Introduce keyed set structures for inputs and outputs
1: 4e1cb3e74b ! 1: f3a2a403c4 lift joinable_struct fields by type, not by token
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
              }
  
              /// Visit each conflicted field, calling `f(field_name, key, &conflict)`.
-@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
-             /// callers can tell which entry conflicts. For scalar and option
+             ///
+             /// Only visits fields that contain conflicts. Clean fields are skipped.
+-            /// For map fields, visits each conflicted entry with `Some(&key)`, so
+-            /// callers can tell which entry conflicts. For scalar and option
++            /// For map fields and options holding maps, visits each conflicted
++            /// entry with `Some(&key)`, so callers can tell which entry conflicts. For other
              /// fields `key` is `None`.
              #[cfg_attr(
 -                not(test),

@github-actions

Copy link
Copy Markdown
range-diff for force push 103b805377 → 9442a7d917 November 16, 2026 03:46 UTC: 1 modified; 1 commit; base 5d0742b812 → 558e0c9d6c (diverged, 4 ahead and 4 behind)

reproduce: git range-diff 5d0742b..103b805 558e0c9..9442a7d

1:  103b805377 +725 -0 4f ! 1:  9442a7d917 +725 -0 4f Introduce keyed set structures for inputs and outputs
1: 103b805377 ! 1: 9442a7d917 Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +}
 
  ## crates/concurrent-psbt/src/psbt/mod.rs ##
-@@ crates/concurrent-psbt/src/psbt/mod.rs: mod conflict_macro;
+@@
  mod joinable_struct_macro;
  pub mod global;
  pub mod input;

@github-actions

Copy link
Copy Markdown
range-diff for force push 9442a7d917 → 15e3bcc2f7 November 16, 2026 03:51 UTC: 1 unchanged; 1 commit; base 558e0c9d6c → bfa047201a (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 558e0c9..9442a7d bfa0472..15e3bcc

1:  9442a7d917 +725 -0 4f = 1:  15e3bcc2f7 +725 -0 4f Introduce keyed set structures for inputs and outputs

@github-actions

Copy link
Copy Markdown
range-diff for force push 15e3bcc2f7 → 52a877bd3e November 16, 2026 04:03 UTC: 1 modified; 1 commit; same base bfa047201a

reproduce: git range-diff bfa0472..15e3bcc bfa0472..52a877b

1:  15e3bcc2f7 +725 -0 4f ! 1:  52a877bd3e +843 -0 4f Introduce keyed set structures for inputs and outputs
1: 15e3bcc2f7 ! 1: 52a877bd3e Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +            }
 +        }
 +    }
++}
++
++#[cfg(all(test, any(feature = "unit-tests", feature = "prop-tests")))]
++#[cfg_attr(coverage_nightly, coverage(off))]
++mod conflict_regressions {
++    use std::collections::{HashMap, HashSet};
++
++    use super::{Freezable, KeyedSet, SetConflict};
++    use crate::lattice::partial::Conflict;
++    use crate::{Conflicts, Join, Lift, ResultWrapped};
++
++    fn check_conflicts<'a>(
++        conflicts: impl Iterator<Item = SetConflict<'a, u8, &'a Conflict<u8>>>,
++        common: u8,
++        extra: u8,
++        values: [u8; 2],
++        membership: bool,
++        entry: bool,
++    ) {
++        let mut membership_count = 0;
++        let mut entry_count = 0;
++        for conflict in conflicts {
++            match conflict {
++                SetConflict::Membership(evidence) => {
++                    membership_count += 1;
++                    assert_eq!(evidence.frozen, &HashSet::from([common]));
++                    assert_eq!(evidence.unexpected, &extra);
++                    assert!(!evidence.frozen.contains(evidence.unexpected));
++                }
++                SetConflict::Entry { key, conflict } => {
++                    entry_count += 1;
++                    assert_eq!(key, &common);
++                    assert_eq!(conflict.into_iter().copied().collect::<Vec<_>>(), values);
++                }
++            }
++        }
++        assert_eq!(membership_count, usize::from(membership));
++        assert_eq!(entry_count, usize::from(entry));
++    }
++
++    fn check_keyed_contract(common: u8, value: u8, outer_key: u8) {
++        let extra = common.wrapping_add(1);
++        for frozen in [false, true] {
++            for entry_conflict in [false, true] {
++                let other = if entry_conflict {
++                    value.wrapping_add(1)
++                } else {
++                    value
++                };
++                let left = Freezable::Modifiable(KeyedSet(HashMap::from([(common, value)])));
++                let left = if frozen { left.freeze() } else { left };
++                let right = Freezable::Modifiable(KeyedSet(HashMap::from([
++                    (common, other),
++                    (extra, value),
++                ])));
++                let joined = Lift::wrap(left.clone()).join(Lift::wrap(right.clone()));
++                let expected_ok = !frozen && !entry_conflict;
++                assert_eq!(ResultWrapped::is_ok(&joined), expected_ok);
++                let expected = if expected_ok {
++                    Ok(right.clone())
++                } else {
++                    Err(joined.clone())
++                };
++                assert_eq!(ResultWrapped::try_unwrap(joined.clone()), expected);
++                check_conflicts(
++                    Conflicts::conflicts(&joined),
++                    common,
++                    extra,
++                    [value, other],
++                    frozen,
++                    entry_conflict,
++                );
++
++                let nested = HashMap::from([(outer_key, Some(left))])
++                    .wrap()
++                    .join(HashMap::from([(outer_key, Some(right.clone()))]).wrap());
++                check_conflicts(
++                    Conflicts::conflicts(&nested).map(|(key, conflict)| {
++                        assert_eq!(key, &outer_key);
++                        conflict
++                    }),
++                    common,
++                    extra,
++                    [value, other],
++                    frozen,
++                    entry_conflict,
++                );
++                assert_eq!(ResultWrapped::is_ok(&nested), expected_ok);
++                let expected = if expected_ok {
++                    Ok(HashMap::from([(outer_key, Some(right))]))
++                } else {
++                    Err(nested.clone())
++                };
++                assert_eq!(ResultWrapped::try_unwrap(nested), expected);
++            }
++        }
++    }
++
++    #[cfg(feature = "unit-tests")]
++    #[test]
++    fn keyed_conflicts_keep_membership_entries_and_outer_keys() {
++        check_keyed_contract(7, 42, 9);
++    }
++
++    #[cfg(feature = "prop-tests")]
++    mod properties {
++        use super::*;
++        use proptest::prelude::*;
++
++        proptest! {
++            #[test]
++            fn keyed_conflicts_match_failed_unwraps(
++                common in any::<u8>(), value in any::<u8>(), outer_key in any::<u8>(),
++            ) {
++                check_keyed_contract(common, value, outer_key);
++            }
++        }
++    }
 +}
 
  ## crates/concurrent-psbt/src/psbt/mod.rs ##

@github-actions

Copy link
Copy Markdown
range-diff for force push 52a877bd3e → fd8eb7e9dc November 16, 2026 04:08 UTC: 1 modified; 1 commit; same base bfa047201a

reproduce: git range-diff bfa0472..52a877b bfa0472..fd8eb7e

1:  52a877bd3e +843 -0 4f ! 1:  fd8eb7e9dc +981 -0 5f Introduce keyed set structures for inputs and outputs
1: 52a877bd3e ! 1: fd8eb7e9dc Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/mod.rs
  pub use tap_leaf_hashes::TapLeafHashes;
 +
 +pub mod conflicts;
+
+ ## crates/concurrent-psbt/tests/psbt_conflict_paths.rs (new) ##
+@@
++#![cfg(any(feature = "unit-tests", feature = "prop-tests"))]
++#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
++
++#[cfg_attr(coverage_nightly, coverage(off))]
++mod cases {
++    use bitcoin::hashes::Hash;
++    use bitcoin::{Amount, OutPoint, ScriptBuf, Txid};
++    use concurrent_psbt::Join;
++    use concurrent_psbt::conflicts::{ConflictPath, MembershipConflict, PsbtConflict};
++    use concurrent_psbt::global::{Global, GlobalConflict, GlobalField};
++    use concurrent_psbt::input::{Input, InputConflict, InputField};
++    use concurrent_psbt::output::{Output, OutputConflict, OutputField, UniqueId};
++    use psbt_v2::raw;
++    use std::collections::{BTreeMap, HashSet};
++
++    fn check_locations(tag: u8, keydata: Vec<u8>) {
++        let keys: Vec<_> = (0..3)
++            .map(|scope| {
++                let mut key = keydata.clone();
++                key.push(scope);
++                raw::Key {
++                    type_value: 0x80,
++                    key,
++                }
++            })
++            .collect();
++        let outpoint = OutPoint {
++            txid: Txid::from_byte_array([tag; 32]),
++            vout: 0,
++        };
++        let extra_outpoint = OutPoint {
++            vout: 1,
++            ..outpoint
++        };
++        let id = UniqueId::try_from(vec![tag, 0]).unwrap();
++        let extra_id = UniqueId::try_from(vec![tag, 1]).unwrap();
++        let fields = |scope: usize, value| BTreeMap::from([(keys[scope].clone(), vec![value])]);
++        let global = |value| {
++            let mut global = Global::default();
++            global.set_unknowns(fields(0, value));
++            global
++        };
++        let input = |value| {
++            let mut input = Input::new(&outpoint);
++            input.set_unknowns(fields(1, value));
++            input
++        };
++        let output = |value| {
++            let mut output = Output::new(id.clone(), Amount::from_sat(42), ScriptBuf::new());
++            output.set_unknowns(fields(2, value));
++            output
++        };
++        let other = tag.wrapping_add(1);
++        let global = global(tag).wrap().join(global(other).wrap());
++        let input = input(tag).wrap().join(input(other).wrap());
++        let output = output(tag).wrap().join(output(other).wrap());
++        let mut diagnostics: Vec<_> = global
++            .conflicts()
++            .map(PsbtConflict::Global)
++            .chain(input.conflicts().map(|conflict| PsbtConflict::Input {
++                outpoint: &outpoint,
++                conflict,
++            }))
++            .chain(
++                output
++                    .conflicts()
++                    .map(|conflict| PsbtConflict::Output { id: &id, conflict }),
++            )
++            .collect();
++        for diagnostic in &diagnostics {
++            let values = match diagnostic {
++                PsbtConflict::Global(GlobalConflict::Unknown { values, .. })
++                | PsbtConflict::Input {
++                    conflict: InputConflict::Unknown { values, .. },
++                    ..
++                }
++                | PsbtConflict::Output {
++                    conflict: OutputConflict::Unknown { values, .. },
++                    ..
++                } => values,
++                other => panic!("unexpected conflict: {other:?}"),
++            };
++            assert_eq!(
++                values.into_iter().cloned().collect::<Vec<_>>(),
++                [vec![tag], vec![other]]
++            );
++        }
++        let frozen_inputs = HashSet::from([outpoint]);
++        let frozen_outputs = HashSet::from([id.clone()]);
++        diagnostics.push(PsbtConflict::InputMembership(MembershipConflict {
++            frozen: &frozen_inputs,
++            unexpected: &extra_outpoint,
++        }));
++        diagnostics.push(PsbtConflict::OutputMembership(MembershipConflict {
++            frozen: &frozen_outputs,
++            unexpected: &extra_id,
++        }));
++        assert_eq!(
++            diagnostics
++                .iter()
++                .map(PsbtConflict::path)
++                .collect::<Vec<_>>(),
++            [
++                ConflictPath::Global(GlobalField::Unknown(&keys[0])),
++                ConflictPath::Input {
++                    outpoint: &outpoint,
++                    field: InputField::Unknown(&keys[1])
++                },
++                ConflictPath::Output {
++                    id: &id,
++                    field: OutputField::Unknown(&keys[2])
++                },
++                ConflictPath::InputMembership,
++                ConflictPath::OutputMembership,
++            ]
++        );
++    }
++
++    #[cfg(feature = "unit-tests")]
++    #[test]
++    fn diagnostics_locate_each_scope_and_its_keydata() {
++        check_locations(7, vec![1, 2]);
++    }
++
++    #[cfg(feature = "prop-tests")]
++    mod properties {
++        use super::*;
++        use proptest::prelude::*;
++        proptest! {
++            #[test]
++            fn diagnostic_paths_keep_scope_identity_and_keydata(
++                tag in any::<u8>(), keydata in proptest::collection::vec(any::<u8>(), 0..8),
++            ) {
++                check_locations(tag, keydata);
++            }
++        }
++    }
++}

@github-actions

Copy link
Copy Markdown
range-diff for force push fd8eb7e9dc → bbeaafa8bf November 16, 2026 04:23 UTC: 1 unchanged; 1 commit; base bfa047201a → 13974295ec (diverged, 4 ahead and 4 behind)

reproduce: git range-diff bfa0472..fd8eb7e 1397429..bbeaafa

1:  fd8eb7e9dc +981 -0 5f = 1:  bbeaafa8bf +981 -0 5f Introduce keyed set structures for inputs and outputs

@github-actions

Copy link
Copy Markdown
range-diff for force push bbeaafa8bf → 1aa57fc30c November 16, 2026 04:59 UTC: 1 modified; 1 commit; base 13974295ec → 8c2e1d8f34 (diverged, 4 ahead and 4 behind)

reproduce: git range-diff 1397429..bbeaafa 8c2e1d8..1aa57fc

1:  bbeaafa8bf +981 -0 5f ! 1:  1aa57fc30c +981 -0 5f Introduce keyed set structures for inputs and outputs
1: bbeaafa8bf ! 1: 1aa57fc30c Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/mod.rs
 +mod keyed_set;
  pub mod output;
  pub(crate) mod proprietary;
- mod tap_leaf_hashes;
  mod values;
- 
- pub use tap_leaf_hashes::TapLeafHashes;
 +
 +pub mod conflicts;

/// Entries with the same key are joined, and the rest are unioned. A frozen
/// set's keys are fixed, so each distinct set of frozen keys is also kept.
/// The join is clean only if there is at most one distinct frozen key set and
/// it equals the keys of the entries. So a frozen set joins cleanly with

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Doc claims same-key frozen joins always clean

ResultKeyedSet's doc says a frozen set joins cleanly with frozen sets of the same keys, but is_ok/try_unwrap also require every entry to be conflict-free; same-key entries with unequal values make the join unclean, as frozen_sets_with_the_same_keys_join_entry_by_entry asserts.

oakagent · automated · 1aa57fc

@arminsabouri arminsabouri left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

There seems to be no correctness bugs but I found some implementation details around frozen sets confusing. Did not review the tests.

Edit: and did not review any of the conflict stuff

}

impl<K, V> Freezable<K, V> {
/// Returns the underlying KeyedSet

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

nit:

Suggested change
/// Returns the underlying KeyedSet
/// Returns the underlying [`KeyedSet`]

Comment on lines +89 to +90
/// A PSBT's inputs or outputs are frozen once they are no longer modifiable. In a given PSBT this
/// enum tag must track the `tx_modifiable_flags` in the `Global` struct.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Is this trackign done in a different PR ?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

As far as I can tell this PR doesn't care about global flags.

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.

yes, that happens in #82

Comment on lines +222 to +224
if !self.frozen.contains(&keys) {
self.frozen.push(keys);
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

What if it contains only a subset of the keys ?

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.

that represents a conflict, e.g. PSBT A unmodifiable with {a,b} was merged into PSBT B modifiable with {a, b, c} would have entries {a,b,c} and a frozen key set of {a,b} which is a cnflict

self.len().is_ok()
}

fn add_frozen(&mut self, keys: HashSet<K>) {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Its odd that you would want to add mutability to a frozen part of the datastructure. i.e if outputs are "frozen" via global flags we I believe it would violate BIP370 if you added more outputs.

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.

two PSBTs can disagree on whether or not they are modifiable, in a way that is still coherent to join, e.g. if PSBT A is unmodifiable and has inputs {a,b,c} and PSBT B is modifiable and has inputs {a,b}, then there is no conflict when merging them, and PSBT B may have fields associated with those inputs that merge cleanly into A

This abstraction stores a set of inputs or outputs, keyed by their
identifier.

This this behaves like the set of identifiers that can union or conflict
when joined depending on whether or not it is frozen.

Additionally, with each identifier is also associated a value, so this
also works like a hashmap. These values are joined recursively, so a set
being frozen only means its identifier set is immutable.
@github-actions

Copy link
Copy Markdown
range-diff for force push 1aa57fc30c → 2e33c8cdd8 November 16, 2026 18:07 UTC: 1 modified; 1 commit; same base 8c2e1d8f34

reproduce: git range-diff 8c2e1d8..1aa57fc 8c2e1d8..2e33c8c

1:  1aa57fc30c +981 -0 5f ! 1:  2e33c8cdd8 +978 -0 5f Introduce keyed set structures for inputs and outputs
1: 1aa57fc30c ! 1: 2e33c8cdd8 Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +//! but its entries can still be joined with entries that add information to them. A
 +//! [`ResultKeyedSet`] keeps every distinct frozen key set it joins, which keeps the join
 +//! idempotent, commutative and associative. It is clean only if the keys of its entries match
-+//! the frozen key sets.
++//! the frozen key sets and every entry is conflict-free.
 +
 +use std::collections::hash_map::{Entry, IntoValues};
 +use std::collections::{HashMap, HashSet};
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +
 +/// A [`KeyedSet`] whose keys may be frozen.
 +///
-+/// A PSBT's inputs or outputs are `Frozen` when the matching bit of `tx_modifiable_flags` is
-+/// clear.
++/// Callers use `Frozen` for PSBT inputs or outputs when the matching bit of
++/// `tx_modifiable_flags` is clear.
 +#[derive(Debug, Clone)]
 +pub(crate) enum Freezable<K, V> {
 +    /// Modifiable sets can be joined, unioning their keys and joining values
 +    /// which share the same key.
 +    Modifiable(KeyedSet<K, V>),
 +
-+    /// A frozen set's keys are fixed. In the result domain, it can be joined
-+    /// only with frozen sets that freeze the same keys, or modifiable sets
-+    /// whose keys are a subset of the frozen keys. In both cases the result
-+    /// is frozen.
++    /// Keys are fixed. Joining with a different frozen key set or with new
++    /// keys records a membership conflict. Entry values are joined independently.
 +    Frozen(KeyedSet<K, V>),
 +}
 +
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +}
 +
 +impl<K, V> Freezable<K, V> {
-+    /// Returns the underlying KeyedSet
++    /// Returns the underlying [`KeyedSet`].
 +    pub(crate) fn set(&self) -> &KeyedSet<K, V> {
 +        match self {
 +            Self::Modifiable(set) | Self::Frozen(set) => set,
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +///
 +/// Entries with the same key are joined, and the rest are unioned. A frozen
 +/// set's keys are fixed, so each distinct set of frozen keys is also kept.
-+/// The join is clean only if there is at most one distinct frozen key set and
-+/// it equals the keys of the entries. So a frozen set joins cleanly with
-+/// frozen sets of the same keys, and with modifiable sets whose keys it
-+/// already has.
++/// The result is clean when every entry is conflict-free and either no
++/// frozen key set exists, or one distinct frozen key set equals the entry keys.
 +///
 +/// The default, the empty modifiable set, is the identity of the join.
 +#[derive(Debug, Clone)]
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    }
 +}
 +
-+#[cfg(all(test, any(feature = "unit-tests", feature = "prop-tests")))]
++#[cfg(test)]
++#[cfg(any(feature = "unit-tests", feature = "prop-tests"))]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod conflict_regressions {
 +    use std::collections::{HashMap, HashSet};

@github-actions

Copy link
Copy Markdown
range-diff for force push 2e33c8cdd8 → b04356d5b8 November 16, 2026 18:10 UTC: 1 modified; 1 commit; same base 8c2e1d8f34

reproduce: git range-diff 8c2e1d8..2e33c8c 8c2e1d8..b04356d

1:  2e33c8cdd8 +978 -0 5f ! 1:  b04356d5b8 +976 -0 5f Introduce keyed set structures for inputs and outputs
1: 2e33c8cdd8 ! 1: b04356d5b8 Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +            }
 +        }
 +    }
-+}
 +
-+#[cfg(test)]
-+#[cfg(any(feature = "unit-tests", feature = "prop-tests"))]
-+#[cfg_attr(coverage_nightly, coverage(off))]
-+mod conflict_regressions {
-+    use std::collections::{HashMap, HashSet};
-+
-+    use super::{Freezable, KeyedSet, SetConflict};
-+    use crate::lattice::partial::Conflict;
-+    use crate::{Conflicts, Join, Lift, ResultWrapped};
-+
-+    fn check_conflicts<'a>(
-+        conflicts: impl Iterator<Item = SetConflict<'a, u8, &'a Conflict<u8>>>,
-+        common: u8,
-+        extra: u8,
-+        values: [u8; 2],
-+        membership: bool,
-+        entry: bool,
-+    ) {
-+        let mut membership_count = 0;
-+        let mut entry_count = 0;
-+        for conflict in conflicts {
-+            match conflict {
-+                SetConflict::Membership(evidence) => {
-+                    membership_count += 1;
-+                    assert_eq!(evidence.frozen, &HashSet::from([common]));
-+                    assert_eq!(evidence.unexpected, &extra);
-+                    assert!(!evidence.frozen.contains(evidence.unexpected));
-+                }
-+                SetConflict::Entry { key, conflict } => {
-+                    entry_count += 1;
-+                    assert_eq!(key, &common);
-+                    assert_eq!(conflict.into_iter().copied().collect::<Vec<_>>(), values);
++    #[cfg(any(feature = "unit-tests", feature = "prop-tests"))]
++    mod conflict_regressions {
++        use std::collections::{HashMap, HashSet};
++
++        use super::{Freezable, KeyedSet, SetConflict};
++        use crate::lattice::partial::Conflict;
++        use crate::{Conflicts, Join, Lift, ResultWrapped};
++
++        fn check_conflicts<'a>(
++            conflicts: impl Iterator<Item = SetConflict<'a, u8, &'a Conflict<u8>>>,
++            common: u8,
++            extra: u8,
++            values: [u8; 2],
++            membership: bool,
++            entry: bool,
++        ) {
++            let mut membership_count = 0;
++            let mut entry_count = 0;
++            for conflict in conflicts {
++                match conflict {
++                    SetConflict::Membership(evidence) => {
++                        membership_count += 1;
++                        assert_eq!(evidence.frozen, &HashSet::from([common]));
++                        assert_eq!(evidence.unexpected, &extra);
++                        assert!(!evidence.frozen.contains(evidence.unexpected));
++                    }
++                    SetConflict::Entry { key, conflict } => {
++                        entry_count += 1;
++                        assert_eq!(key, &common);
++                        assert_eq!(conflict.into_iter().copied().collect::<Vec<_>>(), values);
++                    }
 +                }
 +            }
++            assert_eq!(membership_count, usize::from(membership));
++            assert_eq!(entry_count, usize::from(entry));
 +        }
-+        assert_eq!(membership_count, usize::from(membership));
-+        assert_eq!(entry_count, usize::from(entry));
-+    }
-+
-+    fn check_keyed_contract(common: u8, value: u8, outer_key: u8) {
-+        let extra = common.wrapping_add(1);
-+        for frozen in [false, true] {
-+            for entry_conflict in [false, true] {
-+                let other = if entry_conflict {
-+                    value.wrapping_add(1)
-+                } else {
-+                    value
-+                };
-+                let left = Freezable::Modifiable(KeyedSet(HashMap::from([(common, value)])));
-+                let left = if frozen { left.freeze() } else { left };
-+                let right = Freezable::Modifiable(KeyedSet(HashMap::from([
-+                    (common, other),
-+                    (extra, value),
-+                ])));
-+                let joined = Lift::wrap(left.clone()).join(Lift::wrap(right.clone()));
-+                let expected_ok = !frozen && !entry_conflict;
-+                assert_eq!(ResultWrapped::is_ok(&joined), expected_ok);
-+                let expected = if expected_ok {
-+                    Ok(right.clone())
-+                } else {
-+                    Err(joined.clone())
-+                };
-+                assert_eq!(ResultWrapped::try_unwrap(joined.clone()), expected);
-+                check_conflicts(
-+                    Conflicts::conflicts(&joined),
-+                    common,
-+                    extra,
-+                    [value, other],
-+                    frozen,
-+                    entry_conflict,
-+                );
 +
-+                let nested = HashMap::from([(outer_key, Some(left))])
-+                    .wrap()
-+                    .join(HashMap::from([(outer_key, Some(right.clone()))]).wrap());
-+                check_conflicts(
-+                    Conflicts::conflicts(&nested).map(|(key, conflict)| {
-+                        assert_eq!(key, &outer_key);
-+                        conflict
-+                    }),
-+                    common,
-+                    extra,
-+                    [value, other],
-+                    frozen,
-+                    entry_conflict,
-+                );
-+                assert_eq!(ResultWrapped::is_ok(&nested), expected_ok);
-+                let expected = if expected_ok {
-+                    Ok(HashMap::from([(outer_key, Some(right))]))
-+                } else {
-+                    Err(nested.clone())
-+                };
-+                assert_eq!(ResultWrapped::try_unwrap(nested), expected);
++        fn check_keyed_contract(common: u8, value: u8, outer_key: u8) {
++            let extra = common.wrapping_add(1);
++            for frozen in [false, true] {
++                for entry_conflict in [false, true] {
++                    let other = if entry_conflict {
++                        value.wrapping_add(1)
++                    } else {
++                        value
++                    };
++                    let left = Freezable::Modifiable(KeyedSet(HashMap::from([(common, value)])));
++                    let left = if frozen { left.freeze() } else { left };
++                    let right = Freezable::Modifiable(KeyedSet(HashMap::from([
++                        (common, other),
++                        (extra, value),
++                    ])));
++                    let joined = Lift::wrap(left.clone()).join(Lift::wrap(right.clone()));
++                    let expected_ok = !frozen && !entry_conflict;
++                    assert_eq!(ResultWrapped::is_ok(&joined), expected_ok);
++                    let expected = if expected_ok {
++                        Ok(right.clone())
++                    } else {
++                        Err(joined.clone())
++                    };
++                    assert_eq!(ResultWrapped::try_unwrap(joined.clone()), expected);
++                    check_conflicts(
++                        Conflicts::conflicts(&joined),
++                        common,
++                        extra,
++                        [value, other],
++                        frozen,
++                        entry_conflict,
++                    );
++
++                    let nested = HashMap::from([(outer_key, Some(left))])
++                        .wrap()
++                        .join(HashMap::from([(outer_key, Some(right.clone()))]).wrap());
++                    check_conflicts(
++                        Conflicts::conflicts(&nested).map(|(key, conflict)| {
++                            assert_eq!(key, &outer_key);
++                            conflict
++                        }),
++                        common,
++                        extra,
++                        [value, other],
++                        frozen,
++                        entry_conflict,
++                    );
++                    assert_eq!(ResultWrapped::is_ok(&nested), expected_ok);
++                    let expected = if expected_ok {
++                        Ok(HashMap::from([(outer_key, Some(right))]))
++                    } else {
++                        Err(nested.clone())
++                    };
++                    assert_eq!(ResultWrapped::try_unwrap(nested), expected);
++                }
 +            }
 +        }
-+    }
-+
-+    #[cfg(feature = "unit-tests")]
-+    #[test]
-+    fn keyed_conflicts_keep_membership_entries_and_outer_keys() {
-+        check_keyed_contract(7, 42, 9);
-+    }
 +
-+    #[cfg(feature = "prop-tests")]
-+    mod properties {
-+        use super::*;
-+        use proptest::prelude::*;
++        #[cfg(feature = "unit-tests")]
++        #[test]
++        fn keyed_conflicts_keep_membership_entries_and_outer_keys() {
++            check_keyed_contract(7, 42, 9);
++        }
 +
-+        proptest! {
-+            #[test]
-+            fn keyed_conflicts_match_failed_unwraps(
-+                common in any::<u8>(), value in any::<u8>(), outer_key in any::<u8>(),
-+            ) {
-+                check_keyed_contract(common, value, outer_key);
++        #[cfg(feature = "prop-tests")]
++        mod properties {
++            use super::*;
++            use proptest::prelude::*;
++
++            proptest! {
++                #[test]
++                fn keyed_conflicts_match_failed_unwraps(
++                    common in any::<u8>(), value in any::<u8>(), outer_key in any::<u8>(),
++                ) {
++                    check_keyed_contract(common, value, outer_key);
++                }
 +            }
 +        }
 +    }

@github-actions

Copy link
Copy Markdown
range-diff for force push b04356d5b8 → 621eee135d November 16, 2026 18:15 UTC: 1 modified; 1 commit; same base 8c2e1d8f34

reproduce: git range-diff 8c2e1d8..b04356d 8c2e1d8..621eee1

1:  b04356d5b8 +976 -0 5f ! 1:  621eee135d +992 -0 5f Introduce keyed set structures for inputs and outputs
1: b04356d5b8 ! 1: 621eee135d Introduce keyed set structures for inputs and outputs
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +
 +/// A [`KeyedSet`] whose keys may be frozen.
 +///
-+/// Callers use `Frozen` for PSBT inputs or outputs when the matching bit of
-+/// `tx_modifiable_flags` is clear.
++/// The enclosing PSBT conversion maps the corresponding `tx_modifiable_flags`
++/// bit to this tag: a clear bit means `Frozen`. This type stores that choice;
++/// reading and writing the global flags belongs to the conversion layer.
 +#[derive(Debug, Clone)]
 +pub(crate) enum Freezable<K, V> {
 +    /// Modifiable sets can be joined, unioning their keys and joining values
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +/// The result is clean when every entry is conflict-free and either no
 +/// frozen key set exists, or one distinct frozen key set equals the entry keys.
 +///
++/// For example, frozen `{a, b, c}` joined with modifiable `{a, b}` keeps the
++/// frozen membership `{a, b, c}` and joins the values for `a` and `b`. It can
++/// unwrap if those values are compatible.
++///
++/// Conversely, frozen `{a, b}` joined with modifiable `{a, b, c}` retains all
++/// three entries and the frozen key set `{a, b}`. The extra key `c` is a
++/// membership conflict, so `try_unwrap` returns `Err` rather than an enlarged
++/// frozen set.
++///
 +/// The default, the empty modifiable set, is the identity of the join.
 +#[derive(Debug, Clone)]
 +pub(crate) struct ResultKeyedSet<K, V> {
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    /// Return the number of entries, or the conflicting sizes of the frozen
 +    /// key sets and the entries.
 +    ///
-+    /// Every frozen key set is a subset of the keys of the entries, so the
-+    /// sizes are all equal only if the keys agree with the frozen sets.
++    /// Each recorded frozen key set came with entries for all its keys, and
++    /// joins retain every entry. It is therefore a subset of the entry keys:
++    /// equal sizes imply equal keys, while a proper subset has a smaller size
++    /// and makes this return a conflict.
 +    pub(crate) fn len(&self) -> JoinResult<usize> {
 +        self.frozen
 +            .iter()
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +        self.len().is_ok()
 +    }
 +
++    /// Record another operand's frozen key set, deduplicating exact matches.
++    /// This accumulates membership constraints without changing any recorded
++    /// key set. Distinct sets are retained even when one is a subset of another,
++    /// preserving the evidence of conflicting frozen memberships.
 +    fn add_frozen(&mut self, keys: HashSet<K>) {
 +        if !self.frozen.contains(&keys) {
 +            self.frozen.push(keys);

@github-actions

Copy link
Copy Markdown
range-diff for force push 621eee135d → 839365306e November 16, 2026 23:40 UTC: 1 unchanged; 1 commit; base 8c2e1d8f34 → 50eab5bc68 (diverged, 1 ahead and 1 behind)

reproduce: git range-diff 8c2e1d8..621eee1 50eab5b..8393653

1:  621eee135d +992 -0 5f = 1:  839365306e +992 -0 5f Introduce keyed set structures for inputs and outputs

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.

4 participants