Skip to content

introduce Lift and Conflicts traits to simplify struct macro - #121

Open
yuval-block wants to merge 1 commit into
mainfrom
joinable-struct-lift
Open

yuval-block wants to merge 1 commit into
mainfrom
joinable-struct-lift

Conversation

@yuval-block

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

Copy link
Copy Markdown
Collaborator

joinable_struct! previously chose each field's rules by matching how its type was spelled. Qualified paths and aliases of containers could therefore be treated as scalars.

Lift::wrap now selects the result-domain type through the field's type. PartialJoin values lift into JoinResult; Option, BTreeMap, and HashMap lift their values recursively, including generated PSBT records. ResultWrapped::try_unwrap is the inverse operation when there are no conflicts. Failed extraction retains the whole wrapped container, including its clean entries. Taproot key-origin tuples use the existing IdempotentValue join with structural equality, replacing the special order-insensitive comparison.

Conflicts composes borrowed iterators without erasing conflict values or map keys. PSBT conflict enums identify fields and keydata, and enclosing containers retain the keys that locate each record. These replace the Debug-based callback visitor. The existing PSBT extension names remain aliases of Lift, preserving .wrap() call sites.

record_conflicts! is a temporary addition, invoked by joinable_struct! with explicit conflict mappings. Once #116 introduces our own PSBT structs, joinable_struct! will subsume it so one field declaration defines the source type, result type, and conflict variants.

The borrowed conflict iterators address the introspection described in #44, with typed PSBT field paths and keydata.

@github-code-quality

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

Copy link
Copy Markdown

Code coverage overview

Languages: Rust

Rust / code-coverage/cargo-llvm-cov

main 3e0c224 joinable-struct-lift 0e4597c +/-
100% 100% 0%
View coverage of the 8 most impacted files.
File main 3e0c224 joinable-struct-lift 0e4597c +/-
crates/concurre...ons/btreemap.rs 100% 100% 0%
crates/concurre...ions/hashmap.rs 100% 100% 0%
crates/concurre...tions/option.rs 100% 100% 0%
crates/concurre...tice/partial.rs 100% 100% 0%
crates/concurre...struct_macro.rs 100% 100% 0%
crates/concurre...nflict_macro.rs 0% 100% +100%
crates/concurre...lattice/lift.rs 0% 100% +100%
crates/concurre...ce/conflicts.rs 0% 100% +100%

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


Updated November 16, 2026 05:37 UTC

@yuval-block
yuval-block marked this pull request as ready for review November 16, 2026 00:29
@yuval-block
yuval-block marked this pull request as draft November 16, 2026 02:16
@yuval-block yuval-block changed the title lift joinable_struct fields by type, not by token introduce Lift trait to simplify struct macro Nov 16, 2026
@github-actions

Copy link
Copy Markdown
range-diff for force push 439d9e2a38 → b72b43e9b8 November 16, 2026 03:12 UTC: 1 modified; 1 commit; same base 3e0c2248af

reproduce: git range-diff 3e0c224..439d9e2 3e0c224..b72b43e

1:  439d9e2a38 +319 -550 10f ! 1:  b72b43e9b8 +499 -635 16f lift joinable_struct fields by type, not by token
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,
          Err(_) => unreachable!("is_ok() guard verified all entries"),
