From 690a1aab839649bb2381ed6e5f18717a255a1005 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 25 Jul 2023 15:14:24 +1000 Subject: [PATCH 1/4] Rename traits MiniscriptKey and ScriptContext In an effort to make the code more terse with no loss of clarity rename the crate's main two traits `MiniscriptKey` to `Key` and `ScriptContext` to `Context`. The diff is big but can be verified by simply doing a search-and-replace on `MiniscriptKey` -> `Key` and `ScriptContext` -> `Context`. Then run `cargo +nightly fmt`. No other manual changes. --- bitcoind-tests/tests/setup/test_util.rs | 6 +- bitcoind-tests/tests/test_desc.rs | 4 +- examples/sign_multisig.rs | 2 +- src/descriptor/bare.rs | 44 +-- src/descriptor/key.rs | 8 +- src/descriptor/mod.rs | 32 +-- src/descriptor/segwitv0.rs | 46 ++-- src/descriptor/sh.rs | 26 +- src/descriptor/sortedmulti.rs | 26 +- src/descriptor/tr.rs | 52 ++-- src/interpreter/inner.rs | 8 +- src/interpreter/mod.rs | 16 +- src/iter/mod.rs | 6 +- src/lib.rs | 64 ++--- src/macros.rs | 52 ++-- src/miniscript/analyzable.rs | 4 +- src/miniscript/astelem.rs | 22 +- src/miniscript/context.rs | 338 ++++++++++++------------ src/miniscript/decode.rs | 14 +- src/miniscript/iter.rs | 18 +- src/miniscript/mod.rs | 58 ++-- src/miniscript/satisfy.rs | 62 ++--- src/miniscript/types/correctness.rs | 6 +- src/miniscript/types/extra_props.rs | 12 +- src/miniscript/types/malleability.rs | 6 +- src/miniscript/types/mod.rs | 26 +- src/policy/compiler.rs | 46 ++-- src/policy/concrete.rs | 38 +-- src/policy/mod.rs | 18 +- src/policy/semantic.rs | 22 +- src/psbt/mod.rs | 4 +- src/pub_macros.rs | 32 +-- src/test_utils.rs | 2 +- src/util.rs | 10 +- 34 files changed, 552 insertions(+), 578 deletions(-) diff --git a/bitcoind-tests/tests/setup/test_util.rs b/bitcoind-tests/tests/setup/test_util.rs index 3b77047a0..e844e7fd8 100644 --- a/bitcoind-tests/tests/setup/test_util.rs +++ b/bitcoind-tests/tests/setup/test_util.rs @@ -25,8 +25,8 @@ use bitcoin::secp256k1; use internals::hex::exts::DisplayHex; use miniscript::descriptor::{SinglePub, SinglePubKey}; use miniscript::{ - bitcoin, hash256, Descriptor, DescriptorPublicKey, Error, Miniscript, ScriptContext, - TranslatePk, Translator, + bitcoin, hash256, Context, Descriptor, DescriptorPublicKey, Error, Miniscript, TranslatePk, + Translator, }; use rand::RngCore; use secp256k1::XOnlyPublicKey; @@ -150,7 +150,7 @@ pub fn random_pk(mut seed: u8) -> bitcoin::PublicKey { #[allow(dead_code)] // https://github.com/rust-lang/rust/issues/46379. The code is pub fn and integration test, but still shows warnings /// Parse an insane miniscript into a miniscript with the format described above at file header -pub fn parse_insane_ms( +pub fn parse_insane_ms( ms: &str, pubdata: &PubData, ) -> Miniscript { diff --git a/bitcoind-tests/tests/test_desc.rs b/bitcoind-tests/tests/test_desc.rs index 06c8e8f82..e5ca47178 100644 --- a/bitcoind-tests/tests/test_desc.rs +++ b/bitcoind-tests/tests/test_desc.rs @@ -19,7 +19,7 @@ use bitcoin::{ use bitcoind::bitcoincore_rpc::{json, Client, RpcApi}; use miniscript::bitcoin::{self, ecdsa, taproot, ScriptBuf}; use miniscript::psbt::{PsbtExt, PsbtInputExt}; -use miniscript::{Descriptor, Miniscript, ScriptContext, ToPublicKey}; +use miniscript::{Context, Descriptor, Miniscript, ToPublicKey}; mod setup; use rand::RngCore; @@ -318,7 +318,7 @@ pub fn test_desc_satisfy( } // Find all secret corresponding to the known public keys in ms -fn find_sks_ms( +fn find_sks_ms( ms: &Miniscript, testdata: &TestData, ) -> Vec { diff --git a/examples/sign_multisig.rs b/examples/sign_multisig.rs index 1e913f609..022f5d74a 100644 --- a/examples/sign_multisig.rs +++ b/examples/sign_multisig.rs @@ -23,7 +23,7 @@ fn main() { assert_eq!(descriptor.max_weight_to_satisfy().unwrap(), 253); // Sometimes it is necessary to have additional information to get the - // `bitcoin::PublicKey` from the `MiniscriptKey` which can be supplied by + // `bitcoin::PublicKey` from the `Key` which can be supplied by // the `to_pk_ctx` parameter. For example, when calculating the script // pubkey of a descriptor with xpubs, the secp context and child information // maybe required. diff --git a/src/descriptor/bare.rs b/src/descriptor/bare.rs index a8028fe60..3179f486a 100644 --- a/src/descriptor/bare.rs +++ b/src/descriptor/bare.rs @@ -14,24 +14,24 @@ use bitcoin::{Address, Network, ScriptBuf}; use super::checksum::{self, verify_checksum}; use crate::expression::{self, FromTree}; -use crate::miniscript::context::{ScriptContext, ScriptContextError}; +use crate::miniscript::context::{Context, ContextError}; use crate::policy::{semantic, Liftable}; use crate::prelude::*; use crate::util::{varint_len, witness_to_scriptsig}; use crate::{ - BareCtx, Error, ForEachKey, Miniscript, MiniscriptKey, Satisfier, ToPublicKey, TranslateErr, - TranslatePk, Translator, + BareCtx, Error, ForEachKey, Key, Miniscript, Satisfier, ToPublicKey, TranslateErr, TranslatePk, + Translator, }; /// Create a Bare Descriptor. That is descriptor that is /// not wrapped in sh or wsh. This covers the Pk descriptor #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] -pub struct Bare { +pub struct Bare { /// underlying miniscript ms: Miniscript, } -impl Bare { +impl Bare { /// Create a new raw descriptor pub fn new(ms: Miniscript) -> Result { // do the top-level checks @@ -91,7 +91,7 @@ impl Bare { } } -impl Bare { +impl Bare { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> ScriptBuf { self.ms.encode() @@ -134,13 +134,13 @@ impl Bare { } } -impl fmt::Debug for Bare { +impl fmt::Debug for Bare { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.ms) } } -impl fmt::Display for Bare { +impl fmt::Display for Bare { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use fmt::Write; let mut wrapped_f = checksum::Formatter::new(f); @@ -149,7 +149,7 @@ impl fmt::Display for Bare { } } -impl Liftable for Bare { +impl Liftable for Bare { fn lift(&self) -> Result, Error> { self.ms.lift() } @@ -174,7 +174,7 @@ impl_from_str!( } ); -impl ForEachKey for Bare { +impl ForEachKey for Bare { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: F) -> bool { self.ms.for_each_key(pred) } @@ -182,8 +182,8 @@ impl ForEachKey for Bare { impl TranslatePk for Bare

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Bare; @@ -197,14 +197,14 @@ where /// A bare PkH descriptor at top level #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] -pub struct Pkh { +pub struct Pkh { /// underlying publickey pk: Pk, } -impl Pkh { +impl Pkh { /// Create a new Pkh descriptor - pub fn new(pk: Pk) -> Result { + pub fn new(pk: Pk) -> Result { // do the top-level checks match BareCtx::check_pk(&pk) { Ok(()) => Ok(Pkh { pk }), @@ -254,7 +254,7 @@ impl Pkh { } } -impl Pkh { +impl Pkh { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> ScriptBuf { // Fine to hard code the `Network` here because we immediately call @@ -311,13 +311,13 @@ impl Pkh { } } -impl fmt::Debug for Pkh { +impl fmt::Debug for Pkh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "pkh({:?})", self.pk) } } -impl fmt::Display for Pkh { +impl fmt::Display for Pkh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use fmt::Write; let mut wrapped_f = checksum::Formatter::new(f); @@ -326,7 +326,7 @@ impl fmt::Display for Pkh { } } -impl Liftable for Pkh { +impl Liftable for Pkh { fn lift(&self) -> Result, Error> { Ok(semantic::Policy::Key(self.pk.clone())) } @@ -359,7 +359,7 @@ impl_from_str!( } ); -impl ForEachKey for Pkh { +impl ForEachKey for Pkh { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { pred(&self.pk) } @@ -367,8 +367,8 @@ impl ForEachKey for Pkh { impl TranslatePk for Pkh

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Pkh; diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index 83308e0dc..d659ecbe0 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -16,7 +16,7 @@ use bitcoin::secp256k1::{Secp256k1, Signing, Verification}; use crate::prelude::*; #[cfg(feature = "serde")] use crate::serde::{Deserialize, Deserializer, Serialize, Serializer}; -use crate::{hash256, MiniscriptKey, ToPublicKey}; +use crate::{hash256, Key, ToPublicKey}; /// The descriptor pubkey, either a single pubkey or an xpub. #[derive(Debug, Eq, PartialEq, Clone, Ord, PartialOrd, Hash)] @@ -982,7 +982,7 @@ impl DescriptorXKey { } } -impl MiniscriptKey for DescriptorPublicKey { +impl Key for DescriptorPublicKey { type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; type Ripemd160 = ripemd160::Hash; @@ -1103,7 +1103,7 @@ impl fmt::Display for DefiniteDescriptorKey { } } -impl MiniscriptKey for DefiniteDescriptorKey { +impl Key for DefiniteDescriptorKey { type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; type Ripemd160 = ripemd160::Hash; @@ -1188,7 +1188,7 @@ mod test { use super::{ DescriptorKeyParseError, DescriptorMultiXKey, DescriptorPublicKey, DescriptorSecretKey, - MiniscriptKey, Wildcard, + Key, Wildcard, }; use crate::prelude::*; diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index 4ccf50f18..c9bda096b 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -25,8 +25,8 @@ use crate::miniscript::decode::Terminal; use crate::miniscript::{Legacy, Miniscript, Segwitv0}; use crate::prelude::*; use crate::{ - expression, hash256, BareCtx, Error, ForEachKey, MiniscriptKey, Satisfier, ToPublicKey, - TranslateErr, TranslatePk, Translator, + expression, hash256, BareCtx, Error, ForEachKey, Key, Satisfier, ToPublicKey, TranslateErr, + TranslatePk, Translator, }; mod bare; @@ -61,7 +61,7 @@ pub type KeyMap = HashMap; /// Script descriptor #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Descriptor { +pub enum Descriptor { /// A raw scriptpubkey (including pay-to-pubkey) under Legacy context Bare(Bare), /// Pay-to-PubKey-Hash @@ -76,42 +76,42 @@ pub enum Descriptor { Tr(Tr), } -impl From> for Descriptor { +impl From> for Descriptor { #[inline] fn from(inner: Bare) -> Self { Descriptor::Bare(inner) } } -impl From> for Descriptor { +impl From> for Descriptor { #[inline] fn from(inner: Pkh) -> Self { Descriptor::Pkh(inner) } } -impl From> for Descriptor { +impl From> for Descriptor { #[inline] fn from(inner: Wpkh) -> Self { Descriptor::Wpkh(inner) } } -impl From> for Descriptor { +impl From> for Descriptor { #[inline] fn from(inner: Sh) -> Self { Descriptor::Sh(inner) } } -impl From> for Descriptor { +impl From> for Descriptor { #[inline] fn from(inner: Wsh) -> Self { Descriptor::Wsh(inner) } } -impl From> for Descriptor { +impl From> for Descriptor { #[inline] fn from(inner: Tr) -> Self { Descriptor::Tr(inner) @@ -161,7 +161,7 @@ impl DescriptorType { } } -impl Descriptor { +impl Descriptor { // Keys /// Create a new pk descriptor @@ -378,7 +378,7 @@ impl Descriptor { } } -impl Descriptor { +impl Descriptor { /// Computes the Bitcoin address of the descriptor, if one exists /// /// Some descriptors like pk() don't have an address. @@ -511,8 +511,8 @@ impl Descriptor { impl TranslatePk for Descriptor

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Descriptor; @@ -533,7 +533,7 @@ where } } -impl ForEachKey for 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), @@ -919,7 +919,7 @@ impl_from_str!( } ); -impl fmt::Debug 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), @@ -932,7 +932,7 @@ impl fmt::Debug for Descriptor { } } -impl fmt::Display 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), diff --git a/src/descriptor/segwitv0.rs b/src/descriptor/segwitv0.rs index 4d7c4e7a3..9a00f199c 100644 --- a/src/descriptor/segwitv0.rs +++ b/src/descriptor/segwitv0.rs @@ -12,22 +12,22 @@ use bitcoin::{Address, Network, ScriptBuf}; use super::checksum::{self, verify_checksum}; use super::SortedMultiVec; use crate::expression::{self, FromTree}; -use crate::miniscript::context::{ScriptContext, ScriptContextError}; +use crate::miniscript::context::{Context, ContextError}; use crate::policy::{semantic, Liftable}; use crate::prelude::*; use crate::util::varint_len; use crate::{ - Error, ForEachKey, Miniscript, MiniscriptKey, Satisfier, Segwitv0, ToPublicKey, TranslateErr, + Error, ForEachKey, Key, Miniscript, Satisfier, Segwitv0, ToPublicKey, TranslateErr, TranslatePk, Translator, }; /// A Segwitv0 wsh descriptor #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] -pub struct Wsh { +pub struct Wsh { /// underlying miniscript inner: WshInner, } -impl Wsh { +impl Wsh { /// Get the Inner pub fn into_inner(self) -> WshInner { self.inner @@ -130,7 +130,7 @@ impl Wsh { } } -impl Wsh { +impl Wsh { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> ScriptBuf { self.inner_script().to_v0_p2wsh() @@ -193,14 +193,14 @@ impl Wsh { /// Wsh Inner #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] -pub enum WshInner { +pub enum WshInner { /// Sorted Multi SortedMulti(SortedMultiVec), /// Wsh Miniscript Ms(Miniscript), } -impl Liftable for Wsh { +impl Liftable for Wsh { fn lift(&self) -> Result, Error> { match self.inner { WshInner::SortedMulti(ref smv) => smv.lift(), @@ -234,7 +234,7 @@ impl_from_tree!( } ); -impl fmt::Debug for Wsh { +impl fmt::Debug for Wsh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.inner { WshInner::SortedMulti(ref smv) => write!(f, "wsh({:?})", smv), @@ -243,7 +243,7 @@ impl fmt::Debug for Wsh { } } -impl fmt::Display for Wsh { +impl fmt::Display for Wsh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use fmt::Write; let mut wrapped_f = checksum::Formatter::new(f); @@ -265,7 +265,7 @@ impl_from_str!( } ); -impl ForEachKey for Wsh { +impl ForEachKey for Wsh { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: F) -> bool { match self.inner { WshInner::SortedMulti(ref smv) => smv.for_each_key(pred), @@ -276,8 +276,8 @@ impl ForEachKey for Wsh { impl TranslatePk for Wsh

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Wsh; @@ -295,14 +295,14 @@ where /// A bare Wpkh descriptor at top level #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] -pub struct Wpkh { +pub struct Wpkh { /// underlying publickey pk: Pk, } -impl Wpkh { +impl Wpkh { /// Create a new Wpkh descriptor - pub fn new(pk: Pk) -> Result { + pub fn new(pk: Pk) -> Result { // do the top-level checks match Segwitv0::check_pk(&pk) { Ok(_) => Ok(Wpkh { pk }), @@ -329,7 +329,7 @@ impl Wpkh { /// Checks whether the descriptor is safe. pub fn sanity_check(&self) -> Result<(), Error> { if self.pk.is_uncompressed() { - Err(Error::ContextError(ScriptContextError::CompressedOnly( + Err(Error::ContextError(ContextError::CompressedOnly( self.pk.to_string(), ))) } else { @@ -361,7 +361,7 @@ impl Wpkh { } } -impl Wpkh { +impl Wpkh { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> ScriptBuf { let addr = Address::p2wpkh(&self.pk.to_public_key(), Network::Bitcoin) @@ -418,13 +418,13 @@ impl Wpkh { } } -impl fmt::Debug for Wpkh { +impl fmt::Debug for Wpkh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "wpkh({:?})", self.pk) } } -impl fmt::Display for Wpkh { +impl fmt::Display for Wpkh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use fmt::Write; let mut wrapped_f = checksum::Formatter::new(f); @@ -433,7 +433,7 @@ impl fmt::Display for Wpkh { } } -impl Liftable for Wpkh { +impl Liftable for Wpkh { fn lift(&self) -> Result, Error> { Ok(semantic::Policy::Key(self.pk.clone())) } @@ -466,7 +466,7 @@ impl_from_str!( } ); -impl ForEachKey for Wpkh { +impl ForEachKey for Wpkh { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { pred(&self.pk) } @@ -474,8 +474,8 @@ impl ForEachKey for Wpkh { impl TranslatePk for Wpkh

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Wpkh; diff --git a/src/descriptor/sh.rs b/src/descriptor/sh.rs index 1f18c641a..9545a9573 100644 --- a/src/descriptor/sh.rs +++ b/src/descriptor/sh.rs @@ -16,25 +16,25 @@ use bitcoin::{script, Address, Network, ScriptBuf}; use super::checksum::{self, verify_checksum}; use super::{SortedMultiVec, Wpkh, Wsh}; use crate::expression::{self, FromTree}; -use crate::miniscript::context::ScriptContext; +use crate::miniscript::context::Context; use crate::policy::{semantic, Liftable}; use crate::prelude::*; use crate::util::{varint_len, witness_to_scriptsig}; use crate::{ - push_opcode_size, Error, ForEachKey, Legacy, Miniscript, MiniscriptKey, Satisfier, Segwitv0, - ToPublicKey, TranslateErr, TranslatePk, Translator, + push_opcode_size, Error, ForEachKey, Key, Legacy, Miniscript, Satisfier, Segwitv0, ToPublicKey, + TranslateErr, TranslatePk, Translator, }; /// A Legacy p2sh Descriptor #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] -pub struct Sh { +pub struct Sh { /// underlying miniscript inner: ShInner, } /// Sh Inner #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] -pub enum ShInner { +pub enum ShInner { /// Nested Wsh Wsh(Wsh), /// Nested Wpkh @@ -45,7 +45,7 @@ pub enum ShInner { Ms(Miniscript), } -impl Liftable for Sh { +impl Liftable for Sh { fn lift(&self) -> Result, Error> { match self.inner { ShInner::Wsh(ref wsh) => wsh.lift(), @@ -56,7 +56,7 @@ impl Liftable for Sh { } } -impl fmt::Debug for Sh { +impl fmt::Debug for Sh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.inner { ShInner::Wsh(ref wsh_inner) => write!(f, "sh({:?})", wsh_inner), @@ -67,7 +67,7 @@ impl fmt::Debug for Sh { } } -impl fmt::Display for Sh { +impl fmt::Display for Sh { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use fmt::Write; let mut wrapped_f = checksum::Formatter::new(f); @@ -117,7 +117,7 @@ impl_from_str!( } ); -impl Sh { +impl Sh { /// Get the Inner pub fn into_inner(self) -> ShInner { self.inner @@ -278,7 +278,7 @@ impl Sh { } } -impl Sh { +impl Sh { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> ScriptBuf { match self.inner { @@ -418,7 +418,7 @@ impl Sh { } } -impl ForEachKey for Sh { +impl ForEachKey for Sh { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: F) -> bool { match self.inner { ShInner::Wsh(ref wsh) => wsh.for_each_key(pred), @@ -431,8 +431,8 @@ impl ForEachKey for Sh { impl TranslatePk for Sh

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Sh; diff --git a/src/descriptor/sortedmulti.rs b/src/descriptor/sortedmulti.rs index b626c1c9a..01ee071ae 100644 --- a/src/descriptor/sortedmulti.rs +++ b/src/descriptor/sortedmulti.rs @@ -11,27 +11,27 @@ use core::str::FromStr; use bitcoin::script; -use crate::miniscript::context::ScriptContext; +use crate::miniscript::context::Context; use crate::miniscript::decode::Terminal; use crate::miniscript::limits::MAX_PUBKEYS_PER_MULTISIG; use crate::prelude::*; use crate::{ - errstr, expression, policy, script_num_size, Error, ForEachKey, Miniscript, MiniscriptKey, - Satisfier, ToPublicKey, TranslateErr, Translator, + errstr, expression, policy, script_num_size, Error, ForEachKey, Key, Miniscript, Satisfier, + ToPublicKey, TranslateErr, Translator, }; /// Contents of a "sortedmulti" descriptor #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub struct SortedMultiVec { +pub struct SortedMultiVec { /// signatures required pub k: usize, /// public keys inside sorted Multi pub pks: Vec, - /// The current ScriptContext for sortedmulti + /// The current Context for sortedmulti pub(crate) phantom: PhantomData, } -impl SortedMultiVec { +impl SortedMultiVec { /// Create a new instance of `SortedMultiVec` given a list of keys and the threshold /// /// Internally checks all the applicable size limits and pubkey types limitations according to the current `Ctx`. @@ -89,7 +89,7 @@ impl SortedMultiVec { ) -> Result, TranslateErr> where T: Translator, - Q: MiniscriptKey, + Q: Key, { let pks: Result, _> = self.pks.iter().map(|pk| t.pk(pk)).collect(); let res = SortedMultiVec::new(self.k, pks?).map_err(TranslateErr::OuterError)?; @@ -97,13 +97,13 @@ impl SortedMultiVec { } } -impl ForEachKey for SortedMultiVec { +impl ForEachKey for SortedMultiVec { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: F) -> bool { self.pks.iter().all(pred) } } -impl SortedMultiVec { +impl SortedMultiVec { /// utility function to sanity a sorted multi vec pub fn sanity_check(&self) -> Result<(), Error> { let ms: Miniscript = @@ -115,7 +115,7 @@ impl SortedMultiVec { } } -impl SortedMultiVec { +impl SortedMultiVec { /// Create Terminal::Multi containing sorted pubkeys pub fn sorted_node(&self) -> Terminal where @@ -193,7 +193,7 @@ impl SortedMultiVec { } } -impl policy::Liftable for SortedMultiVec { +impl policy::Liftable for SortedMultiVec { fn lift(&self) -> Result, Error> { let ret = policy::semantic::Policy::Threshold( self.k, @@ -206,13 +206,13 @@ impl policy::Liftable for SortedMulti } } -impl fmt::Debug for SortedMultiVec { +impl fmt::Debug for SortedMultiVec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } -impl fmt::Display for SortedMultiVec { +impl fmt::Display for SortedMultiVec { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "sortedmulti({}", self.k)?; for k in &self.pks { diff --git a/src/descriptor/tr.rs b/src/descriptor/tr.rs index 23c1742d0..ce82601a7 100644 --- a/src/descriptor/tr.rs +++ b/src/descriptor/tr.rs @@ -18,15 +18,15 @@ use crate::policy::Liftable; use crate::prelude::*; use crate::util::{varint_len, witness_size}; use crate::{ - errstr, Error, ForEachKey, MiniscriptKey, Satisfier, ScriptContext, Tap, ToPublicKey, - TranslateErr, TranslatePk, Translator, + errstr, Context, Error, ForEachKey, Key, Satisfier, Tap, ToPublicKey, TranslateErr, + TranslatePk, Translator, }; /// A Taproot Tree representation. // Hidden leaves are not yet supported in descriptor spec. Conceptually, it should // be simple to integrate those here, but it is best to wait on core for the exact syntax. #[derive(Clone, Ord, PartialOrd, Eq, PartialEq, Hash)] -pub enum TapTree { +pub enum TapTree { /// A taproot tree structure Tree { /// Left tree branch. @@ -44,7 +44,7 @@ pub enum TapTree { } /// A taproot descriptor -pub struct Tr { +pub struct Tr { /// A taproot internal key internal_key: Pk, /// Optional Taproot Tree with spending conditions @@ -59,7 +59,7 @@ pub struct Tr { spend_info: Mutex>>, } -impl Clone for Tr { +impl Clone for Tr { fn clone(&self) -> Self { // When cloning, construct a new Mutex so that distinct clones don't // cause blocking between each other. We clone only the internal `Arc`, @@ -78,15 +78,15 @@ impl Clone for Tr { } } -impl PartialEq for Tr { +impl PartialEq for Tr { fn eq(&self, other: &Self) -> bool { self.internal_key == other.internal_key && self.tree == other.tree } } -impl Eq for Tr {} +impl Eq for Tr {} -impl PartialOrd for Tr { +impl PartialOrd for Tr { fn partial_cmp(&self, other: &Self) -> Option { match self.internal_key.partial_cmp(&other.internal_key) { Some(cmp::Ordering::Equal) => {} @@ -96,7 +96,7 @@ impl PartialOrd for Tr { } } -impl Ord for Tr { +impl Ord for Tr { fn cmp(&self, other: &Self) -> cmp::Ordering { match self.internal_key.cmp(&other.internal_key) { cmp::Ordering::Equal => {} @@ -106,14 +106,14 @@ impl Ord for Tr { } } -impl hash::Hash for Tr { +impl hash::Hash for Tr { fn hash(&self, state: &mut H) { self.internal_key.hash(state); self.tree.hash(state); } } -impl TapTree { +impl TapTree { /// Creates a `TapTree` by combining `left` and `right` tree nodes. pub(crate) fn combine(left: TapTree, right: TapTree) -> Self { let height = 1 + cmp::max(left.height(), right.height()); @@ -148,7 +148,7 @@ impl TapTree { fn translate_helper(&self, t: &mut T) -> Result, TranslateErr> where T: Translator, - Q: MiniscriptKey, + Q: Key, { let frag = match *self { TapTree::Tree { @@ -166,7 +166,7 @@ impl TapTree { } } -impl fmt::Display for TapTree { +impl fmt::Display for TapTree { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { TapTree::Tree { @@ -179,7 +179,7 @@ impl fmt::Display for TapTree { } } -impl fmt::Debug for TapTree { +impl fmt::Debug for TapTree { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { TapTree::Tree { @@ -192,7 +192,7 @@ impl fmt::Debug for TapTree { } } -impl Tr { +impl Tr { /// Create a new [`Tr`] descriptor from internal key and [`TapTree`] pub fn new(internal_key: Pk, tree: Option>) -> Result { Tap::check_pk(&internal_key)?; @@ -378,7 +378,7 @@ impl Tr { } } -impl Tr { +impl Tr { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> ScriptBuf { let output_key = self.spend_info().output_key(); @@ -429,13 +429,13 @@ impl Tr { /// would yield (2, A), (2, B), (2,C), (3, D), (3, E). /// #[derive(Debug, Clone)] -pub struct TapTreeIter<'a, Pk: MiniscriptKey> { +pub struct TapTreeIter<'a, Pk: Key> { stack: Vec<(u8, &'a TapTree)>, } impl<'a, Pk> Iterator for TapTreeIter<'a, Pk> where - Pk: MiniscriptKey + 'a, + Pk: Key + 'a, { type Item = (u8, &'a Miniscript); @@ -533,7 +533,7 @@ impl_from_str!( } ); -impl fmt::Debug for Tr { +impl fmt::Debug for Tr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.tree { Some(ref s) => write!(f, "tr({:?},{:?})", self.internal_key, s), @@ -542,7 +542,7 @@ impl fmt::Debug for Tr { } } -impl fmt::Display for Tr { +impl fmt::Display for Tr { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use fmt::Write; let mut wrapped_f = checksum::Formatter::new(f); @@ -625,9 +625,9 @@ fn split_once(inp: &str, delim: char) -> Option<(&str, &str)> { } } -impl Liftable for TapTree { +impl Liftable for TapTree { fn lift(&self) -> Result, Error> { - fn lift_helper(s: &TapTree) -> Result, Error> { + fn lift_helper(s: &TapTree) -> Result, Error> { match *s { TapTree::Tree { ref left, @@ -646,7 +646,7 @@ impl Liftable for TapTree { } } -impl Liftable for Tr { +impl Liftable for Tr { fn lift(&self) -> Result, Error> { match &self.tree { Some(root) => Ok(Policy::Threshold( @@ -658,7 +658,7 @@ impl Liftable for Tr { } } -impl ForEachKey for Tr { +impl ForEachKey for Tr { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { let script_keys_res = self .iter_scripts() @@ -669,8 +669,8 @@ impl ForEachKey for Tr { impl TranslatePk for Tr

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Tr; diff --git a/src/interpreter/inner.rs b/src/interpreter/inner.rs index 266670eaf..10c6a2cd3 100644 --- a/src/interpreter/inner.rs +++ b/src/interpreter/inner.rs @@ -6,7 +6,7 @@ use bitcoin::taproot::{ControlBlock, TAPROOT_ANNEX_PREFIX}; use bitcoin::Witness; use super::{stack, BitcoinKey, Error, Stack}; -use crate::miniscript::context::{NoChecks, ScriptContext, SigType}; +use crate::miniscript::context::{Context, NoChecks, SigType}; use crate::prelude::*; use crate::{BareCtx, ExtParams, Legacy, Miniscript, Segwitv0, Tap, ToPublicKey, Translator}; @@ -38,7 +38,7 @@ fn pk_from_stack_elem( // Parse the script with appropriate context to check for context errors like // correct usage of x-only keys or multi_a -fn script_from_stack_elem( +fn script_from_stack_elem( elem: &stack::Element<'_>, ) -> Result, Error> { match *elem { @@ -368,7 +368,7 @@ pub(super) trait ToNoChecks { fn to_no_checks_ms(&self) -> Miniscript; } -impl ToNoChecks for Miniscript { +impl ToNoChecks for Miniscript { fn to_no_checks_ms(&self) -> Miniscript { struct TranslateFullPk; @@ -385,7 +385,7 @@ impl ToNoChecks for Miniscript { } } -impl ToNoChecks for Miniscript { +impl ToNoChecks for Miniscript { fn to_no_checks_ms(&self) -> Miniscript { // specify the () error type as this cannot error struct TranslateXOnlyPk; diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index 37cd457fa..794b73cee 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -15,7 +15,7 @@ use bitcoin::hashes::{hash160, ripemd160, sha256, Hash}; use bitcoin::{absolute, secp256k1, sighash, taproot, Sequence, TxOut, Witness}; use crate::miniscript::context::{NoChecks, SigType}; -use crate::miniscript::ScriptContext; +use crate::miniscript::Context; use crate::prelude::*; use crate::{hash256, Descriptor, Miniscript, Terminal, ToPublicKey}; @@ -26,7 +26,7 @@ mod stack; pub use self::error::Error; use self::error::PkEvalErrInner; use self::stack::Stack; -use crate::MiniscriptKey; +use crate::Key; /// An iterable Miniscript-structured representation of the spending of a coin pub struct Interpreter<'txin> { @@ -72,15 +72,15 @@ impl KeySigPair { } // Internally used enum for different types of bitcoin keys -// Even though we implement MiniscriptKey for BitcoinKey, we make sure that there +// Even though we implement Key for BitcoinKey, we make sure that there // are little mis-use // - The only constructors for this are only called in from_txdata that take care // using the correct enum variant // - This does not implement ToPublicKey to avoid context dependant encoding/decoding of 33/32 // byte keys. This allows us to keep a single NoChecks context instead of a context for // for NoChecksSchnorr/NoChecksEcdsa. -// Long term TODO: There really should be not be any need for Miniscript struct -// to have the Pk: MiniscriptKey bound. The bound should be on all of it's methods. That would +// Long term TODO: There really should be not be any need for Miniscript struct +// to have the Pk: Key bound. The bound should be on all of it's methods. That would // require changing Miniscript struct to three generics Miniscript and bound on // all of the methods of Miniscript to ensure that Pkh = Pk::Hash #[derive(Hash, Eq, Ord, PartialEq, PartialOrd, Clone, Copy, Debug)] @@ -122,7 +122,7 @@ impl From for BitcoinKey { } } -impl MiniscriptKey for BitcoinKey { +impl Key for BitcoinKey { type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; type Ripemd160 = ripemd160::Hash; @@ -536,7 +536,7 @@ pub struct Iter<'intp, 'txin: 'intp> { ///Iterator for Iter impl<'intp, 'txin: 'intp> Iterator for Iter<'intp, 'txin> where - NoChecks: ScriptContext, + NoChecks: Context, { type Item = Result; @@ -556,7 +556,7 @@ where impl<'intp, 'txin: 'intp> Iter<'intp, 'txin> where - NoChecks: ScriptContext, + NoChecks: Context, { /// Helper function to push a NodeEvaluationState on state stack fn push_evaluation_state( diff --git a/src/iter/mod.rs b/src/iter/mod.rs index 02e59b6e2..46af5ab52 100644 --- a/src/iter/mod.rs +++ b/src/iter/mod.rs @@ -15,9 +15,9 @@ pub use tree::{ }; use crate::sync::Arc; -use crate::{Miniscript, MiniscriptKey, ScriptContext, Terminal}; +use crate::{Context, Key, Miniscript, Terminal}; -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> TreeLike for &'a Miniscript { +impl<'a, Pk: Key, Ctx: Context> TreeLike for &'a Miniscript { fn as_node(&self) -> Tree { use Terminal::*; match self.node { @@ -42,7 +42,7 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> TreeLike for &'a Miniscript TreeLike for Arc> { +impl TreeLike for Arc> { fn as_node(&self) -> Tree { use Terminal::*; match self.node { diff --git a/src/lib.rs b/src/lib.rs index 707b496c5..1acc8ac8b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -144,14 +144,14 @@ use bitcoin::locktime::absolute; pub use crate::descriptor::{DefiniteDescriptorKey, Descriptor, DescriptorPublicKey}; pub use crate::interpreter::Interpreter; pub use crate::miniscript::analyzable::{AnalysisError, ExtParams}; -pub use crate::miniscript::context::{BareCtx, Legacy, ScriptContext, Segwitv0, SigType, Tap}; +pub use crate::miniscript::context::{BareCtx, Context, Legacy, Segwitv0, SigType, Tap}; pub use crate::miniscript::decode::Terminal; pub use crate::miniscript::satisfy::{Preimage32, Satisfier}; pub use crate::miniscript::{hash256, Miniscript}; use crate::prelude::*; ///Public key trait which can be converted to Hash type -pub trait MiniscriptKey: Clone + Eq + Ord + fmt::Debug + fmt::Display + hash::Hash { +pub trait Key: Clone + Eq + Ord + fmt::Debug + fmt::Display + hash::Hash { /// Returns true if the pubkey is uncompressed. Defaults to `false`. fn is_uncompressed(&self) -> bool { false @@ -170,31 +170,31 @@ pub trait MiniscriptKey: Clone + Eq + Ord + fmt::Debug + fmt::Display + hash::Ha 0 } - /// The associated [`bitcoin::hashes::sha256::Hash`] for this [`MiniscriptKey`], used in the + /// The associated [`bitcoin::hashes::sha256::Hash`] for this [`Key`], used in the /// sha256 fragment. type Sha256: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; - /// The associated [`miniscript::hash256::Hash`] for this [`MiniscriptKey`], used in the + /// The associated [`miniscript::hash256::Hash`] for this [`Key`], used in the /// hash256 fragment. type Hash256: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; - /// The associated [`bitcoin::hashes::ripemd160::Hash`] for this [`MiniscriptKey`] type, used + /// The associated [`bitcoin::hashes::ripemd160::Hash`] for this [`Key`] type, used /// in the ripemd160 fragment. type Ripemd160: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; - /// The associated [`bitcoin::hashes::hash160::Hash`] for this [`MiniscriptKey`] type, used in + /// The associated [`bitcoin::hashes::hash160::Hash`] for this [`Key`] type, used in /// the hash160 fragment. type Hash160: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; } -impl MiniscriptKey for bitcoin::secp256k1::PublicKey { +impl Key for bitcoin::secp256k1::PublicKey { type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; type Ripemd160 = ripemd160::Hash; type Hash160 = hash160::Hash; } -impl MiniscriptKey for bitcoin::PublicKey { +impl Key for bitcoin::PublicKey { /// Returns the compressed-ness of the underlying secp256k1 key. fn is_uncompressed(&self) -> bool { !self.compressed @@ -206,7 +206,7 @@ impl MiniscriptKey for bitcoin::PublicKey { type Hash160 = hash160::Hash; } -impl MiniscriptKey for bitcoin::secp256k1::XOnlyPublicKey { +impl Key for bitcoin::secp256k1::XOnlyPublicKey { type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; type Ripemd160 = ripemd160::Hash; @@ -217,7 +217,7 @@ impl MiniscriptKey for bitcoin::secp256k1::XOnlyPublicKey { } } -impl MiniscriptKey for String { +impl Key for String { type Sha256 = String; // specify hashes as string type Hash256 = String; type Ripemd160 = String; @@ -225,7 +225,7 @@ impl MiniscriptKey for String { } /// Trait describing public key types which can be converted to bitcoin pubkeys -pub trait ToPublicKey: MiniscriptKey { +pub trait ToPublicKey: Key { /// Converts an object to a public key fn to_public_key(&self) -> bitcoin::PublicKey; @@ -235,7 +235,7 @@ pub trait ToPublicKey: MiniscriptKey { bitcoin::secp256k1::XOnlyPublicKey::from(pk.inner) } - /// Obtain the public key hash for this MiniscriptKey + /// Obtain the public key hash for this Key /// Expects an argument to specify the signature type. /// This would determine whether to serialize the key as 32 byte x-only pubkey /// or regular public key when computing the hash160 @@ -246,17 +246,17 @@ pub trait ToPublicKey: MiniscriptKey { } } - /// Converts the generic associated [`MiniscriptKey::Sha256`] to [`sha256::Hash`] - fn to_sha256(hash: &::Sha256) -> sha256::Hash; + /// Converts the generic associated [`Key::Sha256`] to [`sha256::Hash`] + fn to_sha256(hash: &::Sha256) -> sha256::Hash; - /// Converts the generic associated [`MiniscriptKey::Hash256`] to [`hash256::Hash`] - fn to_hash256(hash: &::Hash256) -> hash256::Hash; + /// Converts the generic associated [`Key::Hash256`] to [`hash256::Hash`] + fn to_hash256(hash: &::Hash256) -> hash256::Hash; - /// Converts the generic associated [`MiniscriptKey::Ripemd160`] to [`ripemd160::Hash`] - fn to_ripemd160(hash: &::Ripemd160) -> ripemd160::Hash; + /// Converts the generic associated [`Key::Ripemd160`] to [`ripemd160::Hash`] + fn to_ripemd160(hash: &::Ripemd160) -> ripemd160::Hash; - /// Converts the generic associated [`MiniscriptKey::Hash160`] to [`hash160::Hash`] - fn to_hash160(hash: &::Hash160) -> hash160::Hash; + /// Converts the generic associated [`Key::Hash160`] to [`hash160::Hash`] + fn to_hash160(hash: &::Hash160) -> hash160::Hash; } impl ToPublicKey for bitcoin::PublicKey { @@ -338,8 +338,8 @@ impl ToPublicKey for bitcoin::secp256k1::XOnlyPublicKey { /// associated with the other key. Used by the [`TranslatePk`] trait to do the actual translations. pub trait Translator where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { /// Translates public keys P -> Q. fn pk(&mut self, pk: &P) -> Result; @@ -412,8 +412,8 @@ impl fmt::Debug for TranslateErr { /// the actual translation function calls. pub trait TranslatePk where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { /// The associated output type. This must be `Self`. type Output; @@ -426,9 +426,9 @@ where } /// Either a key or keyhash, but both contain Pk -// pub struct ForEach<'a, Pk: MiniscriptKey>(&'a Pk); +// pub struct ForEach<'a, Pk: Key>(&'a Pk); -// impl<'a, Pk: MiniscriptKey> ForEach<'a, Pk> { +// impl<'a, Pk: Key> ForEach<'a, Pk> { // /// Convenience method to avoid distinguishing between keys and hashes when these are the same type // pub fn as_key(&self) -> &'a Pk { // self.0 @@ -436,7 +436,7 @@ where // } /// Trait describing the ability to iterate over every key -pub trait ForEachKey { +pub trait ForEachKey { /// Run a predicate on every key in the descriptor, returning whether /// the predicate returned true for every key fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: F) -> bool @@ -520,7 +520,7 @@ pub enum Error { /// Errors related to lifting LiftError(policy::LiftError), /// Forward script context related errors - ContextError(miniscript::context::ScriptContextError), + ContextError(miniscript::context::ContextError), /// Recursion depth exceeded when parsing policy/miniscript from string MaxRecursiveDepthExceeded, /// Script size too large @@ -681,8 +681,8 @@ impl error::Error for Error { #[doc(hidden)] impl From> for Error where - Pk: MiniscriptKey, - Ctx: ScriptContext, + Pk: Key, + Ctx: Context, { fn from(e: miniscript::types::Error) -> Error { Error::TypeCheck(e.to_string()) @@ -697,8 +697,8 @@ impl From for Error { } #[doc(hidden)] -impl From for Error { - fn from(e: miniscript::context::ScriptContextError) -> Error { +impl From for Error { + fn from(e: miniscript::context::ContextError) -> Error { Error::ContextError(e) } } diff --git a/src/macros.rs b/src/macros.rs index 6d4b9156b..115aac32a 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -28,16 +28,16 @@ macro_rules! impl_from_tree { ) => { impl $crate::expression::FromTree for $name where - Pk: MiniscriptKey + core::str::FromStr, + Pk: Key + core::str::FromStr, Pk::Sha256: core::str::FromStr, Pk::Hash256: core::str::FromStr, Pk::Ripemd160: core::str::FromStr, Pk::Hash160: core::str::FromStr, ::Err: $crate::prelude::ToString, - <::Sha256 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Hash256 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Ripemd160 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Hash160 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Sha256 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Hash256 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Ripemd160 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Hash160 as core::str::FromStr>::Err: $crate::prelude::ToString, $($gen : $gen_con,)* { @@ -60,16 +60,16 @@ macro_rules! impl_from_str { ) => { impl core::str::FromStr for $name where - Pk: MiniscriptKey + core::str::FromStr, + Pk: Key + core::str::FromStr, Pk::Sha256: core::str::FromStr, Pk::Hash256: core::str::FromStr, Pk::Ripemd160: core::str::FromStr, Pk::Hash160: core::str::FromStr, ::Err: $crate::prelude::ToString, - <::Sha256 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Hash256 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Ripemd160 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Hash160 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Sha256 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Hash256 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Ripemd160 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Hash160 as core::str::FromStr>::Err: $crate::prelude::ToString, $($gen : $gen_con,)* { type Err = $err_ty; @@ -92,16 +92,16 @@ macro_rules! impl_block_str { ) => { impl $name where - Pk: MiniscriptKey + core::str::FromStr, + Pk: Key + core::str::FromStr, Pk::Sha256: core::str::FromStr, Pk::Hash256: core::str::FromStr, Pk::Ripemd160: core::str::FromStr, Pk::Hash160: core::str::FromStr, ::Err: $crate::prelude::ToString, - <::Sha256 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Hash256 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Ripemd160 as core::str::FromStr>::Err: $crate::prelude::ToString, - <::Hash160 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Sha256 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Hash256 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Ripemd160 as core::str::FromStr>::Err: $crate::prelude::ToString, + <::Hash160 as core::str::FromStr>::Err: $crate::prelude::ToString, $($gen : $gen_con,)* { $(#[$meta])* @@ -119,19 +119,19 @@ macro_rules! serde_string_impl_pk { #[cfg(feature = "serde")] impl<'de, Pk $(, $gen)*> $crate::serde::Deserialize<'de> for $name where - Pk: $crate::MiniscriptKey + core::str::FromStr, + Pk: $crate::Key + core::str::FromStr, Pk::Sha256: core::str::FromStr, Pk::Hash256: core::str::FromStr, Pk::Ripemd160: core::str::FromStr, Pk::Hash160: core::str::FromStr, ::Err: core::fmt::Display, - <::Sha256 as core::str::FromStr>::Err: + <::Sha256 as core::str::FromStr>::Err: core::fmt::Display, - <::Hash256 as core::str::FromStr>::Err: + <::Hash256 as core::str::FromStr>::Err: core::fmt::Display, - <::Ripemd160 as core::str::FromStr>::Err: + <::Ripemd160 as core::str::FromStr>::Err: core::fmt::Display, - <::Hash160 as core::str::FromStr>::Err: + <::Hash160 as core::str::FromStr>::Err: core::fmt::Display, $($gen : $gen_con,)* { @@ -147,19 +147,19 @@ macro_rules! serde_string_impl_pk { struct Visitor(PhantomData<(Pk $(, $gen)*)>); impl<'de, Pk $(, $gen)*> $crate::serde::de::Visitor<'de> for Visitor where - Pk: $crate::MiniscriptKey + core::str::FromStr, + Pk: $crate::Key + core::str::FromStr, Pk::Sha256: core::str::FromStr, Pk::Hash256: core::str::FromStr, Pk::Ripemd160: core::str::FromStr, Pk::Hash160: core::str::FromStr, ::Err: core::fmt::Display, - <::Sha256 as core::str::FromStr>::Err: + <::Sha256 as core::str::FromStr>::Err: core::fmt::Display, - <::Hash256 as core::str::FromStr>::Err: + <::Hash256 as core::str::FromStr>::Err: core::fmt::Display, - <::Ripemd160 as core::str::FromStr>::Err: + <::Ripemd160 as core::str::FromStr>::Err: core::fmt::Display, - <::Hash160 as core::str::FromStr>::Err: + <::Hash160 as core::str::FromStr>::Err: core::fmt::Display, $($gen: $gen_con,)* { @@ -198,7 +198,7 @@ macro_rules! serde_string_impl_pk { #[cfg(feature = "serde")] impl<'de, Pk $(, $gen)*> $crate::serde::Serialize for $name where - Pk: $crate::MiniscriptKey, + Pk: $crate::Key, $($gen: $gen_con,)* { fn serialize(&self, serializer: S) -> Result diff --git a/src/miniscript/analyzable.rs b/src/miniscript/analyzable.rs index 4c30e7df9..f2bbe3f73 100644 --- a/src/miniscript/analyzable.rs +++ b/src/miniscript/analyzable.rs @@ -10,7 +10,7 @@ use core::fmt; use std::error; use crate::prelude::*; -use crate::{Miniscript, MiniscriptKey, ScriptContext, Terminal}; +use crate::{Context, Key, Miniscript, Terminal}; /// Params for parsing miniscripts that either non-sane or non-specified(experimental) in the spec. /// Used as a parameter [`Miniscript::from_str_ext`] and [`Miniscript::parse_with_ext`]. @@ -184,7 +184,7 @@ impl error::Error for AnalysisError { } } -impl Miniscript { +impl Miniscript { /// Whether all spend paths of miniscript require a signature pub fn requires_sig(&self) -> bool { self.ty.mall.safe diff --git a/src/miniscript/astelem.rs b/src/miniscript/astelem.rs index c7d403679..315a2e22a 100644 --- a/src/miniscript/astelem.rs +++ b/src/miniscript/astelem.rs @@ -16,14 +16,12 @@ use sync::Arc; use crate::miniscript::context::SigType; use crate::miniscript::types::{self, Property}; -use crate::miniscript::ScriptContext; +use crate::miniscript::Context; use crate::prelude::*; use crate::util::MsKeyBuilder; -use crate::{ - errstr, expression, AbsLockTime, Error, Miniscript, MiniscriptKey, Terminal, ToPublicKey, -}; +use crate::{errstr, expression, AbsLockTime, Error, Key, Miniscript, Terminal, ToPublicKey}; -impl Terminal { +impl Terminal { /// Internal helper function for displaying wrapper types; returns /// a character to display before the `:` as well as a reference /// to the wrapped type to allow easy recursion @@ -44,7 +42,7 @@ impl Terminal { } } -impl fmt::Debug for Terminal { +impl fmt::Debug for Terminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("[")?; if let Ok(type_map) = types::Type::type_check(self, |_| None) { @@ -142,7 +140,7 @@ impl fmt::Debug for Terminal { } } -impl fmt::Display for Terminal { +impl fmt::Display for Terminal { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Terminal::PkK(ref pk) => write!(f, "pk_k({})", pk), @@ -242,7 +240,7 @@ impl fmt::Display for Terminal { } impl_from_tree!( - ;Ctx; ScriptContext, + ;Ctx; Context, Arc>, fn from_tree(top: &expression::Tree) -> Result>, Error> { Ok(Arc::new(expression::FromTree::from_tree(top)?)) @@ -250,7 +248,7 @@ impl_from_tree!( ); impl_from_tree!( - ;Ctx; ScriptContext, + ;Ctx; Context, Terminal, fn from_tree(top: &expression::Tree) -> Result, Error> { let mut aliased_wrap; @@ -431,13 +429,13 @@ impl_from_tree!( ); /// Helper trait to add a `push_astelem` method to `script::Builder` -trait PushAstElem { +trait PushAstElem { fn push_astelem(self, ast: &Miniscript) -> Self where Pk: ToPublicKey; } -impl PushAstElem for script::Builder { +impl PushAstElem for script::Builder { fn push_astelem(self, ast: &Miniscript) -> Self where Pk: ToPublicKey, @@ -446,7 +444,7 @@ impl PushAstElem for script::Bui } } -impl Terminal { +impl Terminal { /// Encode the element as a fragment of Bitcoin Script. The inverse /// function, from Script to an AST element, is implemented in the /// `parse` module. diff --git a/src/miniscript/context.rs b/src/miniscript/context.rs index f3563b83c..589cfdf86 100644 --- a/src/miniscript/context.rs +++ b/src/miniscript/context.rs @@ -17,11 +17,11 @@ use crate::miniscript::limits::{ use crate::miniscript::types; use crate::prelude::*; use crate::util::witness_to_scriptsig; -use crate::{hash256, Error, ForEachKey, Miniscript, MiniscriptKey, Terminal}; +use crate::{hash256, Error, ForEachKey, Key, Miniscript, Terminal}; /// Error for Script Context #[derive(Clone, PartialEq, Eq, Debug)] -pub enum ScriptContextError { +pub enum ContextError { /// Script Context does not permit PkH for non-malleability /// It is not possible to estimate the pubkey size at the creation /// time because of uncompressed pubkeys @@ -68,9 +68,9 @@ pub enum ScriptContextError { } #[cfg(feature = "std")] -impl error::Error for ScriptContextError { +impl error::Error for ContextError { fn cause(&self) -> Option<&dyn error::Error> { - use self::ScriptContextError::*; + use self::ContextError::*; match self { MalleablePkH @@ -93,100 +93,100 @@ impl error::Error for ScriptContextError { } } -impl fmt::Display for ScriptContextError { +impl fmt::Display for ContextError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ScriptContextError::MalleablePkH => write!(f, "PkH is malleable under Legacy rules"), - ScriptContextError::MalleableOrI => write!(f, "OrI is malleable under Legacy rules"), - ScriptContextError::MalleableDupIf => { + ContextError::MalleablePkH => write!(f, "PkH is malleable under Legacy rules"), + ContextError::MalleableOrI => write!(f, "OrI is malleable under Legacy rules"), + ContextError::MalleableDupIf => { write!(f, "DupIf is malleable under Legacy rules") } - ScriptContextError::CompressedOnly(ref pk) => { + ContextError::CompressedOnly(ref pk) => { write!( f, "Only Compressed pubkeys are allowed in segwit context. Found {}", pk ) } - ScriptContextError::XOnlyKeysNotAllowed(ref pk, ref ctx) => { + ContextError::XOnlyKeysNotAllowed(ref pk, ref ctx) => { write!(f, "x-only key {} not allowed in {}", pk, ctx) } - ScriptContextError::UncompressedKeysNotAllowed => { + ContextError::UncompressedKeysNotAllowed => { write!( f, "uncompressed keys cannot be used in Taproot descriptors." ) } - ScriptContextError::MaxWitnessItemssExceeded { actual, limit } => write!( + ContextError::MaxWitnessItemssExceeded { actual, limit } => write!( f, "At least one spending path in the Miniscript fragment has {} more \ witness items than limit {}.", actual, limit ), - ScriptContextError::MaxOpCountExceeded => write!( + ContextError::MaxOpCountExceeded => write!( f, "At least one satisfaction path in the Miniscript fragment contains \ more than MAX_OPS_PER_SCRIPT opcodes." ), - ScriptContextError::MaxWitnessScriptSizeExceeded => write!( + ContextError::MaxWitnessScriptSizeExceeded => write!( f, "The Miniscript corresponding Script would be larger than \ MAX_STANDARD_P2WSH_SCRIPT_SIZE bytes." ), - ScriptContextError::MaxRedeemScriptSizeExceeded => write!( + ContextError::MaxRedeemScriptSizeExceeded => write!( f, "The Miniscript corresponding Script would be larger than \ MAX_SCRIPT_ELEMENT_SIZE bytes." ), - ScriptContextError::MaxScriptSigSizeExceeded => write!( + ContextError::MaxScriptSigSizeExceeded => write!( f, "At least one satisfaction in Miniscript would be larger than \ MAX_SCRIPTSIG_SIZE scriptsig" ), - ScriptContextError::ImpossibleSatisfaction => { + ContextError::ImpossibleSatisfaction => { write!( f, "Impossible to satisfy Miniscript under the current context" ) } - ScriptContextError::TaprootMultiDisabled => { + ContextError::TaprootMultiDisabled => { write!(f, "Invalid use of Multi node in taproot context") } - ScriptContextError::StackSizeLimitExceeded { actual, limit } => { + ContextError::StackSizeLimitExceeded { actual, limit } => { write!( f, "Stack limit {} can exceed the allowed limit {} in at least one script path during script execution", actual, limit ) } - ScriptContextError::CheckMultiSigLimitExceeded => { + ContextError::CheckMultiSigLimitExceeded => { write!( f, "CHECkMULTISIG ('multi()' descriptor) only supports up to 20 pubkeys" ) } - ScriptContextError::MultiANotAllowed => { + ContextError::MultiANotAllowed => { write!(f, "Multi a(CHECKSIGADD) only allowed post tapscript") } } } } -/// The ScriptContext for Miniscript. Additional type information associated with +/// The Context for Miniscript. Additional type information associated with /// miniscript that is used for carrying out checks that dependent on the /// context under which the script is used. /// For example, disallowing uncompressed keys in Segwit context -pub trait ScriptContext: +pub trait Context: fmt::Debug + Clone + Ord + PartialOrd + Eq + PartialEq + hash::Hash + private::Sealed where - Self::Key: MiniscriptKey, - Self::Key: MiniscriptKey, - Self::Key: MiniscriptKey, - Self::Key: MiniscriptKey, + Self::Key: Key, + Self::Key: Key, + Self::Key: Key, + Self::Key: Key, { /// The consensus key associated with the type. Must be a parseable key type Key: ParseableKey; - /// Depending on ScriptContext, fragments can be malleable. For Example, + /// Depending on Context, fragments can be malleable. For Example, /// under Legacy context, PkH is malleable because it is possible to /// estimate the cost of satisfaction because of compressed keys /// This is currently only used in compiler code for removing malleable @@ -194,14 +194,14 @@ where /// This does NOT recursively check if the children of the fragment are /// valid or not. Since the compilation proceeds in a leaf to root fashion, /// a recursive check is unnecessary. - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( _frag: &Terminal, - ) -> Result<(), ScriptContextError>; + ) -> Result<(), ContextError>; - /// Check whether the given satisfaction is valid under the ScriptContext + /// Check whether the given satisfaction is valid under the Context /// For example, segwit satisfactions may fail if the witness len is more /// 3600 or number of stack elements are more than 100. - fn check_witness(_witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(_witness: &[Vec]) -> Result<(), ContextError> { // Only really need to do this for segwitv0 and legacy // Bare is already restrcited by standardness rules // and would reach these limits. @@ -212,23 +212,23 @@ where /// Legacy/Bare does not allow x_only keys /// Segwit does not allow uncompressed keys and x_only keys /// Tapscript does not allow uncompressed keys - fn check_pk(pk: &Pk) -> Result<(), ScriptContextError>; + fn check_pk(pk: &Pk) -> Result<(), ContextError>; /// Depending on script context, the size of a satifaction witness may slightly differ. - fn max_satisfaction_size(ms: &Miniscript) -> Option; + fn max_satisfaction_size(ms: &Miniscript) -> Option; /// Depending on script Context, some of the Terminals might not /// be valid under the current consensus rules. /// Or some of the script resource limits may have been exceeded. /// These miniscripts would never be accepted by the Bitcoin network and hence /// it is safe to discard them - /// For example, in Segwit Context with MiniscriptKey as bitcoin::PublicKey + /// For example, in Segwit Context with Key as bitcoin::PublicKey /// uncompressed public keys are non-standard and thus invalid. /// In LegacyP2SH context, scripts above 520 bytes are invalid. /// Post Tapscript upgrade, this would have to consider other nodes. /// This does *NOT* recursively check the miniscript fragments. - fn check_global_consensus_validity( + fn check_global_consensus_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } @@ -236,13 +236,13 @@ where /// may have been exceeded under the current bitcoin core policy rules /// These miniscripts would never be accepted by the Bitcoin network and hence /// it is safe to discard them. (unless explicitly disabled by non-standard flag) - /// For example, in Segwit Context with MiniscriptKey as bitcoin::PublicKey + /// For example, in Segwit Context with Key as bitcoin::PublicKey /// scripts over 3600 bytes are invalid. /// Post Tapscript upgrade, this would have to consider other nodes. /// This does *NOT* recursively check the miniscript fragments. - fn check_global_policy_validity( + fn check_global_policy_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } @@ -250,9 +250,9 @@ where /// It is possible that some paths of miniscript may exceed resource limits /// and our current satisfier and lifting analysis would not work correctly. /// For example, satisfaction path(Legacy/Segwitv0) may require more than 201 opcodes. - fn check_local_consensus_validity( + fn check_local_consensus_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } @@ -261,17 +261,15 @@ where /// and our current satisfier and lifting analysis would not work correctly. /// For example, satisfaction path in Legacy context scriptSig more /// than 1650 bytes - fn check_local_policy_validity( + fn check_local_policy_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } /// Check the consensus + policy(if not disabled) rules that are not based /// satisfaction - fn check_global_validity( - ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + fn check_global_validity(ms: &Miniscript) -> Result<(), ContextError> { Self::check_global_consensus_validity(ms)?; Self::check_global_policy_validity(ms)?; Ok(()) @@ -279,9 +277,7 @@ where /// Check the consensus + policy(if not disabled) rules including the /// ones for satisfaction - fn check_local_validity( - ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + fn check_local_validity(ms: &Miniscript) -> Result<(), ContextError> { Self::check_global_consensus_validity(ms)?; Self::check_global_policy_validity(ms)?; Self::check_local_consensus_validity(ms)?; @@ -290,7 +286,7 @@ where } /// Check whether the top-level is type B - fn top_level_type_check(ms: &Miniscript) -> Result<(), Error> { + fn top_level_type_check(ms: &Miniscript) -> Result<(), Error> { if ms.ty.corr.base != types::Base::B { return Err(Error::NonTopLevel(format!("{:?}", ms))); } @@ -328,7 +324,7 @@ where } /// Other top level checks that are context specific - fn other_top_level_checks(_ms: &Miniscript) -> Result<(), Error> { + fn other_top_level_checks(_ms: &Miniscript) -> Result<(), Error> { Ok(()) } @@ -341,7 +337,7 @@ where // that are only applicable at the top-level // We can also combine the top-level check for Base::B here // even though it does not depend on context, but helps in cleaner code - fn top_level_checks(ms: &Miniscript) -> Result<(), Error> { + fn top_level_checks(ms: &Miniscript) -> Result<(), Error> { Self::top_level_type_check(ms)?; Self::other_top_level_checks(ms) } @@ -355,7 +351,7 @@ where /// Note that this includes the serialization prefix. Returns /// 34/66 for Bare/Legacy based on key compressedness /// 34 for Segwitv0, 33 for Tap - fn pk_len(pk: &Pk) -> usize; + fn pk_len(pk: &Pk) -> usize; /// Local helper function to display error messages with context fn name_str() -> &'static str; @@ -370,31 +366,31 @@ pub enum SigType { Schnorr, } -/// Legacy ScriptContext +/// Legacy Context /// To be used as P2SH scripts /// For creation of Bare scriptpubkeys, construct the Miniscript -/// under `Bare` ScriptContext +/// under `Bare` Context #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum Legacy {} -impl ScriptContext for Legacy { +impl Context for Legacy { type Key = bitcoin::PublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( frag: &Terminal, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { match *frag { - Terminal::PkH(ref _pkh) => Err(ScriptContextError::MalleablePkH), - Terminal::RawPkH(ref _pk) => Err(ScriptContextError::MalleablePkH), - Terminal::OrI(ref _a, ref _b) => Err(ScriptContextError::MalleableOrI), - Terminal::DupIf(ref _ms) => Err(ScriptContextError::MalleableDupIf), + Terminal::PkH(ref _pkh) => Err(ContextError::MalleablePkH), + Terminal::RawPkH(ref _pk) => Err(ContextError::MalleablePkH), + Terminal::OrI(ref _a, ref _b) => Err(ContextError::MalleableOrI), + Terminal::DupIf(ref _ms) => Err(ContextError::MalleableDupIf), _ => Ok(()), } } // Only compressed and uncompressed public keys are allowed in Legacy context - fn check_pk(pk: &Pk) -> Result<(), ScriptContextError> { + fn check_pk(pk: &Pk) -> Result<(), ContextError> { if pk.is_x_only_key() { - Err(ScriptContextError::XOnlyKeysNotAllowed( + Err(ContextError::XOnlyKeysNotAllowed( pk.to_string(), Self::name_str(), )) @@ -403,71 +399,67 @@ impl ScriptContext for Legacy { } } - fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(witness: &[Vec]) -> Result<(), ContextError> { // In future, we could avoid by having a function to count only // len of script instead of converting it. if witness_to_scriptsig(witness).len() > MAX_SCRIPTSIG_SIZE { - return Err(ScriptContextError::MaxScriptSigSizeExceeded); + return Err(ContextError::MaxScriptSigSizeExceeded); } Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { if ms.ext.pk_cost > MAX_SCRIPT_ELEMENT_SIZE { - return Err(ScriptContextError::MaxRedeemScriptSizeExceeded); + return Err(ContextError::MaxRedeemScriptSizeExceeded); } match ms.node { Terminal::PkK(ref pk) => Self::check_pk(pk), Terminal::Multi(_k, ref pks) => { if pks.len() > MAX_PUBKEYS_PER_MULTISIG { - return Err(ScriptContextError::CheckMultiSigLimitExceeded); + return Err(ContextError::CheckMultiSigLimitExceeded); } for pk in pks.iter() { Self::check_pk(pk)?; } Ok(()) } - Terminal::MultiA(..) => Err(ScriptContextError::MultiANotAllowed), + Terminal::MultiA(..) => Err(ContextError::MultiANotAllowed), _ => Ok(()), } } - fn check_local_consensus_validity( + fn check_local_consensus_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { match ms.ext.ops.op_count() { - None => Err(ScriptContextError::MaxOpCountExceeded), + None => Err(ContextError::MaxOpCountExceeded), Some(op_count) if op_count > MAX_OPS_PER_SCRIPT => { - Err(ScriptContextError::MaxOpCountExceeded) + Err(ContextError::MaxOpCountExceeded) } _ => Ok(()), } } - fn check_local_policy_validity( - ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + fn check_local_policy_validity(ms: &Miniscript) -> Result<(), ContextError> { // Legacy scripts permit upto 1000 stack elements, 520 bytes consensus limits // on P2SH size, it is not possible to reach the 1000 elements limit and hence // we do not check it. match ms.max_satisfaction_size() { - Err(_e) => Err(ScriptContextError::ImpossibleSatisfaction), - Ok(size) if size > MAX_SCRIPTSIG_SIZE => { - Err(ScriptContextError::MaxScriptSigSizeExceeded) - } + Err(_e) => Err(ContextError::ImpossibleSatisfaction), + Ok(size) if size > MAX_SCRIPTSIG_SIZE => Err(ContextError::MaxScriptSigSizeExceeded), _ => Ok(()), } } - fn max_satisfaction_size(ms: &Miniscript) -> Option { + fn max_satisfaction_size(ms: &Miniscript) -> Option { // The scriptSig cost is the second element of the tuple ms.ext.max_sat_size.map(|x| x.1) } - fn pk_len(pk: &Pk) -> usize { + fn pk_len(pk: &Pk) -> usize { if pk.is_uncompressed() { 66 } else { @@ -484,24 +476,24 @@ impl ScriptContext for Legacy { } } -/// Segwitv0 ScriptContext +/// Segwitv0 Context #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum Segwitv0 {} -impl ScriptContext for Segwitv0 { +impl Context for Segwitv0 { type Key = bitcoin::PublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( _frag: &Terminal, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } // No x-only keys or uncompressed keys in Segwitv0 context - fn check_pk(pk: &Pk) -> Result<(), ScriptContextError> { + fn check_pk(pk: &Pk) -> Result<(), ContextError> { if pk.is_uncompressed() { - Err(ScriptContextError::UncompressedKeysNotAllowed) + Err(ContextError::UncompressedKeysNotAllowed) } else if pk.is_x_only_key() { - Err(ScriptContextError::XOnlyKeysNotAllowed( + Err(ContextError::XOnlyKeysNotAllowed( pk.to_string(), Self::name_str(), )) @@ -510,9 +502,9 @@ impl ScriptContext for Segwitv0 { } } - fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(witness: &[Vec]) -> Result<(), ContextError> { if witness.len() > MAX_STANDARD_P2WSH_STACK_ITEMS { - return Err(ScriptContextError::MaxWitnessItemssExceeded { + return Err(ContextError::MaxWitnessItemssExceeded { actual: witness.len(), limit: MAX_STANDARD_P2WSH_STACK_ITEMS, }); @@ -520,61 +512,59 @@ impl ScriptContext for Segwitv0 { Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { if ms.ext.pk_cost > MAX_SCRIPT_SIZE { - return Err(ScriptContextError::MaxWitnessScriptSizeExceeded); + return Err(ContextError::MaxWitnessScriptSizeExceeded); } match ms.node { Terminal::PkK(ref pk) => Self::check_pk(pk), Terminal::Multi(_k, ref pks) => { if pks.len() > MAX_PUBKEYS_PER_MULTISIG { - return Err(ScriptContextError::CheckMultiSigLimitExceeded); + return Err(ContextError::CheckMultiSigLimitExceeded); } for pk in pks.iter() { Self::check_pk(pk)?; } Ok(()) } - Terminal::MultiA(..) => Err(ScriptContextError::MultiANotAllowed), + Terminal::MultiA(..) => Err(ContextError::MultiANotAllowed), _ => Ok(()), } } - fn check_local_consensus_validity( + fn check_local_consensus_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { match ms.ext.ops.op_count() { - None => Err(ScriptContextError::MaxOpCountExceeded), + None => Err(ContextError::MaxOpCountExceeded), Some(op_count) if op_count > MAX_OPS_PER_SCRIPT => { - Err(ScriptContextError::MaxOpCountExceeded) + Err(ContextError::MaxOpCountExceeded) } _ => Ok(()), } } - fn check_global_policy_validity( + fn check_global_policy_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { if ms.ext.pk_cost > MAX_STANDARD_P2WSH_SCRIPT_SIZE { - return Err(ScriptContextError::MaxWitnessScriptSizeExceeded); + return Err(ContextError::MaxWitnessScriptSizeExceeded); } Ok(()) } - fn check_local_policy_validity( - ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + fn check_local_policy_validity(ms: &Miniscript) -> Result<(), ContextError> { // We don't need to know if this is actually a p2wsh as the standard satisfaction for // other Segwitv0 defined programs all require (much) less than 100 elements. // The witness script item is accounted for in max_satisfaction_witness_elements(). match ms.max_satisfaction_witness_elements() { // No possible satisfactions - Err(_e) => Err(ScriptContextError::ImpossibleSatisfaction), + Err(_e) => Err(ContextError::ImpossibleSatisfaction), Ok(max_witness_items) if max_witness_items > MAX_STANDARD_P2WSH_STACK_ITEMS => { - Err(ScriptContextError::MaxWitnessItemssExceeded { + Err(ContextError::MaxWitnessItemssExceeded { actual: max_witness_items, limit: MAX_STANDARD_P2WSH_STACK_ITEMS, }) @@ -583,12 +573,12 @@ impl ScriptContext for Segwitv0 { } } - fn max_satisfaction_size(ms: &Miniscript) -> Option { + fn max_satisfaction_size(ms: &Miniscript) -> Option { // The witness stack cost is the first element of the tuple ms.ext.max_sat_size.map(|x| x.0) } - fn pk_len(_pk: &Pk) -> usize { + fn pk_len(_pk: &Pk) -> usize { 34 } @@ -601,33 +591,33 @@ impl ScriptContext for Segwitv0 { } } -/// Tap ScriptContext +/// Tap Context #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum Tap {} -impl ScriptContext for Tap { +impl Context for Tap { type Key = bitcoin::secp256k1::XOnlyPublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( _frag: &Terminal, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { // No fragment is malleable in tapscript context. // Certain fragments like Multi are invalid, but are not malleable Ok(()) } // No uncompressed keys in Tap context - fn check_pk(pk: &Pk) -> Result<(), ScriptContextError> { + fn check_pk(pk: &Pk) -> Result<(), ContextError> { if pk.is_uncompressed() { - Err(ScriptContextError::UncompressedKeysNotAllowed) + Err(ContextError::UncompressedKeysNotAllowed) } else { Ok(()) } } - fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(witness: &[Vec]) -> Result<(), ContextError> { // Note that tapscript has a 1000 limit compared to 100 of segwitv0 if witness.len() > MAX_STACK_SIZE { - return Err(ScriptContextError::MaxWitnessItemssExceeded { + return Err(ContextError::MaxWitnessItemssExceeded { actual: witness.len(), limit: MAX_STACK_SIZE, }); @@ -635,16 +625,16 @@ impl ScriptContext for Tap { Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { // No script size checks for global consensus rules // Should we really check for block limits here. // When the transaction sizes get close to block limits, // some guarantees are not easy to satisfy because of knapsack // constraints if ms.ext.pk_cost > MAX_BLOCK_WEIGHT as usize { - return Err(ScriptContextError::MaxWitnessScriptSizeExceeded); + return Err(ContextError::MaxWitnessScriptSizeExceeded); } match ms.node { @@ -655,14 +645,14 @@ impl ScriptContext for Tap { } Ok(()) } - Terminal::Multi(..) => Err(ScriptContextError::TaprootMultiDisabled), + Terminal::Multi(..) => Err(ContextError::TaprootMultiDisabled), _ => Ok(()), } } - fn check_local_consensus_validity( + fn check_local_consensus_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { // Taproot introduces the concept of sigops budget. // All valid miniscripts satisfy the sigops constraint // Whenever we add new fragment that uses pk(pk() or multi based on checksigadd) @@ -677,7 +667,7 @@ impl ScriptContext for Tap { ms.ext.stack_elem_count_sat, ) { if s + h > MAX_STACK_SIZE { - return Err(ScriptContextError::StackSizeLimitExceeded { + return Err(ContextError::StackSizeLimitExceeded { actual: s + h, limit: MAX_STACK_SIZE, }); @@ -686,20 +676,20 @@ impl ScriptContext for Tap { Ok(()) } - fn check_global_policy_validity( + fn check_global_policy_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { // No script rules, rules are subject to entire tx rules Ok(()) } - fn check_local_policy_validity( + fn check_local_policy_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } - fn max_satisfaction_size(ms: &Miniscript) -> Option { + fn max_satisfaction_size(ms: &Miniscript) -> Option { // The witness stack cost is the first element of the tuple ms.ext.max_sat_size.map(|x| x.0) } @@ -708,7 +698,7 @@ impl ScriptContext for Tap { SigType::Schnorr } - fn pk_len(_pk: &Pk) -> usize { + fn pk_len(_pk: &Pk) -> usize { 33 } @@ -717,18 +707,18 @@ impl ScriptContext for Tap { } } -/// Bare ScriptContext +/// Bare Context /// To be used as raw script pubkeys /// In general, it is not recommended to use Bare descriptors /// as they as strongly limited by standardness policies. #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum BareCtx {} -impl ScriptContext for BareCtx { +impl Context for BareCtx { type Key = bitcoin::PublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( _frag: &Terminal, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { // Bare fragments can't contain miniscript because of standardness rules // This function is only used in compiler which already checks the standardness // and consensus rules, and because of the limited allowance of bare scripts @@ -737,9 +727,9 @@ impl ScriptContext for BareCtx { } // No x-only keys in Bare context - fn check_pk(pk: &Pk) -> Result<(), ScriptContextError> { + fn check_pk(pk: &Pk) -> Result<(), ContextError> { if pk.is_x_only_key() { - Err(ScriptContextError::XOnlyKeysNotAllowed( + Err(ContextError::XOnlyKeysNotAllowed( pk.to_string(), Self::name_str(), )) @@ -748,41 +738,41 @@ impl ScriptContext for BareCtx { } } - fn check_global_consensus_validity( + fn check_global_consensus_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { if ms.ext.pk_cost > MAX_SCRIPT_SIZE { - return Err(ScriptContextError::MaxWitnessScriptSizeExceeded); + return Err(ContextError::MaxWitnessScriptSizeExceeded); } match ms.node { Terminal::PkK(ref key) => Self::check_pk(key), Terminal::Multi(_k, ref pks) => { if pks.len() > MAX_PUBKEYS_PER_MULTISIG { - return Err(ScriptContextError::CheckMultiSigLimitExceeded); + return Err(ContextError::CheckMultiSigLimitExceeded); } for pk in pks.iter() { Self::check_pk(pk)?; } Ok(()) } - Terminal::MultiA(..) => Err(ScriptContextError::MultiANotAllowed), + Terminal::MultiA(..) => Err(ContextError::MultiANotAllowed), _ => Ok(()), } } - fn check_local_consensus_validity( + fn check_local_consensus_validity( ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { match ms.ext.ops.op_count() { - None => Err(ScriptContextError::MaxOpCountExceeded), + None => Err(ContextError::MaxOpCountExceeded), Some(op_count) if op_count > MAX_OPS_PER_SCRIPT => { - Err(ScriptContextError::MaxOpCountExceeded) + Err(ContextError::MaxOpCountExceeded) } _ => Ok(()), } } - fn other_top_level_checks(ms: &Miniscript) -> Result<(), Error> { + fn other_top_level_checks(ms: &Miniscript) -> Result<(), Error> { match &ms.node { Terminal::Check(ref ms) => match &ms.node { Terminal::RawPkH(_pkh) => Ok(()), @@ -794,12 +784,12 @@ impl ScriptContext for BareCtx { } } - fn max_satisfaction_size(ms: &Miniscript) -> Option { + fn max_satisfaction_size(ms: &Miniscript) -> Option { // The witness stack cost is the first element of the tuple ms.ext.max_sat_size.map(|x| x.1) } - fn pk_len(pk: &Pk) -> usize { + fn pk_len(pk: &Pk) -> usize { if pk.is_uncompressed() { 66 } else { @@ -823,49 +813,49 @@ impl ScriptContext for BareCtx { /// This context should *NOT* be used unless you know what you are doing. #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd, Hash)] pub enum NoChecks {} -impl ScriptContext for NoChecks { +impl Context for NoChecks { // todo: When adding support for interpreter, we need a enum with all supported keys here type Key = bitcoin::PublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( _frag: &Terminal, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } // No checks in NoChecks - fn check_pk(_pk: &Pk) -> Result<(), ScriptContextError> { + fn check_pk(_pk: &Pk) -> Result<(), ContextError> { Ok(()) } - fn check_global_policy_validity( + fn check_global_policy_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } - fn check_local_policy_validity( + fn check_local_policy_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } - fn check_local_consensus_validity( + fn check_local_consensus_validity( _ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + ) -> Result<(), ContextError> { Ok(()) } - fn max_satisfaction_size(_ms: &Miniscript) -> Option { + fn max_satisfaction_size(_ms: &Miniscript) -> Option { panic!("Tried to compute a satisfaction size bound on a no-checks ecdsa miniscript") } - fn pk_len(_pk: &Pk) -> usize { + fn pk_len(_pk: &Pk) -> usize { panic!("Tried to compute a pk len bound on a no-checks ecdsa miniscript") } @@ -874,24 +864,20 @@ impl ScriptContext for NoChecks { "NochecksEcdsa" } - fn check_witness(_witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(_witness: &[Vec]) -> Result<(), ContextError> { // Only really need to do this for segwitv0 and legacy // Bare is already restrcited by standardness rules // and would reach these limits. Ok(()) } - fn check_global_validity( - ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + fn check_global_validity(ms: &Miniscript) -> Result<(), ContextError> { Self::check_global_consensus_validity(ms)?; Self::check_global_policy_validity(ms)?; Ok(()) } - fn check_local_validity( - ms: &Miniscript, - ) -> Result<(), ScriptContextError> { + fn check_local_validity(ms: &Miniscript) -> Result<(), ContextError> { Self::check_global_consensus_validity(ms)?; Self::check_global_policy_validity(ms)?; Self::check_local_consensus_validity(ms)?; @@ -899,18 +885,18 @@ impl ScriptContext for NoChecks { Ok(()) } - fn top_level_type_check(ms: &Miniscript) -> Result<(), Error> { + fn top_level_type_check(ms: &Miniscript) -> Result<(), Error> { if ms.ty.corr.base != types::Base::B { return Err(Error::NonTopLevel(format!("{:?}", ms))); } Ok(()) } - fn other_top_level_checks(_ms: &Miniscript) -> Result<(), Error> { + fn other_top_level_checks(_ms: &Miniscript) -> Result<(), Error> { Ok(()) } - fn top_level_checks(ms: &Miniscript) -> Result<(), Error> { + fn top_level_checks(ms: &Miniscript) -> Result<(), Error> { Self::top_level_type_check(ms)?; Self::other_top_level_checks(ms) } diff --git a/src/miniscript/decode.rs b/src/miniscript/decode.rs index d5fa907a6..8f5cc163c 100644 --- a/src/miniscript/decode.rs +++ b/src/miniscript/decode.rs @@ -19,11 +19,11 @@ use crate::miniscript::lex::{Token as Tk, TokenIter}; use crate::miniscript::limits::MAX_PUBKEYS_PER_MULTISIG; use crate::miniscript::types::extra_props::ExtData; use crate::miniscript::types::{Property, Type}; -use crate::miniscript::ScriptContext; +use crate::miniscript::Context; use crate::prelude::*; #[cfg(doc)] use crate::Descriptor; -use crate::{bitcoin, hash256, AbsLockTime, Error, Miniscript, MiniscriptKey, ToPublicKey}; +use crate::{bitcoin, hash256, AbsLockTime, Error, Key, Miniscript, ToPublicKey}; fn return_none(_: usize) -> Option { None @@ -122,7 +122,7 @@ enum NonTerm { /// The average user should always use the [`Descriptor`] APIs. Advanced users who want deal /// with Miniscript ASTs should use the [`Miniscript`] APIs. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Terminal { +pub enum Terminal { /// `1` True, /// `0` @@ -213,9 +213,9 @@ macro_rules! match_token { ///Vec representing terminals stack while decoding. #[derive(Debug)] -struct TerminalStack(Vec>); +struct TerminalStack(Vec>); -impl TerminalStack { +impl TerminalStack { ///Wrapper around self.0.pop() fn pop(&mut self) -> Option> { self.0.pop() @@ -283,9 +283,7 @@ impl TerminalStack { /// Parse a script fragment into an `Miniscript` #[allow(unreachable_patterns)] -pub fn parse( - tokens: &mut TokenIter, -) -> Result, Error> { +pub fn parse(tokens: &mut TokenIter) -> Result, Error> { let mut non_term = Vec::with_capacity(tokens.len()); let mut term = TerminalStack(Vec::with_capacity(tokens.len())); diff --git a/src/miniscript/iter.rs b/src/miniscript/iter.rs index f64b350ec..1b30ad3e1 100644 --- a/src/miniscript/iter.rs +++ b/src/miniscript/iter.rs @@ -10,11 +10,11 @@ use core::ops::Deref; use sync::Arc; use super::decode::Terminal; -use super::{Miniscript, MiniscriptKey, ScriptContext}; +use super::{Context, Key, Miniscript}; use crate::prelude::*; /// Iterator-related extensions for [Miniscript] -impl Miniscript { +impl Miniscript { /// Creates a new [Iter] iterator that will iterate over all [Miniscript] items within /// AST by traversing its branches. For the specific algorithm please see /// [Iter::next] function. @@ -109,7 +109,7 @@ impl Miniscript { /// Iterator for traversing all [Miniscript] miniscript AST references starting from some specific /// node which constructs the iterator via [Miniscript::iter] method. -pub struct Iter<'a, Pk: MiniscriptKey, Ctx: ScriptContext> { +pub struct Iter<'a, Pk: Key, Ctx: Context> { next: Option<&'a Miniscript>, // Here we store vec of path elements, where each element is a tuple, consisting of: // 1. Miniscript node on the path @@ -117,7 +117,7 @@ pub struct Iter<'a, Pk: MiniscriptKey, Ctx: ScriptContext> { path: Vec<(&'a Miniscript, usize)>, } -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iter<'a, Pk, Ctx> { +impl<'a, Pk: Key, Ctx: Context> Iter<'a, Pk, Ctx> { fn new(miniscript: &'a Miniscript) -> Self { Iter { next: Some(miniscript), @@ -126,7 +126,7 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iter<'a, Pk, Ctx> { } } -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iterator for Iter<'a, Pk, Ctx> { +impl<'a, Pk: Key, Ctx: Context> Iterator for Iter<'a, Pk, Ctx> { type Item = &'a Miniscript; /// First, the function returns `self`, then the first child of the self (if any), @@ -169,15 +169,15 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iterator for Iter<'a, Pk, Ctx> { } } -/// Iterator for traversing all [MiniscriptKey]'s in AST starting from some specific node which +/// Iterator for traversing all [Key]'s in AST starting from some specific node which /// constructs the iterator via [Miniscript::iter_pk] method. -pub struct PkIter<'a, Pk: MiniscriptKey, Ctx: ScriptContext> { +pub struct PkIter<'a, Pk: Key, Ctx: Context> { node_iter: Iter<'a, Pk, Ctx>, curr_node: Option<&'a Miniscript>, key_index: usize, } -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> PkIter<'a, Pk, Ctx> { +impl<'a, Pk: Key, Ctx: Context> PkIter<'a, Pk, Ctx> { fn new(miniscript: &'a Miniscript) -> Self { let mut iter = Iter::new(miniscript); PkIter { @@ -188,7 +188,7 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> PkIter<'a, Pk, Ctx> { } } -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iterator for PkIter<'a, Pk, Ctx> { +impl<'a, Pk: Key, Ctx: Context> Iterator for PkIter<'a, Pk, Ctx> { type Item = Pk; fn next(&mut self) -> Option { diff --git a/src/miniscript/mod.rs b/src/miniscript/mod.rs index ed607977c..a5ec49ff8 100644 --- a/src/miniscript/mod.rs +++ b/src/miniscript/mod.rs @@ -41,17 +41,17 @@ use sync::Arc; use self::lex::{lex, TokenIter}; use self::types::Property; -pub use crate::miniscript::context::ScriptContext; +pub use crate::miniscript::context::Context; use crate::miniscript::decode::Terminal; use crate::miniscript::types::extra_props::ExtData; use crate::miniscript::types::Type; -use crate::{expression, Error, ForEachKey, MiniscriptKey, ToPublicKey, TranslatePk, Translator}; +use crate::{expression, Error, ForEachKey, Key, ToPublicKey, TranslatePk, Translator}; #[cfg(test)] mod ms_tests; /// The top-level miniscript abstract syntax tree (AST). #[derive(Clone)] -pub struct Miniscript { +pub struct Miniscript { /// A node in the AST. pub node: Terminal, /// The correctness and malleability type information for the AST node. @@ -62,7 +62,7 @@ pub struct Miniscript { phantom: PhantomData, } -impl Miniscript { +impl Miniscript { /// 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. @@ -241,7 +241,7 @@ impl Miniscript { } } -impl Miniscript { +impl Miniscript { /// Attempt to parse an insane(scripts don't clear sanity checks) /// script into a Miniscript representation. /// Use this to parse scripts with repeated pubkeys, timelock mixing, malleable @@ -323,7 +323,7 @@ impl Miniscript { /// `PartialOrd` of `Miniscript` must depend only on node and not the type information. /// /// The type information and extra properties are implied by the AST. -impl PartialOrd for Miniscript { +impl PartialOrd for Miniscript { fn partial_cmp(&self, other: &Miniscript) -> Option { Some(self.node.cmp(&other.node)) } @@ -332,7 +332,7 @@ impl PartialOrd for Miniscript { /// `Ord` of `Miniscript` must depend only on node and not the type information. /// /// The type information and extra properties are implied by the AST. -impl Ord for Miniscript { +impl Ord for Miniscript { fn cmp(&self, other: &Miniscript) -> cmp::Ordering { self.node.cmp(&other.node) } @@ -341,7 +341,7 @@ impl Ord for Miniscript { /// `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 { +impl PartialEq for Miniscript { fn eq(&self, other: &Miniscript) -> bool { self.node.eq(&other.node) } @@ -350,30 +350,30 @@ impl PartialEq for Miniscript { /// `Eq` of `Miniscript` must depend only on node and not the type information. /// /// The type information and extra properties are implied by the AST. -impl Eq for Miniscript {} +impl Eq for Miniscript {} /// `Hash` of `Miniscript` must depend only on node and not the type information. /// /// The type information and extra properties are implied by the AST. -impl hash::Hash for Miniscript { +impl hash::Hash for Miniscript { fn hash(&self, state: &mut H) { self.node.hash(state); } } -impl fmt::Debug for Miniscript { +impl fmt::Debug for Miniscript { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.node) } } -impl fmt::Display for Miniscript { +impl fmt::Display for Miniscript { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.node) } } -impl ForEachKey for Miniscript { +impl ForEachKey for Miniscript { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { for ms in self.pre_order_iter() { match ms.node { @@ -401,9 +401,9 @@ impl ForEachKey for Miniscript TranslatePk for Miniscript where - Pk: MiniscriptKey, - Q: MiniscriptKey, - Ctx: ScriptContext, + Pk: Key, + Q: Key, + Ctx: Context, { type Output = Miniscript; @@ -417,14 +417,14 @@ where } } -impl Miniscript { +impl Miniscript { pub(super) fn translate_pk_ctx( &self, t: &mut T, ) -> Result, TranslateErr> where - Q: MiniscriptKey, - CtxQ: ScriptContext, + Q: Key, + CtxQ: Context, T: Translator, { let mut translated = vec![]; @@ -499,7 +499,7 @@ impl Miniscript { } impl_block_str!( - ;Ctx; ScriptContext, + ;Ctx; Context, Miniscript, /// Attempt to parse an insane(scripts don't clear sanity checks) /// from string into a Miniscript representation. @@ -515,7 +515,7 @@ impl_block_str!( ); impl_block_str!( - ;Ctx; ScriptContext, + ;Ctx; Context, Miniscript, /// Attempt to parse an Miniscripts that don't follow the spec. /// Use this to parse scripts with repeated pubkeys, timelock mixing, malleable @@ -538,7 +538,7 @@ impl_block_str!( ); impl_from_tree!( - ;Ctx; ScriptContext, + ;Ctx; Context, Arc>, fn from_tree(top: &expression::Tree) -> Result>, Error> { Ok(Arc::new(expression::FromTree::from_tree(top)?)) @@ -546,7 +546,7 @@ impl_from_tree!( ); impl_from_tree!( - ;Ctx; ScriptContext, + ;Ctx; Context, Miniscript, /// Parse an expression tree into a Miniscript. As a general rule, this /// should not be called directly; rather go through the descriptor API. @@ -557,7 +557,7 @@ impl_from_tree!( ); impl_from_str!( - ;Ctx; ScriptContext, + ;Ctx; Context, Miniscript, type Err = Error;, /// Parse a Miniscript from string and perform sanity checks @@ -569,7 +569,7 @@ impl_from_str!( } ); -serde_string_impl_pk!(Miniscript, "a miniscript", Ctx; ScriptContext); +serde_string_impl_pk!(Miniscript, "a miniscript", Ctx; Context); /// Provides a Double SHA256 `Hash` type that displays forwards. pub mod hash256 { @@ -595,7 +595,7 @@ mod tests { use bitcoin::{self, secp256k1, Sequence}; use sync::Arc; - use super::{Miniscript, ScriptContext, Segwitv0, Tap}; + use super::{Context, Miniscript, Segwitv0, Tap}; use crate::miniscript::types::{self, ExtData, Property, Type}; use crate::miniscript::Terminal; use crate::policy::Liftable; @@ -627,7 +627,7 @@ mod tests { ret } - fn string_rtt( + fn string_rtt( script: Miniscript, expected_debug: &str, expected_display: &str, @@ -645,7 +645,7 @@ mod tests { assert_eq!(roundtrip, script); } - fn string_display_debug_test( + fn string_display_debug_test( script: Miniscript, expected_debug: &str, expected_display: &str, @@ -661,7 +661,7 @@ mod tests { } } - fn dummy_string_rtt( + fn dummy_string_rtt( script: Miniscript, expected_debug: &str, expected_display: &str, diff --git a/src/miniscript/satisfy.rs b/src/miniscript/satisfy.rs index 7ba993e49..01b035161 100644 --- a/src/miniscript/satisfy.rs +++ b/src/miniscript/satisfy.rs @@ -17,7 +17,7 @@ use sync::Arc; use super::context::SigType; use crate::prelude::*; use crate::util::witness_size; -use crate::{Miniscript, MiniscriptKey, ScriptContext, Terminal, ToPublicKey}; +use crate::{Context, Key, Miniscript, Terminal, ToPublicKey}; /// Type alias for 32 byte Preimage. pub type Preimage32 = [u8; 32]; @@ -25,7 +25,7 @@ pub type Preimage32 = [u8; 32]; /// Every method has a default implementation that simply returns `None` /// on every query. Users are expected to override the methods that they /// have data for. -pub trait Satisfier { +pub trait Satisfier { /// Given a public key, look up an ECDSA signature with that key fn lookup_ecdsa_sig(&self, _: &Pk) -> Option { None @@ -116,9 +116,9 @@ pub trait Satisfier { } // Allow use of `()` as a "no conditions available" satisfier -impl Satisfier for () {} +impl Satisfier for () {} -impl Satisfier for Sequence { +impl Satisfier for Sequence { fn check_older(&self, n: Sequence) -> bool { if !self.is_relative_lock_time() { return false; @@ -142,7 +142,7 @@ impl Satisfier for Sequence { } } -impl Satisfier for absolute::LockTime { +impl Satisfier for absolute::LockTime { fn check_after(&self, n: absolute::LockTime) -> bool { use absolute::LockTime::*; @@ -153,13 +153,13 @@ impl Satisfier for absolute::LockTime { } } } -impl Satisfier for HashMap { +impl Satisfier for HashMap { fn lookup_ecdsa_sig(&self, key: &Pk) -> Option { self.get(key).copied() } } -impl Satisfier +impl Satisfier for HashMap<(Pk, TapLeafHash), bitcoin::taproot::Signature> { fn lookup_tap_leaf_script_sig( @@ -175,10 +175,10 @@ impl Satisfier } } -impl Satisfier +impl Satisfier for HashMap where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, { fn lookup_ecdsa_sig(&self, key: &Pk) -> Option { self.get(&key.to_pubkeyhash(SigType::Ecdsa)).map(|x| x.1) @@ -197,10 +197,10 @@ where } } -impl Satisfier +impl Satisfier for HashMap<(hash160::Hash, TapLeafHash), (Pk, bitcoin::taproot::Signature)> where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, { fn lookup_tap_leaf_script_sig( &self, @@ -220,7 +220,7 @@ where } } -impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier> Satisfier for &'a S { +impl<'a, Pk: Key + ToPublicKey, S: Satisfier> Satisfier for &'a S { fn lookup_ecdsa_sig(&self, p: &Pk) -> Option { (**self).lookup_ecdsa_sig(p) } @@ -290,7 +290,7 @@ impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier> Satisfier for &' } } -impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier> Satisfier for &'a mut S { +impl<'a, Pk: Key + ToPublicKey, S: Satisfier> Satisfier for &'a mut S { fn lookup_ecdsa_sig(&self, p: &Pk) -> Option { (**self).lookup_ecdsa_sig(p) } @@ -365,7 +365,7 @@ macro_rules! impl_tuple_satisfier { #[allow(non_snake_case)] impl<$($ty,)* Pk> Satisfier for ($($ty,)*) where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, $($ty: Satisfier< Pk>,)* { fn lookup_ecdsa_sig(&self, key: &Pk) -> Option { @@ -573,7 +573,7 @@ impl Ord for Witness { impl Witness { /// Turn a signature into (part of) a satisfaction - fn signature, Ctx: ScriptContext>( + fn signature, Ctx: Context>( sat: S, pk: &Pk, leaf_hash: &TapLeafHash, @@ -594,7 +594,7 @@ impl Witness { } /// Turn a public key related to a pkh into (part of) a satisfaction - fn pkh_public_key, Ctx: ScriptContext>( + fn pkh_public_key, Ctx: Context>( sat: S, pkh: &hash160::Hash, ) -> Self { @@ -613,7 +613,7 @@ impl Witness { } /// Turn a key/signature pair related to a pkh into (part of) a satisfaction - fn pkh_signature, Ctx: ScriptContext>( + fn pkh_signature, Ctx: Context>( sat: S, pkh: &hash160::Hash, leaf_hash: &TapLeafHash, @@ -727,8 +727,8 @@ impl Satisfaction { min_fn: &mut F, ) -> Self where - Pk: MiniscriptKey + ToPublicKey, - Ctx: ScriptContext, + Pk: Key + ToPublicKey, + Ctx: Context, Sat: Satisfier, F: FnMut(Satisfaction, Satisfaction) -> Satisfaction, { @@ -845,8 +845,8 @@ impl Satisfaction { min_fn: &mut F, ) -> Self where - Pk: MiniscriptKey + ToPublicKey, - Ctx: ScriptContext, + Pk: Key + ToPublicKey, + Ctx: Context, Sat: Satisfier, F: FnMut(Satisfaction, Satisfaction) -> Satisfaction, { @@ -973,8 +973,8 @@ impl Satisfaction { thresh_fn: &mut G, ) -> Self where - Pk: MiniscriptKey + ToPublicKey, - Ctx: ScriptContext, + Pk: Key + ToPublicKey, + Ctx: Context, Sat: Satisfier, F: FnMut(Satisfaction, Satisfaction) -> Satisfaction, G: FnMut( @@ -1292,8 +1292,8 @@ impl Satisfaction { thresh_fn: &mut G, ) -> Self where - Pk: MiniscriptKey + ToPublicKey, - Ctx: ScriptContext, + Pk: Key + ToPublicKey, + Ctx: Context, Sat: Satisfier, F: FnMut(Satisfaction, Satisfaction) -> Satisfaction, G: FnMut( @@ -1454,11 +1454,7 @@ impl Satisfaction { } /// Produce a satisfaction non-malleable satisfaction - pub(super) fn satisfy< - Pk: MiniscriptKey + ToPublicKey, - Ctx: ScriptContext, - Sat: Satisfier, - >( + pub(super) fn satisfy>( term: &Terminal, stfr: &Sat, root_has_sig: bool, @@ -1475,11 +1471,7 @@ impl Satisfaction { } /// Produce a satisfaction(possibly malleable) - pub(super) fn satisfy_mall< - Pk: MiniscriptKey + ToPublicKey, - Ctx: ScriptContext, - Sat: Satisfier, - >( + pub(super) fn satisfy_mall>( term: &Terminal, stfr: &Sat, root_has_sig: bool, diff --git a/src/miniscript/types/correctness.rs b/src/miniscript/types/correctness.rs index a4c3b2fa9..76706e961 100644 --- a/src/miniscript/types/correctness.rs +++ b/src/miniscript/types/correctness.rs @@ -3,7 +3,7 @@ //! Correctness/Soundness type properties use super::{ErrorKind, Property}; -use crate::ScriptContext; +use crate::Context; /// Basic type representing where the fragment can go #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] @@ -131,7 +131,7 @@ impl Property for Correctness { } } - fn from_pk_k() -> Self { + fn from_pk_k() -> Self { Correctness { base: Base::K, input: Input::OneNonZero, @@ -140,7 +140,7 @@ impl Property for Correctness { } } - fn from_pk_h() -> Self { + fn from_pk_h() -> Self { Correctness { base: Base::K, input: Input::AnyNonZero, diff --git a/src/miniscript/types/extra_props.rs b/src/miniscript/types/extra_props.rs index 3f12e5a88..6ad233f70 100644 --- a/src/miniscript/types/extra_props.rs +++ b/src/miniscript/types/extra_props.rs @@ -8,10 +8,10 @@ use core::iter::once; use bitcoin::{absolute, Sequence}; -use super::{Error, ErrorKind, Property, ScriptContext}; +use super::{Context, Error, ErrorKind, Property}; use crate::miniscript::context::SigType; use crate::prelude::*; -use crate::{script_num_size, MiniscriptKey, Terminal}; +use crate::{script_num_size, Key, Terminal}; /// Timelock information for satisfaction of a fragment. #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)] @@ -183,7 +183,7 @@ impl Property for ExtData { } } - fn from_pk_k() -> Self { + fn from_pk_k() -> Self { ExtData { pk_cost: match Ctx::sig_type() { SigType::Ecdsa => 34, @@ -204,7 +204,7 @@ impl Property for ExtData { } } - fn from_pk_h() -> Self { + fn from_pk_h() -> Self { ExtData { pk_cost: 24, has_free_verify: false, @@ -896,8 +896,8 @@ impl Property for ExtData { ) -> Result> where C: FnMut(usize) -> Option, - Ctx: ScriptContext, - Pk: MiniscriptKey, + Ctx: Context, + Pk: Key, { let wrap_err = |result: Result| { result.map_err(|kind| Error { diff --git a/src/miniscript/types/malleability.rs b/src/miniscript/types/malleability.rs index d1b8e4dba..59c62bb06 100644 --- a/src/miniscript/types/malleability.rs +++ b/src/miniscript/types/malleability.rs @@ -3,7 +3,7 @@ //! Malleability-related Type properties use super::{ErrorKind, Property}; -use crate::ScriptContext; +use crate::Context; /// Whether the fragment has a dissatisfaction, and if so, whether /// it is unique. Affects both correctness and malleability-freeness, @@ -83,7 +83,7 @@ impl Property for Malleability { } } - fn from_pk_k() -> Self { + fn from_pk_k() -> Self { Malleability { dissat: Dissat::Unique, safe: true, @@ -91,7 +91,7 @@ impl Property for Malleability { } } - fn from_pk_h() -> Self { + fn from_pk_h() -> Self { Malleability { dissat: Dissat::Unique, safe: true, diff --git a/src/miniscript/types/mod.rs b/src/miniscript/types/mod.rs index 35a29605e..cc28ecf39 100644 --- a/src/miniscript/types/mod.rs +++ b/src/miniscript/types/mod.rs @@ -17,8 +17,8 @@ use bitcoin::{absolute, Sequence}; pub use self::correctness::{Base, Correctness, Input}; pub use self::extra_props::ExtData; pub use self::malleability::{Dissat, Malleability}; -use super::ScriptContext; -use crate::{MiniscriptKey, Terminal}; +use super::Context; +use crate::{Key, Terminal}; /// None-returning function to help type inference when we need a /// closure that simply returns `None` @@ -88,14 +88,14 @@ pub enum ErrorKind { /// Error type for typechecking #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] -pub struct Error { +pub struct Error { /// The fragment that failed typecheck pub fragment: Terminal, /// The reason that typechecking failed pub error: ErrorKind, } -impl fmt::Display for Error { +impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.error { ErrorKind::InvalidTime => write!( @@ -205,7 +205,7 @@ impl fmt::Display for Error { } #[cfg(feature = "std")] -impl error::Error for Error { +impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { None } @@ -246,10 +246,10 @@ pub trait Property: Sized { fn from_false() -> Self; /// Type property of the `PkK` fragment - fn from_pk_k() -> Self; + fn from_pk_k() -> Self; /// Type property of the `PkH` fragment - fn from_pk_h() -> Self; + fn from_pk_h() -> Self; /// Type property of a `Multi` fragment fn from_multi(k: usize, n: usize) -> Self; @@ -380,8 +380,8 @@ pub trait Property: Sized { ) -> Result> where C: FnMut(usize) -> Option, - Pk: MiniscriptKey, - Ctx: ScriptContext, + Pk: Key, + Ctx: Context, { let mut get_child = |sub, n| { child(n) @@ -547,14 +547,14 @@ impl Property for Type { } } - fn from_pk_k() -> Self { + fn from_pk_k() -> Self { Type { corr: Property::from_pk_k::(), mall: Property::from_pk_k::(), } } - fn from_pk_h() -> Self { + fn from_pk_h() -> Self { Type { corr: Property::from_pk_h::(), mall: Property::from_pk_h::(), @@ -775,8 +775,8 @@ impl Property for Type { ) -> Result> where C: FnMut(usize) -> Option, - Pk: MiniscriptKey, - Ctx: ScriptContext, + Pk: Key, + Ctx: Context, { let wrap_err = |result: Result| { result.map_err(|kind| Error { diff --git a/src/policy/compiler.rs b/src/policy/compiler.rs index c3c13ec62..25d91a0b1 100644 --- a/src/policy/compiler.rs +++ b/src/policy/compiler.rs @@ -15,10 +15,10 @@ use sync::Arc; use crate::miniscript::context::SigType; use crate::miniscript::limits::MAX_PUBKEYS_PER_MULTISIG; use crate::miniscript::types::{self, ErrorKind, ExtData, Property, Type}; -use crate::miniscript::ScriptContext; +use crate::miniscript::Context; use crate::policy::Concrete; use crate::prelude::*; -use crate::{policy, Miniscript, MiniscriptKey, Terminal}; +use crate::{policy, Key, Miniscript, Terminal}; type PolicyCache = BTreeMap<(Concrete, OrdF64, Option), BTreeMap>>; @@ -172,7 +172,7 @@ impl Property for CompilerExtData { } } - fn from_pk_k() -> Self { + fn from_pk_k() -> Self { CompilerExtData { branch_prob: None, sat_cost: match Ctx::sig_type() { @@ -183,7 +183,7 @@ impl Property for CompilerExtData { } } - fn from_pk_h() -> Self { + fn from_pk_h() -> Self { CompilerExtData { branch_prob: None, sat_cost: match Ctx::sig_type() { @@ -454,14 +454,14 @@ impl Property for CompilerExtData { /// Miniscript AST fragment with additional data needed by the compiler #[derive(Clone, Debug)] -struct AstElemExt { +struct AstElemExt { /// The actual Miniscript fragment with type information ms: Arc>, /// Its "type" in terms of compiler data comp_ext_data: CompilerExtData, } -impl AstElemExt { +impl AstElemExt { /// Compute a 1-dimensional cost, given a probability of satisfaction /// and a probability of dissatisfaction; if `dissat_prob` is `None` /// then it is assumed that dissatisfaction never occurs @@ -477,7 +477,7 @@ impl AstElemExt { } } -impl AstElemExt { +impl AstElemExt { fn terminal(ast: Terminal) -> AstElemExt { AstElemExt { comp_ext_data: CompilerExtData::type_check(&ast, |_| None).unwrap(), @@ -533,14 +533,14 @@ impl AstElemExt { /// Different types of casts possible for each node. #[allow(clippy::type_complexity)] #[derive(Copy, Clone)] -struct Cast { +struct Cast { node: fn(Arc>) -> Terminal, ast_type: fn(types::Type) -> Result, ext_data: fn(types::ExtData) -> Result, comp_ext_data: fn(CompilerExtData) -> Result, } -impl Cast { +impl Cast { fn cast(&self, ast: &AstElemExt) -> Result, ErrorKind> { Ok(AstElemExt { ms: Arc::new(Miniscript::from_components_unchecked( @@ -553,7 +553,7 @@ impl Cast { } } -fn all_casts() -> [Cast; 10] { +fn all_casts() -> [Cast; 10] { [ Cast { ext_data: types::ExtData::cast_check, @@ -647,7 +647,7 @@ fn all_casts() -> [Cast; 10] { /// the map. /// In general, we maintain the invariant that if anything is inserted into the /// map, it's cast closure must also be considered for best compilations. -fn insert_elem( +fn insert_elem( map: &mut BTreeMap>, elem: AstElemExt, sat_prob: f64, @@ -700,7 +700,7 @@ fn insert_elem( /// At the start and end of this function, we maintain that the invariant that /// all map is smallest possible closure of all compilations of a policy with /// given sat and dissat probabilities. -fn insert_elem_closure( +fn insert_elem_closure( map: &mut BTreeMap>, astelem_ext: AstElemExt, sat_prob: f64, @@ -734,7 +734,7 @@ fn insert_elem_closure( /// given that it may be not be necessary to dissatisfy. For these elements, we /// apply the wrappers around the element once and bring them into the same /// dissat probability map and get their closure. -fn insert_best_wrapped( +fn insert_best_wrapped( policy_cache: &mut PolicyCache, policy: &Concrete, map: &mut BTreeMap>, @@ -767,8 +767,8 @@ fn best_compilations( dissat_prob: Option, ) -> Result>, CompilerError> where - Pk: MiniscriptKey, - Ctx: ScriptContext, + Pk: Key, + Ctx: Context, { //Check the cache for hits let ord_sat_prob = OrdF64(sat_prob); @@ -1068,8 +1068,8 @@ fn compile_binary( bin_func: F, ) -> Result<(), CompilerError> where - Pk: MiniscriptKey, - Ctx: ScriptContext, + Pk: Key, + Ctx: Context, F: Fn(Arc>, Arc>) -> Terminal, { for l in left_comp.values_mut() { @@ -1091,7 +1091,7 @@ where /// `sat_prob` and `dissat_prob` represent the sat and dissat probabilities of /// root and_or node. `weights` represent the odds for taking each sub branch #[allow(clippy::too_many_arguments)] -fn compile_tern( +fn compile_tern( policy_cache: &mut PolicyCache, policy: &Concrete, ret: &mut BTreeMap>, @@ -1122,7 +1122,7 @@ fn compile_tern( } /// Obtain the best compilation of for p=1.0 and q=0 -pub fn best_compilation( +pub fn best_compilation( policy: &Concrete, ) -> Result, CompilerError> { let mut policy_cache = PolicyCache::::new(); @@ -1144,8 +1144,8 @@ fn best_t( dissat_prob: Option, ) -> Result, CompilerError> where - Pk: MiniscriptKey, - Ctx: ScriptContext, + Pk: Key, + Ctx: Context, { best_compilations(policy_cache, policy, sat_prob, dissat_prob)? .into_iter() @@ -1166,8 +1166,8 @@ fn best( dissat_prob: Option, ) -> Result, CompilerError> where - Pk: MiniscriptKey, - Ctx: ScriptContext, + Pk: Key, + Ctx: Context, { best_compilations(policy_cache, policy, sat_prob, dissat_prob)? .into_iter() diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index d030a99d2..ae7c6458d 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -11,7 +11,7 @@ use bitcoin::{absolute, Sequence}; #[cfg(feature = "compiler")] use { crate::descriptor::TapTree, - crate::miniscript::ScriptContext, + crate::miniscript::Context, crate::policy::compiler::CompilerError, crate::policy::compiler::OrdF64, crate::policy::{compiler, Concrete, Liftable, Semantic}, @@ -28,7 +28,7 @@ use crate::miniscript::types::extra_props::TimelockInfo; use crate::prelude::*; #[cfg(all(doc, not(feature = "compiler")))] use crate::Descriptor; -use crate::{errstr, AbsLockTime, Error, ForEachKey, MiniscriptKey, Translator}; +use crate::{errstr, AbsLockTime, Error, ForEachKey, Key, Translator}; /// Maximum TapLeafs allowed in a compiled TapTree #[cfg(feature = "compiler")] @@ -38,7 +38,7 @@ const MAX_COMPILATION_LEAVES: usize = 1024; /// and whose disjunctions are annotated with satisfaction probabilities /// to assist the compiler. #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Policy { +pub enum Policy { /// Unsatisfiable. Unsatisfiable, /// Trivially satisfiable. @@ -68,7 +68,7 @@ pub enum Policy { impl Policy where - Pk: MiniscriptKey, + Pk: Key, { /// Construct a `Policy::After` from `n`. Helper function equivalent to /// `Policy::After(absolute::LockTime::from_consensus(n))`. @@ -88,7 +88,7 @@ where /// probabilities to assist the compiler #[cfg(feature = "compiler")] #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -enum PolicyArc { +enum PolicyArc { /// Unsatisfiable Unsatisfiable, /// Trivially satisfiable @@ -117,7 +117,7 @@ enum PolicyArc { } #[cfg(feature = "compiler")] -impl From> for Policy { +impl From> for Policy { fn from(p: PolicyArc) -> Self { match p { PolicyArc::Unsatisfiable => Policy::Unsatisfiable, @@ -150,7 +150,7 @@ impl From> for Policy { } #[cfg(feature = "compiler")] -impl From> for PolicyArc { +impl From> for PolicyArc { fn from(p: Policy) -> Self { match p { Policy::Unsatisfiable => PolicyArc::Unsatisfiable, @@ -275,7 +275,7 @@ impl error::Error for PolicyError { } } -impl Policy { +impl Policy { /// Flattens the [`Policy`] tree structure into a vector of tuples `(leaf script, leaf probability)` /// with leaf probabilities corresponding to odds for each sub-branch in the policy. /// We calculate the probability of selecting the sub-branch at every level and calculate the @@ -483,7 +483,7 @@ impl Policy { /// use the policy compiler once, and then use the miniscript output as a stable identifier. See /// the compiler document in [`doc/compiler.md`] for more details. #[cfg(feature = "compiler")] - pub fn compile_to_descriptor( + pub fn compile_to_descriptor( &self, desc_ctx: DescriptorCtx, ) -> Result, Error> { @@ -511,7 +511,7 @@ impl Policy { /// use the policy compiler once, and then use the miniscript output as a stable identifier. See /// the compiler document in doc/compiler.md for more details. #[cfg(feature = "compiler")] - pub fn compile(&self) -> Result, CompilerError> { + pub fn compile(&self) -> Result, CompilerError> { self.is_valid()?; match self.is_safe_nonmalleable() { (false, _) => Err(CompilerError::TopLevelNonSafe), @@ -522,7 +522,7 @@ impl Policy { } #[cfg(feature = "compiler")] -impl PolicyArc { +impl PolicyArc { /// Returns a vector of policies whose disjunction is isomorphic to the initial one. /// /// This function is supposed to incrementally expand i.e. represent the policy as @@ -654,13 +654,13 @@ impl PolicyArc { } } -impl ForEachKey for Policy { +impl ForEachKey for Policy { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { self.real_for_each_key(&mut pred) } } -impl Policy { +impl Policy { fn real_for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: &mut F) -> bool { match *self { Policy::Unsatisfiable | Policy::Trivial => true, @@ -686,7 +686,7 @@ impl Policy { pub fn translate_pk(&self, t: &mut T) -> Result, E> where T: Translator, - Q: MiniscriptKey, + Q: Key, { self._translate_pk(t) } @@ -694,7 +694,7 @@ impl Policy { fn _translate_pk(&self, t: &mut T) -> Result, E> where T: Translator, - Q: MiniscriptKey, + Q: Key, { match *self { Policy::Unsatisfiable => Ok(Policy::Unsatisfiable), @@ -970,7 +970,7 @@ impl Policy { } } -impl fmt::Debug for Policy { +impl fmt::Debug for Policy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Policy::Unsatisfiable => f.write_str("UNSATISFIABLE()"), @@ -1013,7 +1013,7 @@ impl fmt::Debug for Policy { } } -impl fmt::Display for Policy { +impl fmt::Display for Policy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Policy::Unsatisfiable => f.write_str("UNSATISFIABLE"), @@ -1187,7 +1187,7 @@ impl_from_tree!( /// Creates a Huffman Tree from compiled [`Miniscript`] nodes. #[cfg(feature = "compiler")] -fn with_huffman_tree( +fn with_huffman_tree( ms: Vec<(OrdF64, Miniscript)>, ) -> Result, Error> { let mut node_weights = BinaryHeap::<(Reverse, TapTree)>::new(); @@ -1221,7 +1221,7 @@ fn with_huffman_tree( /// by the simple argument that choosing `k` conditions from `n` available conditions might not contain /// any one of the conditions exclusively. #[cfg(feature = "compiler")] -fn generate_combination( +fn generate_combination( policy_vec: &Vec>>, prob: f64, k: usize, diff --git a/src/policy/mod.rs b/src/policy/mod.rs index 27165c2e2..c9423b296 100644 --- a/src/policy/mod.rs +++ b/src/policy/mod.rs @@ -21,8 +21,8 @@ pub mod semantic; pub use self::concrete::Policy as Concrete; pub use self::semantic::Policy as Semantic; use crate::descriptor::Descriptor; -use crate::miniscript::{Miniscript, ScriptContext}; -use crate::{Error, MiniscriptKey, Terminal}; +use crate::miniscript::{Context, Miniscript}; +use crate::{Error, Key, Terminal}; /// Policy entailment algorithm maximum number of terminals allowed. const ENTAILMENT_MAX_TERMINALS: usize = 20; @@ -43,7 +43,7 @@ const ENTAILMENT_MAX_TERMINALS: usize = 20; /// exceed resource limits for any compilation but cannot detect such policies /// while lifting. Note that our compiler would not succeed for any such /// policies. -pub trait Liftable { +pub trait Liftable { /// Converts this object into an abstract policy. fn lift(&self) -> Result, Error>; } @@ -84,7 +84,7 @@ impl error::Error for LiftError { } } -impl Miniscript { +impl Miniscript { /// Lifting corresponds to conversion of a miniscript into a [`Semantic`] /// policy for human readable or machine analysis. However, naively lifting /// miniscripts can result in incorrect interpretations that don't @@ -103,7 +103,7 @@ impl Miniscript { } } -impl Liftable for Miniscript { +impl Liftable for Miniscript { fn lift(&self) -> Result, Error> { // check whether the root miniscript can have a spending path that is // a combination of heightlock and timelock @@ -112,7 +112,7 @@ impl Liftable for Miniscript } } -impl Liftable for Terminal { +impl Liftable for Terminal { fn lift(&self) -> Result, Error> { let ret = match *self { Terminal::PkK(ref pk) | Terminal::PkH(ref pk) => Semantic::Key(pk.clone()), @@ -163,7 +163,7 @@ impl Liftable for Terminal { } } -impl Liftable for Descriptor { +impl Liftable for Descriptor { fn lift(&self) -> Result, Error> { match *self { Descriptor::Bare(ref bare) => bare.lift(), @@ -176,13 +176,13 @@ impl Liftable for Descriptor { } } -impl Liftable for Semantic { +impl Liftable for Semantic { fn lift(&self) -> Result, Error> { Ok(self.clone()) } } -impl Liftable for Concrete { +impl Liftable for Concrete { fn lift(&self) -> Result, Error> { // do not lift if there is a possible satisfaction // involving combination of timelocks and heightlocks diff --git a/src/policy/semantic.rs b/src/policy/semantic.rs index aa2de8680..1d2dc44f7 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -13,7 +13,7 @@ use bitcoin::{absolute, Sequence}; use super::concrete::PolicyError; use super::ENTAILMENT_MAX_TERMINALS; use crate::prelude::*; -use crate::{errstr, expression, AbsLockTime, Error, ForEachKey, MiniscriptKey, Translator}; +use crate::{errstr, expression, AbsLockTime, Error, ForEachKey, Key, Translator}; /// Abstract policy which corresponds to the semantics of a miniscript and /// which allows complex forms of analysis, e.g. filtering and normalization. @@ -22,7 +22,7 @@ use crate::{errstr, expression, AbsLockTime, Error, ForEachKey, MiniscriptKey, T /// 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 Policy { /// Unsatisfiable. Unsatisfiable, /// Trivially satisfiable. @@ -47,7 +47,7 @@ pub enum Policy { impl Policy where - Pk: MiniscriptKey, + Pk: Key, { /// Constructs a `Policy::After` from `n`. /// @@ -64,13 +64,13 @@ where } } -impl ForEachKey for Policy { +impl ForEachKey for Policy { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { self.real_for_each_key(&mut pred) } } -impl Policy { +impl Policy { fn real_for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: &mut F) -> bool { match *self { Policy::Unsatisfiable | Policy::Trivial => true, @@ -131,7 +131,7 @@ impl Policy { pub fn translate_pk(&self, t: &mut T) -> Result, E> where T: Translator, - Q: MiniscriptKey, + Q: Key, { self._translate_pk(t) } @@ -139,7 +139,7 @@ impl Policy { fn _translate_pk(&self, t: &mut T) -> Result, E> where T: Translator, - Q: MiniscriptKey, + Q: Key, { match *self { Policy::Unsatisfiable => Ok(Policy::Unsatisfiable), @@ -244,7 +244,7 @@ impl Policy { } } -impl fmt::Debug for Policy { +impl fmt::Debug for Policy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Policy::Unsatisfiable => f.write_str("UNSATISFIABLE()"), @@ -277,7 +277,7 @@ impl fmt::Debug for Policy { } } -impl fmt::Display for Policy { +impl fmt::Display for Policy { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Policy::Unsatisfiable => f.write_str("UNSATISFIABLE"), @@ -400,7 +400,7 @@ impl_from_tree!( } ); -impl 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 { @@ -627,7 +627,7 @@ impl Policy { } } -impl Policy { +impl Policy { /// "Sorts" a policy to bring it into a canonical form to allow comparisons. /// /// Does **not** allow policies to be compared for functional equivalence; diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 1668f2f66..8905cb4dc 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -22,7 +22,7 @@ use bitcoin::{absolute, bip32, Script, ScriptBuf, Sequence}; use crate::miniscript::context::SigType; use crate::prelude::*; use crate::{ - descriptor, interpreter, DefiniteDescriptorKey, Descriptor, DescriptorPublicKey, MiniscriptKey, + descriptor, interpreter, DefiniteDescriptorKey, Descriptor, DescriptorPublicKey, Key, Preimage32, Satisfier, ToPublicKey, TranslatePk, Translator, }; @@ -271,7 +271,7 @@ impl<'psbt> PsbtInputSatisfier<'psbt> { } } -impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfier<'psbt> { +impl<'psbt, Pk: Key + ToPublicKey> Satisfier for PsbtInputSatisfier<'psbt> { fn lookup_tap_key_spend_sig(&self) -> Option { self.psbt.inputs[self.index].tap_key_sig } diff --git a/src/pub_macros.rs b/src/pub_macros.rs index bdb0d59b4..5e3ccbecb 100644 --- a/src/pub_macros.rs +++ b/src/pub_macros.rs @@ -47,29 +47,29 @@ macro_rules! translate_hash_fail { ($source: ty, $target:ty, $error_ty: ty) => { fn sha256( &mut self, - _sha256: &<$source as $crate::MiniscriptKey>::Sha256, - ) -> Result<<$target as $crate::MiniscriptKey>::Sha256, $error_ty> { + _sha256: &<$source as $crate::Key>::Sha256, + ) -> Result<<$target as $crate::Key>::Sha256, $error_ty> { panic!("Called sha256 on translate_only_pk") } fn hash256( &mut self, - _hash256: &<$source as $crate::MiniscriptKey>::Hash256, - ) -> Result<<$target as $crate::MiniscriptKey>::Hash256, $error_ty> { + _hash256: &<$source as $crate::Key>::Hash256, + ) -> Result<<$target as $crate::Key>::Hash256, $error_ty> { panic!("Called hash256 on translate_only_pk") } fn hash160( &mut self, - _hash160: &<$source as $crate::MiniscriptKey>::Hash160, - ) -> Result<<$target as $crate::MiniscriptKey>::Hash160, $error_ty> { + _hash160: &<$source as $crate::Key>::Hash160, + ) -> Result<<$target as $crate::Key>::Hash160, $error_ty> { panic!("Called hash160 on translate_only_pk") } fn ripemd160( &mut self, - _ripemd160: &<$source as $crate::MiniscriptKey>::Ripemd160, - ) -> Result<<$target as $crate::MiniscriptKey>::Ripemd160, $error_ty> { + _ripemd160: &<$source as $crate::Key>::Ripemd160, + ) -> Result<<$target as $crate::Key>::Ripemd160, $error_ty> { panic!("Called ripemd160 on translate_only_pk") } }; @@ -88,29 +88,29 @@ macro_rules! translate_hash_clone { ($source: ty, $target:ty, $error_ty: ty) => { fn sha256( &mut self, - sha256: &<$source as $crate::MiniscriptKey>::Sha256, - ) -> Result<<$target as $crate::MiniscriptKey>::Sha256, $error_ty> { + sha256: &<$source as $crate::Key>::Sha256, + ) -> Result<<$target as $crate::Key>::Sha256, $error_ty> { Ok((*sha256).into()) } fn hash256( &mut self, - hash256: &<$source as $crate::MiniscriptKey>::Hash256, - ) -> Result<<$target as $crate::MiniscriptKey>::Hash256, $error_ty> { + hash256: &<$source as $crate::Key>::Hash256, + ) -> Result<<$target as $crate::Key>::Hash256, $error_ty> { Ok((*hash256).into()) } fn hash160( &mut self, - hash160: &<$source as $crate::MiniscriptKey>::Hash160, - ) -> Result<<$target as $crate::MiniscriptKey>::Hash160, $error_ty> { + hash160: &<$source as $crate::Key>::Hash160, + ) -> Result<<$target as $crate::Key>::Hash160, $error_ty> { Ok((*hash160).into()) } fn ripemd160( &mut self, - ripemd160: &<$source as $crate::MiniscriptKey>::Ripemd160, - ) -> Result<<$target as $crate::MiniscriptKey>::Ripemd160, $error_ty> { + ripemd160: &<$source as $crate::Key>::Ripemd160, + ) -> Result<<$target as $crate::Key>::Ripemd160, $error_ty> { Ok((*ripemd160).into()) } }; diff --git a/src/test_utils.rs b/src/test_utils.rs index dea8aae58..329ea0de1 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -12,7 +12,7 @@ use bitcoin::secp256k1; use crate::miniscript::context::SigType; use crate::{hash256, ToPublicKey, Translator}; -/// Translate from a String MiniscriptKey type to bitcoin::PublicKey +/// Translate from a String Key type to bitcoin::PublicKey /// If the hashmap is populated, this will lookup for keys in HashMap /// Otherwise, this will return a translation to a random key #[derive(Debug, PartialEq, Eq, Clone)] diff --git a/src/util.rs b/src/util.rs index 0564108a3..5469ef7e8 100644 --- a/src/util.rs +++ b/src/util.rs @@ -8,7 +8,7 @@ use bitcoin::PubkeyHash; use crate::miniscript::context; use crate::prelude::*; -use crate::{ScriptContext, ToPublicKey}; +use crate::{Context, ToPublicKey}; pub(crate) fn varint_len(n: usize) -> usize { bitcoin::VarInt(n as u64).len() } @@ -38,20 +38,20 @@ pub(crate) trait MsKeyBuilder { fn push_ms_key(self, key: &Pk) -> Self where Pk: ToPublicKey, - Ctx: ScriptContext; + Ctx: Context; /// Serialize the key hash as bytes based on script context. Used when encoding miniscript into bitcoin script fn push_ms_key_hash(self, key: &Pk) -> Self where Pk: ToPublicKey, - Ctx: ScriptContext; + Ctx: Context; } impl MsKeyBuilder for script::Builder { fn push_ms_key(self, key: &Pk) -> Self where Pk: ToPublicKey, - Ctx: ScriptContext, + Ctx: Context, { match Ctx::sig_type() { context::SigType::Ecdsa => self.push_key(&key.to_public_key()), @@ -62,7 +62,7 @@ impl MsKeyBuilder for script::Builder { fn push_ms_key_hash(self, key: &Pk) -> Self where Pk: ToPublicKey, - Ctx: ScriptContext, + Ctx: Context, { match Ctx::sig_type() { context::SigType::Ecdsa => self.push_slice(key.to_public_key().pubkey_hash()), From f8a847d73213146ebd42f34dfebb64cd1fabb126 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 25 Jul 2023 15:41:13 +1000 Subject: [PATCH 2/4] Take advantage of shorter generic Key Now we have `Key` instead of `MiniscriptKey` we can take advantage of the shorter name to inline the where clauses when appropriate. --- src/descriptor/bare.rs | 12 ++---------- src/descriptor/mod.rs | 6 +----- src/descriptor/segwitv0.rs | 12 ++---------- src/descriptor/sh.rs | 6 +----- src/descriptor/tr.rs | 6 +----- src/lib.rs | 6 +----- 6 files changed, 8 insertions(+), 40 deletions(-) diff --git a/src/descriptor/bare.rs b/src/descriptor/bare.rs index 3179f486a..8d50d6136 100644 --- a/src/descriptor/bare.rs +++ b/src/descriptor/bare.rs @@ -180,11 +180,7 @@ impl ForEachKey for Bare { } } -impl TranslatePk for Bare

-where - P: Key, - Q: Key, -{ +impl TranslatePk for Bare

{ type Output = Bare; fn translate_pk(&self, t: &mut T) -> Result, TranslateErr> @@ -365,11 +361,7 @@ impl ForEachKey for Pkh { } } -impl TranslatePk for Pkh

-where - P: Key, - Q: Key, -{ +impl TranslatePk for Pkh

{ type Output = Pkh; fn translate_pk(&self, t: &mut T) -> Result> diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index c9bda096b..91e41a051 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -509,11 +509,7 @@ impl Descriptor { } } -impl TranslatePk for Descriptor

-where - P: Key, - Q: Key, -{ +impl TranslatePk for Descriptor

{ type Output = Descriptor; /// Converts a descriptor using abstract keys to one using specific keys. diff --git a/src/descriptor/segwitv0.rs b/src/descriptor/segwitv0.rs index 9a00f199c..135abc39c 100644 --- a/src/descriptor/segwitv0.rs +++ b/src/descriptor/segwitv0.rs @@ -274,11 +274,7 @@ impl ForEachKey for Wsh { } } -impl TranslatePk for Wsh

-where - P: Key, - Q: Key, -{ +impl TranslatePk for Wsh

{ type Output = Wsh; fn translate_pk(&self, t: &mut T) -> Result> @@ -472,11 +468,7 @@ impl ForEachKey for Wpkh { } } -impl TranslatePk for Wpkh

-where - P: Key, - Q: Key, -{ +impl TranslatePk for Wpkh

{ type Output = Wpkh; fn translate_pk(&self, t: &mut T) -> Result> diff --git a/src/descriptor/sh.rs b/src/descriptor/sh.rs index 9545a9573..fcf00bb5f 100644 --- a/src/descriptor/sh.rs +++ b/src/descriptor/sh.rs @@ -429,11 +429,7 @@ impl ForEachKey for Sh { } } -impl TranslatePk for Sh

-where - P: Key, - Q: Key, -{ +impl TranslatePk for Sh

{ type Output = Sh; fn translate_pk(&self, t: &mut T) -> Result> diff --git a/src/descriptor/tr.rs b/src/descriptor/tr.rs index ce82601a7..1b2039462 100644 --- a/src/descriptor/tr.rs +++ b/src/descriptor/tr.rs @@ -667,11 +667,7 @@ impl ForEachKey for Tr { } } -impl TranslatePk for Tr

-where - P: Key, - Q: Key, -{ +impl TranslatePk for Tr

{ type Output = Tr; fn translate_pk(&self, translate: &mut T) -> Result> diff --git a/src/lib.rs b/src/lib.rs index 1acc8ac8b..08c3dddd9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -410,11 +410,7 @@ impl fmt::Debug for TranslateErr { /// Converts a descriptor using abstract keys to one using specific keys. Uses translator `t` to do /// the actual translation function calls. -pub trait TranslatePk -where - P: Key, - Q: Key, -{ +pub trait TranslatePk { /// The associated output type. This must be `Self`. type Output; From cf6607896bdeb43e698c5c26ec5944df6a749e96 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 25 Jul 2023 15:32:00 +1000 Subject: [PATCH 3/4] Add MiniscriptKey and ScriptContext aliases We just renamed the `MinscriptKey` trait to `Key` and `ScriptContext` to `Context`. Add an alias for each of them to the original name. This helps backwards compatibility but also makes the library more ergonomic since the new names are so generic they could cause naming conflicts in downstream crates. --- src/lib.rs | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 08c3dddd9..1fa9d6cbe 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -140,6 +140,10 @@ use std::error; use bitcoin::blockdata::{opcodes, script}; use bitcoin::hashes::{hash160, ripemd160, sha256, Hash}; use bitcoin::locktime::absolute; +/// `ScriptContext` alias to make usage of the library more ergonomic by reducing naming conflicts. +pub use Context as ScriptContext; +/// `MiniscriptKey` alias to make usage of the library more ergonomic by reducing naming conflicts. +pub use Key as MiniscriptKey; pub use crate::descriptor::{DefiniteDescriptorKey, Descriptor, DescriptorPublicKey}; pub use crate::interpreter::Interpreter; From 24c11c09f66e213306ff3569e2b07adfe1bf3221 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 8 Aug 2023 09:11:11 +1000 Subject: [PATCH 4/4] Add ScriptContextError alias Add an alias to the `miniscript::context` module to maintain backwards comparability. Also, as for `ScriptContext` this may reduce potential naming conflicts downstream because "context" is not that unique. Note the alias is in `miniscript::context` but in `miniscript` there is a re-export of `Contetxt` but not one of the error. --- src/miniscript/context.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/miniscript/context.rs b/src/miniscript/context.rs index 589cfdf86..a37e074bf 100644 --- a/src/miniscript/context.rs +++ b/src/miniscript/context.rs @@ -7,6 +7,8 @@ use std::error; use bitcoin::constants::MAX_BLOCK_WEIGHT; use bitcoin::hashes::{hash160, ripemd160, sha256}; +/// `ScriptContextError` alias for backwards compatability and to reduce potential naming conflicts. +pub use ContextError as ScriptContextError; use super::decode::ParseableKey; use crate::miniscript::limits::{