From 6c068f50684735d714efbbcab0a856aa6d7c561f Mon Sep 17 00:00:00 2001 From: bitgobot Date: Wed, 11 Nov 2026 06:34:17 +0000 Subject: [PATCH] fix: evaluate satisfier outcomes once per node Compute satisfaction and dissatisfaction in post-order and reuse child outcomes, preventing nested branches from consuming exponential CPU. Check context resource limits before satisfaction and template building to reject invalid untrusted descriptors and PSBT scripts early. Cover nested branch complexity, resource boundaries, descriptor plans, and signed PSBT finalization. Document the stricter resource checks. Ticket: CSHLD-2226 Signed-off-by: Mukesh Mahadev Prajapati --- CHANGELOG.md | 10 + src/miniscript/mod.rs | 212 ++++++++++++++- src/miniscript/satisfy.rs | 418 +++++++++++++----------------- src/policy/concrete.rs | 2 +- tests/satisfaction_regressions.rs | 298 +++++++++++++++++++++ 5 files changed, 694 insertions(+), 246 deletions(-) create mode 100644 tests/satisfaction_regressions.rs diff --git a/CHANGELOG.md b/CHANGELOG.md index d52c78b49..f577cbe20 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +# Unreleased + +- Evaluate satisfaction and dissatisfaction once per Miniscript node in post-order, + avoiding exponential recomputation in nested branches. Witness copying remains + polynomial in script size; evaluation no longer recurses through subtrees. +- Check context consensus and standardness resource limits before satisfaction or + template construction, including scripts decoded with relaxed parsing options. + Resource-invalid satisfaction returns a context error; planning templates are + impossible. This also protects descriptor planning and PSBT finalization. + # # 12.3.1 - April 1, 2025 - Silent fix for CVE-2025-43707 (crash on satisfaction of particularly crafted `thresh` fragments) [#798](https://github.com/rust-bitcoin/rust-miniscript/pull/798) diff --git a/src/miniscript/mod.rs b/src/miniscript/mod.rs index a36cef547..31d128b87 100644 --- a/src/miniscript/mod.rs +++ b/src/miniscript/mod.rs @@ -433,11 +433,15 @@ impl Miniscript { } /// Attempt to produce non-malleable satisfying witness for the - /// witness script represented by the parse tree + /// witness script represented by the parse tree. + /// + /// Checks the context consensus and standardness resource limits before + /// querying the satisfier. pub fn satisfy>(&self, satisfier: S) -> Result>, Error> where Pk: ToPublicKey, { + Ctx::check_local_validity(self)?; // Only satisfactions for default versions (0xc0) are allowed. let satisfaction = satisfy::Satisfaction::satisfy( &self.node, @@ -449,7 +453,10 @@ impl Miniscript { } /// Attempt to produce a malleable satisfying witness for the - /// witness script represented by the parse tree + /// witness script represented by the parse tree. + /// + /// Checks the context consensus and standardness resource limits before + /// querying the satisfier. pub fn satisfy_malleable>( &self, satisfier: S, @@ -457,6 +464,7 @@ impl Miniscript { where Pk: ToPublicKey, { + Ctx::check_local_validity(self)?; let satisfaction = satisfy::Satisfaction::satisfy_mall( &self.node, &satisfier, @@ -481,7 +489,10 @@ impl Miniscript { } } - /// Attempt to produce a non-malleable witness template given the assets available + /// Attempt to produce a non-malleable witness template given the assets available. + /// + /// Returns an impossible template without querying the provider if the + /// context consensus or standardness resource limits are exceeded. pub fn build_template>( &self, provider: &P, @@ -489,6 +500,14 @@ impl Miniscript { where Pk: ToPublicKey, { + if Ctx::check_local_validity(self).is_err() { + return satisfy::Satisfaction { + stack: satisfy::Witness::Impossible, + has_sig: false, + absolute_timelock: None, + relative_timelock: None, + }; + } satisfy::Satisfaction::build_template( &self.node, provider, @@ -497,7 +516,10 @@ impl Miniscript { ) } - /// Attempt to produce a malleable witness template given the assets available + /// Attempt to produce a malleable witness template given the assets available. + /// + /// Returns an impossible template without querying the provider if the + /// context consensus or standardness resource limits are exceeded. pub fn build_template_mall>( &self, provider: &P, @@ -505,6 +527,14 @@ impl Miniscript { where Pk: ToPublicKey, { + if Ctx::check_local_validity(self).is_err() { + return satisfy::Satisfaction { + stack: satisfy::Witness::Impossible, + has_sig: false, + absolute_timelock: None, + relative_timelock: None, + }; + } satisfy::Satisfaction::build_template_mall( &self.node, provider, @@ -1883,6 +1913,180 @@ mod tests { Tapscript::decode_insane(&script.into_script()).unwrap_err(); } + // Any lookup proves resource validation happened too late. + struct NoResourceLookups; + + impl Satisfier for NoResourceLookups { + fn lookup_ecdsa_sig(&self, _: &Pk) -> Option { + panic!("resource-invalid scripts must not query signatures") + } + + fn lookup_tap_leaf_script_sig( + &self, + _: &Pk, + _: &TapLeafHash, + ) -> Option { + panic!("resource-invalid scripts must not query signatures") + } + + fn lookup_raw_pkh_pk(&self, _: &hash160::Hash) -> Option { + panic!("resource-invalid scripts must not query public keys") + } + + fn lookup_raw_pkh_ecdsa_sig( + &self, + _: &hash160::Hash, + ) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> { + panic!("resource-invalid scripts must not query signatures") + } + + fn check_after(&self, _: bitcoin::absolute::LockTime) -> bool { + panic!("resource-invalid scripts must not query timelocks") + } + } + + fn assert_resource_rejected(ms: &Miniscript) + where + Pk: crate::MiniscriptKey + ToPublicKey, + Ctx: ScriptContext, + { + let error = Ctx::check_local_validity(ms).unwrap_err(); + for template in [ + ms.build_template(&NoResourceLookups), + ms.build_template_mall(&NoResourceLookups), + ] { + assert_eq!(template.stack, crate::miniscript::satisfy::Witness::Impossible); + assert!(!template.has_sig); + assert_eq!(template.absolute_timelock, None); + assert_eq!(template.relative_timelock, None); + } + assert!(matches!(ms.satisfy(NoResourceLookups), Err(Error::ContextError(e)) if e == error)); + assert!( + matches!(ms.satisfy_malleable(NoResourceLookups), Err(Error::ContextError(e)) if e == error) + ); + } + + fn resource_timelock_script(verified_locks: usize) -> bitcoin::ScriptBuf { + let mut builder = bitcoin::script::Builder::new(); + for _ in 0..verified_locks { + builder = builder + .push_int(1) + .push_opcode(bitcoin::opcodes::all::OP_CLTV) + .push_opcode(bitcoin::opcodes::all::OP_VERIFY); + } + builder + .push_int(1) + .push_opcode(bitcoin::opcodes::all::OP_CLTV) + .into_script() + } + + #[test] + fn satisfaction_resource_limits_reject_decoded_opcode_overflow() { + let script = resource_timelock_script(101); + let legacy = Miniscript::::decode_insane(&script).unwrap(); + let bare = Miniscript::::decode_insane(&script).unwrap(); + let segwit = Segwitv0Script::decode_insane(&script).unwrap(); + assert_eq!(segwit.ext.ops.op_count(), Some(203)); + assert_resource_rejected(&legacy); + assert_resource_rejected(&bare); + assert_resource_rejected(&segwit); + } + + #[test] + fn satisfaction_resource_limits_reject_decoded_witness_overflow() { + let key = pubkeys(1)[0]; + let multi = format!("multi(20,{})", vec![key.to_string(); 20].join(",")); + let source = format!("and_v(v:{},", multi).repeat(4) + &multi + &")".repeat(4); + let script = Segwitv0Script::from_str_insane(&source).unwrap().encode(); + let ms = Segwitv0Script::decode_insane(&script).unwrap(); + assert_eq!(ms.max_satisfaction_witness_elements().unwrap(), 106); + assert!(matches!( + Segwitv0::check_local_validity(&ms), + Err(crate::miniscript::context::ScriptContextError::MaxWitnessItemsExceeded { + actual: 106, + limit: 100, + }) + )); + assert_resource_rejected(&ms); + } + + #[test] + fn satisfaction_resource_limits_reject_decoded_scriptsig_overflow() { + let pkh = format!("pkh({})", pubkeys(1)[0]); + let source = format!("and_v(v:{},", pkh).repeat(15) + &pkh + &")".repeat(15); + let script = Miniscript::::from_str_insane(&source) + .unwrap() + .encode(); + let ms = Miniscript::::decode_with_ext( + &script, + &ExtParams::allow_all(), + ) + .unwrap(); + assert!(matches!( + Legacy::check_local_validity(&ms), + Err(crate::miniscript::context::ScriptContextError::MaxScriptSigSizeExceeded { + limit: 1650, + .. + }) + )); + assert_resource_rejected(&ms); + } + + #[test] + fn satisfaction_resource_limits_reject_decoded_tap_stack_overflow() { + let key = pubkeys(1)[0].inner.x_only_public_key().0; + let multi = format!("multi_a(1,{})", vec![key.to_string(); 999].join(",")); + let source = format!("and_v(v:{},pk({}))", multi, key); + let script = Tapscript::from_str_insane(&source).unwrap().encode(); + let ms = Tapscript::decode_insane(&script).unwrap(); + assert!(matches!( + Tap::check_local_validity(&ms), + Err(crate::miniscript::context::ScriptContextError::StackSizeLimitExceeded { + limit: 1000, + .. + }) + )); + assert_resource_rejected(&ms); + } + + fn assert_valid_resource_timelocks() { + let ms = + Miniscript::::decode_insane(&resource_timelock_script(100)).unwrap(); + assert_eq!(ms.ext.ops.op_count(), Some(201)); + let locktime = bitcoin::absolute::LockTime::from_height(1).unwrap(); + for template in [ + ms.build_template(&locktime), + ms.build_template_mall(&locktime), + ] { + assert_eq!(template.stack, crate::miniscript::satisfy::Witness::Stack(vec![])); + assert_eq!( + template.absolute_timelock, + Some(crate::AbsLockTime::from_consensus(1).unwrap()) + ); + } + assert_eq!(ms.satisfy(locktime).unwrap(), Vec::>::new()); + assert_eq!(ms.satisfy_malleable(locktime).unwrap(), Vec::>::new()); + } + + #[test] + fn satisfaction_resource_limits_preserve_valid_decoded_scripts() { + assert_valid_resource_timelocks::(); + assert_valid_resource_timelocks::(); + assert_valid_resource_timelocks::(); + // Tapscript does not have the pre-Taproot 201-opcode limit. + assert_valid_resource_timelocks::(); + let ms = Tapscript::decode_insane(&resource_timelock_script(101)).unwrap(); + let locktime = bitcoin::absolute::LockTime::from_height(1).unwrap(); + for template in [ + ms.build_template(&locktime), + ms.build_template_mall(&locktime), + ] { + assert_eq!(template.stack, crate::miniscript::satisfy::Witness::Stack(vec![])); + } + assert_eq!(ms.satisfy(locktime).unwrap(), Vec::>::new()); + assert_eq!(ms.satisfy_malleable(locktime).unwrap(), Vec::>::new()); + } + #[test] fn test_context_global_consensus() { // Test from string tests diff --git a/src/miniscript/satisfy.rs b/src/miniscript/satisfy.rs index 25c781798..98dbc0dcf 100644 --- a/src/miniscript/satisfy.rs +++ b/src/miniscript/satisfy.rs @@ -15,6 +15,7 @@ use bitcoin::{absolute, relative, ScriptBuf, Sequence}; use sync::Arc; use super::context::SigType; +use crate::iter::TreeLike; use crate::plan::AssetProvider; use crate::prelude::*; use crate::util::witness_size; @@ -892,6 +893,11 @@ pub struct Satisfaction { pub relative_timelock: Option, } +// Node addresses are stable while building a template. Structural keys would recursively +// compare subtrees; pointer identity also keeps distinct occurrences independent. +type SatisfactionCache = + BTreeMap<(*const Terminal, bool), Satisfaction>>; + impl Satisfaction> { /// The empty satisfaction. /// @@ -931,14 +937,27 @@ impl Satisfaction> { Ctx: ScriptContext, P: AssetProvider, { - Self::satisfy_helper( - term, - provider, - root_has_sig, - leaf_hash, - &mut Satisfaction::minimum, - &mut Satisfaction::thresh, - ) + let mut cache = BTreeMap::new(); + // Both child outcomes are available before evaluating their parent. + // Witnesses may be copied, but subtrees are never re-evaluated. + for item in term.post_order_iter() { + let result = Self::satisfy_step( + item.node, + provider, + root_has_sig, + leaf_hash, + &mut Self::minimum, + &mut Self::thresh, + &cache, + ); + cache.insert((item.node as *const _, true), result); + let result = Self::dissatisfy_step(item.node, provider, &cache); + cache.insert((item.node as *const _, false), result); + } + // The post-order pass always includes the root satisfaction. + cache + .remove(&(term as *const _, true)) + .expect("root satisfaction was evaluated") } pub(crate) fn build_template_mall( @@ -951,58 +970,54 @@ impl Satisfaction> { Ctx: ScriptContext, P: AssetProvider, { - Self::satisfy_helper( - term, - provider, - root_has_sig, - leaf_hash, - &mut Satisfaction::minimum_mall, - &mut Satisfaction::thresh_mall, - ) + let mut cache = BTreeMap::new(); + // Both child outcomes are available before evaluating their parent. + // Witnesses may be copied, but subtrees are never re-evaluated. + for item in term.post_order_iter() { + let result = Self::satisfy_step( + item.node, + provider, + root_has_sig, + leaf_hash, + &mut Self::minimum_mall, + &mut Self::thresh_mall, + &cache, + ); + cache.insert((item.node as *const _, true), result); + let result = Self::dissatisfy_step(item.node, provider, &cache); + cache.insert((item.node as *const _, false), result); + } + // The post-order pass always includes the root satisfaction. + cache + .remove(&(term as *const _, true)) + .expect("root satisfaction was evaluated") + } + + fn cached( + cache: &SatisfactionCache, + term: &Terminal, + satisfied: bool, + ) -> Self { + // Post-order evaluation inserts both child outcomes before visiting the parent. + cache + .get(&(term as *const _, satisfied)) + .expect("child outcomes were evaluated") + .clone() } // produce a non-malleable satisafaction for thesh frag - fn thresh( + fn thresh( thresh: &Threshold>, 0>, - stfr: &Sat, - root_has_sig: bool, - leaf_hash: &TapLeafHash, - min_fn: &mut F, - ) -> Self - where - Ctx: ScriptContext, - Sat: AssetProvider, - F: FnMut( - Satisfaction>, - Satisfaction>, - ) -> Satisfaction>, - { + cache: &SatisfactionCache, + ) -> Self { let mut sats = thresh .iter() - .map(|s| { - Self::satisfy_helper( - &s.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - &mut Self::thresh, - ) - }) + .map(|s| Self::cached(cache, &s.node, true)) .collect::>(); // Start with the to-return stack set to all dissatisfactions let mut ret_stack = thresh .iter() - .map(|s| { - Self::dissatisfy_helper( - &s.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - &mut Self::thresh, - ) - }) + .map(|s| Self::cached(cache, &s.node, false)) .collect::>(); // Sort everything by (sat cost - dissat cost), except that @@ -1080,47 +1095,18 @@ impl Satisfaction> { } // produce a possily malleable satisafaction for thesh frag - fn thresh_mall( + fn thresh_mall( thresh: &Threshold>, 0>, - stfr: &Sat, - root_has_sig: bool, - leaf_hash: &TapLeafHash, - min_fn: &mut F, - ) -> Self - where - Ctx: ScriptContext, - Sat: AssetProvider, - F: FnMut( - Satisfaction>, - Satisfaction>, - ) -> Satisfaction>, - { + cache: &SatisfactionCache, + ) -> Self { let mut sats = thresh .iter() - .map(|s| { - Self::satisfy_helper( - &s.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - &mut Self::thresh_mall, - ) - }) + .map(|s| Self::cached(cache, &s.node, true)) .collect::>(); // Start with the to-return stack set to all dissatisfactions let mut ret_stack = thresh .iter() - .map(|s| { - Self::dissatisfy_helper( - &s.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - &mut Self::thresh_mall, - ) - }) + .map(|s| Self::cached(cache, &s.node, false)) .collect::>(); // Sort everything by (sat cost - dissat cost), except that @@ -1227,13 +1213,14 @@ impl Satisfaction> { } // produce a non-malleable satisfaction - fn satisfy_helper( + fn satisfy_step( term: &Terminal, stfr: &Sat, root_has_sig: bool, leaf_hash: &TapLeafHash, min_fn: &mut F, thresh_fn: &mut G, + cache: &SatisfactionCache, ) -> Self where Ctx: ScriptContext, @@ -1244,10 +1231,7 @@ impl Satisfaction> { ) -> Satisfaction>, G: FnMut( &Threshold>, 0>, - &Sat, - bool, - &TapLeafHash, - &mut F, + &SatisfactionCache, ) -> Satisfaction>, { match *term { @@ -1346,18 +1330,9 @@ impl Satisfaction> { | Terminal::Check(ref sub) | Terminal::Verify(ref sub) | Terminal::NonZero(ref sub) - | Terminal::ZeroNotEqual(ref sub) => { - Self::satisfy_helper(&sub.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn) - } + | Terminal::ZeroNotEqual(ref sub) => Self::cached(cache, &sub.node, true), Terminal::DupIf(ref sub) => { - let sat = Self::satisfy_helper( - &sub.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); + let sat = Self::cached(cache, &sub.node, true); Satisfaction { stack: Witness::combine(sat.stack, Witness::push_1()), has_sig: sat.has_sig, @@ -1366,51 +1341,23 @@ impl Satisfaction> { } } Terminal::AndV(ref l, ref r) | Terminal::AndB(ref l, ref r) => { - let l_sat = - Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let r_sat = - Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); + let l_sat = Self::cached(cache, &l.node, true); + let r_sat = Self::cached(cache, &r.node, true); l_sat.concatenate_rev(r_sat) } Terminal::AndOr(ref a, ref b, ref c) => { - let a_sat = - Self::satisfy_helper(&a.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let a_nsat = Self::dissatisfy_helper( - &a.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); - let b_sat = - Self::satisfy_helper(&b.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let c_sat = - Self::satisfy_helper(&c.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); + let a_sat = Self::cached(cache, &a.node, true); + let a_nsat = Self::cached(cache, &a.node, false); + let b_sat = Self::cached(cache, &b.node, true); + let c_sat = Self::cached(cache, &c.node, true); min_fn(a_sat.concatenate_rev(b_sat), a_nsat.concatenate_rev(c_sat)) } Terminal::OrB(ref l, ref r) => { - let l_sat = - Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let r_sat = - Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let l_nsat = Self::dissatisfy_helper( - &l.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); - let r_nsat = Self::dissatisfy_helper( - &r.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); + let l_sat = Self::cached(cache, &l.node, true); + let r_sat = Self::cached(cache, &r.node, true); + let l_nsat = Self::cached(cache, &l.node, false); + let r_nsat = Self::cached(cache, &r.node, false); assert!(!l_nsat.has_sig); assert!(!r_nsat.has_sig); @@ -1421,28 +1368,17 @@ impl Satisfaction> { ) } Terminal::OrD(ref l, ref r) | Terminal::OrC(ref l, ref r) => { - let l_sat = - Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let r_sat = - Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let l_nsat = Self::dissatisfy_helper( - &l.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); + let l_sat = Self::cached(cache, &l.node, true); + let r_sat = Self::cached(cache, &r.node, true); + let l_nsat = Self::cached(cache, &l.node, false); assert!(!l_nsat.has_sig); min_fn(l_sat, Satisfaction::concatenate_rev(l_nsat, r_sat)) } Terminal::OrI(ref l, ref r) => { - let l_sat = - Self::satisfy_helper(&l.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let r_sat = - Self::satisfy_helper(&r.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); + let l_sat = Self::cached(cache, &l.node, true); + let r_sat = Self::cached(cache, &r.node, true); min_fn( Satisfaction { stack: Witness::combine(l_sat.stack, Witness::push_1()), @@ -1463,19 +1399,10 @@ impl Satisfaction> { // this is just an and thresh .iter() - .map(|s| { - Self::satisfy_helper( - &s.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ) - }) + .map(|s| Self::cached(cache, &s.node, true)) .fold(Satisfaction::empty(), Satisfaction::concatenate_rev) } else { - thresh_fn(thresh, stfr, root_has_sig, leaf_hash, min_fn) + thresh_fn(thresh, cache) } } Terminal::Multi(ref thresh) => { @@ -1570,29 +1497,11 @@ impl Satisfaction> { } // Helper function to produce a dissatisfaction - fn dissatisfy_helper( + fn dissatisfy_step>( term: &Terminal, stfr: &Sat, - root_has_sig: bool, - leaf_hash: &TapLeafHash, - min_fn: &mut F, - thresh_fn: &mut G, - ) -> Self - where - Ctx: ScriptContext, - Sat: AssetProvider, - F: FnMut( - Satisfaction>, - Satisfaction>, - ) -> Satisfaction>, - G: FnMut( - &Threshold>, 0>, - &Sat, - bool, - &TapLeafHash, - &mut F, - ) -> Satisfaction>, - { + cache: &SatisfactionCache, + ) -> Self { match *term { Terminal::PkK(..) => Satisfaction { stack: Witness::push_0(), @@ -1646,9 +1555,7 @@ impl Satisfaction> { Terminal::Alt(ref sub) | Terminal::Swap(ref sub) | Terminal::Check(ref sub) - | Terminal::ZeroNotEqual(ref sub) => { - Self::dissatisfy_helper(&sub.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn) - } + | Terminal::ZeroNotEqual(ref sub) => Self::cached(cache, &sub.node, false), Terminal::DupIf(_) | Terminal::NonZero(_) => Satisfaction { stack: Witness::push_0(), has_sig: false, @@ -1656,49 +1563,20 @@ impl Satisfaction> { absolute_timelock: None, }, Terminal::AndV(ref v, ref other) => { - let vsat = - Self::satisfy_helper(&v.node, stfr, root_has_sig, leaf_hash, min_fn, thresh_fn); - let odissat = Self::dissatisfy_helper( - &other.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); + let vsat = Self::cached(cache, &v.node, true); + let odissat = Self::cached(cache, &other.node, false); vsat.concatenate_rev(odissat) } Terminal::AndB(ref l, ref r) | Terminal::OrB(ref l, ref r) | Terminal::OrD(ref l, ref r) | Terminal::AndOr(ref l, _, ref r) => { - let lnsat = Self::dissatisfy_helper( - &l.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); - let rnsat = Self::dissatisfy_helper( - &r.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); + let lnsat = Self::cached(cache, &l.node, false); + let rnsat = Self::cached(cache, &r.node, false); lnsat.concatenate_rev(rnsat) } Terminal::OrI(ref l, ref r) => { - let lnsat = Self::dissatisfy_helper( - &l.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); + let lnsat = Self::cached(cache, &l.node, false); let dissat_1 = Satisfaction { stack: Witness::combine(lnsat.stack, Witness::push_1()), has_sig: lnsat.has_sig, @@ -1706,14 +1584,7 @@ impl Satisfaction> { absolute_timelock: None, }; - let rnsat = Self::dissatisfy_helper( - &r.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); + let rnsat = Self::cached(cache, &r.node, false); let dissat_2 = Satisfaction { stack: Witness::combine(rnsat.stack, Witness::push_0()), has_sig: rnsat.has_sig, @@ -1726,16 +1597,7 @@ impl Satisfaction> { } Terminal::Thresh(ref thresh) => thresh .iter() - .map(|s| { - Self::dissatisfy_helper( - &s.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ) - }) + .map(|s| Self::cached(cache, &s.node, false)) .fold(Satisfaction::empty(), Satisfaction::concatenate_rev), Terminal::Multi(ref thresh) => Satisfaction { stack: Witness::Stack(vec![Placeholder::PushZero; thresh.k() + 1]), @@ -1809,3 +1671,77 @@ impl Satisfaction> { .expect("the same satisfier should manage to complete the template") } } + +#[cfg(test)] +mod tests { + use core::cell::Cell; + use core::str::FromStr; + + use bitcoin::key::XOnlyPublicKey; + + use super::*; + use crate::{ExtParams, Tap}; + + struct CountingAssets { + calls: Cell, + available: Cell, + } + + impl AssetProvider for CountingAssets { + fn provider_lookup_tap_leaf_script_sig( + &self, + _: &XOnlyPublicKey, + _: &TapLeafHash, + ) -> Option { + self.calls.set(self.calls.get() + 1); + if self.available.get() { + Some(64) + } else { + None + } + } + } + + #[test] + fn nested_branch_planning_queries_each_key_once() { + let key = XOnlyPublicKey::from_str( + "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", + ) + .unwrap(); + let depth = 100; + for branch in 0..4 { + let mut script = format!("pk({})", key); + for _ in 0..depth { + script = match branch { + 0 => format!("or_b(utv:{},s:pk({}))", script, key), + 1 => format!("or_d(utv:{},pk({}))", script, key), + 2 => format!("andor(utv:{},pk({}),pk({}))", script, key, key), + _ => format!("thresh(1,utv:{},s:pk({}))", script, key), + }; + } + let ms = + Miniscript::::from_str_ext(&script, &ExtParams::allow_all()) + .unwrap(); + let assets = CountingAssets { calls: Cell::new(0), available: Cell::new(true) }; + let expected_calls = 1 + depth * if branch == 2 { 2 } else { 1 }; + for malleable in [false, true] { + for available in [true, false] { + assets.calls.set(0); + assets.available.set(available); + let sat = if malleable { + ms.build_template_mall(&assets) + } else { + ms.build_template(&assets) + }; + if available { + assert!(matches!(sat.stack, Witness::Stack(_))); + assert!(sat.has_sig); + } else { + assert_eq!(sat.stack, Witness::Impossible); + } + assert_eq!(assets.calls.get(), expected_calls); + } + } + } + } +} diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 547b4e86d..f4ac8a03a 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -346,7 +346,7 @@ impl Policy { /// /// It is **not recommended** to use policy as a stable identifier for a miniscript. You should /// use the policy compiler once, and then use the miniscript output as a stable identifier. See - /// the compiler document in [`doc/compiler.md`] for more details. + /// the compiler document in doc/compiler.md for more details. #[cfg(feature = "compiler")] pub fn compile_to_descriptor( &self, diff --git a/tests/satisfaction_regressions.rs b/tests/satisfaction_regressions.rs new file mode 100644 index 000000000..6f88bb6e4 --- /dev/null +++ b/tests/satisfaction_regressions.rs @@ -0,0 +1,298 @@ +// SPDX-License-Identifier: CC0-1.0 + +use std::str::FromStr; + +use bitcoin::psbt::Psbt; +use bitcoin::secp256k1::{Keypair, PublicKey as SecpPublicKey, Secp256k1, SecretKey}; +use bitcoin::sighash::{EcdsaSighashType, SighashCache, TapSighashType}; +use bitcoin::taproot::{LeafVersion, TapLeafHash}; +use bitcoin::{ + absolute, transaction, Amount, PublicKey, ScriptBuf, Sequence, Transaction, TxIn, TxOut, +}; +use miniscript::plan::Assets; +use miniscript::psbt::{self, InputError, PsbtExt, PsbtInputExt}; +use miniscript::{DefiniteDescriptorKey, Descriptor, DescriptorPublicKey, Error}; + +fn signing_keys(count: u8) -> Vec<(SecretKey, PublicKey)> { + let secp = Secp256k1::new(); + (1..=count) + .map(|index| { + let secret = SecretKey::from_slice(&[index; 32]).unwrap(); + let public = PublicKey::new(SecpPublicKey::from_secret_key(&secp, &secret)); + (secret, public) + }) + .collect() +} + +fn signature_chain(keys: &[(SecretKey, PublicKey)]) -> String { + let mut script = format!("pk({})", keys.last().unwrap().1); + for (_, key) in keys[..keys.len() - 1].iter().rev() { + script = format!("and_v(v:pk({}),{})", key, script); + } + script +} + +fn psbt_for_descriptor(descriptor: &Descriptor) -> Psbt { + let transaction = Transaction { + version: transaction::Version::TWO, + lock_time: absolute::LockTime::ZERO, + input: vec![TxIn { sequence: Sequence::from_height(1), ..Default::default() }], + output: vec![TxOut { value: Amount::from_sat(9_000), script_pubkey: ScriptBuf::new() }], + }; + let mut psbt = Psbt::from_unsigned_tx(transaction).unwrap(); + psbt.inputs[0].witness_utxo = + Some(TxOut { value: Amount::from_sat(10_000), script_pubkey: descriptor.script_pubkey() }); + psbt.inputs[0] + .update_with_descriptor_unchecked(descriptor) + .unwrap(); + psbt +} + +#[test] +fn descriptor_plans_deep_signature_chains() { + for (taproot, depth) in [(false, 32), (true, 100)] { + let keys = signing_keys((depth + 2) as u8); + let script = signature_chain(&keys[..depth + 1]); + let descriptor = if taproot { + format!("tr({},{})", keys[depth + 1].1, script) + } else { + format!("wsh({})", script) + }; + let descriptor = Descriptor::::from_str(&descriptor).unwrap(); + descriptor.sanity_check().unwrap(); + let assets = Assets::new().add( + keys[..depth + 1] + .iter() + .map(|(_, key)| DescriptorPublicKey::from_str(&key.to_string()).unwrap()) + .collect::>(), + ); + + assert_eq!(descriptor.clone().plan(&Assets::new()).unwrap_err(), descriptor); + assert_eq!(descriptor.clone().plan_mall(&Assets::new()).unwrap_err(), descriptor); + for plan in [ + descriptor.clone().plan(&assets), + descriptor.clone().plan_mall(&assets), + ] { + let plan = plan.unwrap(); + assert_eq!(plan.witness_template().len(), depth + 1 + if taproot { 2 } else { 0 }); + assert_eq!(plan.absolute_timelock, None); + assert_eq!(plan.relative_timelock, None); + let mut input = bitcoin::psbt::Input::default(); + plan.update_psbt_input(&mut input); + if taproot { + assert_eq!(input.tap_scripts.len(), 1); + assert!(input.tap_internal_key.is_none()); + } else { + assert_eq!(input.witness_script, Some(descriptor.explicit_script().unwrap())); + } + } + } +} + +#[test] +fn descriptor_plans_bounded_branching_chain() { + let keys = signing_keys(10); + let mut script = format!("pk({})", keys[8].1); + for (_, key) in keys[..8].iter().rev() { + script = format!("or_d(pk({}),{})", key, script); + } + for descriptor in [ + format!("wsh({})", script), + format!("tr({},{})", keys[9].1, script), + ] { + let descriptor = Descriptor::::from_str(&descriptor).unwrap(); + let assets = + Assets::new().add(DescriptorPublicKey::from_str(&keys[0].1.to_string()).unwrap()); + assert_eq!(descriptor.clone().plan(&Assets::new()).unwrap_err(), descriptor); + assert_eq!(descriptor.clone().plan_mall(&Assets::new()).unwrap_err(), descriptor); + let plan = descriptor.clone().plan(&assets).unwrap(); + let malleable_plan = descriptor.plan_mall(&assets).unwrap(); + assert_eq!(plan.witness_template(), malleable_plan.witness_template()); + assert_eq!( + plan.witness_template().len(), + if plan.witness_version() == Some(bitcoin::WitnessVersion::V1) { + 3 + } else { + 1 + } + ); + } +} + +#[test] +fn psbt_finalize_deep_signed_chains() { + let secp = Secp256k1::new(); + for (taproot, depth) in [(false, 32), (true, 100)] { + let keys = signing_keys((depth + 2) as u8); + let script = signature_chain(&keys[..depth + 1]); + let descriptor = if taproot { + format!("tr({},{})", keys[depth + 1].1, script) + } else { + format!("wsh({})", script) + }; + let descriptor = Descriptor::::from_str(&descriptor).unwrap(); + let mut psbt = psbt_for_descriptor(&descriptor); + let (script, control_block) = if taproot { + let (control_block, (script, version)) = + psbt.inputs[0].tap_scripts.iter().next().unwrap(); + assert_eq!(*version, LeafVersion::TapScript); + (script.clone(), Some(control_block.serialize())) + } else { + (psbt.inputs[0].witness_script.clone().unwrap(), None) + }; + let leaf_hash = if taproot { + Some(TapLeafHash::from_script(&script, LeafVersion::TapScript)) + } else { + None + }; + + let (unfinalized, errors) = psbt.clone().finalize(&secp).unwrap_err(); + assert_eq!(unfinalized, psbt); + assert_eq!(errors.len(), 1); + if taproot { + assert!(matches!(errors[0], psbt::Error::InputError(InputError::CouldNotSatisfyTr, 0))); + } else { + assert!(matches!( + errors[0], + psbt::Error::InputError(InputError::MiniscriptError(Error::CouldNotSatisfy), 0) + )); + } + + let message = psbt + .sighash_msg(0, &mut SighashCache::new(&psbt.unsigned_tx), leaf_hash) + .unwrap() + .to_secp_msg(); + let mut signatures = Vec::new(); + for (secret, public) in &keys[..depth + 1] { + let signature = if let Some(leaf_hash) = leaf_hash { + let keypair = Keypair::from_secret_key(&secp, secret); + let signature = bitcoin::taproot::Signature { + signature: secp.sign_schnorr_no_aux_rand(&message, &keypair), + sighash_type: TapSighashType::Default, + }; + psbt.inputs[0] + .tap_script_sigs + .insert((public.inner.x_only_public_key().0, leaf_hash), signature); + signature.to_vec() + } else { + let signature = bitcoin::ecdsa::Signature { + signature: secp.sign_ecdsa(&message, secret), + sighash_type: EcdsaSighashType::All, + }; + psbt.inputs[0].partial_sigs.insert(*public, signature); + signature.to_vec() + }; + signatures.push(signature); + } + signatures.reverse(); + signatures.push(script.into_bytes()); + if let Some(control_block) = control_block { + signatures.push(control_block); + } + + for finalized in [psbt.clone().finalize(&secp), psbt.finalize_mall(&secp)] { + let finalized = finalized.unwrap(); + assert!(finalized.inputs[0].final_script_sig.is_none()); + assert_eq!( + finalized.inputs[0] + .final_script_witness + .as_ref() + .unwrap() + .to_vec(), + signatures + ); + finalized.extract(&secp).unwrap(); + } + } +} + +#[test] +fn over_op_limit_wsh_is_rejected_with_sufficient_assets() { + let keys = signing_keys(1); + let mut script = format!("pk({})", keys[0].1); + // Each verified CSV adds two counted opcodes; the final CHECKSIG adds one. + for _ in 0..101 { + script = format!("and_v(v:older(1),{})", script); + } + let descriptor = + Descriptor::::from_str(&format!("wsh({})", script)).unwrap(); + let assets = Assets::new() + .add(DescriptorPublicKey::from_str(&keys[0].1.to_string()).unwrap()) + .older(Sequence::from_height(1).to_relative_lock_time().unwrap()); + assert_eq!(descriptor.clone().plan(&assets).unwrap_err(), descriptor); + assert_eq!(descriptor.clone().plan_mall(&assets).unwrap_err(), descriptor); + + let secp = Secp256k1::new(); + let mut psbt = psbt_for_descriptor(&descriptor); + let message = psbt + .sighash_msg(0, &mut SighashCache::new(&psbt.unsigned_tx), None) + .unwrap() + .to_secp_msg(); + psbt.inputs[0].partial_sigs.insert( + keys[0].1, + bitcoin::ecdsa::Signature { + signature: secp.sign_ecdsa(&message, &keys[0].0), + sighash_type: EcdsaSighashType::All, + }, + ); + for result in [ + psbt.clone().finalize(&secp), + psbt.clone().finalize_mall(&secp), + ] { + let (unfinalized, errors) = result.unwrap_err(); + assert_eq!(unfinalized, psbt); + assert_eq!(errors.len(), 1); + assert!(matches!( + errors[0], + psbt::Error::InputError(InputError::MiniscriptError(Error::ContextError(_)), 0) + )); + } +} + +#[test] +fn repeated_subtree_consumers_report_missing_signatures() { + let keys = signing_keys(8); + let mut script = format!("pk({})", keys[0].1); + // Keep the consumer fixture small; provider-call tests enforce the complexity bound. + for (_, key) in &keys[1..7] { + script = format!("or_b(utv:{},s:pk({}))", script, key); + } + let secp = Secp256k1::verification_only(); + for (taproot, descriptor) in [ + (false, format!("wsh({})", script)), + (true, format!("tr({},{})", keys[7].1, script)), + ] { + let descriptor = Descriptor::::from_str(&descriptor).unwrap(); + descriptor.sanity_check().unwrap(); + assert_eq!(descriptor.clone().plan(&Assets::new()).unwrap_err(), descriptor); + assert_eq!(descriptor.clone().plan_mall(&Assets::new()).unwrap_err(), descriptor); + + let psbt = psbt_for_descriptor(&descriptor); + assert!(psbt.inputs[0].partial_sigs.is_empty()); + assert!(psbt.inputs[0].tap_script_sigs.is_empty()); + if taproot { + assert_eq!(psbt.inputs[0].tap_scripts.len(), 1); + } else { + assert_eq!(psbt.inputs[0].witness_script, Some(descriptor.explicit_script().unwrap())); + } + for result in [ + psbt.clone().finalize(&secp), + psbt.clone().finalize_mall(&secp), + ] { + let (unfinalized, errors) = result.unwrap_err(); + assert_eq!(unfinalized, psbt); + assert_eq!(errors.len(), 1); + if taproot { + assert!(matches!( + errors[0], + psbt::Error::InputError(InputError::CouldNotSatisfyTr, 0) + )); + } else { + assert!(matches!( + errors[0], + psbt::Error::InputError(InputError::MiniscriptError(Error::CouldNotSatisfy), 0) + )); + } + } + } +}