@@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<V: PartialJoin> HashMapR
  }
  
 -impl<K: Hash + Eq, V: HashMapResultValue> ResultHashMapExt for HashMap<K, V> {
-+impl<K: Hash + Eq, V: ResultValue> ResultHashMapExt for HashMap<K, V> {
-     type Key = K;
-     type Value = V;
+-    type Key = K;
+-    type Value = V;
++impl<K: Hash + Eq, V: ResultWrapped> ResultWrapped for HashMap<K, V> {
++    type Clean = HashMap<K, V::Clean>;
  
+     fn is_ok(&self) -> bool {
+         self.values().all(|v| v.is_ok())
 @@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<K: Hash + Eq, V: HashMapResultValue> ResultHashMapExt for HashMap<K, V> {
  #[cfg_attr(coverage_nightly, coverage(off))]
  mod tests {
@@ crates/concurrent-psbt/src/collections/hashmap.rs: impl<K: Hash + Eq, V: HashMap
      #[derive(Debug, Clone, PartialEq, Eq, Hash)]
      struct Val(u8);
 @@ crates/concurrent-psbt/src/collections/hashmap.rs: mod tests {
+     mod unit {
+         use super::*;
  
+-        fn wrap_map<K: Eq + Hash>(m: HashMap<K, Val>) -> HashMap<K, JoinResult<Val>> {
+-            m.map_values(PartialJoin::wrap)
++        #[test]
++        fn nested_maps_lift_join_and_preserve_conflicts() {
++            let a: HashMap<u8, Option<HashMap<u8, Val>>> =
++                [(1, Some([(2, Val(3))].into())), (4, None)].into();
++            let b: HashMap<u8, Option<HashMap<u8, Val>>> = [(1, Some([(2, Val(5))].into()))].into();
++            assert_eq!(ResultWrapped::try_unwrap(a.clone().wrap()), Ok(a.clone()));
++            let joined = a.wrap().join(b.wrap());
++            assert!(!ResultWrapped::is_ok(&joined));
++            assert_eq!(
++                ResultWrapped::try_unwrap(joined.clone()),
++                Err(joined.clone())
++            );
++            let keys: Vec<_> = joined
++                .conflicts()
++                .map(|(outer, (inner, _))| (*outer, *inner))
++                .collect();
++            assert_eq!(keys, [(1, 2)]);
+         }
+ 
+         #[test]
+-        fn map_values_preserves_keys() {
++        fn wrap_preserves_keys() {
+             let m: HashMap<&str, Val> = [("a", Val(1)), ("b", Val(2))].into();
+-            let w = wrap_map(m);
++            let w = m.wrap();
+             assert_eq!(w.len(), 2);
+             assert_eq!(w.get("a"), Some(&Ok(Val(1))));
+         }
+@@ crates/concurrent-psbt/src/collections/hashmap.rs: mod tests {
+         #[test]
+         fn try_unwrap_ok() {
+             let m: HashMap<&str, Val> = [("a", Val(1))].into();
+-            assert_eq!(wrap_map(m.clone()).try_unwrap().unwrap(), m);
++            assert_eq!(m.clone().wrap().try_unwrap().unwrap(), m);
+         }
+ 
+         #[test]
+@@ crates/concurrent-psbt/src/collections/hashmap.rs: mod tests {
+             let a: HashMap<u8, Val> = [(0, Val(0))].into();
+             let c: HashMap<u8, Val> = [(0, Val(1))].into();
+             assert_eq!(
+-                wrap_map(a).join(wrap_map(c)),
++                a.wrap().join(c.wrap()),
+                 [(0, Err(Conflict::from_values([Val(0), Val(1)])))].into()
+             );
+         }
+@@ crates/concurrent-psbt/src/collections/hashmap.rs: mod tests {
+             let a: HashMap<u8, Val> = [(0, Val(0))].into();
+             let c: HashMap<u8, Val> = [(0, Val(1))].into();
+             assert_eq!(
+-                wrap_map(a).join(wrap_map(c)).try_unwrap(),
++                a.wrap().join(c.wrap()).try_unwrap(),
+                 Err([(0, Err(Conflict::from_values([Val(0), Val(1)])))].into())
+             );
+         }
+@@ crates/concurrent-psbt/src/collections/hashmap.rs: mod tests {
          // Type-specific
          proptest! {
--            #[test]
+             #[test]
 -            fn result_value_try_unwrap_preserves_conflict(a in arb_val(), b in arb_val()) {
 -                let value: JoinResult<Val> = Err(Conflict::from_values([a, b]));
 -                prop_assert_eq!(
@@ crates/concurrent-psbt/src/collections/hashmap.rs: mod tests {
 -                );
 -            }
 -
-             #[test]
-             fn wrap_try_unwrap_roundtrip(m in proptest::collection::hash_map(0u8..4, arb_val(), 0..=3)) {
+-            #[test]
+-            fn wrap_try_unwrap_roundtrip(m in proptest::collection::hash_map(0u8..4, arb_val(), 0..=3)) {
++            fn lift_try_unwrap_roundtrip(m in proptest::collection::hash_map(0u8..4, arb_val(), 0..=3)) {
                  let len = m.len();
+-                let wrapped: HashMap<u8, JoinResult<Val>> = m.map_values(PartialJoin::wrap);
++                let wrapped: HashMap<u8, JoinResult<Val>> = m.clone().wrap();
+                 prop_assert_eq!(wrapped.len(), len);
+                 prop_assert!(wrapped.is_ok());
+-                prop_assert!(wrapped.try_unwrap().is_ok());
++                prop_assert_eq!(wrapped.try_unwrap(), Ok(m));
+             }
+ 
+             #[test]
+@@ crates/concurrent-psbt/src/collections/hashmap.rs: mod tests {
+                 prop_assert_eq!(m.is_ok(), !has_conflict);
+             }
+ 
++            #[test]
++            fn visits_each_conflict_under_its_key(m in arb_hashmap()) {
++                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);
++            }
++
+             #[test]
+             fn try_unwrap_err_when_conflict(
+                 m in proptest::collection::hash_map(0u8..4, arb_join_result(), 1..=3)
 
  ## crates/concurrent-psbt/src/collections/mod.rs ##
 @@
  //! Join implementations for standard library collection types.
  //!
- //! Each collection type provides crate-internal joins for the result domain,
+-//! Each collection type provides crate-internal joins for the result domain,
 -//! plus helper traits for lifting (`wrap`) and lowering (`try_unwrap`) between
 -//! clean and result representations.
-+//! and `Option` and `BTreeMap` implement [`Lift`](crate::lattice::lift::Lift),
-+//! [`ResultValue`](crate::lattice::lift::ResultValue) and
-+//! [`VisitConflicts`](crate::lattice::lift::VisitConflicts) by lifting their
-+//! contents.
++//! Collections lift and unwrap their contents recursively. Conflict iterators
++//! preserve the keys at each level.
  
  pub(crate) mod btreemap;
  pub(crate) mod hashmap;
 
  ## crates/concurrent-psbt/src/collections/option.rs ##
 @@
++use crate::lattice::conflicts::Conflicts;
  use crate::lattice::join::Join;
 -use crate::lattice::partial::{Conflict, JoinResult, PartialJoin};
-+use crate::lattice::lift::{ConflictVisitor, Lift, ResultValue, VisitConflicts};
++use crate::lattice::lift::{Lift, ResultWrapped};
  
  /// [`Join`] for `Option<V>`: `None` is the identity element.
  ///
@@ crates/concurrent-psbt/src/collections/option.rs: where
 -    type Item = V;
 -    fn wrap(self) -> Option<JoinResult<V>> {
 -        self.map(|v| v.wrap())
-+    fn lift(self) -> Self::Result {
-+        self.map(Lift::lift)
++    fn wrap(self) -> Self::Result {
++        self.map(Lift::wrap)
      }
  }
  
@@ crates/concurrent-psbt/src/collections/option.rs: where
 -impl<V: PartialJoin> ResultOptionExt for Option<JoinResult<V>> {
 -    type Value = V;
 +/// `None` has no conflicts.
-+impl<R: ResultValue> ResultValue for Option<R> {
++impl<R: ResultWrapped> ResultWrapped for Option<R> {
 +    type Clean = Option<R::Clean>;
  
      fn is_ok(&self) -> bool {
@@ crates/concurrent-psbt/src/collections/option.rs: where
 +    }
 +}
 +
-+impl<R: VisitConflicts> VisitConflicts for Option<R> {
-+    fn visit_conflicts(&self, f: &mut ConflictVisitor<'_>) {
-+        if let Some(value) = self {
-+            value.visit_conflicts(f);
-+        }
++impl<R: Conflicts> Conflicts for Option<R> {
++    type Item<'a>
++        = R::Item<'a>
++    where
++        Self: 'a;
++
++    fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>> {
++        self.iter().flat_map(Conflicts::conflicts)
      }
  }
  
@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
  
          #[test]
 -        fn wrap_none() {
--            assert_eq!(None::<Foo>.wrap(), None);
 +        fn lift_none() {
-+            assert_eq!(None::<Foo>.lift(), None);
+             assert_eq!(None::<Foo>.wrap(), None);
          }
  
          #[test]
 -        fn wrap_some() {
--            assert_eq!(Some(Foo(0)).wrap(), Some(Ok(Foo(0))));
 +        fn lift_some() {
-+            assert_eq!(Some(Foo(0)).lift(), Some(Ok(Foo(0))));
+             assert_eq!(Some(Foo(0)).wrap(), Some(Ok(Foo(0))));
          }
  
-         #[test]
-         fn try_unwrap_ok() {
--            assert_eq!(Some(Foo(0)).wrap().try_unwrap(), Ok(Some(Foo(0))));
-+            assert_eq!(Some(Foo(0)).lift().try_unwrap(), Ok(Some(Foo(0))));
+@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
          }
  
          #[test]
 -        fn wrapped_conflict_join() {
 +        fn lifted_conflict_join() {
              assert_eq!(
--                Some(Foo(0)).wrap().join(Some(Foo(1)).wrap()),
-+                Some(Foo(0)).lift().join(Some(Foo(1)).lift()),
+                 Some(Foo(0)).wrap().join(Some(Foo(1)).wrap()),
                  Some(Err(Conflict::from_values([Foo(0), Foo(1)])))
-             );
-         }
+@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
  
          #[test]
          fn try_unwrap_conflict() {
@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
 -                Some(Foo(0)).wrap().join(Some(Foo(1)).wrap()).try_unwrap(),
 -                Err(Conflict::from_values([Foo(0), Foo(1)]))
 -            );
-+            let conflict = Some(Foo(0)).lift().join(Some(Foo(1)).lift());
++            let conflict = Some(Foo(0)).wrap().join(Some(Foo(1)).wrap());
 +            assert_eq!(conflict.clone().try_unwrap(), Err(conflict));
          }
      }
  
-@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
-         fn arb_option_join_result() -> impl Strategy<Value = Option<JoinResult<Foo>>> {
-             prop_oneof![
-                 Just(None),
--                arb_foo().prop_map(|v| Some(v).wrap()),
-+                arb_foo().prop_map(|v| Some(v).lift()),
-                 proptest::collection::hash_set(arb_foo(), 1..=3)
-                     .prop_map(|s| Some(Err(Conflict::from_values(s)))),
-             ]
 @@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
              fn is_ok_consistent_with_try_unwrap(a in arb_option_join_result()) {
                  prop_assert_eq!(a.clone().is_ok(), a.try_unwrap().is_ok());
@@ crates/concurrent-psbt/src/collections/option.rs: mod tests {
 +
 +            #[test]
 +            fn visits_the_conflict_inside_some(a in arb_option_join_result()) {
-+                let mut visited = Vec::new();
-+                a.visit_conflicts(&mut |key, conflict| {
-+                    visited.push((key.is_none(), format!("{conflict:?}")));
-+                });
-+                let expected = match &a {
-+                    Some(Err(conflict)) => vec![(true, format!("{conflict:?}"))],
-+                    _ => vec![],
-+                };
-+                prop_assert_eq!(visited, expected);
++                let expected = a.as_ref().and_then(|value| value.as_ref().err());
++                prop_assert_eq!(a.conflicts().collect::<Vec<_>>(), expected.into_iter().collect::<Vec<_>>());
 +            }
          }
      }
  }
 
+ ## crates/concurrent-psbt/src/lattice/conflicts.rs (new) ##
+@@
++use super::partial::{Conflict, JoinResult, PartialJoin};
++
++/// Borrow conflicts without erasing their values or enclosing map keys.
++pub trait Conflicts {
++    type Item<'a>
++    where
++        Self: 'a;
++
++    fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>>;
++}
++
++impl<V: PartialJoin> Conflicts for JoinResult<V> {
++    type Item<'a>
++        = &'a Conflict<V>
++    where
++        Self: 'a;
++
++    fn conflicts(&self) -> impl Iterator<Item = Self::Item<'_>> {
++        self.as_ref().err().into_iter()
++    }
++}
+
  ## crates/concurrent-psbt/src/lattice/lift.rs (new) ##
 @@
 +//! Moving between clean values and their result-domain counterparts.
 +//!
 +//! A clean value [`Lift`]s into a result-domain value whose joins record
-+//! conflicts instead of failing. A [`ResultValue`] lowers back to the clean
-+//! value once it has no conflicts, and [`VisitConflicts`] reports the conflicts
-+//! it does have.
++//! 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` and `BTreeMap` lift their contents (see
++//! [`JoinResult`], and `Option`, `BTreeMap` and `HashMap` lift their contents (see
 +//! [`crate::collections`]).
 +
-+use std::fmt::Debug;
-+
 +use crate::lattice::join::Join;
 +use crate::lattice::partial::{JoinResult, PartialJoin};
 +
 +/// A clean value with a result-domain counterpart.
-+pub(crate) trait Lift: Sized {
++pub trait Lift: Sized {
 +    /// The result-domain counterpart, which lowers back to `Self`.
-+    type Result: Join + ResultValue<Clean = Self>;
++    type Result: Join + ResultWrapped<Clean = Self>;
 +    /// Lift into the result domain, without conflicts.
-+    fn lift(self) -> Self::Result;
++    fn wrap(self) -> Self::Result;
 +}
 +
 +/// A result-domain value, which may hold conflicts.
-+pub(crate) trait ResultValue: Sized {
++pub trait ResultWrapped: Sized {
 +    /// Clean value extracted when the result-domain value has no conflicts.
 +    type Clean;
 +    /// Returns `true` when this value contains no conflicts.
@@ crates/concurrent-psbt/src/lattice/lift.rs (new)
 +    fn try_unwrap(self) -> Result<Self::Clean, Self>;
 +}
 +
-+/// Callback receiving a conflict and the map key it sits under, if any.
-+pub(crate) type ConflictVisitor<'a> = dyn FnMut(Option<&dyn Debug>, &dyn Debug) + 'a;
-+
-+/// A result-domain value whose conflicts can be enumerated.
-+pub(crate) trait VisitConflicts {
-+    /// Call `f(key, conflict)` for each conflict.
-+    ///
-+    /// `key` is the map key under which the conflict sits, or `None` for a
-+    /// conflict that is not in a map.
-+    fn visit_conflicts(&self, f: &mut ConflictVisitor<'_>);
-+}
-+
 +impl<V: PartialJoin> Lift for V {
 +    type Result = JoinResult<V>;
 +
-+    fn lift(self) -> JoinResult<V> {
-+        self.wrap()
++    fn wrap(self) -> JoinResult<V> {
++        Ok(self)
 +    }
 +}
 +
-+impl<V: PartialJoin> ResultValue for JoinResult<V> {
++impl<V: PartialJoin> ResultWrapped for JoinResult<V> {
 +    type Clean = V;
 +
 +    fn is_ok(&self) -> bool {
@@ crates/concurrent-psbt/src/lattice/lift.rs (new)
 +    }
 +}
 +
-+impl<V: PartialJoin + Debug> VisitConflicts for JoinResult<V> {
-+    fn visit_conflicts(&self, f: &mut ConflictVisitor<'_>) {
-+        if let Err(conflict) = self {
-+            f(None, conflict);
-+        }
-+    }
-+}
-+
 +#[cfg(all(test, feature = "prop-tests"))]
 +#[cfg_attr(coverage_nightly, coverage(off))]
 +mod tests {
 +    use super::*;
++    use crate::lattice::conflicts::Conflicts;
 +    use crate::lattice::partial::Conflict;
 +    use proptest::prelude::*;
 +
 +    proptest! {
 +        #[test]
 +        fn lift_try_unwrap_roundtrip(a in 0u8..4) {
-+            let lifted = a.lift();
-+            prop_assert!(ResultValue::is_ok(&lifted));
-+            let mut visited = 0;
-+            lifted.visit_conflicts(&mut |_, _| visited += 1);
-+            prop_assert_eq!(visited, 0);
-+            prop_assert_eq!(ResultValue::try_unwrap(lifted), Ok(a));
++            let lifted = a.wrap();
++            prop_assert!(ResultWrapped::is_ok(&lifted));
++            prop_assert_eq!(lifted.conflicts().count(), 0);
++            prop_assert_eq!(ResultWrapped::try_unwrap(lifted), Ok(a));
 +        }
 +
 +        #[test]
 +        fn conflicts_are_kept_and_visited(a in 0u8..4, b in 0u8..4) {
 +            prop_assume!(a != b);
 +            let value: JoinResult<u8> = Err(Conflict::from_values([a, b]));
-+            prop_assert!(!ResultValue::is_ok(&value));
-+            let mut visited = Vec::new();
-+            value.visit_conflicts(&mut |key, conflict| {
-+                visited.push((key.is_none(), format!("{conflict:?}")));
-+            });
-+            prop_assert_eq!(visited, [(true, format!("{:?}", value.clone().unwrap_err()))]);
-+            prop_assert_eq!(ResultValue::try_unwrap(value.clone()), Err(value));
++            prop_assert!(!ResultWrapped::is_ok(&value));
++            prop_assert_eq!(value.conflicts().collect::<Vec<_>>(), vec![value.as_ref().unwrap_err()]);
++            prop_assert_eq!(ResultWrapped::try_unwrap(value.clone()), Err(value));
 +        }
 +    }
 +}
 
  ## crates/concurrent-psbt/src/lattice/mod.rs ##
 @@
++pub(crate) mod conflicts;
  #[macro_use]
  pub(crate) mod join;
 +pub(crate) mod lift;
  #[macro_use]
  pub(crate) mod partial;
 
+ ## crates/concurrent-psbt/src/lattice/partial.rs ##
+@@ crates/concurrent-psbt/src/lattice/partial.rs: pub trait PartialJoin: Sized + PartialEq {
+     /// `Conflict` is joined with another value, new entries are appended, so a multi-way fold does
+     /// not preserve per-operand attribution.
+     fn try_join(self, other: Self) -> JoinResult<Self>;
+-
+-    /// Lift a value into the result domain as `Ok(self)`.
+-    fn wrap(self) -> JoinResult<Self> {
+-        Ok(self)
+-    }
+ }
+ 
+ /// Result of a fallible join: `Ok(v)` where `v` is the least upper bound if one exists,
+@@ crates/concurrent-psbt/src/lattice/partial.rs: mod tests {
+     #[cfg(feature = "unit-tests")]
+     mod unit {
+         use super::*;
++        use crate::Lift;
+ 
+         #[test]
+         fn result_ok_ok_different_produces_conflict() {
+@@ crates/concurrent-psbt/src/lattice/partial.rs: mod tests {
+     #[cfg(feature = "prop-tests")]
+     mod prop {
+         use super::*;
++        use crate::Lift;
+         use proptest::prelude::*;
+ 
+         fn arb_foo() -> impl Strategy<Value = Foo> {
+
+ ## crates/concurrent-psbt/src/lib.rs ##
+@@ crates/concurrent-psbt/src/lib.rs: pub use lattice::join::{Join, JoinMut};
+ pub use lattice::partial::{Conflict, JoinResult, PartialJoin};
+ pub use psbt::input;
+ pub use psbt::output;
++
++pub use lattice::conflicts::Conflicts;
++pub use lattice::lift::{Lift, ResultWrapped};
++pub use psbt::global;
+
+ ## crates/concurrent-psbt/src/psbt/conflict_macro.rs (new) ##
+@@
++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)]
+-#![cfg_attr(
+-    not(test),
+-    expect(
+-        dead_code,
+-        reason = "exported once UnorderedPsbt composes the PSBT types"
+-    )
+-)]
+ 
+ //! PSBT global field merging.
+ //!
 @@
  //! enabling field-by-field merging that accumulates conflicts without short-circuiting.
  //! [`GlobalExt::wrap`] lifts a clean [`Global`] into the result domain.
@@ 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 {
+@@ 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();
+             let mut b = Global::default();
+             a.tx_version = transaction::Version::ONE;
+             b.tx_version = transaction::Version::TWO;
+-            let mut fields = Vec::new();
+-            a.wrap()
+-                .join(b.wrap())
+-                .for_each_conflict(|field, _, _| fields.push(field.to_owned()));
+-            assert_eq!(fields, ["tx_version"]);
++            let joined = a.wrap().join(b.wrap());
++            assert_eq!(
++                joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(),
++                [GlobalField::TxVersion]
++            );
+         }
+     }
+ 
 
  ## crates/concurrent-psbt/src/psbt/input.rs ##
 @@
@@ 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! {
+     }
+ }
  
++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/input.rs: mod tests {
 -        #[test]
 -        fn for_each_conflict_reports_every_conflicted_field() {
 -            let result = all_fields_conflict(1);
-+        fn inputs_spending_different_outpoints_conflict() {
-+            let joined = make_input(1, 0).wrap().join(make_input(2, 0).wrap());
-             let mut fields = Vec::new();
+-            let mut fields = Vec::new();
 -            result.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
 -
 -            assert_eq!(fields, ALL_CONFLICT_FIELDS);
-+            joined.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
-+            assert_eq!(fields, ["previous_txid"]);
++        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.clone().try_unwrap(), Err(joined));
          }
  
@@ 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
 +/// [`PartialJoin`](crate::PartialJoin) scalar as a
-+/// [`JoinResult`](crate::JoinResult), and `Option` and `BTreeMap` by lifting
++/// [`JoinResult`](crate::JoinResult), and `Option`, `BTreeMap` and `HashMap` by lifting
 +/// their contents. Paths and type aliases resolve like any other type.
  ///
  /// Generates:
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
  /// 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`
++/// 4. `$Result::is_ok` and `$Result::try_unwrap`
++/// 5. `Lift for $Source` and `ResultWrapped 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
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs
          }
  
 -        // 2. Ext trait + impl
-         pub trait $Ext {
-+            #[doc = concat!(
-+                "Lift into the result domain as a conflict-free [`",
-+                stringify!($Result),
-+                "`]."
-+            )]
-             fn wrap(self) -> $Result;
-         }
+-        pub trait $Ext {
+-            fn wrap(self) -> $Result;
+-        }
++        pub use $crate::Lift as $Ext;
++
++        impl $crate::lattice::lift::Lift for $Source {
++            type Result = $Result;
  
-@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_struct {
+-        impl $Ext for $Source {
              fn wrap(self) -> $Result {
                  $Result {
                      $(
 -                        $field: joinable_struct!(@wrap $category self . $field),
 -                    )*
-+                        $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_
                  $(
 -                    joinable_struct!(@is_ok $category self . $field)
 -                )&&*
-+                    $crate::lattice::lift::ResultValue::is_ok(&self.$field)
-+                )&&+
-             }
- 
-             /// Visit each conflicted field, calling `f(field_name, key, &conflict)`.
-             ///
-             /// Only visits fields that contain conflicts. Clean fields are skipped.
+-            }
+-
+-            /// Visit each conflicted field, calling `f(field_name, key, &conflict)`.
+-            ///
+-            /// Only visits fields that contain conflicts. Clean fields are skipped.
 -            /// For map fields, visits each conflicted entry with `Some(&key)`, so
 -            /// callers can tell which entry conflicts. For scalar and option
-+            /// For map fields and options holding maps, visits each conflicted
-+            /// entry with `Some(&key)`, so callers can tell which entry conflicts. For other
-             /// fields `key` is `None`.
-             #[cfg_attr(
+-            /// fields `key` is `None`.
+-            #[cfg_attr(
 -                not(test),
 -                expect(dead_code, reason = "only tests enumerate conflicted fields so far")
-+                not(all(test, feature = "unit-tests")),
-+                expect(dead_code, reason = "only unit tests enumerate conflicted fields until #44 settles conflict iteration")
-             )]
-             pub(crate) fn for_each_conflict(
-                 &self,
-                 mut f: impl FnMut(&str, Option<&dyn std::fmt::Debug>, &dyn std::fmt::Debug),
-             ) {
-                 $(
+-            )]
+-            pub(crate) fn for_each_conflict(
+-                &self,
+-                mut f: impl FnMut(&str, Option<&dyn std::fmt::Debug>, &dyn std::fmt::Debug),
+-            ) {
+-                $(
 -                    joinable_struct!(@visit_conflict $category self . $field, f);
 -                )*
-+                    $crate::lattice::lift::VisitConflicts::visit_conflicts(
-+                        &self.$field,
-+                        &mut |key, conflict| f(stringify!($field), key, conflict),
-+                    );
-+                )+
++                    $crate::lattice::lift::ResultWrapped::is_ok(&self.$field)
++                )&&+
              }
  
 +            /// Extract the clean value, or return `self` if any field holds a
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
                      $(
 -                        $field: joinable_struct!(@unwrap $category self . $field),
 -                    )*
-+                        $field: $crate::lattice::lift::ResultValue::try_unwrap(self.$field)
++                        $field: $crate::lattice::lift::ResultWrapped::try_unwrap(self.$field)
 +                            .expect("verified all fields are 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 {
++        impl $crate::lattice::lift::ResultWrapped for $Result {
 +            type Clean = $Source;
  
 -    // --- Visit-conflict rules ---
@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: macro_rules! joinable_
              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/joinable_struct_macro.rs: macro_rules! joinable_
 +
 +    use super::sample::{Sample, SampleExt};
 +    use crate::lattice::join::Join;
-+    use crate::lattice::lift::ResultValue;
++    use crate::lattice::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 structs_lift_inside_a_map() {
++        let clean = std::collections::HashMap::from([(0u8, sample(1, 2, 3))]);
++        let lifted = clean.wrap();
++        assert_eq!(lifted[&0], sample(1, 2, 3).wrap());
++        assert_eq!(
++            ResultWrapped::try_unwrap(lifted).ok(),
++            Some(std::collections::HashMap::from([(0u8, sample(1, 2, 3))]))
++        );
++    }
++
      #[test]
      fn equal_structs_join_and_unwrap() {
          let joined = sample(1, 2, 3).wrap().join(sample(1, 2, 3).wrap());
 -        assert!(joined.is_ok());
 -        assert_eq!(joined.try_unwrap().ok(), Some(sample(1, 2, 3)));
-+        assert!(ResultValue::is_ok(&joined));
-+        assert_eq!(ResultValue::try_unwrap(joined).ok(), Some(sample(1, 2, 3)));
++        assert!(ResultWrapped::is_ok(&joined));
++        assert_eq!(
++            ResultWrapped::try_unwrap(joined).ok(),
++            Some(sample(1, 2, 3))
++        );
      }
  
      #[test]
-@@ crates/concurrent-psbt/src/psbt/joinable_struct_macro.rs: mod tests {
-                 ("map".to_owned(), Some("0".to_owned())),
+-    fn conflicting_fields_are_reported_by_name_and_key() {
++    fn conflicting_fields_retain_typed_paths() {
+         let joined = sample(1, 2, 3).wrap().join(sample(4, 5, 6).wrap());
+         assert!(!joined.is_ok());
+-        let mut fields = Vec::new();
+-        joined.for_each_conflict(|field, key, _| {
+-            fields.push((field.to_owned(), key.map(|k| format!("{k:?}"))));
+-        });
++        use super::sample::SampleField;
+         assert_eq!(
+-            fields,
++            joined.conflicts().map(|c| c.path()).collect::<Vec<_>>(),
+             [
+-                ("scalar".to_owned(), None),
+-                ("option".to_owned(), None),
+-                ("map".to_owned(), Some("0".to_owned())),
++                SampleField::Scalar,
++                SampleField::Option,
++                SampleField::Map(&0)
              ]
          );
 -        assert!(joined.try_unwrap().is_err());
-+        assert_eq!(ResultValue::try_unwrap(joined.clone()), Err(joined));
++        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/mod.rs ##
+@@
+ #[macro_use]
++mod conflict_macro;
++#[macro_use]
+ mod joinable_struct_macro;
+-pub(crate) mod global;
++pub mod global;
+ pub mod input;
+ pub mod output;
+ mod values;
+
  ## 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};
+@@ 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
 @@ 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());
 -        }
 -
 -        #[test]
 -        fn for_each_conflict_reports_every_conflicted_field() {
 -            let result = all_fields_conflict(1);
-+            let joined = with_amount(100).wrap().join(with_amount(200).wrap());
-             let mut fields = Vec::new();
+-            let mut fields = Vec::new();
 -            result.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
 -            assert_eq!(fields, ALL_CONFLICT_FIELDS);
-+            joined.for_each_conflict(|field, _, _| fields.push(field.to_owned()));
-+            assert_eq!(fields, ["amount"]);
++            let joined = with_amount(100).wrap().join(with_amount(200).wrap());
++            let fields: Vec<_> = joined.conflicts().map(|c| c.path()).collect();
++            assert_eq!(fields, [OutputField::Amount]);
 +            assert_eq!(joined.clone().try_unwrap(), Err(joined));
          }
      }
@@ crates/concurrent-psbt/src/psbt/output.rs: mod tests {
              }
  
          }
+
+ ## crates/concurrent-psbt/src/values.rs ##
+@@ crates/concurrent-psbt/src/values.rs: mod tests {
+     #[cfg(feature = "prop-tests")]
+     mod prop {
+         use super::*;
++        use crate::Lift;
+         use crate::lattice::join::Join;
+         use proptest::prelude::*;
+ 

@yuval-block yuval-block changed the title introduce Lift trait to simplify struct macro introduce Lift and Conflicts traits to simplify struct macro Nov 16, 2026
@github-actions

Copy link
Copy Markdown
range-diff for force push b72b43e9b8 → 441292fb76 November 16, 2026 03:32 UTC: 1 modified; 1 commit; same base 3e0c2248af

reproduce: git range-diff 3e0c224..b72b43e 3e0c224..441292f

1:  b72b43e9b8 +499 -635 16f ! 1:  441292fb76 +553 -636 17f Lift PSBT fields recursively and retain typed conflict paths
1: b72b43e9b8 ! 1: 441292fb76 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/psbt/global.rs
  use bitcoin::bip32::{KeySource, Xpub};
  use bitcoin::locktime::absolute;
  use bitcoin::transaction;
+ 
+ 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! {
      }
  }
@@ 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());
++        }
++    }
++}

@github-actions

Copy link
Copy Markdown
range-diff for force push 441292fb76 → 4c1849a74d November 16, 2026 03:33 UTC: 1 modified; 1 commit; same base 3e0c2248af

reproduce: git range-diff 3e0c224..441292f 3e0c224..4c1849a

1:  441292fb76 +553 -636 17f ! 1:  4c1849a74d +546 -635 17f Lift PSBT fields recursively and retain typed conflict paths
1: 441292fb76 ! 1: 4c1849a74d Lift PSBT fields recursively and retain typed conflict paths
@@ crates/concurrent-psbt/src/psbt/global.rs
  joinable_struct! {
      /// Result-domain wrapper around a BIP 370 [`Global`].
 @@ 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 {
+     /// [`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());
 -        }
 -

@github-actions

Copy link
Copy Markdown
range-diff for force push 4c1849a74d → 4bc24cac39 November 16, 2026 03:40 UTC: 1 modified; 1 commit; same base 3e0c2248af

reproduce: git range-diff 3e0c224..4c1849a 3e0c224..4bc24ca

1:  4c1849a74d +546 -635 17f ! 1:  4bc24cac39 +551 -635 17f Lift PSBT fields recursively and retain typed conflict paths
1: 4c1849a74d ! 1: 4bc24cac39 Lift PSBT fields recursively and retain typed conflict paths
@@ 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: `joinable_struct!` subsumes this when PR #109 introduces our own
++//! PSBT structs, using one field list for the structs and their conflict API.
++
 +macro_rules! record_conflicts {
 +    (
 +        $Result:ident, $Conflict:ident, $Field:ident {

@yuval-block
yuval-block marked this pull request as ready for review November 16, 2026 03:46
@github-actions

Copy link
Copy Markdown
range-diff for force push 4bc24cac39 → 26f6320adb November 16, 2026 04:18 UTC: 1 modified; 1 commit; same base 3e0c2248af

reproduce: git range-diff 3e0c224..4bc24ca 3e0c224..26f6320

1:  4bc24cac39 +551 -635 17f ! 1:  26f6320adb +551 -635 17f Lift PSBT fields recursively and retain typed conflict paths
1: 4bc24cac39 ! 1: 26f6320adb Lift PSBT fields recursively and retain typed conflict paths
@@ crates/concurrent-psbt/src/psbt/conflict_macro.rs (new)
 @@
 +//! Generates typed conflict enums for the external PSBT types.
 +//!
-+//! Temporary: `joinable_struct!` subsumes this when PR #109 introduces our own
-+//! PSBT structs, using one field list for the structs and their conflict API.
++//! Temporary until `joinable_struct!` defines the source structs and generates
++//! their conflict API from the same field list.
 +
 +macro_rules! record_conflicts {
 +    (

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>
@github-actions

Copy link
Copy Markdown
range-diff for force push 26f6320adb → 0e4597c7b1 November 16, 2026 04:51 UTC: 1 modified; 1 commit; same base 3e0c2248af

reproduce: git range-diff 3e0c224..26f6320 3e0c224..0e4597c

1:  26f6320adb +551 -635 17f ! 1:  0e4597c7b1 +584 -661 18f Lift PSBT fields recursively and retain typed conflict paths
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")]

@oakagent

Copy link
Copy Markdown

@yuval-block 0e4597c is clean; the ACK waits on the description:

  • Not mentioned: concurrent_psbt::global is now public, exposing Global and its conflict enums. (crates/concurrent-psbt/src/psbt/mod.rs:5)

oakagent · automated

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants