diff --git a/CHANGELOG.md b/CHANGELOG.md index d52c78b49..57cb6e589 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,18 @@ +# Unreleased + +- Evaluate satisfaction and dissatisfaction once per Miniscript node in post-order, + avoiding exponential recomputation in nested branches. Child outcomes are released + as soon as their parent consumes them, keeping peak memory proportional to the live + node frontier; evaluation no longer recurses through subtrees. +- Enforce the context resource limits that hold for every satisfaction path, such as + the opcode-count limits, before the satisfier is queried, including for scripts + decoded with relaxed parsing options. Limits that depend on the chosen path, such + as the Segwit witness-item, Legacy scriptSig and Taproot stack-size limits, are + enforced against the satisfaction that was actually built, so scripts with an + over-limit branch can still be satisfied through an in-limit path. 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/context.rs b/src/miniscript/context.rs index b08d8ed3c..4c6a2237d 100644 --- a/src/miniscript/context.rs +++ b/src/miniscript/context.rs @@ -13,9 +13,9 @@ use crate::miniscript::limits::{ MAX_OPS_PER_SCRIPT, MAX_SCRIPTSIG_SIZE, MAX_SCRIPT_ELEMENT_SIZE, MAX_SCRIPT_SIZE, MAX_STACK_SIZE, MAX_STANDARD_P2WSH_SCRIPT_SIZE, MAX_STANDARD_P2WSH_STACK_ITEMS, }; -use crate::miniscript::types; +use crate::miniscript::{satisfy, types}; use crate::prelude::*; -use crate::util::witness_to_scriptsig; +use crate::util::{witness_to_scriptsig, ItemSize}; use crate::{hash256, Error, ForEachKey, Miniscript, MiniscriptKey, Terminal}; /// Error for Script Context @@ -258,6 +258,40 @@ where Ok(()) } + /// Check the context resource limits that hold for the script itself, + /// regardless of which satisfaction path is chosen, such as the + /// opcode-count limits. Since no satisfaction path can avoid these + /// limits, they may be enforced before the satisfier queries the + /// provider. + /// + /// Defaults to the global checks plus the local consensus checks, which + /// are path-independent for the pre-Segwit-v1 contexts. Contexts whose + /// local consensus limits depend on the chosen satisfaction path, like + /// the Taproot stack-size limits, must override this method to exclude + /// those limits, which are then enforced on the chosen satisfaction by + /// [`ScriptContext::check_satisfaction_validity`]. + fn check_static_validity( + ms: &Miniscript, + ) -> Result<(), ScriptContextError> { + Self::check_global_consensus_validity(ms)?; + Self::check_global_policy_validity(ms)?; + Self::check_local_consensus_validity(ms) + } + + /// Check the context resource limits that depend on which satisfaction + /// path was chosen, against the satisfaction that was actually built. + /// This allows satisfying scripts that have over-limit satisfaction + /// paths as long as the chosen path itself fits the limits. + /// + /// Returns `Ok` for impossible or unavailable satisfactions, which do + /// not produce a witness to check. Defaults to `Ok` for contexts + /// without path-dependent limits. + fn check_satisfaction_validity( + _satisfaction: &satisfy::Satisfaction>, + ) -> Result<(), ScriptContextError> { + Ok(()) + } + /// Check the consensus + policy(if not disabled) rules that are not based /// satisfaction fn check_global_validity( @@ -471,6 +505,23 @@ impl ScriptContext for Legacy { ms.ext.max_sat_size.map(|x| x.1) } + fn check_satisfaction_validity( + satisfaction: &satisfy::Satisfaction>, + ) -> Result<(), ScriptContextError> { + if let satisfy::Witness::Stack(stack) = &satisfaction.stack { + // The typechecker accounts for the scriptSig cost as the sum of + // the push-encoded witness items of the satisfaction path. + let script_sig_size = stack.iter().map(|item| item.size()).sum::(); + if script_sig_size > MAX_SCRIPTSIG_SIZE { + return Err(ScriptContextError::MaxScriptSigSizeExceeded { + actual: script_sig_size, + limit: MAX_SCRIPTSIG_SIZE, + }); + } + } + Ok(()) + } + fn pk_len(pk: &Pk) -> usize { if pk.is_uncompressed() { 66 @@ -599,6 +650,23 @@ impl ScriptContext for Segwitv0 { ms.ext.max_sat_size.map(|x| x.0) } + fn check_satisfaction_validity( + satisfaction: &satisfy::Satisfaction>, + ) -> Result<(), ScriptContextError> { + if let satisfy::Witness::Stack(stack) = &satisfaction.stack { + // Account for the witness script item in the same way as + // `max_satisfaction_witness_elements`. + let witness_items = stack.len() + 1; + if witness_items > MAX_STANDARD_P2WSH_STACK_ITEMS { + return Err(ScriptContextError::MaxWitnessItemsExceeded { + actual: witness_items, + limit: MAX_STANDARD_P2WSH_STACK_ITEMS, + }); + } + } + Ok(()) + } + fn pk_len(_pk: &Pk) -> usize { 34 } fn name_str() -> &'static str { "Segwitv0" } @@ -713,6 +781,36 @@ impl ScriptContext for Tap { Ok(()) } + fn check_static_validity( + ms: &Miniscript, + ) -> Result<(), ScriptContextError> { + // The Taproot stack-size limits depend on the chosen satisfaction + // path, so they are enforced against the built satisfaction by + // `check_satisfaction_validity` instead of up front. + Self::check_global_consensus_validity(ms)?; + Self::check_global_policy_validity(ms) + } + + fn check_satisfaction_validity( + satisfaction: &satisfy::Satisfaction>, + ) -> Result<(), ScriptContextError> { + if let satisfy::Witness::Stack(stack) = &satisfaction.stack { + // The witness elements all reach the stack before the script + // executes, so a satisfaction with more elements than the + // stack limit is consensus-invalid whichever path is chosen. + // The stack usage during execution of the chosen path is + // enforced against the same limit when the witness is + // validated. + if stack.len() > MAX_STACK_SIZE { + return Err(ScriptContextError::StackSizeLimitExceeded { + actual: stack.len(), + limit: MAX_STACK_SIZE, + }); + } + } + Ok(()) + } + fn max_satisfaction_size(ms: &Miniscript) -> Option { // The witness stack cost is the first element of the tuple ms.ext.max_sat_size.map(|x| x.0) diff --git a/src/miniscript/mod.rs b/src/miniscript/mod.rs index a36cef547..4b3323f49 100644 --- a/src/miniscript/mod.rs +++ b/src/miniscript/mod.rs @@ -433,23 +433,38 @@ 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. + /// + /// Enforces the context resource limits that hold for every satisfaction + /// path before querying the satisfier, and the path-dependent limits + /// against the satisfaction that was actually built, so scripts with an + /// over-limit branch can still be satisfied through an in-limit path. pub fn satisfy>(&self, satisfier: S) -> Result>, Error> where Pk: ToPublicKey, { + Ctx::check_static_validity(self)?; // Only satisfactions for default versions (0xc0) are allowed. - let satisfaction = satisfy::Satisfaction::satisfy( + let template = satisfy::Satisfaction::>::build_template( &self.node, &satisfier, self.ty.mall.safe, &self.leaf_hash_internal(), ); + Ctx::check_satisfaction_validity(&template)?; + let satisfaction = template + .try_completing(&satisfier) + .expect("the same satisfier should manage to complete the template"); self._satisfy(satisfaction) } /// Attempt to produce a malleable satisfying witness for the - /// witness script represented by the parse tree + /// witness script represented by the parse tree. + /// + /// Enforces the context resource limits that hold for every satisfaction + /// path before querying the satisfier, and the path-dependent limits + /// against the satisfaction that was actually built, so scripts with an + /// over-limit branch can still be satisfied through an in-limit path. pub fn satisfy_malleable>( &self, satisfier: S, @@ -457,12 +472,17 @@ impl Miniscript { where Pk: ToPublicKey, { - let satisfaction = satisfy::Satisfaction::satisfy_mall( + Ctx::check_static_validity(self)?; + let template = satisfy::Satisfaction::>::build_template_mall( &self.node, &satisfier, self.ty.mall.safe, &self.leaf_hash_internal(), ); + Ctx::check_satisfaction_validity(&template)?; + let satisfaction = template + .try_completing(&satisfier) + .expect("the same satisfier should manage to complete the template"); self._satisfy(satisfaction) } @@ -481,7 +501,24 @@ impl Miniscript { } } - /// Attempt to produce a non-malleable witness template given the assets available + /// An impossible template, returned when the context resource limits + /// reject the script. + fn impossible_template() -> satisfy::Satisfaction> { + satisfy::Satisfaction { + stack: satisfy::Witness::Impossible, + has_sig: false, + absolute_timelock: None, + relative_timelock: None, + } + } + + /// Attempt to produce a non-malleable witness template given the assets available. + /// + /// Returns an impossible template, without querying the provider, if + /// the context resource limits that hold for every satisfaction path + /// are exceeded. Path-dependent limits are checked against the template + /// that was actually built, so scripts with an over-limit branch can + /// still be planned through an in-limit path. pub fn build_template>( &self, provider: &P, @@ -489,15 +526,28 @@ impl Miniscript { where Pk: ToPublicKey, { - satisfy::Satisfaction::build_template( + if Ctx::check_static_validity(self).is_err() { + return Self::impossible_template(); + } + let template = satisfy::Satisfaction::build_template( &self.node, provider, self.ty.mall.safe, &self.leaf_hash_internal(), - ) + ); + if Ctx::check_satisfaction_validity(&template).is_err() { + return Self::impossible_template(); + } + template } - /// 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 resource limits that hold for every satisfaction path + /// are exceeded. Path-dependent limits are checked against the template + /// that was actually built, so scripts with an over-limit branch can + /// still be planned through an in-limit path. pub fn build_template_mall>( &self, provider: &P, @@ -505,12 +555,19 @@ impl Miniscript { where Pk: ToPublicKey, { - satisfy::Satisfaction::build_template_mall( + if Ctx::check_static_validity(self).is_err() { + return Self::impossible_template(); + } + let template = satisfy::Satisfaction::build_template_mall( &self.node, provider, self.ty.mall.safe, &self.leaf_hash_internal(), - ) + ); + if Ctx::check_satisfaction_validity(&template).is_err() { + return Self::impossible_template(); + } + template } } @@ -1062,6 +1119,7 @@ pub mod hash256 { #[cfg(test)] mod tests { + use core::cell::Cell; use core::str; use core::str::FromStr; @@ -1883,6 +1941,323 @@ 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") + } + } + + // Supplies a dummy signature for every key, so that the satisfier always + // picks the most expensive satisfaction path, and records that the + // satisfier was queried: the path-dependent resource limits are + // enforced against the chosen satisfaction, which is only known after + // the satisfier is queried. + struct AllSignatures { + queried: Cell, + } + + impl AllSignatures { + fn new() -> Self { AllSignatures { queried: Cell::new(false) } } + + fn assert_queried(&self) { + assert!(self.queried.get(), "the chosen satisfaction must be built before checking"); + } + } + + impl Satisfier for AllSignatures { + fn lookup_ecdsa_sig(&self, _: &Pk) -> Option { + self.queried.set(true); + Some(bitcoin::ecdsa::Signature { + signature: secp256k1::ecdsa::Signature::from_compact(&[1; 64]).unwrap(), + sighash_type: bitcoin::sighash::EcdsaSighashType::All, + }) + } + + fn lookup_raw_pkh_pk(&self, _: &hash160::Hash) -> Option { + self.queried.set(true); + Some(pubkeys(1)[0]) + } + + fn lookup_raw_pkh_ecdsa_sig( + &self, + _: &hash160::Hash, + ) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> { + self.queried.set(true); + Some(( + pubkeys(1)[0], + bitcoin::ecdsa::Signature { + signature: secp256k1::ecdsa::Signature::from_compact(&[1; 64]).unwrap(), + sighash_type: bitcoin::sighash::EcdsaSighashType::All, + }, + )) + } + + fn lookup_tap_leaf_script_sig( + &self, + _: &Pk, + _: &TapLeafHash, + ) -> Option { + self.queried.set(true); + Some(bitcoin::taproot::Signature { + signature: secp256k1::schnorr::Signature::from_slice(&[1; 64]).unwrap(), + sighash_type: bitcoin::sighash::TapSighashType::Default, + }) + } + } + + // The limits that hold for every satisfaction path are enforced before + // the satisfier is queried. + fn assert_static_rejected(ms: &Miniscript) + where + Pk: crate::MiniscriptKey + ToPublicKey, + Ctx: ScriptContext, + { + let error = Ctx::check_static_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_static_rejected(&legacy); + assert_static_rejected(&bare); + assert_static_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, + }) + )); + // The witness-item limit is enforced against the chosen + // satisfaction, after the satisfier is queried: with every + // signature available, the chosen path needs 106 witness items. + let assets = AllSignatures::new(); + for template in [ms.build_template(&assets), ms.build_template_mall(&assets)] { + 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); + } + assets.assert_queried(); + for result in [ms.satisfy(&assets), ms.satisfy_malleable(&assets)] { + assert!(matches!( + result, + Err(Error::ContextError( + crate::miniscript::context::ScriptContextError::MaxWitnessItemsExceeded { + actual: 106, + limit: 100, + } + )) + )); + } + } + + #[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, + .. + }) + )); + // The scriptSig limit is enforced against the chosen satisfaction: + // the scriptSig is the sum of the push-encoded witness items of the + // chosen path, over the limit even though the opcode count is fine. + let assets = AllSignatures::new(); + for template in [ms.build_template(&assets), ms.build_template_mall(&assets)] { + assert_eq!(template.stack, crate::miniscript::satisfy::Witness::Impossible); + } + assets.assert_queried(); + for result in [ms.satisfy(&assets), ms.satisfy_malleable(&assets)] { + assert!(matches!( + result, + Err(Error::ContextError( + crate::miniscript::context::ScriptContextError::MaxScriptSigSizeExceeded { + limit: 1650, + .. + } + )) + )); + } + } + + #[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({}),and_v(v:pk({}),{}))", key, key, multi); + 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, + .. + }) + )); + // The stack limit is enforced against the chosen satisfaction: the + // chosen witness needs 1001 elements even though Taproot has no + // opcode-count limit. + let assets = AllSignatures::new(); + for template in [ms.build_template(&assets), ms.build_template_mall(&assets)] { + assert_eq!(template.stack, crate::miniscript::satisfy::Witness::Impossible); + } + assets.assert_queried(); + for result in [ms.satisfy(&assets), ms.satisfy_malleable(&assets)] { + assert!(matches!( + result, + Err(Error::ContextError( + crate::miniscript::context::ScriptContextError::StackSizeLimitExceeded { + actual: 1001, + limit: 1000, + } + )) + )); + } + } + + #[test] + fn satisfaction_path_limits_allow_over_limit_sibling_branch() { + // The worst-case limits reject the script because the multi branch + // needs too many witness items, but the chosen satisfaction only + // uses the in-limit pk branch and is still produced. + let keys = pubkeys(2); + let multi = format!("multi(20,{})", vec![keys[0].to_string(); 20].join(",")); + let over_limit = format!("and_v(v:{},", multi).repeat(4) + &multi + &")".repeat(4); + let source = format!("or_d(pk({}),{})", keys[1], over_limit); + let ms = Segwitv0Script::from_str_insane(&source).unwrap(); + assert!(matches!( + Segwitv0::check_local_validity(&ms), + Err(crate::miniscript::context::ScriptContextError::MaxWitnessItemsExceeded { .. }) + )); + let assets = AllSignatures::new(); + for template in [ms.build_template(&assets), ms.build_template_mall(&assets)] { + assert!(matches!(template.stack, crate::miniscript::satisfy::Witness::Stack(_))); + } + for witness in [ + ms.satisfy(&assets).unwrap(), + ms.satisfy_malleable(&assets).unwrap(), + ] { + assert_eq!(witness.len(), 1); + } + } + + 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..069e57b3c 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,26 @@ pub struct Satisfaction { pub relative_timelock: Option, } +/// The satisfaction and dissatisfaction of a single node, computed exactly +/// once by the post-order pass of [`Satisfaction::build_template`]. +struct SatDissat { + sat: Satisfaction>, + dissat: Satisfaction>, +} + +/// Post-order cache of the per-node outcomes, indexed by each node's +/// position in the iteration. A child's outcomes are released as soon as +/// its parent has consumed them, so the cache only holds the outcomes that +/// are still reachable. +type SatisfactionCache = Vec>>; + +/// The shared post-order cache together with the child indices of the node +/// currently being evaluated. +struct NodeCache<'a, Pk: MiniscriptKey> { + cache: &'a SatisfactionCache, + children: &'a [usize], +} + impl Satisfaction> { /// The empty satisfaction. /// @@ -931,14 +952,37 @@ 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: SatisfactionCache = Vec::new(); + // Every node is evaluated exactly once, in post-order, so that both + // child outcomes are available when their parent is evaluated. A + // child's outcomes are released as soon as its parent has consumed + // them: witnesses may be copied, but subtrees are never + // re-evaluated, and peak memory stays proportional to the live + // node frontier rather than the size of the whole tree. + for item in term.post_order_iter() { + let nodes = NodeCache { cache: &cache, children: &item.child_indices }; + let sat = Self::satisfy_step( + item.node, + provider, + root_has_sig, + leaf_hash, + &mut Self::minimum, + &mut Self::thresh, + &nodes, + ); + let dissat = Self::dissatisfy_step(item.node, &nodes, provider); + for &index in &item.child_indices { + cache[index] = None; + } + // Post-order indices are assigned in iteration order. + debug_assert_eq!(item.index, cache.len()); + cache.push(Some(SatDissat { sat, dissat })); + } + // The root is evaluated last in post-order. + match cache.pop() { + Some(Some(SatDissat { sat, .. })) => sat, + _ => unreachable!("post-order evaluation always visits the root node"), + } } pub(crate) fn build_template_mall( @@ -951,58 +995,70 @@ 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: SatisfactionCache = Vec::new(); + // Every node is evaluated exactly once, in post-order, so that both + // child outcomes are available when their parent is evaluated. A + // child's outcomes are released as soon as its parent has consumed + // them: witnesses may be copied, but subtrees are never + // re-evaluated, and peak memory stays proportional to the live + // node frontier rather than the size of the whole tree. + for item in term.post_order_iter() { + let nodes = NodeCache { cache: &cache, children: &item.child_indices }; + let sat = Self::satisfy_step( + item.node, + provider, + root_has_sig, + leaf_hash, + &mut Self::minimum_mall, + &mut Self::thresh_mall, + &nodes, + ); + let dissat = Self::dissatisfy_step(item.node, &nodes, provider); + for &index in &item.child_indices { + cache[index] = None; + } + // Post-order indices are assigned in iteration order. + debug_assert_eq!(item.index, cache.len()); + cache.push(Some(SatDissat { sat, dissat })); + } + // The root is evaluated last in post-order. + match cache.pop() { + Some(Some(SatDissat { sat, .. })) => sat, + _ => unreachable!("post-order evaluation always visits the root node"), + } + } + + fn cached(nodes: &NodeCache<'_, Pk>, index: usize, satisfied: bool) -> Self { + // Post-order evaluation stores both outcomes of every child before + // visiting the parent, and releases them only after the parent has + // consumed them. + let entry = nodes.cache[index] + .as_ref() + .expect("child outcomes were evaluated"); + if satisfied { + entry.sat.clone() + } else { + entry.dissat.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>, - { + nodes: &NodeCache<'_, Pk>, + ) -> Self { + let children = nodes.children; + debug_assert_eq!(children.len(), thresh.n()); let mut sats = thresh .iter() - .map(|s| { - Self::satisfy_helper( - &s.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - &mut Self::thresh, - ) - }) + .enumerate() + .map(|(i, _)| Self::cached(nodes, children[i], 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, - ) - }) + .enumerate() + .map(|(i, _)| Self::cached(nodes, children[i], false)) .collect::>(); // Sort everything by (sat cost - dissat cost), except that @@ -1080,47 +1136,22 @@ 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>, - { + nodes: &NodeCache<'_, Pk>, + ) -> Self { + let children = nodes.children; + debug_assert_eq!(children.len(), thresh.n()); let mut sats = thresh .iter() - .map(|s| { - Self::satisfy_helper( - &s.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - &mut Self::thresh_mall, - ) - }) + .enumerate() + .map(|(i, _)| Self::cached(nodes, children[i], 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, - ) - }) + .enumerate() + .map(|(i, _)| Self::cached(nodes, children[i], false)) .collect::>(); // Sort everything by (sat cost - dissat cost), except that @@ -1227,13 +1258,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, + nodes: &NodeCache<'_, Pk>, ) -> Self where Ctx: ScriptContext, @@ -1244,12 +1276,10 @@ impl Satisfaction> { ) -> Satisfaction>, G: FnMut( &Threshold>, 0>, - &Sat, - bool, - &TapLeafHash, - &mut F, + &NodeCache<'_, Pk>, ) -> Satisfaction>, { + let children = nodes.children; match *term { Terminal::PkK(ref pk) => Satisfaction { stack: Witness::signature::<_, Ctx>(stfr, pk, leaf_hash), @@ -1341,23 +1371,14 @@ impl Satisfaction> { relative_timelock: None, absolute_timelock: None, }, - Terminal::Alt(ref sub) - | Terminal::Swap(ref sub) - | 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::DupIf(ref sub) => { - let sat = Self::satisfy_helper( - &sub.node, - stfr, - root_has_sig, - leaf_hash, - min_fn, - thresh_fn, - ); + Terminal::Alt(..) + | Terminal::Swap(..) + | Terminal::Check(..) + | Terminal::Verify(..) + | Terminal::NonZero(..) + | Terminal::ZeroNotEqual(..) => Self::cached(nodes, children[0], true), + Terminal::DupIf(..) => { + let sat = Self::cached(nodes, children[0], true); Satisfaction { stack: Witness::combine(sat.stack, Witness::push_1()), has_sig: sat.has_sig, @@ -1365,52 +1386,24 @@ impl Satisfaction> { absolute_timelock: sat.absolute_timelock, } } - 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); + Terminal::AndV(..) | Terminal::AndB(..) => { + let l_sat = Self::cached(nodes, children[0], true); + let r_sat = Self::cached(nodes, children[1], 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); + Terminal::AndOr(..) => { + let a_sat = Self::cached(nodes, children[0], true); + let a_nsat = Self::cached(nodes, children[0], false); + let b_sat = Self::cached(nodes, children[1], true); + let c_sat = Self::cached(nodes, children[2], 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, - ); + Terminal::OrB(..) => { + let l_sat = Self::cached(nodes, children[0], true); + let r_sat = Self::cached(nodes, children[1], true); + let l_nsat = Self::cached(nodes, children[0], false); + let r_nsat = Self::cached(nodes, children[1], false); assert!(!l_nsat.has_sig); assert!(!r_nsat.has_sig); @@ -1420,29 +1413,18 @@ impl Satisfaction> { Satisfaction::concatenate_rev(l_sat, r_nsat), ) } - 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, - ); + Terminal::OrD(..) | Terminal::OrC(..) => { + let l_sat = Self::cached(nodes, children[0], true); + let r_sat = Self::cached(nodes, children[1], true); + let l_nsat = Self::cached(nodes, children[0], 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); + Terminal::OrI(..) => { + let l_sat = Self::cached(nodes, children[0], true); + let r_sat = Self::cached(nodes, children[1], true); min_fn( Satisfaction { stack: Witness::combine(l_sat.stack, Witness::push_1()), @@ -1463,19 +1445,11 @@ 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, - ) - }) + .enumerate() + .map(|(i, _)| Self::cached(nodes, children[i], true)) .fold(Satisfaction::empty(), Satisfaction::concatenate_rev) } else { - thresh_fn(thresh, stfr, root_has_sig, leaf_hash, min_fn) + thresh_fn(thresh, nodes) } } Terminal::Multi(ref thresh) => { @@ -1570,29 +1544,12 @@ impl Satisfaction> { } // Helper function to produce a dissatisfaction - fn dissatisfy_helper( + fn dissatisfy_step>( term: &Terminal, + nodes: &NodeCache<'_, Pk>, 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>, - { + ) -> Self { + let children = nodes.children; match *term { Terminal::PkK(..) => Satisfaction { stack: Witness::push_0(), @@ -1643,62 +1600,28 @@ impl Satisfaction> { relative_timelock: None, absolute_timelock: None, }, - 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::Alt(..) + | Terminal::Swap(..) + | Terminal::Check(..) + | Terminal::ZeroNotEqual(..) => Self::cached(nodes, children[0], false), Terminal::DupIf(_) | Terminal::NonZero(_) => Satisfaction { stack: Witness::push_0(), has_sig: false, relative_timelock: None, 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, - ); + Terminal::AndV(..) => { + let vsat = Self::cached(nodes, children[0], true); + let odissat = Self::cached(nodes, children[1], 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, - ); + Terminal::AndB(..) | Terminal::OrB(..) | Terminal::OrD(..) | Terminal::AndOr(..) => { + let lnsat = Self::cached(nodes, children[0], false); + let rnsat = Self::cached(nodes, children[1], 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, - ); + Terminal::OrI(..) => { + let lnsat = Self::cached(nodes, children[0], false); let dissat_1 = Satisfaction { stack: Witness::combine(lnsat.stack, Witness::push_1()), has_sig: lnsat.has_sig, @@ -1706,14 +1629,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(nodes, children[1], false); let dissat_2 = Satisfaction { stack: Witness::combine(rnsat.stack, Witness::push_0()), has_sig: rnsat.has_sig, @@ -1726,16 +1642,8 @@ 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, - ) - }) + .enumerate() + .map(|(i, _)| Self::cached(nodes, children[i], false)) .fold(Satisfaction::empty(), Satisfaction::concatenate_rev), Terminal::Multi(ref thresh) => Satisfaction { stack: Witness::Stack(vec![Placeholder::PushZero; thresh.k() + 1]), @@ -1774,38 +1682,76 @@ impl Satisfaction> { } } -impl Satisfaction> { - /// Produce a satisfaction non-malleable satisfaction - pub(super) fn satisfy( - term: &Terminal, - stfr: &Sat, - root_has_sig: bool, - leaf_hash: &TapLeafHash, - ) -> Self - where - Ctx: ScriptContext, - Pk: MiniscriptKey + ToPublicKey, - Sat: Satisfier, - { - Satisfaction::>::build_template(term, &stfr, root_has_sig, leaf_hash) - .try_completing(stfr) - .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, } - /// Produce a satisfaction(possibly malleable) - pub(super) fn satisfy_mall( - term: &Terminal, - stfr: &Sat, - root_has_sig: bool, - leaf_hash: &TapLeafHash, - ) -> Self - where - Ctx: ScriptContext, - Pk: MiniscriptKey + ToPublicKey, - Sat: Satisfier, - { - Satisfaction::>::build_template_mall(term, &stfr, root_has_sig, leaf_hash) - .try_completing(stfr) - .expect("the same satisfier should manage to complete the template") + 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) + )); + } + } + } +}