From 9b93a19beb2cfe9528afa9350af5b65b48b465de Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 13 May 2026 11:49:38 +1000 Subject: [PATCH 1/3] Enable use_self lint Tighten up the linting by using `use_self` and fix all warnings. I got claude to do the fixes. It eventually found its way to using cargo clippy --fix --allow-dirty --allow-staged --workspace \ --all-targets --all-features -- -D clippy::use-self FTR this does not enable the lint because for some reason adding this to the manifest doesn't work. ```rust [workspace.lints.clippy] use_self = "warn" ``` I tested this patch using `cargo +$(cat ./nightly-version ) clippy -- -D clippy::use-self` --- src/descriptor/bare.rs | 6 +- src/descriptor/checksum.rs | 10 +- src/descriptor/key.rs | 134 ++++----- src/descriptor/key_map.rs | 10 +- src/descriptor/mod.rs | 284 +++++++++--------- src/descriptor/segwitv0.rs | 8 +- src/descriptor/sh.rs | 2 +- src/descriptor/tr/mod.rs | 4 +- src/descriptor/tr/spend_info.rs | 2 +- src/descriptor/tr/taptree.rs | 4 +- .../wallet_policy/key_expression.rs | 6 +- src/descriptor/wallet_policy/mod.rs | 44 +-- src/error.rs | 22 +- src/expression/error.rs | 60 ++-- src/interpreter/error.rs | 96 +++--- src/interpreter/inner.rs | 4 +- src/interpreter/mod.rs | 24 +- src/interpreter/stack.rs | 4 +- src/iter/tree.rs | 14 +- src/lib.rs | 90 +++--- src/miniscript/analyzable.rs | 38 +-- src/miniscript/astelem.rs | 60 ++-- src/miniscript/context.rs | 30 +- src/miniscript/decode.rs | 126 ++++---- src/miniscript/display.rs | 76 ++--- src/miniscript/iter.rs | 4 +- src/miniscript/lex.rs | 12 +- src/miniscript/mod.rs | 92 +++--- src/miniscript/satisfy/mod.rs | 128 ++++---- src/miniscript/types/correctness.rs | 70 ++--- src/miniscript/types/extra_props.rs | 62 ++-- src/miniscript/types/malleability.rs | 54 ++-- src/miniscript/types/mod.rs | 56 ++-- src/plan.rs | 6 +- src/policy/compiler.rs | 104 +++---- src/policy/concrete.rs | 122 ++++---- src/policy/mod.rs | 44 +-- src/policy/semantic.rs | 126 ++++---- src/primitives/absolute_locktime.rs | 4 +- src/primitives/relative_locktime.rs | 12 +- src/primitives/threshold.rs | 10 +- src/psbt/mod.rs | 94 +++--- src/util.rs | 26 +- 43 files changed, 1092 insertions(+), 1092 deletions(-) diff --git a/src/descriptor/bare.rs b/src/descriptor/bare.rs index 844516779..9ae529357 100644 --- a/src/descriptor/bare.rs +++ b/src/descriptor/bare.rs @@ -172,7 +172,7 @@ impl FromTree for Bare { fn from_tree(root: expression::TreeIterItem) -> Result { let sub = Miniscript::::from_tree(root)?; BareCtx::top_level_checks(&sub)?; - Bare::new(sub) + Self::new(sub) } } @@ -202,7 +202,7 @@ impl Pkh { pub fn new(pk: Pk) -> Result { // do the top-level checks match BareCtx::check_pk(&pk) { - Ok(()) => Ok(Pkh { pk }), + Ok(()) => Ok(Self { pk }), Err(e) => Err(e), } } @@ -359,7 +359,7 @@ impl FromTree for Pkh { let pk = root .verify_terminal_parent("pkh", "public key") .map_err(Error::Parse)?; - Pkh::new(pk).map_err(Error::ContextError) + Self::new(pk).map_err(Error::ContextError) } } diff --git a/src/descriptor/checksum.rs b/src/descriptor/checksum.rs index 2e66c6aa9..22c3fe81c 100644 --- a/src/descriptor/checksum.rs +++ b/src/descriptor/checksum.rs @@ -61,13 +61,13 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Error::InvalidCharacter { ch, pos } => { + Self::InvalidCharacter { ch, pos } => { write!(f, "invalid character '{}' (position {})", ch, pos) } - Error::InvalidChecksumLength { actual, expected } => { + Self::InvalidChecksumLength { actual, expected } => { write!(f, "invalid checksum (length {}, expected {})", actual, expected) } - Error::InvalidChecksum { actual, expected } => { + Self::InvalidChecksum { actual, expected } => { f.write_str("invalid checksum ")?; for ch in actual { ch.fmt(f)?; @@ -135,13 +135,13 @@ pub struct Engine { } impl Default for Engine { - fn default() -> Engine { Engine::new() } + fn default() -> Self { Self::new() } } impl Engine { /// Constructs an engine with no input. pub fn new() -> Self { - Engine { inner: bech32::primitives::checksum::Engine::new(), cls: 0, clscount: 0 } + Self { inner: bech32::primitives::checksum::Engine::new(), cls: 0, clscount: 0 } } /// Inputs some data into the checksum engine. diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index 3c726501a..7c69e33b8 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -77,11 +77,11 @@ pub struct DerivPaths(Vec); impl DerivPaths { /// Create a non empty derivation paths list. - pub fn new(paths: Vec) -> Option { + pub fn new(paths: Vec) -> Option { if paths.is_empty() { None } else { - Some(DerivPaths(paths)) + Some(Self(paths)) } } @@ -132,12 +132,12 @@ pub enum XKeyNetwork { impl fmt::Display for DescriptorSecretKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - DescriptorSecretKey::Single(ref sk) => { + Self::Single(ref sk) => { maybe_fmt_master_id(f, &sk.origin)?; sk.key.fmt(f)?; Ok(()) } - DescriptorSecretKey::XPrv(ref xprv) => { + Self::XPrv(ref xprv) => { maybe_fmt_master_id(f, &xprv.origin)?; xprv.xkey.fmt(f)?; fmt_derivation_path(f, &xprv.derivation_path)?; @@ -148,7 +148,7 @@ impl fmt::Display for DescriptorSecretKey { } Ok(()) } - DescriptorSecretKey::MultiXPrv(ref xprv) => { + Self::MultiXPrv(ref xprv) => { maybe_fmt_master_id(f, &xprv.origin)?; xprv.xkey.fmt(f)?; fmt_derivation_paths(f, xprv.derivation_paths.paths())?; @@ -205,9 +205,9 @@ pub enum Wildcard { impl fmt::Display for Wildcard { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - Wildcard::None => write!(f, ""), - Wildcard::Unhardened => write!(f, "/*"), - Wildcard::Hardened => write!(f, "/*h"), + Self::None => write!(f, ""), + Self::Unhardened => write!(f, "/*"), + Self::Hardened => write!(f, "/*h"), } } } @@ -628,9 +628,9 @@ impl DescriptorSecretKey { secp: &Secp256k1, ) -> Result { let pk = match self { - DescriptorSecretKey::Single(prv) => DescriptorPublicKey::Single(prv.to_public(secp)), - DescriptorSecretKey::XPrv(xprv) => DescriptorPublicKey::XPub(xprv.to_public(secp)?), - DescriptorSecretKey::MultiXPrv(xprv) => { + Self::Single(prv) => DescriptorPublicKey::Single(prv.to_public(secp)), + Self::XPrv(xprv) => DescriptorPublicKey::XPub(xprv.to_public(secp)?), + Self::MultiXPrv(xprv) => { DescriptorPublicKey::MultiXPub(xprv.to_public(secp)?) } }; @@ -641,8 +641,8 @@ impl DescriptorSecretKey { /// Whether or not this key has multiple derivation paths. pub fn is_multipath(&self) -> bool { match *self { - DescriptorSecretKey::Single(..) | DescriptorSecretKey::XPrv(..) => false, - DescriptorSecretKey::MultiXPrv(_) => true, + Self::Single(..) | Self::XPrv(..) => false, + Self::MultiXPrv(_) => true, } } @@ -651,16 +651,16 @@ impl DescriptorSecretKey { /// For raw keys and single-path extended keys it will return the key itself. /// For multipath extended keys it will return a single-path extended key per derivation /// path. - pub fn into_single_keys(self) -> Vec { + pub fn into_single_keys(self) -> Vec { match self { - DescriptorSecretKey::Single(..) | DescriptorSecretKey::XPrv(..) => vec![self], - DescriptorSecretKey::MultiXPrv(xpub) => { + Self::Single(..) | Self::XPrv(..) => vec![self], + Self::MultiXPrv(xpub) => { let DescriptorMultiXKey { origin, xkey, derivation_paths, wildcard } = xpub; derivation_paths .into_paths() .into_iter() .map(|derivation_path| { - DescriptorSecretKey::XPrv(DescriptorXKey { + Self::XPrv(DescriptorXKey { origin: origin.clone(), xkey, derivation_path, @@ -738,14 +738,14 @@ impl FromStr for DescriptorPublicKey { if key_part.contains("pub") { let (xpub, derivation_paths, wildcard) = parse_xkey_deriv(key_part)?; if derivation_paths.len() > 1 { - Ok(DescriptorPublicKey::MultiXPub(DescriptorMultiXKey { + Ok(Self::MultiXPub(DescriptorMultiXKey { origin, xkey: xpub, derivation_paths: DerivPaths::new(derivation_paths).expect("Not empty"), wildcard, })) } else { - Ok(DescriptorPublicKey::XPub(DescriptorXKey { + Ok(Self::XPub(DescriptorXKey { origin, xkey: xpub, derivation_path: derivation_paths.into_iter().next().unwrap_or_default(), @@ -778,20 +778,20 @@ impl FromStr for DescriptorPublicKey { )) } }; - Ok(DescriptorPublicKey::Single(SinglePub { key, origin })) + Ok(Self::Single(SinglePub { key, origin })) } } } impl From for DescriptorPublicKey { fn from(key: XOnlyPublicKey) -> Self { - DescriptorPublicKey::Single(SinglePub { origin: None, key: SinglePubKey::XOnly(key) }) + Self::Single(SinglePub { origin: None, key: SinglePubKey::XOnly(key) }) } } impl From for DescriptorPublicKey { fn from(key: PublicKey) -> Self { - DescriptorPublicKey::Single(SinglePub { origin: None, key: SinglePubKey::FullKey(key) }) + Self::Single(SinglePub { origin: None, key: SinglePubKey::FullKey(key) }) } } @@ -799,21 +799,21 @@ impl DescriptorPublicKey { /// The fingerprint of the master key associated with this key, `0x00000000` if none. pub fn master_fingerprint(&self) -> bip32::Fingerprint { match *self { - DescriptorPublicKey::XPub(ref xpub) => { + Self::XPub(ref xpub) => { if let Some((fingerprint, _)) = xpub.origin { fingerprint } else { xpub.xkey.fingerprint() } } - DescriptorPublicKey::MultiXPub(ref xpub) => { + Self::MultiXPub(ref xpub) => { if let Some((fingerprint, _)) = xpub.origin { fingerprint } else { xpub.xkey.fingerprint() } } - DescriptorPublicKey::Single(ref single) => { + Self::Single(ref single) => { if let Some((fingerprint, _)) = single.origin { fingerprint } else { @@ -843,7 +843,7 @@ impl DescriptorPublicKey { /// For multipath extended keys, this returns `None`. pub fn full_derivation_path(&self) -> Option { match *self { - DescriptorPublicKey::XPub(ref xpub) => { + Self::XPub(ref xpub) => { let origin_path = if let Some((_, ref path)) = xpub.origin { path.clone() } else { @@ -851,14 +851,14 @@ impl DescriptorPublicKey { }; Some(origin_path.extend(&xpub.derivation_path)) } - DescriptorPublicKey::Single(ref single) => { + Self::Single(ref single) => { Some(if let Some((_, ref path)) = single.origin { path.clone() } else { bip32::DerivationPath::from(vec![]) }) } - DescriptorPublicKey::MultiXPub(_) => None, + Self::MultiXPub(_) => None, } } @@ -871,7 +871,7 @@ impl DescriptorPublicKey { /// to the wildcard type (hardened or normal). pub fn full_derivation_paths(&self) -> Vec { match self { - DescriptorPublicKey::MultiXPub(xpub) => { + Self::MultiXPub(xpub) => { let origin_path = if let Some((_, ref path)) = xpub.origin { path.clone() } else { @@ -898,9 +898,9 @@ impl DescriptorPublicKey { /// For multipath extended keys, this returns `None`. pub fn derivation_path(&self) -> Option { match *self { - DescriptorPublicKey::XPub(ref xpub) => Some(xpub.derivation_path.clone()), - DescriptorPublicKey::Single(_) => Some(bip32::DerivationPath::from(vec![])), - DescriptorPublicKey::MultiXPub(_) => None, + Self::XPub(ref xpub) => Some(xpub.derivation_path.clone()), + Self::Single(_) => Some(bip32::DerivationPath::from(vec![])), + Self::MultiXPub(_) => None, } } @@ -911,40 +911,40 @@ impl DescriptorPublicKey { /// to the wildcard type (hardened or normal). pub fn derivation_paths(&self) -> Vec { match &self { - DescriptorPublicKey::XPub(xpub) => { + Self::XPub(xpub) => { vec![xpub.derivation_path.clone()] } - DescriptorPublicKey::Single(_) => { + Self::Single(_) => { vec![bip32::DerivationPath::from(vec![])] } - DescriptorPublicKey::MultiXPub(xpub) => xpub.derivation_paths.paths().clone(), + Self::MultiXPub(xpub) => xpub.derivation_paths.paths().clone(), } } /// Whether or not the key has a wildcard pub fn has_wildcard(&self) -> bool { match *self { - DescriptorPublicKey::Single(..) => false, - DescriptorPublicKey::XPub(ref xpub) => xpub.wildcard != Wildcard::None, - DescriptorPublicKey::MultiXPub(ref xpub) => xpub.wildcard != Wildcard::None, + Self::Single(..) => false, + Self::XPub(ref xpub) => xpub.wildcard != Wildcard::None, + Self::MultiXPub(ref xpub) => xpub.wildcard != Wildcard::None, } } /// Return a Wildcard if key is a XKey pub fn wildcard(&self) -> Option { match *self { - DescriptorPublicKey::Single(..) => None, - DescriptorPublicKey::XPub(ref xpub) => Some(xpub.wildcard), - DescriptorPublicKey::MultiXPub(ref xpub) => Some(xpub.wildcard), + Self::Single(..) => None, + Self::XPub(ref xpub) => Some(xpub.wildcard), + Self::MultiXPub(ref xpub) => Some(xpub.wildcard), } } /// Whether or not the key has a hardened step in path pub fn has_hardened_step(&self) -> bool { let paths = match self { - DescriptorPublicKey::Single(..) => &[], - DescriptorPublicKey::XPub(xpub) => core::slice::from_ref(&xpub.derivation_path), - DescriptorPublicKey::MultiXPub(xpub) => &xpub.derivation_paths.paths()[..], + Self::Single(..) => &[], + Self::XPub(xpub) => core::slice::from_ref(&xpub.derivation_path), + Self::MultiXPub(xpub) => &xpub.derivation_paths.paths()[..], }; for p in paths { for step in p.into_iter() { @@ -975,8 +975,8 @@ impl DescriptorPublicKey { index: u32, ) -> Result { let definite = match self { - DescriptorPublicKey::Single(_) => self, - DescriptorPublicKey::XPub(xpub) => { + Self::Single(_) => self, + Self::XPub(xpub) => { let derivation_path = match xpub.wildcard { Wildcard::None => xpub.derivation_path, Wildcard::Unhardened => xpub.derivation_path.into_child( @@ -990,14 +990,14 @@ impl DescriptorPublicKey { .ok_or(NonDefiniteKeyError::HardenedStep)?, ), }; - DescriptorPublicKey::XPub(DescriptorXKey { + Self::XPub(DescriptorXKey { origin: xpub.origin, xkey: xpub.xkey, derivation_path, wildcard: Wildcard::None, }) } - DescriptorPublicKey::MultiXPub(_) => return Err(NonDefiniteKeyError::Multipath), + Self::MultiXPub(_) => return Err(NonDefiniteKeyError::Multipath), }; DefiniteDescriptorKey::new(definite) @@ -1006,8 +1006,8 @@ impl DescriptorPublicKey { /// Whether or not this key has multiple derivation paths. pub fn is_multipath(&self) -> bool { match *self { - DescriptorPublicKey::Single(..) | DescriptorPublicKey::XPub(..) => false, - DescriptorPublicKey::MultiXPub(_) => true, + Self::Single(..) | Self::XPub(..) => false, + Self::MultiXPub(_) => true, } } @@ -1016,16 +1016,16 @@ impl DescriptorPublicKey { /// For raw public key and single-path extended keys it will return the key itself. /// For multipath extended keys it will return a single-path extended key per derivation /// path. - pub fn into_single_keys(self) -> Vec { + pub fn into_single_keys(self) -> Vec { match self { - DescriptorPublicKey::Single(..) | DescriptorPublicKey::XPub(..) => vec![self], - DescriptorPublicKey::MultiXPub(xpub) => { + Self::Single(..) | Self::XPub(..) => vec![self], + Self::MultiXPub(xpub) => { let DescriptorMultiXKey { origin, xkey, derivation_paths, wildcard } = xpub; derivation_paths .into_paths() .into_iter() .map(|derivation_path| { - DescriptorPublicKey::XPub(DescriptorXKey { + Self::XPub(DescriptorXKey { origin: origin.clone(), xkey, derivation_path, @@ -1042,9 +1042,9 @@ impl DescriptorPublicKey { /// Returns `None` for single keys (non-extended keys), `Some(NetworkKind)` for extended keys. pub fn xkey_network(&self) -> Option { match self { - DescriptorPublicKey::Single(_) => None, - DescriptorPublicKey::XPub(xpub) => Some(xpub.xkey.network), - DescriptorPublicKey::MultiXPub(multi_xpub) => Some(multi_xpub.xkey.network), + Self::Single(_) => None, + Self::XPub(xpub) => Some(xpub.xkey.network), + Self::MultiXPub(multi_xpub) => Some(multi_xpub.xkey.network), } } } @@ -1058,18 +1058,18 @@ impl FromStr for DescriptorSecretKey { if key_part.len() <= 52 { let sk = bitcoin::PrivateKey::from_str(key_part) .map_err(DescriptorKeyParseError::WifPrivateKey)?; - Ok(DescriptorSecretKey::Single(SinglePriv { key: sk, origin })) + Ok(Self::Single(SinglePriv { key: sk, origin })) } else { let (xpriv, derivation_paths, wildcard) = parse_xkey_deriv(key_part)?; if derivation_paths.len() > 1 { - Ok(DescriptorSecretKey::MultiXPrv(DescriptorMultiXKey { + Ok(Self::MultiXPrv(DescriptorMultiXKey { origin, xkey: xpriv, derivation_paths: DerivPaths::new(derivation_paths).expect("Not empty"), wildcard, })) } else { - Ok(DescriptorSecretKey::XPrv(DescriptorXKey { + Ok(Self::XPrv(DescriptorXKey { origin, xkey: xpriv, derivation_path: derivation_paths.into_iter().next().unwrap_or_default(), @@ -1350,23 +1350,23 @@ impl MiniscriptKey for DescriptorPublicKey { fn is_uncompressed(&self) -> bool { match self { - DescriptorPublicKey::Single(key) => key.is_uncompressed(), + Self::Single(key) => key.is_uncompressed(), _ => false, } } fn is_x_only_key(&self) -> bool { match self { - DescriptorPublicKey::Single(single_pub) => single_pub.is_x_only_key(), + Self::Single(single_pub) => single_pub.is_x_only_key(), _ => false, } } fn num_der_paths(&self) -> usize { match self { - DescriptorPublicKey::Single(single) => single.num_der_paths(), - DescriptorPublicKey::XPub(xpub) => xpub.num_der_paths(), - DescriptorPublicKey::MultiXPub(xpub) => xpub.num_der_paths(), + Self::Single(single) => single.num_der_paths(), + Self::XPub(xpub) => xpub.num_der_paths(), + Self::MultiXPub(xpub) => xpub.num_der_paths(), } } } @@ -1444,7 +1444,7 @@ impl FromStr for DefiniteDescriptorKey { fn from_str(s: &str) -> Result { let d = DescriptorPublicKey::from_str(s)?; - DefiniteDescriptorKey::new(d).map_err(DescriptorKeyParseError::NonDefiniteKey) + Self::new(d).map_err(DescriptorKeyParseError::NonDefiniteKey) } } @@ -1495,7 +1495,7 @@ impl<'de> Deserialize<'de> for DescriptorPublicKey { D: Deserializer<'de>, { let s = String::deserialize(deserializer)?; - DescriptorPublicKey::from_str(&s).map_err(crate::serde::de::Error::custom) + Self::from_str(&s).map_err(crate::serde::de::Error::custom) } } diff --git a/src/descriptor/key_map.rs b/src/descriptor/key_map.rs index 3e193ec87..78474cb6b 100644 --- a/src/descriptor/key_map.rs +++ b/src/descriptor/key_map.rs @@ -109,13 +109,13 @@ impl GetKey for DescriptorSecretKey { secp: &Secp256k1, ) -> Result, Self::Error> { match (self, key_request) { - (DescriptorSecretKey::Single(single_priv), key_request) => { + (Self::Single(single_priv), key_request) => { let sk = single_priv.key; let pk = sk.public_key(secp); let pubkey_map = BTreeMap::from([(pk, sk)]); pubkey_map.get_key(key_request, secp) } - (DescriptorSecretKey::XPrv(descriptor_xkey), KeyRequest::Pubkey(public_key)) => { + (Self::XPrv(descriptor_xkey), KeyRequest::Pubkey(public_key)) => { let xpriv = descriptor_xkey .xkey .derive_priv(secp, &descriptor_xkey.derivation_path) @@ -129,7 +129,7 @@ impl GetKey for DescriptorSecretKey { } } ( - DescriptorSecretKey::XPrv(descriptor_xkey), + Self::XPrv(descriptor_xkey), ref key_request @ KeyRequest::Bip32(ref key_source), ) => { if let Some(key) = descriptor_xkey.xkey.get_key(key_request.clone(), secp)? { @@ -152,11 +152,11 @@ impl GetKey for DescriptorSecretKey { Ok(None) } - (DescriptorSecretKey::XPrv(_), KeyRequest::XOnlyPubkey(_)) => { + (Self::XPrv(_), KeyRequest::XOnlyPubkey(_)) => { Err(GetKeyError::NotSupported) } ( - desc_multi_sk @ DescriptorSecretKey::MultiXPrv(_descriptor_multi_xkey), + desc_multi_sk @ Self::MultiXPrv(_descriptor_multi_xkey), key_request, ) => { for desc_sk in &desc_multi_sk.clone().into_single_keys() { diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index 995276c4b..837b17003 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -80,32 +80,32 @@ pub enum Descriptor { impl From> for Descriptor { #[inline] - fn from(inner: Bare) -> Self { Descriptor::Bare(inner) } + fn from(inner: Bare) -> Self { Self::Bare(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Pkh) -> Self { Descriptor::Pkh(inner) } + fn from(inner: Pkh) -> Self { Self::Pkh(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Wpkh) -> Self { Descriptor::Wpkh(inner) } + fn from(inner: Wpkh) -> Self { Self::Wpkh(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Sh) -> Self { Descriptor::Sh(inner) } + fn from(inner: Sh) -> Self { Self::Sh(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Wsh) -> Self { Descriptor::Wsh(inner) } + fn from(inner: Wsh) -> Self { Self::Wsh(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Tr) -> Self { Descriptor::Tr(inner) } + fn from(inner: Tr) -> Self { Self::Tr(inner) } } /// Descriptor Type of the descriptor @@ -153,19 +153,19 @@ impl Descriptor { Miniscript::from_ast(Terminal::PkK(pk)).expect("Type check cannot fail"), ))) .expect("Type check cannot fail"); - Descriptor::Bare(Bare::new(ms).expect("Context checks cannot fail for p2pk")) + Self::Bare(Bare::new(ms).expect("Context checks cannot fail for p2pk")) } /// Create a new PkH descriptor - pub fn new_pkh(pk: Pk) -> Result { Ok(Descriptor::Pkh(Pkh::new(pk)?)) } + pub fn new_pkh(pk: Pk) -> Result { Ok(Self::Pkh(Pkh::new(pk)?)) } /// Create a new Wpkh descriptor /// Will return Err if uncompressed key is used - pub fn new_wpkh(pk: Pk) -> Result { Ok(Descriptor::Wpkh(Wpkh::new(pk)?)) } + pub fn new_wpkh(pk: Pk) -> Result { Ok(Self::Wpkh(Wpkh::new(pk)?)) } /// Create a new sh wrapped wpkh from `Pk`. /// Errors when uncompressed keys are supplied - pub fn new_sh_wpkh(pk: Pk) -> Result { Ok(Descriptor::Sh(Sh::new_wpkh(pk)?)) } + pub fn new_sh_wpkh(pk: Pk) -> Result { Ok(Self::Sh(Sh::new_wpkh(pk)?)) } // Miniscripts @@ -173,37 +173,37 @@ impl Descriptor { /// Errors when miniscript exceeds resource limits under p2sh context /// or does not type check at the top level pub fn new_sh(ms: Miniscript) -> Result { - Ok(Descriptor::Sh(Sh::new(ms)?)) + Ok(Self::Sh(Sh::new(ms)?)) } /// Create a new wsh descriptor from witness script /// Errors when miniscript exceeds resource limits under p2sh context /// or does not type check at the top level pub fn new_wsh(ms: Miniscript) -> Result { - Ok(Descriptor::Wsh(Wsh::new(ms)?)) + Ok(Self::Wsh(Wsh::new(ms)?)) } /// Create a new sh wrapped wsh descriptor with witness script /// Errors when miniscript exceeds resource limits under wsh context /// or does not type check at the top level pub fn new_sh_wsh(ms: Miniscript) -> Result { - Ok(Descriptor::Sh(Sh::new_wsh(ms)?)) + Ok(Self::Sh(Sh::new_wsh(ms)?)) } /// Create a new bare descriptor from witness script /// Errors when miniscript exceeds resource limits under bare context /// or does not type check at the top level pub fn new_bare(ms: Miniscript) -> Result { - Ok(Descriptor::Bare(Bare::new(ms)?)) + Ok(Self::Bare(Bare::new(ms)?)) } // Wrap with sh /// Create a new sh wrapper for the given wpkh descriptor - pub fn new_sh_with_wpkh(wpkh: Wpkh) -> Self { Descriptor::Sh(Sh::new_with_wpkh(wpkh)) } + pub fn new_sh_with_wpkh(wpkh: Wpkh) -> Self { Self::Sh(Sh::new_with_wpkh(wpkh)) } /// Create a new sh wrapper for the given wsh descriptor - pub fn new_sh_with_wsh(wsh: Wsh) -> Self { Descriptor::Sh(Sh::new_with_wsh(wsh)) } + pub fn new_sh_with_wsh(wsh: Wsh) -> Self { Self::Sh(Sh::new_with_wsh(wsh)) } // sorted multi @@ -213,7 +213,7 @@ impl Descriptor { pub fn new_sh_sortedmulti( thresh: Threshold, ) -> Result { - Ok(Descriptor::Sh(Sh::new_sortedmulti(thresh)?)) + Ok(Self::Sh(Sh::new_sortedmulti(thresh)?)) } /// Create a new sh wrapped wsh sortedmulti descriptor from threshold @@ -222,7 +222,7 @@ impl Descriptor { pub fn new_sh_wsh_sortedmulti( thresh: Threshold, ) -> Result { - Ok(Descriptor::Sh(Sh::new_wsh_sortedmulti(thresh)?)) + Ok(Self::Sh(Sh::new_wsh_sortedmulti(thresh)?)) } /// Create a new wsh sorted multi descriptor @@ -230,34 +230,34 @@ impl Descriptor { pub fn new_wsh_sortedmulti( thresh: Threshold, ) -> Result { - Ok(Descriptor::Wsh(Wsh::new_sortedmulti(thresh)?)) + Ok(Self::Wsh(Wsh::new_sortedmulti(thresh)?)) } /// Create new tr descriptor /// Errors when miniscript exceeds resource limits under Tap context pub fn new_tr(key: Pk, script: Option>) -> Result { - Ok(Descriptor::Tr(Tr::new(key, script)?)) + Ok(Self::Tr(Tr::new(key, script)?)) } /// An iterator over all the keys referenced in the descriptor. pub fn iter_pk(&self) -> PkIter<'_, Pk> { match *self { - Descriptor::Bare(ref bare) => PkIter::from_miniscript_bare(bare.as_inner()), - Descriptor::Pkh(ref pk) => PkIter::from_key(pk.as_inner().clone()), - Descriptor::Wpkh(ref pk) => PkIter::from_key(pk.as_inner().clone()), - Descriptor::Sh(ref sh) => match *sh.as_inner() { + Self::Bare(ref bare) => PkIter::from_miniscript_bare(bare.as_inner()), + Self::Pkh(ref pk) => PkIter::from_key(pk.as_inner().clone()), + Self::Wpkh(ref pk) => PkIter::from_key(pk.as_inner().clone()), + Self::Sh(ref sh) => match *sh.as_inner() { ShInner::Wsh(ref wsh) => PkIter::from_miniscript_segwit(wsh.as_inner()), ShInner::Wpkh(ref pk) => PkIter::from_key(pk.as_inner().clone()), ShInner::Ms(ref ms) => PkIter::from_miniscript_legacy(ms), }, - Descriptor::Wsh(ref wsh) => PkIter::from_miniscript_segwit(wsh.as_inner()), - Descriptor::Tr(ref tr) => PkIter::from_tr(tr), + Self::Wsh(ref wsh) => PkIter::from_miniscript_segwit(wsh.as_inner()), + Self::Tr(ref tr) => PkIter::from_tr(tr), } } /// For a Taproot descriptor, returns the internal key. pub fn internal_key(&self) -> Option<&Pk> { - if let Descriptor::Tr(ref tr) = self { + if let Self::Tr(ref tr) = self { Some(tr.internal_key()) } else { None @@ -269,7 +269,7 @@ impl Descriptor { /// To obtain the individual leaves of the tree, call [`TapTree::leaves`] on the /// returned value. pub fn tap_tree(&self) -> Option<&TapTree> { - if let Descriptor::Tr(ref tr) = self { + if let Self::Tr(ref tr) = self { tr.tap_tree() } else { None @@ -281,7 +281,7 @@ impl Descriptor { /// If the descriptor is not a Taproot descriptor, **or** if the descriptor is a /// Taproot descriptor containing only a keyspend, returns an empty iterator. pub fn tap_tree_iter(&self) -> tr::TapTreeIter<'_, Pk> { - if let Descriptor::Tr(ref tr) = self { + if let Self::Tr(ref tr) = self { if let Some(tree) = tr.tap_tree() { return tree.leaves(); } @@ -292,16 +292,16 @@ impl Descriptor { /// Get the [DescriptorType] of [Descriptor] pub fn desc_type(&self) -> DescriptorType { match *self { - Descriptor::Bare(..) => DescriptorType::Bare, - Descriptor::Pkh(..) => DescriptorType::Pkh, - Descriptor::Wpkh(..) => DescriptorType::Wpkh, - Descriptor::Sh(ref sh) => match sh.as_inner() { + Self::Bare(..) => DescriptorType::Bare, + Self::Pkh(..) => DescriptorType::Pkh, + Self::Wpkh(..) => DescriptorType::Wpkh, + Self::Sh(ref sh) => match sh.as_inner() { ShInner::Wsh(..) => DescriptorType::ShWsh, ShInner::Wpkh(ref _wpkh) => DescriptorType::ShWpkh, ShInner::Ms(..) => DescriptorType::Sh, }, - Descriptor::Wsh(..) => DescriptorType::Wsh, - Descriptor::Tr(..) => DescriptorType::Tr, + Self::Wsh(..) => DescriptorType::Wsh, + Self::Tr(..) => DescriptorType::Tr, } } @@ -316,12 +316,12 @@ impl Descriptor { /// The signer may not be able to find satisfactions even if one exists. pub fn sanity_check(&self) -> Result<(), Error> { match *self { - Descriptor::Bare(ref bare) => bare.sanity_check(), - Descriptor::Pkh(_) => Ok(()), - Descriptor::Wpkh(ref wpkh) => wpkh.sanity_check(), - Descriptor::Wsh(ref wsh) => wsh.sanity_check(), - Descriptor::Sh(ref sh) => sh.sanity_check(), - Descriptor::Tr(ref tr) => tr.sanity_check(), + Self::Bare(ref bare) => bare.sanity_check(), + Self::Pkh(_) => Ok(()), + Self::Wpkh(ref wpkh) => wpkh.sanity_check(), + Self::Wsh(ref wsh) => wsh.sanity_check(), + Self::Sh(ref sh) => sh.sanity_check(), + Self::Tr(ref tr) => tr.sanity_check(), } } @@ -365,12 +365,12 @@ impl Descriptor { /// When the descriptor is impossible to safisfy (ex: sh(OP_FALSE)). pub fn max_weight_to_satisfy(&self) -> Result { let weight = match *self { - Descriptor::Bare(ref bare) => bare.max_weight_to_satisfy()?, - Descriptor::Pkh(ref pkh) => pkh.max_weight_to_satisfy(), - Descriptor::Wpkh(ref wpkh) => wpkh.max_weight_to_satisfy(), - Descriptor::Wsh(ref wsh) => wsh.max_weight_to_satisfy()?, - Descriptor::Sh(ref sh) => sh.max_weight_to_satisfy()?, - Descriptor::Tr(ref tr) => tr.max_weight_to_satisfy()?, + Self::Bare(ref bare) => bare.max_weight_to_satisfy()?, + Self::Pkh(ref pkh) => pkh.max_weight_to_satisfy(), + Self::Wpkh(ref wpkh) => wpkh.max_weight_to_satisfy(), + Self::Wsh(ref wsh) => wsh.max_weight_to_satisfy()?, + Self::Sh(ref sh) => sh.max_weight_to_satisfy()?, + Self::Tr(ref tr) => tr.max_weight_to_satisfy()?, }; Ok(weight) } @@ -391,12 +391,12 @@ impl Descriptor { #[allow(deprecated)] pub fn max_satisfaction_weight(&self) -> Result { let weight = match *self { - Descriptor::Bare(ref bare) => bare.max_satisfaction_weight()?, - Descriptor::Pkh(ref pkh) => pkh.max_satisfaction_weight(), - Descriptor::Wpkh(ref wpkh) => wpkh.max_satisfaction_weight(), - Descriptor::Wsh(ref wsh) => wsh.max_satisfaction_weight()?, - Descriptor::Sh(ref sh) => sh.max_satisfaction_weight()?, - Descriptor::Tr(ref tr) => tr.max_satisfaction_weight()?, + Self::Bare(ref bare) => bare.max_satisfaction_weight()?, + Self::Pkh(ref pkh) => pkh.max_satisfaction_weight(), + Self::Wpkh(ref wpkh) => wpkh.max_satisfaction_weight(), + Self::Wsh(ref wsh) => wsh.max_satisfaction_weight()?, + Self::Sh(ref sh) => sh.max_satisfaction_weight()?, + Self::Tr(ref tr) => tr.max_satisfaction_weight()?, }; Ok(weight) } @@ -410,12 +410,12 @@ impl Descriptor { T: Translator, { let desc = match *self { - Descriptor::Bare(ref bare) => Descriptor::Bare(bare.translate_pk(t)?), - Descriptor::Pkh(ref pk) => Descriptor::Pkh(pk.translate_pk(t)?), - Descriptor::Wpkh(ref pk) => Descriptor::Wpkh(pk.translate_pk(t)?), - Descriptor::Sh(ref sh) => Descriptor::Sh(sh.translate_pk(t)?), - Descriptor::Wsh(ref wsh) => Descriptor::Wsh(wsh.translate_pk(t)?), - Descriptor::Tr(ref tr) => Descriptor::Tr(tr.translate_pk(t)?), + Self::Bare(ref bare) => Descriptor::Bare(bare.translate_pk(t)?), + Self::Pkh(ref pk) => Descriptor::Pkh(pk.translate_pk(t)?), + Self::Wpkh(ref pk) => Descriptor::Wpkh(pk.translate_pk(t)?), + Self::Sh(ref sh) => Descriptor::Sh(sh.translate_pk(t)?), + Self::Wsh(ref wsh) => Descriptor::Wsh(wsh.translate_pk(t)?), + Self::Tr(ref tr) => Descriptor::Tr(tr.translate_pk(t)?), }; Ok(desc) } @@ -430,24 +430,24 @@ impl Descriptor { /// For raw/bare descriptors that don't have an address. pub fn address(&self, network: Network) -> Result { match *self { - Descriptor::Bare(_) => Err(Error::BareDescriptorAddr), - Descriptor::Pkh(ref pkh) => Ok(pkh.address(network)), - Descriptor::Wpkh(ref wpkh) => Ok(wpkh.address(network)), - Descriptor::Wsh(ref wsh) => Ok(wsh.address(network)), - Descriptor::Sh(ref sh) => Ok(sh.address(network)), - Descriptor::Tr(ref tr) => Ok(tr.address(network)), + Self::Bare(_) => Err(Error::BareDescriptorAddr), + Self::Pkh(ref pkh) => Ok(pkh.address(network)), + Self::Wpkh(ref wpkh) => Ok(wpkh.address(network)), + Self::Wsh(ref wsh) => Ok(wsh.address(network)), + Self::Sh(ref sh) => Ok(sh.address(network)), + Self::Tr(ref tr) => Ok(tr.address(network)), } } /// Computes the scriptpubkey of the descriptor. pub fn script_pubkey(&self) -> ScriptBuf { match *self { - Descriptor::Bare(ref bare) => bare.script_pubkey(), - Descriptor::Pkh(ref pkh) => pkh.script_pubkey(), - Descriptor::Wpkh(ref wpkh) => wpkh.script_pubkey(), - Descriptor::Wsh(ref wsh) => wsh.script_pubkey(), - Descriptor::Sh(ref sh) => sh.script_pubkey(), - Descriptor::Tr(ref tr) => tr.script_pubkey(), + Self::Bare(ref bare) => bare.script_pubkey(), + Self::Pkh(ref pkh) => pkh.script_pubkey(), + Self::Wpkh(ref wpkh) => wpkh.script_pubkey(), + Self::Wsh(ref wsh) => wsh.script_pubkey(), + Self::Sh(ref sh) => sh.script_pubkey(), + Self::Tr(ref tr) => tr.script_pubkey(), } } @@ -460,12 +460,12 @@ impl Descriptor { /// will change). pub fn unsigned_script_sig(&self) -> ScriptBuf { match *self { - Descriptor::Bare(_) => ScriptBuf::new(), - Descriptor::Pkh(_) => ScriptBuf::new(), - Descriptor::Wpkh(_) => ScriptBuf::new(), - Descriptor::Wsh(_) => ScriptBuf::new(), - Descriptor::Sh(ref sh) => sh.unsigned_script_sig(), - Descriptor::Tr(_) => ScriptBuf::new(), + Self::Bare(_) => ScriptBuf::new(), + Self::Pkh(_) => ScriptBuf::new(), + Self::Wpkh(_) => ScriptBuf::new(), + Self::Wsh(_) => ScriptBuf::new(), + Self::Sh(ref sh) => sh.unsigned_script_sig(), + Self::Tr(_) => ScriptBuf::new(), } } @@ -477,12 +477,12 @@ impl Descriptor { /// If the descriptor is a taproot descriptor. pub fn explicit_script(&self) -> Result { match *self { - Descriptor::Bare(ref bare) => Ok(bare.script_pubkey()), - Descriptor::Pkh(ref pkh) => Ok(pkh.script_pubkey()), - Descriptor::Wpkh(ref wpkh) => Ok(wpkh.script_pubkey()), - Descriptor::Wsh(ref wsh) => Ok(wsh.inner_script()), - Descriptor::Sh(ref sh) => Ok(sh.inner_script()), - Descriptor::Tr(_) => Err(Error::TrNoScriptCode), + Self::Bare(ref bare) => Ok(bare.script_pubkey()), + Self::Pkh(ref pkh) => Ok(pkh.script_pubkey()), + Self::Wpkh(ref wpkh) => Ok(wpkh.script_pubkey()), + Self::Wsh(ref wsh) => Ok(wsh.inner_script()), + Self::Sh(ref sh) => Ok(sh.inner_script()), + Self::Tr(_) => Err(Error::TrNoScriptCode), } } @@ -495,12 +495,12 @@ impl Descriptor { /// If the descriptor is a taproot descriptor. pub fn script_code(&self) -> Result { match *self { - Descriptor::Bare(ref bare) => Ok(bare.ecdsa_sighash_script_code()), - Descriptor::Pkh(ref pkh) => Ok(pkh.ecdsa_sighash_script_code()), - Descriptor::Wpkh(ref wpkh) => Ok(wpkh.ecdsa_sighash_script_code()), - Descriptor::Wsh(ref wsh) => Ok(wsh.ecdsa_sighash_script_code()), - Descriptor::Sh(ref sh) => Ok(sh.ecdsa_sighash_script_code()), - Descriptor::Tr(_) => Err(Error::TrNoScriptCode), + Self::Bare(ref bare) => Ok(bare.ecdsa_sighash_script_code()), + Self::Pkh(ref pkh) => Ok(pkh.ecdsa_sighash_script_code()), + Self::Wpkh(ref wpkh) => Ok(wpkh.ecdsa_sighash_script_code()), + Self::Wsh(ref wsh) => Ok(wsh.ecdsa_sighash_script_code()), + Self::Sh(ref sh) => Ok(sh.ecdsa_sighash_script_code()), + Self::Tr(_) => Err(Error::TrNoScriptCode), } } @@ -512,12 +512,12 @@ impl Descriptor { S: Satisfier, { match *self { - Descriptor::Bare(ref bare) => bare.get_satisfaction(satisfier), - Descriptor::Pkh(ref pkh) => pkh.get_satisfaction(satisfier), - Descriptor::Wpkh(ref wpkh) => wpkh.get_satisfaction(satisfier), - Descriptor::Wsh(ref wsh) => wsh.get_satisfaction(satisfier), - Descriptor::Sh(ref sh) => sh.get_satisfaction(satisfier), - Descriptor::Tr(ref tr) => tr.get_satisfaction(&satisfier), + Self::Bare(ref bare) => bare.get_satisfaction(satisfier), + Self::Pkh(ref pkh) => pkh.get_satisfaction(satisfier), + Self::Wpkh(ref wpkh) => wpkh.get_satisfaction(satisfier), + Self::Wsh(ref wsh) => wsh.get_satisfaction(satisfier), + Self::Sh(ref sh) => sh.get_satisfaction(satisfier), + Self::Tr(ref tr) => tr.get_satisfaction(&satisfier), } } @@ -529,12 +529,12 @@ impl Descriptor { S: Satisfier, { match *self { - Descriptor::Bare(ref bare) => bare.get_satisfaction_mall(satisfier), - Descriptor::Pkh(ref pkh) => pkh.get_satisfaction_mall(satisfier), - Descriptor::Wpkh(ref wpkh) => wpkh.get_satisfaction_mall(satisfier), - Descriptor::Wsh(ref wsh) => wsh.get_satisfaction_mall(satisfier), - Descriptor::Sh(ref sh) => sh.get_satisfaction_mall(satisfier), - Descriptor::Tr(ref tr) => tr.get_satisfaction_mall(&satisfier), + Self::Bare(ref bare) => bare.get_satisfaction_mall(satisfier), + Self::Pkh(ref pkh) => pkh.get_satisfaction_mall(satisfier), + Self::Wpkh(ref wpkh) => wpkh.get_satisfaction_mall(satisfier), + Self::Wsh(ref wsh) => wsh.get_satisfaction_mall(satisfier), + Self::Sh(ref sh) => sh.get_satisfaction_mall(satisfier), + Self::Tr(ref tr) => tr.get_satisfaction_mall(&satisfier), } } @@ -574,12 +574,12 @@ impl Descriptor { P: AssetProvider, { let satisfaction = match self { - Descriptor::Bare(ref bare) => bare.plan_satisfaction(provider), - Descriptor::Pkh(ref pkh) => pkh.plan_satisfaction(provider), - Descriptor::Wpkh(ref wpkh) => wpkh.plan_satisfaction(provider), - Descriptor::Wsh(ref wsh) => wsh.plan_satisfaction(provider), - Descriptor::Sh(ref sh) => sh.plan_satisfaction(provider), - Descriptor::Tr(ref tr) => tr.plan_satisfaction(provider), + Self::Bare(ref bare) => bare.plan_satisfaction(provider), + Self::Pkh(ref pkh) => pkh.plan_satisfaction(provider), + Self::Wpkh(ref wpkh) => wpkh.plan_satisfaction(provider), + Self::Wsh(ref wsh) => wsh.plan_satisfaction(provider), + Self::Sh(ref sh) => sh.plan_satisfaction(provider), + Self::Tr(ref tr) => tr.plan_satisfaction(provider), }; if let satisfy::Witness::Stack(stack) = satisfaction.stack { @@ -615,12 +615,12 @@ impl Descriptor { P: AssetProvider, { let satisfaction = match self { - Descriptor::Bare(ref bare) => bare.plan_satisfaction_mall(provider), - Descriptor::Pkh(ref pkh) => pkh.plan_satisfaction_mall(provider), - Descriptor::Wpkh(ref wpkh) => wpkh.plan_satisfaction_mall(provider), - Descriptor::Wsh(ref wsh) => wsh.plan_satisfaction_mall(provider), - Descriptor::Sh(ref sh) => sh.plan_satisfaction_mall(provider), - Descriptor::Tr(ref tr) => tr.plan_satisfaction_mall(provider), + Self::Bare(ref bare) => bare.plan_satisfaction_mall(provider), + Self::Pkh(ref pkh) => pkh.plan_satisfaction_mall(provider), + Self::Wpkh(ref wpkh) => wpkh.plan_satisfaction_mall(provider), + Self::Wsh(ref wsh) => wsh.plan_satisfaction_mall(provider), + Self::Sh(ref sh) => sh.plan_satisfaction_mall(provider), + Self::Tr(ref tr) => tr.plan_satisfaction_mall(provider), }; if let satisfy::Witness::Stack(stack) = satisfaction.stack { @@ -640,12 +640,12 @@ impl Descriptor { impl ForEachKey for Descriptor { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: F) -> bool { match *self { - Descriptor::Bare(ref bare) => bare.for_each_key(pred), - Descriptor::Pkh(ref pkh) => pkh.for_each_key(pred), - Descriptor::Wpkh(ref wpkh) => wpkh.for_each_key(pred), - Descriptor::Wsh(ref wsh) => wsh.for_each_key(pred), - Descriptor::Sh(ref sh) => sh.for_each_key(pred), - Descriptor::Tr(ref tr) => tr.for_each_key(pred), + Self::Bare(ref bare) => bare.for_each_key(pred), + Self::Pkh(ref pkh) => pkh.for_each_key(pred), + Self::Wpkh(ref wpkh) => wpkh.for_each_key(pred), + Self::Wsh(ref wsh) => wsh.for_each_key(pred), + Self::Sh(ref sh) => sh.for_each_key(pred), + Self::Tr(ref tr) => tr.for_each_key(pred), } } } @@ -790,7 +790,7 @@ impl Descriptor { pub fn parse_descriptor( secp: &secp256k1::Secp256k1, s: &str, - ) -> Result<(Descriptor, KeyMap), Error> { + ) -> Result<(Self, KeyMap), Error> { fn parse_key( s: &str, key_map: &mut KeyMap, @@ -943,7 +943,7 @@ impl Descriptor { /// For multipath descriptors it will return as many descriptors as there is /// "parallel" paths. For regular descriptors it will just return itself. #[allow(clippy::blocks_in_conditions)] - pub fn into_single_descriptors(self) -> Result>, Error> { + pub fn into_single_descriptors(self) -> Result, Error> { // All single-path descriptors contained in this descriptor. let mut descriptors = Vec::new(); // We (ab)use `for_any_key` to gather the number of separate descriptors. @@ -1121,24 +1121,24 @@ impl Descriptor { impl crate::expression::FromTree for Descriptor { /// Parse an expression tree into a descriptor. - fn from_tree(top: expression::TreeIterItem) -> Result, Error> { + fn from_tree(top: expression::TreeIterItem) -> Result { Ok(match (top.name(), top.n_children()) { - ("pkh", 1) => Descriptor::Pkh(Pkh::from_tree(top)?), - ("wpkh", 1) => Descriptor::Wpkh(Wpkh::from_tree(top)?), - ("sh", 1) => Descriptor::Sh(Sh::from_tree(top)?), - ("wsh", 1) => Descriptor::Wsh(Wsh::from_tree(top)?), - ("tr", _) => Descriptor::Tr(Tr::from_tree(top)?), - _ => Descriptor::Bare(Bare::from_tree(top)?), + ("pkh", 1) => Self::Pkh(Pkh::from_tree(top)?), + ("wpkh", 1) => Self::Wpkh(Wpkh::from_tree(top)?), + ("sh", 1) => Self::Sh(Sh::from_tree(top)?), + ("wsh", 1) => Self::Wsh(Wsh::from_tree(top)?), + ("tr", _) => Self::Tr(Tr::from_tree(top)?), + _ => Self::Bare(Bare::from_tree(top)?), }) } } impl FromStr for Descriptor { type Err = Error; - fn from_str(s: &str) -> Result, Error> { + fn from_str(s: &str) -> Result { let top = expression::Tree::from_str(s)?; let ret = Self::from_tree(top.root())?; - if let Descriptor::Tr(ref inner) = ret { + if let Self::Tr(ref inner) = ret { // FIXME preserve weird/broken behavior from 12.x. // See https://github.com/rust-bitcoin/rust-miniscript/issues/734 ret.sanity_check()?; @@ -1154,12 +1154,12 @@ impl FromStr for Descriptor { impl fmt::Debug for Descriptor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Descriptor::Bare(ref sub) => fmt::Debug::fmt(sub, f), - Descriptor::Pkh(ref pkh) => fmt::Debug::fmt(pkh, f), - Descriptor::Wpkh(ref wpkh) => fmt::Debug::fmt(wpkh, f), - Descriptor::Sh(ref sub) => fmt::Debug::fmt(sub, f), - Descriptor::Wsh(ref sub) => fmt::Debug::fmt(sub, f), - Descriptor::Tr(ref tr) => fmt::Debug::fmt(tr, f), + Self::Bare(ref sub) => fmt::Debug::fmt(sub, f), + Self::Pkh(ref pkh) => fmt::Debug::fmt(pkh, f), + Self::Wpkh(ref wpkh) => fmt::Debug::fmt(wpkh, f), + Self::Sh(ref sub) => fmt::Debug::fmt(sub, f), + Self::Wsh(ref sub) => fmt::Debug::fmt(sub, f), + Self::Tr(ref tr) => fmt::Debug::fmt(tr, f), } } } @@ -1167,12 +1167,12 @@ impl fmt::Debug for Descriptor { impl fmt::Display for Descriptor { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Descriptor::Bare(ref sub) => fmt::Display::fmt(sub, f), - Descriptor::Pkh(ref pkh) => fmt::Display::fmt(pkh, f), - Descriptor::Wpkh(ref wpkh) => fmt::Display::fmt(wpkh, f), - Descriptor::Sh(ref sub) => fmt::Display::fmt(sub, f), - Descriptor::Wsh(ref sub) => fmt::Display::fmt(sub, f), - Descriptor::Tr(ref tr) => fmt::Display::fmt(tr, f), + Self::Bare(ref sub) => fmt::Display::fmt(sub, f), + Self::Pkh(ref pkh) => fmt::Display::fmt(pkh, f), + Self::Wpkh(ref wpkh) => fmt::Display::fmt(wpkh, f), + Self::Sh(ref sub) => fmt::Display::fmt(sub, f), + Self::Wsh(ref sub) => fmt::Display::fmt(sub, f), + Self::Tr(ref tr) => fmt::Display::fmt(tr, f), } } } diff --git a/src/descriptor/segwitv0.rs b/src/descriptor/segwitv0.rs index 883ac7b1b..3fbae0bf3 100644 --- a/src/descriptor/segwitv0.rs +++ b/src/descriptor/segwitv0.rs @@ -194,7 +194,7 @@ impl crate::expression::FromTree for Wsh { let sub = Miniscript::from_tree(top)?; Segwitv0::top_level_checks(&sub)?; - Ok(Wsh { ms: sub }) + Ok(Self { ms: sub }) } } @@ -212,7 +212,7 @@ impl core::str::FromStr for Wsh { type Err = Error; fn from_str(s: &str) -> Result { let top = expression::Tree::from_str(s)?; - Wsh::::from_tree(top.root()) + Self::from_tree(top.root()) } } @@ -234,7 +234,7 @@ impl Wpkh { pub fn new(pk: Pk) -> Result { // do the top-level checks match Segwitv0::check_pk(&pk) { - Ok(_) => Ok(Wpkh { pk }), + Ok(_) => Ok(Self { pk }), Err(e) => Err(e), } } @@ -404,7 +404,7 @@ impl crate::expression::FromTree for Wpkh { let pk = top .verify_terminal_parent("wpkh", "public key") .map_err(Error::Parse)?; - Wpkh::new(pk).map_err(Error::ContextError) + Self::new(pk).map_err(Error::ContextError) } } diff --git a/src/descriptor/sh.rs b/src/descriptor/sh.rs index c824c7bda..c8e9578df 100644 --- a/src/descriptor/sh.rs +++ b/src/descriptor/sh.rs @@ -92,7 +92,7 @@ impl crate::expression::FromTree for Sh { ShInner::Ms(sub) } }; - Ok(Sh { inner }) + Ok(Self { inner }) } } diff --git a/src/descriptor/tr/mod.rs b/src/descriptor/tr/mod.rs index 47a72cfff..a0e3f346b 100644 --- a/src/descriptor/tr/mod.rs +++ b/src/descriptor/tr/mod.rs @@ -360,7 +360,7 @@ impl crate::expression::FromTree for Tr { .map_err(Error::Parse)?; let tap_tree = match root_children.next() { - None => return Tr::new(internal_key, None), + None => return Self::new(internal_key, None), Some(tree) => tree, }; @@ -391,7 +391,7 @@ impl crate::expression::FromTree for Tr { tap_tree_iter.skip_descendants(); } } - Tr::new(internal_key, Some(tree_builder.finalize())) + Self::new(internal_key, Some(tree_builder.finalize())) } } diff --git a/src/descriptor/tr/spend_info.rs b/src/descriptor/tr/spend_info.rs index b0d23121d..e857d262f 100644 --- a/src/descriptor/tr/spend_info.rs +++ b/src/descriptor/tr/spend_info.rs @@ -149,7 +149,7 @@ impl TrSpendInfo { let (output_key, output_key_parity) = internal_key.tap_tweak(&secp, nodes.first().map(|node| node.sibling_hash)); - TrSpendInfo { internal_key, output_key, output_key_parity, nodes } + Self { internal_key, output_key, output_key_parity, nodes } } /// If this [`TrSpendInfo`] has an associated Taproot tree, return its Merkle root. diff --git a/src/descriptor/tr/taptree.rs b/src/descriptor/tr/taptree.rs index 27e860390..e7db70beb 100644 --- a/src/descriptor/tr/taptree.rs +++ b/src/descriptor/tr/taptree.rs @@ -33,11 +33,11 @@ pub struct TapTree { impl TapTree { /// Creates a `TapTree` leaf from a Miniscript. pub fn leaf>>>(ms: A) -> Self { - TapTree { depths_leaves: vec![(0, ms.into())] } + Self { depths_leaves: vec![(0, ms.into())] } } /// Creates a `TapTree` by combining `left` and `right` tree nodes. - pub fn combine(left: TapTree, right: TapTree) -> Result { + pub fn combine(left: Self, right: Self) -> Result { let mut depths_leaves = Vec::with_capacity(left.depths_leaves.len() + right.depths_leaves.len()); for (depth, leaf) in left.depths_leaves.iter().chain(right.depths_leaves.iter()) { diff --git a/src/descriptor/wallet_policy/key_expression.rs b/src/descriptor/wallet_policy/key_expression.rs index eac27480b..ec31a50e5 100644 --- a/src/descriptor/wallet_policy/key_expression.rs +++ b/src/descriptor/wallet_policy/key_expression.rs @@ -27,7 +27,7 @@ pub struct KeyExpression { pub struct KeyIndex(pub u32); impl KeyExpression { - pub fn is_disjoint(&self, other: &KeyExpression) -> bool { + pub fn is_disjoint(&self, other: &Self) -> bool { let lhs: BTreeSet<_> = self .derivation_paths .paths() @@ -57,7 +57,7 @@ impl TryFrom<&str> for KeyExpression { } let (ki, derivation_paths, wildcard) = parse_xkey_deriv(&s.replace(RECEIVE_CHANGE_SHORTHAND, RECEIVE_CHANGE_PATH))?; - Ok(KeyExpression { + Ok(Self { index: ki, derivation_paths: DerivPaths::new(derivation_paths) .ok_or(WalletPolicyError::KeyExpressionParseMustHaveDerivPath)?, @@ -125,7 +125,7 @@ impl FromStr for KeyIndex { let index = index_str .parse() .map_err(|_| WalletPolicyError::KeyIndexParseInvalidIndex(index_str))?; - Ok(KeyIndex(index)) + Ok(Self(index)) } Some(ch) => Err(WalletPolicyError::KeyIndexParseExpectedAtSign(ch)), None => Err(WalletPolicyError::KeyIndexParseInvalidIndex(s.into())), diff --git a/src/descriptor/wallet_policy/mod.rs b/src/descriptor/wallet_policy/mod.rs index e170ddc39..f78c8c640 100644 --- a/src/descriptor/wallet_policy/mod.rs +++ b/src/descriptor/wallet_policy/mod.rs @@ -130,9 +130,9 @@ impl WalletPolicy { /// template. pub fn from_descriptor_unchecked( descriptor: &Descriptor, - ) -> Result { + ) -> Result { let mut translator = WalletPolicyTranslator { key_info: descriptor.iter_pk().collect() }; - Ok(WalletPolicy { + Ok(Self { template: descriptor.translate_pk(&mut translator).map_err(|e| { e.expect_translator_err("converting descriptor to wallet policy template") })?, @@ -144,8 +144,8 @@ impl WalletPolicy { /// validates the underyling template. pub fn from_descriptor( descriptor: &Descriptor, - ) -> Result { - WalletPolicy::from_descriptor_unchecked(descriptor).and_then(WalletPolicy::validate) + ) -> Result { + Self::from_descriptor_unchecked(descriptor).and_then(Self::validate) } /// Convert a `WalletPolicy` into a `Descriptor` using @@ -170,7 +170,7 @@ impl WalletPolicy { /// Validates the wallet policy template. #[must_use = "Wallet policy won't be considered valid until this is called"] - fn validate(self) -> Result { + fn validate(self) -> Result { // HACK: don't know how else to prevent the following invalid cases from // the test vectors while still using the current Descriptor parsing: // skipped or out of order placeholders, repeated placeholds, @@ -198,7 +198,7 @@ impl TryFrom<&Descriptor> for WalletPolicy { type Error = WalletPolicyError; fn try_from(desc: &Descriptor) -> Result { - WalletPolicy::from_descriptor(desc) + Self::from_descriptor(desc) } } @@ -207,9 +207,9 @@ impl TryFrom<&str> for WalletPolicy { fn try_from(desc: &str) -> Result { match Descriptor::::from_str(desc) { - Ok(template) => Ok(WalletPolicy { template, key_info: vec![] }.validate()?), + Ok(template) => Ok(Self { template, key_info: vec![] }.validate()?), Err(err1) => match Descriptor::::from_str(desc) { - Ok(desc) => Ok(WalletPolicy::from_descriptor(&desc)?), + Ok(desc) => Ok(Self::from_descriptor(&desc)?), Err(err2) => Err(WalletPolicyError::WalletPolicyParseFromString(format!( "Couldn't parse from descriptor [{err1}], or wallet policy template: [{err2}]" ))), @@ -254,7 +254,7 @@ pub enum WalletPolicyError { impl From for DescriptorKeyParseError { fn from(err: WalletPolicyError) -> Self { - DescriptorKeyParseError::XKeyParseError(XKeyParseError::Bip388(err)) + Self::XKeyParseError(XKeyParseError::Bip388(err)) } } @@ -266,41 +266,41 @@ impl std::error::Error for WalletPolicyError { impl Display for WalletPolicyError { fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { - WalletPolicyError::KeyExpressionParseMustHaveDerivPath => { + Self::KeyExpressionParseMustHaveDerivPath => { write!(f, "Key expression placeholder must have a derivation path after it") } - WalletPolicyError::KeyExpressionParseInvalidDerivPath => { + Self::KeyExpressionParseInvalidDerivPath => { write!( f, "Key expression placeholder must be of the format \"/**\" or \"//*\"" ) } - WalletPolicyError::KeyIndexParseInvalidIndex(index_str) => { + Self::KeyIndexParseInvalidIndex(index_str) => { write!(f, "Couldn't parse index, got {index_str}") } - WalletPolicyError::KeyIndexParseExpectedAtSign(ch) => { + Self::KeyIndexParseExpectedAtSign(ch) => { write!(f, "Expected KeyIndex '@' sign, got {ch}") } - WalletPolicyError::KeyInfoInvalidKeyIndex(idx) => { + Self::KeyInfoInvalidKeyIndex(idx) => { write!(f, "Invalid index [{idx}] into key info for wallet policy") } - WalletPolicyError::TemplateValidationKeyIndexOutOfOrder => { + Self::TemplateValidationKeyIndexOutOfOrder => { write!(f, "The template has indexes that are out of order") } - WalletPolicyError::TemplateValidationNonDisjointPaths => { + Self::TemplateValidationNonDisjointPaths => { write!(f, "The template has identical indexes but the paths are non-disjoint") } - WalletPolicyError::TranslatorEmptyDerivationPaths => { + Self::TranslatorEmptyDerivationPaths => { write!(f, "Expected derivation paths when translating into KeyExpression") } - WalletPolicyError::TranslatorMissingWildcard => { + Self::TranslatorMissingWildcard => { write!(f, "Missing wildcard. Not an xpub?") } - WalletPolicyError::WalletPolicyParseFromString(msg) => msg.fmt(f), - WalletPolicyError::WalletPolicyInvalidKeyInfo => { + Self::WalletPolicyParseFromString(msg) => msg.fmt(f), + Self::WalletPolicyInvalidKeyInfo => { write!(f, "Invalid key information for WalletPolicy template") } - WalletPolicyError::TranslatorInvalidHashHex(kind, raw) => { + Self::TranslatorInvalidHashHex(kind, raw) => { write!(f, "Invalid hex for {kind} hash terminal: {raw}") } } @@ -308,7 +308,7 @@ impl Display for WalletPolicyError { } impl From for XKeyParseError { - fn from(err: WalletPolicyError) -> Self { XKeyParseError::Bip388(err) } + fn from(err: WalletPolicyError) -> Self { Self::Bip388(err) } } #[cfg(test)] diff --git a/src/error.rs b/src/error.rs index fc2467a08..5014adba0 100644 --- a/src/error.rs +++ b/src/error.rs @@ -34,7 +34,7 @@ pub enum ParseError { impl ParseError { /// Boxes a `FromStr` error for a `Pk` (or associated types) into a `ParseError` pub(crate) fn box_from_str(e: E) -> Self { - ParseError::FromStr(Box::new(e)) + Self::FromStr(Box::new(e)) } } @@ -49,11 +49,11 @@ impl From for ParseError { impl fmt::Display for ParseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - ParseError::AbsoluteLockTime(ref e) => e.fmt(f), - ParseError::RelativeLockTime(ref e) => e.fmt(f), - ParseError::FromStr(ref e) => e.fmt(f), - ParseError::Num(ref e) => e.fmt(f), - ParseError::Tree(ref e) => e.fmt(f), + Self::AbsoluteLockTime(ref e) => e.fmt(f), + Self::RelativeLockTime(ref e) => e.fmt(f), + Self::FromStr(ref e) => e.fmt(f), + Self::Num(ref e) => e.fmt(f), + Self::Tree(ref e) => e.fmt(f), } } } @@ -62,11 +62,11 @@ impl fmt::Display for ParseError { impl error::Error for ParseError { fn source(&self) -> Option<&(dyn error::Error + 'static)> { match self { - ParseError::AbsoluteLockTime(ref e) => Some(e), - ParseError::RelativeLockTime(ref e) => Some(e), - ParseError::FromStr(..) => None, - ParseError::Num(ref e) => Some(e), - ParseError::Tree(ref e) => Some(e), + Self::AbsoluteLockTime(ref e) => Some(e), + Self::RelativeLockTime(ref e) => Some(e), + Self::FromStr(..) => None, + Self::Num(ref e) => Some(e), + Self::Tree(ref e) => Some(e), } } } diff --git a/src/expression/error.rs b/src/expression/error.rs index bd62863d4..7d6a8dc2a 100644 --- a/src/expression/error.rs +++ b/src/expression/error.rs @@ -104,41 +104,41 @@ impl From for ParseTreeError { impl fmt::Display for ParseTreeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - ParseTreeError::Checksum(ref e) => e.fmt(f), - ParseTreeError::MaxRecursionDepthExceeded { actual, maximum } => { + Self::Checksum(ref e) => e.fmt(f), + Self::MaxRecursionDepthExceeded { actual, maximum } => { write!(f, "maximum recursion depth exceeded (max {}, got {})", maximum, actual) } - ParseTreeError::ExpectedParenOrComma { ch, pos } => { + Self::ExpectedParenOrComma { ch, pos } => { write!( f, "invalid character `{}` (position {}); expected comma or close-paren", ch, pos ) } - ParseTreeError::UnmatchedOpenParen { ch, pos } => { + Self::UnmatchedOpenParen { ch, pos } => { write!(f, "`{}` (position {}) not closed", ch, pos) } - ParseTreeError::UnmatchedCloseParen { ch, pos } => { + Self::UnmatchedCloseParen { ch, pos } => { write!(f, "`{}` (position {}) not opened", ch, pos) } - ParseTreeError::MismatchedParens { open_ch, open_pos, close_ch, close_pos } => { + Self::MismatchedParens { open_ch, open_pos, close_ch, close_pos } => { write!( f, "`{}` (position {}) closed by `{}` (position {})", open_ch, open_pos, close_ch, close_pos ) } - ParseTreeError::IllegalCurlyBrace { pos } => { + Self::IllegalCurlyBrace { pos } => { write!(f, "illegal `{{` at position {} (Taproot branches not allowed here)", pos) } - ParseTreeError::IncorrectName { actual, expected } => { + Self::IncorrectName { actual, expected } => { if expected.is_empty() { write!(f, "found node '{}', expected nameless node", actual) } else { write!(f, "expected node '{}', found '{}'", expected, actual) } } - ParseTreeError::IncorrectNumberOfChildren { + Self::IncorrectNumberOfChildren { description, n_children, minimum, @@ -156,17 +156,17 @@ impl fmt::Display for ParseTreeError { }?; write!(f, ", but found {}", n_children) } - ParseTreeError::MultipleSeparators { separator, pos } => { + Self::MultipleSeparators { separator, pos } => { write!( f, "separator '{}' occurred multiple times (second time at position {})", separator, pos ) } - ParseTreeError::TrailingCharacter { ch, pos } => { + Self::TrailingCharacter { ch, pos } => { write!(f, "trailing data `{}...` (position {})", ch, pos) } - ParseTreeError::UnknownName { name } => write!(f, "unrecognized name '{}'", name), + Self::UnknownName { name } => write!(f, "unrecognized name '{}'", name), } } } @@ -174,18 +174,18 @@ impl fmt::Display for ParseTreeError { impl std::error::Error for ParseTreeError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - ParseTreeError::Checksum(ref e) => Some(e), - ParseTreeError::MaxRecursionDepthExceeded { .. } - | ParseTreeError::ExpectedParenOrComma { .. } - | ParseTreeError::UnmatchedOpenParen { .. } - | ParseTreeError::UnmatchedCloseParen { .. } - | ParseTreeError::MismatchedParens { .. } - | ParseTreeError::IllegalCurlyBrace { .. } - | ParseTreeError::IncorrectName { .. } - | ParseTreeError::IncorrectNumberOfChildren { .. } - | ParseTreeError::MultipleSeparators { .. } - | ParseTreeError::TrailingCharacter { .. } - | ParseTreeError::UnknownName { .. } => None, + Self::Checksum(ref e) => Some(e), + Self::MaxRecursionDepthExceeded { .. } + | Self::ExpectedParenOrComma { .. } + | Self::UnmatchedOpenParen { .. } + | Self::UnmatchedCloseParen { .. } + | Self::MismatchedParens { .. } + | Self::IllegalCurlyBrace { .. } + | Self::IncorrectName { .. } + | Self::IncorrectNumberOfChildren { .. } + | Self::MultipleSeparators { .. } + | Self::TrailingCharacter { .. } + | Self::UnknownName { .. } => None, } } } @@ -209,11 +209,11 @@ pub enum ParseNumError { impl fmt::Display for ParseNumError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - ParseNumError::StdParse(ref e) => e.fmt(f), - ParseNumError::InvalidLeadingDigit(ch) => { + Self::StdParse(ref e) => e.fmt(f), + Self::InvalidLeadingDigit(ch) => { write!(f, "numbers must start with 1-9, not {}", ch) } - ParseNumError::IllegalZero { context } => { + Self::IllegalZero { context } => { write!(f, "{} may not be 0", context) } } @@ -224,9 +224,9 @@ impl fmt::Display for ParseNumError { impl std::error::Error for ParseNumError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { - ParseNumError::StdParse(ref e) => Some(e), - ParseNumError::InvalidLeadingDigit(..) => None, - ParseNumError::IllegalZero { .. } => None, + Self::StdParse(ref e) => Some(e), + Self::InvalidLeadingDigit(..) => None, + Self::IllegalZero { .. } => None, } } } diff --git a/src/interpreter/error.rs b/src/interpreter/error.rs index 4e47932a6..8f796872a 100644 --- a/src/interpreter/error.rs +++ b/src/interpreter/error.rs @@ -118,69 +118,69 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Error::AbsoluteLockTimeNotMet(n) => { + Self::AbsoluteLockTimeNotMet(n) => { write!(f, "required absolute locktime CLTV of {} blocks, not met", n) } - Error::AbsoluteLockTimeComparisonInvalid(n, lock_time) => write!( + Self::AbsoluteLockTimeComparisonInvalid(n, lock_time) => write!( f, "could not satisfy, lock time values are different units n: {} lock_time: {}", n, lock_time ), - Error::CannotInferTrDescriptors => write!(f, "Cannot infer taproot descriptors"), - Error::ControlBlockParse(ref e) => write!(f, "Control block parse error {}", e), - Error::ControlBlockVerificationError => { + Self::CannotInferTrDescriptors => write!(f, "Cannot infer taproot descriptors"), + Self::ControlBlockParse(ref e) => write!(f, "Control block parse error {}", e), + Self::ControlBlockVerificationError => { f.write_str("Control block verification failed") } - Error::EcdsaSig(ref s) => write!(f, "Ecdsa sig error: {}", s), - Error::ExpectedPush => f.write_str("expected push in script"), - Error::CouldNotEvaluate => f.write_str("Interpreter Error: Could not evaluate"), - Error::HashPreimageLengthMismatch => f.write_str("Hash preimage should be 32 bytes"), - Error::IncorrectPubkeyHash => f.write_str("public key did not match scriptpubkey"), - Error::IncorrectScriptHash => f.write_str("redeem script did not match scriptpubkey"), - Error::IncorrectWPubkeyHash => { + Self::EcdsaSig(ref s) => write!(f, "Ecdsa sig error: {}", s), + Self::ExpectedPush => f.write_str("expected push in script"), + Self::CouldNotEvaluate => f.write_str("Interpreter Error: Could not evaluate"), + Self::HashPreimageLengthMismatch => f.write_str("Hash preimage should be 32 bytes"), + Self::IncorrectPubkeyHash => f.write_str("public key did not match scriptpubkey"), + Self::IncorrectScriptHash => f.write_str("redeem script did not match scriptpubkey"), + Self::IncorrectWPubkeyHash => { f.write_str("public key did not match scriptpubkey (segwit v0)") } - Error::IncorrectWScriptHash => f.write_str("witness script did not match scriptpubkey"), - Error::InsufficientSignaturesMultiSig => f.write_str("Insufficient signatures for CMS"), - Error::InvalidSchnorrSighashType(ref sig) => { + Self::IncorrectWScriptHash => f.write_str("witness script did not match scriptpubkey"), + Self::InsufficientSignaturesMultiSig => f.write_str("Insufficient signatures for CMS"), + Self::InvalidSchnorrSighashType(ref sig) => { write!(f, "Invalid sighash type for schnorr signature '{:x}'", sig.as_hex()) } - Error::InvalidEcdsaSignature(pk) => write!(f, "bad ecdsa signature with pk {}", pk), - Error::InvalidSchnorrSignature(pk) => write!(f, "bad schnorr signature with pk {}", pk), - Error::NonStandardSighash(ref sig) => { + Self::InvalidEcdsaSignature(pk) => write!(f, "bad ecdsa signature with pk {}", pk), + Self::InvalidSchnorrSignature(pk) => write!(f, "bad schnorr signature with pk {}", pk), + Self::NonStandardSighash(ref sig) => { write!(f, "Non standard sighash type for signature '{:x}'", sig.as_hex()) } - Error::NonEmptyWitness => f.write_str("legacy spend had nonempty witness"), - Error::NonEmptyScriptSig => f.write_str("segwit spend had nonempty scriptsig"), - Error::Miniscript(ref e) => write!(f, "parse error: {}", e), - Error::MissingExtraZeroMultiSig => f.write_str("CMS missing extra zero"), - Error::MultiSigEvaluationError => { + Self::NonEmptyWitness => f.write_str("legacy spend had nonempty witness"), + Self::NonEmptyScriptSig => f.write_str("segwit spend had nonempty scriptsig"), + Self::Miniscript(ref e) => write!(f, "parse error: {}", e), + Self::MissingExtraZeroMultiSig => f.write_str("CMS missing extra zero"), + Self::MultiSigEvaluationError => { f.write_str("CMS script aborted, incorrect satisfaction/dissatisfaction") } - Error::PkEvaluationError(ref key) => write!(f, "Incorrect Signature for pk {}", key), - Error::PkHashVerifyFail(ref hash) => write!(f, "Pubkey Hash check failed {}", hash), - Error::PubkeyParseError => f.write_str("could not parse pubkey"), - Error::XOnlyPublicKeyParseError => f.write_str("could not parse x-only pubkey"), - Error::RelativeLockTimeNotMet(n) => { + Self::PkEvaluationError(ref key) => write!(f, "Incorrect Signature for pk {}", key), + Self::PkHashVerifyFail(ref hash) => write!(f, "Pubkey Hash check failed {}", hash), + Self::PubkeyParseError => f.write_str("could not parse pubkey"), + Self::XOnlyPublicKeyParseError => f.write_str("could not parse x-only pubkey"), + Self::RelativeLockTimeNotMet(n) => { write!(f, "required relative locktime CSV of {} blocks, not met", n) } - Error::RelativeLockTimeDisabled(n) => { + Self::RelativeLockTimeDisabled(n) => { write!(f, "required relative locktime CSV of {} blocks, but tx sequence number has disable-flag set", n) } - Error::ScriptSatisfactionError => f.write_str("Top level script must be satisfied"), - Error::Secp(ref e) => fmt::Display::fmt(e, f), - Error::SchnorrSig(ref s) => write!(f, "Schnorr sig error: {}", s), - Error::SighashError(ref e) => fmt::Display::fmt(e, f), - Error::TapAnnexUnsupported => f.write_str("Encountered annex element"), - Error::UncompressedPubkey => { + Self::ScriptSatisfactionError => f.write_str("Top level script must be satisfied"), + Self::Secp(ref e) => fmt::Display::fmt(e, f), + Self::SchnorrSig(ref s) => write!(f, "Schnorr sig error: {}", s), + Self::SighashError(ref e) => fmt::Display::fmt(e, f), + Self::TapAnnexUnsupported => f.write_str("Encountered annex element"), + Self::UncompressedPubkey => { f.write_str("uncompressed pubkey in non-legacy descriptor") } - Error::UnexpectedStackBoolean => { + Self::UnexpectedStackBoolean => { f.write_str("Expected Stack Push operation, found stack bool") } - Error::UnexpectedStackElementPush => write!(f, "Got {}, expected Stack Boolean", 1), - Error::UnexpectedStackEnd => f.write_str("unexpected end of stack"), - Error::VerifyFailed => { + Self::UnexpectedStackElementPush => write!(f, "Got {}, expected Stack Boolean", 1), + Self::UnexpectedStackEnd => f.write_str("unexpected end of stack"), + Self::VerifyFailed => { f.write_str("Expected Satisfied Boolean at stack top for VERIFY") } } @@ -238,27 +238,27 @@ impl error::Error for Error { #[doc(hidden)] impl From for Error { - fn from(e: secp256k1::Error) -> Error { Error::Secp(e) } + fn from(e: secp256k1::Error) -> Self { Self::Secp(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::sighash::InvalidSighashTypeError) -> Error { Error::SighashError(e) } + fn from(e: bitcoin::sighash::InvalidSighashTypeError) -> Self { Self::SighashError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::ecdsa::Error) -> Error { Error::EcdsaSig(e) } + fn from(e: bitcoin::ecdsa::Error) -> Self { Self::EcdsaSig(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::taproot::SigFromSliceError) -> Error { Error::SchnorrSig(e) } + fn from(e: bitcoin::taproot::SigFromSliceError) -> Self { Self::SchnorrSig(e) } } #[doc(hidden)] impl From for Error { - fn from(e: crate::Error) -> Error { Error::Miniscript(e) } + fn from(e: crate::Error) -> Self { Self::Miniscript(e) } } /// A type of representing which keys errored during interpreter checksig evaluation @@ -274,8 +274,8 @@ pub enum PkEvalErrInner { impl From for PkEvalErrInner { fn from(pk: BitcoinKey) -> Self { match pk { - BitcoinKey::Fullkey(pk) => PkEvalErrInner::FullKey(pk), - BitcoinKey::XOnlyPublicKey(xpk) => PkEvalErrInner::XOnlyKey(xpk), + BitcoinKey::Fullkey(pk) => Self::FullKey(pk), + BitcoinKey::XOnlyPublicKey(xpk) => Self::XOnlyKey(xpk), } } } @@ -283,8 +283,8 @@ impl From for PkEvalErrInner { impl fmt::Display for PkEvalErrInner { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - PkEvalErrInner::FullKey(pk) => pk.fmt(f), - PkEvalErrInner::XOnlyKey(xpk) => xpk.fmt(f), + Self::FullKey(pk) => pk.fmt(f), + Self::XOnlyKey(xpk) => xpk.fmt(f), } } } diff --git a/src/interpreter/inner.rs b/src/interpreter/inner.rs index b65e26a7f..df693aa97 100644 --- a/src/interpreter/inner.rs +++ b/src/interpreter/inner.rs @@ -416,7 +416,7 @@ mod tests { } impl KeyTestData { - fn from_key(key: bitcoin::PublicKey) -> KeyTestData { + fn from_key(key: bitcoin::PublicKey) -> Self { // what a funny looking signature.. let dummy_sig_vec = hex::decode_to_vec( "\ @@ -432,7 +432,7 @@ mod tests { let wpkh_spk = bitcoin::ScriptBuf::new_p2wpkh(&wpkhash); let wpkh_scripthash = hash160::Hash::hash(wpkh_spk.as_bytes()).into(); - KeyTestData { + Self { pk_spk: bitcoin::ScriptBuf::new_p2pk(&key), pkh_spk: bitcoin::ScriptBuf::new_p2pkh(&pkhash), pk_sig: script::Builder::new().push_slice(dummy_sig).into_script(), diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index 5aed49fb0..8145b1c6f 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -55,8 +55,8 @@ impl KeySigPair { /// Obtain a pair of ([`bitcoin::PublicKey`], [`bitcoin::ecdsa::Signature`]) from [`KeySigPair`] pub fn as_ecdsa(&self) -> Option<(bitcoin::PublicKey, bitcoin::ecdsa::Signature)> { match self { - KeySigPair::Ecdsa(pk, sig) => Some((*pk, *sig)), - KeySigPair::Schnorr(_, _) => None, + Self::Ecdsa(pk, sig) => Some((*pk, *sig)), + Self::Schnorr(_, _) => None, } } @@ -65,8 +65,8 @@ impl KeySigPair { &self, ) -> Option<(bitcoin::key::XOnlyPublicKey, bitcoin::taproot::Signature)> { match self { - KeySigPair::Ecdsa(_, _) => None, - KeySigPair::Schnorr(pk, sig) => Some((*pk, *sig)), + Self::Ecdsa(_, _) => None, + Self::Schnorr(pk, sig) => Some((*pk, *sig)), } } } @@ -94,8 +94,8 @@ enum BitcoinKey { impl BitcoinKey { fn to_pubkeyhash(self, sig_type: SigType) -> hash160::Hash { match self { - BitcoinKey::Fullkey(pk) => pk.to_pubkeyhash(sig_type), - BitcoinKey::XOnlyPublicKey(pk) => pk.to_pubkeyhash(sig_type), + Self::Fullkey(pk) => pk.to_pubkeyhash(sig_type), + Self::XOnlyPublicKey(pk) => pk.to_pubkeyhash(sig_type), } } } @@ -104,18 +104,18 @@ impl BitcoinKey { impl fmt::Display for BitcoinKey { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - BitcoinKey::Fullkey(pk) => pk.to_public_key().fmt(f), - BitcoinKey::XOnlyPublicKey(pk) => pk.to_public_key().fmt(f), + Self::Fullkey(pk) => pk.to_public_key().fmt(f), + Self::XOnlyPublicKey(pk) => pk.to_public_key().fmt(f), } } } impl From for BitcoinKey { - fn from(pk: bitcoin::PublicKey) -> Self { BitcoinKey::Fullkey(pk) } + fn from(pk: bitcoin::PublicKey) -> Self { Self::Fullkey(pk) } } impl From for BitcoinKey { - fn from(xpk: bitcoin::key::XOnlyPublicKey) -> Self { BitcoinKey::XOnlyPublicKey(xpk) } + fn from(xpk: bitcoin::key::XOnlyPublicKey) -> Self { Self::XOnlyPublicKey(xpk) } } impl MiniscriptKey for BitcoinKey { @@ -126,8 +126,8 @@ impl MiniscriptKey for BitcoinKey { fn is_uncompressed(&self) -> bool { match *self { - BitcoinKey::Fullkey(pk) => !pk.compressed, - BitcoinKey::XOnlyPublicKey(_) => false, + Self::Fullkey(pk) => !pk.compressed, + Self::XOnlyPublicKey(_) => false, } } fn is_x_only_key(&self) -> bool { false } diff --git a/src/interpreter/stack.rs b/src/interpreter/stack.rs index 647a84713..5ec4ef7ed 100644 --- a/src/interpreter/stack.rs +++ b/src/interpreter/stack.rs @@ -30,11 +30,11 @@ pub enum Element<'txin> { } impl<'txin> From<&'txin Vec> for Element<'txin> { - fn from(v: &'txin Vec) -> Element<'txin> { From::from(&v[..]) } + fn from(v: &'txin Vec) -> Self { From::from(&v[..]) } } impl<'txin> From<&'txin [u8]> for Element<'txin> { - fn from(v: &'txin [u8]) -> Element<'txin> { + fn from(v: &'txin [u8]) -> Self { if *v == [1] { Element::Satisfied } else if v.is_empty() { diff --git a/src/iter/tree.rs b/src/iter/tree.rs index 5084d1f8d..262c5ab0c 100644 --- a/src/iter/tree.rs +++ b/src/iter/tree.rs @@ -135,7 +135,7 @@ impl IterStackItem { /// Constructor for a new stack item with a given element and relationship /// to its parent. fn unprocessed(elem: T, parent_stack_idx: Option) -> Self { - IterStackItem { + Self { processed: false, child_indices: Vec::with_capacity(elem.n_children()), parent_stack_idx, @@ -220,15 +220,15 @@ impl TreeLike for Rtl { fn nary_len(tc: &Self::NaryChildren) -> usize { T::nary_len(tc) } fn nary_index(tc: Self::NaryChildren, idx: usize) -> Self { let rtl_idx = T::nary_len(&tc) - idx - 1; - Rtl(T::nary_index(tc, rtl_idx)) + Self(T::nary_index(tc, rtl_idx)) } fn as_node(&self) -> Tree { match self.0.as_node() { Tree::Nullary => Tree::Nullary, - Tree::Unary(a) => Tree::Unary(Rtl(a)), - Tree::Binary(a, b) => Tree::Binary(Rtl(b), Rtl(a)), - Tree::Ternary(a, b, c) => Tree::Ternary(Rtl(c), Rtl(b), Rtl(a)), + Tree::Unary(a) => Tree::Unary(Self(a)), + Tree::Binary(a, b) => Tree::Binary(Self(b), Self(a)), + Tree::Ternary(a, b, c) => Tree::Ternary(Self(c), Self(b), Self(a)), Tree::Nary(data) => Tree::Nary(data), } } @@ -377,7 +377,7 @@ impl PreOrderIterItem { /// /// Marks the index as 0. The index must be manually set before yielding. fn initial(node: T, parent: Option) -> Self { - PreOrderIterItem { + Self { is_complete: node.n_children() == 0, node, parent, @@ -388,7 +388,7 @@ impl PreOrderIterItem { /// Creates a `PreOrderIterItem` which yields a given element again. fn increment(self, n_children: usize) -> Self { - PreOrderIterItem { + Self { node: self.node, index: self.index, parent: self.parent, diff --git a/src/lib.rs b/src/lib.rs index cbed64e51..9e42b8ef3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -206,10 +206,10 @@ impl MiniscriptKey for bitcoin::secp256k1::XOnlyPublicKey { } impl MiniscriptKey for String { - type Sha256 = String; - type Hash256 = String; - type Ripemd160 = String; - type Hash160 = String; + type Sha256 = Self; + type Hash256 = Self; + type Ripemd160 = Self; + type Hash160 = Self; fn is_x_only_key(&self) -> bool { false } fn num_der_paths(&self) -> usize { 0 } @@ -505,48 +505,48 @@ const MAX_RECURSION_DEPTH: u32 = 402; impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Error::ScriptLexer(ref e) => e.fmt(f), - Error::AddrError(ref e) => fmt::Display::fmt(e, f), - Error::AddrP2shError(ref e) => fmt::Display::fmt(e, f), - Error::UnexpectedStart => f.write_str("unexpected start of script"), - Error::Unexpected(ref s) => write!(f, "unexpected «{}»", s), - Error::UnknownWrapper(ch) => write!(f, "unknown wrapper «{}:»", ch), - Error::NonTopLevel(ref s) => write!(f, "non-T miniscript: {}", s), - Error::Trailing(ref s) => write!(f, "trailing tokens: {}", s), - Error::MissingSig(ref pk) => write!(f, "missing signature for key {:?}", pk), - Error::CouldNotSatisfy => f.write_str("could not satisfy"), - Error::TypeCheck(ref e) => write!(f, "typecheck: {}", e), - Error::Secp(ref e) => fmt::Display::fmt(e, f), - Error::ContextError(ref e) => fmt::Display::fmt(e, f), - Error::TapTreeDepthError(ref e) => fmt::Display::fmt(e, f), + Self::ScriptLexer(ref e) => e.fmt(f), + Self::AddrError(ref e) => fmt::Display::fmt(e, f), + Self::AddrP2shError(ref e) => fmt::Display::fmt(e, f), + Self::UnexpectedStart => f.write_str("unexpected start of script"), + Self::Unexpected(ref s) => write!(f, "unexpected «{}»", s), + Self::UnknownWrapper(ch) => write!(f, "unknown wrapper «{}:»", ch), + Self::NonTopLevel(ref s) => write!(f, "non-T miniscript: {}", s), + Self::Trailing(ref s) => write!(f, "trailing tokens: {}", s), + Self::MissingSig(ref pk) => write!(f, "missing signature for key {:?}", pk), + Self::CouldNotSatisfy => f.write_str("could not satisfy"), + Self::TypeCheck(ref e) => write!(f, "typecheck: {}", e), + Self::Secp(ref e) => fmt::Display::fmt(e, f), + Self::ContextError(ref e) => fmt::Display::fmt(e, f), + Self::TapTreeDepthError(ref e) => fmt::Display::fmt(e, f), #[cfg(feature = "compiler")] - Error::CompilerError(ref e) => fmt::Display::fmt(e, f), - Error::ConcretePolicy(ref e) => fmt::Display::fmt(e, f), - Error::LiftError(ref e) => fmt::Display::fmt(e, f), - Error::MaxRecursiveDepthExceeded => write!( + Self::CompilerError(ref e) => fmt::Display::fmt(e, f), + Self::ConcretePolicy(ref e) => fmt::Display::fmt(e, f), + Self::LiftError(ref e) => fmt::Display::fmt(e, f), + Self::MaxRecursiveDepthExceeded => write!( f, "Recursive depth over {} not permitted", MAX_RECURSION_DEPTH ), - Error::NonStandardBareScript => write!( + Self::NonStandardBareScript => write!( f, "Anything but c:pk(key) (P2PK), c:pk_h(key) (P2PKH), and thresh_m(k,...) \ up to n=3 is invalid by standardness (bare). " ), - Error::AnalysisError(ref e) => e.fmt(f), - Error::ImpossibleSatisfaction => write!(f, "Impossible to satisfy Miniscript"), - Error::BareDescriptorAddr => write!(f, "Bare descriptors don't have address"), - Error::PubKeyCtxError(ref pk, ref ctx) => { + Self::AnalysisError(ref e) => e.fmt(f), + Self::ImpossibleSatisfaction => write!(f, "Impossible to satisfy Miniscript"), + Self::BareDescriptorAddr => write!(f, "Bare descriptors don't have address"), + Self::PubKeyCtxError(ref pk, ref ctx) => { write!(f, "Pubkey error: {} under {} scriptcontext", pk, ctx) } - Error::TrNoScriptCode => write!(f, "No script code for Tr descriptors"), - Error::MultipathDescLenMismatch => write!(f, "At least two BIP389 key expressions in the descriptor contain tuples of derivation indexes of different lengths"), - Error::AbsoluteLockTime(ref e) => e.fmt(f), - Error::RelativeLockTime(ref e) => e.fmt(f), - Error::Threshold(ref e) => e.fmt(f), - Error::ParseThreshold(ref e) => e.fmt(f), - Error::Parse(ref e) => e.fmt(f), + Self::TrNoScriptCode => write!(f, "No script code for Tr descriptors"), + Self::MultipathDescLenMismatch => write!(f, "At least two BIP389 key expressions in the descriptor contain tuples of derivation indexes of different lengths"), + Self::AbsoluteLockTime(ref e) => e.fmt(f), + Self::RelativeLockTime(ref e) => e.fmt(f), + Self::Threshold(ref e) => e.fmt(f), + Self::ParseThreshold(ref e) => e.fmt(f), + Self::Parse(ref e) => e.fmt(f), } } } @@ -594,53 +594,53 @@ impl std::error::Error for Error { #[doc(hidden)] impl From for Error { - fn from(e: miniscript::lex::Error) -> Error { Error::ScriptLexer(e) } + fn from(e: miniscript::lex::Error) -> Self { Self::ScriptLexer(e) } } #[doc(hidden)] impl From for Error { - fn from(e: miniscript::types::Error) -> Error { Error::TypeCheck(e.to_string()) } + fn from(e: miniscript::types::Error) -> Self { Self::TypeCheck(e.to_string()) } } #[doc(hidden)] impl From for Error { - fn from(e: policy::LiftError) -> Error { Error::LiftError(e) } + fn from(e: policy::LiftError) -> Self { Self::LiftError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: crate::descriptor::TapTreeDepthError) -> Error { Error::TapTreeDepthError(e) } + fn from(e: crate::descriptor::TapTreeDepthError) -> Self { Self::TapTreeDepthError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: miniscript::context::ScriptContextError) -> Error { Error::ContextError(e) } + fn from(e: miniscript::context::ScriptContextError) -> Self { Self::ContextError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: miniscript::analyzable::AnalysisError) -> Error { Error::AnalysisError(e) } + fn from(e: miniscript::analyzable::AnalysisError) -> Self { Self::AnalysisError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::secp256k1::Error) -> Error { Error::Secp(e) } + fn from(e: bitcoin::secp256k1::Error) -> Self { Self::Secp(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::address::ParseError) -> Error { Error::AddrError(e) } + fn from(e: bitcoin::address::ParseError) -> Self { Self::AddrError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::address::P2shError) -> Error { Error::AddrP2shError(e) } + fn from(e: bitcoin::address::P2shError) -> Self { Self::AddrP2shError(e) } } #[doc(hidden)] #[cfg(feature = "compiler")] impl From for Error { - fn from(e: crate::policy::compiler::CompilerError) -> Error { Error::CompilerError(e) } + fn from(e: crate::policy::compiler::CompilerError) -> Self { Self::CompilerError(e) } } /// The size of an encoding of a number in Script @@ -760,7 +760,7 @@ mod prelude { } impl Mutex { - pub fn new(inner: T) -> Mutex { Mutex { inner: RefCell::new(inner) } } + pub fn new(inner: T) -> Self { Self { inner: RefCell::new(inner) } } pub fn lock(&self) -> LockResult> { Ok(MutexGuard { lock: self.inner.borrow_mut() }) diff --git a/src/miniscript/analyzable.rs b/src/miniscript/analyzable.rs index 13ccb5e65..31f6ef8b5 100644 --- a/src/miniscript/analyzable.rs +++ b/src/miniscript/analyzable.rs @@ -43,8 +43,8 @@ pub struct ExtParams { impl ExtParams { /// Create a new ExtParams that with all the sanity rules - pub fn new() -> ExtParams { - ExtParams { + pub fn new() -> Self { + Self { top_unsafe: false, resource_limitations: false, timelock_mixing: false, @@ -55,13 +55,13 @@ impl ExtParams { } /// Create a new ExtParams that allows all the sanity rules - pub fn sane() -> ExtParams { ExtParams::new() } + pub fn sane() -> Self { Self::new() } /// Create a new ExtParams that insanity rules /// This enables parsing well specified but "insane" miniscripts. /// Refer to the [`ExtParams`] documentation for more details on "insane" miniscripts. - pub fn insane() -> ExtParams { - ExtParams { + pub fn insane() -> Self { + Self { top_unsafe: true, resource_limitations: true, timelock_mixing: true, @@ -72,8 +72,8 @@ impl ExtParams { } /// Enable all non-sane rules and experimental rules - pub fn allow_all() -> ExtParams { - ExtParams { + pub fn allow_all() -> Self { + Self { top_unsafe: true, resource_limitations: true, timelock_mixing: true, @@ -84,37 +84,37 @@ impl ExtParams { } /// Builder that allows non-safe miniscripts. - pub fn top_unsafe(mut self) -> ExtParams { + pub fn top_unsafe(mut self) -> Self { self.top_unsafe = true; self } /// Builder that allows miniscripts with exceed resource limitations. - pub fn exceed_resource_limitations(mut self) -> ExtParams { + pub fn exceed_resource_limitations(mut self) -> Self { self.resource_limitations = true; self } /// Builder that allows miniscripts with timelock mixing. - pub fn timelock_mixing(mut self) -> ExtParams { + pub fn timelock_mixing(mut self) -> Self { self.timelock_mixing = true; self } /// Builder that allows malleable miniscripts. - pub fn malleability(mut self) -> ExtParams { + pub fn malleability(mut self) -> Self { self.malleability = true; self } /// Builder that allows miniscripts with repeated public keys. - pub fn repeated_pk(mut self) -> ExtParams { + pub fn repeated_pk(mut self) -> Self { self.repeated_pk = true; self } /// Builder that allows miniscripts with raw pkh fragments. - pub fn raw_pkh(mut self) -> ExtParams { + pub fn raw_pkh(mut self) -> Self { self.raw_pkh = true; self } @@ -148,20 +148,20 @@ pub enum AnalysisError { impl fmt::Display for AnalysisError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - AnalysisError::SiglessBranch => { + Self::SiglessBranch => { f.write_str("All spend paths must require a signature") } - AnalysisError::RepeatedPubkeys => { + Self::RepeatedPubkeys => { f.write_str("Miniscript contains repeated pubkeys or pubkeyhashes") } - AnalysisError::BranchExceedResouceLimits => { + Self::BranchExceedResouceLimits => { f.write_str("At least one spend path exceeds the resource limits(stack depth/satisfaction size..)") } - AnalysisError::HeightTimelockCombination => { + Self::HeightTimelockCombination => { f.write_str("Contains a combination of heightlock and timelock") } - AnalysisError::Malleable => f.write_str("Miniscript is malleable"), - AnalysisError::ContainsRawPkh => f.write_str("Miniscript contains raw pkh"), + Self::Malleable => f.write_str("Miniscript is malleable"), + Self::ContainsRawPkh => f.write_str("Miniscript contains raw pkh"), } } } diff --git a/src/miniscript/astelem.rs b/src/miniscript/astelem.rs index 078cfac58..0d906b116 100644 --- a/src/miniscript/astelem.rs +++ b/src/miniscript/astelem.rs @@ -40,110 +40,110 @@ impl Terminal { Pk: ToPublicKey, { match *self { - Terminal::PkK(ref pk) => builder.push_ms_key::<_, Ctx>(pk), - Terminal::PkH(ref pk) => builder + Self::PkK(ref pk) => builder.push_ms_key::<_, Ctx>(pk), + Self::PkH(ref pk) => builder .push_opcode(opcodes::all::OP_DUP) .push_opcode(opcodes::all::OP_HASH160) .push_ms_key_hash::<_, Ctx>(pk) .push_opcode(opcodes::all::OP_EQUALVERIFY), - Terminal::RawPkH(ref hash) => builder + Self::RawPkH(ref hash) => builder .push_opcode(opcodes::all::OP_DUP) .push_opcode(opcodes::all::OP_HASH160) .push_slice(hash.to_byte_array()) .push_opcode(opcodes::all::OP_EQUALVERIFY), - Terminal::After(t) => builder + Self::After(t) => builder .push_int(absolute::LockTime::from(t).to_consensus_u32() as i64) .push_opcode(opcodes::all::OP_CLTV), - Terminal::Older(t) => builder + Self::Older(t) => builder .push_int(t.to_consensus_u32().into()) .push_opcode(opcodes::all::OP_CSV), - Terminal::Sha256(ref h) => builder + Self::Sha256(ref h) => builder .push_opcode(opcodes::all::OP_SIZE) .push_int(32) .push_opcode(opcodes::all::OP_EQUALVERIFY) .push_opcode(opcodes::all::OP_SHA256) .push_slice(Pk::to_sha256(h).to_byte_array()) .push_opcode(opcodes::all::OP_EQUAL), - Terminal::Hash256(ref h) => builder + Self::Hash256(ref h) => builder .push_opcode(opcodes::all::OP_SIZE) .push_int(32) .push_opcode(opcodes::all::OP_EQUALVERIFY) .push_opcode(opcodes::all::OP_HASH256) .push_slice(Pk::to_hash256(h).to_byte_array()) .push_opcode(opcodes::all::OP_EQUAL), - Terminal::Ripemd160(ref h) => builder + Self::Ripemd160(ref h) => builder .push_opcode(opcodes::all::OP_SIZE) .push_int(32) .push_opcode(opcodes::all::OP_EQUALVERIFY) .push_opcode(opcodes::all::OP_RIPEMD160) .push_slice(Pk::to_ripemd160(h).to_byte_array()) .push_opcode(opcodes::all::OP_EQUAL), - Terminal::Hash160(ref h) => builder + Self::Hash160(ref h) => builder .push_opcode(opcodes::all::OP_SIZE) .push_int(32) .push_opcode(opcodes::all::OP_EQUALVERIFY) .push_opcode(opcodes::all::OP_HASH160) .push_slice(Pk::to_hash160(h).to_byte_array()) .push_opcode(opcodes::all::OP_EQUAL), - Terminal::True => builder.push_opcode(opcodes::OP_TRUE), - Terminal::False => builder.push_opcode(opcodes::OP_FALSE), - Terminal::Alt(ref sub) => builder + Self::True => builder.push_opcode(opcodes::OP_TRUE), + Self::False => builder.push_opcode(opcodes::OP_FALSE), + Self::Alt(ref sub) => builder .push_opcode(opcodes::all::OP_TOALTSTACK) .push_astelem(sub) .push_opcode(opcodes::all::OP_FROMALTSTACK), - Terminal::Swap(ref sub) => builder.push_opcode(opcodes::all::OP_SWAP).push_astelem(sub), - Terminal::Check(ref sub) => builder + Self::Swap(ref sub) => builder.push_opcode(opcodes::all::OP_SWAP).push_astelem(sub), + Self::Check(ref sub) => builder .push_astelem(sub) .push_opcode(opcodes::all::OP_CHECKSIG), - Terminal::DupIf(ref sub) => builder + Self::DupIf(ref sub) => builder .push_opcode(opcodes::all::OP_DUP) .push_opcode(opcodes::all::OP_IF) .push_astelem(sub) .push_opcode(opcodes::all::OP_ENDIF), - Terminal::Verify(ref sub) => builder.push_astelem(sub).push_verify(), - Terminal::NonZero(ref sub) => builder + Self::Verify(ref sub) => builder.push_astelem(sub).push_verify(), + Self::NonZero(ref sub) => builder .push_opcode(opcodes::all::OP_SIZE) .push_opcode(opcodes::all::OP_0NOTEQUAL) .push_opcode(opcodes::all::OP_IF) .push_astelem(sub) .push_opcode(opcodes::all::OP_ENDIF), - Terminal::ZeroNotEqual(ref sub) => builder + Self::ZeroNotEqual(ref sub) => builder .push_astelem(sub) .push_opcode(opcodes::all::OP_0NOTEQUAL), - Terminal::AndV(ref left, ref right) => builder.push_astelem(left).push_astelem(right), - Terminal::AndB(ref left, ref right) => builder + Self::AndV(ref left, ref right) => builder.push_astelem(left).push_astelem(right), + Self::AndB(ref left, ref right) => builder .push_astelem(left) .push_astelem(right) .push_opcode(opcodes::all::OP_BOOLAND), - Terminal::AndOr(ref a, ref b, ref c) => builder + Self::AndOr(ref a, ref b, ref c) => builder .push_astelem(a) .push_opcode(opcodes::all::OP_NOTIF) .push_astelem(c) .push_opcode(opcodes::all::OP_ELSE) .push_astelem(b) .push_opcode(opcodes::all::OP_ENDIF), - Terminal::OrB(ref left, ref right) => builder + Self::OrB(ref left, ref right) => builder .push_astelem(left) .push_astelem(right) .push_opcode(opcodes::all::OP_BOOLOR), - Terminal::OrD(ref left, ref right) => builder + Self::OrD(ref left, ref right) => builder .push_astelem(left) .push_opcode(opcodes::all::OP_IFDUP) .push_opcode(opcodes::all::OP_NOTIF) .push_astelem(right) .push_opcode(opcodes::all::OP_ENDIF), - Terminal::OrC(ref left, ref right) => builder + Self::OrC(ref left, ref right) => builder .push_astelem(left) .push_opcode(opcodes::all::OP_NOTIF) .push_astelem(right) .push_opcode(opcodes::all::OP_ENDIF), - Terminal::OrI(ref left, ref right) => builder + Self::OrI(ref left, ref right) => builder .push_opcode(opcodes::all::OP_IF) .push_astelem(left) .push_opcode(opcodes::all::OP_ELSE) .push_astelem(right) .push_opcode(opcodes::all::OP_ENDIF), - Terminal::Thresh(ref thresh) => { + Self::Thresh(ref thresh) => { builder = builder.push_astelem(&thresh.data()[0]); for sub in &thresh.data()[1..] { builder = builder.push_astelem(sub).push_opcode(opcodes::all::OP_ADD); @@ -152,10 +152,10 @@ impl Terminal { .push_int(thresh.k() as i64) .push_opcode(opcodes::all::OP_EQUAL) } - Terminal::Multi(ref thresh) | Terminal::SortedMulti(ref thresh) => { + Self::Multi(ref thresh) | Self::SortedMulti(ref thresh) => { debug_assert!(Ctx::sig_type() == SigType::Ecdsa); let sorted; - let iter = if let Terminal::SortedMulti(thresh) = self { + let iter = if let Self::SortedMulti(thresh) = self { sorted = thresh.clone().into_sorted_bip67(); sorted.iter() } else { @@ -169,10 +169,10 @@ impl Terminal { .push_int(thresh.n() as i64) .push_opcode(opcodes::all::OP_CHECKMULTISIG) } - Terminal::MultiA(ref thresh) | Terminal::SortedMultiA(ref thresh) => { + Self::MultiA(ref thresh) | Self::SortedMultiA(ref thresh) => { debug_assert!(Ctx::sig_type() == SigType::Schnorr); let sorted; - let mut iter = if let Terminal::SortedMultiA(thresh) = self { + let mut iter = if let Self::SortedMultiA(thresh) = self { sorted = thresh.clone().into_sorted_bip67_xonly(); sorted.iter() } else { diff --git a/src/miniscript/context.rs b/src/miniscript/context.rs index bc2d6bb6f..4957209ad 100644 --- a/src/miniscript/context.rs +++ b/src/miniscript/context.rs @@ -91,69 +91,69 @@ impl error::Error for ScriptContextError { impl fmt::Display for ScriptContextError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ScriptContextError::MalleableOrI => write!(f, "OrI is malleable under Legacy rules"), - ScriptContextError::MalleableDupIf => { + Self::MalleableOrI => write!(f, "OrI is malleable under Legacy rules"), + Self::MalleableDupIf => { write!(f, "DupIf is malleable under Legacy rules") } - ScriptContextError::CompressedOnly(ref pk) => { + Self::CompressedOnly(ref pk) => { write!(f, "Only Compressed pubkeys are allowed in segwit context. Found {}", pk) } - ScriptContextError::XOnlyKeysNotAllowed(ref pk, ref ctx) => { + Self::XOnlyKeysNotAllowed(ref pk, ref ctx) => { write!(f, "x-only key {} not allowed in {}", pk, ctx) } - ScriptContextError::UncompressedKeysNotAllowed => { + Self::UncompressedKeysNotAllowed => { write!(f, "uncompressed keys cannot be used in Taproot descriptors.") } - ScriptContextError::MaxWitnessItemsExceeded { actual, limit } => write!( + Self::MaxWitnessItemsExceeded { actual, limit } => write!( f, "At least one satisfaction path in the Miniscript fragment has {} witness items \ (limit: {}).", actual, limit ), - ScriptContextError::MaxOpCountExceeded { actual, limit } => write!( + Self::MaxOpCountExceeded { actual, limit } => write!( f, "At least one satisfaction path in the Miniscript fragment contains {} opcodes \ (limit: {}).", actual, limit ), - ScriptContextError::MaxWitnessScriptSizeExceeded { max, got } => write!( + Self::MaxWitnessScriptSizeExceeded { max, got } => write!( f, "The Miniscript corresponding Script cannot be larger than \ {} bytes, but got {} bytes.", max, got ), - ScriptContextError::MaxRedeemScriptSizeExceeded { max, got } => write!( + Self::MaxRedeemScriptSizeExceeded { max, got } => write!( f, "The Miniscript corresponding Script cannot be larger than \ {} bytes, but got {} bytes.", max, got ), - ScriptContextError::MaxBareScriptSizeExceeded { max, got } => write!( + Self::MaxBareScriptSizeExceeded { max, got } => write!( f, "The Miniscript corresponding Script cannot be larger than \ {} bytes, but got {} bytes.", max, got ), - ScriptContextError::MaxScriptSigSizeExceeded { actual, limit } => write!( + Self::MaxScriptSigSizeExceeded { actual, limit } => write!( f, "At least one satisfaction path in the Miniscript fragment has {} bytes \ (limit: {}).", actual, limit ), - ScriptContextError::ImpossibleSatisfaction => { + Self::ImpossibleSatisfaction => { write!(f, "Impossible to satisfy Miniscript under the current context") } - ScriptContextError::TaprootMultiDisabled => { + Self::TaprootMultiDisabled => { write!(f, "Invalid use of Multi node in taproot context") } - ScriptContextError::StackSizeLimitExceeded { actual, limit } => { + Self::StackSizeLimitExceeded { actual, limit } => { write!( f, "Stack limit {} can exceed the allowed limit {} in at least one script path during script execution", actual, limit ) } - ScriptContextError::MultiANotAllowed => { + Self::MultiANotAllowed => { write!(f, "Multi a(CHECKSIGADD) only allowed post tapscript") } } diff --git a/src/miniscript/decode.rs b/src/miniscript/decode.rs index a8c0b8491..f529d7a5a 100644 --- a/src/miniscript/decode.rs +++ b/src/miniscript/decode.rs @@ -32,13 +32,13 @@ pub trait ParseableKey: Sized + ToPublicKey + private::Sealed { impl ParseableKey for bitcoin::PublicKey { fn from_slice(sl: &[u8]) -> Result { - bitcoin::PublicKey::from_slice(sl).map_err(KeyError::Full) + Self::from_slice(sl).map_err(KeyError::Full) } } impl ParseableKey for bitcoin::secp256k1::XOnlyPublicKey { fn from_slice(sl: &[u8]) -> Result { - bitcoin::secp256k1::XOnlyPublicKey::from_slice(sl).map_err(KeyError::XOnly) + Self::from_slice(sl).map_err(KeyError::XOnly) } } @@ -167,58 +167,58 @@ impl Clone for Terminal { /// If users just want to clone Arcs they can use Arc::clone themselves. fn clone(&self) -> Self { match self { - Terminal::PkK(ref p) => Terminal::PkK(p.clone()), - Terminal::PkH(ref p) => Terminal::PkH(p.clone()), - Terminal::RawPkH(ref p) => Terminal::RawPkH(*p), - Terminal::After(ref n) => Terminal::After(*n), - Terminal::Older(ref n) => Terminal::Older(*n), - Terminal::Sha256(ref x) => Terminal::Sha256(x.clone()), - Terminal::Hash256(ref x) => Terminal::Hash256(x.clone()), - Terminal::Ripemd160(ref x) => Terminal::Ripemd160(x.clone()), - Terminal::Hash160(ref x) => Terminal::Hash160(x.clone()), - Terminal::True => Terminal::True, - Terminal::False => Terminal::False, - Terminal::Alt(ref sub) => Terminal::Alt(Arc::new(Miniscript::clone(sub))), - Terminal::Swap(ref sub) => Terminal::Swap(Arc::new(Miniscript::clone(sub))), - Terminal::Check(ref sub) => Terminal::Check(Arc::new(Miniscript::clone(sub))), - Terminal::DupIf(ref sub) => Terminal::DupIf(Arc::new(Miniscript::clone(sub))), - Terminal::Verify(ref sub) => Terminal::Verify(Arc::new(Miniscript::clone(sub))), - Terminal::NonZero(ref sub) => Terminal::NonZero(Arc::new(Miniscript::clone(sub))), - Terminal::ZeroNotEqual(ref sub) => { - Terminal::ZeroNotEqual(Arc::new(Miniscript::clone(sub))) + Self::PkK(ref p) => Self::PkK(p.clone()), + Self::PkH(ref p) => Self::PkH(p.clone()), + Self::RawPkH(ref p) => Self::RawPkH(*p), + Self::After(ref n) => Self::After(*n), + Self::Older(ref n) => Self::Older(*n), + Self::Sha256(ref x) => Self::Sha256(x.clone()), + Self::Hash256(ref x) => Self::Hash256(x.clone()), + Self::Ripemd160(ref x) => Self::Ripemd160(x.clone()), + Self::Hash160(ref x) => Self::Hash160(x.clone()), + Self::True => Self::True, + Self::False => Self::False, + Self::Alt(ref sub) => Self::Alt(Arc::new(Miniscript::clone(sub))), + Self::Swap(ref sub) => Self::Swap(Arc::new(Miniscript::clone(sub))), + Self::Check(ref sub) => Self::Check(Arc::new(Miniscript::clone(sub))), + Self::DupIf(ref sub) => Self::DupIf(Arc::new(Miniscript::clone(sub))), + Self::Verify(ref sub) => Self::Verify(Arc::new(Miniscript::clone(sub))), + Self::NonZero(ref sub) => Self::NonZero(Arc::new(Miniscript::clone(sub))), + Self::ZeroNotEqual(ref sub) => { + Self::ZeroNotEqual(Arc::new(Miniscript::clone(sub))) } - Terminal::AndV(ref left, ref right) => Terminal::AndV( + Self::AndV(ref left, ref right) => Self::AndV( Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right)), ), - Terminal::AndB(ref left, ref right) => Terminal::AndB( + Self::AndB(ref left, ref right) => Self::AndB( Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right)), ), - Terminal::AndOr(ref a, ref b, ref c) => Terminal::AndOr( + Self::AndOr(ref a, ref b, ref c) => Self::AndOr( Arc::new(Miniscript::clone(a)), Arc::new(Miniscript::clone(b)), Arc::new(Miniscript::clone(c)), ), - Terminal::OrB(ref left, ref right) => { - Terminal::OrB(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) + Self::OrB(ref left, ref right) => { + Self::OrB(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) } - Terminal::OrD(ref left, ref right) => { - Terminal::OrD(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) + Self::OrD(ref left, ref right) => { + Self::OrD(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) } - Terminal::OrC(ref left, ref right) => { - Terminal::OrC(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) + Self::OrC(ref left, ref right) => { + Self::OrC(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) } - Terminal::OrI(ref left, ref right) => { - Terminal::OrI(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) + Self::OrI(ref left, ref right) => { + Self::OrI(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) } - Terminal::Thresh(ref thresh) => { - Terminal::Thresh(thresh.map_ref(|child| Arc::new(Miniscript::clone(child)))) + Self::Thresh(ref thresh) => { + Self::Thresh(thresh.map_ref(|child| Arc::new(Miniscript::clone(child)))) } - Terminal::Multi(ref thresh) => Terminal::Multi(thresh.clone()), - Terminal::SortedMulti(ref thresh) => Terminal::SortedMulti(thresh.clone()), - Terminal::MultiA(ref thresh) => Terminal::MultiA(thresh.clone()), - Terminal::SortedMultiA(ref thresh) => Terminal::SortedMultiA(thresh.clone()), + Self::Multi(ref thresh) => Self::Multi(thresh.clone()), + Self::SortedMulti(ref thresh) => Self::SortedMulti(thresh.clone()), + Self::MultiA(ref thresh) => Self::MultiA(thresh.clone()), + Self::SortedMultiA(ref thresh) => Self::SortedMultiA(thresh.clone()), } } } @@ -227,21 +227,21 @@ impl PartialEq for Terminal { fn eq(&self, other: &Self) -> bool { for (me, you) in self.pre_order_iter().zip(other.pre_order_iter()) { match (me, you) { - (Terminal::PkK(key1), Terminal::PkK(key2)) if key1 != key2 => return false, - (Terminal::PkH(key1), Terminal::PkH(key2)) if key1 != key2 => return false, - (Terminal::RawPkH(h1), Terminal::RawPkH(h2)) if h1 != h2 => return false, - (Terminal::After(t1), Terminal::After(t2)) if t1 != t2 => return false, - (Terminal::Older(t1), Terminal::Older(t2)) if t1 != t2 => return false, - (Terminal::Sha256(h1), Terminal::Sha256(h2)) if h1 != h2 => return false, - (Terminal::Hash256(h1), Terminal::Hash256(h2)) if h1 != h2 => return false, - (Terminal::Ripemd160(h1), Terminal::Ripemd160(h2)) if h1 != h2 => return false, - (Terminal::Hash160(h1), Terminal::Hash160(h2)) if h1 != h2 => return false, - (Terminal::Multi(th1), Terminal::Multi(th2)) if th1 != th2 => return false, - (Terminal::SortedMulti(th1), Terminal::SortedMulti(th2)) if th1 != th2 => { + (Self::PkK(key1), Self::PkK(key2)) if key1 != key2 => return false, + (Self::PkH(key1), Self::PkH(key2)) if key1 != key2 => return false, + (Self::RawPkH(h1), Self::RawPkH(h2)) if h1 != h2 => return false, + (Self::After(t1), Self::After(t2)) if t1 != t2 => return false, + (Self::Older(t1), Self::Older(t2)) if t1 != t2 => return false, + (Self::Sha256(h1), Self::Sha256(h2)) if h1 != h2 => return false, + (Self::Hash256(h1), Self::Hash256(h2)) if h1 != h2 => return false, + (Self::Ripemd160(h1), Self::Ripemd160(h2)) if h1 != h2 => return false, + (Self::Hash160(h1), Self::Hash160(h2)) if h1 != h2 => return false, + (Self::Multi(th1), Self::Multi(th2)) if th1 != th2 => return false, + (Self::SortedMulti(th1), Self::SortedMulti(th2)) if th1 != th2 => { return false } - (Terminal::MultiA(th1), Terminal::MultiA(th2)) if th1 != th2 => return false, - (Terminal::SortedMultiA(th1), Terminal::SortedMultiA(th2)) if th1 != th2 => { + (Self::MultiA(th1), Self::MultiA(th2)) if th1 != th2 => return false, + (Self::SortedMultiA(th1), Self::SortedMultiA(th2)) if th1 != th2 => { return false } _ => { @@ -261,22 +261,22 @@ impl core::hash::Hash for Terminal key.hash(hasher), - Terminal::PkH(key) => key.hash(hasher), - Terminal::RawPkH(h) => h.hash(hasher), - Terminal::After(t) => t.hash(hasher), - Terminal::Older(t) => t.hash(hasher), - Terminal::Sha256(h) => h.hash(hasher), - Terminal::Hash256(h) => h.hash(hasher), - Terminal::Ripemd160(h) => h.hash(hasher), - Terminal::Hash160(h) => h.hash(hasher), - Terminal::Thresh(th) => { + Self::PkK(key) => key.hash(hasher), + Self::PkH(key) => key.hash(hasher), + Self::RawPkH(h) => h.hash(hasher), + Self::After(t) => t.hash(hasher), + Self::Older(t) => t.hash(hasher), + Self::Sha256(h) => h.hash(hasher), + Self::Hash256(h) => h.hash(hasher), + Self::Ripemd160(h) => h.hash(hasher), + Self::Hash160(h) => h.hash(hasher), + Self::Thresh(th) => { th.k().hash(hasher); th.n().hash(hasher); // The actual children will be hashed when we iterate } - Terminal::Multi(th) | Terminal::SortedMulti(th) => th.hash(hasher), - Terminal::MultiA(th) | Terminal::SortedMultiA(th) => th.hash(hasher), + Self::Multi(th) | Self::SortedMulti(th) => th.hash(hasher), + Self::MultiA(th) | Self::SortedMultiA(th) => th.hash(hasher), _ => {} } } diff --git a/src/miniscript/display.rs b/src/miniscript/display.rs index 3a1ac1ebd..ea6128ab1 100644 --- a/src/miniscript/display.rs +++ b/src/miniscript/display.rs @@ -239,47 +239,47 @@ impl Terminal { /// Not public since we intend to move it to the Inner type once that exists. fn fragment_name(&self) -> &'static str { match *self { - Terminal::True => "1", - Terminal::False => "0", - Terminal::PkK(..) => "pk_k", - Terminal::PkH(..) => "pk_h", + Self::True => "1", + Self::False => "0", + Self::PkK(..) => "pk_k", + Self::PkH(..) => "pk_h", // `RawPkH` is currently unsupported in the descriptor spec. We temporarily // display and parse these by prefixing them with 'expr'. - Terminal::RawPkH(..) => "expr_raw_pk_h", - Terminal::After(..) => "after", - Terminal::Older(..) => "older", - Terminal::Sha256(..) => "sha256", - Terminal::Hash256(..) => "hash256", - Terminal::Ripemd160(..) => "ripemd160", - Terminal::Hash160(..) => "hash160", - Terminal::Alt(..) => "a", - Terminal::Swap(..) => "s", - Terminal::Check(ref sub) if matches!(sub.as_inner(), Terminal::PkK(..)) => "pk", - Terminal::Check(ref sub) if matches!(sub.as_inner(), Terminal::PkH(..)) => "pkh", - Terminal::Check(ref sub) if matches!(sub.as_inner(), Terminal::RawPkH(..)) => { + Self::RawPkH(..) => "expr_raw_pk_h", + Self::After(..) => "after", + Self::Older(..) => "older", + Self::Sha256(..) => "sha256", + Self::Hash256(..) => "hash256", + Self::Ripemd160(..) => "ripemd160", + Self::Hash160(..) => "hash160", + Self::Alt(..) => "a", + Self::Swap(..) => "s", + Self::Check(ref sub) if matches!(sub.as_inner(), Self::PkK(..)) => "pk", + Self::Check(ref sub) if matches!(sub.as_inner(), Self::PkH(..)) => "pkh", + Self::Check(ref sub) if matches!(sub.as_inner(), Self::RawPkH(..)) => { "expr_raw_pkh" } - Terminal::Check(..) => "c", - Terminal::DupIf(..) => "d", - Terminal::Verify(..) => "v", - Terminal::NonZero(..) => "j", - Terminal::ZeroNotEqual(..) => "n", - Terminal::AndV(_, ref r) if matches!(r.as_inner(), Terminal::True) => "t", - Terminal::AndV(..) => "and_v", - Terminal::AndOr(_, _, ref c) if matches!(c.as_inner(), Terminal::False) => "and_n", - Terminal::AndB(..) => "and_b", - Terminal::AndOr(..) => "andor", - Terminal::OrB(..) => "or_b", - Terminal::OrD(..) => "or_d", - Terminal::OrC(..) => "or_c", - Terminal::OrI(_, ref r) if matches!(r.as_inner(), Terminal::False) => "u", - Terminal::OrI(ref l, _) if matches!(l.as_inner(), Terminal::False) => "l", - Terminal::OrI(..) => "or_i", - Terminal::Thresh(..) => "thresh", - Terminal::Multi(..) => "multi", - Terminal::SortedMulti(..) => "sortedmulti", - Terminal::MultiA(..) => "multi_a", - Terminal::SortedMultiA(..) => "sortedmulti_a", + Self::Check(..) => "c", + Self::DupIf(..) => "d", + Self::Verify(..) => "v", + Self::NonZero(..) => "j", + Self::ZeroNotEqual(..) => "n", + Self::AndV(_, ref r) if matches!(r.as_inner(), Self::True) => "t", + Self::AndV(..) => "and_v", + Self::AndOr(_, _, ref c) if matches!(c.as_inner(), Self::False) => "and_n", + Self::AndB(..) => "and_b", + Self::AndOr(..) => "andor", + Self::OrB(..) => "or_b", + Self::OrD(..) => "or_d", + Self::OrC(..) => "or_c", + Self::OrI(_, ref r) if matches!(r.as_inner(), Self::False) => "u", + Self::OrI(ref l, _) if matches!(l.as_inner(), Self::False) => "l", + Self::OrI(..) => "or_i", + Self::Thresh(..) => "thresh", + Self::Multi(..) => "multi", + Self::SortedMulti(..) => "sortedmulti", + Self::MultiA(..) => "multi_a", + Self::SortedMultiA(..) => "sortedmulti_a", } } @@ -287,7 +287,7 @@ impl Terminal { /// /// Not public since we intend to move it to the Inner type once that exists. fn is_wrapper(&self) -> bool { - !matches!(self, Terminal::True | Terminal::False) && self.fragment_name().len() == 1 + !matches!(self, Self::True | Self::False) && self.fragment_name().len() == 1 } } diff --git a/src/miniscript/iter.rs b/src/miniscript/iter.rs index 0ef2272af..7a19253e5 100644 --- a/src/miniscript/iter.rs +++ b/src/miniscript/iter.rs @@ -27,7 +27,7 @@ impl Miniscript { /// Enumerates all child nodes of the current AST node (`self`) and returns a `Vec` referencing /// them. - pub fn branches(&self) -> Vec<&Miniscript> { + pub fn branches(&self) -> Vec<&Self> { match self.node { Terminal::PkK(_) | Terminal::PkH(_) @@ -63,7 +63,7 @@ impl Miniscript { } /// Returns child node with given index, if any - pub fn get_nth_child(&self, n: usize) -> Option<&Miniscript> { + pub fn get_nth_child(&self, n: usize) -> Option<&Self> { match (n, &self.node) { (0, Terminal::Alt(node)) | (0, Terminal::Swap(node)) diff --git a/src/miniscript/lex.rs b/src/miniscript/lex.rs index 1df1f2dd4..a40a3108d 100644 --- a/src/miniscript/lex.rs +++ b/src/miniscript/lex.rs @@ -53,11 +53,11 @@ pub enum Token { impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Token::Num(n) => write!(f, "#{}", n), - Token::Hash20(b) => write!(f, "{}", b.as_hex()), - Token::Bytes32(b) => write!(f, "{}", b.as_hex()), - Token::Bytes33(b) => write!(f, "{}", b.as_hex()), - Token::Bytes65(b) => write!(f, "{}", b.as_hex()), + Self::Num(n) => write!(f, "#{}", n), + Self::Hash20(b) => write!(f, "{}", b.as_hex()), + Self::Bytes32(b) => write!(f, "{}", b.as_hex()), + Self::Bytes33(b) => write!(f, "{}", b.as_hex()), + Self::Bytes65(b) => write!(f, "{}", b.as_hex()), x => write!(f, "{:?}", x), } } @@ -70,7 +70,7 @@ pub struct TokenIter(Vec); impl TokenIter { /// Create a new TokenIter - pub fn new(v: Vec) -> TokenIter { TokenIter(v) } + pub fn new(v: Vec) -> Self { Self(v) } /// Look at the top at Iterator pub fn peek(&self) -> Option<&Token> { self.0.last() } diff --git a/src/miniscript/mod.rs b/src/miniscript/mod.rs index cb944b585..b021a556b 100644 --- a/src/miniscript/mod.rs +++ b/src/miniscript/mod.rs @@ -130,7 +130,7 @@ mod private { Terminal::SortedMultiA(ref thresh) => Terminal::SortedMultiA(thresh.clone()), }; - stack.push(Arc::new(Miniscript { + stack.push(Arc::new(Self { node: new_term, ty: item.node.ty, ext: item.node.ext, @@ -145,7 +145,7 @@ mod private { impl Miniscript { /// The `1` combinator. - pub const TRUE: Self = Miniscript { + pub const TRUE: Self = Self { node: Terminal::True, ty: types::Type::TRUE, ext: types::extra_props::ExtData::TRUE, @@ -153,7 +153,7 @@ mod private { }; /// The `0` combinator. - pub const FALSE: Self = Miniscript { + pub const FALSE: Self = Self { node: Terminal::False, ty: types::Type::FALSE, ext: types::extra_props::ExtData::FALSE, @@ -319,8 +319,8 @@ mod private { /// Add type information(Type and Extdata) to Miniscript based on /// `AstElem` fragment. Dependent on display and clone because of Error /// Display code of type_check. - pub fn from_ast(t: Terminal) -> Result, Error> { - let res = Miniscript { + pub fn from_ast(t: Terminal) -> Result { + let res = Self { ty: Type::type_check(&t)?, ext: ExtData::type_check(&t), node: t, @@ -346,8 +346,8 @@ mod private { node: Terminal, ty: types::Type, ext: types::extra_props::ExtData, - ) -> Miniscript { - Miniscript { node, ty, ext, phantom: PhantomData } + ) -> Self { + Self { node, ty, ext, phantom: PhantomData } } } } @@ -563,15 +563,15 @@ impl Miniscript { /// It may make sense to use this method when parsing Script that is already /// embedded in the chain. While it is inadvisable to use insane Miniscripts, /// once it's on the chain you don't have much choice anymore. - pub fn decode_consensus(script: &script::Script) -> Result, Error> { - Miniscript::decode_with_ext(script, &ExtParams::allow_all()) + pub fn decode_consensus(script: &script::Script) -> Result { + Self::decode_with_ext(script, &ExtParams::allow_all()) } /// Attempt to decode a Miniscript from Script, specifying which validation parameters to apply. pub fn decode_with_ext( script: &script::Script, ext: &ExtParams, - ) -> Result, Error> { + ) -> Result { let tokens = lex(script)?; let mut iter = TokenIter::new(tokens); @@ -621,7 +621,7 @@ impl Miniscript { /// .expect("Compressed keys are allowed in Segwit context"); /// /// ``` - pub fn decode(script: &script::Script) -> Result, Error> { + pub fn decode(script: &script::Script) -> Result { let ms = Self::decode_with_ext(script, &ExtParams::sane())?; Ok(ms) } @@ -631,7 +631,7 @@ impl Miniscript { /// /// The type information and extra properties are implied by the AST. impl PartialOrd for Miniscript { - fn partial_cmp(&self, other: &Miniscript) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } @@ -640,14 +640,14 @@ impl PartialOrd for Miniscript { /// /// The type information and extra properties are implied by the AST. impl Ord for Miniscript { - fn cmp(&self, other: &Miniscript) -> cmp::Ordering { self.node.cmp(&other.node) } + fn cmp(&self, other: &Self) -> cmp::Ordering { self.node.cmp(&other.node) } } /// `PartialEq` of `Miniscript` must depend only on node and not the type information. /// /// The type information and extra properties are implied by the AST. impl PartialEq for Miniscript { - fn eq(&self, other: &Miniscript) -> bool { self.node.eq(&other.node) } + fn eq(&self, other: &Self) -> bool { self.node.eq(&other.node) } } /// `Eq` of `Miniscript` must depend only on node and not the type information. @@ -778,7 +778,7 @@ impl Miniscript { } /// Substitutes raw public keys hashes with the public keys as provided by map. - pub fn substitute_raw_pkh(&self, pk_map: &BTreeMap) -> Miniscript { + pub fn substitute_raw_pkh(&self, pk_map: &BTreeMap) -> Self { let mut stack = vec![]; for item in self.rtl_post_order_iter() { let new_term = match item.node.node { @@ -824,7 +824,7 @@ impl Miniscript { Terminal::SortedMultiA(ref thresh) => Terminal::SortedMultiA(thresh.clone()), }; - stack.push(Arc::new(Miniscript::from_components_unchecked( + stack.push(Arc::new(Self::from_components_unchecked( new_term, item.node.ty, item.node.ext, @@ -844,8 +844,8 @@ impl Miniscript { /// Some of the analysis guarantees of miniscript are lost when dealing with /// insane scripts. In general, in a multi-party setting users should only /// accept sane scripts. - pub fn from_str_insane(s: &str) -> Result, Error> { - Miniscript::from_str_ext(s, &ExtParams::insane()) + pub fn from_str_insane(s: &str) -> Result { + Self::from_str_ext(s, &ExtParams::insane()) } /// Attempt to parse an Miniscripts that don't follow the spec. @@ -853,10 +853,10 @@ impl Miniscript { /// scripts, raw pubkey hashes without sig or scripts that can exceed resource limits. /// /// Use [`ExtParams`] builder to specify the types of non-sane rules to allow while parsing. - pub fn from_str_ext(s: &str, ext: &ExtParams) -> Result, Error> { + pub fn from_str_ext(s: &str, ext: &ExtParams) -> Result { // This checks for invalid ASCII chars let top = expression::Tree::from_str(s)?; - let ms: Miniscript = expression::FromTree::from_tree(top.root())?; + let ms: Self = expression::FromTree::from_tree(top.root())?; ms.ext_check(ext)?; if ms.ty.corr.base != types::Base::B { @@ -869,7 +869,7 @@ impl Miniscript { impl FromTree for Arc> { fn from_tree(root: TreeIterItem) -> Result { - Miniscript::from_tree(root).map(Arc::new) + Miniscript::from_tree(root).map(Self::new) } } @@ -932,70 +932,70 @@ impl FromTree for Miniscript { let new = match frag_name { "expr_raw_pkh" => node .verify_terminal_parent("expr_raw_pkh", "public key hash") - .map(Miniscript::expr_raw_pkh) + .map(Self::expr_raw_pkh) .map_err(Error::Parse), "pk" => node .verify_terminal_parent("pk", "public key") - .map(Miniscript::pk) + .map(Self::pk) .map_err(Error::Parse), "pkh" => node .verify_terminal_parent("pkh", "public key") - .map(Miniscript::pkh) + .map(Self::pkh) .map_err(Error::Parse), "pk_k" => node .verify_terminal_parent("pk_k", "public key") - .map(Miniscript::pk_k) + .map(Self::pk_k) .map_err(Error::Parse), "pk_h" => node .verify_terminal_parent("pk_h", "public key") - .map(Miniscript::pk_h) + .map(Self::pk_h) .map_err(Error::Parse), "after" => node .verify_after() - .map(Miniscript::after) + .map(Self::after) .map_err(Error::Parse), "older" => node .verify_older() - .map(Miniscript::older) + .map(Self::older) .map_err(Error::Parse), "sha256" => node .verify_terminal_parent("sha256", "hash") - .map(Miniscript::sha256) + .map(Self::sha256) .map_err(Error::Parse), "hash256" => node .verify_terminal_parent("hash256", "hash") - .map(Miniscript::hash256) + .map(Self::hash256) .map_err(Error::Parse), "ripemd160" => node .verify_terminal_parent("ripemd160", "hash") - .map(Miniscript::ripemd160) + .map(Self::ripemd160) .map_err(Error::Parse), "hash160" => node .verify_terminal_parent("hash160", "hash") - .map(Miniscript::hash160) + .map(Self::hash160) .map_err(Error::Parse), "1" => { node.verify_n_children("1", 0..=0) .map_err(From::from) .map_err(Error::Parse)?; - Ok(Miniscript::TRUE) + Ok(Self::TRUE) } "0" => { node.verify_n_children("0", 0..=0) .map_err(From::from) .map_err(Error::Parse)?; - Ok(Miniscript::FALSE) + Ok(Self::FALSE) } "and_v" => binary(node, &mut stack, "and_v", Terminal::AndV), "and_b" => binary(node, &mut stack, "and_b", Terminal::AndB), "and_n" => binary(node, &mut stack, "and_n", |x, y| { - Terminal::AndOr(x, y, Arc::new(Miniscript::FALSE)) + Terminal::AndOr(x, y, Arc::new(Self::FALSE)) }), "andor" => { node.verify_n_children("andor", 3..=3) .map_err(From::from) .map_err(Error::Parse)?; - Miniscript::from_ast(Terminal::AndOr( + Self::from_ast(Terminal::AndOr( stack.pop().unwrap(), stack.pop().unwrap(), stack.pop().unwrap(), @@ -1008,23 +1008,23 @@ impl FromTree for Miniscript { "thresh" => node .verify_threshold(|_| Ok(stack.pop().unwrap())) .map(Terminal::Thresh) - .and_then(Miniscript::from_ast), + .and_then(Self::from_ast), "multi" => node .verify_threshold(|sub| sub.verify_terminal("public_key").map_err(Error::Parse)) .map(Terminal::Multi) - .and_then(Miniscript::from_ast), + .and_then(Self::from_ast), "sortedmulti" => node .verify_threshold(|sub| sub.verify_terminal("public_key").map_err(Error::Parse)) .map(Terminal::SortedMulti) - .and_then(Miniscript::from_ast), + .and_then(Self::from_ast), "multi_a" => node .verify_threshold(|sub| sub.verify_terminal("public_key").map_err(Error::Parse)) .map(Terminal::MultiA) - .and_then(Miniscript::from_ast), + .and_then(Self::from_ast), "sortedmulti_a" => node .verify_threshold(|sub| sub.verify_terminal("public_key").map_err(Error::Parse)) .map(Terminal::SortedMultiA) - .and_then(Miniscript::from_ast), + .and_then(Self::from_ast), x => { Err(Error::Parse(crate::ParseError::Tree(crate::ParseTreeError::UnknownName { name: x.to_owned(), @@ -1050,12 +1050,12 @@ impl FromTree for Miniscript { b'v' => Terminal::Verify(new), b'j' => Terminal::NonZero(new), b'n' => Terminal::ZeroNotEqual(new), - b't' => Terminal::AndV(new, Arc::new(Miniscript::TRUE)), - b'u' => Terminal::OrI(new, Arc::new(Miniscript::FALSE)), - b'l' => Terminal::OrI(Arc::new(Miniscript::FALSE), new), + b't' => Terminal::AndV(new, Arc::new(Self::TRUE)), + b'u' => Terminal::OrI(new, Arc::new(Self::FALSE)), + b'l' => Terminal::OrI(Arc::new(Self::FALSE), new), x => return Err(Error::UnknownWrapper(x.into())), }; - new = Arc::new(Miniscript::from_ast(term)?); + new = Arc::new(Self::from_ast(term)?); } } @@ -1080,7 +1080,7 @@ impl str::FromStr for Miniscript { /// Parse a Miniscript from string and perform sanity checks /// See [Miniscript::from_str_insane] to parse scripts from string that /// do not clear the [Miniscript::sanity_check] checks. - fn from_str(s: &str) -> Result, Error> { + fn from_str(s: &str) -> Result { let ms = Self::from_str_ext(s, &ExtParams::sane())?; Ok(ms) } diff --git a/src/miniscript/satisfy/mod.rs b/src/miniscript/satisfy/mod.rs index cc38e386b..d0ad9cf30 100644 --- a/src/miniscript/satisfy/mod.rs +++ b/src/miniscript/satisfy/mod.rs @@ -741,14 +741,14 @@ impl Placeholder { /// Replaces the placeholders with the information given by the satisfier pub fn satisfy_self>(&self, sat: &Sat) -> Option> { match self { - Placeholder::Pubkey(pk, size) => { + Self::Pubkey(pk, size) => { if *size == 33 { Some(pk.to_x_only_pubkey().serialize().to_vec()) } else { Some(pk.to_public_key().to_bytes()) } } - Placeholder::PubkeyHash(pkh, size) => sat + Self::PubkeyHash(pkh, size) => sat .lookup_raw_pkh_pk(pkh) .map(|p| p.to_public_key()) .or(sat.lookup_raw_pkh_ecdsa_sig(pkh).map(|(p, _)| p)) @@ -758,40 +758,40 @@ impl Placeholder { debug_assert!(1 + pk.len() == *size); pk }), - Placeholder::Hash256Preimage(h) => sat.lookup_hash256(h).map(|p| p.to_vec()), - Placeholder::Sha256Preimage(h) => sat.lookup_sha256(h).map(|p| p.to_vec()), - Placeholder::Hash160Preimage(h) => sat.lookup_hash160(h).map(|p| p.to_vec()), - Placeholder::Ripemd160Preimage(h) => sat.lookup_ripemd160(h).map(|p| p.to_vec()), - Placeholder::EcdsaSigPk(pk) => sat.lookup_ecdsa_sig(pk).map(|s| s.to_vec()), - Placeholder::EcdsaSigPkHash(pkh) => { + Self::Hash256Preimage(h) => sat.lookup_hash256(h).map(|p| p.to_vec()), + Self::Sha256Preimage(h) => sat.lookup_sha256(h).map(|p| p.to_vec()), + Self::Hash160Preimage(h) => sat.lookup_hash160(h).map(|p| p.to_vec()), + Self::Ripemd160Preimage(h) => sat.lookup_ripemd160(h).map(|p| p.to_vec()), + Self::EcdsaSigPk(pk) => sat.lookup_ecdsa_sig(pk).map(|s| s.to_vec()), + Self::EcdsaSigPkHash(pkh) => { sat.lookup_raw_pkh_ecdsa_sig(pkh).map(|(_, s)| s.to_vec()) } - Placeholder::SchnorrSigPk(pk, SchnorrSigType::ScriptSpend { leaf_hash }, size) => sat + Self::SchnorrSigPk(pk, SchnorrSigType::ScriptSpend { leaf_hash }, size) => sat .lookup_tap_leaf_script_sig(pk, leaf_hash) .map(|s| s.to_vec()) .map(|s| { debug_assert!(s.len() == *size); s }), - Placeholder::SchnorrSigPk(pk, _, size) => sat + Self::SchnorrSigPk(pk, _, size) => sat .lookup_tap_key_spend_sig(pk) .map(|s| s.to_vec()) .map(|s| { debug_assert!(s.len() == *size); s }), - Placeholder::SchnorrSigPkHash(pkh, tap_leaf_hash, size) => sat + Self::SchnorrSigPkHash(pkh, tap_leaf_hash, size) => sat .lookup_raw_pkh_tap_leaf_script_sig(&(*pkh, *tap_leaf_hash)) .map(|(_, s)| { let sig = s.to_vec(); debug_assert!(sig.len() == *size); sig }), - Placeholder::HashDissatisfaction => Some(vec![0; 32]), - Placeholder::PushZero => Some(vec![]), - Placeholder::PushOne => Some(vec![1]), - Placeholder::TapScript(s) => Some(s.to_bytes()), - Placeholder::TapControlBlock(cb) => Some(cb.serialize()), + Self::HashDissatisfaction => Some(vec![0; 32]), + Self::PushZero => Some(vec![]), + Self::PushOne => Some(vec![1]), + Self::TapScript(s) => Some(s.to_bytes()), + Self::TapControlBlock(cb) => Some(cb.serialize()), } } } @@ -816,17 +816,17 @@ impl PartialOrd for Witness> { impl Ord for Witness> { fn cmp(&self, other: &Self) -> cmp::Ordering { match (self, other) { - (Witness::Stack(v1), Witness::Stack(v2)) => { + (Self::Stack(v1), Self::Stack(v2)) => { let w1 = witness_size(v1); let w2 = witness_size(v2); w1.cmp(&w2) } - (Witness::Stack(_), _) => cmp::Ordering::Less, - (_, Witness::Stack(_)) => cmp::Ordering::Greater, - (Witness::Impossible, Witness::Unavailable) => cmp::Ordering::Less, - (Witness::Unavailable, Witness::Impossible) => cmp::Ordering::Greater, - (Witness::Impossible, Witness::Impossible) => cmp::Ordering::Equal, - (Witness::Unavailable, Witness::Unavailable) => cmp::Ordering::Equal, + (Self::Stack(_), _) => cmp::Ordering::Less, + (_, Self::Stack(_)) => cmp::Ordering::Greater, + (Self::Impossible, Self::Unavailable) => cmp::Ordering::Less, + (Self::Unavailable, Self::Impossible) => cmp::Ordering::Greater, + (Self::Impossible, Self::Impossible) => cmp::Ordering::Equal, + (Self::Unavailable, Self::Unavailable) => cmp::Ordering::Equal, } } } @@ -836,20 +836,20 @@ impl Witness> { fn signature>(sat: &S, pk: &Pk, leaf_hash: Option) -> Self { if let Some(leaf_hash) = leaf_hash { match sat.provider_lookup_tap_leaf_script_sig(pk, &leaf_hash) { - Some(size) => Witness::Stack(vec![Placeholder::SchnorrSigPk( + Some(size) => Self::Stack(vec![Placeholder::SchnorrSigPk( pk.clone(), SchnorrSigType::ScriptSpend { leaf_hash }, size, )]), // Signatures cannot be forged - None => Witness::Impossible, + None => Self::Impossible, } } else { if sat.provider_lookup_ecdsa_sig(pk) { - Witness::Stack(vec![Placeholder::EcdsaSigPk(pk.clone())]) + Self::Stack(vec![Placeholder::EcdsaSigPk(pk.clone())]) } else { // Signatures cannot be forged - Witness::Impossible + Self::Impossible } } } @@ -863,12 +863,12 @@ impl Witness> { // instead of impossible since it is the same as pub-key hashes match Ctx::sig_type() { SigType::Ecdsa => match sat.provider_lookup_raw_pkh_pk(pkh) { - Some(pk) => Witness::Stack(vec![Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk))]), - None => Witness::Unavailable, + Some(pk) => Self::Stack(vec![Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk))]), + None => Self::Unavailable, }, SigType::Schnorr => match sat.provider_lookup_raw_pkh_x_only_pk(pkh) { - Some(pk) => Witness::Stack(vec![Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk))]), - None => Witness::Unavailable, + Some(pk) => Self::Stack(vec![Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk))]), + None => Self::Unavailable, }, } } @@ -881,19 +881,19 @@ impl Witness> { ) -> Self { if let Some(leaf_hash) = leaf_hash { match sat.provider_lookup_raw_pkh_tap_leaf_script_sig(&(*pkh, leaf_hash)) { - Some((pk, size)) => Witness::Stack(vec![ + Some((pk, size)) => Self::Stack(vec![ Placeholder::SchnorrSigPkHash(*pkh, leaf_hash, size), Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk)), ]), - None => Witness::Impossible, + None => Self::Impossible, } } else { match sat.provider_lookup_raw_pkh_ecdsa_sig(pkh) { - Some(pk) => Witness::Stack(vec![ + Some(pk) => Self::Stack(vec![ Placeholder::EcdsaSigPkHash(*pkh), Placeholder::PubkeyHash(*pkh, Ctx::pk_len(&pk)), ]), - None => Witness::Impossible, + None => Self::Impossible, } } } @@ -901,65 +901,65 @@ impl Witness> { /// Turn a hash preimage into (part of) a satisfaction fn ripemd160_preimage>(sat: &S, h: &Pk::Ripemd160) -> Self { if sat.provider_lookup_ripemd160(h) { - Witness::Stack(vec![Placeholder::Ripemd160Preimage(h.clone())]) + Self::Stack(vec![Placeholder::Ripemd160Preimage(h.clone())]) // Note hash preimages are unavailable instead of impossible } else { - Witness::Unavailable + Self::Unavailable } } /// Turn a hash preimage into (part of) a satisfaction fn hash160_preimage>(sat: &S, h: &Pk::Hash160) -> Self { if sat.provider_lookup_hash160(h) { - Witness::Stack(vec![Placeholder::Hash160Preimage(h.clone())]) + Self::Stack(vec![Placeholder::Hash160Preimage(h.clone())]) // Note hash preimages are unavailable instead of impossible } else { - Witness::Unavailable + Self::Unavailable } } /// Turn a hash preimage into (part of) a satisfaction fn sha256_preimage>(sat: &S, h: &Pk::Sha256) -> Self { if sat.provider_lookup_sha256(h) { - Witness::Stack(vec![Placeholder::Sha256Preimage(h.clone())]) + Self::Stack(vec![Placeholder::Sha256Preimage(h.clone())]) // Note hash preimages are unavailable instead of impossible } else { - Witness::Unavailable + Self::Unavailable } } /// Turn a hash preimage into (part of) a satisfaction fn hash256_preimage>(sat: &S, h: &Pk::Hash256) -> Self { if sat.provider_lookup_hash256(h) { - Witness::Stack(vec![Placeholder::Hash256Preimage(h.clone())]) + Self::Stack(vec![Placeholder::Hash256Preimage(h.clone())]) // Note hash preimages are unavailable instead of impossible } else { - Witness::Unavailable + Self::Unavailable } } } impl Witness> { /// Produce something like a 32-byte 0 push - fn hash_dissatisfaction() -> Self { Witness::Stack(vec![Placeholder::HashDissatisfaction]) } + fn hash_dissatisfaction() -> Self { Self::Stack(vec![Placeholder::HashDissatisfaction]) } /// Construct a satisfaction equivalent to an empty stack - const fn empty() -> Self { Witness::Stack(vec![]) } + const fn empty() -> Self { Self::Stack(vec![]) } /// Construct a satisfaction equivalent to `OP_1` - fn push_1() -> Self { Witness::Stack(vec![Placeholder::PushOne]) } + fn push_1() -> Self { Self::Stack(vec![Placeholder::PushOne]) } /// Construct a satisfaction equivalent to a single empty push - fn push_0() -> Self { Witness::Stack(vec![Placeholder::PushZero]) } + fn push_0() -> Self { Self::Stack(vec![Placeholder::PushZero]) } /// Concatenate, or otherwise combine, two satisfactions fn combine(one: Self, two: Self) -> Self { match (one, two) { - (Witness::Impossible, _) | (_, Witness::Impossible) => Witness::Impossible, - (Witness::Unavailable, _) | (_, Witness::Unavailable) => Witness::Unavailable, - (Witness::Stack(mut a), Witness::Stack(b)) => { + (Self::Impossible, _) | (_, Self::Impossible) => Self::Impossible, + (Self::Unavailable, _) | (_, Self::Unavailable) => Self::Unavailable, + (Self::Stack(mut a), Self::Stack(b)) => { a.extend(b); - Witness::Stack(a) + Self::Stack(a) } } } @@ -985,7 +985,7 @@ impl Satisfaction> { /// This has the property that, when concatenated on either side with another satisfaction /// X, the result will be X. fn empty() -> Self { - Satisfaction { + Self { has_sig: false, relative_timelock: None, absolute_timelock: None, @@ -1000,7 +1000,7 @@ impl Satisfaction> { /// natural than the opposite order, and more importantly, allows this method to be /// used when folding over an iterator of multiple satisfactions. fn concatenate_rev(self, other: Self) -> Self { - Satisfaction { + Self { has_sig: self.has_sig || other.has_sig, relative_timelock: cmp::max(self.relative_timelock, other.relative_timelock), absolute_timelock: cmp::max(self.absolute_timelock, other.absolute_timelock), @@ -1071,7 +1071,7 @@ impl Satisfaction> { // For example, the fragment thresh(2, hash, 0, 0, 0) // is has an impossible witness if sats[sat_indices[k - 1]].stack == Witness::Impossible { - Satisfaction { + Self { stack: Witness::Impossible, // If the witness is impossible, we don't care about the // has_sig flag, nor about the timelocks @@ -1098,7 +1098,7 @@ impl Satisfaction> { for sat in &ret_stack { assert!(!sat.has_sig); } - Satisfaction { + Self { stack: Witness::Unavailable, has_sig: false, relative_timelock: None, @@ -1108,7 +1108,7 @@ impl Satisfaction> { // Otherwise flatten everything out ret_stack .into_iter() - .fold(Satisfaction::empty(), Satisfaction::concatenate_rev) + .fold(Self::empty(), Self::concatenate_rev) } } @@ -1142,7 +1142,7 @@ impl Satisfaction> { // no non-malleability checks needed ret_stack .into_iter() - .fold(Satisfaction::empty(), Satisfaction::concatenate_rev) + .fold(Self::empty(), Self::concatenate_rev) } fn minimum(sat1: Self, sat2: Self) -> Self { @@ -1157,7 +1157,7 @@ impl Satisfaction> { match (sat1.has_sig, sat2.has_sig) { // If neither option has a signature, this is a malleability // vector, so choose neither one. - (false, false) => Satisfaction { + (false, false) => Self { stack: Witness::Unavailable, has_sig: false, relative_timelock: None, @@ -1166,13 +1166,13 @@ impl Satisfaction> { // If only one has a signature, take the one that doesn't; a // third party could malleate by removing the signature, but // can't malleate if he'd have to add it - (false, true) => Satisfaction { + (false, true) => Self { stack: sat1.stack, has_sig: false, relative_timelock: sat1.relative_timelock, absolute_timelock: sat1.absolute_timelock, }, - (true, false) => Satisfaction { + (true, false) => Self { stack: sat2.stack, has_sig: false, relative_timelock: sat2.relative_timelock, @@ -1181,13 +1181,13 @@ impl Satisfaction> { // If both have a signature associated with them, choose the // cheaper one (where "cheaper" is defined such that available // things are cheaper than unavailable ones) - (true, true) if sat1.stack < sat2.stack => Satisfaction { + (true, true) if sat1.stack < sat2.stack => Self { stack: sat1.stack, has_sig: true, relative_timelock: sat1.relative_timelock, absolute_timelock: sat1.absolute_timelock, }, - (true, true) => Satisfaction { + (true, true) => Self { stack: sat2.stack, has_sig: true, relative_timelock: sat2.relative_timelock, @@ -1210,7 +1210,7 @@ impl Satisfaction> { } else { (sat2.stack, sat2.absolute_timelock, sat2.relative_timelock) }; - Satisfaction { + Self { stack, // The fragment is has_sig only if both of the // fragments are has_sig @@ -1222,7 +1222,7 @@ impl Satisfaction> { /// Try creating the final witness using a [`Satisfier`] pub fn try_completing>(&self, stfr: &Sat) -> Option>> { - let Satisfaction { stack, has_sig, relative_timelock, absolute_timelock } = self; + let Self { stack, has_sig, relative_timelock, absolute_timelock } = self; let stack = match stack { Witness::Stack(stack) => Witness::Stack( stack diff --git a/src/miniscript/types/correctness.rs b/src/miniscript/types/correctness.rs index 5db001567..250a912dd 100644 --- a/src/miniscript/types/correctness.rs +++ b/src/miniscript/types/correctness.rs @@ -50,11 +50,11 @@ impl Input { const fn constfn_eq(self, other: Self) -> bool { matches!( (self, other), - (Input::Zero, Input::Zero) - | (Input::One, Input::One) - | (Input::Any, Input::Any) - | (Input::OneNonZero, Input::OneNonZero) - | (Input::AnyNonZero, Input::AnyNonZero) + (Self::Zero, Self::Zero) + | (Self::One, Self::One) + | (Self::Any, Self::Any) + | (Self::OneNonZero, Self::OneNonZero) + | (Self::AnyNonZero, Self::AnyNonZero) ) } @@ -64,9 +64,9 @@ impl Input { const fn is_subtype(&self, other: Self) -> bool { match (*self, other) { (x, y) if x.constfn_eq(y) => true, - (Input::OneNonZero, Input::One) - | (Input::OneNonZero, Input::AnyNonZero) - | (_, Input::Any) => true, + (Self::OneNonZero, Self::One) + | (Self::OneNonZero, Self::AnyNonZero) + | (_, Self::Any) => true, _ => false, } } @@ -97,11 +97,11 @@ pub struct Correctness { impl Correctness { /// Correctness data for the `1` combinator pub const TRUE: Self = - Correctness { base: Base::B, input: Input::Zero, dissatisfiable: false, unit: true }; + Self { base: Base::B, input: Input::Zero, dissatisfiable: false, unit: true }; /// Correctness data for the `0` combinator pub const FALSE: Self = - Correctness { base: Base::B, input: Input::Zero, dissatisfiable: true, unit: true }; + Self { base: Base::B, input: Input::Zero, dissatisfiable: true, unit: true }; /// Check whether the `self` is a subtype of `other` argument . /// This checks whether the argument `other` has attributes which are present @@ -134,12 +134,12 @@ impl Correctness { /// Constructor for the correctness properties of the `pk_k` fragment. pub const fn pk_k() -> Self { - Correctness { base: Base::K, input: Input::OneNonZero, dissatisfiable: true, unit: true } + Self { base: Base::K, input: Input::OneNonZero, dissatisfiable: true, unit: true } } /// Constructor for the correctness properties of the `pk_h` fragment. pub const fn pk_h() -> Self { - Correctness { + Self { base: Base::K, input: Input::AnyNonZero, dissatisfiable: true, // FIXME check with sipa @@ -149,37 +149,37 @@ impl Correctness { /// Constructor for the correctness properties of the `multi` fragment. pub const fn multi() -> Self { - Correctness { base: Base::B, input: Input::AnyNonZero, dissatisfiable: true, unit: true } + Self { base: Base::B, input: Input::AnyNonZero, dissatisfiable: true, unit: true } } /// Constructor for the correctness properties of the `sortedmulti` fragment. pub const fn sortedmulti() -> Self { - Correctness { base: Base::B, input: Input::AnyNonZero, dissatisfiable: true, unit: true } + Self { base: Base::B, input: Input::AnyNonZero, dissatisfiable: true, unit: true } } /// Constructor for the correctness properties of the `multi_a` fragment. pub const fn multi_a() -> Self { - Correctness { base: Base::B, input: Input::Any, dissatisfiable: true, unit: true } + Self { base: Base::B, input: Input::Any, dissatisfiable: true, unit: true } } /// Constructor for the correctness properties of the `sortedmulti_a` fragment. pub const fn sortedmulti_a() -> Self { - Correctness { base: Base::B, input: Input::Any, dissatisfiable: true, unit: true } + Self { base: Base::B, input: Input::Any, dissatisfiable: true, unit: true } } /// Constructor for the correctness properties of any of the hash fragments. pub const fn hash() -> Self { - Correctness { base: Base::B, input: Input::OneNonZero, dissatisfiable: true, unit: true } + Self { base: Base::B, input: Input::OneNonZero, dissatisfiable: true, unit: true } } /// Constructor for the correctness properties of either of the time fragments. pub const fn time() -> Self { - Correctness { base: Base::B, input: Input::Zero, dissatisfiable: false, unit: false } + Self { base: Base::B, input: Input::Zero, dissatisfiable: false, unit: false } } /// Constructor for the correctness properties of the `a:` fragment. pub const fn cast_alt(self) -> Result { - Ok(Correctness { + Ok(Self { base: match self.base { Base::B => Base::W, x => return Err(ErrorKind::ChildBase1(x)), @@ -192,7 +192,7 @@ impl Correctness { /// Constructor for the correctness properties of the `s:` fragment. pub const fn cast_swap(self) -> Result { - Ok(Correctness { + Ok(Self { base: match self.base { Base::B => Base::W, x => return Err(ErrorKind::ChildBase1(x)), @@ -208,7 +208,7 @@ impl Correctness { /// Constructor for the correctness properties of the `c:` fragment. pub const fn cast_check(self) -> Result { - Ok(Correctness { + Ok(Self { base: match self.base { Base::K => Base::B, x => return Err(ErrorKind::ChildBase1(x)), @@ -221,7 +221,7 @@ impl Correctness { /// Constructor for the correctness properties of the `d:` fragment. pub const fn cast_dupif(self) -> Result { - Ok(Correctness { + Ok(Self { base: match self.base { Base::V => Base::B, x => return Err(ErrorKind::ChildBase1(x)), @@ -237,7 +237,7 @@ impl Correctness { /// Constructor for the correctness properties of the `v:` fragment. pub const fn cast_verify(self) -> Result { - Ok(Correctness { + Ok(Self { base: match self.base { Base::B => Base::V, x => return Err(ErrorKind::ChildBase1(x)), @@ -253,7 +253,7 @@ impl Correctness { if !self.input.constfn_eq(Input::OneNonZero) && !self.input.constfn_eq(Input::AnyNonZero) { return Err(ErrorKind::NonZeroZero); } - Ok(Correctness { + Ok(Self { base: match self.base { Base::B => Base::B, x => return Err(ErrorKind::ChildBase1(x)), @@ -266,7 +266,7 @@ impl Correctness { /// Constructor for the correctness properties of the `n:` fragment. pub const fn cast_zeronotequal(self) -> Result { - Ok(Correctness { + Ok(Self { base: match self.base { Base::B => Base::B, x => return Err(ErrorKind::ChildBase1(x)), @@ -279,7 +279,7 @@ impl Correctness { /// Constructor for the correctness properties of the `t:` fragment. pub const fn cast_true(self) -> Result { - Ok(Correctness { + Ok(Self { base: match self.base { Base::V => Base::B, x => return Err(ErrorKind::ChildBase1(x)), @@ -292,7 +292,7 @@ impl Correctness { /// Constructor for the correctness properties of the `l:` and `u:` fragments. pub const fn cast_or_i_false(self) -> Result { - Ok(Correctness { + Ok(Self { base: match self.base { Base::B => Base::B, x => return Err(ErrorKind::ChildBase1(x)), @@ -310,7 +310,7 @@ impl Correctness { /// Constructor for the correctness properties of the `and_b` fragment pub const fn and_b(left: Self, right: Self) -> Result { - Ok(Correctness { + Ok(Self { base: match (left.base, right.base) { (Base::B, Base::W) => Base::B, (x, y) => return Err(ErrorKind::ChildBase2(x, y)), @@ -333,7 +333,7 @@ impl Correctness { /// Constructor for the correctness properties of the `and_v` fragment pub const fn and_v(left: Self, right: Self) -> Result { - Ok(Correctness { + Ok(Self { base: match (left.base, right.base) { (Base::V, Base::B) => Base::B, (Base::V, Base::K) => Base::K, @@ -364,7 +364,7 @@ impl Correctness { if !right.dissatisfiable { return Err(ErrorKind::RightNotDissatisfiable); } - Ok(Correctness { + Ok(Self { base: match (left.base, right.base) { (Base::B, Base::W) => Base::B, (x, y) => return Err(ErrorKind::ChildBase2(x, y)), @@ -390,7 +390,7 @@ impl Correctness { if !left.unit { return Err(ErrorKind::LeftNotUnit); } - Ok(Correctness { + Ok(Self { base: match (left.base, right.base) { (Base::B, Base::B) => Base::B, (x, y) => return Err(ErrorKind::ChildBase2(x, y)), @@ -413,7 +413,7 @@ impl Correctness { if !left.unit { return Err(ErrorKind::LeftNotUnit); } - Ok(Correctness { + Ok(Self { base: match (left.base, right.base) { (Base::B, Base::V) => Base::V, (x, y) => return Err(ErrorKind::ChildBase2(x, y)), @@ -430,7 +430,7 @@ impl Correctness { /// Constructor for the correctness properties of the `or_i` fragment pub const fn or_i(left: Self, right: Self) -> Result { - Ok(Correctness { + Ok(Self { base: match (left.base, right.base) { (Base::B, Base::B) => Base::B, (Base::V, Base::V) => Base::V, @@ -454,7 +454,7 @@ impl Correctness { if !a.unit { return Err(ErrorKind::LeftNotUnit); } - Ok(Correctness { + Ok(Self { base: match (a.base, b.base, c.base) { (Base::B, Base::B, Base::B) => Base::B, (Base::B, Base::K, Base::K) => Base::K, @@ -503,7 +503,7 @@ impl Correctness { } } - Ok(Correctness { + Ok(Self { base: Base::B, input: match num_args { 0 => Input::Zero, diff --git a/src/miniscript/types/extra_props.rs b/src/miniscript/types/extra_props.rs index 204b4bddf..2cd5061aa 100644 --- a/src/miniscript/types/extra_props.rs +++ b/src/miniscript/types/extra_props.rs @@ -29,7 +29,7 @@ pub struct TimelockInfo { impl TimelockInfo { /// Creates a new `TimelockInfo` with all fields set to false. pub const fn new() -> Self { - TimelockInfo { + Self { csv_with_height: false, csv_with_time: false, cltv_with_height: false, @@ -52,9 +52,9 @@ impl TimelockInfo { } /// Combines timelocks, if threshold `k` is greater than one we check for any unspendable paths. - pub(crate) fn combine_threshold(k: usize, timelocks: I) -> TimelockInfo + pub(crate) fn combine_threshold(k: usize, timelocks: I) -> Self where - I: IntoIterator, + I: IntoIterator, { // Propagate all fields of `TimelockInfo` from each of the node's children to the node // itself (by taking the logical-or of all of them). In case `k == 1` (this is a disjunction) @@ -65,7 +65,7 @@ impl TimelockInfo { // timelock requirements, this represents an inaccessible spending branch. timelocks .into_iter() - .fold(TimelockInfo::default(), |mut acc, t| { + .fold(Self::default(), |mut acc, t| { // If more than one branch may be taken, and some other branch has a requirement // that conflicts with this one, set `contains_combination`. if k > 1 { @@ -163,7 +163,7 @@ pub struct ExtData { impl ExtData { /// Extra data for the `0` combinator - pub const FALSE: Self = ExtData { + pub const FALSE: Self = Self { pk_cost: 1, has_free_verify: false, static_ops: 0, @@ -180,7 +180,7 @@ impl ExtData { }; /// Extra data for the `1` combinator - pub const TRUE: Self = ExtData { + pub const TRUE: Self = Self { pk_cost: 1, has_free_verify: false, static_ops: 0, @@ -211,7 +211,7 @@ impl ExtData { crate::SigType::Schnorr => (33, 66), }; - ExtData { + Self { pk_cost: key_bytes, has_free_verify: false, static_ops: 0, @@ -247,7 +247,7 @@ impl ExtData { (crate::SigType::Schnorr, _) => (33, 66), }; - ExtData { + Self { pk_cost: 24, has_free_verify: false, static_ops: 3, @@ -281,7 +281,7 @@ impl ExtData { (true, false) => 3, (false, false) => 2, }; - ExtData { + Self { pk_cost: num_cost + thresh .iter() @@ -325,7 +325,7 @@ impl ExtData { (true, false) => 3, (false, false) => 2, }; - ExtData { + Self { pk_cost: num_cost + 33 * n /*pks*/ + (n - 1) /*checksigadds*/ + 1, has_free_verify: true, static_ops: 0, // irrelevant; no ops limit in Taproot @@ -353,7 +353,7 @@ impl ExtData { /// Extra properties for the `sha256` fragment. pub const fn sha256() -> Self { - ExtData { + Self { pk_cost: 33 + 6, has_free_verify: true, static_ops: 4, @@ -378,7 +378,7 @@ impl ExtData { /// Extra properties for the `hash256` fragment. pub const fn hash256() -> Self { - ExtData { + Self { pk_cost: 33 + 6, has_free_verify: true, static_ops: 4, @@ -403,7 +403,7 @@ impl ExtData { /// Extra properties for the `ripemd160` fragment. pub const fn ripemd160() -> Self { - ExtData { + Self { pk_cost: 21 + 6, has_free_verify: true, static_ops: 4, @@ -428,7 +428,7 @@ impl ExtData { /// Extra properties for the `hash160` fragment. pub const fn hash160() -> Self { - ExtData { + Self { pk_cost: 21 + 6, has_free_verify: true, static_ops: 4, @@ -453,7 +453,7 @@ impl ExtData { /// Extra properties for the `after` fragment. pub fn after(t: AbsLockTime) -> Self { - ExtData { + Self { pk_cost: script_num_size(t.to_consensus_u32() as usize) + 1, has_free_verify: false, static_ops: 1, @@ -478,7 +478,7 @@ impl ExtData { /// Extra properties for the `older` fragment. pub fn older(t: RelLockTime) -> Self { - ExtData { + Self { pk_cost: script_num_size(t.to_consensus_u32() as usize) + 1, has_free_verify: false, static_ops: 1, @@ -503,7 +503,7 @@ impl ExtData { /// Extra properties for the `a:` fragment. pub const fn cast_alt(self) -> Self { - ExtData { + Self { pk_cost: self.pk_cost + 2, has_free_verify: false, static_ops: 2 + self.static_ops, @@ -516,7 +516,7 @@ impl ExtData { /// Extra properties for the `s:` fragment. pub const fn cast_swap(self) -> Self { - ExtData { + Self { pk_cost: self.pk_cost + 1, has_free_verify: self.has_free_verify, static_ops: 1 + self.static_ops, @@ -529,7 +529,7 @@ impl ExtData { /// Extra properties for the `c:` fragment. pub const fn cast_check(self) -> Self { - ExtData { + Self { pk_cost: self.pk_cost + 1, has_free_verify: true, static_ops: 1 + self.static_ops, @@ -542,7 +542,7 @@ impl ExtData { /// Extra properties for the `d:` fragment. pub fn cast_dupif(self) -> Self { - ExtData { + Self { pk_cost: self.pk_cost + 3, has_free_verify: false, static_ops: 3 + self.static_ops, @@ -569,7 +569,7 @@ impl ExtData { /// Extra properties for the `v:` fragment. pub fn cast_verify(self) -> Self { let verify_cost = usize::from(!self.has_free_verify); - ExtData { + Self { pk_cost: self.pk_cost + usize::from(!self.has_free_verify), has_free_verify: false, static_ops: verify_cost + self.static_ops, @@ -582,7 +582,7 @@ impl ExtData { /// Extra properties for the `j:` fragment. pub const fn cast_nonzero(self) -> Self { - ExtData { + Self { pk_cost: self.pk_cost + 4, has_free_verify: false, static_ops: 4 + self.static_ops, @@ -601,7 +601,7 @@ impl ExtData { /// Extra properties for the `n:` fragment. pub const fn cast_zeronotequal(self) -> Self { - ExtData { + Self { pk_cost: self.pk_cost + 1, has_free_verify: false, static_ops: 1 + self.static_ops, @@ -628,7 +628,7 @@ impl ExtData { /// Extra properties for the `and_b` fragment. pub fn and_b(l: Self, r: Self) -> Self { - ExtData { + Self { pk_cost: l.pk_cost + r.pk_cost + 1, has_free_verify: false, static_ops: 1 + l.static_ops + r.static_ops, @@ -657,7 +657,7 @@ impl ExtData { /// Extra properties for the `and_v` fragment. pub fn and_v(l: Self, r: Self) -> Self { - ExtData { + Self { pk_cost: l.pk_cost + r.pk_cost, has_free_verify: r.has_free_verify, static_ops: l.static_ops + r.static_ops, @@ -689,7 +689,7 @@ impl ExtData { }) }; - ExtData { + Self { pk_cost: l.pk_cost + r.pk_cost + 1, has_free_verify: false, static_ops: 1 + l.static_ops + r.static_ops, @@ -715,7 +715,7 @@ impl ExtData { }) }; - ExtData { + Self { pk_cost: l.pk_cost + r.pk_cost + 3, has_free_verify: false, static_ops: 3 + l.static_ops + r.static_ops, @@ -738,7 +738,7 @@ impl ExtData { }) }; - ExtData { + Self { pk_cost: l.pk_cost + r.pk_cost + 2, has_free_verify: false, static_ops: 2 + l.static_ops + r.static_ops, @@ -766,7 +766,7 @@ impl ExtData { max_exec_op_count: data.max_exec_op_count, }; - ExtData { + Self { pk_cost: l.pk_cost + r.pk_cost + 3, has_free_verify: false, static_ops: 3 + l.static_ops + r.static_ops, @@ -792,7 +792,7 @@ impl ExtData { }) }; - ExtData { + Self { pk_cost: a.pk_cost + b.pk_cost + c.pk_cost + 3, has_free_verify: false, static_ops: 3 + a.static_ops + b.static_ops + c.static_ops, @@ -931,7 +931,7 @@ impl ExtData { None }; - ExtData { + Self { pk_cost: pk_cost + n - 1, //all pk cost + (n-1)*ADD has_free_verify: true, static_ops: static_ops + 1 + (n - 1), // adds and equal diff --git a/src/miniscript/types/malleability.rs b/src/miniscript/types/malleability.rs index 93f32b3a6..79ee429e0 100644 --- a/src/miniscript/types/malleability.rs +++ b/src/miniscript/types/malleability.rs @@ -34,9 +34,9 @@ impl Dissat { const fn constfn_eq(self, other: Self) -> bool { matches!( (self, other), - (Dissat::None, Dissat::None) - | (Dissat::Unique, Dissat::Unique) - | (Dissat::Unknown, Dissat::Unknown) + (Self::None, Self::None) + | (Self::Unique, Self::Unique) + | (Self::Unknown, Self::Unknown) ) } @@ -45,7 +45,7 @@ impl Dissat { const fn is_subtype(&self, other: Self) -> bool { match (*self, other) { (x, y) if x.constfn_eq(y) => true, - (_, Dissat::Unknown) => true, + (_, Self::Unknown) => true, _ => false, } } @@ -70,11 +70,11 @@ pub struct Malleability { impl Malleability { /// Malleability data for the `1` combinator - pub const TRUE: Self = Malleability { dissat: Dissat::None, safe: false, non_malleable: true }; + pub const TRUE: Self = Self { dissat: Dissat::None, safe: false, non_malleable: true }; /// Malleability data for the `0` combinator pub const FALSE: Self = - Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true }; + Self { dissat: Dissat::Unique, safe: true, non_malleable: true }; /// Check whether the `self` is a subtype of `other` argument. /// @@ -91,42 +91,42 @@ impl Malleability { impl Malleability { /// Constructor for the malleabilitiy properties of the `pk_k` fragment. pub const fn pk_k() -> Self { - Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } + Self { dissat: Dissat::Unique, safe: true, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `pk_h` fragment. pub const fn pk_h() -> Self { - Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } + Self { dissat: Dissat::Unique, safe: true, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `multi` fragment. pub const fn multi() -> Self { - Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } + Self { dissat: Dissat::Unique, safe: true, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `sortedmulti` fragment. pub const fn sortedmulti() -> Self { - Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } + Self { dissat: Dissat::Unique, safe: true, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `multi_a` fragment. pub const fn multi_a() -> Self { - Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } + Self { dissat: Dissat::Unique, safe: true, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `sortedmulti_a` fragment. pub const fn sortedmulti_a() -> Self { - Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } + Self { dissat: Dissat::Unique, safe: true, non_malleable: true } } /// Constructor for the malleabilitiy properties of any of the hash fragments. pub const fn hash() -> Self { - Malleability { dissat: Dissat::Unknown, safe: false, non_malleable: true } + Self { dissat: Dissat::Unknown, safe: false, non_malleable: true } } /// Constructor for the malleabilitiy properties of either `after` or `older`. pub const fn time() -> Self { - Malleability { dissat: Dissat::None, safe: false, non_malleable: true } + Self { dissat: Dissat::None, safe: false, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `a:` fragment. @@ -140,7 +140,7 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `d:` fragment. pub const fn cast_dupif(self) -> Self { - Malleability { + Self { dissat: if self.dissat.constfn_eq(Dissat::None) { Dissat::Unique } else { @@ -153,12 +153,12 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `v:` fragment. pub const fn cast_verify(self) -> Self { - Malleability { dissat: Dissat::None, safe: self.safe, non_malleable: self.non_malleable } + Self { dissat: Dissat::None, safe: self.safe, non_malleable: self.non_malleable } } /// Constructor for the malleabilitiy properties of the `j:` fragment. pub const fn cast_nonzero(self) -> Self { - Malleability { + Self { dissat: if self.dissat.constfn_eq(Dissat::None) { Dissat::Unique } else { @@ -174,12 +174,12 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `t:` fragment. pub const fn cast_true(self) -> Self { - Malleability { dissat: Dissat::None, safe: self.safe, non_malleable: self.non_malleable } + Self { dissat: Dissat::None, safe: self.safe, non_malleable: self.non_malleable } } /// Constructor for the malleabilitiy properties of the `l:` or `u:` fragments. pub const fn cast_or_i_false(self) -> Self { - Malleability { + Self { dissat: if self.dissat.constfn_eq(Dissat::None) { Dissat::Unique } else { @@ -192,7 +192,7 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `and_b` fragment. pub const fn and_b(left: Self, right: Self) -> Self { - Malleability { + Self { dissat: match (left.dissat, right.dissat) { (Dissat::None, Dissat::None) => Dissat::None, (Dissat::None, _) if left.safe => Dissat::None, @@ -213,7 +213,7 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `and_v` fragment. pub const fn and_v(left: Self, right: Self) -> Self { - Malleability { + Self { dissat: match (left.safe, right.dissat) { (_, Dissat::None) => Dissat::None, // fy (true, _) => Dissat::None, // sx @@ -226,7 +226,7 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `or_b` fragment. pub const fn or_b(left: Self, right: Self) -> Self { - Malleability { + Self { dissat: Dissat::Unique, safe: left.safe && right.safe, non_malleable: left.non_malleable @@ -239,7 +239,7 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `or_d` fragment. pub const fn or_d(left: Self, right: Self) -> Self { - Malleability { + Self { dissat: right.dissat, safe: left.safe && right.safe, non_malleable: left.non_malleable @@ -251,7 +251,7 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `or_c` fragment. pub const fn or_c(left: Self, right: Self) -> Self { - Malleability { + Self { dissat: Dissat::None, safe: left.safe && right.safe, non_malleable: left.non_malleable @@ -263,7 +263,7 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `or_i` fragment. pub const fn or_i(left: Self, right: Self) -> Self { - Malleability { + Self { dissat: match (left.dissat, right.dissat) { (Dissat::None, Dissat::None) => Dissat::None, (Dissat::Unique, Dissat::None) => Dissat::Unique, @@ -277,7 +277,7 @@ impl Malleability { /// Constructor for the malleabilitiy properties of the `andor` fragment. pub const fn and_or(a: Self, b: Self, c: Self) -> Self { - Malleability { + Self { dissat: match (a.safe, b.dissat, c.dissat) { (_, Dissat::None, Dissat::Unique) => Dissat::Unique, //E: ez fy (true, _, Dissat::Unique) => Dissat::Unique, // E: ez sx @@ -310,7 +310,7 @@ impl Malleability { all_are_non_malleable &= subtype.non_malleable; } - Malleability { + Self { dissat: if all_are_dissat_unique && safe_count == n { Dissat::Unique } else { diff --git a/src/miniscript/types/mod.rs b/src/miniscript/types/mod.rs index 674603edf..1b3a3d88c 100644 --- a/src/miniscript/types/mod.rs +++ b/src/miniscript/types/mod.rs @@ -197,10 +197,10 @@ impl fmt::Display for Type { impl Type { /// Type of the `0` combinator - pub const TRUE: Self = Type { corr: Correctness::TRUE, mall: Malleability::TRUE }; + pub const TRUE: Self = Self { corr: Correctness::TRUE, mall: Malleability::TRUE }; /// Type of the `0` combinator - pub const FALSE: Self = Type { corr: Correctness::FALSE, mall: Malleability::FALSE }; + pub const FALSE: Self = Self { corr: Correctness::FALSE, mall: Malleability::FALSE }; /// Check whether the `self` is a subtype of `other` argument . /// This checks whether the argument `other` has attributes which are present @@ -219,41 +219,41 @@ impl Type { } /// Constructor for the type of the `pk_k` fragment. - pub const fn pk_k() -> Self { Type { corr: Correctness::pk_k(), mall: Malleability::pk_k() } } + pub const fn pk_k() -> Self { Self { corr: Correctness::pk_k(), mall: Malleability::pk_k() } } /// Constructor for the type of the `pk_h` fragment. - pub const fn pk_h() -> Self { Type { corr: Correctness::pk_h(), mall: Malleability::pk_h() } } + pub const fn pk_h() -> Self { Self { corr: Correctness::pk_h(), mall: Malleability::pk_h() } } /// Constructor for the type of the `multi` fragment. pub const fn multi() -> Self { - Type { corr: Correctness::multi(), mall: Malleability::multi() } + Self { corr: Correctness::multi(), mall: Malleability::multi() } } /// Constructor for the type of the `sortedmulti` fragment. pub const fn sortedmulti() -> Self { - Type { corr: Correctness::sortedmulti(), mall: Malleability::sortedmulti() } + Self { corr: Correctness::sortedmulti(), mall: Malleability::sortedmulti() } } /// Constructor for the type of the `multi_a` fragment. pub const fn multi_a() -> Self { - Type { corr: Correctness::multi_a(), mall: Malleability::multi_a() } + Self { corr: Correctness::multi_a(), mall: Malleability::multi_a() } } /// Constructor for the type of the `sortednmulti_a` fragment. pub const fn sortedmulti_a() -> Self { - Type { corr: Correctness::sortedmulti_a(), mall: Malleability::sortedmulti_a() } + Self { corr: Correctness::sortedmulti_a(), mall: Malleability::sortedmulti_a() } } /// Constructor for the type of all the hash fragments. - pub const fn hash() -> Self { Type { corr: Correctness::hash(), mall: Malleability::hash() } } + pub const fn hash() -> Self { Self { corr: Correctness::hash(), mall: Malleability::hash() } } /// Constructor for the type of the `after` and `older` fragments. - pub const fn time() -> Self { Type { corr: Correctness::time(), mall: Malleability::time() } } + pub const fn time() -> Self { Self { corr: Correctness::time(), mall: Malleability::time() } } /// Constructor for the type of the `a:` fragment. pub const fn cast_alt(self) -> Result { // FIXME need to do manual `?` because ? is not supported in constfns. (Also below.) - Ok(Type { + Ok(Self { corr: match Correctness::cast_alt(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -264,7 +264,7 @@ impl Type { /// Constructor for the type of the `s:` fragment. pub const fn cast_swap(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_swap(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -275,7 +275,7 @@ impl Type { /// Constructor for the type of the `c:` fragment. pub const fn cast_check(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_check(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -286,7 +286,7 @@ impl Type { /// Constructor for the type of the `d:` fragment. pub const fn cast_dupif(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_dupif(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -297,7 +297,7 @@ impl Type { /// Constructor for the type of the `v:` fragment. pub const fn cast_verify(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_verify(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -308,7 +308,7 @@ impl Type { /// Constructor for the type of the `j:` fragment. pub const fn cast_nonzero(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_nonzero(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -319,7 +319,7 @@ impl Type { /// Constructor for the type of the `n:` fragment. pub const fn cast_zeronotequal(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_zeronotequal(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -330,7 +330,7 @@ impl Type { /// Constructor for the type of the `t:` fragment. pub const fn cast_true(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_true(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -341,7 +341,7 @@ impl Type { /// Constructor for the type of the `u:` fragment. pub const fn cast_unlikely(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_or_i_false(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -352,7 +352,7 @@ impl Type { /// Constructor for the type of the `l:` fragment. pub const fn cast_likely(self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::cast_or_i_false(self.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -363,7 +363,7 @@ impl Type { /// Constructor for the type of the `and_b` fragment. pub const fn and_b(left: Self, right: Self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::and_b(left.corr, right.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -374,7 +374,7 @@ impl Type { /// Constructor for the type of the `and_v` fragment. pub const fn and_v(left: Self, right: Self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::and_v(left.corr, right.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -385,7 +385,7 @@ impl Type { /// Constructor for the type of the `or_b` fragment. pub const fn or_b(left: Self, right: Self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::or_b(left.corr, right.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -396,7 +396,7 @@ impl Type { /// Constructor for the type of the `or_b` fragment. pub const fn or_d(left: Self, right: Self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::or_d(left.corr, right.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -407,7 +407,7 @@ impl Type { /// Constructor for the type of the `or_c` fragment. pub const fn or_c(left: Self, right: Self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::or_c(left.corr, right.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -418,7 +418,7 @@ impl Type { /// Constructor for the type of the `or_i` fragment. pub const fn or_i(left: Self, right: Self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::or_i(left.corr, right.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -429,7 +429,7 @@ impl Type { /// Constructor for the type of the `and_or` fragment. pub const fn and_or(a: Self, b: Self, c: Self) -> Result { - Ok(Type { + Ok(Self { corr: match Correctness::and_or(a.corr, b.corr, c.corr) { Ok(x) => x, Err(e) => return Err(e), @@ -444,7 +444,7 @@ impl Type { where I: Clone + ExactSizeIterator, { - Ok(Type { + Ok(Self { corr: Correctness::threshold(k, subs.clone().map(|s| &s.corr))?, mall: Malleability::threshold(k, subs.map(|s| &s.mall)), }) diff --git a/src/plan.rs b/src/plan.rs index f1f57b10e..06d186046 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -433,7 +433,7 @@ pub struct CanSign { } impl Default for CanSign { - fn default() -> Self { CanSign { ecdsa: true, taproot: TaprootCanSign::default() } } + fn default() -> Self { Self { ecdsa: true, taproot: TaprootCanSign::default() } } } #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -460,7 +460,7 @@ impl TaprootCanSign { impl Default for TaprootCanSign { fn default() -> Self { - TaprootCanSign { + Self { key_spend: true, script_spend: TaprootAvailableLeaves::Any, sighash_default: true, @@ -640,7 +640,7 @@ impl FromIterator for Assets { keys.insert(((pk.master_fingerprint(), deriv_path), CanSign::default())); } } - Assets { keys, ..Default::default() } + Self { keys, ..Default::default() } } } diff --git a/src/policy/compiler.rs b/src/policy/compiler.rs index 24b0f0ae1..5e2f48ebc 100644 --- a/src/policy/compiler.rs +++ b/src/policy/compiler.rs @@ -29,10 +29,10 @@ impl Eq for OrdF64 {} // We could derive PartialOrd, but we can't derive Ord, and clippy wants us // to derive both or neither. Better to be explicit. impl PartialOrd for OrdF64 { - fn partial_cmp(&self, other: &OrdF64) -> Option { Some(self.cmp(other)) } + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for OrdF64 { - fn cmp(&self, other: &OrdF64) -> cmp::Ordering { + fn cmp(&self, other: &Self) -> cmp::Ordering { // will panic if given NaN self.0.partial_cmp(&other.0).unwrap() } @@ -76,28 +76,28 @@ pub enum CompilerError { impl fmt::Display for CompilerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - CompilerError::NonBinaryArgAnd => { + Self::NonBinaryArgAnd => { f.write_str("And policy fragment must take 2 arguments") } - CompilerError::NonBinaryArgOr => { + Self::NonBinaryArgOr => { f.write_str("Or policy fragment must take 2 arguments") } - CompilerError::TopLevelNonSafe => { + Self::TopLevelNonSafe => { f.write_str("Top Level script is not safe on some spendpath") } - CompilerError::ImpossibleNonMalleableCompilation => { + Self::ImpossibleNonMalleableCompilation => { f.write_str("The compiler could not find any non-malleable compilation") } - CompilerError::LimitsExceeded => f.write_str( + Self::LimitsExceeded => f.write_str( "At least one spending path has exceeded the standardness or consensus limits", ), - CompilerError::NoInternalKey => { + Self::NoInternalKey => { f.write_str("Taproot compilation had no internal key available") } - CompilerError::TooManyTapleaves { n, max } => { + Self::TooManyTapleaves { n, max } => { write!(f, "Policy had too many Tapleaves (found {}, maximum {})", n, max) } - CompilerError::IfFragmentInNativeLeaf { leaf_index } => { + Self::IfFragmentInNativeLeaf { leaf_index } => { write!( f, "native Taproot compilation produced a leaf with OP_IF/NOTIF at leaf index {}; \ @@ -105,7 +105,7 @@ impl fmt::Display for CompilerError { leaf_index ) } - CompilerError::PolicyError(ref e) => fmt::Display::fmt(e, f), + Self::PolicyError(ref e) => fmt::Display::fmt(e, f), } } } @@ -131,7 +131,7 @@ impl error::Error for CompilerError { #[doc(hidden)] impl From for CompilerError { - fn from(e: policy::concrete::PolicyError) -> CompilerError { CompilerError::PolicyError(e) } + fn from(e: policy::concrete::PolicyError) -> Self { Self::PolicyError(e) } } /// Hash required for using OrdF64 as key for hashmap @@ -169,8 +169,8 @@ impl CompilationKey { } /// Helper to create compilation key from components - fn from_type(ty: Type, expensive_verify: bool, dissat_prob: Option) -> CompilationKey { - CompilationKey { ty, expensive_verify, dissat_prob: dissat_prob.map(OrdF64) } + fn from_type(ty: Type, expensive_verify: bool, dissat_prob: Option) -> Self { + Self { ty, expensive_verify, dissat_prob: dissat_prob.map(OrdF64) } } } @@ -190,13 +190,13 @@ struct CompilerExtData { } impl CompilerExtData { - const TRUE: Self = CompilerExtData { branch_prob: None, sat_cost: 0.0, dissat_cost: None }; + const TRUE: Self = Self { branch_prob: None, sat_cost: 0.0, dissat_cost: None }; const FALSE: Self = - CompilerExtData { branch_prob: None, sat_cost: f64::MAX, dissat_cost: Some(0.0) }; + Self { branch_prob: None, sat_cost: f64::MAX, dissat_cost: Some(0.0) }; fn pk_k() -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: match Ctx::sig_type() { SigType::Ecdsa => 73.0, @@ -207,7 +207,7 @@ impl CompilerExtData { } fn pk_h() -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: match Ctx::sig_type() { SigType::Ecdsa => 73.0 + 34.0, @@ -223,7 +223,7 @@ impl CompilerExtData { } fn multi(k: usize, _n: usize) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: 1.0 + 73.0 * k as f64, dissat_cost: Some(1.0 * (k + 1) as f64), @@ -231,7 +231,7 @@ impl CompilerExtData { } fn sortedmulti(k: usize, _n: usize) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: 1.0 + 73.0 * k as f64, dissat_cost: Some(1.0 * (k + 1) as f64), @@ -239,7 +239,7 @@ impl CompilerExtData { } fn multi_a(k: usize, n: usize) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: 66.0 * k as f64 + (n - k) as f64, dissat_cost: Some(n as f64), /* ... := 0x00 ... 0x00 (n times) */ @@ -249,13 +249,13 @@ impl CompilerExtData { fn sortedmulti_a(k: usize, n: usize) -> Self { Self::multi_a(k, n) } fn hash() -> Self { - CompilerExtData { branch_prob: None, sat_cost: 33.0, dissat_cost: Some(33.0) } + Self { branch_prob: None, sat_cost: 33.0, dissat_cost: Some(33.0) } } - fn time() -> Self { CompilerExtData { branch_prob: None, sat_cost: 0.0, dissat_cost: None } } + fn time() -> Self { Self { branch_prob: None, sat_cost: 0.0, dissat_cost: None } } fn cast_alt(self) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: self.dissat_cost, @@ -263,7 +263,7 @@ impl CompilerExtData { } fn cast_swap(self) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: self.dissat_cost, @@ -271,7 +271,7 @@ impl CompilerExtData { } fn cast_check(self) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: self.dissat_cost, @@ -279,19 +279,19 @@ impl CompilerExtData { } fn cast_dupif(self) -> Self { - CompilerExtData { branch_prob: None, sat_cost: 2.0 + self.sat_cost, dissat_cost: Some(1.0) } + Self { branch_prob: None, sat_cost: 2.0 + self.sat_cost, dissat_cost: Some(1.0) } } fn cast_verify(self) -> Self { - CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: None } + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: None } } fn cast_nonzero(self) -> Self { - CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: Some(1.0) } + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: Some(1.0) } } fn cast_zeronotequal(self) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: self.dissat_cost, @@ -299,19 +299,19 @@ impl CompilerExtData { } fn cast_true(self) -> Self { - CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: None } + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: None } } fn cast_unlikely(self) -> Self { - CompilerExtData { branch_prob: None, sat_cost: 2.0 + self.sat_cost, dissat_cost: Some(1.0) } + Self { branch_prob: None, sat_cost: 2.0 + self.sat_cost, dissat_cost: Some(1.0) } } fn cast_likely(self) -> Self { - CompilerExtData { branch_prob: None, sat_cost: 1.0 + self.sat_cost, dissat_cost: Some(2.0) } + Self { branch_prob: None, sat_cost: 1.0 + self.sat_cost, dissat_cost: Some(2.0) } } fn and_b(left: Self, right: Self) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: left.sat_cost + right.sat_cost, dissat_cost: match (left.dissat_cost, right.dissat_cost) { @@ -322,7 +322,7 @@ impl CompilerExtData { } fn and_v(left: Self, right: Self) -> Self { - CompilerExtData { + Self { branch_prob: None, sat_cost: left.sat_cost + right.sat_cost, dissat_cost: None, @@ -336,7 +336,7 @@ impl CompilerExtData { let rprob = r .branch_prob .expect("BUG: right branch prob must be set for disjunctions"); - CompilerExtData { + Self { branch_prob: None, sat_cost: lprob * (l.sat_cost + r.dissat_cost.unwrap()) + rprob * (r.sat_cost + l.dissat_cost.unwrap()), @@ -351,7 +351,7 @@ impl CompilerExtData { let rprob = r .branch_prob .expect("BUG: right branch prob must be set for disjunctions"); - CompilerExtData { + Self { branch_prob: None, sat_cost: lprob * l.sat_cost + rprob * (r.sat_cost + l.dissat_cost.unwrap()), dissat_cost: r.dissat_cost.map(|rd| l.dissat_cost.unwrap() + rd), @@ -365,7 +365,7 @@ impl CompilerExtData { let rprob = r .branch_prob .expect("BUG: right branch prob must be set for disjunctions"); - CompilerExtData { + Self { branch_prob: None, sat_cost: lprob * l.sat_cost + rprob * (r.sat_cost + l.dissat_cost.unwrap()), dissat_cost: None, @@ -380,7 +380,7 @@ impl CompilerExtData { let rprob = r .branch_prob .expect("BUG: right branch prob must be set for disjunctions"); - CompilerExtData { + Self { branch_prob: None, sat_cost: lprob * (2.0 + l.sat_cost) + rprob * (1.0 + r.sat_cost), dissat_cost: if let (Some(ldis), Some(rdis)) = (l.dissat_cost, r.dissat_cost) { @@ -408,7 +408,7 @@ impl CompilerExtData { .dissat_cost .expect("BUG: and_or first arg(a) must be dissatisfiable"); debug_assert_eq!(aprob, bprob); //A and B must have same branch prob. - CompilerExtData { + Self { branch_prob: None, sat_cost: aprob * (a.sat_cost + b.sat_cost) + cprob * (adis + c.sat_cost), dissat_cost: c.dissat_cost.map(|cdis| adis + cdis), @@ -427,7 +427,7 @@ impl CompilerExtData { sat_cost += sub.sat_cost; dissat_cost += sub.dissat_cost.unwrap(); } - CompilerExtData { + Self { branch_prob: None, sat_cost: sat_cost * k_over_n + dissat_cost * (1.0 - k_over_n), dissat_cost: Some(dissat_cost), @@ -558,15 +558,15 @@ impl AstElemExt { } impl AstElemExt { - fn terminal(ms: Miniscript) -> AstElemExt { - AstElemExt { comp_ext_data: CompilerExtData::type_check(ms.as_inner()), ms: Arc::new(ms) } + fn terminal(ms: Miniscript) -> Self { + Self { comp_ext_data: CompilerExtData::type_check(ms.as_inner()), ms: Arc::new(ms) } } fn binary( ast: Terminal, - l: &AstElemExt, - r: &AstElemExt, - ) -> Result, types::Error> { + l: &Self, + r: &Self, + ) -> Result { let lookup_ext = |n| match n { 0 => l.comp_ext_data, 1 => r.comp_ext_data, @@ -577,7 +577,7 @@ impl AstElemExt { let ty = types::Type::type_check(&ast)?; let ext = types::ExtData::type_check(&ast); let comp_ext_data = CompilerExtData::type_check_with_child(&ast, lookup_ext); - Ok(AstElemExt { + Ok(Self { ms: Arc::new(Miniscript::from_components_unchecked(ast, ty, ext)), comp_ext_data, }) @@ -585,10 +585,10 @@ impl AstElemExt { fn ternary( ast: Terminal, - a: &AstElemExt, - b: &AstElemExt, - c: &AstElemExt, - ) -> Result, types::Error> { + a: &Self, + b: &Self, + c: &Self, + ) -> Result { let lookup_ext = |n| match n { 0 => a.comp_ext_data, 1 => b.comp_ext_data, @@ -600,7 +600,7 @@ impl AstElemExt { let ty = types::Type::type_check(&ast)?; let ext = types::ExtData::type_check(&ast); let comp_ext_data = CompilerExtData::type_check_with_child(&ast, lookup_ext); - Ok(AstElemExt { + Ok(Self { ms: Arc::new(Miniscript::from_components_unchecked(ast, ty, ext)), comp_ext_data, }) diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 34873e548..8a197fb1e 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -62,12 +62,12 @@ pub enum Policy { /// A HASH160 whose preimage must be provided to satisfy the descriptor. Hash160(Pk::Hash160), /// A list of sub-policies, all of which must be satisfied. - And(Vec>>), + And(Vec>), /// A list of sub-policies, one of which must be satisfied, along with /// relative probabilities for each one. - Or(Vec<(usize, Arc>)>), + Or(Vec<(usize, Arc)>), /// A set of descriptors, satisfactions must be provided for `k` of them. - Thresh(Threshold>, 0>), + Thresh(Threshold, 0>), } /// Detailed error type for concrete policies. @@ -97,10 +97,10 @@ pub enum DescriptorCtx { impl fmt::Display for PolicyError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - PolicyError::HeightTimelockCombination => { + Self::HeightTimelockCombination => { f.write_str("Cannot lift policies that have a heightlock and timelock combination") } - PolicyError::DuplicatePubKeys => f.write_str("Policy contains duplicate keys"), + Self::DuplicatePubKeys => f.write_str("Policy contains duplicate keys"), } } } @@ -154,10 +154,10 @@ impl Policy { fn check_binary_ops(&self) -> Result<(), CompilerError> { for policy in self.pre_order_iter() { match *policy { - Policy::And(ref subs) if subs.len() != 2 => { + Self::And(ref subs) if subs.len() != 2 => { return Err(CompilerError::NonBinaryArgAnd); } - Policy::Or(ref subs) if subs.len() != 2 => { + Self::Or(ref subs) if subs.len() != 2 => { return Err(CompilerError::NonBinaryArgOr); } _ => {} @@ -195,11 +195,11 @@ impl Policy { /// Extracts the internal_key from this policy tree. #[cfg(feature = "compiler")] - fn extract_key(self, unspendable_key: Option) -> Result<(Pk, Policy), CompilerError> { + fn extract_key(self, unspendable_key: Option) -> Result<(Pk, Self), CompilerError> { let internal_key = self .tapleaf_probability_iter() .filter_map(|(prob, ref pol)| match pol { - Policy::Key(pk) => Some((OrdF64(prob), pk)), + Self::Key(pk) => Some((OrdF64(prob), pk)), _ => None, }) .max_by_key(|(prob, _)| *prob) @@ -242,12 +242,12 @@ impl Policy { let tree = Descriptor::new_tr( internal_key, match policy { - Policy::Trivial => None, + Self::Trivial => None, policy => { let mut leaf_compilations: Vec<(OrdF64, Miniscript)> = vec![]; for (prob, pol) in policy.tapleaf_probability_iter() { // policy corresponding to the key (replaced by unsatisfiable) is skipped - if *pol == Policy::Unsatisfiable { + if *pol == Self::Unsatisfiable { continue; } let compilation = compiler::best_compilation::(pol)?; @@ -298,7 +298,7 @@ impl Policy { _ => { let (internal_key, policy) = self.clone().extract_key(unspendable_key)?; let tap_tree = match policy { - Policy::Trivial => None, + Self::Trivial => None, policy => { let leaves = policy.enumerate_leaves(1.0, max_leaves, Self::enumerate_pol_native); @@ -308,7 +308,7 @@ impl Policy { } let mut leaf_compilations: Vec<(OrdF64, Miniscript)> = vec![]; for (leaf_idx, (prob, pol)) in leaves.iter().enumerate() { - if **pol == Policy::Unsatisfiable { + if **pol == Self::Unsatisfiable { continue; } let compilation = compiler::best_compilation::(pol.as_ref())?; @@ -369,12 +369,12 @@ impl Policy { let tree = Descriptor::new_tr( internal_key, match policy { - Policy::Trivial => None, + Self::Trivial => None, policy => { let leaf_compilations: Vec<_> = policy .enumerate_policy_tree(1.0) .into_iter() - .filter(|x| x.1 != Arc::new(Policy::Unsatisfiable)) + .filter(|x| x.1 != Arc::new(Self::Unsatisfiable)) .map(|(prob, pol)| { ( OrdF64(prob), @@ -459,20 +459,20 @@ impl Policy { #[cfg(feature = "compiler")] fn enumerate_pol(&self, prob: f64) -> Vec<(f64, Arc)> { match self { - Policy::Or(subs) => { + Self::Or(subs) => { let total_odds = subs.iter().fold(0, |acc, x| acc + x.0); subs.iter() .map(|(odds, pol)| (prob * *odds as f64 / total_odds as f64, pol.clone())) .collect::>() } - Policy::Thresh(ref thresh) if thresh.is_or() => { + Self::Thresh(ref thresh) if thresh.is_or() => { let total_odds = thresh.n(); thresh .iter() .map(|pol| (prob / total_odds as f64, pol.clone())) .collect::>() } - Policy::Thresh(ref thresh) if !thresh.is_and() => generate_combination(thresh, prob), + Self::Thresh(ref thresh) if !thresh.is_and() => generate_combination(thresh, prob), pol => vec![(prob, Arc::new(pol.clone()))], } } @@ -484,21 +484,21 @@ impl Policy { #[cfg(feature = "compiler")] fn enumerate_pol_native(&self, prob: f64) -> Vec<(f64, Arc)> { match self { - Policy::Or(subs) => { + Self::Or(subs) => { let total_odds = subs.iter().fold(0, |acc, x| acc + x.0); subs.iter() .map(|(odds, pol)| (prob * *odds as f64 / total_odds as f64, pol.clone())) .collect::>() } - Policy::Thresh(ref thresh) if thresh.is_or() => { + Self::Thresh(ref thresh) if thresh.is_or() => { let total_odds = thresh.n(); thresh .iter() .map(|pol| (prob / total_odds as f64, pol.clone())) .collect::>() } - Policy::Thresh(ref thresh) if !thresh.is_and() => generate_combination(thresh, prob), - Policy::And(subs) => { + Self::Thresh(ref thresh) if !thresh.is_and() => generate_combination(thresh, prob), + Self::And(subs) => { for (i, sub) in subs.iter().enumerate() { let child_expanded = sub.enumerate_pol_native(1.0); if child_expanded.len() > 1 { @@ -513,7 +513,7 @@ impl Policy { .map(|(child_prob, child_pol)| { let mut new_subs = other.clone(); new_subs.insert(i, child_pol); - (prob * child_prob, Arc::new(Policy::And(new_subs))) + (prob * child_prob, Arc::new(Self::And(new_subs))) }) .collect(); } @@ -572,7 +572,7 @@ impl Policy { 'outer: loop { //--- FIND a plausible node --- let mut prob: Reverse = Reverse(OrdF64(0.0)); - let mut curr_policy: Arc = Arc::new(Policy::Unsatisfiable); + let mut curr_policy: Arc = Arc::new(Self::Unsatisfiable); let mut curr_pol_replace_vec: Vec<(f64, Arc)> = vec![]; let mut no_more_enum = false; @@ -648,7 +648,7 @@ impl Policy { impl ForEachKey for Policy { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { self.pre_order_iter().all(|policy| match policy { - Policy::Key(ref pk) => pred(pk), + Self::Key(ref pk) => pred(pk), _ => true, }) } @@ -692,13 +692,13 @@ impl Policy { } /// Translates `Concrete::Key(key)` to `Concrete::Unsatisfiable` when extracting `TapKey`. - pub fn translate_unsatisfiable_pk(self, key: &Pk) -> Policy { + pub fn translate_unsatisfiable_pk(self, key: &Pk) -> Self { use Policy::*; let mut translated = vec![]; for data in Arc::new(self).rtl_post_order_iter() { let new_policy = match data.node.as_ref() { - Policy::Key(ref k) if k.clone() == *key => Some(Policy::Unsatisfiable), + Self::Key(ref k) if k.clone() == *key => Some(Self::Unsatisfiable), And(ref subs) => { Some(And((0..subs.len()).map(|_| translated.pop().unwrap()).collect())) } @@ -724,7 +724,7 @@ impl Policy { pub fn keys(&self) -> Vec<&Pk> { self.pre_order_iter() .filter_map(|policy| match policy { - Policy::Key(ref pk) => Some(pk), + Self::Key(ref pk) => Some(pk), _ => None, }) .collect() @@ -786,14 +786,14 @@ impl Policy { let mut infos = vec![]; for data in self.rtl_post_order_iter() { let info = match data.node { - Policy::After(ref t) => TimelockInfo { + Self::After(ref t) => TimelockInfo { csv_with_height: false, csv_with_time: false, cltv_with_height: absolute::LockTime::from(*t).is_block_height(), cltv_with_time: absolute::LockTime::from(*t).is_block_time(), contains_combination: false, }, - Policy::Older(ref t) => TimelockInfo { + Self::Older(ref t) => TimelockInfo { csv_with_height: t.is_height_locked(), csv_with_time: t.is_time_locked(), cltv_with_height: false, @@ -883,16 +883,16 @@ impl Policy { impl fmt::Debug for Policy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Policy::Unsatisfiable => f.write_str("UNSATISFIABLE()"), - Policy::Trivial => f.write_str("TRIVIAL()"), - Policy::Key(ref pk) => write!(f, "pk({:?})", pk), - Policy::After(n) => write!(f, "after({})", n), - Policy::Older(n) => write!(f, "older({})", n), - Policy::Sha256(ref h) => write!(f, "sha256({})", h), - Policy::Hash256(ref h) => write!(f, "hash256({})", h), - Policy::Ripemd160(ref h) => write!(f, "ripemd160({})", h), - Policy::Hash160(ref h) => write!(f, "hash160({})", h), - Policy::And(ref subs) => { + Self::Unsatisfiable => f.write_str("UNSATISFIABLE()"), + Self::Trivial => f.write_str("TRIVIAL()"), + Self::Key(ref pk) => write!(f, "pk({:?})", pk), + Self::After(n) => write!(f, "after({})", n), + Self::Older(n) => write!(f, "older({})", n), + Self::Sha256(ref h) => write!(f, "sha256({})", h), + Self::Hash256(ref h) => write!(f, "hash256({})", h), + Self::Ripemd160(ref h) => write!(f, "ripemd160({})", h), + Self::Hash160(ref h) => write!(f, "hash160({})", h), + Self::And(ref subs) => { f.write_str("and(")?; if !subs.is_empty() { write!(f, "{:?}", subs[0])?; @@ -902,7 +902,7 @@ impl fmt::Debug for Policy { } f.write_str(")") } - Policy::Or(ref subs) => { + Self::Or(ref subs) => { f.write_str("or(")?; if !subs.is_empty() { write!(f, "{}@{:?}", subs[0].0, subs[0].1)?; @@ -912,7 +912,7 @@ impl fmt::Debug for Policy { } f.write_str(")") } - Policy::Thresh(ref thresh) => fmt::Debug::fmt(&thresh.debug("thresh", true), f), + Self::Thresh(ref thresh) => fmt::Debug::fmt(&thresh.debug("thresh", true), f), } } } @@ -920,16 +920,16 @@ impl fmt::Debug for Policy { impl fmt::Display for Policy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Policy::Unsatisfiable => f.write_str("UNSATISFIABLE"), - Policy::Trivial => f.write_str("TRIVIAL"), - Policy::Key(ref pk) => write!(f, "pk({})", pk), - Policy::After(n) => write!(f, "after({})", n), - Policy::Older(n) => write!(f, "older({})", n), - Policy::Sha256(ref h) => write!(f, "sha256({})", h), - Policy::Hash256(ref h) => write!(f, "hash256({})", h), - Policy::Ripemd160(ref h) => write!(f, "ripemd160({})", h), - Policy::Hash160(ref h) => write!(f, "hash160({})", h), - Policy::And(ref subs) => { + Self::Unsatisfiable => f.write_str("UNSATISFIABLE"), + Self::Trivial => f.write_str("TRIVIAL"), + Self::Key(ref pk) => write!(f, "pk({})", pk), + Self::After(n) => write!(f, "after({})", n), + Self::Older(n) => write!(f, "older({})", n), + Self::Sha256(ref h) => write!(f, "sha256({})", h), + Self::Hash256(ref h) => write!(f, "hash256({})", h), + Self::Ripemd160(ref h) => write!(f, "ripemd160({})", h), + Self::Hash160(ref h) => write!(f, "hash160({})", h), + Self::And(ref subs) => { f.write_str("and(")?; if !subs.is_empty() { write!(f, "{}", subs[0])?; @@ -939,7 +939,7 @@ impl fmt::Display for Policy { } f.write_str(")") } - Policy::Or(ref subs) => { + Self::Or(ref subs) => { f.write_str("or(")?; if !subs.is_empty() { write!(f, "{}@{}", subs[0].0, subs[0].1)?; @@ -949,16 +949,16 @@ impl fmt::Display for Policy { } f.write_str(")") } - Policy::Thresh(ref thresh) => fmt::Display::fmt(&thresh.display("thresh", true), f), + Self::Thresh(ref thresh) => fmt::Display::fmt(&thresh.display("thresh", true), f), } } } impl str::FromStr for Policy { type Err = Error; - fn from_str(s: &str) -> Result, Error> { + fn from_str(s: &str) -> Result { let tree = expression::Tree::from_str(s)?; - let policy: Policy = FromTree::from_tree(tree.root())?; + let policy: Self = FromTree::from_tree(tree.root())?; policy.check_timelocks().map_err(Error::ConcretePolicy)?; Ok(policy) } @@ -967,7 +967,7 @@ impl str::FromStr for Policy { serde_string_impl_pk!(Policy, "a miniscript concrete policy"); impl expression::FromTree for Policy { - fn from_tree(root: expression::TreeIterItem) -> Result, Error> { + fn from_tree(root: expression::TreeIterItem) -> Result { root.verify_no_curly_braces() .map_err(From::from) .map_err(Error::Parse)?; @@ -1017,13 +1017,13 @@ impl expression::FromTree for Policy { node.verify_n_children("UNSATISFIABLE", 0..=0) .map_err(From::from) .map_err(Error::Parse)?; - Ok(Policy::Unsatisfiable) + Ok(Self::Unsatisfiable) } "TRIVIAL" => { node.verify_n_children("TRIVIAL", 0..=0) .map_err(From::from) .map_err(Error::Parse)?; - Ok(Policy::Trivial) + Ok(Self::Trivial) } "pk" => node .verify_terminal_parent("pk", "public key") @@ -1051,13 +1051,13 @@ impl expression::FromTree for Policy { node.verify_n_children("and", 2..=2) .map_err(From::from) .map_err(Error::Parse)?; - Ok(Policy::And(vec![stack.pop().unwrap().1, stack.pop().unwrap().1])) + Ok(Self::And(vec![stack.pop().unwrap().1, stack.pop().unwrap().1])) } "or" => { node.verify_n_children("or", 2..=2) .map_err(From::from) .map_err(Error::Parse)?; - Ok(Policy::Or(vec![stack.pop().unwrap(), stack.pop().unwrap()])) + Ok(Self::Or(vec![stack.pop().unwrap(), stack.pop().unwrap()])) } "thresh" => node .verify_threshold(|_| Ok(stack.pop().unwrap().1)) diff --git a/src/policy/mod.rs b/src/policy/mod.rs index 073c3aa40..7447356be 100644 --- a/src/policy/mod.rs +++ b/src/policy/mod.rs @@ -66,13 +66,13 @@ pub enum LiftError { impl fmt::Display for LiftError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - LiftError::HeightTimelockCombination => { + Self::HeightTimelockCombination => { f.write_str("Cannot lift policies that have a heightlock and timelock combination") } - LiftError::BranchExceedResourceLimits => f.write_str( + Self::BranchExceedResourceLimits => f.write_str( "Cannot lift policies containing one branch that exceeds resource limits", ), - LiftError::RawDescriptorLift => f.write_str("Cannot lift raw descriptors"), + Self::RawDescriptorLift => f.write_str("Cannot lift raw descriptors"), } } } @@ -180,18 +180,18 @@ impl Liftable for Miniscript impl Liftable for Descriptor { fn lift(&self) -> Result, Error> { match *self { - Descriptor::Bare(ref bare) => bare.lift(), - Descriptor::Pkh(ref pkh) => pkh.lift(), - Descriptor::Wpkh(ref wpkh) => wpkh.lift(), - Descriptor::Wsh(ref wsh) => wsh.lift(), - Descriptor::Sh(ref sh) => sh.lift(), - Descriptor::Tr(ref tr) => tr.lift(), + Self::Bare(ref bare) => bare.lift(), + Self::Pkh(ref pkh) => pkh.lift(), + Self::Wpkh(ref wpkh) => wpkh.lift(), + Self::Wsh(ref wsh) => wsh.lift(), + Self::Sh(ref sh) => sh.lift(), + Self::Tr(ref tr) => tr.lift(), } } } impl Liftable for Semantic { - fn lift(&self) -> Result, Error> { Ok(self.clone()) } + fn lift(&self) -> Result { Ok(self.clone()) } } impl Liftable for Concrete { @@ -200,28 +200,28 @@ impl Liftable for Concrete { // involving combination of timelocks and heightlocks self.check_timelocks().map_err(Error::ConcretePolicy)?; let ret = match *self { - Concrete::Unsatisfiable => Semantic::Unsatisfiable, - Concrete::Trivial => Semantic::Trivial, - Concrete::Key(ref pk) => Semantic::Key(pk.clone()), - Concrete::After(t) => Semantic::After(t), - Concrete::Older(t) => Semantic::Older(t), - Concrete::Sha256(ref h) => Semantic::Sha256(h.clone()), - Concrete::Hash256(ref h) => Semantic::Hash256(h.clone()), - Concrete::Ripemd160(ref h) => Semantic::Ripemd160(h.clone()), - Concrete::Hash160(ref h) => Semantic::Hash160(h.clone()), - Concrete::And(ref subs) => { + Self::Unsatisfiable => Semantic::Unsatisfiable, + Self::Trivial => Semantic::Trivial, + Self::Key(ref pk) => Semantic::Key(pk.clone()), + Self::After(t) => Semantic::After(t), + Self::Older(t) => Semantic::Older(t), + Self::Sha256(ref h) => Semantic::Sha256(h.clone()), + Self::Hash256(ref h) => Semantic::Hash256(h.clone()), + Self::Ripemd160(ref h) => Semantic::Ripemd160(h.clone()), + Self::Hash160(ref h) => Semantic::Hash160(h.clone()), + Self::And(ref subs) => { let semantic_subs: Result>, Error> = subs.iter().map(Liftable::lift).collect(); let semantic_subs = semantic_subs?.into_iter().map(Arc::new).collect(); Semantic::Thresh(Threshold::new(2, semantic_subs).unwrap()) } - Concrete::Or(ref subs) => { + Self::Or(ref subs) => { let semantic_subs: Result>, Error> = subs.iter().map(|(_p, sub)| sub.lift()).collect(); let semantic_subs = semantic_subs?.into_iter().map(Arc::new).collect(); Semantic::Thresh(Threshold::new(1, semantic_subs).unwrap()) } - Concrete::Thresh(ref thresh) => { + Self::Thresh(ref thresh) => { Semantic::Thresh(thresh.translate_ref(|sub| Liftable::lift(sub).map(Arc::new))?) } } diff --git a/src/policy/semantic.rs b/src/policy/semantic.rs index 15ba83618..c67459170 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -45,13 +45,13 @@ pub enum Policy { /// A HASH160 whose preimage must be provided to satisfy the descriptor. Hash160(Pk::Hash160), /// A set of descriptors, satisfactions must be provided for `k` of them. - Thresh(Threshold>, 0>), + Thresh(Threshold, 0>), } impl ForEachKey for Policy { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { self.pre_order_iter().all(|policy| match policy { - Policy::Key(ref pk) => pred(pk), + Self::Key(ref pk) => pred(pk), _ => true, }) } @@ -141,15 +141,15 @@ impl Policy { /// be practically computed. // This algorithm has a naive implementation. It is possible to optimize this // by memoizing and maintaining a hashmap. - pub fn entails(self, other: Policy) -> Option { + pub fn entails(self, other: Self) -> Option { if self.n_terminals() > ENTAILMENT_MAX_TERMINALS { return None; } match (self, other) { - (Policy::Unsatisfiable, _) => Some(true), - (Policy::Trivial, Policy::Trivial) => Some(true), - (Policy::Trivial, _) => Some(false), - (_, Policy::Unsatisfiable) => Some(false), + (Self::Unsatisfiable, _) => Some(true), + (Self::Trivial, Self::Trivial) => Some(true), + (Self::Trivial, _) => Some(false), + (_, Self::Unsatisfiable) => Some(false), (a, b) => { let (a_norm, b_norm) = (a.normalized(), b.normalized()); let first_constraint = a_norm.first_constraint(); @@ -161,7 +161,7 @@ impl Policy { a_norm.satisfy_constraint(&first_constraint, false), b_norm.satisfy_constraint(&first_constraint, false), ); - Some(Policy::entails(a1, b1)? && Policy::entails(a2, b2)?) + Some(Self::entails(a1, b1)? && Self::entails(a2, b2)?) } } } @@ -186,10 +186,10 @@ impl Policy { // Helper function to get the first constraint in the policy. // Returns the first leaf policy. Used in policy entailment. // Assumes that the current policy is normalized. - fn first_constraint(&self) -> Policy { + fn first_constraint(&self) -> Self { debug_assert!(self.clone().normalized() == self.clone()); match self { - Policy::Thresh(ref thresh) => thresh.data()[0].first_constraint(), + Self::Thresh(ref thresh) => thresh.data()[0].first_constraint(), first => first.clone(), } } @@ -198,23 +198,23 @@ impl Policy { // to true or false and returning the resultant normalized policy. Witness // is currently encoded as policy. Only accepts leaf fragment and a // normalized policy - pub(crate) fn satisfy_constraint(self, witness: &Policy, available: bool) -> Policy { + pub(crate) fn satisfy_constraint(self, witness: &Self, available: bool) -> Self { debug_assert!(self.clone().normalized() == self); - if let Policy::Thresh { .. } = *witness { + if let Self::Thresh { .. } = *witness { // We can't debug_assert on Policy::Thresh. panic!("should be unreachable") } let ret = match self { - Policy::Thresh(thresh) => Policy::Thresh(thresh.map(|sub| { + Self::Thresh(thresh) => Self::Thresh(thresh.map(|sub| { Arc::new(sub.as_ref().clone().satisfy_constraint(witness, available)) })), ref leaf if leaf == witness => { if available { - Policy::Trivial + Self::Trivial } else { - Policy::Unsatisfiable + Self::Unsatisfiable } } x => x, @@ -226,16 +226,16 @@ impl Policy { impl fmt::Debug for Policy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Policy::Unsatisfiable => f.write_str("UNSATISFIABLE()"), - Policy::Trivial => f.write_str("TRIVIAL()"), - Policy::Key(ref pkh) => write!(f, "pk({:?})", pkh), - Policy::After(n) => write!(f, "after({})", n), - Policy::Older(n) => write!(f, "older({})", n), - Policy::Sha256(ref h) => write!(f, "sha256({})", h), - Policy::Hash256(ref h) => write!(f, "hash256({})", h), - Policy::Ripemd160(ref h) => write!(f, "ripemd160({})", h), - Policy::Hash160(ref h) => write!(f, "hash160({})", h), - Policy::Thresh(ref thresh) => { + Self::Unsatisfiable => f.write_str("UNSATISFIABLE()"), + Self::Trivial => f.write_str("TRIVIAL()"), + Self::Key(ref pkh) => write!(f, "pk({:?})", pkh), + Self::After(n) => write!(f, "after({})", n), + Self::Older(n) => write!(f, "older({})", n), + Self::Sha256(ref h) => write!(f, "sha256({})", h), + Self::Hash256(ref h) => write!(f, "hash256({})", h), + Self::Ripemd160(ref h) => write!(f, "ripemd160({})", h), + Self::Hash160(ref h) => write!(f, "hash160({})", h), + Self::Thresh(ref thresh) => { if thresh.k() == thresh.n() { thresh.debug("and", false).fmt(f) } else if thresh.k() == 1 { @@ -251,16 +251,16 @@ impl fmt::Debug for Policy { impl fmt::Display for Policy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Policy::Unsatisfiable => f.write_str("UNSATISFIABLE"), - Policy::Trivial => f.write_str("TRIVIAL"), - Policy::Key(ref pkh) => write!(f, "pk({})", pkh), - Policy::After(n) => write!(f, "after({})", n), - Policy::Older(n) => write!(f, "older({})", n), - Policy::Sha256(ref h) => write!(f, "sha256({})", h), - Policy::Hash256(ref h) => write!(f, "hash256({})", h), - Policy::Ripemd160(ref h) => write!(f, "ripemd160({})", h), - Policy::Hash160(ref h) => write!(f, "hash160({})", h), - Policy::Thresh(ref thresh) => { + Self::Unsatisfiable => f.write_str("UNSATISFIABLE"), + Self::Trivial => f.write_str("TRIVIAL"), + Self::Key(ref pkh) => write!(f, "pk({})", pkh), + Self::After(n) => write!(f, "after({})", n), + Self::Older(n) => write!(f, "older({})", n), + Self::Sha256(ref h) => write!(f, "sha256({})", h), + Self::Hash256(ref h) => write!(f, "hash256({})", h), + Self::Ripemd160(ref h) => write!(f, "ripemd160({})", h), + Self::Hash160(ref h) => write!(f, "hash160({})", h), + Self::Thresh(ref thresh) => { if thresh.k() == thresh.n() { thresh.display("and", false).fmt(f) } else if thresh.k() == 1 { @@ -275,7 +275,7 @@ impl fmt::Display for Policy { impl str::FromStr for Policy { type Err = Error; - fn from_str(s: &str) -> Result, Error> { + fn from_str(s: &str) -> Result { let tree = expression::Tree::from_str(s)?; expression::FromTree::from_tree(tree.root()) } @@ -284,7 +284,7 @@ impl str::FromStr for Policy { serde_string_impl_pk!(Policy, "a miniscript semantic policy"); impl expression::FromTree for Policy { - fn from_tree(root: expression::TreeIterItem) -> Result, Error> { + fn from_tree(root: expression::TreeIterItem) -> Result { root.verify_no_curly_braces() .map_err(From::from) .map_err(Error::Parse)?; @@ -309,13 +309,13 @@ impl expression::FromTree for Policy { node.verify_n_children("UNSATISFIABLE", 0..=0) .map_err(From::from) .map_err(Error::Parse)?; - Ok(Policy::Unsatisfiable) + Ok(Self::Unsatisfiable) } "TRIVIAL" => { node.verify_n_children("TRIVIAL", 0..=0) .map_err(From::from) .map_err(Error::Parse)?; - Ok(Policy::Trivial) + Ok(Self::Trivial) } "pk" => node .verify_terminal_parent("pk", "public key") @@ -347,7 +347,7 @@ impl expression::FromTree for Policy { let child_iter = (0..node.n_children()).map(|_| stack.pop().unwrap()); let thresh = Threshold::from_iter(node.n_children(), child_iter) .map_err(Error::Threshold)?; - Ok(Policy::Thresh(thresh)) + Ok(Self::Thresh(thresh)) } "or" => { node.verify_n_children("or", 2..) @@ -355,7 +355,7 @@ impl expression::FromTree for Policy { .map_err(Error::Parse)?; let child_iter = (0..node.n_children()).map(|_| stack.pop().unwrap()); let thresh = Threshold::from_iter(1, child_iter).map_err(Error::Threshold)?; - Ok(Policy::Thresh(thresh)) + Ok(Self::Thresh(thresh)) } "thresh" => { let thresh = node.verify_threshold(|_| Ok::<_, Error>(stack.pop().unwrap()))?; @@ -368,7 +368,7 @@ impl expression::FromTree for Policy { return Err(Error::ParseThreshold(crate::ParseThresholdError::IllegalAnd)); } - Ok(Policy::Thresh(thresh)) + Ok(Self::Thresh(thresh)) } x => { Err(Error::Parse(crate::ParseError::Tree(crate::ParseTreeError::UnknownName { @@ -388,9 +388,9 @@ impl expression::FromTree for Policy { impl Policy { /// Flattens out trees of `And`s and `Or`s; eliminate `Trivial` and /// `Unsatisfiable`s. Does not reorder any branches; use `.sort`. - pub fn normalized(self) -> Policy { + pub fn normalized(self) -> Self { match self { - Policy::Thresh(thresh) => { + Self::Thresh(thresh) => { let mut ret_subs = Vec::with_capacity(thresh.n()); let subs: Vec<_> = thresh @@ -399,11 +399,11 @@ impl Policy { .collect(); let trivial_count = subs .iter() - .filter(|&pol| *pol.as_ref() == Policy::Trivial) + .filter(|&pol| *pol.as_ref() == Self::Trivial) .count(); let unsatisfied_count = subs .iter() - .filter(|&pol| *pol.as_ref() == Policy::Unsatisfiable) + .filter(|&pol| *pol.as_ref() == Self::Unsatisfiable) .count(); let n = subs.len() - unsatisfied_count - trivial_count; // remove all true/false @@ -414,12 +414,12 @@ impl Policy { for sub in subs { match sub.as_ref() { - Policy::Trivial | Policy::Unsatisfiable => {} - Policy::Thresh(ref subthresh) => { + Self::Trivial | Self::Unsatisfiable => {} + Self::Thresh(ref subthresh) => { match (is_and, is_or) { (true, true) => { // means m = n = 1, thresh(1,X) type thing. - ret_subs.push(Arc::new(Policy::Thresh(subthresh.clone()))); + ret_subs.push(Arc::new(Self::Thresh(subthresh.clone()))); } (true, false) if subthresh.k() == subthresh.n() => { ret_subs.extend(subthresh.iter().cloned()) @@ -427,7 +427,7 @@ impl Policy { (false, true) if subthresh.k() == 1 => { ret_subs.extend(subthresh.iter().cloned()) } // or case - _ => ret_subs.push(Arc::new(Policy::Thresh(subthresh.clone()))), + _ => ret_subs.push(Arc::new(Self::Thresh(subthresh.clone()))), } } x => ret_subs.push(Arc::new(x.clone())), @@ -435,22 +435,22 @@ impl Policy { } // Now reason about m of n threshold if m == 0 { - Policy::Trivial + Self::Trivial } else if m > ret_subs.len() { - Policy::Unsatisfiable + Self::Unsatisfiable } else if ret_subs.len() == 1 { let policy = ret_subs.pop().unwrap(); // Only one strong reference because we created the Arc when pushing to ret_subs. Arc::try_unwrap(policy).unwrap() } else if is_and { // unwrap ok since ret_subs is nonempty - Policy::Thresh(Threshold::new(ret_subs.len(), ret_subs).unwrap()) + Self::Thresh(Threshold::new(ret_subs.len(), ret_subs).unwrap()) } else if is_or { // unwrap ok since ret_subs is nonempty - Policy::Thresh(Threshold::new(1, ret_subs).unwrap()) + Self::Thresh(Threshold::new(1, ret_subs).unwrap()) } else { // unwrap ok since ret_subs is nonempty and we made sure m <= ret_subs.len - Policy::Thresh(Threshold::new(m, ret_subs).unwrap()) + Self::Thresh(Threshold::new(m, ret_subs).unwrap()) } } x => x, @@ -462,20 +462,20 @@ impl Policy { /// Only checks whether the policy is `Policy::Trivial`, to check if the /// normalized form is trivial, the caller is expected to normalize the /// policy first. - pub fn is_trivial(&self) -> bool { matches!(*self, Policy::Trivial) } + pub fn is_trivial(&self) -> bool { matches!(*self, Self::Trivial) } /// Detects a false/unsatisfiable policy. /// /// Only checks whether the policy is `Policy::Unsatisfiable`, to check if /// the normalized form is unsatisfiable, the caller is expected to /// normalize the policy first. - pub fn is_unsatisfiable(&self) -> bool { matches!(*self, Policy::Unsatisfiable) } + pub fn is_unsatisfiable(&self) -> bool { matches!(*self, Self::Unsatisfiable) } /// Helper function to do the recursion in `timelocks`. fn real_relative_timelocks(&self) -> Vec { self.pre_order_iter() .filter_map(|policy| match policy { - Policy::Older(t) => Some(t.to_consensus_u32()), + Self::Older(t) => Some(t.to_consensus_u32()), _ => None, }) .collect() @@ -494,7 +494,7 @@ impl Policy { fn real_absolute_timelocks(&self) -> Vec { self.pre_order_iter() .filter_map(|policy| match policy { - Policy::After(t) => Some(t.to_consensus_u32()), + Self::After(t) => Some(t.to_consensus_u32()), _ => None, }) .collect() @@ -511,7 +511,7 @@ impl Policy { /// Filters a policy by eliminating relative timelock constraints /// that are not satisfied at the given `age`. - pub fn at_age(self, age: relative::LockTime) -> Policy { + pub fn at_age(self, age: relative::LockTime) -> Self { use Policy::*; let mut at_age = vec![]; @@ -541,7 +541,7 @@ impl Policy { /// Filters a policy by eliminating absolute timelock constraints /// that are not satisfied at the given `n` (`n OP_CHECKLOCKTIMEVERIFY`). - pub fn at_lock_time(self, n: absolute::LockTime) -> Policy { + pub fn at_lock_time(self, n: absolute::LockTime) -> Self { use Policy::*; let mut at_age = vec![]; @@ -573,7 +573,7 @@ impl Policy { /// Duplicate keys will be double-counted. pub fn n_keys(&self) -> usize { self.pre_order_iter() - .filter(|policy| matches!(policy, Policy::Key(..))) + .filter(|policy| matches!(policy, Self::Key(..))) .count() } @@ -619,7 +619,7 @@ impl Policy { /// Does **not** allow policies to be compared for functional equivalence; /// in general this appears to require Gröbner basis techniques that are not /// implemented. - pub fn sorted(self) -> Policy { + pub fn sorted(self) -> Self { use Policy::*; let mut sorted = vec![]; diff --git a/src/primitives/absolute_locktime.rs b/src/primitives/absolute_locktime.rs index db4624b3a..eaf177091 100644 --- a/src/primitives/absolute_locktime.rs +++ b/src/primitives/absolute_locktime.rs @@ -50,7 +50,7 @@ impl AbsLockTime { /// Constructs an `AbsLockTime` from an nLockTime value or the argument to `CHEKCLOCKTIMEVERIFY`. pub fn from_consensus(n: u32) -> Result { if n >= MIN_ABSOLUTE_LOCKTIME && n <= MAX_ABSOLUTE_LOCKTIME { - Ok(AbsLockTime(absolute::LockTime::from_consensus(n))) + Ok(Self(absolute::LockTime::from_consensus(n))) } else { Err(AbsLockTimeError { value: n }) } @@ -71,7 +71,7 @@ impl AbsLockTime { } impl From for absolute::LockTime { - fn from(lock_time: AbsLockTime) -> absolute::LockTime { lock_time.0 } + fn from(lock_time: AbsLockTime) -> Self { lock_time.0 } } impl cmp::PartialOrd for AbsLockTime { diff --git a/src/primitives/relative_locktime.rs b/src/primitives/relative_locktime.rs index 34ed6052d..be321d1ac 100644 --- a/src/primitives/relative_locktime.rs +++ b/src/primitives/relative_locktime.rs @@ -36,7 +36,7 @@ pub struct RelLockTime(Sequence); impl RelLockTime { /// The "0 blocks" constant. - pub const ZERO: Self = RelLockTime(Sequence::ZERO); + pub const ZERO: Self = Self(Sequence::ZERO); /// Constructs an `RelLockTime` from an nLockTime value or the argument to `CHEKCLOCKTIMEVERIFY`. pub fn from_consensus(n: u32) -> Result { @@ -53,11 +53,11 @@ impl RelLockTime { } /// Takes a 16-bit number of blocks and produces a relative locktime from it. - pub fn from_height_unchecked(height: u16) -> Self { RelLockTime(Sequence::from_height(height)) } + pub fn from_height_unchecked(height: u16) -> Self { Self(Sequence::from_height(height)) } /// Takes a 16-bit number of 512-second time intervals and produces a relative locktime from it. pub fn from_512_second_intervals(time: u16) -> Self { - RelLockTime(Sequence::from_512_second_intervals(time)) + Self(Sequence::from_512_second_intervals(time)) } /// Whether this timelock is blockheight-based. @@ -71,7 +71,7 @@ impl convert::TryFrom for RelLockTime { type Error = RelLockTimeError; fn try_from(seq: Sequence) -> Result { if seq.is_relative_lock_time() && seq != Sequence::ZERO { - Ok(RelLockTime(seq)) + Ok(Self(seq)) } else { Err(RelLockTimeError { value: seq.to_consensus_u32() }) } @@ -79,11 +79,11 @@ impl convert::TryFrom for RelLockTime { } impl From for Sequence { - fn from(lock_time: RelLockTime) -> Sequence { lock_time.0 } + fn from(lock_time: RelLockTime) -> Self { lock_time.0 } } impl From for relative::LockTime { - fn from(lock_time: RelLockTime) -> relative::LockTime { + fn from(lock_time: RelLockTime) -> Self { lock_time.0.to_relative_lock_time().unwrap() } } diff --git a/src/primitives/threshold.rs b/src/primitives/threshold.rs index 1ec8c30dd..a29f89e30 100644 --- a/src/primitives/threshold.rs +++ b/src/primitives/threshold.rs @@ -66,7 +66,7 @@ impl Threshold { /// Constructs a threshold directly from a threshold value and collection. pub fn new(k: usize, inner: Vec) -> Result { validate_k_n::(k, inner.len())?; - Ok(Threshold { k, inner }) + Ok(Self { k, inner }) } /// Constructs a threshold from a threshold value and an iterator that yields collection @@ -87,13 +87,13 @@ impl Threshold { /// Constructor for an "or" represented as a 1-of-2 threshold. pub fn or(left: T, right: T) -> Self { debug_assert!(MAX == 0 || MAX > 1); - Threshold { k: 1, inner: vec![left, right] } + Self { k: 1, inner: vec![left, right] } } /// Constructor for an "and" represented as a 2-of-2 threshold. pub fn and(left: T, right: T) -> Self { debug_assert!(MAX == 0 || MAX > 1); - Threshold { k: 2, inner: vec![left, right] } + Self { k: 2, inner: vec![left, right] } } /// Whether this threshold is a 1-of-n. @@ -277,7 +277,7 @@ impl Threshold { /// Panics if the passed vector is empty. pub fn or_n(inner: Vec) -> Self { assert_ne!(inner.len(), 0); - Threshold { k: 1, inner } + Self { k: 1, inner } } /// Constructor for an "and" represented as a n-of-n threshold. @@ -287,7 +287,7 @@ impl Threshold { /// Panics if the passed vector is empty. pub fn and_n(inner: Vec) -> Self { assert_ne!(inner.len(), 0); - Threshold { k: inner.len(), inner } + Self { k: inner.len(), inner } } } diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 481b5bbe8..8b7700118 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -57,11 +57,11 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Error::InputError(ref inp_err, index) => write!(f, "{} at index {}", inp_err, index), - Error::WrongInputCount { in_tx, in_map } => { + Self::InputError(ref inp_err, index) => write!(f, "{} at index {}", inp_err, index), + Self::WrongInputCount { in_tx, in_map } => { write!(f, "PSBT had {} inputs in transaction but {} inputs in map", in_tx, in_map) } - Error::InputIdxOutofBounds { psbt_inp, index } => write!( + Self::InputIdxOutofBounds { psbt_inp, index } => write!( f, "psbt input index {} out of bounds: psbt.inputs.len() {}", index, psbt_inp @@ -176,44 +176,44 @@ impl error::Error for InputError { impl fmt::Display for InputError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - InputError::InvalidSignature { ref pubkey, ref sig } => { + Self::InvalidSignature { ref pubkey, ref sig } => { write!(f, "PSBT: bad signature {} for key {:?}", pubkey, sig) } - InputError::KeyErr(ref e) => write!(f, "Key Err: {}", e), - InputError::Interpreter(ref e) => write!(f, "Interpreter: {}", e), - InputError::SecpErr(ref e) => write!(f, "Secp Err: {}", e), - InputError::InvalidRedeemScript { ref redeem, ref p2sh_expected } => write!( + Self::KeyErr(ref e) => write!(f, "Key Err: {}", e), + Self::Interpreter(ref e) => write!(f, "Interpreter: {}", e), + Self::SecpErr(ref e) => write!(f, "Secp Err: {}", e), + Self::InvalidRedeemScript { ref redeem, ref p2sh_expected } => write!( f, "Redeem script {} does not match the p2sh script {}", redeem, p2sh_expected ), - InputError::InvalidWitnessScript { ref witness_script, ref p2wsh_expected } => write!( + Self::InvalidWitnessScript { ref witness_script, ref p2wsh_expected } => write!( f, "Witness script {} does not match the p2wsh script {}", witness_script, p2wsh_expected ), - InputError::MiniscriptError(ref e) => write!(f, "Miniscript Error: {}", e), - InputError::MissingWitness => write!(f, "PSBT is missing witness"), - InputError::MissingRedeemScript => write!(f, "PSBT is Redeem script"), - InputError::MissingUtxo => { + Self::MiniscriptError(ref e) => write!(f, "Miniscript Error: {}", e), + Self::MissingWitness => write!(f, "PSBT is missing witness"), + Self::MissingRedeemScript => write!(f, "PSBT is Redeem script"), + Self::MissingUtxo => { write!(f, "PSBT is missing both witness and non-witness UTXO") } - InputError::MissingWitnessScript => write!(f, "PSBT is missing witness script"), - InputError::MissingPubkey => write!(f, "Missing pubkey for a pkh/wpkh"), - InputError::NonEmptyRedeemScript => { + Self::MissingWitnessScript => write!(f, "PSBT is missing witness script"), + Self::MissingPubkey => write!(f, "Missing pubkey for a pkh/wpkh"), + Self::NonEmptyRedeemScript => { write!(f, "PSBT has non-empty redeem script at for legacy transactions") } - InputError::NonEmptyWitnessScript => { + Self::NonEmptyWitnessScript => { write!(f, "PSBT has non-empty witness script at for legacy input") } - InputError::WrongSighashFlag { required, got, pubkey } => write!( + Self::WrongSighashFlag { required, got, pubkey } => write!( f, "PSBT: signature with key {:?} had \ sighashflag {:?} rather than required {:?}", pubkey, got, required ), - InputError::CouldNotSatisfyTr => write!(f, "Could not satisfy Tr descriptor"), - InputError::NonStandardSighashType(ref e) => { + Self::CouldNotSatisfyTr => write!(f, "Could not satisfy Tr descriptor"), + Self::NonStandardSighashType(ref e) => { write!(f, "Non-standard sighash type {}", e) } } @@ -222,17 +222,17 @@ impl fmt::Display for InputError { #[doc(hidden)] impl From for InputError { - fn from(e: super::Error) -> InputError { InputError::MiniscriptError(e) } + fn from(e: super::Error) -> Self { Self::MiniscriptError(e) } } #[doc(hidden)] impl From for InputError { - fn from(e: bitcoin::secp256k1::Error) -> InputError { InputError::SecpErr(e) } + fn from(e: bitcoin::secp256k1::Error) -> Self { Self::SecpErr(e) } } #[doc(hidden)] impl From for InputError { - fn from(e: bitcoin::key::FromSliceError) -> InputError { InputError::KeyErr(e) } + fn from(e: bitcoin::key::FromSliceError) -> Self { Self::KeyErr(e) } } /// Psbt satisfier for at inputs at a particular index. @@ -1193,18 +1193,18 @@ pub enum UtxoUpdateError { impl fmt::Display for UtxoUpdateError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - UtxoUpdateError::IndexOutOfBounds(ind, len) => { + Self::IndexOutOfBounds(ind, len) => { write!(f, "index {}, psbt input len: {}", ind, len) } - UtxoUpdateError::MissingInputUtxo => { + Self::MissingInputUtxo => { write!(f, "Missing input in unsigned transaction") } - UtxoUpdateError::DerivationError(e) => write!(f, "Key derivation error {}", e), - UtxoUpdateError::UtxoCheck => write!( + Self::DerivationError(e) => write!(f, "Key derivation error {}", e), + Self::UtxoCheck => write!( f, "The input's witness_utxo and/or non_witness_utxo were invalid or missing" ), - UtxoUpdateError::MismatchedScriptPubkey => { + Self::MismatchedScriptPubkey => { write!(f, "The input's witness_utxo and/or non_witness_utxo had a script pubkey that didn't match the descriptor") } } @@ -1239,14 +1239,14 @@ pub enum OutputUpdateError { impl fmt::Display for OutputUpdateError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - OutputUpdateError::IndexOutOfBounds(ind, len) => { + Self::IndexOutOfBounds(ind, len) => { write!(f, "index {}, psbt output len: {}", ind, len) } - OutputUpdateError::MissingTxOut => { + Self::MissingTxOut => { write!(f, "Missing txout in the unsigned transaction") } - OutputUpdateError::DerivationError(e) => write!(f, "Key derivation error {}", e), - OutputUpdateError::MismatchedScriptPubkey => { + Self::DerivationError(e) => write!(f, "Key derivation error {}", e), + Self::MismatchedScriptPubkey => { write!(f, "The output's script pubkey didn't match the descriptor") } } @@ -1291,17 +1291,17 @@ pub enum SighashError { impl fmt::Display for SighashError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - SighashError::IndexOutOfBounds(ind, len) => { + Self::IndexOutOfBounds(ind, len) => { write!(f, "index {}, psbt input len: {}", ind, len) } - SighashError::MissingInputUtxo => write!(f, "Missing input utxo in pbst"), - SighashError::MissingSpendUtxos => write!(f, "Missing Psbt spend utxos"), - SighashError::InvalidSighashType => write!(f, "Invalid Sighash type"), - SighashError::MissingWitnessScript => write!(f, "Missing Witness Script"), - SighashError::MissingRedeemScript => write!(f, "Missing Redeem Script"), - SighashError::SighashTaproot(ref e) => write!(f, "sighash taproot: {}", e), - SighashError::SighashP2wpkh(ref e) => write!(f, "sighash p2wpkh: {}", e), - SighashError::TransactionInputsIndex(ref e) => write!(f, "tx inputs index: {}", e), + Self::MissingInputUtxo => write!(f, "Missing input utxo in pbst"), + Self::MissingSpendUtxos => write!(f, "Missing Psbt spend utxos"), + Self::InvalidSighashType => write!(f, "Invalid Sighash type"), + Self::MissingWitnessScript => write!(f, "Missing Witness Script"), + Self::MissingRedeemScript => write!(f, "Missing Redeem Script"), + Self::SighashTaproot(ref e) => write!(f, "sighash taproot: {}", e), + Self::SighashP2wpkh(ref e) => write!(f, "sighash p2wpkh: {}", e), + Self::TransactionInputsIndex(ref e) => write!(f, "tx inputs index: {}", e), } } } @@ -1326,15 +1326,15 @@ impl error::Error for SighashError { } impl From for SighashError { - fn from(e: sighash::TaprootError) -> Self { SighashError::SighashTaproot(e) } + fn from(e: sighash::TaprootError) -> Self { Self::SighashTaproot(e) } } impl From for SighashError { - fn from(e: sighash::P2wpkhError) -> Self { SighashError::SighashP2wpkh(e) } + fn from(e: sighash::P2wpkhError) -> Self { Self::SighashP2wpkh(e) } } impl From for SighashError { - fn from(e: transaction::InputsIndexError) -> Self { SighashError::TransactionInputsIndex(e) } + fn from(e: transaction::InputsIndexError) -> Self { Self::TransactionInputsIndex(e) } } /// Sighash message(signing data) for a given psbt transaction input. @@ -1352,11 +1352,11 @@ impl PsbtSighashMsg { /// Convert the message to a [`secp256k1::Message`]. pub fn to_secp_msg(&self) -> secp256k1::Message { match *self { - PsbtSighashMsg::TapSighash(msg) => secp256k1::Message::from_digest(msg.to_byte_array()), - PsbtSighashMsg::LegacySighash(msg) => { + Self::TapSighash(msg) => secp256k1::Message::from_digest(msg.to_byte_array()), + Self::LegacySighash(msg) => { secp256k1::Message::from_digest(msg.to_byte_array()) } - PsbtSighashMsg::SegwitV0Sighash(msg) => { + Self::SegwitV0Sighash(msg) => { secp256k1::Message::from_digest(msg.to_byte_array()) } } diff --git a/src/util.rs b/src/util.rs index 5de37b780..0ab54d37a 100644 --- a/src/util.rs +++ b/src/util.rs @@ -20,21 +20,21 @@ pub(crate) trait ItemSize { impl ItemSize for Placeholder { fn size(&self) -> usize { match self { - Placeholder::Pubkey(_, size) => *size, - Placeholder::PubkeyHash(_, size) => *size, - Placeholder::EcdsaSigPk(_) | Placeholder::EcdsaSigPkHash(_) => 73, - Placeholder::SchnorrSigPk(_, _, size) | Placeholder::SchnorrSigPkHash(_, _, size) => { + Self::Pubkey(_, size) => *size, + Self::PubkeyHash(_, size) => *size, + Self::EcdsaSigPk(_) | Self::EcdsaSigPkHash(_) => 73, + Self::SchnorrSigPk(_, _, size) | Self::SchnorrSigPkHash(_, _, size) => { size + 1 } // +1 for the OP_PUSH - Placeholder::HashDissatisfaction - | Placeholder::Sha256Preimage(_) - | Placeholder::Hash256Preimage(_) - | Placeholder::Ripemd160Preimage(_) - | Placeholder::Hash160Preimage(_) => 33, - Placeholder::PushOne => 2, // On legacy this should be 1 ? - Placeholder::PushZero => 1, - Placeholder::TapScript(s) => s.len() + varint_len(s.len()), - Placeholder::TapControlBlock(cb) => { + Self::HashDissatisfaction + | Self::Sha256Preimage(_) + | Self::Hash256Preimage(_) + | Self::Ripemd160Preimage(_) + | Self::Hash160Preimage(_) => 33, + Self::PushOne => 2, // On legacy this should be 1 ? + Self::PushZero => 1, + Self::TapScript(s) => s.len() + varint_len(s.len()), + Self::TapControlBlock(cb) => { let block_len = cb.serialize().len(); block_len + varint_len(block_len) } From 45d494b67dd73bfb2448d4794eeb7f5af45dcd79 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Sat, 16 May 2026 10:55:55 +1000 Subject: [PATCH 2/3] Run the formatter All these issues were introduced by the `use_self` change. Fixed separately to make review of that change easier since its 12000 lines long. --- src/descriptor/key.rs | 16 +++---- src/descriptor/key_map.rs | 14 ++---- src/descriptor/mod.rs | 4 +- src/descriptor/wallet_policy/mod.rs | 4 +- src/expression/error.rs | 7 +-- src/interpreter/error.rs | 12 ++--- src/miniscript/decode.rs | 24 ++++------ src/miniscript/display.rs | 4 +- src/miniscript/mod.rs | 19 ++------ src/miniscript/satisfy/mod.rs | 4 +- src/miniscript/types/extra_props.rs | 38 ++++++++-------- src/miniscript/types/malleability.rs | 15 ++----- src/policy/compiler.rs | 66 ++++++---------------------- src/primitives/relative_locktime.rs | 4 +- src/psbt/mod.rs | 8 +--- src/util.rs | 4 +- 16 files changed, 68 insertions(+), 175 deletions(-) diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index 7c69e33b8..96166dcf1 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -630,9 +630,7 @@ impl DescriptorSecretKey { let pk = match self { Self::Single(prv) => DescriptorPublicKey::Single(prv.to_public(secp)), Self::XPrv(xprv) => DescriptorPublicKey::XPub(xprv.to_public(secp)?), - Self::MultiXPrv(xprv) => { - DescriptorPublicKey::MultiXPub(xprv.to_public(secp)?) - } + Self::MultiXPrv(xprv) => DescriptorPublicKey::MultiXPub(xprv.to_public(secp)?), }; Ok(pk) @@ -851,13 +849,11 @@ impl DescriptorPublicKey { }; Some(origin_path.extend(&xpub.derivation_path)) } - Self::Single(ref single) => { - Some(if let Some((_, ref path)) = single.origin { - path.clone() - } else { - bip32::DerivationPath::from(vec![]) - }) - } + Self::Single(ref single) => Some(if let Some((_, ref path)) = single.origin { + path.clone() + } else { + bip32::DerivationPath::from(vec![]) + }), Self::MultiXPub(_) => None, } } diff --git a/src/descriptor/key_map.rs b/src/descriptor/key_map.rs index 78474cb6b..64ff3c297 100644 --- a/src/descriptor/key_map.rs +++ b/src/descriptor/key_map.rs @@ -128,10 +128,7 @@ impl GetKey for DescriptorSecretKey { Ok(None) } } - ( - Self::XPrv(descriptor_xkey), - ref key_request @ KeyRequest::Bip32(ref key_source), - ) => { + (Self::XPrv(descriptor_xkey), ref key_request @ KeyRequest::Bip32(ref key_source)) => { if let Some(key) = descriptor_xkey.xkey.get_key(key_request.clone(), secp)? { return Ok(Some(key)); } @@ -152,13 +149,8 @@ impl GetKey for DescriptorSecretKey { Ok(None) } - (Self::XPrv(_), KeyRequest::XOnlyPubkey(_)) => { - Err(GetKeyError::NotSupported) - } - ( - desc_multi_sk @ Self::MultiXPrv(_descriptor_multi_xkey), - key_request, - ) => { + (Self::XPrv(_), KeyRequest::XOnlyPubkey(_)) => Err(GetKeyError::NotSupported), + (desc_multi_sk @ Self::MultiXPrv(_descriptor_multi_xkey), key_request) => { for desc_sk in &desc_multi_sk.clone().into_single_keys() { // If any key is an error, then all of them will, so here we propagate errors with ?. if let Some(pk) = desc_sk.get_key(key_request.clone(), secp)? { diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index 837b17003..fd6e5a9d7 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -172,9 +172,7 @@ impl Descriptor { /// Create a new sh for a given redeem script /// Errors when miniscript exceeds resource limits under p2sh context /// or does not type check at the top level - pub fn new_sh(ms: Miniscript) -> Result { - Ok(Self::Sh(Sh::new(ms)?)) - } + pub fn new_sh(ms: Miniscript) -> Result { Ok(Self::Sh(Sh::new(ms)?)) } /// Create a new wsh descriptor from witness script /// Errors when miniscript exceeds resource limits under p2sh context diff --git a/src/descriptor/wallet_policy/mod.rs b/src/descriptor/wallet_policy/mod.rs index f78c8c640..00aa635d0 100644 --- a/src/descriptor/wallet_policy/mod.rs +++ b/src/descriptor/wallet_policy/mod.rs @@ -253,9 +253,7 @@ pub enum WalletPolicyError { } impl From for DescriptorKeyParseError { - fn from(err: WalletPolicyError) -> Self { - Self::XKeyParseError(XKeyParseError::Bip388(err)) - } + fn from(err: WalletPolicyError) -> Self { Self::XKeyParseError(XKeyParseError::Bip388(err)) } } #[cfg(feature = "std")] diff --git a/src/expression/error.rs b/src/expression/error.rs index 7d6a8dc2a..c0c6f088d 100644 --- a/src/expression/error.rs +++ b/src/expression/error.rs @@ -138,12 +138,7 @@ impl fmt::Display for ParseTreeError { write!(f, "expected node '{}', found '{}'", expected, actual) } } - Self::IncorrectNumberOfChildren { - description, - n_children, - minimum, - maximum, - } => { + Self::IncorrectNumberOfChildren { description, n_children, minimum, maximum } => { write!(f, "{} must have ", description)?; match (minimum, maximum) { (_, Some(0)) => f.write_str("no children"), diff --git a/src/interpreter/error.rs b/src/interpreter/error.rs index 8f796872a..fde7f51ee 100644 --- a/src/interpreter/error.rs +++ b/src/interpreter/error.rs @@ -128,9 +128,7 @@ impl fmt::Display for Error { ), Self::CannotInferTrDescriptors => write!(f, "Cannot infer taproot descriptors"), Self::ControlBlockParse(ref e) => write!(f, "Control block parse error {}", e), - Self::ControlBlockVerificationError => { - f.write_str("Control block verification failed") - } + Self::ControlBlockVerificationError => f.write_str("Control block verification failed"), Self::EcdsaSig(ref s) => write!(f, "Ecdsa sig error: {}", s), Self::ExpectedPush => f.write_str("expected push in script"), Self::CouldNotEvaluate => f.write_str("Interpreter Error: Could not evaluate"), @@ -172,17 +170,13 @@ impl fmt::Display for Error { Self::SchnorrSig(ref s) => write!(f, "Schnorr sig error: {}", s), Self::SighashError(ref e) => fmt::Display::fmt(e, f), Self::TapAnnexUnsupported => f.write_str("Encountered annex element"), - Self::UncompressedPubkey => { - f.write_str("uncompressed pubkey in non-legacy descriptor") - } + Self::UncompressedPubkey => f.write_str("uncompressed pubkey in non-legacy descriptor"), Self::UnexpectedStackBoolean => { f.write_str("Expected Stack Push operation, found stack bool") } Self::UnexpectedStackElementPush => write!(f, "Got {}, expected Stack Boolean", 1), Self::UnexpectedStackEnd => f.write_str("unexpected end of stack"), - Self::VerifyFailed => { - f.write_str("Expected Satisfied Boolean at stack top for VERIFY") - } + Self::VerifyFailed => f.write_str("Expected Satisfied Boolean at stack top for VERIFY"), } } } diff --git a/src/miniscript/decode.rs b/src/miniscript/decode.rs index f529d7a5a..402ce853c 100644 --- a/src/miniscript/decode.rs +++ b/src/miniscript/decode.rs @@ -184,17 +184,13 @@ impl Clone for Terminal { Self::DupIf(ref sub) => Self::DupIf(Arc::new(Miniscript::clone(sub))), Self::Verify(ref sub) => Self::Verify(Arc::new(Miniscript::clone(sub))), Self::NonZero(ref sub) => Self::NonZero(Arc::new(Miniscript::clone(sub))), - Self::ZeroNotEqual(ref sub) => { - Self::ZeroNotEqual(Arc::new(Miniscript::clone(sub))) + Self::ZeroNotEqual(ref sub) => Self::ZeroNotEqual(Arc::new(Miniscript::clone(sub))), + Self::AndV(ref left, ref right) => { + Self::AndV(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) + } + Self::AndB(ref left, ref right) => { + Self::AndB(Arc::new(Miniscript::clone(left)), Arc::new(Miniscript::clone(right))) } - Self::AndV(ref left, ref right) => Self::AndV( - Arc::new(Miniscript::clone(left)), - Arc::new(Miniscript::clone(right)), - ), - Self::AndB(ref left, ref right) => Self::AndB( - Arc::new(Miniscript::clone(left)), - Arc::new(Miniscript::clone(right)), - ), Self::AndOr(ref a, ref b, ref c) => Self::AndOr( Arc::new(Miniscript::clone(a)), Arc::new(Miniscript::clone(b)), @@ -237,13 +233,9 @@ impl PartialEq for Terminal { (Self::Ripemd160(h1), Self::Ripemd160(h2)) if h1 != h2 => return false, (Self::Hash160(h1), Self::Hash160(h2)) if h1 != h2 => return false, (Self::Multi(th1), Self::Multi(th2)) if th1 != th2 => return false, - (Self::SortedMulti(th1), Self::SortedMulti(th2)) if th1 != th2 => { - return false - } + (Self::SortedMulti(th1), Self::SortedMulti(th2)) if th1 != th2 => return false, (Self::MultiA(th1), Self::MultiA(th2)) if th1 != th2 => return false, - (Self::SortedMultiA(th1), Self::SortedMultiA(th2)) if th1 != th2 => { - return false - } + (Self::SortedMultiA(th1), Self::SortedMultiA(th2)) if th1 != th2 => return false, _ => { if mem::discriminant(me) != mem::discriminant(you) { return false; diff --git a/src/miniscript/display.rs b/src/miniscript/display.rs index ea6128ab1..0d93799c9 100644 --- a/src/miniscript/display.rs +++ b/src/miniscript/display.rs @@ -256,9 +256,7 @@ impl Terminal { Self::Swap(..) => "s", Self::Check(ref sub) if matches!(sub.as_inner(), Self::PkK(..)) => "pk", Self::Check(ref sub) if matches!(sub.as_inner(), Self::PkH(..)) => "pkh", - Self::Check(ref sub) if matches!(sub.as_inner(), Self::RawPkH(..)) => { - "expr_raw_pkh" - } + Self::Check(ref sub) if matches!(sub.as_inner(), Self::RawPkH(..)) => "expr_raw_pkh", Self::Check(..) => "c", Self::DupIf(..) => "d", Self::Verify(..) => "v", diff --git a/src/miniscript/mod.rs b/src/miniscript/mod.rs index b021a556b..cf852d42f 100644 --- a/src/miniscript/mod.rs +++ b/src/miniscript/mod.rs @@ -568,10 +568,7 @@ impl Miniscript { } /// Attempt to decode a Miniscript from Script, specifying which validation parameters to apply. - pub fn decode_with_ext( - script: &script::Script, - ext: &ExtParams, - ) -> Result { + pub fn decode_with_ext(script: &script::Script, ext: &ExtParams) -> Result { let tokens = lex(script)?; let mut iter = TokenIter::new(tokens); @@ -631,9 +628,7 @@ impl Miniscript { /// /// The type information and extra properties are implied by the AST. impl PartialOrd for Miniscript { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } /// `Ord` of `Miniscript` must depend only on node and not the type information. @@ -950,14 +945,8 @@ impl FromTree for Miniscript { .verify_terminal_parent("pk_h", "public key") .map(Self::pk_h) .map_err(Error::Parse), - "after" => node - .verify_after() - .map(Self::after) - .map_err(Error::Parse), - "older" => node - .verify_older() - .map(Self::older) - .map_err(Error::Parse), + "after" => node.verify_after().map(Self::after).map_err(Error::Parse), + "older" => node.verify_older().map(Self::older).map_err(Error::Parse), "sha256" => node .verify_terminal_parent("sha256", "hash") .map(Self::sha256) diff --git a/src/miniscript/satisfy/mod.rs b/src/miniscript/satisfy/mod.rs index d0ad9cf30..849e959cd 100644 --- a/src/miniscript/satisfy/mod.rs +++ b/src/miniscript/satisfy/mod.rs @@ -763,9 +763,7 @@ impl Placeholder { Self::Hash160Preimage(h) => sat.lookup_hash160(h).map(|p| p.to_vec()), Self::Ripemd160Preimage(h) => sat.lookup_ripemd160(h).map(|p| p.to_vec()), Self::EcdsaSigPk(pk) => sat.lookup_ecdsa_sig(pk).map(|s| s.to_vec()), - Self::EcdsaSigPkHash(pkh) => { - sat.lookup_raw_pkh_ecdsa_sig(pkh).map(|(_, s)| s.to_vec()) - } + Self::EcdsaSigPkHash(pkh) => sat.lookup_raw_pkh_ecdsa_sig(pkh).map(|(_, s)| s.to_vec()), Self::SchnorrSigPk(pk, SchnorrSigType::ScriptSpend { leaf_hash }, size) => sat .lookup_tap_leaf_script_sig(pk, leaf_hash) .map(|s| s.to_vec()) diff --git a/src/miniscript/types/extra_props.rs b/src/miniscript/types/extra_props.rs index 2cd5061aa..d4f83c0d6 100644 --- a/src/miniscript/types/extra_props.rs +++ b/src/miniscript/types/extra_props.rs @@ -63,26 +63,24 @@ impl TimelockInfo { // // If `k > 1` we have the additional consideration that if any two children have conflicting // timelock requirements, this represents an inaccessible spending branch. - timelocks - .into_iter() - .fold(Self::default(), |mut acc, t| { - // If more than one branch may be taken, and some other branch has a requirement - // that conflicts with this one, set `contains_combination`. - if k > 1 { - let height_and_time = (acc.csv_with_height && t.csv_with_time) - || (acc.csv_with_time && t.csv_with_height) - || (acc.cltv_with_time && t.cltv_with_height) - || (acc.cltv_with_height && t.cltv_with_time); - - acc.contains_combination |= height_and_time; - } - acc.csv_with_height |= t.csv_with_height; - acc.csv_with_time |= t.csv_with_time; - acc.cltv_with_height |= t.cltv_with_height; - acc.cltv_with_time |= t.cltv_with_time; - acc.contains_combination |= t.contains_combination; - acc - }) + timelocks.into_iter().fold(Self::default(), |mut acc, t| { + // If more than one branch may be taken, and some other branch has a requirement + // that conflicts with this one, set `contains_combination`. + if k > 1 { + let height_and_time = (acc.csv_with_height && t.csv_with_time) + || (acc.csv_with_time && t.csv_with_height) + || (acc.cltv_with_time && t.cltv_with_height) + || (acc.cltv_with_height && t.cltv_with_time); + + acc.contains_combination |= height_and_time; + } + acc.csv_with_height |= t.csv_with_height; + acc.csv_with_time |= t.csv_with_time; + acc.cltv_with_height |= t.cltv_with_height; + acc.cltv_with_time |= t.cltv_with_time; + acc.contains_combination |= t.contains_combination; + acc + }) } } diff --git a/src/miniscript/types/malleability.rs b/src/miniscript/types/malleability.rs index 79ee429e0..84500a0cb 100644 --- a/src/miniscript/types/malleability.rs +++ b/src/miniscript/types/malleability.rs @@ -73,8 +73,7 @@ impl Malleability { pub const TRUE: Self = Self { dissat: Dissat::None, safe: false, non_malleable: true }; /// Malleability data for the `0` combinator - pub const FALSE: Self = - Self { dissat: Dissat::Unique, safe: true, non_malleable: true }; + pub const FALSE: Self = Self { dissat: Dissat::Unique, safe: true, non_malleable: true }; /// Check whether the `self` is a subtype of `other` argument. /// @@ -90,14 +89,10 @@ impl Malleability { impl Malleability { /// Constructor for the malleabilitiy properties of the `pk_k` fragment. - pub const fn pk_k() -> Self { - Self { dissat: Dissat::Unique, safe: true, non_malleable: true } - } + pub const fn pk_k() -> Self { Self { dissat: Dissat::Unique, safe: true, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `pk_h` fragment. - pub const fn pk_h() -> Self { - Self { dissat: Dissat::Unique, safe: true, non_malleable: true } - } + pub const fn pk_h() -> Self { Self { dissat: Dissat::Unique, safe: true, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `multi` fragment. pub const fn multi() -> Self { @@ -125,9 +120,7 @@ impl Malleability { } /// Constructor for the malleabilitiy properties of either `after` or `older`. - pub const fn time() -> Self { - Self { dissat: Dissat::None, safe: false, non_malleable: true } - } + pub const fn time() -> Self { Self { dissat: Dissat::None, safe: false, non_malleable: true } } /// Constructor for the malleabilitiy properties of the `a:` fragment. pub const fn cast_alt(self) -> Self { self } diff --git a/src/policy/compiler.rs b/src/policy/compiler.rs index 5e2f48ebc..3e743a76d 100644 --- a/src/policy/compiler.rs +++ b/src/policy/compiler.rs @@ -76,24 +76,16 @@ pub enum CompilerError { impl fmt::Display for CompilerError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Self::NonBinaryArgAnd => { - f.write_str("And policy fragment must take 2 arguments") - } - Self::NonBinaryArgOr => { - f.write_str("Or policy fragment must take 2 arguments") - } - Self::TopLevelNonSafe => { - f.write_str("Top Level script is not safe on some spendpath") - } + Self::NonBinaryArgAnd => f.write_str("And policy fragment must take 2 arguments"), + Self::NonBinaryArgOr => f.write_str("Or policy fragment must take 2 arguments"), + Self::TopLevelNonSafe => f.write_str("Top Level script is not safe on some spendpath"), Self::ImpossibleNonMalleableCompilation => { f.write_str("The compiler could not find any non-malleable compilation") } Self::LimitsExceeded => f.write_str( "At least one spending path has exceeded the standardness or consensus limits", ), - Self::NoInternalKey => { - f.write_str("Taproot compilation had no internal key available") - } + Self::NoInternalKey => f.write_str("Taproot compilation had no internal key available"), Self::TooManyTapleaves { n, max } => { write!(f, "Policy had too many Tapleaves (found {}, maximum {})", n, max) } @@ -192,8 +184,7 @@ struct CompilerExtData { impl CompilerExtData { const TRUE: Self = Self { branch_prob: None, sat_cost: 0.0, dissat_cost: None }; - const FALSE: Self = - Self { branch_prob: None, sat_cost: f64::MAX, dissat_cost: Some(0.0) }; + const FALSE: Self = Self { branch_prob: None, sat_cost: f64::MAX, dissat_cost: Some(0.0) }; fn pk_k() -> Self { Self { @@ -248,34 +239,20 @@ impl CompilerExtData { fn sortedmulti_a(k: usize, n: usize) -> Self { Self::multi_a(k, n) } - fn hash() -> Self { - Self { branch_prob: None, sat_cost: 33.0, dissat_cost: Some(33.0) } - } + fn hash() -> Self { Self { branch_prob: None, sat_cost: 33.0, dissat_cost: Some(33.0) } } fn time() -> Self { Self { branch_prob: None, sat_cost: 0.0, dissat_cost: None } } fn cast_alt(self) -> Self { - Self { - branch_prob: None, - sat_cost: self.sat_cost, - dissat_cost: self.dissat_cost, - } + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: self.dissat_cost } } fn cast_swap(self) -> Self { - Self { - branch_prob: None, - sat_cost: self.sat_cost, - dissat_cost: self.dissat_cost, - } + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: self.dissat_cost } } fn cast_check(self) -> Self { - Self { - branch_prob: None, - sat_cost: self.sat_cost, - dissat_cost: self.dissat_cost, - } + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: self.dissat_cost } } fn cast_dupif(self) -> Self { @@ -291,11 +268,7 @@ impl CompilerExtData { } fn cast_zeronotequal(self) -> Self { - Self { - branch_prob: None, - sat_cost: self.sat_cost, - dissat_cost: self.dissat_cost, - } + Self { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: self.dissat_cost } } fn cast_true(self) -> Self { @@ -322,11 +295,7 @@ impl CompilerExtData { } fn and_v(left: Self, right: Self) -> Self { - Self { - branch_prob: None, - sat_cost: left.sat_cost + right.sat_cost, - dissat_cost: None, - } + Self { branch_prob: None, sat_cost: left.sat_cost + right.sat_cost, dissat_cost: None } } fn or_b(l: Self, r: Self) -> Self { @@ -562,11 +531,7 @@ impl AstElemExt { Self { comp_ext_data: CompilerExtData::type_check(ms.as_inner()), ms: Arc::new(ms) } } - fn binary( - ast: Terminal, - l: &Self, - r: &Self, - ) -> Result { + fn binary(ast: Terminal, l: &Self, r: &Self) -> Result { let lookup_ext = |n| match n { 0 => l.comp_ext_data, 1 => r.comp_ext_data, @@ -583,12 +548,7 @@ impl AstElemExt { }) } - fn ternary( - ast: Terminal, - a: &Self, - b: &Self, - c: &Self, - ) -> Result { + fn ternary(ast: Terminal, a: &Self, b: &Self, c: &Self) -> Result { let lookup_ext = |n| match n { 0 => a.comp_ext_data, 1 => b.comp_ext_data, diff --git a/src/primitives/relative_locktime.rs b/src/primitives/relative_locktime.rs index be321d1ac..6640963cf 100644 --- a/src/primitives/relative_locktime.rs +++ b/src/primitives/relative_locktime.rs @@ -83,9 +83,7 @@ impl From for Sequence { } impl From for relative::LockTime { - fn from(lock_time: RelLockTime) -> Self { - lock_time.0.to_relative_lock_time().unwrap() - } + fn from(lock_time: RelLockTime) -> Self { lock_time.0.to_relative_lock_time().unwrap() } } impl cmp::PartialOrd for RelLockTime { diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 8b7700118..07860217e 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -1353,12 +1353,8 @@ impl PsbtSighashMsg { pub fn to_secp_msg(&self) -> secp256k1::Message { match *self { Self::TapSighash(msg) => secp256k1::Message::from_digest(msg.to_byte_array()), - Self::LegacySighash(msg) => { - secp256k1::Message::from_digest(msg.to_byte_array()) - } - Self::SegwitV0Sighash(msg) => { - secp256k1::Message::from_digest(msg.to_byte_array()) - } + Self::LegacySighash(msg) => secp256k1::Message::from_digest(msg.to_byte_array()), + Self::SegwitV0Sighash(msg) => secp256k1::Message::from_digest(msg.to_byte_array()), } } } diff --git a/src/util.rs b/src/util.rs index 0ab54d37a..4e71af420 100644 --- a/src/util.rs +++ b/src/util.rs @@ -23,9 +23,7 @@ impl ItemSize for Placeholder { Self::Pubkey(_, size) => *size, Self::PubkeyHash(_, size) => *size, Self::EcdsaSigPk(_) | Self::EcdsaSigPkHash(_) => 73, - Self::SchnorrSigPk(_, _, size) | Self::SchnorrSigPkHash(_, _, size) => { - size + 1 - } // +1 for the OP_PUSH + Self::SchnorrSigPk(_, _, size) | Self::SchnorrSigPkHash(_, _, size) => size + 1, // +1 for the OP_PUSH Self::HashDissatisfaction | Self::Sha256Preimage(_) | Self::Hash256Preimage(_) From ef1009288595853b4a88c7bf06f71b27af0b6fa5 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Wed, 13 May 2026 12:14:54 +1000 Subject: [PATCH 3/3] Rename semantic::Policy to Semantic Rename the `semantic::Policy` to `semantic::Semantic`. Keep the re-export at `Policy/mod.rs` (was an alias). In the `semantic` module unit tests leave `StringPolicy` as it is. Outside the `semantic` module remove the stutter; use `Semantic` instead of `semantic::Semantic`. --- src/descriptor/bare.rs | 8 +- src/descriptor/segwitv0.rs | 8 +- src/descriptor/sh.rs | 6 +- src/descriptor/tr/mod.rs | 11 ++- src/policy/concrete.rs | 2 +- src/policy/mod.rs | 2 +- src/policy/semantic.rs | 164 +++++++++++++++++++------------------ 7 files changed, 101 insertions(+), 100 deletions(-) diff --git a/src/descriptor/bare.rs b/src/descriptor/bare.rs index 9ae529357..40750ad6a 100644 --- a/src/descriptor/bare.rs +++ b/src/descriptor/bare.rs @@ -17,7 +17,7 @@ use crate::expression::{self, FromTree}; use crate::miniscript::context::{ScriptContext, ScriptContextError}; use crate::miniscript::satisfy::{Placeholder, Satisfaction, Witness}; use crate::plan::AssetProvider; -use crate::policy::{semantic, Liftable}; +use crate::policy::{Liftable, Semantic}; use crate::prelude::*; use crate::util::{varint_len, witness_to_scriptsig}; use crate::{ @@ -165,7 +165,7 @@ impl fmt::Display for Bare { } impl Liftable for Bare { - fn lift(&self) -> Result, Error> { self.ms.lift() } + fn lift(&self) -> Result, Error> { self.ms.lift() } } impl FromTree for Bare { @@ -349,9 +349,7 @@ impl fmt::Display for Pkh { } impl Liftable for Pkh { - fn lift(&self) -> Result, Error> { - Ok(semantic::Policy::Key(self.pk.clone())) - } + fn lift(&self) -> Result, Error> { Ok(Semantic::Key(self.pk.clone())) } } impl FromTree for Pkh { diff --git a/src/descriptor/segwitv0.rs b/src/descriptor/segwitv0.rs index 3fbae0bf3..d4f6848f6 100644 --- a/src/descriptor/segwitv0.rs +++ b/src/descriptor/segwitv0.rs @@ -16,7 +16,7 @@ use crate::miniscript::context::{ScriptContext, ScriptContextError}; use crate::miniscript::limits::MAX_PUBKEYS_PER_MULTISIG; use crate::miniscript::satisfy::{Placeholder, Satisfaction, Witness}; use crate::plan::AssetProvider; -use crate::policy::{semantic, Liftable}; +use crate::policy::{Liftable, Semantic}; use crate::prelude::*; use crate::util::varint_len; use crate::{ @@ -182,7 +182,7 @@ impl Wsh { } impl Liftable for Wsh { - fn lift(&self) -> Result, Error> { self.ms.lift() } + fn lift(&self) -> Result, Error> { self.ms.lift() } } impl crate::expression::FromTree for Wsh { @@ -394,9 +394,7 @@ impl fmt::Display for Wpkh { } impl Liftable for Wpkh { - fn lift(&self) -> Result, Error> { - Ok(semantic::Policy::Key(self.pk.clone())) - } + fn lift(&self) -> Result, Error> { Ok(Semantic::Key(self.pk.clone())) } } impl crate::expression::FromTree for Wpkh { diff --git a/src/descriptor/sh.rs b/src/descriptor/sh.rs index c8e9578df..8aa4606bf 100644 --- a/src/descriptor/sh.rs +++ b/src/descriptor/sh.rs @@ -20,7 +20,7 @@ use crate::miniscript::context::ScriptContext; use crate::miniscript::limits::MAX_PUBKEYS_PER_MULTISIG; use crate::miniscript::satisfy::{Placeholder, Satisfaction}; use crate::plan::AssetProvider; -use crate::policy::{semantic, Liftable}; +use crate::policy::{Liftable, Semantic}; use crate::prelude::*; use crate::util::{varint_len, witness_to_scriptsig}; use crate::{ @@ -47,10 +47,10 @@ pub enum ShInner { } impl Liftable for Sh { - fn lift(&self) -> Result, Error> { + fn lift(&self) -> Result, Error> { match self.inner { ShInner::Wsh(ref wsh) => wsh.lift(), - ShInner::Wpkh(ref pk) => Ok(semantic::Policy::Key(pk.as_inner().clone())), + ShInner::Wpkh(ref pk) => Ok(Semantic::Key(pk.as_inner().clone())), ShInner::Ms(ref ms) => ms.lift(), } } diff --git a/src/descriptor/tr/mod.rs b/src/descriptor/tr/mod.rs index a0e3f346b..57a9234fe 100644 --- a/src/descriptor/tr/mod.rs +++ b/src/descriptor/tr/mod.rs @@ -11,8 +11,7 @@ use crate::expression::{self, FromTree}; use crate::miniscript::satisfy::{Placeholder, Satisfaction, SchnorrSigType, Witness}; use crate::miniscript::Miniscript; use crate::plan::AssetProvider; -use crate::policy::semantic::Policy; -use crate::policy::Liftable; +use crate::policy::{Liftable, Semantic}; use crate::prelude::*; use crate::util::{varint_len, witness_size}; use crate::{ @@ -418,13 +417,13 @@ impl fmt::Display for Tr { } impl Liftable for Tr { - fn lift(&self) -> Result, Error> { + fn lift(&self) -> Result, Error> { match &self.tree { - Some(root) => Ok(Policy::Thresh(Threshold::or( - Arc::new(Policy::Key(self.internal_key.clone())), + Some(root) => Ok(Semantic::Thresh(Threshold::or( + Arc::new(Semantic::Key(self.internal_key.clone())), Arc::new(root.lift()?), ))), - None => Ok(Policy::Key(self.internal_key.clone())), + None => Ok(Semantic::Key(self.internal_key.clone())), } } } diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 8a197fb1e..34e5a60e6 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -657,7 +657,7 @@ impl ForEachKey for Policy { impl Policy { /// Converts a policy using one kind of public key to another type of public key. /// - /// For example usage please see [`crate::policy::semantic::Policy::translate_pk`]. + /// For example usage please see [`crate::policy::Semantic::translate_pk`]. pub fn translate_pk(&self, t: &mut T) -> Result, T::Error> where T: Translator, diff --git a/src/policy/mod.rs b/src/policy/mod.rs index 7447356be..7e19364cd 100644 --- a/src/policy/mod.rs +++ b/src/policy/mod.rs @@ -19,7 +19,7 @@ pub mod concrete; pub mod semantic; pub use self::concrete::Policy as Concrete; -pub use self::semantic::Policy as Semantic; +pub use self::semantic::Semantic; use crate::descriptor::Descriptor; use crate::iter::TreeLike as _; use crate::miniscript::{Miniscript, ScriptContext}; diff --git a/src/policy/semantic.rs b/src/policy/semantic.rs index c67459170..6aad2bac7 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -25,7 +25,7 @@ use crate::{ /// representing the same policy are lifted to the same abstract `Policy`, /// regardless of their choice of `pk` or `pk_h` nodes. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord)] -pub enum Policy { +pub enum Semantic { /// Unsatisfiable. Unsatisfiable, /// Trivially satisfiable. @@ -48,7 +48,7 @@ pub enum Policy { Thresh(Threshold, 0>), } -impl ForEachKey for Policy { +impl ForEachKey for Semantic { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { self.pre_order_iter().all(|policy| match policy { Self::Key(ref pk) => pred(pk), @@ -57,7 +57,7 @@ impl ForEachKey for Policy { } } -impl Policy { +impl Semantic { /// Converts a policy using one kind of public key to another type of public key. /// /// # Examples @@ -66,10 +66,10 @@ impl Policy { /// use std::collections::HashMap; /// use std::str::FromStr; /// use miniscript::bitcoin::{hashes::hash160, PublicKey}; - /// use miniscript::{translate_hash_fail, policy::semantic::Policy, Translator}; + /// use miniscript::{translate_hash_fail, policy::semantic::Semantic, Translator}; /// let alice_pk = "02c79ef3ede6d14f72a00d0e49b4becfb152197b64c0707425c4f231df29500ee7"; /// let bob_pk = "03d008a849fbf474bd17e9d2c1a827077a468150e58221582ec3410ab309f5afe4"; - /// let placeholder_policy = Policy::::from_str("and(pk(alice_pk),pk(bob_pk))").unwrap(); + /// let placeholder_policy = Semantic::::from_str("and(pk(alice_pk),pk(bob_pk))").unwrap(); /// /// // Information to translate abstract string type keys to concrete `bitcoin::PublicKey`s. /// // In practice, wallets would map from string key names to BIP32 keys. @@ -99,14 +99,14 @@ impl Policy { /// /// let real_policy = placeholder_policy.translate_pk(&mut t).unwrap(); /// - /// let expected_policy = Policy::from_str(&format!("and(pk({}),pk({}))", alice_pk, bob_pk)).unwrap(); + /// let expected_policy = Semantic::from_str(&format!("and(pk({}),pk({}))", alice_pk, bob_pk)).unwrap(); /// assert_eq!(real_policy, expected_policy); /// ``` - pub fn translate_pk(&self, t: &mut T) -> Result, T::Error> + pub fn translate_pk(&self, t: &mut T) -> Result, T::Error> where T: Translator, { - use Policy::*; + use Semantic::*; let mut translated = vec![]; for data in self.rtl_post_order_iter() { @@ -168,7 +168,7 @@ impl Policy { // Helper function to compute the number of constraints in policy. fn n_terminals(&self) -> usize { - use Policy::*; + use Semantic::*; let mut n_terminals = vec![]; for data in self.rtl_post_order_iter() { @@ -201,7 +201,7 @@ impl Policy { pub(crate) fn satisfy_constraint(self, witness: &Self, available: bool) -> Self { debug_assert!(self.clone().normalized() == self); if let Self::Thresh { .. } = *witness { - // We can't debug_assert on Policy::Thresh. + // We can't debug_assert on Semantic::Thresh. panic!("should be unreachable") } @@ -223,7 +223,7 @@ impl Policy { } } -impl fmt::Debug for Policy { +impl fmt::Debug for Semantic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Self::Unsatisfiable => f.write_str("UNSATISFIABLE()"), @@ -248,7 +248,7 @@ impl fmt::Debug for Policy { } } -impl fmt::Display for Policy { +impl fmt::Display for Semantic { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Self::Unsatisfiable => f.write_str("UNSATISFIABLE"), @@ -273,7 +273,7 @@ impl fmt::Display for Policy { } } -impl str::FromStr for Policy { +impl str::FromStr for Semantic { type Err = Error; fn from_str(s: &str) -> Result { let tree = expression::Tree::from_str(s)?; @@ -281,9 +281,9 @@ impl str::FromStr for Policy { } } -serde_string_impl_pk!(Policy, "a miniscript semantic policy"); +serde_string_impl_pk!(Semantic, "a miniscript semantic policy"); -impl expression::FromTree for Policy { +impl expression::FromTree for Semantic { fn from_tree(root: expression::TreeIterItem) -> Result { root.verify_no_curly_braces() .map_err(From::from) @@ -319,25 +319,31 @@ impl expression::FromTree for Policy { } "pk" => node .verify_terminal_parent("pk", "public key") - .map(Policy::Key) + .map(Semantic::Key) .map_err(Error::Parse), - "after" => node.verify_after().map_err(Error::Parse).map(Policy::After), - "older" => node.verify_older().map_err(Error::Parse).map(Policy::Older), + "after" => node + .verify_after() + .map_err(Error::Parse) + .map(Semantic::After), + "older" => node + .verify_older() + .map_err(Error::Parse) + .map(Semantic::Older), "sha256" => node .verify_terminal_parent("sha256", "hash") - .map(Policy::Sha256) + .map(Semantic::Sha256) .map_err(Error::Parse), "hash256" => node .verify_terminal_parent("hash256", "hash") - .map(Policy::Hash256) + .map(Semantic::Hash256) .map_err(Error::Parse), "ripemd160" => node .verify_terminal_parent("ripemd160", "hash") - .map(Policy::Ripemd160) + .map(Semantic::Ripemd160) .map_err(Error::Parse), "hash160" => node .verify_terminal_parent("hash160", "hash") - .map(Policy::Hash160) + .map(Semantic::Hash160) .map_err(Error::Parse), "and" => { node.verify_n_children("and", 2..) @@ -385,7 +391,7 @@ impl expression::FromTree for Policy { } } -impl Policy { +impl Semantic { /// Flattens out trees of `And`s and `Or`s; eliminate `Trivial` and /// `Unsatisfiable`s. Does not reorder any branches; use `.sort`. pub fn normalized(self) -> Self { @@ -459,14 +465,14 @@ impl Policy { /// Detects a true/trivial policy. /// - /// Only checks whether the policy is `Policy::Trivial`, to check if the + /// Only checks whether the policy is `Semantic::Trivial`, to check if the /// normalized form is trivial, the caller is expected to normalize the /// policy first. pub fn is_trivial(&self) -> bool { matches!(*self, Self::Trivial) } /// Detects a false/unsatisfiable policy. /// - /// Only checks whether the policy is `Policy::Unsatisfiable`, to check if + /// Only checks whether the policy is `Semantic::Unsatisfiable`, to check if /// the normalized form is unsatisfiable, the caller is expected to /// normalize the policy first. pub fn is_unsatisfiable(&self) -> bool { matches!(*self, Self::Unsatisfiable) } @@ -512,7 +518,7 @@ impl Policy { /// Filters a policy by eliminating relative timelock constraints /// that are not satisfied at the given `age`. pub fn at_age(self, age: relative::LockTime) -> Self { - use Policy::*; + use Semantic::*; let mut at_age = vec![]; for data in Arc::new(self).rtl_post_order_iter() { @@ -542,7 +548,7 @@ impl Policy { /// Filters a policy by eliminating absolute timelock constraints /// that are not satisfied at the given `n` (`n OP_CHECKLOCKTIMEVERIFY`). pub fn at_lock_time(self, n: absolute::LockTime) -> Self { - use Policy::*; + use Semantic::*; let mut at_age = vec![]; for data in Arc::new(self).rtl_post_order_iter() { @@ -584,7 +590,7 @@ impl Policy { /// /// Returns `None` if the policy is not satisfiable. pub fn minimum_n_keys(&self) -> Option { - use Policy::*; + use Semantic::*; let mut minimum_n_keys = vec![]; for data in self.rtl_post_order_iter() { @@ -613,14 +619,14 @@ impl Policy { } } -impl Policy { +impl Semantic { /// "Sorts" a policy to bring it into a canonical form to allow comparisons. /// /// Does **not** allow policies to be compared for functional equivalence; /// in general this appears to require Gröbner basis techniques that are not /// implemented. pub fn sorted(self) -> Self { - use Policy::*; + use Semantic::*; let mut sorted = vec![]; for data in Arc::new(self).rtl_post_order_iter() { @@ -644,14 +650,14 @@ impl Policy { } } -impl<'a, Pk: MiniscriptKey> TreeLike for &'a Policy { - type NaryChildren = &'a [Arc>]; +impl<'a, Pk: MiniscriptKey> TreeLike for &'a Semantic { + type NaryChildren = &'a [Arc>]; fn nary_len(tc: &Self::NaryChildren) -> usize { tc.len() } fn nary_index(tc: Self::NaryChildren, idx: usize) -> Self { &tc[idx] } fn as_node(&self) -> Tree { - use Policy::*; + use Semantic::*; match *self { Unsatisfiable | Trivial | Key(_) | After(_) | Older(_) | Sha256(_) | Hash256(_) @@ -661,14 +667,14 @@ impl<'a, Pk: MiniscriptKey> TreeLike for &'a Policy { } } -impl<'a, Pk: MiniscriptKey> TreeLike for &'a Arc> { - type NaryChildren = &'a [Arc>]; +impl<'a, Pk: MiniscriptKey> TreeLike for &'a Arc> { + type NaryChildren = &'a [Arc>]; fn nary_len(tc: &Self::NaryChildren) -> usize { tc.len() } fn nary_index(tc: Self::NaryChildren, idx: usize) -> Self { &tc[idx] } fn as_node(&self) -> Tree { - use Policy::*; + use Semantic::*; match ***self { Unsatisfiable | Trivial | Key(_) | After(_) | Older(_) | Sha256(_) | Hash256(_) @@ -686,7 +692,7 @@ mod tests { use super::*; - type StringPolicy = Policy; + type StringPolicy = Semantic; #[test] fn parse_policy_err() { @@ -697,14 +703,14 @@ mod tests { assert!(StringPolicy::from_str("or(or)").is_err()); - assert!(Policy::::from_str("pk()").is_err()); - assert!(Policy::::from_str( + assert!(Semantic::::from_str("pk()").is_err()); + assert!(Semantic::::from_str( "pk(\ 0200000000000000000000000000000000000002\ )" ) .is_err()); - assert!(Policy::::from_str( + assert!(Semantic::::from_str( "pk(\ 02c79ef3ede6d14f72a00d0e49b4becfb152197b64c0707425c4f231df29500ee7\ )" @@ -715,7 +721,7 @@ mod tests { #[test] fn semantic_analysis() { let policy = StringPolicy::from_str("pk()").unwrap(); - assert_eq!(policy, Policy::Key("".to_owned())); + assert_eq!(policy, Semantic::Key("".to_owned())); assert_eq!(policy.relative_timelocks(), vec![]); assert_eq!(policy.absolute_timelocks(), vec![]); assert_eq!(policy.clone().at_age(RelLockTime::ZERO.into()), policy); @@ -729,15 +735,15 @@ mod tests { assert_eq!(policy.minimum_n_keys(), Some(1)); let policy = StringPolicy::from_str("older(1000)").unwrap(); - assert_eq!(policy, Policy::Older(RelLockTime::from_height(1000).unwrap())); + assert_eq!(policy, Semantic::Older(RelLockTime::from_height(1000).unwrap())); assert_eq!(policy.absolute_timelocks(), vec![]); assert_eq!(policy.relative_timelocks(), vec![1000]); - assert_eq!(policy.clone().at_age(RelLockTime::ZERO.into()), Policy::Unsatisfiable); + assert_eq!(policy.clone().at_age(RelLockTime::ZERO.into()), Semantic::Unsatisfiable); assert_eq!( policy .clone() .at_age(RelLockTime::from_height(999).unwrap().into()), - Policy::Unsatisfiable + Semantic::Unsatisfiable ); assert_eq!( policy @@ -757,19 +763,19 @@ mod tests { let policy = StringPolicy::from_str("or(pk(),older(1000))").unwrap(); assert_eq!( policy, - Policy::Thresh(Threshold::or( - Policy::Key("".to_owned()).into(), - Policy::Older(RelLockTime::from_height(1000).unwrap()).into(), + Semantic::Thresh(Threshold::or( + Semantic::Key("".to_owned()).into(), + Semantic::Older(RelLockTime::from_height(1000).unwrap()).into(), )) ); assert_eq!(policy.relative_timelocks(), vec![1000]); assert_eq!(policy.absolute_timelocks(), vec![]); - assert_eq!(policy.clone().at_age(RelLockTime::ZERO.into()), Policy::Key("".to_owned())); + assert_eq!(policy.clone().at_age(RelLockTime::ZERO.into()), Semantic::Key("".to_owned())); assert_eq!( policy .clone() .at_age(RelLockTime::from_height(999).unwrap().into()), - Policy::Key("".to_owned()) + Semantic::Key("".to_owned()) ); assert_eq!( policy @@ -789,9 +795,9 @@ mod tests { let policy = StringPolicy::from_str("or(pk(),UNSATISFIABLE)").unwrap(); assert_eq!( policy, - Policy::Thresh(Threshold::or( - Policy::Key("".to_owned()).into(), - Policy::Unsatisfiable.into() + Semantic::Thresh(Threshold::or( + Semantic::Key("".to_owned()).into(), + Semantic::Unsatisfiable.into() )) ); assert_eq!(policy.relative_timelocks(), vec![]); @@ -802,9 +808,9 @@ mod tests { let policy = StringPolicy::from_str("and(pk(),UNSATISFIABLE)").unwrap(); assert_eq!( policy, - Policy::Thresh(Threshold::and( - Policy::Key("".to_owned()).into(), - Policy::Unsatisfiable.into() + Semantic::Thresh(Threshold::and( + Semantic::Key("".to_owned()).into(), + Semantic::Unsatisfiable.into() )) ); assert_eq!(policy.relative_timelocks(), vec![]); @@ -820,15 +826,15 @@ mod tests { .unwrap(); assert_eq!( policy, - Policy::Thresh( + Semantic::Thresh( Threshold::new( 2, vec![ - Policy::Older(RelLockTime::from_height(1000).unwrap()).into(), - Policy::Older(RelLockTime::from_height(10000).unwrap()).into(), - Policy::Older(RelLockTime::from_height(1000).unwrap()).into(), - Policy::Older(RelLockTime::from_height(2000).unwrap()).into(), - Policy::Older(RelLockTime::from_height(2000).unwrap()).into(), + Semantic::Older(RelLockTime::from_height(1000).unwrap()).into(), + Semantic::Older(RelLockTime::from_height(10000).unwrap()).into(), + Semantic::Older(RelLockTime::from_height(1000).unwrap()).into(), + Semantic::Older(RelLockTime::from_height(2000).unwrap()).into(), + Semantic::Older(RelLockTime::from_height(2000).unwrap()).into(), ] ) .unwrap() @@ -847,15 +853,15 @@ mod tests { .unwrap(); assert_eq!( policy, - Policy::Thresh( + Semantic::Thresh( Threshold::new( 2, vec![ - Policy::Older(RelLockTime::from_height(1000).unwrap()).into(), - Policy::Older(RelLockTime::from_height(10000).unwrap()).into(), - Policy::Older(RelLockTime::from_height(1000).unwrap()).into(), - Policy::Unsatisfiable.into(), - Policy::Unsatisfiable.into(), + Semantic::Older(RelLockTime::from_height(1000).unwrap()).into(), + Semantic::Older(RelLockTime::from_height(10000).unwrap()).into(), + Semantic::Older(RelLockTime::from_height(1000).unwrap()).into(), + Semantic::Unsatisfiable.into(), + Semantic::Unsatisfiable.into(), ] ) .unwrap() @@ -870,15 +876,15 @@ mod tests { // Block height 1000. let policy = StringPolicy::from_str("after(1000)").unwrap(); - assert_eq!(policy, Policy::After(AbsLockTime::from_consensus(1000).unwrap())); + assert_eq!(policy, Semantic::After(AbsLockTime::from_consensus(1000).unwrap())); assert_eq!(policy.absolute_timelocks(), vec![1000]); assert_eq!(policy.relative_timelocks(), vec![]); - assert_eq!(policy.clone().at_lock_time(absolute::LockTime::ZERO), Policy::Unsatisfiable); + assert_eq!(policy.clone().at_lock_time(absolute::LockTime::ZERO), Semantic::Unsatisfiable); assert_eq!( policy .clone() .at_lock_time(absolute::LockTime::from_height(999).expect("valid block height")), - Policy::Unsatisfiable + Semantic::Unsatisfiable ); assert_eq!( policy @@ -897,48 +903,48 @@ mod tests { policy .clone() .at_lock_time(absolute::LockTime::from_time(500_000_001).expect("valid timestamp")), - Policy::Unsatisfiable + Semantic::Unsatisfiable ); assert_eq!(policy.n_keys(), 0); assert_eq!(policy.minimum_n_keys(), Some(0)); // UNIX timestamp of 10 seconds after the epoch. let policy = StringPolicy::from_str("after(500000010)").unwrap(); - assert_eq!(policy, Policy::After(AbsLockTime::from_consensus(500_000_010).unwrap())); + assert_eq!(policy, Semantic::After(AbsLockTime::from_consensus(500_000_010).unwrap())); assert_eq!(policy.absolute_timelocks(), vec![500_000_010]); assert_eq!(policy.relative_timelocks(), vec![]); // Pass a block height to at_lock_time while policy uses a UNIX timestapm. - assert_eq!(policy.clone().at_lock_time(absolute::LockTime::ZERO), Policy::Unsatisfiable); + assert_eq!(policy.clone().at_lock_time(absolute::LockTime::ZERO), Semantic::Unsatisfiable); assert_eq!( policy .clone() .at_lock_time(absolute::LockTime::from_height(999).expect("valid block height")), - Policy::Unsatisfiable + Semantic::Unsatisfiable ); assert_eq!( policy .clone() .at_lock_time(absolute::LockTime::from_height(1000).expect("valid block height")), - Policy::Unsatisfiable + Semantic::Unsatisfiable ); assert_eq!( policy .clone() .at_lock_time(absolute::LockTime::from_height(10000).expect("valid block height")), - Policy::Unsatisfiable + Semantic::Unsatisfiable ); // And now pass a UNIX timestamp to at_lock_time while policy also uses a timestamp. assert_eq!( policy .clone() .at_lock_time(absolute::LockTime::from_time(500_000_000).expect("valid timestamp")), - Policy::Unsatisfiable + Semantic::Unsatisfiable ); assert_eq!( policy .clone() .at_lock_time(absolute::LockTime::from_time(500_000_001).expect("valid timestamp")), - Policy::Unsatisfiable + Semantic::Unsatisfiable ); assert_eq!( policy @@ -964,7 +970,7 @@ mod tests { // Very bad idea to add master key,pk but let's have it have 50M blocks let master_key = StringPolicy::from_str("and(older(50000000),pk(master))").unwrap(); let new_liquid_pol = - Policy::Thresh(Threshold::or(liquid_pol.clone().into(), master_key.into())); + Semantic::Thresh(Threshold::or(liquid_pol.clone().into(), master_key.into())); assert!(liquid_pol.clone().entails(new_liquid_pol.clone()).unwrap()); assert!(!new_liquid_pol.entails(liquid_pol.clone()).unwrap());