Skip to content

Unordered psbt - #82

Draft
yuval-block wants to merge 8 commits into
mainfrom
unordered-psbt
Draft

yuval-block wants to merge 8 commits into
mainfrom
unordered-psbt

Conversation

@yuval-block

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

Copy link
Copy Markdown
Collaborator

opening as draft since a PR can't have more than one target it only makes sense opened against main after its dependencies are merged

depends on #72 #79 #78

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

Comment thread crates/concurrent-psbt/src/psbt/tx.rs Resolved
@github-actions

This comment has been minimized.

@github-code-quality

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

Copy link
Copy Markdown

Code coverage overview

Languages: Rust

Rust / code-coverage/cargo-llvm-cov

main 5f4ab3b unordered-psbt 2527d0f +/-
100% 100% 0%
View coverage of the 10 most impacted files.
File main 5f4ab3b unordered-psbt 2527d0f +/-
crates/concurre.../src/psbt/tx.rs 0% 100% +100%
crates/concurre...bt/keyed_set.rs 0% 100% +100%
crates/concurre...bt/input_set.rs 0% 100% +100%
crates/concurre...t/output_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 17, 2026 00:22 UTC

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

bip32_derivations: BTreeMap<PublicKey, KeySource>,
tap_internal_key: Option<XOnlyPublicKey>,
tap_tree: Option<TapTree>,
tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>,

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

tap_key_origins breaks Join laws in ResultOutput

The order-insensitive tap-key-origin join keeps the left leaf order, so a.join(b) != b.join(a) and (a.join(b)).join(c) != a.join(b.join(c)) under the derived PartialEq.
The assert_join_laws! generators never populate tap_key_origins, so the property tests miss it.

oak · automated · 06d29dc

Comment thread crates/concurrent-psbt/src/psbt/tx.rs Outdated
let other_output_len = other.outputs.len();

let inputs = self.inputs.join(other.inputs);
let outputs = self.outputs.join(other.outputs);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Join unions distinct outputs without modifiable flag

Joining two UnorderedPsbts with distinct outputs succeeds even when PSBT_GLOBAL_TX_MODIFIABLE has neither modifiable bit set.
The spec requires combining to fail when distinct identifiers are present without the corresponding flag.

Distinct identifiers are only allowed if the corresponding PSBT_GLOBAL_TX_MODIFIABLE flag is set, because such combinations represent additions of inputs or outputs.

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

If this is not the case but a distinct input or output is present, then combining must fail.

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

Test that fails on this commit
use concurrent_psbt::Join;
use concurrent_psbt::input::InputSet;
use concurrent_psbt::output::{OutputSet, OutputUniqueIdExt, UniqueId};
use concurrent_psbt::tx::UnorderedPsbt;
use psbt_v2::v2::{Global, Output};

fn psbt(uid: u8) -> UnorderedPsbt {
    let mut output = Output::default();
    output.set_unique_id(UniqueId::new(vec![uid]));
    let outputs = OutputSet::try_from_outputs([output]).unwrap();
    UnorderedPsbt { global: Global::default(), inputs: InputSet::default(), outputs }
}

#[test]
fn join_distinct_outputs_without_modifiable_flag_must_fail() {
    let joined = psbt(1).wrap().join(psbt(2).wrap());
    assert!(!joined.is_ok());
}

cargo test -p concurrent-psbt --test modifiable_flag join_distinct_outputs_without_modifiable_flag_must_fail

oak · automated · 06d29dc

Comment thread crates/concurrent-psbt/src/psbt/tx.rs Outdated
/// Returns the first input whose outpoint repeats, then the first output
/// that is missing a `PSBT_OUT_UNIQUE_ID` field or repeats one.
pub fn try_from_psbt(psbt: Psbt) -> Result<Self, UnorderedPsbtError> {
let inputs = InputSet::try_from_inputs(psbt.inputs)?.wrap();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

SIGHASH_SINGLE input accepted into unordered PSBT

UnorderedPsbt::try_from_psbt accepts inputs whose sighash_type is SIGHASH_SINGLE; into_psbt then shuffles inputs, so a SIGHASH_SINGLE signature can commit to a different output.
The spec requires SIGHASH_SINGLE inputs not be used in unordered transactions.

SIGHASH_SINGLE inputs MUST not be used in unordered transactions.

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

oak · automated · 06d29dc

@github-actions

This comment has been minimized.

@github-actions

This comment has been minimized.

@xstoicunicornx xstoicunicornx linked an issue Nov 13, 2026 that may be closed by this pull request
@github-actions

Copy link
Copy Markdown
range-diff for force push ac405b3333 → a3a74d8ae5 November 14, 2026 23:39 UTC: 2 modified, 4 unchanged, 1 added; 6 → 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..ac405b3 3e0c224..a3a74d8

1:  0db8544246 +915 -315  8f = 1:  0db8544246 +915 -315  8f define own Global, Input and Output structs
2:  5e37ffb7b5 +313 -590 10f = 2:  5e37ffb7b5 +313 -590 10f lift joinable_struct fields by type, not by token
3:  3e05d55356 +241 -204  7f = 3:  3e05d55356 +241 -204  7f generate v2 conversions from the field lists
-:  ----------               > 4:  20c3f12f9d  +32   -8  4f make Global, Input and Output fields private
4:  584ccad50a +545   -0  2f = 5:  d8b2490d95 +545   -0  2f Introduce keyed set structures for inputs and outputs
5:  ea3545eb42 +296  -20  4f ! 6:  135b77cccd +301  -20  4f introduce OutputSet, keyed by unique output IDs
6:  d589deec25 +338  -44  4f ! 7:  a92a27323f +337  -44  4f Introduce InputSet, keyed by outpoint
5: ea3545eb42 ! 6: 135b77cccd introduce OutputSet, keyed by unique output IDs
@@ crates/concurrent-psbt/src/psbt/output_set.rs (new)
 +            )
 +                .prop_map(|(uid, amount, redeem, witness, props)| {
 +                    let mut output = output(uid, amount);
-+                    output.redeem_script = redeem.map(ScriptBuf::from_bytes);
-+                    output.witness_script = witness.map(ScriptBuf::from_bytes);
-+                    for (k, v) in props {
-+                        let prop_key = psbt_v2::raw::ProprietaryKey {
-+                            prefix: b"test".to_vec(),
-+                            subtype: k[0],
-+                            key: k,
-+                        };
-+                        output.proprietaries.insert(prop_key, v);
-+                    }
++                    output.set_redeem_script(redeem.map(ScriptBuf::from_bytes));
++                    output.set_witness_script(witness.map(ScriptBuf::from_bytes));
++                    output.set_proprietaries(
++                        props
++                            .into_iter()
++                            .map(|(k, v)| {
++                                let prop_key = psbt_v2::raw::ProprietaryKey {
++                                    prefix: b"test".to_vec(),
++                                    subtype: k[0],
++                                    key: k,
++                                };
++                                (prop_key, v)
++                            })
++                            .collect(),
++                    );
 +                    output
 +                })
 +        }
