From 62b1e408aa1e2ead017279f2d786fe5ab179feae Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Thu, 21 Jul 2022 13:41:59 +1000 Subject: [PATCH] Use Key instead of MiniscriptKey One of the main traits in this lib is `MiniscriptKey`, we can shorten this to `Key` with no loss of meaning. This makes the whole codebase more terse. Terse code, if clear, is easier to read because there is less clutter. Also terseness assists the formatter and can reduce lines of code. This patch is the result of running `s/MiniscriptKey/Key/g` on all source files and then running the formatter. To preserve backwards compatibility and make the library more ergonomical to use; add a 'trait alias' of `MiniscriptKey` -> `Key`. --- examples/sign_multisig.rs | 2 +- src/descriptor/bare.rs | 39 ++++---- src/descriptor/key.rs | 6 +- src/descriptor/mod.rs | 32 +++---- src/descriptor/segwitv0.rs | 41 +++++---- src/descriptor/sh.rs | 24 ++--- src/descriptor/sortedmulti.rs | 22 ++--- src/descriptor/tr.rs | 52 ++++++----- src/interpreter/inner.rs | 2 +- src/interpreter/mod.rs | 12 +-- src/lib.rs | 87 +++++++++--------- src/macros.rs | 62 ++++++------- src/miniscript/analyzable.rs | 4 +- src/miniscript/astelem.rs | 26 +++--- src/miniscript/context.rs | 134 +++++++++++++--------------- src/miniscript/decode.rs | 8 +- src/miniscript/iter.rs | 38 ++++---- src/miniscript/mod.rs | 38 ++++---- src/miniscript/satisfy.rs | 51 +++++------ src/miniscript/types/extra_props.rs | 4 +- src/miniscript/types/mod.rs | 12 +-- src/policy/compiler.rs | 32 +++---- src/policy/concrete.rs | 20 ++--- src/policy/mod.rs | 16 ++-- src/policy/semantic.rs | 20 ++--- src/psbt/mod.rs | 6 +- src/test_utils.rs | 4 +- src/util.rs | 2 +- tests/test_cpp.rs | 2 +- tests/test_desc.rs | 2 +- 30 files changed, 387 insertions(+), 413 deletions(-) diff --git a/examples/sign_multisig.rs b/examples/sign_multisig.rs index 5c58bf5d2..bdcc0fb65 100644 --- a/examples/sign_multisig.rs +++ b/examples/sign_multisig.rs @@ -35,7 +35,7 @@ fn main() { assert_eq!(descriptor.max_satisfaction_weight().unwrap(), 258); // 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 9d5dbcc85..0d38f2331 100644 --- a/src/descriptor/bare.rs +++ b/src/descriptor/bare.rs @@ -30,19 +30,18 @@ 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, TranslatePk, - Translator, + BareCtx, Error, ForEachKey, Key, Miniscript, Satisfier, ToPublicKey, 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 @@ -81,7 +80,7 @@ impl Bare { } } -impl Bare { +impl Bare { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> Script { self.ms.encode() @@ -124,13 +123,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 { let desc = format!("{}", self.ms); let checksum = desc_checksum(&desc).map_err(|_| fmt::Error)?; @@ -138,7 +137,7 @@ impl fmt::Display for Bare { } } -impl Liftable for Bare { +impl Liftable for Bare { fn lift(&self) -> Result, Error> { self.ms.lift() } @@ -163,7 +162,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 where Pk: 'a, @@ -175,8 +174,8 @@ impl ForEachKey for Bare { impl TranslatePk for Bare

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Bare; @@ -190,12 +189,12 @@ 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) -> Self { // do the top-level checks @@ -223,7 +222,7 @@ impl Pkh { } } -impl Pkh { +impl Pkh { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> Script { // Fine to hard code the `Network` here because we immediately call @@ -278,13 +277,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 { let desc = format!("pkh({})", self.pk); let checksum = desc_checksum(&desc).map_err(|_| fmt::Error)?; @@ -292,7 +291,7 @@ impl fmt::Display for Pkh { } } -impl Liftable for Pkh { +impl Liftable for Pkh { fn lift(&self) -> Result, Error> { Ok(semantic::Policy::KeyHash(self.pk.to_pubkeyhash())) } @@ -325,7 +324,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 where Pk: 'a, @@ -337,8 +336,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 b12873e81..b5263213b 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -10,7 +10,7 @@ use bitcoin::util::bip32; use bitcoin::{self, XOnlyPublicKey, XpubIdentifier}; use crate::prelude::*; -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)] @@ -729,7 +729,7 @@ impl DescriptorXKey { } } -impl MiniscriptKey for DescriptorPublicKey { +impl Key for DescriptorPublicKey { // This allows us to be able to derive public keys even for PkH s type RawPkHash = Self; type Sha256 = sha256::Hash; @@ -817,7 +817,7 @@ impl fmt::Display for DefiniteDescriptorKey { } } -impl MiniscriptKey for DefiniteDescriptorKey { +impl Key for DefiniteDescriptorKey { // This allows us to be able to derive public keys even for PkH s type RawPkHash = Self; type Sha256 = sha256::Hash; diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index 1c8083d22..b0d692c6f 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -37,8 +37,8 @@ use self::checksum::verify_checksum; use crate::miniscript::{Legacy, Miniscript, Segwitv0}; use crate::prelude::*; use crate::{ - expression, hash256, miniscript, BareCtx, Error, ForEachKey, MiniscriptKey, PkTranslator, - Satisfier, ToPublicKey, TranslatePk, Translator, + expression, hash256, miniscript, BareCtx, Error, ForEachKey, Key, PkTranslator, Satisfier, + ToPublicKey, TranslatePk, Translator, }; mod bare; @@ -72,7 +72,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 @@ -87,42 +87,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) @@ -172,7 +172,7 @@ impl DescriptorType { } } -impl Descriptor { +impl Descriptor { // Keys /// Create a new pk descriptor @@ -339,7 +339,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. @@ -472,8 +472,8 @@ impl Descriptor { impl TranslatePk for Descriptor

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Descriptor; @@ -494,7 +494,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 where Pk: 'a, @@ -821,7 +821,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) => write!(f, "{:?}", sub), @@ -834,7 +834,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) => write!(f, "{}", sub), diff --git a/src/descriptor/segwitv0.rs b/src/descriptor/segwitv0.rs index 9f306ccbc..21f937163 100644 --- a/src/descriptor/segwitv0.rs +++ b/src/descriptor/segwitv0.rs @@ -28,17 +28,16 @@ use crate::policy::{semantic, Liftable}; use crate::prelude::*; use crate::util::varint_len; use crate::{ - Error, ForEachKey, Miniscript, MiniscriptKey, Satisfier, Segwitv0, ToPublicKey, TranslatePk, - Translator, + Error, ForEachKey, Key, Miniscript, Satisfier, Segwitv0, ToPublicKey, 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 @@ -114,7 +113,7 @@ impl Wsh { } } -impl Wsh { +impl Wsh { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> Script { self.inner_script().to_v0_p2wsh() @@ -177,14 +176,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(), @@ -218,7 +217,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), @@ -227,7 +226,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 { let desc = self.to_string_no_checksum(); let checksum = desc_checksum(&desc).map_err(|_| fmt::Error)?; @@ -245,7 +244,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 where Pk: 'a, @@ -260,8 +259,8 @@ impl ForEachKey for Wsh { impl TranslatePk for Wsh

where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { type Output = Wsh; @@ -279,12 +278,12 @@ 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 { // do the top-level checks @@ -334,7 +333,7 @@ impl Wpkh { } } -impl Wpkh { +impl Wpkh { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> Script { let addr = Address::p2wpkh(&self.pk.to_public_key(), Network::Bitcoin) @@ -391,13 +390,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 { let desc = self.to_string_no_checksum(); let checksum = desc_checksum(&desc).map_err(|_| fmt::Error)?; @@ -405,7 +404,7 @@ impl fmt::Display for Wpkh { } } -impl Liftable for Wpkh { +impl Liftable for Wpkh { fn lift(&self) -> Result, Error> { Ok(semantic::Policy::KeyHash(self.pk.to_pubkeyhash())) } @@ -438,7 +437,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 where Pk: 'a, @@ -450,8 +449,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 3b387fc85..74b496c06 100644 --- a/src/descriptor/sh.rs +++ b/src/descriptor/sh.rs @@ -31,20 +31,20 @@ 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, TranslatePk, Translator, + push_opcode_size, Error, ForEachKey, Key, Legacy, Miniscript, Satisfier, Segwitv0, ToPublicKey, + 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 @@ -55,7 +55,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(), @@ -66,7 +66,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), @@ -77,7 +77,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 { let desc = match self.inner { ShInner::Wsh(ref wsh) => format!("sh({})", wsh.to_string_no_checksum()), @@ -126,7 +126,7 @@ impl_from_str!( } ); -impl Sh { +impl Sh { /// Get the Inner pub fn into_inner(self) -> ShInner { self.inner @@ -236,7 +236,7 @@ impl Sh { } } -impl Sh { +impl Sh { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> Script { match self.inner { @@ -376,7 +376,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 where Pk: 'a, @@ -393,8 +393,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 a79e84507..213f49c02 100644 --- a/src/descriptor/sortedmulti.rs +++ b/src/descriptor/sortedmulti.rs @@ -27,13 +27,13 @@ use crate::miniscript::decode::Terminal; use crate::miniscript::limits::MAX_PUBKEYS_PER_MULTISIG; use crate::prelude::*; use crate::{ - errstr, expression, miniscript, policy, script_num_size, Error, ForEachKey, Miniscript, - MiniscriptKey, Satisfier, ToPublicKey, Translator, + errstr, expression, miniscript, policy, script_num_size, Error, ForEachKey, Key, Miniscript, + Satisfier, ToPublicKey, 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 @@ -42,7 +42,7 @@ pub struct SortedMultiVec { 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`. @@ -100,7 +100,7 @@ impl SortedMultiVec { ) -> Result, FuncError> where T: Translator, - Q: MiniscriptKey, + Q: Key, { let pks: Result, _> = self.pks.iter().map(|pk| t.pk(pk)).collect(); Ok(SortedMultiVec { @@ -111,7 +111,7 @@ impl SortedMultiVec { } } -impl ForEachKey for SortedMultiVec { +impl ForEachKey for SortedMultiVec { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool where Pk: 'a, @@ -121,7 +121,7 @@ impl ForEachKey for SortedMultiVec SortedMultiVec { +impl SortedMultiVec { /// utility function to sanity a sorted multi vec pub fn sanity_check(&self) -> Result<(), Error> { let ms: Miniscript = @@ -133,7 +133,7 @@ impl SortedMultiVec { } } -impl SortedMultiVec { +impl SortedMultiVec { /// Create Terminal::Multi containing sorted pubkeys pub fn sorted_node(&self) -> Terminal where @@ -211,7 +211,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, @@ -225,13 +225,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 7280893f7..f3bdf26ed 100644 --- a/src/descriptor/tr.rs +++ b/src/descriptor/tr.rs @@ -18,15 +18,13 @@ use crate::policy::semantic::Policy; use crate::policy::Liftable; use crate::prelude::*; use crate::util::{varint_len, witness_size}; -use crate::{ - errstr, Error, ForEachKey, MiniscriptKey, Satisfier, Tap, ToPublicKey, TranslatePk, Translator, -}; +use crate::{errstr, Error, ForEachKey, Key, Satisfier, Tap, ToPublicKey, 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(Arc>, Arc>), /// A taproot leaf denoting a spending condition @@ -37,7 +35,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 @@ -52,7 +50,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`, @@ -71,15 +69,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) => {} @@ -89,7 +87,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 => {} @@ -99,14 +97,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 { // Helper function to compute height // TODO: Instead of computing this every time we add a new leaf, we should // add height as a separate field in taptree @@ -130,7 +128,7 @@ impl TapTree { fn translate_helper(&self, t: &mut T) -> Result, Error> where T: Translator, - Q: MiniscriptKey, + Q: Key, { let frag = match self { TapTree::Tree(l, r) => TapTree::Tree( @@ -143,7 +141,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(ref left, ref right) => write!(f, "{{{},{}}}", *left, *right), @@ -152,7 +150,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(ref left, ref right) => write!(f, "{{{:?},{:?}}}", *left, *right), @@ -161,7 +159,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 { let nodes = tree.as_ref().map(|t| t.taptree_height()).unwrap_or(0); @@ -307,7 +305,7 @@ impl Tr { } } -impl Tr { +impl Tr { /// Obtains the corresponding script pubkey for this descriptor. pub fn script_pubkey(&self) -> Script { let output_key = self.spend_info().output_key(); @@ -358,13 +356,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); @@ -461,7 +459,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), @@ -470,7 +468,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 { let desc = self.to_string_no_checksum(); let checksum = desc_checksum(&desc).map_err(|_| fmt::Error)?; @@ -546,9 +544,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 l, ref r) => { Ok(Policy::Threshold(1, vec![lift_helper(l)?, lift_helper(r)?])) @@ -562,7 +560,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( @@ -577,7 +575,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 where Pk: 'a, @@ -592,8 +590,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 efe6a44aa..8ce247dd2 100644 --- a/src/interpreter/inner.rs +++ b/src/interpreter/inner.rs @@ -20,7 +20,7 @@ use bitcoin::util::taproot::{ControlBlock, TAPROOT_ANNEX_PREFIX}; use super::{stack, BitcoinKey, Error, Stack, TypedHash160}; use crate::miniscript::context::{NoChecks, ScriptContext}; use crate::prelude::*; -use crate::{BareCtx, Legacy, Miniscript, MiniscriptKey, PkTranslator, Segwitv0, Tap}; +use crate::{BareCtx, Key, Legacy, Miniscript, PkTranslator, Segwitv0, Tap}; /// Attempts to parse a slice as a Bitcoin public key, checking compressedness /// if asked to, but otherwise dropping it diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index 2c2c4b917..8dc54873e 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -39,7 +39,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> { @@ -83,15 +83,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)] @@ -147,7 +147,7 @@ impl TypedHash160 { } } -impl MiniscriptKey for BitcoinKey { +impl Key for BitcoinKey { type RawPkHash = TypedHash160; type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; @@ -1049,7 +1049,7 @@ mod tests { use super::inner::ToNoChecks; use super::*; use crate::miniscript::context::NoChecks; - use crate::{Miniscript, MiniscriptKey, ToPublicKey}; + use crate::{Key, Miniscript, ToPublicKey}; fn setup_keys_sigs( n: usize, diff --git a/src/lib.rs b/src/lib.rs index 3deae23aa..d9ea890ea 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -134,6 +134,9 @@ use std::error; use bitcoin::blockdata::{opcodes, script}; use bitcoin::hashes::{hash160, ripemd160, sha256, Hash}; +/// Export a type alias to make usage of the library more ergonomic since the +/// `Key` trait name is so generic that it may cause naming conflicts. +pub use Key as MiniscriptKey; pub use crate::descriptor::{DefiniteDescriptorKey, Descriptor, DescriptorPublicKey}; pub use crate::interpreter::Interpreter; @@ -144,7 +147,7 @@ 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 @@ -157,24 +160,24 @@ pub trait MiniscriptKey: Clone + Eq + Ord + fmt::Debug + fmt::Display + hash::Ha false } - /// The associated PublicKey Hash for this [`MiniscriptKey`], + /// The associated PublicKey Hash for this [`Key`], /// used in the raw_pkh fragment /// This fragment is only internally used for representing partial descriptors when parsing from script /// The library does not support creating partial descriptors yet. type RawPkHash: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; - /// The associated [`sha256::Hash`] for this [`MiniscriptKey`], + /// The associated [`sha256::Hash`] for this [`Key`], /// used in the hash256 fragment. type Sha256: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; - /// The associated [`hash256::Hash`] for this [`MiniscriptKey`], + /// The associated [`hash256::Hash`] for this [`Key`], /// used in the hash256 fragment. type Hash256: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; - /// The associated [`ripedmd160::Hash`] for this [`MiniscriptKey`] type. + /// The associated [`ripedmd160::Hash`] for this [`Key`] type. /// used in the ripemd160 fragment type Ripemd160: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; - /// The associated [`hash160::Hash`] for this [`MiniscriptKey`] type. + /// The associated [`hash160::Hash`] for this [`Key`] type. /// used in the hash160 fragment type Hash160: Clone + Eq + Ord + fmt::Display + fmt::Debug + hash::Hash; @@ -182,7 +185,7 @@ pub trait MiniscriptKey: Clone + Eq + Ord + fmt::Debug + fmt::Display + hash::Ha fn to_pubkeyhash(&self) -> Self::RawPkHash; } -impl MiniscriptKey for bitcoin::secp256k1::PublicKey { +impl Key for bitcoin::secp256k1::PublicKey { type RawPkHash = hash160::Hash; type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; @@ -194,7 +197,7 @@ impl MiniscriptKey for bitcoin::secp256k1::PublicKey { } } -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 @@ -211,7 +214,7 @@ impl MiniscriptKey for bitcoin::PublicKey { } } -impl MiniscriptKey for bitcoin::secp256k1::XOnlyPublicKey { +impl Key for bitcoin::secp256k1::XOnlyPublicKey { type RawPkHash = hash160::Hash; type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; @@ -227,7 +230,7 @@ impl MiniscriptKey for bitcoin::secp256k1::XOnlyPublicKey { } } -impl MiniscriptKey for String { +impl Key for String { type RawPkHash = String; type Sha256 = String; // specify hashes as string type Hash256 = String; @@ -240,7 +243,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; @@ -253,22 +256,22 @@ pub trait ToPublicKey: MiniscriptKey { /// Converts a hashed version of the public key to a `hash160` hash. /// /// This method must be consistent with `to_public_key`, in the sense - /// that calling `MiniscriptKey::to_pubkeyhash` followed by this function + /// that calling `Key::to_pubkeyhash` followed by this function /// should give the same result as calling `to_public_key` and hashing /// the result directly. - fn hash_to_hash160(hash: &::RawPkHash) -> hash160::Hash; + fn hash_to_hash160(hash: &::RawPkHash) -> hash160::Hash; - /// 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 { @@ -373,7 +376,7 @@ impl str::FromStr for DummyKey { } } -impl MiniscriptKey for DummyKey { +impl Key for DummyKey { type RawPkHash = DummyKeyHash; type Sha256 = DummySha256Hash; type Hash256 = DummyHash256; @@ -565,8 +568,8 @@ impl hash::Hash for DummyHash160Hash { /// 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; @@ -592,8 +595,8 @@ where /// from Pk/Pkh don't change in translation pub trait PkTranslator where - P: MiniscriptKey, - Q: MiniscriptKey, + P: Key, + Q: Key, { /// Provides the translation public keys P -> Q fn pk(&mut self, pk: &P) -> Result; @@ -605,8 +608,8 @@ where impl Translator for T where T: PkTranslator, - P: MiniscriptKey, - Q: MiniscriptKey< + P: Key, + Q: Key< Sha256 = P::Sha256, Hash256 = P::Hash256, Ripemd160 = P::Ripemd160, @@ -617,29 +620,23 @@ where >::pk(self, pk) } - fn pkh( - &mut self, - pkh: &

::RawPkHash, - ) -> Result<::RawPkHash, E> { + fn pkh(&mut self, pkh: &

::RawPkHash) -> Result<::RawPkHash, E> { >::pkh(self, pkh) } - fn sha256(&mut self, sha256: &

::Sha256) -> Result<::Sha256, E> { + fn sha256(&mut self, sha256: &

::Sha256) -> Result<::Sha256, E> { Ok(sha256.clone()) } - fn hash256(&mut self, hash256: &

::Hash256) -> Result<::Hash256, E> { + fn hash256(&mut self, hash256: &

::Hash256) -> Result<::Hash256, E> { Ok(hash256.clone()) } - fn ripemd160( - &mut self, - ripemd160: &

::Ripemd160, - ) -> Result<::Ripemd160, E> { + fn ripemd160(&mut self, ripemd160: &

::Ripemd160) -> Result<::Ripemd160, E> { Ok(ripemd160.clone()) } - fn hash160(&mut self, hash160: &

::Hash160) -> Result<::Hash160, E> { + fn hash160(&mut self, hash160: &

::Hash160) -> Result<::Hash160, E> { Ok(hash160.clone()) } } @@ -648,8 +645,8 @@ where /// 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; @@ -662,9 +659,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 @@ -672,7 +669,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 @@ -912,7 +909,7 @@ impl error::Error for Error { #[doc(hidden)] impl From> for Error where - Pk: MiniscriptKey, + Pk: Key, Ctx: ScriptContext, { fn from(e: miniscript::types::Error) -> Error { diff --git a/src/macros.rs b/src/macros.rs index cdad906ec..7423b89b5 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -26,18 +26,18 @@ macro_rules! impl_from_tree { ) => { impl $crate::expression::FromTree for $name where - Pk: MiniscriptKey + core::str::FromStr, + Pk: Key + core::str::FromStr, Pk::RawPkHash: 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, - <::RawPkHash 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, + <::RawPkHash 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,18 +60,18 @@ macro_rules! impl_from_str { ) => { impl core::str::FromStr for $name where - Pk: MiniscriptKey + core::str::FromStr, + Pk: Key + core::str::FromStr, Pk::RawPkHash: 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, - <::RawPkHash 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, + <::RawPkHash 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; @@ -94,18 +94,18 @@ macro_rules! impl_block_str { ) => { impl $name where - Pk: MiniscriptKey + core::str::FromStr, + Pk: Key + core::str::FromStr, Pk::RawPkHash: 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, - <::RawPkHash 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, + <::RawPkHash 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])* @@ -123,22 +123,22 @@ 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::RawPkHash: 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, - <::RawPkHash as core::str::FromStr>::Err: + <::RawPkHash as 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,)* { @@ -154,22 +154,22 @@ 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::RawPkHash: 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, - <::RawPkHash as core::str::FromStr>::Err: + <::RawPkHash as 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,)* { @@ -208,7 +208,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 7f2f2f11a..bf38fd4d8 100644 --- a/src/miniscript/analyzable.rs +++ b/src/miniscript/analyzable.rs @@ -23,7 +23,7 @@ use std::error; use crate::miniscript::iter::PkPkh; use crate::prelude::*; -use crate::{Miniscript, MiniscriptKey, ScriptContext}; +use crate::{Key, Miniscript, ScriptContext}; /// Possible reasons Miniscript guarantees can fail /// We currently mark Miniscript as Non-Analyzable if @@ -83,7 +83,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 b21756430..7b195d4ab 100644 --- a/src/miniscript/astelem.rs +++ b/src/miniscript/astelem.rs @@ -31,11 +31,11 @@ use crate::miniscript::ScriptContext; use crate::prelude::*; use crate::util::MsKeyBuilder; use crate::{ - errstr, expression, script_num_size, Error, ForEachKey, Miniscript, MiniscriptKey, Terminal, - ToPublicKey, TranslatePk, Translator, + errstr, expression, script_num_size, Error, ForEachKey, Key, Miniscript, Terminal, ToPublicKey, + TranslatePk, Translator, }; -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 @@ -58,8 +58,8 @@ impl Terminal { impl TranslatePk for Terminal where - Pk: MiniscriptKey, - Q: MiniscriptKey, + Pk: Key, + Q: Key, Ctx: ScriptContext, { type Output = Terminal; @@ -73,7 +73,7 @@ where } } -impl Terminal { +impl Terminal { pub(super) fn real_for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: &mut F) -> bool where Pk: 'a, @@ -120,7 +120,7 @@ impl Terminal { pub(super) fn real_translate_pk(&self, t: &mut T) -> Result, E> where - Q: MiniscriptKey, + Q: Key, CtxQ: ScriptContext, T: Translator, { @@ -194,7 +194,7 @@ impl Terminal { } } -impl ForEachKey for Terminal { +impl ForEachKey for Terminal { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool where Pk: 'a, @@ -204,7 +204,7 @@ impl ForEachKey for 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) { @@ -302,7 +302,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), @@ -584,13 +584,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, @@ -599,7 +599,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 d838ee4ba..b74ae5e15 100644 --- a/src/miniscript/context.rs +++ b/src/miniscript/context.rs @@ -29,7 +29,7 @@ use crate::miniscript::limits::{ use crate::miniscript::types; use crate::prelude::*; use crate::util::witness_to_scriptsig; -use crate::{hash256, Error, Miniscript, MiniscriptKey, Terminal}; +use crate::{hash256, Error, Key, Miniscript, Terminal}; /// Error for Script Context #[derive(Clone, PartialEq, Eq, Debug)] @@ -191,11 +191,11 @@ impl fmt::Display for ScriptContextError { pub trait ScriptContext: 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: MiniscriptKey, + Self::Key: Key, + 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; @@ -207,14 +207,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>; /// Check whether the given satisfaction is valid under the ScriptContext /// 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<(), ScriptContextError> { // Only really need to do this for segwitv0 and legacy // Bare is already restrcited by standardness rules // and would reach these limits. @@ -222,18 +222,18 @@ where } /// 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> { Ok(()) @@ -243,11 +243,11 @@ 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> { Ok(()) @@ -257,7 +257,7 @@ 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> { Ok(()) @@ -268,7 +268,7 @@ 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> { Ok(()) @@ -276,9 +276,7 @@ where /// 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<(), ScriptContextError> { Self::check_global_consensus_validity(ms)?; Self::check_global_policy_validity(ms)?; Ok(()) @@ -286,9 +284,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<(), ScriptContextError> { Self::check_global_consensus_validity(ms)?; Self::check_global_policy_validity(ms)?; Self::check_local_consensus_validity(ms)?; @@ -297,7 +293,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))); } @@ -305,7 +301,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(()) } @@ -318,7 +314,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) } @@ -332,7 +328,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; @@ -355,7 +351,7 @@ pub enum Legacy {} impl ScriptContext for Legacy { type Key = bitcoin::PublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( frag: &Terminal, ) -> Result<(), ScriptContextError> { match *frag { @@ -367,7 +363,7 @@ impl ScriptContext for Legacy { } } - fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { // 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 { @@ -376,7 +372,7 @@ impl ScriptContext for Legacy { Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { if ms.ext.pk_cost > MAX_SCRIPT_ELEMENT_SIZE { @@ -411,7 +407,7 @@ impl ScriptContext for Legacy { Ok(()) } - fn check_local_consensus_validity( + fn check_local_consensus_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { match ms.ext.ops.op_count() { @@ -423,7 +419,7 @@ impl ScriptContext for Legacy { } } - fn check_local_policy_validity( + fn check_local_policy_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { // Legacy scripts permit upto 1000 stack elements, 520 bytes consensus limits @@ -438,12 +434,12 @@ impl ScriptContext for Legacy { } } - 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 { @@ -466,13 +462,13 @@ pub enum Segwitv0 {} impl ScriptContext for Segwitv0 { type Key = bitcoin::PublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( _frag: &Terminal, ) -> Result<(), ScriptContextError> { Ok(()) } - fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { if witness.len() > MAX_STANDARD_P2WSH_STACK_ITEMS { return Err(ScriptContextError::MaxWitnessItemssExceeded { actual: witness.len(), @@ -482,7 +478,7 @@ impl ScriptContext for Segwitv0 { Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { if ms.ext.pk_cost > MAX_SCRIPT_SIZE { @@ -522,7 +518,7 @@ impl ScriptContext for Segwitv0 { } } - fn check_local_consensus_validity( + fn check_local_consensus_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { match ms.ext.ops.op_count() { @@ -534,7 +530,7 @@ impl ScriptContext for Segwitv0 { } } - fn check_global_policy_validity( + fn check_global_policy_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { if ms.ext.pk_cost > MAX_STANDARD_P2WSH_SCRIPT_SIZE { @@ -543,7 +539,7 @@ impl ScriptContext for Segwitv0 { Ok(()) } - fn check_local_policy_validity( + fn check_local_policy_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { // We don't need to know if this is actually a p2wsh as the standard satisfaction for @@ -562,12 +558,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 } @@ -586,7 +582,7 @@ pub enum Tap {} impl ScriptContext for Tap { type Key = bitcoin::secp256k1::XOnlyPublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( _frag: &Terminal, ) -> Result<(), ScriptContextError> { // No fragment is malleable in tapscript context. @@ -594,7 +590,7 @@ impl ScriptContext for Tap { Ok(()) } - fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(witness: &[Vec]) -> Result<(), ScriptContextError> { // Note that tapscript has a 1000 limit compared to 100 of segwitv0 if witness.len() > MAX_STACK_SIZE { return Err(ScriptContextError::MaxWitnessItemssExceeded { @@ -605,7 +601,7 @@ impl ScriptContext for Tap { Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { // No script size checks for global consensus rules @@ -629,7 +625,7 @@ impl ScriptContext for Tap { } } - fn check_local_consensus_validity( + fn check_local_consensus_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { // Taproot introduces the concept of sigops budget. @@ -655,20 +651,20 @@ impl ScriptContext for Tap { Ok(()) } - fn check_global_policy_validity( + fn check_global_policy_validity( _ms: &Miniscript, ) -> Result<(), ScriptContextError> { // 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> { 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) } @@ -677,7 +673,7 @@ impl ScriptContext for Tap { SigType::Schnorr } - fn pk_len(_pk: &Pk) -> usize { + fn pk_len(_pk: &Pk) -> usize { 33 } @@ -695,7 +691,7 @@ pub enum BareCtx {} impl ScriptContext for BareCtx { type Key = bitcoin::PublicKey; - fn check_terminal_non_malleable( + fn check_terminal_non_malleable( _frag: &Terminal, ) -> Result<(), ScriptContextError> { // Bare fragments can't contain miniscript because of standardness rules @@ -705,7 +701,7 @@ impl ScriptContext for BareCtx { Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { if ms.ext.pk_cost > MAX_SCRIPT_SIZE { @@ -737,7 +733,7 @@ impl ScriptContext for BareCtx { } } - fn check_local_consensus_validity( + fn check_local_consensus_validity( ms: &Miniscript, ) -> Result<(), ScriptContextError> { match ms.ext.ops.op_count() { @@ -749,7 +745,7 @@ impl ScriptContext for BareCtx { } } - 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(()), @@ -761,12 +757,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() { 65 } else { @@ -793,41 +789,41 @@ pub enum NoChecks {} impl ScriptContext 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> { Ok(()) } - fn check_global_policy_validity( + fn check_global_policy_validity( _ms: &Miniscript, ) -> Result<(), ScriptContextError> { Ok(()) } - fn check_global_consensus_validity( + fn check_global_consensus_validity( _ms: &Miniscript, ) -> Result<(), ScriptContextError> { Ok(()) } - fn check_local_policy_validity( + fn check_local_policy_validity( _ms: &Miniscript, ) -> Result<(), ScriptContextError> { Ok(()) } - fn check_local_consensus_validity( + fn check_local_consensus_validity( _ms: &Miniscript, ) -> Result<(), ScriptContextError> { 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") } @@ -836,24 +832,20 @@ impl ScriptContext for NoChecks { "NochecksEcdsa" } - fn check_witness(_witness: &[Vec]) -> Result<(), ScriptContextError> { + fn check_witness(_witness: &[Vec]) -> Result<(), ScriptContextError> { // 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<(), ScriptContextError> { 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<(), ScriptContextError> { Self::check_global_consensus_validity(ms)?; Self::check_global_policy_validity(ms)?; Self::check_local_consensus_validity(ms)?; @@ -861,18 +853,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 d7f72c1d8..01312d3c1 100644 --- a/src/miniscript/decode.rs +++ b/src/miniscript/decode.rs @@ -32,7 +32,7 @@ use crate::miniscript::types::extra_props::ExtData; use crate::miniscript::types::{Property, Type}; use crate::miniscript::ScriptContext; use crate::prelude::*; -use crate::{bitcoin, hash256, Error, Miniscript, MiniscriptKey, ToPublicKey}; +use crate::{bitcoin, hash256, Error, Key, Miniscript, ToPublicKey}; fn return_none(_: usize) -> Option { None @@ -125,7 +125,7 @@ enum NonTerm { /// All AST elements #[allow(broken_intra_doc_links)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] -pub enum Terminal { +pub enum Terminal { /// `1` True, /// `0` @@ -212,9 +212,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() diff --git a/src/miniscript/iter.rs b/src/miniscript/iter.rs index 1df400902..436737d3c 100644 --- a/src/miniscript/iter.rs +++ b/src/miniscript/iter.rs @@ -21,11 +21,11 @@ use core::ops::Deref; use sync::Arc; use super::decode::Terminal; -use super::{Miniscript, MiniscriptKey, ScriptContext}; +use super::{Key, Miniscript, ScriptContext}; 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. @@ -226,7 +226,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: ScriptContext> { 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 @@ -234,7 +234,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: ScriptContext> Iter<'a, Pk, Ctx> { fn new(miniscript: &'a Miniscript) -> Self { Iter { next: Some(miniscript), @@ -243,7 +243,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: ScriptContext> Iterator for Iter<'a, Pk, Ctx> { type Item = &'a Miniscript; /// First, the function returns `self`, then the first child of the self (if any), @@ -286,15 +286,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: ScriptContext> { 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: ScriptContext> PkIter<'a, Pk, Ctx> { fn new(miniscript: &'a Miniscript) -> Self { let mut iter = Iter::new(miniscript); PkIter { @@ -305,7 +305,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: ScriptContext> Iterator for PkIter<'a, Pk, Ctx> { type Item = Pk; fn next(&mut self) -> Option { @@ -328,15 +328,15 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iterator for PkIter<'a, Pk, Ctx> } } -/// Iterator for traversing all [MiniscriptKey] hashes in AST starting from some specific node which +/// Iterator for traversing all [Key] hashes in AST starting from some specific node which /// constructs the iterator via [Miniscript::iter_pkh] method. -pub struct PkhIter<'a, Pk: MiniscriptKey, Ctx: ScriptContext> { +pub struct PkhIter<'a, Pk: Key, Ctx: ScriptContext> { node_iter: Iter<'a, Pk, Ctx>, curr_node: Option<&'a Miniscript>, key_index: usize, } -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> PkhIter<'a, Pk, Ctx> { +impl<'a, Pk: Key, Ctx: ScriptContext> PkhIter<'a, Pk, Ctx> { fn new(miniscript: &'a Miniscript) -> Self { let mut iter = Iter::new(miniscript); PkhIter { @@ -347,7 +347,7 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> PkhIter<'a, Pk, Ctx> { } } -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iterator for PkhIter<'a, Pk, Ctx> { +impl<'a, Pk: Key, Ctx: ScriptContext> Iterator for PkhIter<'a, Pk, Ctx> { type Item = Pk::RawPkHash; fn next(&mut self) -> Option { @@ -372,14 +372,14 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iterator for PkhIter<'a, Pk, Ctx /// Enum representing either key or a key hash value coming from a miniscript item inside AST #[derive(Clone, PartialEq, Eq, Debug)] -pub enum PkPkh { +pub enum PkPkh { /// Plain public key PlainPubkey(Pk), /// Hashed public key HashedPubkey(Pk::RawPkHash), } -impl> PkPkh { +impl> PkPkh { /// Convenience method to avoid distinguishing between keys and hashes when these are the same type pub fn as_key(self) -> Pk { match self { @@ -389,16 +389,16 @@ impl> PkPkh { } } -/// Iterator for traversing all [MiniscriptKey]'s and hashes, depending what data are present in AST, +/// Iterator for traversing all [Key]'s and hashes, depending what data are present in AST, /// starting from some specific node which constructs the iterator via /// [Miniscript::iter_pk_pkh] method. -pub struct PkPkhIter<'a, Pk: MiniscriptKey, Ctx: ScriptContext> { +pub struct PkPkhIter<'a, Pk: Key, Ctx: ScriptContext> { node_iter: Iter<'a, Pk, Ctx>, curr_node: Option<&'a Miniscript>, key_index: usize, } -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> PkPkhIter<'a, Pk, Ctx> { +impl<'a, Pk: Key, Ctx: ScriptContext> PkPkhIter<'a, Pk, Ctx> { fn new(miniscript: &'a Miniscript) -> Self { let mut iter = Iter::new(miniscript); PkPkhIter { @@ -433,7 +433,7 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> PkPkhIter<'a, Pk, Ctx> { } } -impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iterator for PkPkhIter<'a, Pk, Ctx> { +impl<'a, Pk: Key, Ctx: ScriptContext> Iterator for PkPkhIter<'a, Pk, Ctx> { type Item = PkPkh; fn next(&mut self) -> Option { diff --git a/src/miniscript/mod.rs b/src/miniscript/mod.rs index 9d50d63d1..b9e59a259 100644 --- a/src/miniscript/mod.rs +++ b/src/miniscript/mod.rs @@ -54,13 +54,13 @@ pub use crate::miniscript::context::ScriptContext; 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; /// Top-level script AST type #[derive(Clone)] -pub struct Miniscript { +pub struct Miniscript { ///A node in the Abstract Syntax Tree( pub node: Terminal, ///The correctness and malleability type information for the AST node @@ -74,7 +74,7 @@ pub struct Miniscript { /// `PartialOrd` of `Miniscript` must depend only on node and not the type information. /// The type information and extra_properties can be deterministically determined /// by the ast. -impl PartialOrd for Miniscript { +impl PartialOrd for Miniscript { fn partial_cmp(&self, other: &Miniscript) -> Option { Some(self.node.cmp(&other.node)) } @@ -83,7 +83,7 @@ impl PartialOrd for Miniscript { /// `Ord` of `Miniscript` must depend only on node and not the type information. /// The type information and extra_properties can be deterministically determined /// by the ast. -impl Ord for Miniscript { +impl Ord for Miniscript { fn cmp(&self, other: &Miniscript) -> cmp::Ordering { self.node.cmp(&other.node) } @@ -92,7 +92,7 @@ impl Ord for Miniscript { /// `PartialEq` of `Miniscript` must depend only on node and not the type information. /// The type information and extra_properties can be deterministically determined /// by the ast. -impl PartialEq for Miniscript { +impl PartialEq for Miniscript { fn eq(&self, other: &Miniscript) -> bool { self.node.eq(&other.node) } @@ -101,21 +101,21 @@ impl PartialEq for Miniscript { /// `Eq` of `Miniscript` must depend only on node and not the type information. /// The type information and extra_properties can be deterministically determined /// by the ast. -impl Eq for Miniscript {} +impl Eq for Miniscript {} -impl fmt::Debug for Miniscript { +impl fmt::Debug for Miniscript { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.node) } } -impl hash::Hash for Miniscript { +impl hash::Hash for Miniscript { fn hash(&self, state: &mut H) { self.node.hash(state); } } -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. @@ -129,13 +129,13 @@ impl Miniscript { } } -impl fmt::Display for Miniscript { +impl fmt::Display for Miniscript { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.node) } } -impl Miniscript { +impl Miniscript { /// Extracts the `AstElem` representing the root of the miniscript pub fn into_inner(self) -> Terminal { self.node @@ -214,7 +214,7 @@ impl Miniscript { impl Miniscript where - Pk: MiniscriptKey, + Pk: Key, Ctx: ScriptContext, { /// Encode as a Bitcoin script @@ -237,7 +237,7 @@ where } } -impl Miniscript { +impl Miniscript { /// Maximum number of witness elements used to satisfy the Miniscript /// fragment, including the witness script itself. Used to estimate /// the weight of the `VarInt` that specifies this number in a serialized @@ -269,7 +269,7 @@ impl Miniscript { } } -impl ForEachKey for Miniscript { +impl ForEachKey for Miniscript { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool where Pk: 'a, @@ -281,8 +281,8 @@ impl ForEachKey for Miniscript TranslatePk for Miniscript where - Pk: MiniscriptKey, - Q: MiniscriptKey, + Pk: Key, + Q: Key, Ctx: ScriptContext, { type Output = Miniscript; @@ -297,7 +297,7 @@ where } } -impl Miniscript { +impl Miniscript { fn real_for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, pred: &mut F) -> bool where Pk: 'a, @@ -311,7 +311,7 @@ impl Miniscript { t: &mut T, ) -> Result, FuncError> where - Q: MiniscriptKey, + Q: Key, CtxQ: ScriptContext, T: Translator, { @@ -352,7 +352,7 @@ impl_block_str!( } ); -impl Miniscript { +impl Miniscript { /// Attempt to produce non-malleable satisfying witness for the /// witness script represented by the parse tree pub fn satisfy>(&self, satisfier: S) -> Result>, Error> diff --git a/src/miniscript/satisfy.rs b/src/miniscript/satisfy.rs index 37723117c..ed31f5c43 100644 --- a/src/miniscript/satisfy.rs +++ b/src/miniscript/satisfy.rs @@ -30,7 +30,7 @@ use crate::miniscript::limits::{ }; use crate::prelude::*; use crate::util::witness_size; -use crate::{Miniscript, MiniscriptKey, ScriptContext, Terminal, ToPublicKey}; +use crate::{Key, Miniscript, ScriptContext, Terminal, ToPublicKey}; /// Type alias for 32 byte Preimage. pub type Preimage32 = [u8; 32]; @@ -38,7 +38,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 @@ -120,13 +120,13 @@ pub trait Satisfier { } // Allow use of `()` as a "no conditions available" satisfier -impl Satisfier for () {} +impl Satisfier for () {} /// Newtype around `u32` which implements `Satisfier` using `n` as an /// relative locktime pub struct Older(pub u32); -impl Satisfier for Older { +impl Satisfier for Older { fn check_older(&self, n: u32) -> bool { if self.0 & SEQUENCE_LOCKTIME_DISABLE_FLAG != 0 { return true; @@ -151,7 +151,7 @@ impl Satisfier for Older { /// absolute locktime pub struct After(pub u32); -impl Satisfier for After { +impl Satisfier for After { fn check_after(&self, n: u32) -> bool { // if n > self.0; we will be returning false anyways if n < LOCKTIME_THRESHOLD && self.0 >= LOCKTIME_THRESHOLD { @@ -162,15 +162,13 @@ impl Satisfier for After { } } -impl Satisfier for HashMap { +impl Satisfier for HashMap { fn lookup_ecdsa_sig(&self, key: &Pk) -> Option { self.get(key).copied() } } -impl Satisfier - for HashMap<(Pk, TapLeafHash), bitcoin::SchnorrSig> -{ +impl Satisfier for HashMap<(Pk, TapLeafHash), bitcoin::SchnorrSig> { fn lookup_tap_leaf_script_sig(&self, key: &Pk, h: &TapLeafHash) -> Option { // Unfortunately, there is no way to get a &(a, b) from &a and &b without allocating // If we change the signature the of lookup_tap_leaf_script_sig to accept a tuple. We would @@ -180,10 +178,9 @@ impl Satisfier } } -impl Satisfier - for HashMap +impl Satisfier for HashMap where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, { fn lookup_ecdsa_sig(&self, key: &Pk) -> Option { self.get(&key.to_pubkeyhash()).map(|x| x.1) @@ -202,10 +199,10 @@ where } } -impl Satisfier +impl Satisfier for HashMap<(Pk::RawPkHash, TapLeafHash), (Pk, bitcoin::SchnorrSig)> where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, { fn lookup_tap_leaf_script_sig(&self, key: &Pk, h: &TapLeafHash) -> Option { self.get(&(key.to_pubkeyhash(), *h)).map(|x| x.1) @@ -220,7 +217,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) } @@ -282,7 +279,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) } @@ -349,7 +346,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 { @@ -674,7 +671,7 @@ impl Satisfaction { min_fn: &mut F, ) -> Self where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, Ctx: ScriptContext, Sat: Satisfier, F: FnMut(Satisfaction, Satisfaction) -> Satisfaction, @@ -792,7 +789,7 @@ impl Satisfaction { min_fn: &mut F, ) -> Self where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, Ctx: ScriptContext, Sat: Satisfier, F: FnMut(Satisfaction, Satisfaction) -> Satisfaction, @@ -920,7 +917,7 @@ impl Satisfaction { thresh_fn: &mut G, ) -> Self where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, Ctx: ScriptContext, Sat: Satisfier, F: FnMut(Satisfaction, Satisfaction) -> Satisfaction, @@ -1232,7 +1229,7 @@ impl Satisfaction { thresh_fn: &mut G, ) -> Self where - Pk: MiniscriptKey + ToPublicKey, + Pk: Key + ToPublicKey, Ctx: ScriptContext, Sat: Satisfier, F: FnMut(Satisfaction, Satisfaction) -> Satisfaction, @@ -1400,11 +1397,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, @@ -1421,11 +1414,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/extra_props.rs b/src/miniscript/types/extra_props.rs index 0cd97f78b..b929dc6d4 100644 --- a/src/miniscript/types/extra_props.rs +++ b/src/miniscript/types/extra_props.rs @@ -10,7 +10,7 @@ use crate::miniscript::limits::{ LOCKTIME_THRESHOLD, SEQUENCE_LOCKTIME_DISABLE_FLAG, SEQUENCE_LOCKTIME_TYPE_FLAG, }; 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)] @@ -897,7 +897,7 @@ impl Property for ExtData { where C: FnMut(usize) -> Option, Ctx: ScriptContext, - Pk: MiniscriptKey, + Pk: Key, { let wrap_err = |result: Result| { result.map_err(|kind| Error { diff --git a/src/miniscript/types/mod.rs b/src/miniscript/types/mod.rs index 161185c4f..4328ac2b5 100644 --- a/src/miniscript/types/mod.rs +++ b/src/miniscript/types/mod.rs @@ -29,7 +29,7 @@ pub use self::extra_props::ExtData; pub use self::malleability::{Dissat, Malleability}; use super::limits::SEQUENCE_LOCKTIME_DISABLE_FLAG; use super::ScriptContext; -use crate::{MiniscriptKey, Terminal}; +use crate::{Key, Terminal}; /// None-returning function to help type inference when we need a /// closure that simply returns `None` @@ -99,14 +99,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!( @@ -216,7 +216,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 } @@ -394,7 +394,7 @@ pub trait Property: Sized { ) -> Result> where C: FnMut(usize) -> Option, - Pk: MiniscriptKey, + Pk: Key, Ctx: ScriptContext, { let mut get_child = |sub, n| { @@ -782,7 +782,7 @@ impl Property for Type { ) -> Result> where C: FnMut(usize) -> Option, - Pk: MiniscriptKey, + Pk: Key, Ctx: ScriptContext, { let wrap_err = |result: Result| { diff --git a/src/policy/compiler.rs b/src/policy/compiler.rs index c5cb7cdea..99c8c2b52 100644 --- a/src/policy/compiler.rs +++ b/src/policy/compiler.rs @@ -31,7 +31,7 @@ use crate::miniscript::types::{self, ErrorKind, ExtData, Property, Type}; use crate::miniscript::ScriptContext; 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>>; @@ -460,14 +460,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 @@ -483,7 +483,7 @@ impl AstElemExt { } } -impl AstElemExt { +impl AstElemExt { fn terminal(ast: Terminal) -> AstElemExt { AstElemExt { comp_ext_data: CompilerExtData::type_check(&ast, |_| None).unwrap(), @@ -548,14 +548,14 @@ impl AstElemExt { /// Different types of casts possible for each node. #[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 { @@ -569,7 +569,7 @@ impl Cast { } } -fn all_casts() -> [Cast; 10] { +fn all_casts() -> [Cast; 10] { [ Cast { ext_data: types::ExtData::cast_check, @@ -663,7 +663,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, @@ -716,7 +716,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, @@ -750,7 +750,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>, @@ -783,7 +783,7 @@ fn best_compilations( dissat_prob: Option, ) -> Result>, CompilerError> where - Pk: MiniscriptKey, + Pk: Key, Ctx: ScriptContext, { //Check the cache for hits @@ -1084,7 +1084,7 @@ fn compile_binary( bin_func: F, ) -> Result<(), CompilerError> where - Pk: MiniscriptKey, + Pk: Key, Ctx: ScriptContext, F: Fn(Arc>, Arc>) -> Terminal, { @@ -1106,7 +1106,7 @@ where /// Helper function to compile different order of and_or fragments. /// `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 -fn compile_tern( +fn compile_tern( policy_cache: &mut PolicyCache, policy: &Concrete, ret: &mut BTreeMap>, @@ -1137,7 +1137,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(); @@ -1159,7 +1159,7 @@ fn best_t( dissat_prob: Option, ) -> Result, CompilerError> where - Pk: MiniscriptKey, + Pk: Key, Ctx: ScriptContext, { best_compilations(policy_cache, policy, sat_prob, dissat_prob)? @@ -1181,7 +1181,7 @@ fn best( dissat_prob: Option, ) -> Result, CompilerError> where - Pk: MiniscriptKey, + Pk: Key, Ctx: ScriptContext, { best_compilations(policy_cache, policy, sat_prob, dissat_prob)? diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 6e28f3d11..72c68dd8c 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -38,13 +38,13 @@ use crate::expression::{self, FromTree}; use crate::miniscript::limits::{LOCKTIME_THRESHOLD, SEQUENCE_LOCKTIME_TYPE_FLAG}; use crate::miniscript::types::extra_props::TimelockInfo; use crate::prelude::*; -use crate::{errstr, Error, ForEachKey, MiniscriptKey, Translator}; +use crate::{errstr, Error, ForEachKey, Key, Translator}; /// Concrete policy which corresponds directly to a Miniscript structure, /// 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 @@ -166,7 +166,7 @@ impl error::Error for PolicyError { } } -impl Policy { +impl Policy { /// Flatten the [`Policy`] tree structure into a Vector of tuple `(leaf script, leaf probability)` /// with leaf probabilities corresponding to odds for sub-branch in the policy. /// We calculate the probability of selecting the sub-branch at every level and calculate the @@ -339,7 +339,7 @@ impl Policy { } } -impl ForEachKey for Policy { +impl ForEachKey for Policy { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool where Pk: 'a, @@ -362,7 +362,7 @@ impl ForEachKey for Policy { } } -impl Policy { +impl Policy { /// Convert a policy using one kind of public key to another /// type of public key /// @@ -428,7 +428,7 @@ impl Policy { pub fn translate_pk(&self, t: &mut T) -> Result, E> where T: Translator, - Q: MiniscriptKey, + Q: Key, { self._translate_pk(t) } @@ -436,7 +436,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), @@ -677,7 +677,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()"), @@ -720,7 +720,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"), @@ -898,7 +898,7 @@ impl_from_tree!( /// Create 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(); diff --git a/src/policy/mod.rs b/src/policy/mod.rs index 9e91dc7fe..91931894a 100644 --- a/src/policy/mod.rs +++ b/src/policy/mod.rs @@ -36,7 +36,7 @@ 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::{Error, Key, Terminal}; /// Policy entailment algorithm maximum number of terminals allowed const ENTAILMENT_MAX_TERMINALS: usize = 20; @@ -53,7 +53,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 { /// Convert the object into an abstract policy fn lift(&self) -> Result, Error>; } @@ -92,7 +92,7 @@ impl error::Error for LiftError { } } -impl Miniscript { +impl Miniscript { /// Lifting corresponds conversion of miniscript into Policy /// [policy.semantic.Policy] for human readable or machine analysis. /// However, naively lifting miniscripts can result in incorrect @@ -112,7 +112,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 @@ -121,7 +121,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::KeyHash(pk.to_pubkeyhash()), @@ -173,7 +173,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(), @@ -186,13 +186,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 1bf430cb9..611ee9fc5 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -20,7 +20,7 @@ use core::{fmt, str}; use super::concrete::PolicyError; use super::ENTAILMENT_MAX_TERMINALS; use crate::prelude::*; -use crate::{errstr, expression, timelock, Error, ForEachKey, MiniscriptKey, Translator}; +use crate::{errstr, expression, timelock, 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 @@ -29,7 +29,7 @@ use crate::{errstr, expression, timelock, Error, ForEachKey, MiniscriptKey, Tran /// representing the same policy are lifted to the same `Semantic`, /// 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 @@ -52,7 +52,7 @@ pub enum Policy { Threshold(usize, Vec>), } -impl ForEachKey for Policy { +impl ForEachKey for Policy { fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool where Pk: 'a, @@ -72,7 +72,7 @@ impl ForEachKey for Policy { } } -impl Policy { +impl Policy { /// Convert a policy using one kind of public key to another /// type of public key /// @@ -138,7 +138,7 @@ impl Policy { pub fn translate_pkh(&self, t: &mut T) -> Result, E> where T: Translator, - Q: MiniscriptKey, + Q: Key, { self._translate_pkh(t) } @@ -146,7 +146,7 @@ impl Policy { fn _translate_pkh(&self, t: &mut T) -> Result, E> where T: Translator, - Q: MiniscriptKey, + Q: Key, { match *self { Policy::Unsatisfiable => Ok(Policy::Unsatisfiable), @@ -251,7 +251,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()"), @@ -284,7 +284,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"), @@ -414,7 +414,7 @@ impl_from_tree!( } ); -impl Policy { +impl Policy { /// Flatten 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 { @@ -633,7 +633,7 @@ impl Policy { } } -impl Policy { +impl Policy { /// "Sort" a policy to bring it into a canonical form to allow comparisons. /// Does **not** allow policies to be compared for functional equivalence; /// in general this appears to require Gröbner basis techniques that are not diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index b0047bd78..7821f9624 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -36,8 +36,8 @@ use crate::miniscript::limits::SEQUENCE_LOCKTIME_DISABLE_FLAG; use crate::miniscript::satisfy::{After, Older}; use crate::prelude::*; use crate::{ - descriptor, interpreter, DefiniteDescriptorKey, Descriptor, MiniscriptKey, PkTranslator, - Preimage32, Satisfier, ToPublicKey, TranslatePk, + descriptor, interpreter, DefiniteDescriptorKey, Descriptor, Key, PkTranslator, Preimage32, + Satisfier, ToPublicKey, TranslatePk, }; mod finalizer; @@ -285,7 +285,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/test_utils.rs b/src/test_utils.rs index 64a3202f4..82cd925ba 100644 --- a/src/test_utils.rs +++ b/src/test_utils.rs @@ -6,9 +6,9 @@ use std::str::FromStr; use bitcoin::hashes::{hash160, ripemd160, sha256}; use bitcoin::secp256k1; -use crate::{hash256, MiniscriptKey, Translator}; +use crate::{hash256, Key, 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 b59c2fde4..c5e1609f1 100644 --- a/src/util.rs +++ b/src/util.rs @@ -3,7 +3,7 @@ use bitcoin::Script; use crate::miniscript::context; use crate::prelude::*; -use crate::{MiniscriptKey, ScriptContext, ToPublicKey}; +use crate::{Key, ScriptContext, ToPublicKey}; pub(crate) fn varint_len(n: usize) -> usize { bitcoin::VarInt(n as u64).len() } diff --git a/tests/test_cpp.rs b/tests/test_cpp.rs index a6e7fd1a3..07b75d23c 100644 --- a/tests/test_cpp.rs +++ b/tests/test_cpp.rs @@ -17,7 +17,7 @@ use bitcoin::{self, Amount, OutPoint, Transaction, TxIn, TxOut, Txid}; use bitcoind::bitcoincore_rpc::{json, Client, RpcApi}; use miniscript::miniscript::iter; use miniscript::psbt::PsbtExt; -use miniscript::{Descriptor, Miniscript, MiniscriptKey, Segwitv0}; +use miniscript::{Descriptor, Key, Miniscript, Segwitv0}; mod setup; use setup::test_util::{self, PubData, TestData}; diff --git a/tests/test_desc.rs b/tests/test_desc.rs index f94264c72..f7e34584d 100644 --- a/tests/test_desc.rs +++ b/tests/test_desc.rs @@ -20,7 +20,7 @@ use bitcoin::{ use bitcoind::bitcoincore_rpc::{json, Client, RpcApi}; use miniscript::miniscript::iter; use miniscript::psbt::{PsbtExt, PsbtInputExt}; -use miniscript::{Descriptor, Miniscript, MiniscriptKey, ScriptContext, ToPublicKey}; +use miniscript::{Descriptor, Key, Miniscript, ScriptContext, ToPublicKey}; mod setup; use rand::RngCore;