6: d589deec25 ! 7: a92a27323f Introduce InputSet, keyed by outpoint
@@ crates/concurrent-psbt/src/psbt/input_set.rs (new)
 +        #[test]
 +        fn inputs_with_different_sequences_for_one_outpoint_conflict() {
 +            let with_sequence = |sequence| {
-+                let input = Input {
-+                    sequence: Some(Sequence(sequence)),
-+                    ..make_input(1, 0)
-+                };
++                let mut input = make_input(1, 0);
++                input.set_sequence(Some(Sequence(sequence)));
 +                InputSet::try_from_inputs([input]).unwrap().wrap()
 +            };
 +            let joined = with_sequence(1).join(with_sequence(2));
@@ crates/concurrent-psbt/src/psbt/input_set.rs (new)
 +                s2 in 0u32..3,
 +            ) {
 +                let singleton = |sequence| {
-+                    let input = Input { sequence: Some(Sequence(sequence)), ..Input::new(&op) };
++                    let mut input = Input::new(&op);
++                    input.set_sequence(Some(Sequence(sequence)));
 +                    InputSet::try_from_inputs([input]).unwrap().wrap()
 +                };
 +                let joined = singleton(s1).join(singleton(s2));

@oakagent oakagent left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed the 6 newest of 8 commits; the rest of the pull request will be reviewed in the next cycles.

/// list.
/// 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. The field itself is private: its visibility

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's visibility claim conflicts with private mirrored fields

The doc says a field's visibility applies to the $Source field and that the struct has the fields "as written", but in the v2 form the recursive call drops $vis for fields entries, so those fields are private and pub reaches only the accessors.

Each field may carry attributes and a visibility, which apply to the

— fungi-protocol/concurrent-psbt@20c3f12 · crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs#L23

1. $Source struct with the fields as written

— fungi-protocol/concurrent-psbt@20c3f12 · crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs#L27

oakagent · automated · a3a74d8

/// 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.

Clean-join doc ignores conflicting entries

is_ok also requires every entry to be conflict-free, so a frozen set joined with a same-key or subset-key set whose shared values differ is not clean and try_unwrap returns Err; the doc's unqualified joins cleanly is false for that case.

oakagent · automated · a3a74d8

/// Extract a clean [`UnorderedPsbt`] if there are no conflicts, otherwise return `self`.
///
/// # Errors
/// Returns `Err(self)` if any field contains a conflict.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

is_ok docs omit frozen membership mismatch

try_unwrap and is_ok (line 242) can fail when frozen sets have different members even though every field is conflict-free; ResultKeyedSet::is_ok also requires keys_agree, which the method docs omit.

/// Frozen inputs or outputs join cleanly only with frozen sets of the same /// members, or with modifiable sets whose members they already have.

— fungi-protocol/concurrent-psbt@a3a74d8 · crates/concurrent-psbt/src/psbt/tx.rs#L37-L38

self.keys_agree() && self.entries.0.is_ok()

— fungi-protocol/concurrent-psbt@a3a74d8 · crates/concurrent-psbt/src/psbt/keyed_set.rs#L241

oakagent · automated · a3a74d8

@github-actions

Copy link
Copy Markdown
range-diff for force push a3a74d8ae5 → f75c6a9162 November 15, 2026 02:13 UTC: 3 modified, 4 unchanged; 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..a3a74d8 3e0c224..f75c6a9

1:  0db8544246 +915 -315  8f ! 1:  91dd03bef5 +909 -315  8f define own Global, Input and Output structs
2:  5e37ffb7b5 +313 -590 10f = 2:  b2a9b9e0e3 +313 -590 10f lift joinable_struct fields by type, not by token
3:  3e05d55356 +241 -204  7f ! 3:  3943f9919b +241 -198  7f generate v2 conversions from the field lists
4:  20c3f12f9d  +32   -8  4f ! 4:  a1723301e7  +42   -8  5f make Global, Input and Output fields private
5:  d8b2490d95 +545   -0  2f = 5:  60e06c9274 +545   -0  2f Introduce keyed set structures for inputs and outputs
6:  135b77cccd +301  -20  4f = 6:  bbc6975fbb +301  -20  4f introduce OutputSet, keyed by unique output IDs
7:  a92a27323f +337  -44  4f = 7:  77d58e903b +337  -44  4f Introduce InputSet, keyed by outpoint
1: 0db8544246 ! 1: 91dd03bef5 define own Global, Input and Output structs
@@ crates/concurrent-psbt/src/psbt/input.rs: use bitcoin::key::{PublicKey, XOnlyPub
 +}
 +
 +impl From<Input> for psbt_v2::v2::Input {
-+    #[expect(
-+        clippy::needless_update,
-+        reason = "keeps building if psbt-v2 adds fields this crate does not support yet"
-+    )]
 +    fn from(input: Input) -> Self {
 +        let outpoint = out_point(&input);
 +        Self {
-+            previous_txid: input.previous_txid,
-+            spent_output_index: input.spent_output_index,
 +            sequence: input.sequence,
 +            min_time: input.min_time,
 +            min_height: input.min_height,
3: 3e05d55356 ! 3: 3943f9919b generate v2 conversions from the field lists
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
  }
  
  impl From<Input> for psbt_v2::v2::Input {
--    #[expect(
--        clippy::needless_update,
--        reason = "keeps building if psbt-v2 adds fields this crate does not support yet"
--    )]
      fn from(input: Input) -> Self {
 -        let outpoint = out_point(&input);
 -        Self {
--            previous_txid: input.previous_txid,
--            spent_output_index: input.spent_output_index,
 -            sequence: input.sequence,
 -            min_time: input.min_time,
 -            min_height: input.min_height,
4: 20c3f12f9d ! 4: a1723301e7 make Global, Input and Output fields private
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
          impl $Source {
              /// The mirrored fields of `v2`, with these proprietary fields.
              fn from_v2_fields(v2: $V2, $( $proprietary: $P ),*) -> Self {
+
+ ## crates/concurrent-psbt/src/psbt/output.rs ##
+@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
+                 prop_assert_eq!(r.is_ok(), r.try_unwrap().is_ok());
+             }
+ 
++            #[test]
++            fn a_set_field_reads_back(
++                mut o in arb_output(),
++                redeem in proptest::option::of(proptest::collection::vec(0u8..255, 0..=8)),
++            ) {
++                let redeem = redeem.map(ScriptBuf::from_bytes);
++                o.set_redeem_script(redeem.clone());
++                prop_assert_eq!(o.redeem_script(), &redeem);
++            }
++
+         }
+     }
+ 

@github-actions

Copy link
Copy Markdown
range-diff for force push f75c6a9162 → 35bf83523d November 15, 2026 23:52 UTC: 1 modified, 3 unchanged, 3 dropped, 3 added; 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..f75c6a9 3e0c224..35bf835

1:  91dd03bef5 +909 -315  8f < -:  ----------               define own Global, Input and Output structs
2:  b2a9b9e0e3 +313 -590 10f ! 1:  439d9e2a38 +319 -550 10f lift joinable_struct fields by type, not by token
3:  3943f9919b +241 -198  7f < -:  ----------               generate v2 conversions from the field lists
4:  a1723301e7  +42   -8  5f < -:  ----------               make Global, Input and Output fields private
-:  ----------               > 2:  3a5f624ca5 +464 -151  6f define own Global, Input and Output structs
-:  ----------               > 3:  86572d9e5f +284  -89  6f require a unique ID on every Output
-:  ----------               > 4:  e4468abab2 +220 -103  7f store tap leaf hashes as TapLeafHashes
5:  60e06c9274 +545   -0  2f = 5:  dcf9f5d0a3 +545   -0  2f Introduce keyed set structures for inputs and outputs
6:  bbc6975fbb +301  -20  4f = 6:  9a23fc71d1 +301  -20  4f introduce OutputSet, keyed by unique output IDs
7:  77d58e903b +337  -44  4f = 7:  95c869edff +337  -44  4f Introduce InputSet, keyed by outpoint
2: b2a9b9e0e3 ! 1: 439d9e2a38 lift joinable_struct fields by type, not by token
@@ crates/concurrent-psbt/src/lattice/mod.rs
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
 @@
- //! each of them in the internal result domain, enabling field-by-field merging
- //! that accumulates conflicts without short-circuiting.
+ //! enabling field-by-field merging that accumulates conflicts without short-circuiting.
+ //! [`GlobalExt::wrap`] lifts a clean [`Global`] into the result domain.
  
 +use std::collections::BTreeMap;
 +
@@ 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: joinable_struct! {
+ 
+ /// Extract the [`OutPoint`] this input spends (previous txid + output index).
+ #[cfg_attr(
+-    not(test),
++    not(all(test, feature = "unit-tests")),
+     expect(
+         dead_code,
+         reason = "used by InputSet once inputs are keyed by spent outpoint"
 @@ 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::bip32::{DerivationPath, Fingerprint};
          use bitcoin::hashes::Hash;
-         use bitcoin::secp256k1::{Keypair, Message, Secp256k1, SecretKey};
-         use bitcoin::sighash::TapSighashType;
-         use std::collections::BTreeMap;
- 
+-        use bitcoin::secp256k1::{Secp256k1, SecretKey};
+-
 -        const ALL_CONFLICT_FIELDS: &[&str] = &[
 -            "previous_txid",
 -            "spent_output_index",
@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
 -
 -            result
 -        }
--
+ 
          fn make_input(txid_byte: u8, vout: u32) -> Input {
              let txid = bitcoin::Txid::from_byte_array([txid_byte; 32]);
-             Input::new(&bitcoin::OutPoint { txid, vout })
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
          }
  
          #[test]
@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
 +            assert_eq!(joined.clone().try_unwrap(), Err(joined));
          }
  
-         /// An input with every field set, so a conversion that drops one
-@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
-         }
- 
          #[test]
--        fn v2_conversion_keeps_every_field() {
-+        fn v2_conversion_round_trips_a_populated_input() {
-             let input = populated_input();
-             assert_eq!(Input::from(psbt_v2::v2::Input::from(input.clone())), input);
-         }
 @@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
          proptest! {
              #[test]
@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
 +                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() {
@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
 
  ## crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs ##
 @@
- /// Generate a product type, its result-domain counterpart, and their lattice
- /// operations from a single field list using standard Rust type syntax.
+ /// Generate a result-domain product type and its lattice operations from a
+ /// single field list using standard Rust type syntax.
  ///
 -/// Fields are classified automatically:
 -///
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +/// [`PartialJoin`](crate::PartialJoin) scalar as a
 +/// [`JoinResult`](crate::JoinResult), and `Option` and `BTreeMap` by lifting
 +/// their contents. Paths and type aliases resolve like any other type.
- ///
- /// Each field may carry attributes and a visibility, which apply to the
- /// `$Source` field; fields of `$Result` are `pub(crate)`.
  ///
  /// Generates:
- /// 1. `$Source` struct with the fields as written
--/// 2. `$Result` struct with transformed field types
-+/// 2. `$Result` struct with the lifted field types
- /// 3. `$Source::wrap`
- /// 4. `Join for $Result`
--/// 5. `$Result::is_ok`
--/// 6. `$Result::try_unwrap`
--///
--/// The field list must name at least one field: `is_ok` is generated as the
+-/// 1. `$Result` struct with transformed field types
++/// 1. `$Result` struct with the lifted field types
+ /// 2. `$Ext` trait with `wrap` method on the source type
+ /// 3. `Join for $Result`
+-/// 4. `$Result::is_ok`
+-/// 5. `$Result::try_unwrap`
++/// 4. `$Result::is_ok`, `$Result::for_each_conflict` and `$Result::try_unwrap`
++/// 5. `ResultValue for $Result`
+ ///
+ /// The field list must name at least one field: `is_ok` is generated as the
 -/// conjunction of the per-field checks, which has no expansion for an empty
 -/// list.
-+/// 5. `$Result::is_ok`, `$Result::for_each_conflict` and `$Result::try_unwrap`
-+/// 6. `ResultValue for $Result`
++/// conjunction of the per-field checks.
  macro_rules! joinable_struct {
 -    // ── Entry point ──────────────────────────────────────────
      (
-         $(#[$source_meta:meta])*
-         source: $Source:ident,
          $(#[$result_meta:meta])*
+         source: $Source:ident,
          result: $Result:ident,
+         ext: $Ext:ident,
 -        fields: { $($fields:tt)* }
 -    ) => {
 -        joinable_struct!(@munch
--            source_meta: [ $(#[$source_meta])* ]
--            result_meta: [ $(#[$result_meta])* ]
+-            meta: [ $(#[$result_meta])* ]
 -            source: $Source
 -            result: $Result
+-            ext: $Ext
 -            classified: []
 -            rest: [ $($fields)* ]
 -        );
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 -
 -    // ── Option<T> ────────────────────────────────────────────
 -    (@munch
--        source_meta: $source_meta:tt
--        result_meta: $result_meta:tt
+-        meta: $meta:tt
 -        source: $Source:ident
 -        result: $Result:ident
+-        ext: $Ext:ident
 -        classified: [ $($classified:tt)* ]
--        rest: [
--            $(#[$field_meta:meta])* $vis:vis $field:ident : Option < $T:ty > ,
--            $($rest:tt)*
--        ]
+-        rest: [ $field:ident : Option < $T:ty > , $($rest:tt)* ]
 -    ) => {
 -        joinable_struct!(@munch
--            source_meta: $source_meta
--            result_meta: $result_meta
+-            meta: $meta
 -            source: $Source
 -            result: $Result
--            classified: [
--                $($classified)*
--                (option [ $(#[$field_meta])* ] [ $vis ] $field $T)
--            ]
+-            ext: $Ext
+-            classified: [ $($classified)* (option $field $T) ]
 -            rest: [ $($rest)* ]
 -        );
 -    };
 -
 -    // ── BTreeMap<K, V> ──────────────────────────────────────
 -    (@munch
--        source_meta: $source_meta:tt
--        result_meta: $result_meta:tt
+-        meta: $meta:tt
 -        source: $Source:ident
 -        result: $Result:ident
+-        ext: $Ext:ident
 -        classified: [ $($classified:tt)* ]
--        rest: [
--            $(#[$field_meta:meta])* $vis:vis $field:ident : BTreeMap < $K:ty , $V:ty > ,
--            $($rest:tt)*
--        ]
+-        rest: [ $field:ident : BTreeMap < $K:ty , $V:ty > , $($rest:tt)* ]
 -    ) => {
 -        joinable_struct!(@munch
--            source_meta: $source_meta
--            result_meta: $result_meta
+-            meta: $meta
 -            source: $Source
 -            result: $Result
--            classified: [
--                $($classified)*
--                (map [ $(#[$field_meta])* ] [ $vis ] $field [ $K => $V ])
--            ]
+-            ext: $Ext
+-            classified: [ $($classified)* (map $field [ $K => $V ]) ]
 -            rest: [ $($rest)* ]
 -        );
 -    };
 -
 -    // ── Scalar T (catch-all; must come after Option, BTreeMap) ─
 -    (@munch
--        source_meta: $source_meta:tt
--        result_meta: $result_meta:tt
+-        meta: $meta:tt
 -        source: $Source:ident
 -        result: $Result:ident
+-        ext: $Ext:ident
 -        classified: [ $($classified:tt)* ]
--        rest: [
--            $(#[$field_meta:meta])* $vis:vis $field:ident : $T:ty ,
--            $($rest:tt)*
--        ]
+-        rest: [ $field:ident : $T:ty , $($rest:tt)* ]
 -    ) => {
 -        joinable_struct!(@munch
--            source_meta: $source_meta
--            result_meta: $result_meta
+-            meta: $meta
 -            source: $Source
 -            result: $Result
--            classified: [
--                $($classified)*
--                (scalar [ $(#[$field_meta])* ] [ $vis ] $field $T)
--            ]
+-            ext: $Ext
+-            classified: [ $($classified)* (scalar $field $T) ]
 -            rest: [ $($rest)* ]
 -        );
 -    };
 -
 -    // ── Terminal: no more fields ─────────────────────────────
 -    (@munch
--        source_meta: [ $(#[$source_meta:meta])* ]
--        result_meta: [ $(#[$result_meta:meta])* ]
+-        meta: [ $(#[$result_meta:meta])* ]
 -        source: $Source:ident
 -        result: $Result:ident
--        classified: [
--            $( (
--                $category:ident
--                [ $(#[$field_meta:meta])* ]
--                [ $vis:vis ]
--                $field:ident
--                $type_tokens:tt
--            ) )*
--        ]
+-        ext: $Ext:ident
+-        classified: [ $( ($category:ident $field:ident $type_tokens:tt) )* ]
 -        rest: []
 +        fields: {
-+            $( $(#[$field_meta:meta])* $vis:vis $field:ident : $T:ty ),+ $(,)?
++            $( $field:ident : $T:ty ),+ $(,)?
 +        }
      ) => {
--        // 1. Source struct
-         $(#[$source_meta])*
-         #[derive(Debug, Clone, PartialEq, Eq)]
-         pub struct $Source {
-             $(
-                 $(#[$field_meta])*
--                $vis $field: joinable_struct!(@source_type $category $type_tokens),
--            )*
-+                $vis $field: $T,
-+            )+
-         }
- 
--        // 2. Result struct
+-        // 1. Result struct
          $(#[$result_meta])*
          #[derive(Debug, Clone, PartialEq)]
          pub struct $Result {
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +            )+
          }
  
--        // 3. wrap
-         impl $Source {
-             #[doc = concat!(
-                 "Lift into the result domain as a conflict-free [`",
+-        // 2. Ext trait + impl
+         pub trait $Ext {
++            #[doc = concat!(
++                "Lift into the result domain as a conflict-free [`",
++                stringify!($Result),
++                "`]."
++            )]
+             fn wrap(self) -> $Result;
+         }
+ 
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
-             pub fn wrap(self) -> $Result {
+             fn wrap(self) -> $Result {
                  $Result {
                      $(
 -                        $field: joinable_struct!(@wrap $category self . $field),
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
              }
          }
  
--        // 4. Join
+-        // 3. Join
          impl $crate::lattice::join::Join for $Result {
              fn join(self, other: Self) -> Self {
                  $Result {
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
              }
          }
  
--        // 5. is_ok + 6. try_unwrap
+-        // 4. is_ok + 5. try_unwrap
          impl $Result {
 +            /// Returns `true` if no field holds a conflict.
              pub fn is_ok(&self) -> bool {
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
              }
          }
 -    };
- 
--    // --- Type rules ---
 -
--    (@source_type scalar $T:ty) => {
--        $T
--    };
--    (@source_type option $T:ty) => {
--        Option<$T>
--    };
--    (@source_type map [$K:ty => $V:ty]) => {
--        std::collections::BTreeMap<$K, $V>
--    };
+-    // --- Type transformation rules ---
 -
 -    (@result_type scalar $T:ty) => {
 -        $crate::lattice::partial::JoinResult<$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_
 -    };
 -
 -    // --- is_ok rules ---
--
+ 
 -    (@is_ok scalar $self:ident . $field:ident) => {
 -        $self.$field.is_ok()
 -    };
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 -    (@is_ok map $self:ident . $field:ident) => {
 -        $crate::collections::btreemap::ResultBTreeMapExt::is_ok(&$self.$field)
 -    };
--
++        impl $crate::lattice::lift::ResultValue for $Result {
++            type Clean = $Source;
+ 
 -    // --- Visit-conflict rules ---
 +            fn is_ok(&self) -> bool {
 +                $Result::is_ok(self)
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
  
 -    use crate::lattice::join::Join;
 -
++    /// One field per kind of lifting, the option spelled as a path.
+     #[derive(Debug, PartialEq)]
+     pub struct Sample {
+-        scalar: u8,
+-        option: Option<u8>,
+-        map: BTreeMap<u8, u8>,
++        pub scalar: u8,
++        pub option: std::option::Option<u8>,
++        pub map: BTreeMap<u8, u8>,
+     }
+ 
      joinable_struct! {
--        /// One field per category.
-+        /// One field per kind of lifting, the option spelled as a path.
+-        /// Result-domain form of [`Sample`], one field per category.
++        /// Result-domain form of [`Sample`].
          source: Sample,
-         /// Result-domain form of [`Sample`].
          result: ResultSample,
+         ext: SampleExt,
          fields: {
--            scalar: u8,
+             scalar: u8,
 -            option: Option<u8>,
--            map: BTreeMap<u8, u8>,
-+            pub scalar: u8,
-+            pub option: std::option::Option<u8>,
-+            pub map: BTreeMap<u8, u8>,
++            option: std::option::Option<u8>,
+             map: BTreeMap<u8, u8>,
          }
      }
 +}
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 +mod tests {
 +    use std::collections::BTreeMap;
 +
-+    use super::sample::Sample;
++    use super::sample::{Sample, SampleExt};
 +    use crate::lattice::join::Join;
 +    use crate::lattice::lift::ResultValue;
  
@@ crates/concurrent-psbt/src/psbt/output.rs
 +
  use bitcoin::bip32::KeySource;
  use bitcoin::key::{PublicKey, XOnlyPublicKey};
- use bitcoin::taproot::TapTree;
+ use bitcoin::taproot::{TapLeafHash, 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::bip32::{DerivationPath, Fingerprint};
-         use bitcoin::hashes::Hash;
-         use bitcoin::secp256k1::{Secp256k1, SecretKey};
-         use bitcoin::taproot::{TapLeafHash, TaprootBuilder};
-         use std::collections::BTreeMap;
- 
+-        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 {
 -        }
 -
 -        fn all_fields_conflict(seed: u8) -> ResultOutput {
--            let mut result = output(seed).wrap();
--            result.unique_id = empty_conflict();
+-            let mut result = Output::default().wrap();
 -            result.amount = empty_conflict();
 -            result.script_pubkey = empty_conflict();
 -            result.redeem_script = Some(empty_conflict());
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
 -            );
 -            result
 -        }
--
+ 
          #[test]
 -        fn try_unwrap_conflicting_returns_err() {
 -            let a = Output {
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
 +        fn outputs_with_different_amounts_conflict() {
 +            let with_amount = |sats| Output {
 +                amount: Amount::from_sat(sats),
-                 ..output(1)
+                 ..Output::default()
              };
 -            let b = Output {
 -                amount: bitcoin::Amount::from_sat(200),
--                ..output(1)
+-                ..Output::default()
 -            };
 -            assert!(a.wrap().join(b.wrap()).try_unwrap().is_err());
 -        }
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
 +            assert_eq!(fields, ["amount"]);
 +            assert_eq!(joined.clone().try_unwrap(), Err(joined));
          }
+     }
  
-         /// An output with every field set, so a conversion that drops one
 @@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
          proptest! {
              #[test]

@github-actions

Copy link
Copy Markdown
range-diff for force push 35bf83523d → d7528fc86f November 16, 2026 00:16 UTC: 1 modified, 6 unchanged; 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..35bf835 3e0c224..d7528fc

1:  439d9e2a38 +319 -550 10f = 1:  439d9e2a38 +319 -550 10f lift joinable_struct fields by type, not by token
2:  3a5f624ca5 +464 -151  6f = 2:  3a5f624ca5 +464 -151  6f define own Global, Input and Output structs
3:  86572d9e5f +284  -89  6f = 3:  86572d9e5f +284  -89  6f require a unique ID on every Output
4:  e4468abab2 +220 -103  7f ! 4:  5cf8f49ac9 +220 -103  7f store tap leaf hashes as TapLeafHashes
5:  dcf9f5d0a3 +545   -0  2f = 5:  25198c9ee7 +545   -0  2f Introduce keyed set structures for inputs and outputs
6:  9a23fc71d1 +301  -20  4f = 6:  800d3772d5 +301  -20  4f introduce OutputSet, keyed by unique output IDs
7:  95c869edff +337  -44  4f = 7:  2a7612e4db +337  -44  4f Introduce InputSet, keyed by outpoint
4: e4468abab2 ! 4: 5cf8f49ac9 store tap leaf hashes as TapLeafHashes
@@ Commit message
     after the type names a MirroredField that converts between them.
     tap_key_origins uses TapKeyOrigins to convert each key's leaf hashes.
 
-    closes #76
+    supersedes #76
 
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@github-actions

Copy link
Copy Markdown
range-diff for force push d7528fc86f → 7fe9c87e5c November 16, 2026 03:20 UTC: 7 modified; 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..d7528fc 3e0c224..7fe9c87

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

1:  439d9e2a38 +319 -550 10f ! 1:  b72b43e9b8 +499 -635 16f lift joinable_struct fields by type, not by token
2:  3a5f624ca5 +464 -151  6f ! 2:  5088693414 +491 -182  6f define own Global, Input and Output structs
3:  86572d9e5f +284  -89  6f ! 3:  b8f825d24f +285  -89  6f require a unique ID on every Output
4:  5cf8f49ac9 +220 -103  7f ! 4:  3bebd68a9b +374 -157  8f store tap leaf hashes as TapLeafHashes
5:  25198c9ee7 +545   -0  2f ! 5:  a09dc87596 +725   -0  4f Introduce keyed set structures for inputs and outputs
7:  2a7612e4db +337  -44  4f ! 6:  35910fca22 +315   -1  3f Introduce InputSet, keyed by outpoint
6:  800d3772d5 +301  -20  4f ! 7:  cd20f9d27a +329   -0  3f introduce OutputSet, keyed by unique output IDs
1: 439d9e2a38 ! 1: b72b43e9b8 lift joinable_struct fields by type, not by token
@@ Metadata
 Author: Yuval Kogman <nothingmuch@woobling.org>
 
  ## Commit message ##
-    lift joinable_struct fields by type, not by token
+    Lift PSBT fields recursively and retain typed conflict paths
 
-    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.
+    Choose each field's result type through Lift, so aliases and qualified
+    Option, BTreeMap, and HashMap types behave like their underlying types.
+    Generated PSBT records can themselves be wrapped inside these containers.
 
-    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.
+    Lift::wrap pairs with ResultWrapped::try_unwrap. Failed extraction retains
+    the complete wrapped container, including its clean entries.
 
-    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.
+    Compose borrowed Conflicts iterators without erasing map keys or value
+    types. Record conflict enums identify the field and any keydata, replacing
+    the Debug-based callback visitor.
 
     Suggested-by: Codex
-
     Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
 
  ## crates/concurrent-psbt/src/collections/btreemap.rs ##
 @@
  use std::collections::BTreeMap;
-+use std::fmt::Debug;
  
++use crate::lattice::conflicts::Conflicts;
  use crate::lattice::join::{Join, JoinMut};
 -use crate::lattice::partial::{JoinResult, PartialJoin};
 -
@@ crates/concurrent-psbt/src/collections/btreemap.rs
 -    /// Lift each value to `Ok`, preserving keys.
 -    fn wrap(self) -> BTreeMap<Self::Key, JoinResult<Self::Value>>;
 -}
-+use crate::lattice::lift::{ConflictVisitor, Lift, ResultValue, VisitConflicts};
++use crate::lattice::lift::{Lift, ResultWrapped};
++
++impl<K: Ord, V: Lift> Lift for BTreeMap<K, V> {
++    type Result = BTreeMap<K, V::Result>;
  
 -impl<K: Ord, V: PartialJoin> BTreeMapExt for BTreeMap<K, V> {
 -    type Key = K;
 -    type Value = V;
 -    fn wrap(self) -> BTreeMap<K, JoinResult<V>> {
--        self.into_iter().map(|(k, v)| (k, v.wrap())).collect()
--    }
--}
-+/// Each value lifts, keeping its key.
-+impl<K: Ord, V: Lift> Lift for BTreeMap<K, V> {
-+    type Result = BTreeMap<K, V::Result>;
++    fn wrap(self) -> Self::Result {
+         self.into_iter().map(|(k, v)| (k, v.wrap())).collect()
+     }
+ }
  
 -/// Extension trait for `BTreeMap<K, JoinResult<V>>` — `is_ok` checks all values,
 -/// `try_unwrap` extracts the plain map or returns `self` on conflict.
@@ crates/concurrent-psbt/src/collections/btreemap.rs
 -    fn is_ok(&self) -> bool;
 -    /// Extract the plain `BTreeMap<K, V>`, or return `self` if any value is a conflict.
 -    fn try_unwrap(self) -> Result<BTreeMap<Self::Key, Self::Value>, Self>;
-+    fn lift(self) -> Self::Result {
-+        self.into_iter().map(|(k, v)| (k, v.lift())).collect()
-+    }
- }
- 
+-}
+-
 -impl<K: Ord, V: PartialJoin> ResultBTreeMapExt for BTreeMap<K, JoinResult<V>> {
 -    type Key = K;
 -    type Value = V;
-+/// 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> {
++impl<K: Ord, R: ResultWrapped> ResultWrapped for BTreeMap<K, R> {
 +    type Clean = BTreeMap<K, R::Clean>;
  
      fn is_ok(&self) -> bool {
@@ crates/concurrent-psbt/src/collections/btreemap.rs
 +}
 +
 +#[cfg_attr(coverage_nightly, coverage(off))]
-+fn unwrap_after_is_ok<R: ResultValue>(value: R) -> R::Clean {
++fn unwrap_after_is_ok<R: ResultWrapped>(value: R) -> R::Clean {
 +    match value.try_unwrap() {
 +        Ok(value) => value,
 +        Err(_) => unreachable!("is_ok() guard verified all entries"),
 +    }
 +}
 +
-+/// Reports each conflict with the key of the value holding it.
-+impl<K: Debug, R: VisitConflicts> VisitConflicts for BTreeMap<K, R> {
-+    fn visit_conflicts(&self, f: &mut ConflictVisitor<'_>) {
-+        for (key, value) in self {
-+            value.visit_conflicts(&mut |_, conflict| f(Some(key), conflict));
-+        }
++impl<K, R: Conflicts> Conflicts for BTreeMap<K, R> {
++    type Item<'a>
++        = (&'a K, R::Item<'a>)
++    where
++        Self: 'a;
++
++    fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>> {
++        self.iter()
++            .flat_map(|(key, value)| value.conflicts().map(move |conflict| (key, conflict)))
      }
  }
  
@@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
 -        fn wrap_lifts() {
 +        fn lift_lifts_each_value() {
              let a: BTreeMap<u8, Val> = [(0, Val(0))].into();
--            assert_eq!(a.wrap(), [(0, Ok(Val(0)))].into());
-+            assert_eq!(a.lift(), [(0, Ok(Val(0)))].into());
+             assert_eq!(a.wrap(), [(0, Ok(Val(0)))].into());
          }
  
          #[test]
@@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
              let a: BTreeMap<u8, Val> = [(0, Val(0))].into();
              let b: BTreeMap<u8, Val> = [(1, Val(0))].into();
              assert_eq!(
--                a.wrap().join(b.wrap()),
-+                a.lift().join(b.lift()),
-                 [(0, Ok(Val(0))), (1, Ok(Val(0)))].into()
-             );
-         }
 @@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
-             let a: BTreeMap<u8, Val> = [(0, Val(0))].into();
-             let b: BTreeMap<u8, Val> = [(1, Val(0))].into();
-             assert_eq!(
--                a.wrap().join(b.wrap()).try_unwrap(),
-+                a.lift().join(b.lift()).try_unwrap(),
-                 Ok([(0, Val(0)), (1, Val(0))].into())
-             );
          }
  
          #[test]
@@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
              let a: BTreeMap<u8, Val> = [(0, Val(0))].into();
              let c: BTreeMap<u8, Val> = [(0, Val(1))].into();
              assert_eq!(
--                a.wrap().join(c.wrap()),
-+                a.lift().join(c.lift()),
-                 [(0, Err(Conflict::from_values([Val(0), Val(1)])))].into()
-             );
-         }
-@@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
-             let a: BTreeMap<u8, Val> = [(0, Val(0))].into();
-             let c: BTreeMap<u8, Val> = [(0, Val(1))].into();
-             assert_eq!(
--                a.wrap().join(c.wrap()).try_unwrap(),
-+                a.lift().join(c.lift()).try_unwrap(),
-                 Err([(0, Err(Conflict::from_values([Val(0), Val(1)])))].into())
-             );
-         }
 @@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
          // Type-specific
          proptest! {
@@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
 -                prop_assert_eq!(wrapped.len(), len);
 -                prop_assert!(wrapped.is_ok());
 -                prop_assert!(wrapped.try_unwrap().is_ok());
-+                let lifted: BTreeMap<u8, JoinResult<Val>> = m.clone().lift();
++                let lifted: BTreeMap<u8, JoinResult<Val>> = m.clone().wrap();
 +                prop_assert_eq!(lifted.len(), len);
 +                prop_assert!(lifted.is_ok());
 +                prop_assert_eq!(lifted.try_unwrap(), Ok(m));
@@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
  
 +            #[test]
 +            fn visits_each_conflict_under_its_key(m in arb_btreemap()) {
-+                let mut visited = Vec::new();
-+                m.visit_conflicts(&mut |key, conflict| {
-+                    visited.push((format!("{key:?}"), format!("{conflict:?}")));
-+                });
-+                let expected: Vec<_> = m
-+                    .iter()
-+                    .filter_map(|(k, v)| v.as_ref().err().map(|c| (format!("{:?}", Some(k)), format!("{c:?}"))))
++                let visited: std::collections::BTreeMap<_, _> = m.conflicts().collect();
++                let expected: std::collections::BTreeMap<_, _> = m.iter()
++                    .filter_map(|(key, value)| value.as_ref().err().map(|conflict| (key, conflict)))
 +                    .collect();
 +                prop_assert_eq!(visited, expected);
 +            }
@@ crates/concurrent-psbt/src/collections/btreemap.rs: mod tests {
                  m in arb_btreemap()
 
  ## crates/concurrent-psbt/src/collections/hashmap.rs ##
-@@ crates/concurrent-psbt/src/collections/hashmap.rs: use std::collections::HashMap;
+@@
+ use std::collections::HashMap;
  use std::hash::Hash;
  
++use crate::lattice::conflicts::Conflicts;
  use crate::lattice::join::{Join, JoinMut};
 -use crate::lattice::partial::{JoinResult, PartialJoin};
-+use crate::lattice::lift::ResultValue;
++use crate::lattice::lift::{Lift, ResultWrapped};
  
  /// [`JoinMut`] (in-place join) for `HashMap`: matching keys are joined, disjoint keys are unioned.
  impl<K, V> JoinMut for HashMap<K, V>
-@@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<K: Hash + Eq, V> HashMapExt for HashMap<K, V> {
+@@ crates/concurrent-psbt/src/collections/hashmap.rs: where
+     }
+ }
+ 
+-/// Extension trait for transforming `HashMap` values while preserving keys.
+-#[cfg_attr(
+-    not(test),
+-    expect(
+-        dead_code,
+-        reason = "temporary helper is consumed by PSBT set wrappers in later commits"
+-    )
+-)]
+-pub(crate) trait HashMapExt {
+-    type Key;
+-    type Value;
+-    /// Transform each value, preserving keys.
+-    fn map_values<ResultValue>(
+-        self,
+-        f: impl FnMut(Self::Value) -> ResultValue,
+-    ) -> HashMap<Self::Key, ResultValue>;
+-}
++impl<K: Hash + Eq, V: Lift> Lift for HashMap<K, V> {
++    type Result = HashMap<K, V::Result>;
+ 
+-impl<K: Hash + Eq, V> HashMapExt for HashMap<K, V> {
+-    type Key = K;
+-    type Value = V;
+-    fn map_values<ResultValue>(
+-        self,
+-        mut f: impl FnMut(V) -> ResultValue,
+-    ) -> HashMap<K, ResultValue> {
+-        self.into_iter().map(|(k, v)| (k, f(v))).collect()
++    fn wrap(self) -> Self::Result {
++        self.into_iter()
++            .map(|(key, value)| (key, value.wrap()))
++            .collect()
      }
  }
  
@@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<K: Hash + Eq, V> HashMap
 -
 -impl<V: PartialJoin> HashMapResultValue for JoinResult<V> {
 -    type Clean = V;
--
++impl<K, R: Conflicts> Conflicts for HashMap<K, R> {
++    type Item<'a>
++        = (&'a K, R::Item<'a>)
++    where
++        Self: 'a;
+ 
 -    fn is_ok(&self) -> bool {
 -        Result::is_ok(self)
--    }
++    fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>> {
++        self.iter()
++            .flat_map(|(key, value)| value.conflicts().map(move |conflict| (key, conflict)))
+     }
 -
 -    fn try_unwrap(self) -> Result<V, Self> {
 -        match self {
@@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<K: Hash + Eq, V> HashMap
 -    }
 -}
 -
- /// Extension trait for result-domain `HashMap` values.
- #[cfg_attr(
-     not(test),
-@@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<V: PartialJoin> HashMapResultValue for JoinResult<V> {
- )]
- pub(crate) trait ResultHashMapExt: Sized {
-     type Key;
+-/// Extension trait for result-domain `HashMap` values.
+-#[cfg_attr(
+-    not(test),
+-    expect(
+-        dead_code,
+-        reason = "temporary helper is consumed by PSBT set wrappers in later commits"
+-    )
+-)]
+-pub(crate) trait ResultHashMapExt: Sized {
+-    type Key;
 -    type Value: HashMapResultValue;
-+    type Value: ResultValue;
-     /// Returns `true` if every value in the map is conflict-free.
-     fn is_ok(&self) -> bool;
-     /// Extract the plain map, or return `self` if any value is a conflict.
+-    /// Returns `true` if every value in the map is conflict-free.
+-    fn is_ok(&self) -> bool;
+-    /// Extract the plain map, or return `self` if any value is a conflict.
 -    fn try_unwrap(
 -        self,
 -    ) -> Result<HashMap<Self::Key, <Self::Value as HashMapResultValue>::Clean>, Self>;
-+    fn try_unwrap(self) -> Result<HashMap<Self::Key, <Self::Value as ResultValue>::Clean>, Self>;
  }
  
  #[cfg_attr(coverage_nightly, coverage(off))]
 -fn unwrap_after_is_ok<V: HashMapResultValue>(value: V) -> V::Clean {
-+fn unwrap_after_is_ok<V: ResultValue>(value: V) -> V::Clean {
++fn unwrap_after_is_ok<V: ResultWrapped>(value: V) -> V::Clean {
      match value.try_unwrap() {
          Ok(value) => value,
… (truncated)
2: 3a5f624ca5 ! 2: 5088693414 define own Global, Input and Output structs
@@ crates/concurrent-psbt/Cargo.toml: prop-tests = []
  ## crates/concurrent-psbt/src/psbt/global.rs ##
 @@
  #![allow(clippy::result_large_err)]
--#![cfg_attr(
--    not(test),
--    expect(
--        dead_code,
--        reason = "exported once UnorderedPsbt composes the PSBT types"
--    )
 +#![expect(
 +    dead_code,
 +    reason = "exported once UnorderedPsbt composes the PSBT types"
- )]
++)]
  
 -//! PSBT global field merging.
 +//! PSBT global fields and their merging.
@@ crates/concurrent-psbt/src/psbt/global.rs: use bitcoin::bip32::{KeySource, Xpub}
 -        xpubs: BTreeMap<Xpub, KeySource>,
 -        proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
 -        unknowns: BTreeMap<raw::Key, Vec<u8>>,
+-    }
 +        pub tx_version: transaction::Version,
 +        pub fallback_lock_time: Option<absolute::LockTime>,
 +        pub tx_modifiable_flags: u8,
@@ crates/concurrent-psbt/src/psbt/global.rs: use bitcoin::bip32::{KeySource, Xpub}
 +        pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
 +        pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
 +    },
-+}
-+
+ }
+ 
+ record_conflicts! {
+     ResultGlobal, GlobalConflict, GlobalField {
+-    Version => version: Version,
+-    InputCount => input_count: usize,
+-    OutputCount => output_count: usize,
+     TxVersion => tx_version: transaction::Version,
+     FallbackLockTime => fallback_lock_time: absolute::LockTime,
+     TxModifiableFlags => tx_modifiable_flags: u8,
+@@ crates/concurrent-psbt/src/psbt/global.rs: record_conflicts! {
+     }
+ }
+ 
 +impl Default for Global {
 +    fn default() -> Self {
 +        Self::from_v2_fields(psbt_v2::v2::Global::default())
@@ crates/concurrent-psbt/src/psbt/global.rs: use bitcoin::bip32::{KeySource, Xpub}
 +            output_count,
 +            ..psbt_v2::v2::Global::default()
 +        })
-     }
- }
- 
++    }
++}
++
+ #[cfg(test)]
+ #[cfg_attr(coverage_nightly, coverage(off))]
+ mod tests {
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
              assert!(joined.try_unwrap().is_err());
          }
@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
 +        }
 +
          #[test]
-         fn for_each_conflict_reports_the_conflicted_field() {
+         fn conflicts_identify_the_field() {
              let mut a = Global::default();
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
+             a.tx_version = transaction::Version::ONE;
+             b.tx_version = transaction::Version::TWO;
+             let joined = a.wrap().join(b.wrap());
+-            assert_eq!(
+-                joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(),
+-                [GlobalField::TxVersion]
+-            );
++            assert_eq!(joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(), [GlobalField::TxVersion]);
+         }
+     }
+ 
      #[cfg(feature = "prop-tests")]
      mod prop {
          use super::*;
@@ crates/concurrent-psbt/src/psbt/input.rs: use bitcoin::key::{PublicKey, XOnlyPub
 -        tap_merkle_root: Option<TapNodeHash>,
 -        proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
 -        unknowns: BTreeMap<raw::Key, Vec<u8>>,
+-    }
 +        pub previous_txid: Txid,
 +        pub spent_output_index: u32,
 +        pub sequence: Option<Sequence>,
@@ crates/concurrent-psbt/src/psbt/input.rs: use bitcoin::key::{PublicKey, XOnlyPub
 +        pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
 +        pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
 +    },
-+}
-+
+ }
+ 
+ record_conflicts! {
+@@ crates/concurrent-psbt/src/psbt/input.rs: record_conflicts! {
+     }
+ }
+ 
 +impl Input {
 +    /// Create an input spending `outpoint`, with every other field unset.
 +    pub fn new(outpoint: &OutPoint) -> Self {
@@ crates/concurrent-psbt/src/psbt/input.rs: use bitcoin::key::{PublicKey, XOnlyPub
 +    fn from(input: Input) -> Self {
 +        let base = psbt_v2::v2::Input::new(&out_point(&input));
 +        input.encode_v2(base)
-     }
- }
- 
++    }
++}
++
  /// Extract the [`OutPoint`] this input spends (previous txid + output index).
 -#[cfg_attr(
 -    not(all(test, feature = "unit-tests")),
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
  ///
  /// Each field's result-domain type is `<Type as Lift>::Result`, so a field
  /// joins the way its type [`Lift`](crate::lattice::lift::Lift)s: a
-@@
- /// [`JoinResult`](crate::JoinResult), and `Option` and `BTreeMap` by lifting
+ /// [`PartialJoin`](crate::PartialJoin) scalar as a
+-/// [`JoinResult`](crate::JoinResult), and `Option`, `BTreeMap` and `HashMap` by lifting
++/// [`JoinResult`](crate::JoinResult), and `Option` and `BTreeMap` by lifting
  /// their contents. Paths and type aliases resolve like any other type.
  ///
 +/// Each field may carry attributes and a visibility, which apply to the
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 -/// 1. `$Result` struct with the lifted field types
 -/// 2. `$Ext` trait with `wrap` method on the source type
 -/// 3. `Join for $Result`
--/// 4. `$Result::is_ok`, `$Result::for_each_conflict` and `$Result::try_unwrap`
--/// 5. `ResultValue for $Result`
+-/// 4. `$Result::is_ok` and `$Result::try_unwrap`
+-/// 5. `Lift for $Source` and `ResultWrapped for $Result`
 +/// 1. `$Source` struct with the fields as written
 +/// 2. `$Result` struct with the lifted field types
 +/// 3. `$Source::wrap`
 +/// 4. `Join for $Result`
-+/// 5. `$Result::is_ok`, `$Result::for_each_conflict` and `$Result::try_unwrap`
-+/// 6. `ResultValue for $Result`
++/// 5. `$Result::is_ok` and `$Result::try_unwrap`
++/// 6. `ResultWrapped for $Result`
 +///
 +/// Each entry in `fields` mirrors the field of the same name, and type, in the
 +/// `v2` type. The field itself is private: its visibility
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
              )+
          }
  
--        pub trait $Ext {
-+        impl $Source {
-             #[doc = concat!(
-                 "Lift into the result domain as a conflict-free [`",
-                 stringify!($Result),
-                 "`]."
-             )]
--            fn wrap(self) -> $Result;
--        }
+-        pub use $crate::Lift as $Ext;
+-
+-        impl $crate::lattice::lift::Lift for $Source {
+-            type Result = $Result;
 -
--        impl $Ext for $Source {
 -            fn wrap(self) -> $Result {
++        impl $Source {
++            #[doc = concat!(
++                "Lift into the result domain as a conflict-free [`",
++                stringify!($Result),
++                "`]."
++            )]
 +            pub fn wrap(self) -> $Result {
                  $Result {
                      $(
-                         $field: $crate::lattice::lift::Lift::lift(self.$field),
+                         $field: $crate::lattice::lift::Lift::wrap(self.$field),
+@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
+             }
+         }
+ 
++        impl $crate::Lift for $Source {
++            type Result = $Result;
++            fn wrap(self) -> $Result { Self::wrap(self) }
++        }
++
+         impl $crate::lattice::join::Join for $Result {
+             fn join(self, other: Self) -> Self {
+                 $Result {
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
  mod sample {
      use std::collections::BTreeMap;
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 -            scalar: u8,
 -            option: std::option::Option<u8>,
 -            map: BTreeMap<u8, u8>,
+-        }
+-    }
+-    record_conflicts! {
+-        ResultSample, SampleConflict, SampleField {
+-            Scalar => scalar: u8,
+-            Option => option: u8,
+-            Map => map[u8]: u8,
 +            pub scalar: u8,
 +            pub option: std::option::Option<u8>,
 +            pub map: BTreeMap<u8, u8>,
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: mod sample {
 -    use super::sample::{Sample, SampleExt};
 +    use super::sample::Sample;
      use crate::lattice::join::Join;
-     use crate::lattice::lift::ResultValue;
+-    use crate::lattice::lift::ResultWrapped;
++    use crate::lattice::lift::{Lift, ResultWrapped};
  
+     fn sample(scalar: u8, option: u8, value: u8) -> Sample {
+         Sample {
+@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: mod tests {
+     }
+ 
+     #[test]
+-    fn conflicting_fields_retain_typed_paths() {
++    fn conflicting_fields_are_preserved() {
+         let joined = sample(1, 2, 3).wrap().join(sample(4, 5, 6).wrap());
+         assert!(!joined.is_ok());
+-        use super::sample::SampleField;
++        use crate::lattice::conflicts::Conflicts;
++        assert_eq!(joined.scalar.conflicts().count(), 1);
++        assert_eq!(joined.option.conflicts().count(), 1);
+         assert_eq!(
+-            joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(),
+-            [
+-                SampleField::Scalar,
+-                SampleField::Option,
+-                SampleField::Map(&0)
+-            ]
++            joined
++                .map
++                .conflicts()
++                .map(|(key, _)| *key)
++                .collect::<Vec<_>>(),
++            [0]
+         );
+-        use super::sample::SampleConflict;
+-        for (conflict, expected) in joined.conflicts().zip([[1, 4], [2, 5], [3, 6]]) {
+-            match conflict {
+-                SampleConflict::Scalar { values }
+-                | SampleConflict::Option { values }
+-                | SampleConflict::Map { values, .. } => {
+-                    assert_eq!(values.into_iter().copied().collect::<Vec<_>>(), expected);
+-                }
+-            }
+-        }
+         assert_eq!(ResultWrapped::try_unwrap(joined.clone()), Err(joined));
+     }
+ }
 
  ## crates/concurrent-psbt/src/psbt/output.rs ##
 @@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::key::{PublicKey, XOnlyPublicKey};
@@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::key::{PublicKey, XOnlyPu
 -        tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>,
 -        proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
 -        unknowns: BTreeMap<raw::Key, Vec<u8>>,
+-    }
 +        pub amount: Amount,
 +        pub script_pubkey: ScriptBuf,
 +        pub redeem_script: Option<ScriptBuf>,
@@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::key::{PublicKey, XOnlyPu
 +        pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
 +        pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
 +    },
-+}
-+
+ }
+ 
+ record_conflicts! {
+@@ crates/concurrent-psbt/src/psbt/output.rs: record_conflicts! {
+     }
+ }
+ 
 +impl Output {
 +    /// Create an output paying `amount` to `script_pubkey`, with every other
 +    /// field unset.
@@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::key::{PublicKey, XOnlyPu
 +impl From<Output> for psbt_v2::v2::Output {
 +    fn from(output: Output) -> Self {
 +        output.encode_v2(psbt_v2::v2::Output::default())
-     }
- }
- 
++    }
++}
++
+ /// Opaque byte-vector identifier for a PSBT output.
+ ///
+ /// Computed from the `PSBT_OUT_UNIQUE_ID` proprietary field, keyed by subtype
 @@ crates/concurrent-psbt/src/psbt/output.rs: impl std::error::Error for InvalidUniqueId {}
  
  pub const PSBT_OUT_UNIQUE_ID_SUBTYPE: u8 = 0x01;
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
 +                ..output()
              };
              let joined = with_amount(100).wrap().join(with_amount(200).wrap());
-             let mut fields = Vec::new();
-@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
-             assert_eq!(fields, ["amount"]);
+             let fields: Vec<_> = joined.conflicts().map(|c| c.path()).collect();
+             assert_eq!(fields, [OutputField::Amount]);
              assert_eq!(joined.clone().try_unwrap(), Err(joined));
          }
 +
3: 86572d9e5f ! 3: b8f825d24f require a unique ID on every Output
@@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
 +    proprietary: {},
  }
  
- impl Default for Global {
+ record_conflicts! {
 @@ crates/concurrent-psbt/src/psbt/global.rs: impl Default for Global {
  /// Drops the version and the input and output counts.
  impl From<psbt_v2::v2::Global> for Global {
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
 +    proprietary: {},
  }
  
- impl Input {
+ record_conflicts! {
 @@ crates/concurrent-psbt/src/psbt/input.rs: impl Input {
  
  impl From<psbt_v2::v2::Input> for Input {
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
 
  ## crates/concurrent-psbt/src/psbt/mod.rs ##
 @@ crates/concurrent-psbt/src/psbt/mod.rs: mod joinable_struct_macro;
- pub(crate) mod global;
+ pub mod global;
  pub mod input;
  pub mod output;
 +pub(crate) mod proprietary;
@@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
 +    },
  }
  
+ record_conflicts! {
+@@ crates/concurrent-psbt/src/psbt/output.rs: record_conflicts! {
+     TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
+     Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
+     Unknown => unknowns[raw::Key]: Vec<u8>,
++    UniqueId => unique_id: UniqueId,
+     }
+ }
+ 
  impl Output {
 -    /// Create an output paying `amount` to `script_pubkey`, with every other
 -    /// field unset.
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
 +                ..output(1)
              };
              let joined = with_amount(100).wrap().join(with_amount(200).wrap());
-             let mut fields = Vec::new();
+             let fields: Vec<_> = joined.conflicts().map(|c| c.path()).collect();
 @@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
                      },
                      vec![10],
4: 5cf8f49ac9 ! 4: 3bebd68a9b store tap leaf hashes as TapLeafHashes
@@ crates/concurrent-psbt/src/lib.rs: mod psbt;
 +pub use psbt::TapLeafHashes;
  pub use psbt::input;
  pub use psbt::output;
+ 
+
+ ## crates/concurrent-psbt/src/psbt/global.rs ##
+@@
+ #![allow(clippy::result_large_err)]
+-#![expect(
+-    dead_code,
+-    reason = "exported once UnorderedPsbt composes the PSBT types"
++#![cfg_attr(
++    not(test),
++    expect(dead_code, reason = "global serialization is used by UnorderedPsbt")
+ )]
+-
+ //! PSBT global fields and their merging.
+ //!
+ //! [`Global`] holds the global fields of a PSBT, and [`ResultGlobal`] wraps
+@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
+             a.tx_version = transaction::Version::ONE;
+             b.tx_version = transaction::Version::TWO;
+             let joined = a.wrap().join(b.wrap());
+-            assert_eq!(joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(), [GlobalField::TxVersion]);
++            assert_eq!(
++                joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(),
++                [GlobalField::TxVersion]
++            );
+         }
+     }
+ 
+@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
+ 
+             #[test]
+             fn is_ok_consistency(a in arb_result_global()) {
++                prop_assert_eq!(a.conflicts().next().is_none(), a.is_ok());
+                 if a.is_ok() {
+                     prop_assert!(a.try_unwrap().is_ok());
+                 } else {
 
  ## crates/concurrent-psbt/src/psbt/input.rs ##
+@@
+ #![allow(clippy::result_large_err)]
+ 
++//! Per-input field type and input set merging.
++//!
++//! [`ResultInput`] wraps each per-input field in the internal result domain.
++//! [`InputSet`] and [`ResultInputSet`] are sets of inputs identified by the
++//! outpoint each spends. Joining two sets joins the inputs that spend the same
++//! outpoint field by field, and fields that differ become conflicts.
++
+ use std::collections::BTreeMap;
+ 
+ use bitcoin::bip32::KeySource;
 @@ crates/concurrent-psbt/src/psbt/input.rs: use bitcoin::{OutPoint, ScriptBuf, Sequence, Transaction, TxOut, Txid, Witness,
  use psbt_v2::PsbtSighashType;
  use psbt_v2::raw;
@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
          pub tap_internal_key: Option<XOnlyPublicKey>,
          pub tap_merkle_root: Option<TapNodeHash>,
          pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
+@@ crates/concurrent-psbt/src/psbt/input.rs: record_conflicts! {
+     TapKeySig => tap_key_sig: taproot::Signature,
+     TapScriptSig => tap_script_sigs[(XOnlyPublicKey, TapLeafHash)]: taproot::Signature,
+     TapScript => tap_scripts[ControlBlock]: (ScriptBuf, LeafVersion),
+-    TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
++    TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (TapLeafHashes, KeySource),
+     TapInternalKey => tap_internal_key: XOnlyPublicKey,
+     TapMerkleRoot => tap_merkle_root: TapNodeHash,
+     Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
+@@ crates/concurrent-psbt/src/psbt/input.rs: pub(crate) fn out_point(input: &Input) -> OutPoint {
+ 
+ #[cfg(test)]
+ #[cfg_attr(coverage_nightly, coverage(off))]
+-mod tests {
++pub(crate) mod tests {
+     use super::*;
+     use crate::lattice::join::Join;
+ 
+     #[cfg(feature = "unit-tests")]
+-    mod unit {
++    pub(crate) mod unit {
+         use super::*;
+         use bitcoin::bip32::{DerivationPath, Fingerprint};
+         use bitcoin::hashes::Hash;
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+         use bitcoin::sighash::TapSighashType;
+         use std::collections::BTreeMap;
+ 
+-        fn make_input(txid_byte: u8, vout: u32) -> Input {
++        pub(crate) fn make_input(txid_byte: u8, vout: u32) -> Input {
+             let txid = bitcoin::Txid::from_byte_array([txid_byte; 32]);
+             Input::new(&bitcoin::OutPoint { txid, vout })
+         }
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+         #[test]
+         fn inputs_spending_different_outpoints_conflict() {
+             let joined = make_input(1, 0).wrap().join(make_input(2, 0).wrap());
+-            let fields: Vec<_> = joined.conflicts().map(|c| c.path()).collect();
+-            assert_eq!(fields, [InputField::PreviousTxid]);
++            assert_eq!(
++                joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(),
++                [InputField::PreviousTxid]
++            );
+             assert_eq!(joined.clone().try_unwrap(), Err(joined));
+         }
+ 
 @@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
                  tap_key_sig: Some(taproot_signature),
                  tap_script_sigs: BTreeMap::from([((x_only_public_key, leaf), taproot_signature)]),
@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
                  tap_internal_key: Some(x_only_public_key),
                  tap_merkle_root: Some(TapNodeHash::from_byte_array([13; 32])),
                  proprietaries: BTreeMap::from([(
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+             }
+         }
+ 
++        #[test]
++        fn compound_and_proprietary_keydata_identify_conflicts() {
++            let input = populated_input();
++            let mut other = input.clone();
++            let tap_key = *input.tap_script_sigs.keys().next().unwrap();
++            other
++                .tap_script_sigs
++                .get_mut(&tap_key)
++                .unwrap()
++                .sighash_type = TapSighashType::All;
++            let proprietary_key = input.proprietaries.keys().next().unwrap().clone();
++            other
++                .proprietaries
++                .get_mut(&proprietary_key)
++                .unwrap()
++                .push(99);
++            let joined = input.clone().wrap().join(other.wrap());
++            let conflicts: Vec<_> = joined.conflicts().collect();
++            assert_eq!(
++                conflicts.iter().map(|c| c.path()).collect::<Vec<_>>(),
++                [
++                    InputField::TapScriptSig(&tap_key),
++                    InputField::Proprietary(&proprietary_key),
++                ]
++            );
++            let InputConflict::TapScriptSig { key, values } = conflicts[0] else {
++                panic!("taproot signature");
++            };
++            assert_eq!(key, &tap_key);
++            assert_eq!(
++                values
++                    .into_iter()
++                    .map(|signature| signature.sighash_type)
++                    .collect::<Vec<_>>(),
++                [TapSighashType::Default, TapSighashType::All]
++            );
++            let InputConflict::Proprietary { key, values } = conflicts[1] else {
++                panic!("proprietary field");
++            };
++            assert_eq!(key, &proprietary_key);
++            assert_eq!(values.into_iter().next(), input.proprietaries.get(key));
++        }
++
+         #[test]
+         fn v2_conversion_round_trips_a_populated_input() {
+             let input = populated_input();
+@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
+     }
+ 
+     #[cfg(feature = "prop-tests")]
+-    mod prop {
++    pub(crate) mod prop {
+         use super::*;
+         use bitcoin::hashes::Hash;
+         use proptest::prelude::*;
+ 
+-        fn arb_outpoint() -> impl Strategy<Value = OutPoint> {
++        // Small domain for outpoints to ensure collisions
++        pub(crate) fn arb_outpoint() -> impl Strategy<Value = OutPoint> {
+             (0u8..3, 0u32..2).prop_map(|(txid_byte, vout)| OutPoint {
+                 txid: Txid::from_byte_array([txid_byte; 32]),
+                 vout,
+             })
+         }
+ 
+-        fn arb_input() -> impl Strategy<Value = Input> {
+-            (
+-                arb_outpoint(),
+-                proptest::option::of(0u32..8),
+-                proptest::option::of(1u64..10_000),
+-                proptest::option::of(proptest::collection::vec(0u8..255, 0..=8)),
+-                proptest::option::of(proptest::collection::vec(0u8..255, 0..=8)),
+-            )
+-                .prop_map(|(op, seq, utxo_val, redeem, witness)| Input {
+-                    sequence: seq.map(Sequence),
+-                    witness_utxo: utxo_val.map(|v| TxOut {
+-                        value: bitcoin::Amount::from_sat(v),
+-                        script_pubkey: ScriptBuf::new(),
+-                    }),
+-                    redeem_script: redeem.map(ScriptBuf::from_bytes),
+-                    witness_script: witness.map(ScriptBuf::from_bytes),
+-                    ..Input::new(&op)
+-                })
++        pub(crate) fn arb_input() -> impl Strategy<Value = Input> {
++            arb_outpoint().prop_map(|op| Input::new(&op))
+         }
+ 
+-        fn arb_result_input() -> impl Strategy<Value = ResultInput> {
++        /// Wrapped inputs, and joins of two, drawn with optional and map fields
++        /// populated so the join laws exercise every field category.
++        pub(crate) fn arb_result_input() -> impl Strategy<Value = ResultInput> {
+             prop_oneof![
+-                arb_input().prop_map(|i| i.wrap()),
+-                (arb_input(), arb_input()).prop_map(|(a, b)| a.wrap().join(b.wrap())),
++                arb_input_with_fields().prop_map(|i| i.wrap()),
++                (arb_input_with_fields(), arb_input_with_fields())
++                    .prop_map(|(a, b)| a.wrap().join(b.wrap())),
+             ]
+         }
+ 
+-        assert_join_laws!(arb_result_input());
++        // An input with some optional and proprietary fields populated.
++        pub(crate) fn arb_input_with_fields() -> impl Strategy<Value = Input> {
++            (
++                arb_outpoint(),
… (truncated)
5: 25198c9ee7 ! 5: a09dc87596 Introduce keyed set structures for inputs and outputs
@@ Commit message
     also works like a hashmap. These values are joined recursively, so a set
     being frozen only means its identifier set is immutable.
 
+ ## crates/concurrent-psbt/src/lib.rs ##
+@@ crates/concurrent-psbt/src/lib.rs: pub use psbt::output;
+ pub use lattice::conflicts::Conflicts;
+ pub use lattice::lift::{Lift, ResultWrapped};
+ pub use psbt::global;
++
++pub use psbt::conflicts;
+
+ ## crates/concurrent-psbt/src/psbt/conflicts.rs (new) ##
+@@
++//! Borrowed conflicts addressed by PSBT scope, stable entry identity, and field keydata.
++
++use std::collections::HashSet;
++
++use bitcoin::OutPoint;
++
++use super::global::{GlobalConflict, GlobalField};
++use super::input::{InputConflict, InputField};
++use super::output::{OutputConflict, OutputField, UniqueId};
++
++#[derive(Debug, Clone, Copy, PartialEq, Eq)]
++pub enum ConflictPath<'a> {
++    Global(GlobalField<'a>),
++    Input {
++        outpoint: &'a OutPoint,
++        field: InputField<'a>,
++    },
++    Output {
++        id: &'a UniqueId,
++        field: OutputField<'a>,
++    },
++    InputMembership,
++    OutputMembership,
++}
++
++/// A joined member excluded by one of the frozen sets.
++///
++/// Each excluded member is reported once per distinct frozen set that excludes it.
++#[derive(Debug)]
++pub struct MembershipConflict<'a, K> {
++    pub frozen: &'a HashSet<K>,
++    pub unexpected: &'a K,
++}
++
++#[derive(Debug)]
++pub enum PsbtConflict<'a> {
++    Global(GlobalConflict<'a>),
++    Input {
++        outpoint: &'a OutPoint,
++        conflict: InputConflict<'a>,
++    },
++    Output {
++        id: &'a UniqueId,
++        conflict: OutputConflict<'a>,
++    },
++    InputMembership(MembershipConflict<'a, OutPoint>),
++    OutputMembership(MembershipConflict<'a, UniqueId>),
++}
++
++impl<'a> PsbtConflict<'a> {
++    pub fn path(&self) -> ConflictPath<'a> {
++        match self {
++            Self::Global(conflict) => ConflictPath::Global(conflict.path()),
++            Self::Input { outpoint, conflict } => ConflictPath::Input {
++                outpoint,
++                field: conflict.path(),
++            },
++            Self::Output { id, conflict } => ConflictPath::Output {
++                id,
++                field: conflict.path(),
++            },
++            Self::InputMembership(_) => ConflictPath::InputMembership,
++            Self::OutputMembership(_) => ConflictPath::OutputMembership,
++        }
++    }
++}
+
  ## crates/concurrent-psbt/src/psbt/keyed_set.rs (new) ##
 @@
 +//! Keyed sets of PSBT entries, some of which may be frozen.
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +use std::collections::{HashMap, HashSet};
 +use std::hash::Hash;
 +
-+use crate::collections::hashmap::{HashMapExt, ResultHashMapExt};
++use super::conflicts::MembershipConflict;
++use crate::lattice::conflicts::Conflicts;
 +use crate::lattice::join::{Join, JoinMut};
-+use crate::lattice::lift::ResultValue;
++use crate::lattice::lift::{Lift, ResultWrapped};
 +use crate::lattice::partial::JoinResult;
 +
 +/// Set of entries with distinct keys.
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    }
 +}
 +
-+impl<K: Hash + Eq + Clone, V> Freezable<K, V> {
-+    /// Lift into the result domain, wrapping each entry.
-+    pub(crate) fn wrap<W>(self, wrap: impl FnMut(V) -> W) -> ResultKeyedSet<K, W> {
++impl<K: Hash + Eq + Clone, V: Lift> Lift for Freezable<K, V> {
++    type Result = ResultKeyedSet<K, V::Result>;
++
++    fn wrap(self) -> Self::Result {
 +        let frozen = match &self {
 +            Self::Modifiable(_) => Vec::new(),
 +            Self::Frozen(set) => vec![set.0.keys().cloned().collect()],
 +        };
 +        ResultKeyedSet {
-+            entries: KeyedSet(self.into_set().0.map_values(wrap)),
++            entries: KeyedSet(self.into_set().0.wrap()),
 +            frozen,
 +        }
 +    }
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    frozen: Vec<HashSet<K>>,
 +}
 +
++pub(crate) enum SetConflict<'a, K, C> {
++    Membership(MembershipConflict<'a, K>),
++    Entry { key: &'a K, conflict: C },
++}
++
++impl<K: Hash + Eq, R: Conflicts> Conflicts for ResultKeyedSet<K, R> {
++    type Item<'a>
++        = SetConflict<'a, K, R::Item<'a>>
++    where
++        Self: 'a;
++
++    fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>> {
++        let membership = self.frozen.iter().flat_map(|frozen| {
++            self.entries
++                .0
++                .keys()
++                .filter(|key| !frozen.contains(*key))
++                .map(move |unexpected| {
++                    SetConflict::Membership(MembershipConflict { frozen, unexpected })
++                })
++        });
++        membership.chain(
++            self.entries
++                .0
++                .conflicts()
++                .map(|(key, conflict)| SetConflict::Entry { key, conflict }),
++        )
++    }
++}
++
 +// Not derived, since the derive would require `K: Default` and `V: Default`.
 +impl<K, V> Default for ResultKeyedSet<K, V> {
 +    fn default() -> Self {
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    }
 +}
 +
-+impl<K: Hash + Eq, V: ResultValue> ResultKeyedSet<K, V> {
++impl<K: Hash + Eq, V: ResultWrapped> ResultKeyedSet<K, V> {
 +    /// Return `true` if the keys agree with the frozen sets and every entry
 +    /// is conflict-free.
 +    pub(crate) fn is_ok(&self) -> bool {
@@ crates/concurrent-psbt/src/psbt/keyed_set.rs (new)
 +    }
 +}
 +
++impl<K: Hash + Eq, R: ResultWrapped> ResultWrapped for ResultKeyedSet<K, R> {
++    type Clean = Freezable<K, R::Clean>;
… (truncated)
7: 2a7612e4db ! 6: 35910fca22 Introduce InputSet, keyed by outpoint
@@ Commit message
     hashmap keyed by the spent coin's outpoint, so that recursive merging merges
     disjoint field values associated with the same input.
 
- ## crates/concurrent-psbt/src/collections/hashmap.rs ##
-@@ crates/concurrent-psbt/src/collections/hashmap.rs: where
- }
- 
- /// Extension trait for transforming `HashMap` values while preserving keys.
--#[cfg_attr(
--    not(test),
--    expect(
--        dead_code,
--        reason = "temporary helper is consumed by PSBT set wrappers in later commits"
--    )
--)]
- pub(crate) trait HashMapExt {
-     type Key;
-     type Value;
-@@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<K: Hash + Eq, V> HashMapExt for HashMap<K, V> {
- }
- 
- /// Extension trait for result-domain `HashMap` values.
--#[cfg_attr(
--    not(test),
--    expect(
--        dead_code,
--        reason = "temporary helper is consumed by PSBT set wrappers in later commits"
--    )
--)]
- pub(crate) trait ResultHashMapExt: Sized {
-     type Key;
-     type Value: ResultValue;
-
  ## crates/concurrent-psbt/src/psbt/input.rs ##
-@@
- #![allow(clippy::result_large_err)]
- 
-+//! Per-input field type and input set merging.
-+//!
-+//! [`ResultInput`] wraps each per-input field in the internal result domain.
-+//! [`InputSet`] and [`ResultInputSet`] are sets of inputs identified by the
-+//! outpoint each spends. Joining two sets joins the inputs that spend the same
-+//! outpoint field by field, and fields that differ become conflicts.
-+
- use std::collections::BTreeMap;
- 
- use bitcoin::bip32::KeySource;
 @@ crates/concurrent-psbt/src/psbt/input.rs: pub(crate) fn out_point(input: &Input) -> OutPoint {
      }
  }
@@ crates/concurrent-psbt/src/psbt/input.rs: pub(crate) fn out_point(input: &Input)
 +pub use super::input_set::{DuplicateInput, InputSet, ResultInputSet};
  #[cfg(test)]
  #[cfg_attr(coverage_nightly, coverage(off))]
--mod tests {
-+pub(crate) mod tests {
-     use super::*;
-     use crate::lattice::join::Join;
- 
-     #[cfg(feature = "unit-tests")]
--    mod unit {
-+    pub(crate) mod unit {
-         use super::*;
-         use bitcoin::bip32::{DerivationPath, Fingerprint};
-         use bitcoin::hashes::Hash;
-@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
-         use bitcoin::sighash::TapSighashType;
-         use std::collections::BTreeMap;
- 
--        fn make_input(txid_byte: u8, vout: u32) -> Input {
-+        pub(crate) fn make_input(txid_byte: u8, vout: u32) -> Input {
-             let txid = bitcoin::Txid::from_byte_array([txid_byte; 32]);
-             Input::new(&bitcoin::OutPoint { txid, vout })
-         }
-@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
-     }
- 
-     #[cfg(feature = "prop-tests")]
--    mod prop {
-+    pub(crate) mod prop {
-         use super::*;
-         use bitcoin::hashes::Hash;
-         use proptest::prelude::*;
- 
--        fn arb_outpoint() -> impl Strategy<Value = OutPoint> {
-+        // Small domain for outpoints to ensure collisions
-+        pub(crate) fn arb_outpoint() -> impl Strategy<Value = OutPoint> {
-             (0u8..3, 0u32..2).prop_map(|(txid_byte, vout)| OutPoint {
-                 txid: Txid::from_byte_array([txid_byte; 32]),
-                 vout,
-             })
-         }
- 
--        fn arb_input() -> impl Strategy<Value = Input> {
--            (
--                arb_outpoint(),
--                proptest::option::of(0u32..8),
--                proptest::option::of(1u64..10_000),
--                proptest::option::of(proptest::collection::vec(0u8..255, 0..=8)),
--                proptest::option::of(proptest::collection::vec(0u8..255, 0..=8)),
--            )
--                .prop_map(|(op, seq, utxo_val, redeem, witness)| Input {
--                    sequence: seq.map(Sequence),
--                    witness_utxo: utxo_val.map(|v| TxOut {
--                        value: bitcoin::Amount::from_sat(v),
--                        script_pubkey: ScriptBuf::new(),
--                    }),
--                    redeem_script: redeem.map(ScriptBuf::from_bytes),
--                    witness_script: witness.map(ScriptBuf::from_bytes),
--                    ..Input::new(&op)
--                })
-+        pub(crate) fn arb_input() -> impl Strategy<Value = Input> {
-+            arb_outpoint().prop_map(|op| Input::new(&op))
-         }
- 
--        fn arb_result_input() -> impl Strategy<Value = ResultInput> {
-+        /// Wrapped inputs, and joins of two, drawn with optional and map fields
-+        /// populated so the join laws exercise every field category.
-+        pub(crate) fn arb_result_input() -> impl Strategy<Value = ResultInput> {
-             prop_oneof![
--                arb_input().prop_map(|i| i.wrap()),
--                (arb_input(), arb_input()).prop_map(|(a, b)| a.wrap().join(b.wrap())),
-+                arb_input_with_fields().prop_map(|i| i.wrap()),
-+                (arb_input_with_fields(), arb_input_with_fields())
-+                    .prop_map(|(a, b)| a.wrap().join(b.wrap())),
-             ]
-         }
- 
--        assert_join_laws!(arb_result_input());
-+        // An input with some optional and proprietary fields populated.
-+        pub(crate) fn arb_input_with_fields() -> impl Strategy<Value = Input> {
-+            (
-+                arb_outpoint(),
-+                proptest::option::of(0u32..8),      // sequence
-+                proptest::option::of(1u64..10_000), // witness_utxo value (sats)
-+                proptest::option::of(proptest::collection::vec(0u8..255, 0..=8)), // redeem_script
-+                proptest::option::of(proptest::collection::vec(0u8..255, 0..=8)), // witness_script
-+                proptest::option::of(proptest::collection::vec(0u8..255, 0..=8)), // final_script_sig
-+                proptest::collection::btree_map(
-+                    proptest::collection::vec(0u8..255, 1..=4),
-+                    proptest::collection::vec(0u8..255, 0..=4),
-+                    0..=2,
-+                ), // proprietaries
-+            )
-+                .prop_map(
-+                    |(op, seq, utxo_val, redeem, witness_s, final_sig, props)| {
-+                        let mut input = Input {
-+                            sequence: seq.map(Sequence),
-+                            witness_utxo: utxo_val.map(|v| TxOut {
-+                                value: bitcoin::Amount::from_sat(v),
-+                                script_pubkey: ScriptBuf::new(),
-+                            }),
-+                            redeem_script: redeem.map(ScriptBuf::from_bytes),
-+                            witness_script: witness_s.map(ScriptBuf::from_bytes),
-+                            final_script_sig: final_sig.map(ScriptBuf::from_bytes),
-+                            ..Input::new(&op)
-+                        };
-+                        for (k, v) in props {
-+                            input.proprietaries.insert(
-+                                raw::ProprietaryKey {
-+                                    prefix: b"test".to_vec(),
-+                                    subtype: k[0],
-+                                    key: k,
-+                                },
-+                                v,
-+                            );
-+                        }
-+                        input
-+                    },
-+                )
-+        }
+ pub(crate) mod tests {
+@@ crates/concurrent-psbt/src/psbt/input.rs: pub(crate) mod tests {
  
          proptest! {
              #[test]
--            fn wrap_try_unwrap_roundtrip(i in arb_input()) {
+-            fn wrap_try_unwrap_roundtrip(i in prop_oneof![arb_input(), arb_input_with_fields()]) {
 +            fn wrap_try_unwrap_roundtrip(i in arb_input_with_fields()) {
                  prop_assert_eq!(i.clone().wrap().try_unwrap(), Ok(i));
              }
  
-             #[test]
--            fn v2_roundtrip(i in arb_input()) {
-+            fn v2_roundtrip(i in arb_input_with_fields()) {
-                 prop_assert_eq!(Input::from(psbt_v2::v2::Input::from(i.clone())), i);
-             }
- 
-@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
-             fn is_ok_iff_try_unwrap_succeeds(r in arb_result_input()) {
-                 prop_assert_eq!(r.is_ok(), r.try_unwrap().is_ok());
-             }
--
-         }
-+
-+        assert_join_laws!(arb_result_input());
-     }
- }
 
  ## crates/concurrent-psbt/src/psbt/input_set.rs (new) ##
 @@
@@ crates/concurrent-psbt/src/psbt/input_set.rs (new)
 +
 +use bitcoin::OutPoint;
 +
++use super::conflicts::PsbtConflict;
++use super::keyed_set::SetConflict;
++use crate::lattice::conflicts::Conflicts;
 +use crate::lattice::join::Join;
 +use crate::lattice::partial::JoinResult;
++use crate::{Lift, ResultWrapped};
 +
 +use super::input::{Input, ResultInput, out_point};
 +use super::keyed_set::{Freezable, KeyedSet, ResultKeyedSet};
@@ crates/concurrent-psbt/src/psbt/input_set.rs (new)
 +
 +    /// Lift into the result domain as a conflict-free [`ResultInputSet`].
 +    pub fn wrap(self) -> ResultInputSet {
-+        ResultInputSet(self.0.wrap(Input::wrap))
++        ResultInputSet(self.0.wrap())
 +    }
 +
 +    /// Freeze the set, as a PSBT's inputs are once they are no longer
@@ crates/concurrent-psbt/src/psbt/input_set.rs (new)
 +}
 +
 +impl ResultInputSet {
++    /// Borrow membership conflicts and fully addressed entry conflicts.
++    /// Iteration order between entries is unspecified.
++    pub fn conflicts(&self) -> impl Iterator<Item = PsbtConflict<'_>> {
++        self.0.conflicts().map(|conflict| match conflict {
++            SetConflict::Membership(evidence) => PsbtConflict::InputMembership(evidence),
++            SetConflict::Entry { key, conflict } => PsbtConflict::Input {
++                outpoint: key,
++                conflict,
++            },
++        })
++    }
++
 +    /// Return the number of inputs, or the conflicting sizes of the frozen
 +    /// sets and the inputs if they disagree.
 +    pub fn len(&self) -> JoinResult<usize> {
@@ crates/concurrent-psbt/src/psbt/input_set.rs (new)
 +    }
 +}
 +
++impl Lift for InputSet {
++    type Result = ResultInputSet;
++
++    fn wrap(self) -> Self::Result {
++        Self::wrap(self)
++    }
++}
++
++impl ResultWrapped for ResultInputSet {
++    type Clean = InputSet;
++
++    fn is_ok(&self) -> bool {
++        Self::is_ok(self)
++    }
++
++    fn try_unwrap(self) -> Result<Self::Clean, Self> {
++        Self::try_unwrap(self)
++    }
++}
++
++impl Conflicts for ResultInputSet {
++    type Item<'a> = PsbtConflict<'a>;
++
++    fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>> {
++        Self::conflicts(self)
++    }
++}
++
 +#[cfg(test)]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {
@@ crates/concurrent-psbt/src/psbt/input_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(crate) mod global;
+ pub mod global;
  pub mod input;
 +mod input_set;
  #[cfg_attr(
6: 800d3772d5 ! 7: cd20f9d27a introduce OutputSet, keyed by unique output IDs
@@ Commit message
     hashmap keyed by the unique output ID, so that recursive merging merges
     disjoint field values associated with the same output ID.
 
- ## crates/concurrent-psbt/src/collections/hashmap.rs ##
-@@ crates/concurrent-psbt/src/collections/hashmap.rs: where
- }
- 
- /// Extension trait for transforming `HashMap` values while preserving keys.
--#[cfg_attr(
--    not(test),
--    expect(
--        dead_code,
--        reason = "temporary helper is consumed by PSBT set wrappers in later commits"
--    )
--)]
- pub(crate) trait HashMapExt {
-     type Key;
-     type Value;
-@@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<K: Hash + Eq, V> HashMapExt for HashMap<K, V> {
- }
- 
- /// Extension trait for result-domain `HashMap` values.
--#[cfg_attr(
--    not(test),
--    expect(
--        dead_code,
--        reason = "temporary helper is consumed by PSBT set wrappers in later commits"
--    )
--)]
- pub(crate) trait ResultHashMapExt: Sized {
-     type Key;
-     type Value: ResultValue;
-
  ## crates/concurrent-psbt/src/psbt/mod.rs ##
 @@ crates/concurrent-psbt/src/psbt/mod.rs: pub mod input;
  )]
@@ crates/concurrent-psbt/src/psbt/mod.rs: pub mod input;
  mod values;
 
  ## crates/concurrent-psbt/src/psbt/output.rs ##
-@@
- #![allow(clippy::result_large_err)]
- 
-+//! Per-output field type and output set merging.
-+//!
-+//! [`ResultOutput`] wraps each per-output field in the internal result domain.
-+//! [`OutputSet`] and [`ResultOutputSet`] are sets of outputs identified by their
-+//! [`UniqueId`]. Joining two sets joins the outputs that have the same unique ID
-+//! field by field, and fields that differ become conflicts.
-+
- use std::collections::BTreeMap;
- 
- use bitcoin::bip32::KeySource;
-@@ crates/concurrent-psbt/src/psbt/output.rs: impl From<Output> for psbt_v2::v2::Output {
- 
- /// Opaque byte-vector identifier for a PSBT output.
- ///
--/// Computed from the `PSBT_OUT_UNIQUE_ID` proprietary field, keyed by subtype
--/// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Used as the map key in `OutputSet`
--/// so that outputs can be merged in an order-independent way.
-+/// Stored in the `PSBT_OUT_UNIQUE_ID` proprietary field, subtype
-+/// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Identifies an output within an
-+/// [`OutputSet`].
- ///
--/// Built with [`TryFrom`], a unique ID is 1 to [`UniqueId::MAX_LEN`] bytes
--/// long, as is one read from a BIP 370 output. An empty ID would make
--/// unrelated outputs join as one.
-+/// A unique ID built with [`TryFrom`] or read from a BIP 370 output is 1 to
-+/// [`UniqueId::MAX_LEN`] bytes long. An empty ID would make unrelated outputs
-+/// join as one.
- #[derive(Debug, Clone, PartialEq, Eq, Hash)]
- pub struct UniqueId(Vec<u8>);
- 
 @@ crates/concurrent-psbt/src/psbt/output.rs: impl OutputUniqueIdExt for psbt_v2::v2::Output {
      }
  }
@@ crates/concurrent-psbt/src/psbt/output_set.rs (new)
 @@
 +//! Output sets keyed by unique output ID, in plain and result domains.
 +
++use super::conflicts::PsbtConflict;
++use super::keyed_set::SetConflict;
++use crate::lattice::conflicts::Conflicts;
 +use crate::lattice::join::Join;
 +use crate::lattice::partial::JoinResult;
++use crate::{Lift, ResultWrapped};
 +
 +use super::keyed_set::{Freezable, KeyedSet, ResultKeyedSet};
 +use super::output::{Output, ResultOutput, UniqueId};
@@ crates/concurrent-psbt/src/psbt/output_set.rs (new)
 +    }
 +
 +    pub fn wrap(self) -> ResultOutputSet {
-+        ResultOutputSet(self.0.wrap(Output::wrap))
++        ResultOutputSet(self.0.wrap())
 +    }
 +
 +    /// Freeze the set, as a PSBT's outputs are once they are no longer
@@ crates/concurrent-psbt/src/psbt/output_set.rs (new)
 +}
 +
 +impl ResultOutputSet {
++    /// Borrow membership conflicts and fully addressed entry conflicts.
++    /// Iteration order between entries is unspecified.
++    pub fn conflicts(&self) -> impl Iterator<Item = PsbtConflict<'_>> {
++        self.0.conflicts().map(|conflict| match conflict {
++            SetConflict::Membership(evidence) => PsbtConflict::OutputMembership(evidence),
++            SetConflict::Entry { key, conflict } => PsbtConflict::Output { id: key, conflict },
++        })
++    }
++
 +    /// Return the number of outputs, or the conflicting sizes of the frozen
 +    /// sets and the outputs if they disagree.
 +    pub fn len(&self) -> JoinResult<usize> {
@@ crates/concurrent-psbt/src/psbt/output_set.rs (new)
 +    }
 +}
 +
++impl Lift for OutputSet {
++    type Result = ResultOutputSet;
++
++    fn wrap(self) -> Self::Result {
++        Self::wrap(self)
++    }
++}
++
++impl ResultWrapped for ResultOutputSet {
++    type Clean = OutputSet;
++
++    fn is_ok(&self) -> bool {
++        Self::is_ok(self)
++    }
++
++    fn try_unwrap(self) -> Result<Self::Clean, Self> {
++        Self::try_unwrap(self)
++    }
++}
++
++impl Conflicts for ResultOutputSet {
++    type Item<'a> = PsbtConflict<'a>;
++
++    fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>> {
++        Self::conflicts(self)
++    }
++}
++
 +#[cfg(test)]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {

@github-actions

Copy link
Copy Markdown
range-diff for force push 7fe9c87e5c → 5fa5b95986 November 16, 2026 04:30 UTC: 7 modified; 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..7fe9c87 3e0c224..5fa5b95

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

1:  b72b43e9b8 +499 -635 16f ! 1:  26f6320adb +551 -635 17f Lift PSBT fields recursively and retain typed conflict paths
2:  5088693414 +491 -182  6f ! 2:  9c8648af95 +560 -268  8f define own Global, Input and Output structs
3:  b8f825d24f +285  -89  6f ! 3:  1d4c70d008 +285  -89  6f require a unique ID on every Output
4:  3bebd68a9b +374 -157  8f ! 4:  13974295ec +366 -154  8f store tap leaf hashes as TapLeafHashes
5:  a09dc87596 +725   -0  4f ! 5:  bbeaafa8bf +981   -0  5f Introduce keyed set structures for inputs and outputs
6:  35910fca22 +315   -1  3f ! 6:  a587eaa8de +447   -2  4f Introduce InputSet, keyed by outpoint
7:  cd20f9d27a +329   -0  3f ! 7:  935a180af6 +453   -2  4f introduce OutputSet, keyed by unique output IDs
1: b72b43e9b8 ! 1: 26f6320adb Lift PSBT fields recursively and retain typed conflict paths
@@ crates/concurrent-psbt/src/lattice/conflicts.rs (new)
 @@
 +use super::partial::{Conflict, JoinResult, PartialJoin};
 +
-+/// Borrow conflicts without erasing their values or enclosing map keys.
++/// Iterates over conflicts in a value.
++/// Maps pair each item from their values' iterators with its key.
 +pub trait Conflicts {
 +    type Item<'a>
 +    where
@@ crates/concurrent-psbt/src/lattice/conflicts.rs (new)
 
  ## crates/concurrent-psbt/src/lattice/lift.rs (new) ##
 @@
-+//! Moving between clean values and their result-domain counterparts.
++//! The [`Lift`] trait's [`wrap`](Lift::wrap) method lifts an arbitrary value into the Result-domain,
++//! where wrapped values can be [`Join::join`]ed, with incompatible values creating
++//! conflicts instead of failing. [`ResultWrapped::try_unwrap`] lowers back to the value
++//! domain once it has no conflicts. [`conflicts`](crate::Conflicts::conflicts) allows enumeration
++//! of the conflicts in a Result domain value that cannot be lowered back to the value
++//! domain.
 +//!
-+//! A clean value [`Lift`]s into a result-domain value whose joins record
-+//! conflicts instead of failing. A [`ResultWrapped`] lowers back to the clean
-+//! value once it has no conflicts, and conflict iterators expose the conflicts it does have.
-+//!
-+//! The counterpart is chosen by type: a [`PartialJoin`] scalar lifts into a
-+//! [`JoinResult`], and `Option`, `BTreeMap` and `HashMap` lift their contents (see
-+//! [`crate::collections`]).
++//! Value types implementing [`PartialJoin`] lift into a [`JoinResult`].
++//! Collections, i.e. `Option`, `BTreeMap` and `HashMap` lift their value types
++//! recursively (see [`crate::collections`]).
 +
 +use crate::lattice::join::Join;
 +use crate::lattice::partial::{JoinResult, PartialJoin};
@@ crates/concurrent-psbt/src/lib.rs: pub use lattice::join::{Join, JoinMut};
 
  ## crates/concurrent-psbt/src/psbt/conflict_macro.rs (new) ##
 @@
++//! Generates typed conflict enums for the external PSBT types.
++//!
++//! Temporary until `joinable_struct!` defines the source structs and generates
++//! their conflict API from the same field list.
++
 +macro_rules! record_conflicts {
 +    (
 +        $Result:ident, $Conflict:ident, $Field:ident {
@@ crates/concurrent-psbt/src/psbt/global.rs
  use bitcoin::bip32::{KeySource, Xpub};
  use bitcoin::locktime::absolute;
  use bitcoin::transaction;
-@@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
-     }
- }
  
-+record_conflicts! {
-+    ResultGlobal, GlobalConflict, GlobalField {
-+    Version => version: Version,
-+    InputCount => input_count: usize,
-+    OutputCount => output_count: usize,
-+    TxVersion => tx_version: transaction::Version,
-+    FallbackLockTime => fallback_lock_time: absolute::LockTime,
-+    TxModifiableFlags => tx_modifiable_flags: u8,
-+    Xpub => xpubs[Xpub]: KeySource,
-+    Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
-+    Unknown => unknowns[raw::Key]: Vec<u8>,
-+    }
-+}
-+
- #[cfg(test)]
- #[cfg_attr(coverage_nightly, coverage(off))]
- mod tests {
+ use psbt_v2::Version;
+ use psbt_v2::raw;
+-use psbt_v2::v2::Global;
++pub use psbt_v2::v2::Global;
+ 
+ joinable_struct! {
+     /// Result-domain wrapper around a BIP 370 [`Global`].
+@@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
+     /// [`ResultGlobal::try_unwrap`] to extract.
+     source: Global,
+     result: ResultGlobal,
++    conflicts: GlobalConflict, GlobalField {
++        Version => version: Version,
++        InputCount => input_count: usize,
++        OutputCount => output_count: usize,
++        TxVersion => tx_version: transaction::Version,
++        FallbackLockTime => fallback_lock_time: absolute::LockTime,
++        TxModifiableFlags => tx_modifiable_flags: u8,
++        Xpub => xpubs[Xpub]: KeySource,
++        Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
++        Unknown => unknowns[raw::Key]: Vec<u8>,
++    },
+     ext: GlobalExt,
+     fields: {
+         version: Version,
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
          }
  
@@ crates/concurrent-psbt/src/psbt/input.rs
  use bitcoin::hashes::{hash160, ripemd160, sha256, sha256d};
  use bitcoin::key::{PublicKey, XOnlyPublicKey};
 @@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
-     }
- }
+     /// [`ResultInput::try_unwrap`] to recover the clean value once all conflicts are resolved.
+     source: Input,
+     result: ResultInput,
++    conflicts: InputConflict, InputField {
++        PreviousTxid => previous_txid: Txid,
++        SpentOutputIndex => spent_output_index: u32,
++        Sequence => sequence: Sequence,
++        MinTime => min_time: absolute::Time,
++        MinHeight => min_height: absolute::Height,
++        NonWitnessUtxo => non_witness_utxo: Transaction,
++        WitnessUtxo => witness_utxo: TxOut,
++        PartialSig => partial_sigs[PublicKey]: ecdsa::Signature,
++        SighashType => sighash_type: PsbtSighashType,
++        RedeemScript => redeem_script: ScriptBuf,
++        WitnessScript => witness_script: ScriptBuf,
++        Bip32Derivation => bip32_derivations[PublicKey]: KeySource,
++        FinalScriptSig => final_script_sig: ScriptBuf,
++        FinalScriptWitness => final_script_witness: Witness,
++        Ripemd160Preimage => ripemd160_preimages[ripemd160::Hash]: Vec<u8>,
++        Sha256Preimage => sha256_preimages[sha256::Hash]: Vec<u8>,
++        Hash160Preimage => hash160_preimages[hash160::Hash]: Vec<u8>,
++        Hash256Preimage => hash256_preimages[sha256d::Hash]: Vec<u8>,
++        TapKeySig => tap_key_sig: taproot::Signature,
++        TapScriptSig => tap_script_sigs[(XOnlyPublicKey, TapLeafHash)]: taproot::Signature,
++        TapScript => tap_scripts[ControlBlock]: (ScriptBuf, LeafVersion),
++        TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
++        TapInternalKey => tap_internal_key: XOnlyPublicKey,
++        TapMerkleRoot => tap_merkle_root: TapNodeHash,
++        Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
++        Unknown => unknowns[raw::Key]: Vec<u8>,
++    },
+     ext: InputExt,
+     fields: {
+         previous_txid: Txid,
+@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
  
-+record_conflicts! {
-+    ResultInput, InputConflict, InputField {
-+    PreviousTxid => previous_txid: Txid,
-+    SpentOutputIndex => spent_output_index: u32,
-+    Sequence => sequence: Sequence,
-+    MinTime => min_time: absolute::Time,
-+    MinHeight => min_height: absolute::Height,
-+    NonWitnessUtxo => non_witness_utxo: Transaction,
-+    WitnessUtxo => witness_utxo: TxOut,
-+    PartialSig => partial_sigs[PublicKey]: ecdsa::Signature,
-+    SighashType => sighash_type: PsbtSighashType,
-+    RedeemScript => redeem_script: ScriptBuf,
-+    WitnessScript => witness_script: ScriptBuf,
-+    Bip32Derivation => bip32_derivations[PublicKey]: KeySource,
-+    FinalScriptSig => final_script_sig: ScriptBuf,
-+    FinalScriptWitness => final_script_witness: Witness,
-+    Ripemd160Preimage => ripemd160_preimages[ripemd160::Hash]: Vec<u8>,
-+    Sha256Preimage => sha256_preimages[sha256::Hash]: Vec<u8>,
-+    Hash160Preimage => hash160_preimages[hash160::Hash]: Vec<u8>,
-+    Hash256Preimage => hash256_preimages[sha256d::Hash]: Vec<u8>,
-+    TapKeySig => tap_key_sig: taproot::Signature,
-+    TapScriptSig => tap_script_sigs[(XOnlyPublicKey, TapLeafHash)]: taproot::Signature,
-+    TapScript => tap_scripts[ControlBlock]: (ScriptBuf, LeafVersion),
-+    TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
-+    TapInternalKey => tap_internal_key: XOnlyPublicKey,
-+    TapMerkleRoot => tap_merkle_root: TapNodeHash,
-+    Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
-+    Unknown => unknowns[raw::Key]: Vec<u8>,
-+    }
-+}
-+
  /// Extract the [`OutPoint`] this input spends (previous txid + output index).
  #[cfg_attr(
 -    not(test),
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
          $(#[$result_meta:meta])*
          source: $Source:ident,
          result: $Result:ident,
++        conflicts: $Conflict:ident, $Field:ident { $($conflict_fields:tt)* },
          ext: $Ext:ident,
 -        fields: { $($fields:tt)* }
 -    ) => {
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 -    (@wrap map $self:ident . $field:ident) => {
 -        $crate::collections::btreemap::BTreeMapExt::wrap($self.$field)
 -    };
--
+ 
 -    // --- is_ok rules ---
++        record_conflicts! {
++            $Result, $Conflict, $Field { $($conflict_fields)* }
++        }
  
 -    (@is_ok scalar $self:ident . $field:ident) => {
 -        $self.$field.is_ok()
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +        /// Result-domain form of [`Sample`].
          source: Sample,
          result: ResultSample,
++        conflicts: SampleConflict, SampleField {
++            Scalar => scalar: u8,
++            Option => option: u8,
++            Map => map[u8]: u8,
++        },
          ext: SampleExt,
          fields: {
              scalar: u8,
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
              map: BTreeMap<u8, u8>,
          }
      }
-+    record_conflicts! {
-+        ResultSample, SampleConflict, SampleField {
-+            Scalar => scalar: u8,
-+            Option => option: u8,
-+            Map => map[u8]: u8,
-+        }
-+    }
 +}
 +
 +#[cfg(all(test, feature = "unit-tests"))]
@@ crates/concurrent-psbt/src/psbt/output.rs
  use bitcoin::key::{PublicKey, XOnlyPublicKey};
  use bitcoin::taproot::{TapLeafHash, TapTree};
 @@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
-     }
- }
- 
-+record_conflicts! {
-+    ResultOutput, OutputConflict, OutputField {
-+    Amount => amount: Amount,
-+    ScriptPubkey => script_pubkey: ScriptBuf,
-+    RedeemScript => redeem_script: ScriptBuf,
-+    WitnessScript => witness_script: ScriptBuf,
-+    Bip32Derivation => bip32_derivations[PublicKey]: KeySource,
-+    TapInternalKey => tap_internal_key: XOnlyPublicKey,
-+    TapTree => tap_tree: TapTree,
-+    TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
-+    Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
-+    Unknown => unknowns[raw::Key]: Vec<u8>,
-+    }
-+}
-+
- /// Opaque byte-vector identifier for a PSBT output.
- ///
- /// Computed from the `PSBT_OUT_UNIQUE_ID` proprietary field, keyed by subtype
+     /// or an accumulated conflict.
+     source: Output,
+     result: ResultOutput,
++    conflicts: OutputConflict, OutputField {
++        Amount => amount: Amount,
++        ScriptPubkey => script_pubkey: ScriptBuf,
++        RedeemScript => redeem_script: ScriptBuf,
++        WitnessScript => witness_script: ScriptBuf,
++        Bip32Derivation => bip32_derivations[PublicKey]: KeySource,
++        TapInternalKey => tap_internal_key: XOnlyPublicKey,
++        TapTree => tap_tree: TapTree,
++        TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
++        Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
++        Unknown => unknowns[raw::Key]: Vec<u8>,
++    },
+     ext: OutputExt,
+     fields: {
+         amount: Amount,
 @@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
      #[cfg(feature = "unit-tests")]
      mod unit {
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
 -        fn try_unwrap_conflicting_returns_err() {
 -            let a = Output {
 -                amount: bitcoin::Amount::from_sat(100),
--                ..Output::default()
--            };
--            let b = Output {
--                amount: bitcoin::Amount::from_sat(200),
 +        fn outputs_with_different_amounts_conflict() {
 +            let with_amount = |sats| Output {
 +                amount: Amount::from_sat(sats),
                  ..Output::default()
              };
+-            let b = Output {
+-                amount: bitcoin::Amount::from_sat(200),
+-                ..Output::default()
+-            };
 -            assert!(a.wrap().join(b.wrap()).try_unwrap().is_err());
 -        }
 -
@@ crates/concurrent-psbt/src/values.rs: mod tests {
          use crate::lattice::join::Join;
          use proptest::prelude::*;
  
+
+ ## crates/concurrent-psbt/tests/record_conflicts.rs (new) ##
+@@
++#![cfg(feature = "prop-tests")]
++#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
++
++#[cfg_attr(coverage_nightly, coverage(off))]
++mod properties {
++    use std::collections::{BTreeMap, HashMap};
++
++    use bitcoin::transaction;
++    use concurrent_psbt::global::{Global, GlobalField};
++    use concurrent_psbt::{Conflicts, Join, Lift, ResultWrapped};
++    use proptest::prelude::*;
++    use psbt_v2::raw;
++
++    fn convert<T>(global: psbt_v2::v2::Global) -> T
++    where
++        T: TryFrom<psbt_v2::v2::Global>,
++        T::Error: std::fmt::Debug,
++    {
++        T::try_from(global).unwrap()
++    }
++
++    proptest! {
++        #[test]
++        fn nested_record_conflicts_keep_keys_and_field_paths(
++            left_version in 1i32..4, right_version in 1i32..4,
++            left_value in any::<u8>(), right_value in any::<u8>(),
++            outer_key in any::<u8>(), keydata in proptest::collection::vec(any::<u8>(), 0..8),
++        ) {
++            let key = raw::Key { type_value: 0x80, key: keydata };
++            let global = |version, value| convert::<Global>(psbt_v2::v2::Global {
++                tx_version: transaction::Version(version),
++                unknowns: BTreeMap::from([(key.clone(), vec![value])]),
++                ..Default::default()
++            });
++            let left = HashMap::from([(outer_key, Some(global(left_version, left_value)))]);
++            let right = HashMap::from([(outer_key, Some(global(right_version, right_value)))]);
++            let joined = left.wrap().join(right.wrap());
++            let mut paths = Vec::new();
++            for (found_key, conflict) in Conflicts::conflicts(&joined) {
++                prop_assert_eq!(found_key, &outer_key);
++                paths.push(conflict.path());
++            }
++            let mut expected = Vec::new();
++            if left_version != right_version { expected.push(GlobalField::TxVersion); }
++            if left_value != right_value { expected.push(GlobalField::Unknown(&key)); }
++            prop_assert_eq!(&paths, &expected);
++            prop_assert_eq!(ResultWrapped::is_ok(&joined), expected.is_empty());
++            prop_assert_eq!(ResultWrapped::try_unwrap(joined).is_ok(), expected.is_empty());
++        }
++    }
++}
2: 5088693414 ! 2: 9c8648af95 define own Global, Input and Output structs
@@ crates/concurrent-psbt/Cargo.toml: prop-tests = []
  rand = "0.9"
  
 
+ ## crates/concurrent-psbt/src/psbt/conflict_macro.rs (deleted) ##
+@@
+-//! Generates typed conflict enums for the external PSBT types.
+-//!
+-//! Temporary until `joinable_struct!` defines the source structs and generates
+-//! their conflict API from the same field list.
+-
+-macro_rules! record_conflicts {
+-    (
+-        $Result:ident, $Conflict:ident, $Field:ident {
+-            $( $Variant:ident => $field:ident $( [ $Key:ty ] )? : $Value:ty ),+ $(,)?
+-        }
+-    ) => {
+-        #[derive(Debug, Clone, Copy, PartialEq, Eq)]
+-        pub enum $Field<'a> {
+-            $( $Variant $( (&'a $Key) )?, )+
+-        }
+-
+-        #[derive(Debug, Clone, Copy)]
+-        pub enum $Conflict<'a> {
+-            $( $Variant { $( key: &'a $Key, )? values: &'a $crate::Conflict<$Value> }, )+
+-        }
+-
+-        impl<'a> $Conflict<'a> {
+-            pub fn path(&self) -> $Field<'a> {
+-                match self {
+-                    $( Self::$Variant { $( key: record_conflicts!(@key $Key, key), )? .. } => {
+-                        record_conflicts!(@path $Field $Variant key $( [ $Key ] )?)
+-                    }, )+
+-                }
+-            }
+-        }
+-
+-        impl $Result {
+-            /// Borrow each conflicted field, retaining its keydata and value type.
+-            pub fn conflicts(&self) -> impl Iterator<Item = $Conflict<'_>> {
+-                // Exhaustive destructuring requires a mapping for every field.
+-                let Self { $( $field, )+ } = self;
+-                std::iter::empty()
+-                    $( .chain($crate::lattice::conflicts::Conflicts::conflicts($field)
+-                        .map(record_conflicts!(@item $Conflict $Variant $( [ $Key ] )?))) )+
+-            }
+-        }
+-
+-        impl $crate::lattice::conflicts::Conflicts for $Result {
+-            type Item<'a> = $Conflict<'a>;
+-
+-            fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>> {
+-                Self::conflicts(self)
+-            }
+-        }
+-    };
+-    (@key $Key:ty, $key:ident) => { $key };
+-    (@path $Field:ident $Variant:ident $key:ident [ $Key:ty ]) => { $Field::$Variant(*$key) };
+-    (@path $Field:ident $Variant:ident $key:ident) => { $Field::$Variant };
+-    (@item $Conflict:ident $Variant:ident [ $Key:ty ]) => {
+-        |(key, values)| $Conflict::$Variant { key, values }
+-    };
+-    (@item $Conflict:ident $Variant:ident) => {
+-        |values| $Conflict::$Variant { values }
+-    };
+-}
+
  ## crates/concurrent-psbt/src/psbt/global.rs ##
 @@
  #![allow(clippy::result_large_err)]
-+#![expect(
-+    dead_code,
-+    reason = "exported once UnorderedPsbt composes the PSBT types"
++#![cfg_attr(
++    not(test),
++    expect(dead_code, reason = "global serialization is used by UnorderedPsbt")
 +)]
  
 -//! PSBT global field merging.
@@ crates/concurrent-psbt/src/psbt/global.rs: use bitcoin::bip32::{KeySource, Xpub}
  
 -use psbt_v2::Version;
  use psbt_v2::raw;
--use psbt_v2::v2::Global;
+-pub use psbt_v2::v2::Global;
  
  joinable_struct! {
 -    /// Result-domain wrapper around a BIP 370 [`Global`].
@@ crates/concurrent-psbt/src/psbt/global.rs: use bitcoin::bip32::{KeySource, Xpub}
      /// [`ResultGlobal::try_unwrap`] to extract.
 -    source: Global,
      result: ResultGlobal,
+-    conflicts: GlobalConflict, GlobalField {
+-        Version => version: Version,
+-        InputCount => input_count: usize,
+-        OutputCount => output_count: usize,
+-        TxVersion => tx_version: transaction::Version,
+-        FallbackLockTime => fallback_lock_time: absolute::LockTime,
+-        TxModifiableFlags => tx_modifiable_flags: u8,
+-        Xpub => xpubs[Xpub]: KeySource,
+-        Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
+-        Unknown => unknowns[raw::Key]: Vec<u8>,
+-    },
 -    ext: GlobalExt,
++    conflicts: GlobalConflict, GlobalField,
 +    v2: psbt_v2::v2::Global,
      fields: {
 -        version: Version,
@@ crates/concurrent-psbt/src/psbt/global.rs: use bitcoin::bip32::{KeySource, Xpub}
 -        xpubs: BTreeMap<Xpub, KeySource>,
 -        proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
 -        unknowns: BTreeMap<raw::Key, Vec<u8>>,
--    }
-+        pub tx_version: transaction::Version,
-+        pub fallback_lock_time: Option<absolute::LockTime>,
-+        pub tx_modifiable_flags: u8,
-+        pub xpubs: BTreeMap<Xpub, KeySource>,
-+        pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
-+        pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
++        tx_version: transaction::Version => TxVersion,
++        fallback_lock_time: Option<absolute::LockTime> => FallbackLockTime(absolute::LockTime),
++        tx_modifiable_flags: u8 => TxModifiableFlags,
++        xpubs: BTreeMap<Xpub, KeySource> => Xpub[Xpub](KeySource),
++        proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>> => Proprietary[raw::ProprietaryKey](Vec<u8>),
++        unknowns: BTreeMap<raw::Key, Vec<u8>> => Unknown[raw::Key](Vec<u8>),
 +    },
- }
- 
- record_conflicts! {
-     ResultGlobal, GlobalConflict, GlobalField {
--    Version => version: Version,
--    InputCount => input_count: usize,
--    OutputCount => output_count: usize,
-     TxVersion => tx_version: transaction::Version,
-     FallbackLockTime => fallback_lock_time: absolute::LockTime,
-     TxModifiableFlags => tx_modifiable_flags: u8,
-@@ crates/concurrent-psbt/src/psbt/global.rs: record_conflicts! {
-     }
- }
- 
++}
++
 +impl Default for Global {
 +    fn default() -> Self {
 +        Self::from_v2_fields(psbt_v2::v2::Global::default())
@@ crates/concurrent-psbt/src/psbt/global.rs: record_conflicts! {
 +            output_count,
 +            ..psbt_v2::v2::Global::default()
 +        })
-+    }
-+}
-+
- #[cfg(test)]
- #[cfg_attr(coverage_nightly, coverage(off))]
- mod tests {
+     }
+ }
+ 
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
              assert!(joined.try_unwrap().is_err());
          }
… (truncated)
3: b8f825d24f ! 3: 1d4c70d008 require a unique ID on every Output
@@ Commit message
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
 @@ crates/concurrent-psbt/src/psbt/global.rs: joinable_struct! {
-         pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
-         pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
+         proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>> => Proprietary[raw::ProprietaryKey](Vec<u8>),
+         unknowns: BTreeMap<raw::Key, Vec<u8>> => Unknown[raw::Key](Vec<u8>),
      },
 +    proprietary: {},
  }
  
- record_conflicts! {
+ impl Default for Global {
 @@ crates/concurrent-psbt/src/psbt/global.rs: impl Default for Global {
  /// Drops the version and the input and output counts.
  impl From<psbt_v2::v2::Global> for 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: joinable_struct! {
-         pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
-         pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
+         proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>> => Proprietary[raw::ProprietaryKey](Vec<u8>),
+         unknowns: BTreeMap<raw::Key, Vec<u8>> => Unknown[raw::Key](Vec<u8>),
      },
 +    proprietary: {},
  }
  
- record_conflicts! {
+ impl Input {
 @@ crates/concurrent-psbt/src/psbt/input.rs: impl Input {
  
  impl From<psbt_v2::v2::Input> for Input {
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
  macro_rules! joinable_struct {
      (
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
-                 $(#[$field_meta:meta])* $vis:vis
                  $field:ident : $T:ty
+                 => $Variant:ident $( [ $Key:ty ] )? $( ( $Value:ty ) )?
              ),+ $(,)?
 +        },
 +        proprietary: {
 +            $(
 +                $(#[$proprietary_meta:meta])* $proprietary_vis:vis
 +                $proprietary:ident : $P:ty = $Codec:ty
++                => $ProprietaryVariant:ident $( [ $ProprietaryKey:ty ] )? $( ( $ProprietaryValue:ty ) )?
 +            ),* $(,)?
          } $(,)?
      ) => {
          joinable_struct! {
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
-             result: $Result,
+             conflicts: $Conflict, $Field,
              fields: {
-                 $( $(#[$field_meta])* $field: $T, )+
-+                $( $(#[$proprietary_meta])* $proprietary_vis $proprietary: $P, )*
+                 $( $(#[$field_meta])* $field: $T => $Variant $( [ $Key ] )? $( ( $Value ) )?, )+
++                $( $(#[$proprietary_meta])* $proprietary_vis $proprietary: $P => $ProprietaryVariant $( [ $ProprietaryKey ] )? $( ( $ProprietaryValue ) )?, )*
              }
          }
  
@@ crates/concurrent-psbt/src/psbt/output.rs: use bitcoin::taproot::{TapLeafHash, T
      /// Result-domain counterpart of [`Output`].
      ///
 @@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
-         pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
-         pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
+         proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>> => Proprietary[raw::ProprietaryKey](Vec<u8>),
+         unknowns: BTreeMap<raw::Key, Vec<u8>> => Unknown[raw::Key](Vec<u8>),
      },
 +    proprietary: {
-+        unique_id: UniqueId = UniqueIdField,
++        unique_id: UniqueId = UniqueIdField => UniqueId,
 +    },
  }
  
- record_conflicts! {
-@@ crates/concurrent-psbt/src/psbt/output.rs: record_conflicts! {
-     TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
-     Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
-     Unknown => unknowns[raw::Key]: Vec<u8>,
-+    UniqueId => unique_id: UniqueId,
-     }
- }
- 
  impl Output {
 -    /// Create an output paying `amount` to `script_pubkey`, with every other
 -    /// field unset.
4: 3bebd68a9b ! 4: 13974295ec store tap leaf hashes as TapLeafHashes
@@ crates/concurrent-psbt/src/lib.rs: mod psbt;
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
 @@
- #![allow(clippy::result_large_err)]
--#![expect(
--    dead_code,
--    reason = "exported once UnorderedPsbt composes the PSBT types"
-+#![cfg_attr(
-+    not(test),
-+    expect(dead_code, reason = "global serialization is used by UnorderedPsbt")
+     not(test),
+     expect(dead_code, reason = "global serialization is used by UnorderedPsbt")
  )]
 -
  //! PSBT global fields and their merging.
  //!
  //! [`Global`] holds the global fields of a PSBT, and [`ResultGlobal`] wraps
-@@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
-             a.tx_version = transaction::Version::ONE;
-             b.tx_version = transaction::Version::TWO;
-             let joined = a.wrap().join(b.wrap());
--            assert_eq!(joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(), [GlobalField::TxVersion]);
-+            assert_eq!(
-+                joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(),
-+                [GlobalField::TxVersion]
-+            );
-         }
-     }
- 
 @@ crates/concurrent-psbt/src/psbt/global.rs: mod tests {
  
              #[test]
@@ crates/concurrent-psbt/src/psbt/input.rs
 +//! Per-input field type and input set merging.
 +//!
 +//! [`ResultInput`] wraps each per-input field in the internal result domain.
-+//! [`InputSet`] and [`ResultInputSet`] are sets of inputs identified by the
++//! `InputSet` and `ResultInputSet` are sets of inputs identified by the
 +//! outpoint each spends. Joining two sets joins the inputs that spend the same
 +//! outpoint field by field, and fields that differ become conflicts.
 +
@@ crates/concurrent-psbt/src/psbt/input.rs: use bitcoin::{OutPoint, ScriptBuf, Seq
      /// A PSBT input, mirroring the BIP 370 per-input map.
      source: Input,
 @@ 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, (Vec<TapLeafHash>, 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>>,
-@@ crates/concurrent-psbt/src/psbt/input.rs: record_conflicts! {
-     TapKeySig => tap_key_sig: taproot::Signature,
-     TapScriptSig => tap_script_sigs[(XOnlyPublicKey, TapLeafHash)]: taproot::Signature,
-     TapScript => tap_scripts[ControlBlock]: (ScriptBuf, LeafVersion),
--    TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
-+    TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (TapLeafHashes, KeySource),
-     TapInternalKey => tap_internal_key: XOnlyPublicKey,
-     TapMerkleRoot => tap_merkle_root: TapNodeHash,
-     Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
+         tap_key_sig: Option<taproot::Signature> => TapKeySig(taproot::Signature),
+         tap_script_sigs: BTreeMap<(XOnlyPublicKey, TapLeafHash), taproot::Signature> => TapScriptSig[(XOnlyPublicKey, TapLeafHash)](taproot::Signature),
+         tap_scripts: BTreeMap<ControlBlock, (ScriptBuf, LeafVersion)> => TapScript[ControlBlock]((ScriptBuf, LeafVersion)),
+-        tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)> => TapKeyOrigin[XOnlyPublicKey]((Vec<TapLeafHash>, KeySource)),
++        tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins => TapKeyOrigin[XOnlyPublicKey]((TapLeafHashes, KeySource)),
+         tap_internal_key: Option<XOnlyPublicKey> => TapInternalKey(XOnlyPublicKey),
+         tap_merkle_root: Option<TapNodeHash> => TapMerkleRoot(TapNodeHash),
+         proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>> => Proprietary[raw::ProprietaryKey](Vec<u8>),
 @@ crates/concurrent-psbt/src/psbt/input.rs: pub(crate) fn out_point(input: &Input) -> OutPoint {
  
  #[cfg(test)]
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 +/// [`JoinResult`](crate::JoinResult), and `Option`, `BTreeMap` and `HashMap` by lifting
  /// their contents. Paths and type aliases resolve like any other type.
  ///
- /// Each field may carry attributes and a visibility, which apply to the
+ /// Mirrored fields are private, with public getters and setters by default.
 @@
  /// 3. `$Source::wrap`
  /// 4. `Join for $Result`
  /// 5. `$Result::is_ok` and `$Result::try_unwrap`
 -/// 6. `ResultWrapped for $Result`
 +/// 6. `Lift for $Source` and `ResultWrapped for $Result`
++/// 7. Typed conflict paths and `Conflicts for $Result`
  ///
 -/// Each entry in `fields` mirrors the field of the same name, and type, in the
 -/// `v2` type. The field itself is private: its visibility
+-/// applies to a getter of the same name and a `set_` setter, so the
+-/// representation can change, and invariants can be added, without breaking
+-/// callers. Each entry in `proprietary` is written
 +/// 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. The field itself is private: its visibility
- /// applies to a getter of the same name and a `set_` setter, so the
- /// representation can change, and invariants can be added, without breaking
- /// callers. Each entry in `proprietary` is written
++/// 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:
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
-         fields: {
              $(
-                 $(#[$field_meta:meta])* $vis:vis
+                 $(#[$field_meta:meta])*
+                 $( [accessors($accessor_vis:vis)] )?
 -                $field:ident : $T:ty
 +                $field:ident : $T:ty $( = $Conversion:ty )?
+                 => $Variant:ident $( [ $Key:ty ] )? $( ( $Value:ty ) )?
              ),+ $(,)?
          },
-         proprietary: {
 @@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
              /// The mirrored fields of `v2`, with these proprietary fields.
              fn from_v2_fields(v2: $V2, $( $proprietary: $P ),*) -> Self {
@@ crates/concurrent-psbt/src/psbt/output.rs
 +//! Per-output field type and output set merging.
 +//!
 +//! [`ResultOutput`] wraps each per-output field in the internal result domain.
-+//! [`OutputSet`] and [`ResultOutputSet`] are sets of outputs identified by their
++//! `OutputSet` and `ResultOutputSet` are sets of outputs identified by their
 +//! [`UniqueId`]. Joining two sets joins the outputs that have the same unique ID
 +//! field by field, and fields that differ become conflicts.
 +
@@ crates/concurrent-psbt/src/psbt/output.rs
  joinable_struct! {
      /// A PSBT output, mirroring the BIP 370 per-output map, identified by its
 @@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
-         pub bip32_derivations: BTreeMap<PublicKey, KeySource>,
-         pub tap_internal_key: Option<XOnlyPublicKey>,
-         pub tap_tree: Option<TapTree>,
--        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>,
-+        pub tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins,
-         pub proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>>,
-         pub unknowns: BTreeMap<raw::Key, Vec<u8>>,
+         bip32_derivations: BTreeMap<PublicKey, KeySource> => Bip32Derivation[PublicKey](KeySource),
+         tap_internal_key: Option<XOnlyPublicKey> => TapInternalKey(XOnlyPublicKey),
+         tap_tree: Option<TapTree> => TapTree(TapTree),
+-        tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)> => TapKeyOrigin[XOnlyPublicKey]((Vec<TapLeafHash>, KeySource)),
++        tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins => TapKeyOrigin[XOnlyPublicKey]((TapLeafHashes, KeySource)),
+         proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>> => Proprietary[raw::ProprietaryKey](Vec<u8>),
+         unknowns: BTreeMap<raw::Key, Vec<u8>> => Unknown[raw::Key](Vec<u8>),
      },
-@@ crates/concurrent-psbt/src/psbt/output.rs: record_conflicts! {
-     Bip32Derivation => bip32_derivations[PublicKey]: KeySource,
-     TapInternalKey => tap_internal_key: XOnlyPublicKey,
-     TapTree => tap_tree: TapTree,
--    TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (Vec<TapLeafHash>, KeySource),
-+    TapKeyOrigin => tap_key_origins[XOnlyPublicKey]: (TapLeafHashes, KeySource),
-     Proprietary => proprietaries[raw::ProprietaryKey]: Vec<u8>,
-     Unknown => unknowns[raw::Key]: Vec<u8>,
-     UniqueId => unique_id: UniqueId,
 @@ crates/concurrent-psbt/src/psbt/output.rs: impl From<Output> for psbt_v2::v2::Output {
  
  /// Opaque byte-vector identifier for a PSBT output.
@@ crates/concurrent-psbt/src/psbt/output.rs: impl From<Output> for psbt_v2::v2::Ou
 -/// so that outputs can be merged in an order-independent way.
 +/// Stored in the `PSBT_OUT_UNIQUE_ID` proprietary field, subtype
 +/// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Identifies an output within an
-+/// [`OutputSet`].
++/// `OutputSet`.
  ///
 -/// Built with [`TryFrom`], a unique ID is 1 to [`UniqueId::MAX_LEN`] bytes
 -/// long, as is one read from a BIP 370 output. An empty ID would make
5: a09dc87596 ! 5: bbeaafa8bf 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 ##
-@@ crates/concurrent-psbt/src/psbt/mod.rs: mod conflict_macro;
+@@
  mod joinable_struct_macro;
  pub mod global;
  pub mod input;
@@ crates/concurrent-psbt/src/psbt/mod.rs: mod conflict_macro;
  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);
++            }
++        }
++    }
++}
6: 35910fca22 ! 6: a587eaa8de Introduce InputSet, keyed by outpoint
@@ Commit message
     disjoint field values associated with the same input.
 
  ## crates/concurrent-psbt/src/psbt/input.rs ##
+@@
+ //! Per-input field type and input set merging.
+ //!
+ //! [`ResultInput`] wraps each per-input field in the internal result domain.
+-//! `InputSet` and `ResultInputSet` are sets of inputs identified by the
++//! [`InputSet`] and [`ResultInputSet`] are sets of inputs identified by the
+ //! outpoint each spends. Joining two sets joins the inputs that spend the same
+ //! outpoint field by field, and fields that differ become conflicts.
+ 
 @@ crates/concurrent-psbt/src/psbt/input.rs: pub(crate) fn out_point(input: &Input) -> OutPoint {
      }
  }
@@ crates/concurrent-psbt/src/psbt/input_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;
@@ crates/concurrent-psbt/src/psbt/mod.rs: mod conflict_macro;
  #[cfg_attr(
      not(test),
      expect(
+
+ ## crates/concurrent-psbt/tests/input_conflicts.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 std::collections::{HashMap, HashSet};
++
++    use bitcoin::hashes::Hash;
++    use bitcoin::{OutPoint, Sequence, Txid};
++    use concurrent_psbt::conflicts::{ConflictPath, PsbtConflict};
++    use concurrent_psbt::input::{Input, InputConflict, InputField, InputSet};
++    use concurrent_psbt::{Conflicts, Join, Lift, ResultWrapped};
++
++    fn input(outpoint: &OutPoint, sequence: u32) -> Input {
++        let mut input = Input::new(outpoint);
++        input.set_sequence(Some(Sequence(sequence)));
++        input
++    }
++
++    // Exercise clean joins, field conflicts, membership conflicts, and both
++    // together. Each case also runs through the public generic trait surface.
++    fn check_input_set_contract(tag: u8, sequence: u32, outer_key: u8) {
++        let common = OutPoint {
++            txid: Txid::from_byte_array([tag; 32]),
++            vout: 0,
++        };
++        let extra = OutPoint { vout: 1, ..common };
++        for frozen in [false, true] {
++            for field_conflict in [false, true] {
++                let other_sequence = if field_conflict {
++                    sequence.wrapping_add(1)
++                } else {
++                    sequence
++                };
++                let left = InputSet::try_from_inputs([input(&common, sequence)]).unwrap();
++                let left = if frozen { left.freeze() } else { left };
++                let right = InputSet::try_from_inputs([
++                    input(&common, other_sequence),
++                    input(&extra, sequence),
++                ])
++                .unwrap();
++                let joined = Lift::wrap(left.clone()).join(Lift::wrap(right.clone()));
++                let expected_ok = !frozen && !field_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);
++
++                let mut membership_count = 0;
++                let mut field_count = 0;
++                let mut paths = Vec::new();
++                for conflict in Conflicts::conflicts(&joined) {
++                    let path = conflict.path();
++                    paths.push(path);
++                    match conflict {
++                        PsbtConflict::InputMembership(evidence) => {
++                            membership_count += 1;
++                            assert_eq!(path, ConflictPath::InputMembership);
++                            assert_eq!(evidence.unexpected, &extra);
++                            assert_eq!(evidence.frozen, &HashSet::from([common]));
++                        }
++                        PsbtConflict::Input {
++                            outpoint,
++                            conflict: InputConflict::Sequence { values },
++                        } => {
++                            field_count += 1;
++                            assert_eq!(outpoint, &common);
++                            assert_eq!(
++                                path,
++                                ConflictPath::Input {
++                                    outpoint: &common,
++                                    field: InputField::Sequence,
++                                }
++                            );
++                            assert_eq!(
++                                values.into_iter().copied().collect::<Vec<_>>(),
++                                [Sequence(sequence), Sequence(other_sequence)]
++                            );
++                        }
++                        other => panic!("unexpected input-set conflict: {other:?}"),
++                    }
++                }
++                assert_eq!(membership_count, usize::from(frozen));
++                assert_eq!(field_count, usize::from(field_conflict));
++
++                let nested = HashMap::from([(outer_key, Some(left))])
++                    .wrap()
++                    .join(HashMap::from([(outer_key, Some(right.clone()))]).wrap());
++                let nested_paths: Vec<_> = Conflicts::conflicts(&nested)
++                    .map(|(key, conflict)| {
++                        assert_eq!(key, &outer_key);
++                        conflict.path()
++                    })
++                    .collect();
++                assert_eq!(nested_paths.len(), paths.len());
++                assert!(paths.iter().all(|path| nested_paths.contains(path)));
++                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 input_set_traits_preserve_membership_and_field_conflicts() {
++        check_input_set_contract(7, 42, 9);
++    }
++
++    #[cfg(feature = "prop-tests")]
++    mod properties {
++        use super::*;
++        use proptest::prelude::*;
++
++        proptest! {
++            #[test]
++            fn input_set_traits_preserve_every_conflict(
++                tag in any::<u8>(), sequence in any::<u32>(), outer_key in any::<u8>(),
++            ) {
++                check_input_set_contract(tag, sequence, outer_key);
++            }
++        }
++    }
++}
7: cd20f9d27a ! 7: 935a180af6 introduce OutputSet, keyed by unique output IDs
@@ crates/concurrent-psbt/src/psbt/mod.rs: pub mod input;
  mod values;
 
  ## crates/concurrent-psbt/src/psbt/output.rs ##
+@@
+ //! Per-output field type and output set merging.
+ //!
+ //! [`ResultOutput`] wraps each per-output field in the internal result domain.
+-//! `OutputSet` and `ResultOutputSet` are sets of outputs identified by their
++//! [`OutputSet`] and [`ResultOutputSet`] are sets of outputs identified by their
+ //! [`UniqueId`]. Joining two sets joins the outputs that have the same unique ID
+ //! field by field, and fields that differ become conflicts.
+ 
+@@ crates/concurrent-psbt/src/psbt/output.rs: impl From<Output> for psbt_v2::v2::Output {
+ ///
+ /// Stored in the `PSBT_OUT_UNIQUE_ID` proprietary field, subtype
+ /// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Identifies an output within an
+-/// `OutputSet`.
++/// [`OutputSet`].
+ ///
+ /// A unique ID built with [`TryFrom`] or read from a BIP 370 output is 1 to
+ /// [`UniqueId::MAX_LEN`] bytes long. An empty ID would make unrelated outputs
 @@ crates/concurrent-psbt/src/psbt/output.rs: impl OutputUniqueIdExt for psbt_v2::v2::Output {
      }
  }
@@ crates/concurrent-psbt/src/psbt/output_set.rs (new)
 +        }
 +    }
 +}
+
+ ## crates/concurrent-psbt/tests/output_conflicts.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 std::collections::{HashMap, HashSet};
++
++    use bitcoin::{Amount, ScriptBuf};
++    use concurrent_psbt::conflicts::{ConflictPath, PsbtConflict};
++    use concurrent_psbt::output::{Output, OutputConflict, OutputField, OutputSet, UniqueId};
++    use concurrent_psbt::{Conflicts, Join, Lift, ResultWrapped};
++
++    fn output(id: &UniqueId, sats: u64) -> Output {
++        Output::new(id.clone(), Amount::from_sat(sats), ScriptBuf::new())
++    }
++
++    // A fixed ID joins field-by-field, while a second ID tests frozen-set
++    // evidence independently of the amount disagreement at the first ID.
++    fn check_output_set_contract(tag: u8, sats: u64, outer_key: u8) {
++        let common = UniqueId::try_from(vec![tag, 0]).unwrap();
++        let extra = UniqueId::try_from(vec![tag, 1]).unwrap();
++        for frozen in [false, true] {
++            for field_conflict in [false, true] {
++                let other_sats = if field_conflict { sats + 1 } else { sats };
++                let left = OutputSet::try_from_outputs([output(&common, sats)]).unwrap();
++                let left = if frozen { left.freeze() } else { left };
++                let right = OutputSet::try_from_outputs([
++                    output(&common, other_sats),
++                    output(&extra, sats),
++                ])
++                .unwrap();
++                let joined = Lift::wrap(left.clone()).join(Lift::wrap(right.clone()));
++                let expected_ok = !frozen && !field_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);
++
++                let mut membership_count = 0;
++                let mut field_count = 0;
++                let mut paths = Vec::new();
++                for conflict in Conflicts::conflicts(&joined) {
++                    let path = conflict.path();
++                    paths.push(path);
++                    match conflict {
++                        PsbtConflict::OutputMembership(evidence) => {
++                            membership_count += 1;
++                            assert_eq!(path, ConflictPath::OutputMembership);
++                            assert_eq!(evidence.unexpected, &extra);
++                            assert_eq!(evidence.frozen, &HashSet::from([common.clone()]));
++                        }
++                        PsbtConflict::Output {
++                            id,
++                            conflict: OutputConflict::Amount { values },
++                        } => {
++                            field_count += 1;
++                            assert_eq!(id, &common);
++                            assert_eq!(
++                                path,
++                                ConflictPath::Output {
++                                    id: &common,
++                                    field: OutputField::Amount,
++                                }
++                            );
++                            assert_eq!(
++                                values.into_iter().copied().collect::<Vec<_>>(),
++                                [Amount::from_sat(sats), Amount::from_sat(other_sats)]
++                            );
++                        }
++                        other => panic!("unexpected output-set conflict: {other:?}"),
++                    }
++                }
++                assert_eq!(membership_count, usize::from(frozen));
++                assert_eq!(field_count, usize::from(field_conflict));
++
++                let nested = HashMap::from([(outer_key, Some(left))])
++                    .wrap()
++                    .join(HashMap::from([(outer_key, Some(right.clone()))]).wrap());
++                let nested_paths: Vec<_> = Conflicts::conflicts(&nested)
++                    .map(|(key, conflict)| {
++                        assert_eq!(key, &outer_key);
++                        conflict.path()
++                    })
++                    .collect();
++                assert_eq!(nested_paths.len(), paths.len());
++                assert!(paths.iter().all(|path| nested_paths.contains(path)));
++                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 output_set_traits_preserve_membership_and_field_conflicts() {
++        check_output_set_contract(7, 42, 9);
++    }
++
++    #[cfg(feature = "prop-tests")]
++    mod properties {
++        use super::*;
++        use proptest::prelude::*;
++
++        proptest! {
++            #[test]
++            fn output_set_traits_preserve_every_conflict(
++                tag in any::<u8>(), sats in 0u64..=2_100_000_000_000_000,
++                outer_key in any::<u8>(),
++            ) {
++                check_output_set_contract(tag, sats, outer_key);
++            }
++        }
++    }
++}

nothingmuch and others added 4 commits November 16, 2026 04:49
Choose each field's result type through Lift, so aliases and qualified
Option, BTreeMap, and HashMap types behave like their underlying types.
Generated PSBT records can themselves be wrapped inside these containers.

Lift::wrap pairs with ResultWrapped::try_unwrap. Failed extraction retains
the complete wrapped container, including its clean entries.

Compose borrowed Conflicts iterators without erasing map keys or value
types. Record conflict enums identify the field and any keydata, replacing
the Debug-based callback visitor.

Suggested-by: Codex
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
joinable_struct! generates both a plain struct and its result-domain
counterpart, so Global, Input and Output are this crate's types. wrap is
an inherent method, which replaces the GlobalExt, InputExt and OutputExt
traits.

The macro takes the psbt_v2 type and the field list. Each field mirrors
the psbt_v2 field of the same name, so the macro generates the
conversions: from_v2_fields moves the mirrored fields out of a psbt_v2
value, and encode_v2 moves them into one, keeping the psbt_v2 fields
that this crate does not mirror. From converts each type from psbt_v2
and back. Global has no PSBT version or input and output counts, so
Global::into_v2 takes the counts as arguments and sets the version to 2.

The fields are private. A public field cannot enforce an invariant that
the type system does not encode, and cannot be made private again
without breaking callers. The macro generates a getter of the same name
and a `set_` setter with the field's declared visibility, using pastey
to name the setters. OutputUniqueIdExt still reads and writes the unique
ID of an Output.

closes #104

Suggested-by: Codex
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
UniqueId becomes a required and immutable field of Output. Output::new
takes it, and TryFrom<psbt_v2::v2::Output> reads it from
PSBT_OUT_UNIQUE_ID. An output without one, or with an empty or overlong
one, is rejected: an empty ID would make unrelated outputs join as one.
This replaces OutputUniqueIdExt.

joinable_struct! takes the field in a new `proprietary` list. Each entry
names a ProprietaryField codec, which defines the field's key subtype
and encoding, so changing the key later does not change the field's type
or join. The macro decodes the proprietary fields in order, removing
their keys, and encodes them back.

closes #89

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Check compound and proprietary keydata in conflict paths, and exercise
optional and map fields in the owned PSBT join and conversion properties.
@github-actions

Copy link
Copy Markdown
range-diff for force push 5fa5b95986 → e4f34a0d4a November 16, 2026 06:06 UTC: 4 modified, 3 unchanged; 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..5fa5b95 3e0c224..e4f34a0

1:  26f6320adb +551 -635 17f ! 1:  0e4597c7b1 +584 -661 18f Lift PSBT fields recursively and retain typed conflict paths
2:  9c8648af95 +560 -268  8f = 2:  aca5c18ed5 +560 -268  8f define own Global, Input and Output structs
3:  1d4c70d008 +285  -89  6f = 3:  5d7cad32fd +285  -89  6f require a unique ID on every Output
4:  13974295ec +366 -154  8f ! 4:  8c2e1d8f34 +149  -56  4f store tap leaf hashes as TapLeafHashes
5:  bbeaafa8bf +981   -0  5f ! 5:  1aa57fc30c +981   -0  5f Introduce keyed set structures for inputs and outputs
6:  a587eaa8de +447   -2  4f = 6:  b97cb9cfc6 +447   -2  4f Introduce InputSet, keyed by outpoint
7:  935a180af6 +453   -2  4f ! 7:  79f823da84 +453   -2  4f introduce OutputSet, keyed by unique output IDs
1: 26f6320adb ! 1: 0e4597c7b1 Lift PSBT fields recursively and retain typed conflict paths
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
  
          }
 
+ ## crates/concurrent-psbt/src/psbt/values.rs ##
+@@
+ //! [`IdempotentValue`](crate::values::IdempotentValue) implementations for
+ //! bitcoin and psbt-v2 types used as PSBT fields.
+ 
+-use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
+ use crate::values::IdempotentValue;
+ 
+ impl IdempotentValue for bitcoin::absolute::Height {}
+@@ crates/concurrent-psbt/src/psbt/values.rs: impl IdempotentValue for psbt_v2::Version {}
+ 
+ impl IdempotentValue for (bitcoin::ScriptBuf, bitcoin::taproot::LeafVersion) {}
+ 
+-/// BIP 371 taproot BIP 32 derivation values: `(Vec<TapLeafHash>, KeySource)`.
+-///
+-/// The leaf-hash list is the set of tap leaves the key participates in; BIP 371
+-/// imposes no ordering on it, so join equality is order-insensitive: two values
+-/// join iff the key sources match and the leaf lists are equal as multisets.
+-/// `self`'s representation (its leaf order) is kept on `Ok`.
+-impl PartialJoin for (Vec<bitcoin::TapLeafHash>, bitcoin::bip32::KeySource) {
+-    fn try_join(self, other: Self) -> JoinResult<Self> {
+-        fn sorted(leaves: &[bitcoin::TapLeafHash]) -> Vec<bitcoin::TapLeafHash> {
+-            let mut copy = leaves.to_vec();
+-            copy.sort_unstable();
+-            copy
+-        }
+-
+-        if self.1 == other.1 && sorted(&self.0) == sorted(&other.0) {
+-            Ok(self)
+-        } else {
+-            Err(Conflict::from_values([self, other]))
+-        }
+-    }
+-}
++impl IdempotentValue for (Vec<bitcoin::TapLeafHash>, bitcoin::bip32::KeySource) {}
+ 
+ #[cfg(test)]
+ #[cfg_attr(coverage_nightly, coverage(off))]
+@@ crates/concurrent-psbt/src/psbt/values.rs: mod tests {
+         }
+ 
+         #[test]
+-        fn reordered_tap_leaf_hashes_join_ok() {
++        fn reordered_tap_leaf_hashes_conflict() {
+             let a = (vec![leaf(1), leaf(2)], key_source());
+             let b = (vec![leaf(2), leaf(1)], key_source());
+-            // Same leaves as a multiset: joins Ok, keeping self's representation.
+-            assert_eq!(a.clone().try_join(b), Ok(a));
++            assert_eq!(
++                a.clone().try_join(b.clone()),
++                Err(Conflict::from_values([a, b]))
++            );
+         }
+ 
+         #[test]
+@@ crates/concurrent-psbt/src/psbt/values.rs: mod tests {
+         use bitcoin::hashes::Hash;
+         use proptest::prelude::*;
+ 
+-        use crate::lattice::partial::PartialJoin;
++        use crate::lattice::partial::{Conflict, PartialJoin};
+ 
+         fn key_source(byte: u8) -> KeySource {
+             (Fingerprint::from([byte; 4]), DerivationPath::master())
+@@ crates/concurrent-psbt/src/psbt/values.rs: mod tests {
+         }
+ 
+         proptest! {
++            #[test]
++            fn tap_key_origins_use_structural_equality(
++                a in proptest::collection::vec(0u8..3, 0..5),
++                b in proptest::collection::vec(0u8..3, 0..5),
++                source_a in 0u8..2,
++                source_b in 0u8..2,
++            ) {
++                let a = (leaves(&a), key_source(source_a));
++                let b = (leaves(&b), key_source(source_b));
++                prop_assert_eq!(a.clone().try_join(a.clone()), Ok(a.clone()));
++                let expected = if a == b {
++                    Ok(a.clone())
++                } else {
++                    Err(Conflict::from_values([a.clone(), b.clone()]))
++                };
++                prop_assert_eq!(a.try_join(b), expected);
++            }
++
++            #[test]
++            fn repeated_tap_leaf_hashes_conflict(bytes in proptest::collection::vec(any::<u8>(), 1..8)) {
++                let a = (leaves(&bytes), key_source(0));
++                let mut b = a.clone();
++                b.0.push(b.0[0]);
++                prop_assert_eq!(a.clone().try_join(b.clone()), Err(Conflict::from_values([a, b])));
++            }
++
+             #[test]
+             fn different_key_sources_conflict(bytes in proptest::collection::vec(any::<u8>(), 0..8)) {
+                 let a = (leaves(&bytes), key_source(0));
+
  ## crates/concurrent-psbt/src/values.rs ##
 @@ crates/concurrent-psbt/src/values.rs: mod tests {
      #[cfg(feature = "prop-tests")]
4: 13974295ec ! 4: 8c2e1d8f34 store tap leaf hashes as TapLeafHashes
@@ Metadata
 Author: Yuval Kogman <nothingmuch@woobling.org>
 
  ## Commit message ##
-    store tap leaf hashes as TapLeafHashes
+    Exercise owned PSBT conflict paths and conversions
 
-    tap_key_origins stores each key's leaf hashes as TapLeafHashes, whose
-    equality ignores order and repetition: BIP 371 gives the list no order.
-    This replaces the custom join on (Vec<TapLeafHash>, KeySource), which
-    compared the lists as multisets. TapLeafHashes joins as an
-    IdempotentValue, so joining equal values keeps the left one's list.
-
-    A mirrored field's type may now differ from the psbt_v2 field's: an `=`
-    after the type names a MirroredField that converts between them.
-    tap_key_origins uses TapKeyOrigins to convert each key's leaf hashes.
-
-    supersedes #76
-
-    Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
-
- ## crates/concurrent-psbt/src/lib.rs ##
-@@ crates/concurrent-psbt/src/lib.rs: mod psbt;
- 
- pub use lattice::join::{Join, JoinMut};
- pub use lattice::partial::{Conflict, JoinResult, PartialJoin};
-+pub use psbt::TapLeafHashes;
- pub use psbt::input;
- pub use psbt::output;
- 
+    Check compound and proprietary keydata in conflict paths, and exercise
+    optional and map fields in the owned PSBT join and conversion properties.
 
  ## crates/concurrent-psbt/src/psbt/global.rs ##
 @@
@@ crates/concurrent-psbt/src/psbt/input.rs
  use std::collections::BTreeMap;
  
  use bitcoin::bip32::KeySource;
-@@ 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::{TapKeyOrigins, TapLeafHashes};
-+
- joinable_struct! {
-     /// A PSBT input, mirroring the BIP 370 per-input map.
-     source: Input,
-@@ crates/concurrent-psbt/src/psbt/input.rs: joinable_struct! {
-         tap_key_sig: Option<taproot::Signature> => TapKeySig(taproot::Signature),
-         tap_script_sigs: BTreeMap<(XOnlyPublicKey, TapLeafHash), taproot::Signature> => TapScriptSig[(XOnlyPublicKey, TapLeafHash)](taproot::Signature),
-         tap_scripts: BTreeMap<ControlBlock, (ScriptBuf, LeafVersion)> => TapScript[ControlBlock]((ScriptBuf, LeafVersion)),
--        tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)> => TapKeyOrigin[XOnlyPublicKey]((Vec<TapLeafHash>, KeySource)),
-+        tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins => TapKeyOrigin[XOnlyPublicKey]((TapLeafHashes, KeySource)),
-         tap_internal_key: Option<XOnlyPublicKey> => TapInternalKey(XOnlyPublicKey),
-         tap_merkle_root: Option<TapNodeHash> => TapMerkleRoot(TapNodeHash),
-         proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>> => Proprietary[raw::ProprietaryKey](Vec<u8>),
 @@ crates/concurrent-psbt/src/psbt/input.rs: pub(crate) fn out_point(input: &Input) -> OutPoint {
  
  #[cfg(test)]
@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
              assert_eq!(joined.clone().try_unwrap(), Err(joined));
          }
  
-@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
-                 tap_key_sig: Some(taproot_signature),
-                 tap_script_sigs: BTreeMap::from([((x_only_public_key, leaf), taproot_signature)]),
-                 tap_scripts: BTreeMap::from([(control_block, (script, LeafVersion::TapScript))]),
--                tap_key_origins: BTreeMap::from([(x_only_public_key, (vec![leaf], source))]),
-+                tap_key_origins: BTreeMap::from([(
-+                    x_only_public_key,
-+                    (TapLeafHashes::from(vec![leaf]), source),
-+                )]),
-                 tap_internal_key: Some(x_only_public_key),
-                 tap_merkle_root: Some(TapNodeHash::from_byte_array([13; 32])),
-                 proprietaries: BTreeMap::from([(
 @@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
              }
          }
@@ crates/concurrent-psbt/src/psbt/input.rs: mod tests {
 
  ## 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.
- ///
  /// Each field's result-domain type is `<Type as Lift>::Result`, so a field
  /// joins the way its type [`Lift`](crate::lattice::lift::Lift)s: a
  /// [`PartialJoin`](crate::PartialJoin) scalar as a
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
 -/// representation can change, and invariants can be added, without breaking
 -/// callers. Each entry in `proprietary` is written
 +/// 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
++/// 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:
-@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
-             $(
-                 $(#[$field_meta:meta])*
-                 $( [accessors($accessor_vis:vis)] )?
--                $field:ident : $T:ty
-+                $field:ident : $T:ty $( = $Conversion:ty )?
-                 => $Variant:ident $( [ $Key:ty ] )? $( ( $Value:ty ) )?
-             ),+ $(,)?
-         },
-@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
-             /// 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: macro_rules! joinable_struct {
-             /// 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: macro_rules! joinable_struct {
-         }
-     };
- 
-+    (@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/joinable_struct_macro.rs: macro_rules! joinable_struct {
                  "`]."
              )]
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
              fn join(self, other: Self) -> Self {
                  $Result {
 
- ## crates/concurrent-psbt/src/psbt/mod.rs ##
-@@ crates/concurrent-psbt/src/psbt/mod.rs: pub mod global;
- pub mod input;
- pub mod output;
- pub(crate) mod proprietary;
-+mod tap_leaf_hashes;
- mod values;
-+
-+pub use tap_leaf_hashes::TapLeafHashes;
-
  ## crates/concurrent-psbt/src/psbt/output.rs ##
 @@
  #![allow(clippy::result_large_err)]
@@ crates/concurrent-psbt/src/psbt/output.rs
  use bitcoin::bip32::KeySource;
  use bitcoin::key::{PublicKey, XOnlyPublicKey};
 -use bitcoin::taproot::{TapLeafHash, TapTree};
+-use bitcoin::{Amount, ScriptBuf};
 +use bitcoin::taproot::TapTree;
- use bitcoin::{Amount, ScriptBuf};
++use bitcoin::{Amount, ScriptBuf, TapLeafHash};
  use psbt_v2::raw;
  
  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
-@@ crates/concurrent-psbt/src/psbt/output.rs: joinable_struct! {
-         bip32_derivations: BTreeMap<PublicKey, KeySource> => Bip32Derivation[PublicKey](KeySource),
-         tap_internal_key: Option<XOnlyPublicKey> => TapInternalKey(XOnlyPublicKey),
-         tap_tree: Option<TapTree> => TapTree(TapTree),
--        tap_key_origins: BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)> => TapKeyOrigin[XOnlyPublicKey]((Vec<TapLeafHash>, KeySource)),
-+        tap_key_origins: BTreeMap<XOnlyPublicKey, (TapLeafHashes, KeySource)> = TapKeyOrigins => TapKeyOrigin[XOnlyPublicKey]((TapLeafHashes, KeySource)),
-         proprietaries: BTreeMap<raw::ProprietaryKey, Vec<u8>> => Proprietary[raw::ProprietaryKey](Vec<u8>),
-         unknowns: BTreeMap<raw::Key, Vec<u8>> => Unknown[raw::Key](Vec<u8>),
-     },
+     /// [`UniqueId`].
 @@ crates/concurrent-psbt/src/psbt/output.rs: impl From<Output> for psbt_v2::v2::Output {
  
  /// Opaque byte-vector identifier for a PSBT output.
@@ crates/concurrent-psbt/src/psbt/output.rs: impl From<Output> for psbt_v2::v2::Ou
  #[derive(Debug, Clone, PartialEq, Eq, Hash)]
  pub struct UniqueId(Vec<u8>);
  
-@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
-         use bitcoin::bip32::{DerivationPath, Fingerprint};
-         use bitcoin::hashes::Hash;
-         use bitcoin::secp256k1::{Secp256k1, SecretKey};
--        use bitcoin::taproot::TaprootBuilder;
-+        use bitcoin::taproot::{TapLeafHash, TaprootBuilder};
-         use std::collections::BTreeMap;
- 
-         #[test]
 @@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
                  ..output(1)
              };
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
              assert_eq!(joined.clone().try_unwrap(), Err(joined));
          }
  
-@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
-                 tap_tree: Some(TapTree::try_from(tap_tree).expect("complete tree")),
-                 tap_key_origins: BTreeMap::from([(
-                     x_only_public_key,
--                    (vec![TapLeafHash::from_byte_array([5; 32])], source),
-+                    (
-+                        TapLeafHashes::from(vec![TapLeafHash::from_byte_array([5; 32])]),
-+                        source,
-+                    ),
-                 )]),
-                 proprietaries: BTreeMap::from([(
-                     raw::ProprietaryKey {
 @@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
  
              #[test]
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
                  prop_assert_eq!(r.is_ok(), r.try_unwrap().is_ok());
              }
  
-
- ## crates/concurrent-psbt/src/psbt/tap_leaf_hashes.rs (new) ##
-@@
-+//! The leaf hashes of a BIP 371 taproot key origin.
-+
-+use std::collections::{BTreeMap, BTreeSet};
-+
-+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`.
-+///
-+/// Two values are equal when they hold the same hashes, in any order and with
-+/// any repetition. The hashes keep the order they were given in, and joining
-+/// equal values keeps the left one.
-+#[derive(Debug, Clone)]
-+pub struct TapLeafHashes(Vec<TapLeafHash>);
-+
-+impl TapLeafHashes {
-+    /// The leaf hashes, in the order they were given in.
-+    pub fn as_slice(&self) -> &[TapLeafHash] {
-+        &self.0
-+    }
-+
-+    fn set(&self) -> BTreeSet<&TapLeafHash> {
-+        self.0.iter().collect()
-+    }
-+}
-+
-+impl PartialEq for TapLeafHashes {
-+    fn eq(&self, other: &Self) -> bool {
-+        self.set() == other.set()
-+    }
-+}
-+
-+impl Eq for TapLeafHashes {}
-+
-+// Every value is built here, so sorting and deduplicating `leaves` here would
-+// make equal values structurally equal.
-+impl From<Vec<TapLeafHash>> for TapLeafHashes {
-+    fn from(leaves: Vec<TapLeafHash>) -> Self {
-+        Self(leaves)
-+    }
-+}
-+
-+impl From<TapLeafHashes> for Vec<TapLeafHash> {
-+    fn from(leaves: TapLeafHashes) -> Self {
-+        leaves.0
-+    }
-+}
-+
-+impl IdempotentValue for (TapLeafHashes, KeySource) {}
-+
-+/// `PSBT_{IN,OUT}_TAP_BIP32_DERIVATION` as psbt-v2 stores it.
-+type V2TapKeyOrigins = BTreeMap<XOnlyPublicKey, (Vec<TapLeafHash>, KeySource)>;
-+
-+/// Converts `tap_key_origins` between psbt-v2's leaf hash lists and
-+/// [`TapLeafHashes`].
-+pub(crate) enum TapKeyOrigins {}
-+
-+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()
-+    }
-+
-+    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"))]
-+#[cfg_attr(coverage_nightly, coverage(off))]
-+mod tests {
-+    use bitcoin::bip32::{DerivationPath, Fingerprint};
-+    use bitcoin::hashes::Hash;
-+    use bitcoin::secp256k1::{Secp256k1, SecretKey};
-+    use proptest::prelude::*;
-+
-+    use super::*;
-+    use crate::Lift;
-+    use crate::lattice::join::Join;
-+    use crate::lattice::partial::{JoinResult, PartialJoin};
-+
-+    fn arb_leaves() -> impl Strategy<Value = Vec<TapLeafHash>> {
-+        proptest::collection::vec(0u8..3, 0..4).prop_map(|bytes| {
-+            bytes
-+                .into_iter()
-+                .map(|byte| TapLeafHash::from_byte_array([byte; 32]))
-+                .collect()
-+        })
-+    }
-+
-+    /// `leaves` in reverse, with each hash repeated.
-+    fn shuffled(leaves: &[TapLeafHash]) -> Vec<TapLeafHash> {
-+        leaves.iter().rev().flat_map(|&leaf| [leaf, leaf]).collect()
-+    }
-+
-+    fn arb_v2_origin() -> impl Strategy<Value = (Vec<TapLeafHash>, KeySource)> {
-+        (arb_leaves(), 0u8..2).prop_map(|(leaves, source)| {
-+            let source = (Fingerprint::from([source; 4]), DerivationPath::master());
-+            (leaves, source)
-+        })
-+    }
-+
-+    fn arb_origin() -> impl Strategy<Value = (TapLeafHashes, KeySource)> {
-+        arb_v2_origin().prop_map(|(leaves, source)| (leaves.into(), source))
-+    }
-+
-+    fn arb_result_origin() -> impl Strategy<Value = JoinResult<(TapLeafHashes, KeySource)>> {
-+        prop_oneof![
-+            arb_origin().prop_map(Ok),
-+            (arb_origin(), arb_origin()).prop_map(|(a, b)| a.wrap().join(b.wrap())),
-+        ]
-+    }
-+
-+    fn arb_v2_tap_key_origins() -> impl Strategy<Value = V2TapKeyOrigins> {
-+        proptest::collection::btree_map(1u8..4, arb_v2_origin(), 0..3).prop_map(|origins| {
-+            origins
-+                .into_iter()
-+                .map(|(seed, origin)| {
-+                    let secret_key = SecretKey::from_slice(&[seed; 32]).expect("nonzero seed");
-+                    (secret_key.x_only_public_key(&Secp256k1::new()).0, origin)
-+                })
-+                .collect()
-+        })
-+    }
-+
-+    assert_partial_join_laws!(arb_origin(), arb_result_origin());
-+
-+    proptest! {
-+        #[test]
-+        fn reordered_and_repeated_hashes_are_equal(a in arb_leaves()) {
-+            prop_assert_eq!(TapLeafHashes::from(shuffled(&a)), TapLeafHashes::from(a));
-+        }
-+
-+        #[test]
-+        fn an_extra_hash_is_unequal(a in arb_leaves(), extra in 3u8..6) {
-+            let mut b = a.clone();
-+            b.push(TapLeafHash::from_byte_array([extra; 32]));
-+            prop_assert_ne!(TapLeafHashes::from(a), TapLeafHashes::from(b));
-+        }
-+
-+        #[test]
-+        fn join_keeps_the_left_list(a in arb_leaves()) {
-+            let source = (Fingerprint::default(), DerivationPath::master());
-+            let left = (TapLeafHashes::from(a.clone()), source.clone());
-+            let right = (TapLeafHashes::from(shuffled(&a)), source);
-+            let (joined, _) = left.try_join(right).expect("equal values join");
-+            prop_assert_eq!(joined.as_slice(), a.as_slice());
-+        }
-+
-+        #[test]
-+        fn v2_round_trip_keeps_the_lists(origins in arb_v2_tap_key_origins()) {
-+            prop_assert_eq!(TapKeyOrigins::into_v2(TapKeyOrigins::from_v2(origins.clone())), origins);
-+        }
-+    }
-+}
-
- ## crates/concurrent-psbt/src/psbt/values.rs ##
-@@
- //! [`IdempotentValue`](crate::values::IdempotentValue) implementations for
- //! bitcoin and psbt-v2 types used as PSBT fields.
- 
--use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
- use crate::values::IdempotentValue;
- 
- impl IdempotentValue for bitcoin::absolute::Height {}
-@@ crates/concurrent-psbt/src/psbt/values.rs: impl IdempotentValue for psbt_v2::PsbtSighashType {}
- impl IdempotentValue for psbt_v2::Version {}
- 
- impl IdempotentValue for (bitcoin::ScriptBuf, bitcoin::taproot::LeafVersion) {}
--
--/// BIP 371 taproot BIP 32 derivation values: `(Vec<TapLeafHash>, KeySource)`.
--///
--/// The leaf-hash list is the set of tap leaves the key participates in; BIP 371
--/// imposes no ordering on it, so join equality is order-insensitive: two values
--/// join iff the key sources match and the leaf lists are equal as multisets.
--/// `self`'s representation (its leaf order) is kept on `Ok`.
--impl PartialJoin for (Vec<bitcoin::TapLeafHash>, bitcoin::bip32::KeySource) {
--    fn try_join(self, other: Self) -> JoinResult<Self> {
--        fn sorted(leaves: &[bitcoin::TapLeafHash]) -> Vec<bitcoin::TapLeafHash> {
--            let mut copy = leaves.to_vec();
--            copy.sort_unstable();
--            copy
--        }
--
--        if self.1 == other.1 && sorted(&self.0) == sorted(&other.0) {
--            Ok(self)
--        } else {
--            Err(Conflict::from_values([self, other]))
--        }
--    }
--}
--
--#[cfg(test)]
--#[cfg_attr(coverage_nightly, coverage(off))]
--mod tests {
--    #[cfg(feature = "unit-tests")]
--    mod unit {
--        use bitcoin::TapLeafHash;
--        use bitcoin::bip32::{DerivationPath, Fingerprint, KeySource};
--        use bitcoin::hashes::Hash;
--
--        use crate::lattice::partial::{Conflict, PartialJoin};
--
--        fn key_source() -> KeySource {
--            (Fingerprint::from([0u8; 4]), DerivationPath::master())
--        }
--
--        fn leaf(byte: u8) -> TapLeafHash {
--            TapLeafHash::from_byte_array([byte; 32])
--        }
--
--        #[test]
--        fn reordered_tap_leaf_hashes_join_ok() {
--            let a = (vec![leaf(1), leaf(2)], key_source());
--            let b = (vec![leaf(2), leaf(1)], key_source());
--            // Same leaves as a multiset: joins Ok, keeping self's representation.
--            assert_eq!(a.clone().try_join(b), Ok(a));
--        }
--
--        #[test]
--        fn different_tap_leaf_hashes_conflict() {
--            let a = (vec![leaf(1)], key_source());
--            let b = (vec![leaf(2)], key_source());
--            assert_eq!(
--                a.clone().try_join(b.clone()),
--                Err(Conflict::from_values([a, b]))
--            );
--        }
--    }
--
--    #[cfg(feature = "prop-tests")]
--    mod prop {
--        use bitcoin::TapLeafHash;
--        use bitcoin::bip32::{DerivationPath, Fingerprint, KeySource};
--        use bitcoin::hashes::Hash;
--        use proptest::prelude::*;
--
--        use crate::lattice::partial::PartialJoin;
--
--        fn key_source(byte: u8) -> KeySource {
--            (Fingerprint::from([byte; 4]), DerivationPath::master())
--        }
--
--        fn leaves(bytes: &[u8]) -> Vec<TapLeafHash> {
--            bytes
--                .iter()
--                .map(|byte| TapLeafHash::from_byte_array([*byte; 32]))
--                .collect()
--        }
--
--        proptest! {
--            #[test]
--            fn different_key_sources_conflict(bytes in proptest::collection::vec(any::<u8>(), 0..8)) {
--                let a = (leaves(&bytes), key_source(0));
--                let b = (leaves(&bytes), key_source(1));
--                prop_assert!(a.try_join(b).is_err());
--            }
--        }
--    }
--}
5: bbeaafa8bf ! 5: 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;
7: 935a180af6 ! 7: 79f823da84 introduce OutputSet, keyed by unique output IDs
@@ crates/concurrent-psbt/src/psbt/mod.rs: pub mod input;
  pub mod output;
 +mod output_set;
  pub(crate) mod proprietary;
- mod tap_leaf_hashes;
  mod values;
+ 
 
  ## crates/concurrent-psbt/src/psbt/output.rs ##
 @@

@oakagent oakagent left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed the pull request in full: the 6 newest of 8 commits, then the rest of its changes.

///
/// Each entry in `fields` mirrors the field of the same name in the `v2` type.
/// Each entry in `proprietary` is written
/// `name: Type = Codec`, and is stored in a proprietary key of `v2` by the

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Proprietary entry syntax omits => Variant

The proprietary matcher requires => Variant after = Codec, but the explicit syntax documented for proprietary entries omits it, so an entry written as described does not match and fails to compile. The only non-empty proprietary block uses unique_id: UniqueId = UniqueIdField => UniqueId.

oakagent · automated · e4f34a0

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.
Abstractly this is an unordered set of Output structs. Concretely, it is a
hashmap keyed by the unique output ID, so that recursive merging merges
disjoint field values associated with the same output ID.
Abstractly this is an unordered set of Input structs. Concretely, it is a
hashmap keyed by the spent coin's outpoint, so that recursive merging merges
disjoint field values associated with the same input.
This is the unordered counterpart to the upstream Psbt struct. Instead
of Vec<Input> and Vec<Output>, these collections are represented using
InputSet and OutputSet respectively.

The result domain counterpart has additional logic to maintain
consistency of counts, which are stored in the Global struct, with the
actual counts of the InputSet and OutputSet as these are merged
recursively.
@github-actions

Copy link
Copy Markdown
range-diff for force push e4f34a0d4a → c74ab8412a November 16, 2026 18:17 UTC: 1 modified, 6 unchanged; 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..e4f34a0 3e0c224..c74ab84

1:  0e4597c7b1 +584 -661 18f = 1:  0e4597c7b1 +584 -661 18f Lift PSBT fields recursively and retain typed conflict paths
2:  aca5c18ed5 +560 -268  8f = 2:  aca5c18ed5 +560 -268  8f define own Global, Input and Output structs
3:  5d7cad32fd +285  -89  6f = 3:  5d7cad32fd +285  -89  6f require a unique ID on every Output
4:  8c2e1d8f34 +149  -56  4f = 4:  8c2e1d8f34 +149  -56  4f Exercise owned PSBT conflict paths and conversions
5:  1aa57fc30c +981   -0  5f ! 5:  621eee135d +992   -0  5f Introduce keyed set structures for inputs and outputs
7:  79f823da84 +453   -2  4f = 6:  549f48422c +453   -2  4f introduce OutputSet, keyed by unique output IDs
6:  b97cb9cfc6 +447   -2  4f = 7:  f52fcffb5d +447   -2  4f Introduce InputSet, keyed by outpoint
5: 1aa57fc30c ! 5: 621eee135d 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.
++/// 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
 +    /// 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.
++///
++/// 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)]
@@ 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);
@@ 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);
++    #[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 c74ab8412a → 2527d0f2ef November 16, 2026 23:42 UTC: 3 modified, 4 unchanged; 7 commits; same base 3e0c2248af

reproduce: git range-diff 3e0c224..c74ab84 3e0c224..2527d0f

1:  0e4597c7b1 +584 -661 18f = 1:  0e4597c7b1 +584 -661 18f Lift PSBT fields recursively and retain typed conflict paths
2:  aca5c18ed5 +560 -268  8f = 2:  aca5c18ed5 +560 -268  8f define own Global, Input and Output structs
3:  5d7cad32fd +285  -89  6f = 3:  5d7cad32fd +285  -89  6f require a unique ID on every Output
4:  8c2e1d8f34 +149  -56  4f ! 4:  50eab5bc68 +145  -56  4f Exercise owned PSBT conflict paths and conversions
5:  621eee135d +992   -0  5f = 5:  839365306e +992   -0  5f Introduce keyed set structures for inputs and outputs
6:  549f48422c +453   -2  4f ! 6:  a51984cb7c +458   -5  4f introduce OutputSet, keyed by unique output IDs
7:  f52fcffb5d +447   -2  4f ! 7:  213e6e2f9a +451   -4  4f Introduce InputSet, keyed by outpoint
4: 8c2e1d8f34 ! 4: 50eab5bc68 Exercise owned PSBT conflict paths and conversions
@@ crates/concurrent-psbt/src/psbt/input.rs
 @@
  #![allow(clippy::result_large_err)]
  
-+//! Per-input field type and input set merging.
++//! PSBT input fields.
 +//!
-+//! [`ResultInput`] wraps each per-input field in the internal result domain.
-+//! `InputSet` and `ResultInputSet` are sets of inputs identified by the
-+//! outpoint each spends. Joining two sets joins the inputs that spend the same
-+//! outpoint field by field, and fields that differ become conflicts.
++//! [`ResultInput`] joins fields independently, retaining incompatible values
++//! as conflicts.
 +
  use std::collections::BTreeMap;
  
@@ crates/concurrent-psbt/src/psbt/output.rs
 @@
  #![allow(clippy::result_large_err)]
  
-+//! Per-output field type and output set merging.
++//! PSBT output fields.
 +//!
-+//! [`ResultOutput`] wraps each per-output field in the internal result domain.
-+//! `OutputSet` and `ResultOutputSet` are sets of outputs identified by their
-+//! [`UniqueId`]. Joining two sets joins the outputs that have the same unique ID
-+//! field by field, and fields that differ become conflicts.
++//! [`ResultOutput`] joins fields independently, retaining incompatible values
++//! as conflicts.
 +
  use std::collections::BTreeMap;
  
@@ crates/concurrent-psbt/src/psbt/output.rs: impl From<Output> for psbt_v2::v2::Ou
 -/// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Used as the map key in `OutputSet`
 -/// so that outputs can be merged in an order-independent way.
 +/// Stored in the `PSBT_OUT_UNIQUE_ID` proprietary field, subtype
-+/// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Identifies an output within an
-+/// `OutputSet`.
++/// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Identifies an output independently of its
++/// position in a transaction.
  ///
 -/// Built with [`TryFrom`], a unique ID is 1 to [`UniqueId::MAX_LEN`] bytes
 -/// long, as is one read from a BIP 370 output. An empty ID would make
6: 549f48422c ! 6: a51984cb7c introduce OutputSet, keyed by unique output IDs
@@ crates/concurrent-psbt/src/psbt/mod.rs: pub mod input;
 
  ## crates/concurrent-psbt/src/psbt/output.rs ##
 @@
- //! Per-output field type and output set merging.
+ #![allow(clippy::result_large_err)]
+ 
+-//! PSBT output fields.
++//! Per-output field type and output set merging.
  //!
- //! [`ResultOutput`] wraps each per-output field in the internal result domain.
--//! `OutputSet` and `ResultOutputSet` are sets of outputs identified by their
+-//! [`ResultOutput`] joins fields independently, retaining incompatible values
+-//! as conflicts.
++//! [`ResultOutput`] wraps each per-output field in the internal result domain.
 +//! [`OutputSet`] and [`ResultOutputSet`] are sets of outputs identified by their
- //! [`UniqueId`]. Joining two sets joins the outputs that have the same unique ID
- //! field by field, and fields that differ become conflicts.
++//! [`UniqueId`]. Joining two sets joins the outputs that have the same unique ID
++//! field by field, and fields that differ become conflicts.
+ 
+ use std::collections::BTreeMap;
  
 @@ crates/concurrent-psbt/src/psbt/output.rs: impl From<Output> for psbt_v2::v2::Output {
+ /// Opaque byte-vector identifier for a PSBT output.
  ///
  /// Stored in the `PSBT_OUT_UNIQUE_ID` proprietary field, subtype
- /// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Identifies an output within an
--/// `OutputSet`.
+-/// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Identifies an output independently of its
+-/// position in a transaction.
++/// [`PSBT_OUT_UNIQUE_ID_SUBTYPE`]. Identifies an output within an
 +/// [`OutputSet`].
  ///
  /// A unique ID built with [`TryFrom`] or read from a BIP 370 output is 1 to
7: f52fcffb5d ! 7: 213e6e2f9a Introduce InputSet, keyed by outpoint
@@ Commit message
 
  ## crates/concurrent-psbt/src/psbt/input.rs ##
 @@
- //! Per-input field type and input set merging.
+ #![allow(clippy::result_large_err)]
+ 
+-//! PSBT input fields.
++//! Per-input field type and input set merging.
  //!
- //! [`ResultInput`] wraps each per-input field in the internal result domain.
--//! `InputSet` and `ResultInputSet` are sets of inputs identified by the
+-//! [`ResultInput`] joins fields independently, retaining incompatible values
+-//! as conflicts.
++//! [`ResultInput`] wraps each per-input field in the internal result domain.
 +//! [`InputSet`] and [`ResultInputSet`] are sets of inputs identified by the
- //! outpoint each spends. Joining two sets joins the inputs that spend the same
- //! outpoint field by field, and fields that differ become conflicts.
++//! outpoint each spends. Joining two sets joins the inputs that spend the same
++//! outpoint field by field, and fields that differ become conflicts.
+ 
+ use std::collections::BTreeMap;
  
 @@ crates/concurrent-psbt/src/psbt/input.rs: pub(crate) fn out_point(input: &Input) -> OutPoint {
      }

@oakagent oakagent left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Reviewed the 6 newest of 8 commits; the rest of the pull request will be reviewed in the next cycles.


fn try_from(bytes: Vec<u8>) -> Result<Self, InvalidUniqueId> {
if bytes.len() > Self::MAX_LEN {
if bytes.is_empty() || bytes.len() > Self::MAX_LEN {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

33-byte PSBT_OUT_UNIQUE_ID rejected on conversion

The commit routes Output::try_from through UniqueId::try_from, which rejects IDs longer than MAX_LEN (32), so a 33-byte PSBT_OUT_UNIQUE_ID that the spec allows as <bytes unique id> no longer converts; the parent accepted it.

oakagent · automated · 2527d0f

/// then the first output whose `PSBT_OUT_UNIQUE_ID` is missing, empty or
/// longer than [`UniqueId::MAX_LEN`] bytes, then the first unique ID that
/// repeats.
pub fn try_from_psbt(psbt: Psbt) -> Result<Self, UnorderedPsbtError> {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Unordered PSBT accepts SIGHASH_SINGLE flag

try_from_psbt checks only the input and output modifiable bits of tx_modifiable_flags, so a PSBT with the SIGHASH_SINGLE bit (0x04) is accepted even though the spec forbids it in unordered transactions; into_psbt then reorders inputs and outputs, changing which output a SIGHASH_SINGLE input signs.

If set, the Has SIGHASH_SINGLE flag of PSBT_GLOBAL_TX_MODIFIABLE must not be set. SIGHASH_SINGLE inputs MUST not be used in unordered transactions.

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

oakagent · automated · 2527d0f

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.

UnorderedPsbt with PartialJoin

3 participants