From 77eb4a34803ffd13e3bfd6298fe8a249940ab2f8 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 13:01:17 +1000 Subject: [PATCH 01/35] Add clippy config file Add a clippy configuration file with the MSRV set to the current 1.41.1 --- clippy.toml | 1 + 1 file changed, 1 insertion(+) create mode 100644 clippy.toml diff --git a/clippy.toml b/clippy.toml new file mode 100644 index 000000000..799264ef1 --- /dev/null +++ b/clippy.toml @@ -0,0 +1 @@ +msrv = "1.41.1" From e94bf6efb776c234800164451e871fc473fbffa4 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 12:46:45 +1000 Subject: [PATCH 02/35] Remove redundant import statement Clippy emits: warning: this import is redundant As suggested, remove the redundant import. --- src/util.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/util.rs b/src/util.rs index 60af5d6cb..9ace5c172 100644 --- a/src/util.rs +++ b/src/util.rs @@ -1,5 +1,4 @@ use crate::miniscript::context; -use bitcoin; use bitcoin::blockdata::script; use bitcoin::Script; From a1cf3944650e4e3508e78e4bdc0bb80d1e0b1471 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 12:48:51 +1000 Subject: [PATCH 03/35] Use struct field shorthand Clippy emits: warning: redundant field names in struct initialization As suggested, use the field init shorthand. --- src/descriptor/bare.rs | 4 ++-- src/descriptor/segwitv0.rs | 4 ++-- src/descriptor/sh.rs | 4 ++-- src/interpreter/mod.rs | 2 +- src/interpreter/stack.rs | 2 +- src/miniscript/decode.rs | 16 ++++++++-------- src/psbt/mod.rs | 9 +++------ 7 files changed, 19 insertions(+), 22 deletions(-) diff --git a/src/descriptor/bare.rs b/src/descriptor/bare.rs index 6e414a378..ee4c39040 100644 --- a/src/descriptor/bare.rs +++ b/src/descriptor/bare.rs @@ -49,7 +49,7 @@ impl Bare { pub fn new(ms: Miniscript) -> Result { // do the top-level checks BareCtx::top_level_checks(&ms)?; - Ok(Self { ms: ms }) + Ok(Self { ms }) } /// get the inner @@ -241,7 +241,7 @@ impl Pkh { /// Create a new Pkh descriptor pub fn new(pk: Pk) -> Self { // do the top-level checks - Self { pk: pk } + Self { pk } } /// Get a reference to the inner key diff --git a/src/descriptor/segwitv0.rs b/src/descriptor/segwitv0.rs index 1e50610ea..fd9d39015 100644 --- a/src/descriptor/segwitv0.rs +++ b/src/descriptor/segwitv0.rs @@ -313,7 +313,7 @@ where WshInner::SortedMulti(ref smv) => WshInner::SortedMulti(smv.translate_pk(&mut fpk)?), WshInner::Ms(ref ms) => WshInner::Ms(ms.translate_pk(&mut fpk, &mut fpkh)?), }; - Ok(Wsh { inner: inner }) + Ok(Wsh { inner }) } } @@ -333,7 +333,7 @@ impl Wpkh { pk.to_string(), ))) } else { - Ok(Self { pk: pk }) + Ok(Self { pk }) } } diff --git a/src/descriptor/sh.rs b/src/descriptor/sh.rs index 629f2120b..9066abfce 100644 --- a/src/descriptor/sh.rs +++ b/src/descriptor/sh.rs @@ -112,7 +112,7 @@ where ShInner::Ms(sub) } }; - Ok(Sh { inner: inner }) + Ok(Sh { inner }) } else { Err(Error::Unexpected(format!( "{}({} args) while parsing sh descriptor", @@ -439,6 +439,6 @@ where ShInner::SortedMulti(ref smv) => ShInner::SortedMulti(smv.translate_pk(&mut fpk)?), ShInner::Ms(ref ms) => ShInner::Ms(ms.translate_pk(&mut fpk, &mut fpkh)?), }; - Ok(Sh { inner: inner }) + Ok(Sh { inner }) } } diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index f46c09254..e3c0096d3 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -192,7 +192,7 @@ impl<'txin> Interpreter<'txin> { verify_sig: Box bool + 'iter>, ) -> Iter<'txin, 'iter> { Iter { - verify_sig: verify_sig, + verify_sig, public_key: if let inner::Inner::PublicKey(ref pk, _) = self.inner { Some(pk) } else { diff --git a/src/interpreter/stack.rs b/src/interpreter/stack.rs index 554407033..143f6cecf 100644 --- a/src/interpreter/stack.rs +++ b/src/interpreter/stack.rs @@ -209,7 +209,7 @@ impl<'txin> Stack<'txin> { self.push(Element::Satisfied); Some(Ok(SatisfiedConstraint::PublicKeyHash { keyhash: pkh.hash160(), - key_sig: key_sig, + key_sig, })) } Err(e) => return Some(Err(e)), diff --git a/src/miniscript/decode.rs b/src/miniscript/decode.rs index 7f706c2d8..a6b0feefc 100644 --- a/src/miniscript/decode.rs +++ b/src/miniscript/decode.rs @@ -224,8 +224,8 @@ impl TerminalStack { let ext = ExtData::type_check(&ms, return_none)?; let ms = Miniscript { node: ms, - ty: ty, - ext: ext, + ty, + ext, phantom: PhantomData, }; Ctx::check_global_validity(&ms)?; @@ -245,8 +245,8 @@ impl TerminalStack { let ext = ExtData::type_check(&wrapped_ms, return_none)?; let ms = Miniscript { node: wrapped_ms, - ty: ty, - ext: ext, + ty, + ext, phantom: PhantomData, }; Ctx::check_global_validity(&ms)?; @@ -268,8 +268,8 @@ impl TerminalStack { let ext = ExtData::type_check(&wrapped_ms, return_none)?; let ms = Miniscript { node: wrapped_ms, - ty: ty, - ext: ext, + ty, + ext, phantom: PhantomData, }; Ctx::check_global_validity(&ms)?; @@ -558,8 +558,8 @@ pub fn parse( term.0.push(Miniscript { node: wrapped_ms, - ty: ty, - ext: ext, + ty, + ext, phantom: PhantomData, }); } diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index d1b35ba60..6ccd13549 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -249,10 +249,7 @@ impl<'psbt> PsbtInputSatisfier<'psbt> { /// create a new PsbtInputsatisfier from /// psbt and index pub fn new(psbt: &'psbt Psbt, index: usize) -> Self { - Self { - psbt: psbt, - index: index, - } + Self { psbt, index } } } @@ -639,7 +636,7 @@ impl PsbtExt for Psbt { if index >= self.inputs.len() { return Err(Error::InputIdxOutofBounds { psbt_inp: self.inputs.len(), - index: index, + index, }); } finalizer::finalize_input(self, index, secp, /*allow_mall*/ false) @@ -664,7 +661,7 @@ impl PsbtExt for Psbt { if index >= self.inputs.len() { return Err(Error::InputIdxOutofBounds { psbt_inp: self.inputs.len(), - index: index, + index, }); } finalizer::finalize_input(self, index, secp, /*allow_mall*/ false) From 952af97e2aa3986f1141f7fd0cace331ac943157 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 12:51:46 +1000 Subject: [PATCH 04/35] Remove unneeded unit return type Clippy emits: warning: unneeded unit return type As suggested, remove the unneeded unit return type --- src/interpreter/mod.rs | 2 +- src/interpreter/stack.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index e3c0096d3..050f21a38 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -565,7 +565,7 @@ where node: &'intp Miniscript, n_evaluated: usize, n_satisfied: usize, - ) -> () { + ) { self.state.push(NodeEvaluationState { node, n_evaluated, diff --git a/src/interpreter/stack.rs b/src/interpreter/stack.rs index 143f6cecf..fe862e4d7 100644 --- a/src/interpreter/stack.rs +++ b/src/interpreter/stack.rs @@ -115,7 +115,7 @@ impl<'txin> Stack<'txin> { } /// Pushes an element onto the top of the stack - pub fn push(&mut self, elem: Element<'txin>) -> () { + pub fn push(&mut self, elem: Element<'txin>) { self.0.push(elem); } From 03c65871b50581ba7d203b0a77ea09bfcf4f4f49 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 12:56:45 +1000 Subject: [PATCH 05/35] Remove unneeded explicit reference Clippy emits a bunch of warnings of the form warning: this expression borrows a reference (`&Self`) that is immediately dereferenced by the compiler As suggested, remove the unneeded explicit reference. --- src/descriptor/bare.rs | 2 +- src/descriptor/key.rs | 6 +++--- src/descriptor/mod.rs | 4 ++-- src/descriptor/pretaproot.rs | 4 ++-- src/descriptor/segwitv0.rs | 4 ++-- src/descriptor/sh.rs | 8 ++++---- src/descriptor/tr.rs | 10 +++++----- src/interpreter/mod.rs | 10 +++++----- src/miniscript/analyzable.rs | 2 +- src/miniscript/astelem.rs | 2 +- src/miniscript/lex.rs | 8 ++++---- src/psbt/finalizer.rs | 18 +++++++++--------- src/psbt/mod.rs | 8 ++++---- 13 files changed, 43 insertions(+), 43 deletions(-) diff --git a/src/descriptor/bare.rs b/src/descriptor/bare.rs index ee4c39040..97056603f 100644 --- a/src/descriptor/bare.rs +++ b/src/descriptor/bare.rs @@ -111,7 +111,7 @@ where <::Hash as FromStr>::Err: ToString, { fn from_tree(top: &expression::Tree) -> Result { - let sub = Miniscript::::from_tree(&top)?; + let sub = Miniscript::::from_tree(top)?; BareCtx::top_level_checks(&sub)?; Bare::new(sub) } diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index ac116d1ec..73e710e30 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -172,9 +172,9 @@ impl DescriptorXKey { let xprv = self .xkey - .derive_priv(&secp, &hardened_path) + .derive_priv(secp, &hardened_path) .map_err(|_| DescriptorKeyParseError("Unable to derive the hardened steps"))?; - let xpub = bip32::ExtendedPubKey::from_priv(&secp, &xprv); + let xpub = bip32::ExtendedPubKey::from_priv(secp, &xprv); let origin = match &self.origin { Some((fingerprint, path)) => Some(( @@ -188,7 +188,7 @@ impl DescriptorXKey { if hardened_path.is_empty() { None } else { - Some((self.xkey.fingerprint(&secp), hardened_path.into())) + Some((self.xkey.fingerprint(secp), hardened_path.into())) } } }; diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index 375390e47..992b9feac 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -712,7 +712,7 @@ impl Descriptor { key_map: &mut KeyMap| -> Result { let (public_key, secret_key) = match DescriptorSecretKey::from_str(s) { - Ok(sk) => (sk.to_public(&secp)?, Some(sk)), + Ok(sk) => (sk.to_public(secp)?, Some(sk)), Err(_) => (DescriptorPublicKey::from_str(s)?, None), }; @@ -774,7 +774,7 @@ impl Descriptor { let range = if self.is_deriveable() { range } else { 0..1 }; for i in range { - let concrete = self.derived_descriptor(&secp, i)?; + let concrete = self.derived_descriptor(secp, i)?; if &concrete.script_pubkey() == script_pubkey { return Ok(Some((i, concrete))); } diff --git a/src/descriptor/pretaproot.rs b/src/descriptor/pretaproot.rs index c19aba579..a55980a06 100644 --- a/src/descriptor/pretaproot.rs +++ b/src/descriptor/pretaproot.rs @@ -259,7 +259,7 @@ pub(crate) mod traits { { // This expect can technically be avoided if we implement this for types, but // having this expect saves lots of LoC because of default implementation - >::explicit_script(&self) + >::explicit_script(self) .expect("Pre taproot descriptor have explicit script") } @@ -269,7 +269,7 @@ pub(crate) mod traits { where Pk: ToPublicKey, { - >::script_code(&self) + >::script_code(self) .expect("Pre taproot descriptor have non-failing script code") } } diff --git a/src/descriptor/segwitv0.rs b/src/descriptor/segwitv0.rs index fd9d39015..21791d36f 100644 --- a/src/descriptor/segwitv0.rs +++ b/src/descriptor/segwitv0.rs @@ -140,10 +140,10 @@ where let top = &top.args[0]; if top.name == "sortedmulti" { return Ok(Wsh { - inner: WshInner::SortedMulti(SortedMultiVec::from_tree(&top)?), + inner: WshInner::SortedMulti(SortedMultiVec::from_tree(top)?), }); } - let sub = Miniscript::from_tree(&top)?; + let sub = Miniscript::from_tree(top)?; Segwitv0::top_level_checks(&sub)?; Ok(Wsh { inner: WshInner::Ms(sub), diff --git a/src/descriptor/sh.rs b/src/descriptor/sh.rs index 9066abfce..90f54ca54 100644 --- a/src/descriptor/sh.rs +++ b/src/descriptor/sh.rs @@ -103,11 +103,11 @@ where if top.name == "sh" && top.args.len() == 1 { let top = &top.args[0]; let inner = match top.name { - "wsh" => ShInner::Wsh(Wsh::from_tree(&top)?), - "wpkh" => ShInner::Wpkh(Wpkh::from_tree(&top)?), - "sortedmulti" => ShInner::SortedMulti(SortedMultiVec::from_tree(&top)?), + "wsh" => ShInner::Wsh(Wsh::from_tree(top)?), + "wpkh" => ShInner::Wpkh(Wpkh::from_tree(top)?), + "sortedmulti" => ShInner::SortedMulti(SortedMultiVec::from_tree(top)?), _ => { - let sub = Miniscript::from_tree(&top)?; + let sub = Miniscript::from_tree(top)?; Legacy::top_level_checks(&sub)?; ShInner::Ms(sub) } diff --git a/src/descriptor/tr.rs b/src/descriptor/tr.rs index 7dc7e6d75..360cb3b54 100644 --- a/src/descriptor/tr.rs +++ b/src/descriptor/tr.rs @@ -322,8 +322,8 @@ where let (depth, last) = self.stack.pop().expect("Size checked above"); match &*last { TapTree::Tree(l, r) => { - self.stack.push((depth + 1, &r)); - self.stack.push((depth + 1, &l)); + self.stack.push((depth + 1, r)); + self.stack.push((depth + 1, l)); } TapTree::Leaf(ref ms) => return Some((depth, ms)), } @@ -533,7 +533,7 @@ impl Liftable for TapTree { } } - let pol = lift_helper(&self)?; + let pol = lift_helper(self)?; Ok(pol.normalized()) } } @@ -594,7 +594,7 @@ impl DescriptorTrait for Tr { Pk: ToPublicKey, S: Satisfier, { - best_tap_spend(&self, satisfier, false /* allow_mall */) + best_tap_spend(self, satisfier, false /* allow_mall */) } fn get_satisfaction_mall(&self, satisfier: S) -> Result<(Vec>, Script), Error> @@ -602,7 +602,7 @@ impl DescriptorTrait for Tr { Pk: ToPublicKey, S: Satisfier, { - best_tap_spend(&self, satisfier, true /* allow_mall */) + best_tap_spend(self, satisfier, true /* allow_mall */) } fn max_satisfaction_weight(&self) -> Result { diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index 050f21a38..ebacdceef 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -254,13 +254,13 @@ impl<'txin> Interpreter<'txin> { let script_pubkey = self.script_code.as_ref().expect("Legacy have script code"); let sighash = if self.is_legacy() { let sighash_u32 = ecdsa_sig.hash_ty.to_u32(); - cache.legacy_signature_hash(input_idx, &script_pubkey, sighash_u32) + cache.legacy_signature_hash(input_idx, script_pubkey, sighash_u32) } else if self.is_segwit_v0() { let amt = match get_prevout(prevouts, input_idx) { Some(txout) => txout.borrow().value, None => return false, }; - cache.segwit_signature_hash(input_idx, &script_pubkey, amt, ecdsa_sig.hash_ty) + cache.segwit_signature_hash(input_idx, script_pubkey, amt, ecdsa_sig.hash_ty) } else { // taproot(or future) signatures in segwitv0 context return false; @@ -280,7 +280,7 @@ impl<'txin> Interpreter<'txin> { of script code for script spend", ); let leaf_hash = taproot::TapLeafHash::from_script( - &tap_script, + tap_script, taproot::LeafVersion::TapScript, ); cache.taproot_script_spend_signature_hash( @@ -296,7 +296,7 @@ impl<'txin> Interpreter<'txin> { let msg = sighash_msg.map(|hash| secp256k1::Message::from_slice(&hash).expect("32 byte")); let success = - msg.map(|msg| secp.verify_schnorr(&schnorr_sig.sig, &msg, &xpk).is_ok()); + msg.map(|msg| secp.verify_schnorr(&schnorr_sig.sig, &msg, xpk).is_ok()); success.unwrap_or(false) // unwrap_or_default checks for errors, while success would have checksig results } } @@ -975,7 +975,7 @@ where //Pk based descriptor if let Some(pk) = self.public_key { if let Some(stack::Element::Push(sig)) = self.stack.pop() { - if let Ok(key_sig) = verify_sersig(&mut self.verify_sig, &pk, &sig) { + if let Ok(key_sig) = verify_sersig(&mut self.verify_sig, pk, sig) { //Signature check successful, set public_key to None to //terminate the next() function in the subsequent call self.public_key = None; diff --git a/src/miniscript/analyzable.rs b/src/miniscript/analyzable.rs index 873053f66..7a3eb8633 100644 --- a/src/miniscript/analyzable.rs +++ b/src/miniscript/analyzable.rs @@ -83,7 +83,7 @@ impl Miniscript { // It maybe possible to return a detail error type containing why the miniscript // failed. But doing so may require returning a collection of errors pub fn within_resource_limits(&self) -> bool { - match Ctx::check_local_validity(&self) { + match Ctx::check_local_validity(self) { Ok(_) => true, Err(_) => false, } diff --git a/src/miniscript/astelem.rs b/src/miniscript/astelem.rs index 7054e86fd..c3ce5f451 100644 --- a/src/miniscript/astelem.rs +++ b/src/miniscript/astelem.rs @@ -659,7 +659,7 @@ impl Terminal { Terminal::PkH(ref hash) => builder .push_opcode(opcodes::all::OP_DUP) .push_opcode(opcodes::all::OP_HASH160) - .push_slice(&Pk::hash_to_hash160(&hash)[..]) + .push_slice(&Pk::hash_to_hash160(hash)[..]) .push_opcode(opcodes::all::OP_EQUALVERIFY), Terminal::After(t) => builder .push_int(t as i64) diff --git a/src/miniscript/lex.rs b/src/miniscript/lex.rs index 8927f9844..cf4fa84fc 100644 --- a/src/miniscript/lex.rs +++ b/src/miniscript/lex.rs @@ -226,10 +226,10 @@ pub fn lex<'s>(script: &'s script::Script) -> Result>, Error> { } script::Instruction::PushBytes(bytes) => { match bytes.len() { - 20 => ret.push(Token::Hash20(&bytes)), - 32 => ret.push(Token::Bytes32(&bytes)), - 33 => ret.push(Token::Bytes33(&bytes)), - 65 => ret.push(Token::Bytes65(&bytes)), + 20 => ret.push(Token::Hash20(bytes)), + 32 => ret.push(Token::Bytes32(bytes)), + 33 => ret.push(Token::Bytes33(bytes)), + 65 => ret.push(Token::Bytes65(bytes)), _ => { match script::read_scriptint(bytes) { Ok(v) if v >= 0 => { diff --git a/src/psbt/finalizer.rs b/src/psbt/finalizer.rs index 94d85456a..c39e9ec19 100644 --- a/src/psbt/finalizer.rs +++ b/src/psbt/finalizer.rs @@ -106,7 +106,7 @@ pub(super) fn get_scriptpubkey(psbt: &Psbt, index: usize) -> Result<&Script, Inp pub(super) fn get_utxo(psbt: &Psbt, index: usize) -> Result<&bitcoin::TxOut, InputError> { let inp = &psbt.inputs[index]; let utxo = if let Some(ref witness_utxo) = inp.witness_utxo { - &witness_utxo + witness_utxo } else if let Some(ref non_witness_utxo) = inp.non_witness_utxo { let vout = psbt.unsigned_tx.input[index].previous_output.vout; &non_witness_utxo.output[vout as usize] @@ -278,7 +278,7 @@ pub fn interpreter_check( psbt: &Psbt, secp: &Secp256k1, ) -> Result<(), Error> { - let utxos = prevouts(&psbt)?; + let utxos = prevouts(psbt)?; let utxos = &Prevouts::All(&utxos); for (index, input) in psbt.inputs.iter().enumerate() { let empty_script_sig = Script::new(); @@ -290,7 +290,7 @@ pub fn interpreter_check( .map(|wit_slice| Witness::from_vec(wit_slice.to_vec())) // TODO: Update rust-bitcoin psbt API to use witness .unwrap_or(empty_witness); - interpreter_inp_check(psbt, secp, index, utxos, &witness, &script_sig)?; + interpreter_inp_check(psbt, secp, index, utxos, &witness, script_sig)?; } Ok(()) } @@ -313,9 +313,9 @@ fn interpreter_inp_check>( let cltv = psbt.unsigned_tx.lock_time; let csv = psbt.unsigned_tx.input[index].sequence; let interpreter = - interpreter::Interpreter::from_txdata(spk, &script_sig, &witness, cltv, csv) + interpreter::Interpreter::from_txdata(spk, script_sig, witness, cltv, csv) .map_err(|e| Error::InputError(InputError::Interpreter(e), index))?; - let iter = interpreter.iter(secp, &psbt.unsigned_tx, index, &utxos); + let iter = interpreter.iter(secp, &psbt.unsigned_tx, index, utxos); if let Some(error) = iter.filter_map(Result::err).next() { return Err(Error::InputError(InputError::Interpreter(error), index)); }; @@ -373,7 +373,7 @@ fn finalize_input_helper( ) -> Result<(Witness, Script), super::Error> { let (witness, script_sig) = { let spk = get_scriptpubkey(psbt, index).map_err(|e| Error::InputError(e, index))?; - let sat = PsbtInputSatisfier::new(&psbt, index); + let sat = PsbtInputSatisfier::new(psbt, index); if spk.is_v1_p2tr() { // Deal with tr case separately, unfortunately we cannot infer the full descriptor for Tr @@ -382,10 +382,10 @@ fn finalize_input_helper( (wit, Script::new()) } else { // Get a descriptor for this input. - let desc = get_descriptor(&psbt, index).map_err(|e| Error::InputError(e, index))?; + let desc = get_descriptor(psbt, index).map_err(|e| Error::InputError(e, index))?; //generate the satisfaction witness and scriptsig - let sat = PsbtInputSatisfier::new(&psbt, index); + let sat = PsbtInputSatisfier::new(psbt, index); if !allow_mall { desc.get_satisfaction(sat) } else { @@ -396,7 +396,7 @@ fn finalize_input_helper( }; let witness = bitcoin::Witness::from_vec(witness); - let utxos = prevouts(&psbt)?; + let utxos = prevouts(psbt)?; let utxos = &Prevouts::All(&utxos); interpreter_inp_check(psbt, secp, index, utxos, &witness, &script_sig)?; diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 6ccd13549..2fee428fc 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -363,7 +363,7 @@ impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfie fn try_vec_as_preimage32(vec: &Vec) -> Option { if vec.len() == 32 { let mut arr = [0u8; 32]; - arr.copy_from_slice(&vec); + arr.copy_from_slice(vec); Some(arr) } else { None @@ -763,7 +763,7 @@ impl PsbtExt for Psbt { }; let (_, spk_check_passed) = - update_input_with_descriptor_helper(input, &desc, Some(expected_spk)) + update_input_with_descriptor_helper(input, desc, Some(expected_spk)) .map_err(UtxoUpdateError::DerivationError)?; if !spk_check_passed { @@ -831,7 +831,7 @@ impl PsbtExt for Psbt { .unwrap_or(false); if inp_spk.is_v0_p2wpkh() || inp_spk.is_v0_p2wsh() || is_nested_wpkh || is_nested_wsh { let msg = if inp_spk.is_v0_p2wpkh() { - let script_code = script_code_wpkh(&inp_spk); + let script_code = script_code_wpkh(inp_spk); cache.segwit_signature_hash(idx, &script_code, amt, hash_ty)? } else if is_nested_wpkh { let script_code = script_code_wpkh( @@ -852,7 +852,7 @@ impl PsbtExt for Psbt { } else { // legacy sighash case let script_code = if inp_spk.is_p2sh() { - &inp.redeem_script + inp.redeem_script .as_ref() .ok_or(SighashError::MissingRedeemScript)? } else { From 81d5ae61375eddcdae7cd5fc97895dac2a0f4d82 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:00:33 +1000 Subject: [PATCH 06/35] Remove explicit return statement Clippy emits a bunch of warnings of the form: warning: unneeded `return` statement As suggested, remove the explicit return statement. --- src/descriptor/tr.rs | 20 ++++++++------------ src/interpreter/inner.rs | 2 +- src/interpreter/mod.rs | 10 +++++----- src/interpreter/stack.rs | 14 ++++++-------- src/miniscript/context.rs | 10 +++------- src/miniscript/types/correctness.rs | 6 +----- src/miniscript/types/malleability.rs | 6 +----- src/miniscript/types/mod.rs | 5 +---- src/psbt/finalizer.rs | 2 +- 9 files changed, 27 insertions(+), 48 deletions(-) diff --git a/src/descriptor/tr.rs b/src/descriptor/tr.rs index 360cb3b54..1b42b931a 100644 --- a/src/descriptor/tr.rs +++ b/src/descriptor/tr.rs @@ -360,12 +360,10 @@ where let right = parse_tr_script_spend(&args[1])?; Ok(TapTree::Tree(Arc::new(left), Arc::new(right))) } - _ => { - return Err(Error::Unexpected( - "unknown format for script spending paths while parsing taproot descriptor" - .to_string(), - )); - } + _ => Err(Error::Unexpected( + "unknown format for script spending paths while parsing taproot descriptor" + .to_string(), + )), } } @@ -460,7 +458,7 @@ fn parse_tr_tree(s: &str) -> Result { } } - let ret = if s.len() > 3 && &s[..3] == "tr(" && s.as_bytes()[s.len() - 1] == b')' { + if s.len() > 3 && &s[..3] == "tr(" && s.as_bytes()[s.len() - 1] == b')' { let rest = &s[3..s.len() - 1]; if !rest.contains(',') { let internal_key = expression::Tree { @@ -497,12 +495,11 @@ fn parse_tr_tree(s: &str) -> Result { } } else { Err(Error::Unexpected("invalid taproot descriptor".to_string())) - }; - return ret; + } } fn split_once(inp: &str, delim: char) -> Option<(&str, &str)> { - let ret = if inp.is_empty() { + if inp.is_empty() { None } else { let mut found = inp.len(); @@ -518,8 +515,7 @@ fn split_once(inp: &str, delim: char) -> Option<(&str, &str)> { } else { Some((&inp[..found], &inp[found + 1..])) } - }; - return ret; + } } impl Liftable for TapTree { diff --git a/src/interpreter/inner.rs b/src/interpreter/inner.rs index 76bd4c4f1..797fbcabe 100644 --- a/src/interpreter/inner.rs +++ b/src/interpreter/inner.rs @@ -255,7 +255,7 @@ pub(super) fn from_txdata<'txin>( Some(tap_script), )) } else { - return Err(Error::ControlBlockVerificationError); + Err(Error::ControlBlockVerificationError) } } } diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index ebacdceef..6e0195c8a 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -980,20 +980,20 @@ where //terminate the next() function in the subsequent call self.public_key = None; self.stack.push(stack::Element::Satisfied); - return Some(Ok(SatisfiedConstraint::PublicKey { key_sig })); + Some(Ok(SatisfiedConstraint::PublicKey { key_sig })) } else { - return Some(Err(Error::PkEvaluationError(PkEvalErrInner::from(*pk)))); + Some(Err(Error::PkEvaluationError(PkEvalErrInner::from(*pk)))) } } else { - return Some(Err(Error::UnexpectedStackEnd)); + Some(Err(Error::UnexpectedStackEnd)) } } else { //All the script has been executed. //Check that the stack must contain exactly 1 satisfied element if self.stack.pop() == Some(stack::Element::Satisfied) && self.stack.is_empty() { - return None; + None } else { - return Some(Err(Error::ScriptSatisfactionError)); + Some(Err(Error::ScriptSatisfactionError)) } } } diff --git a/src/interpreter/stack.rs b/src/interpreter/stack.rs index fe862e4d7..d4f953971 100644 --- a/src/interpreter/stack.rs +++ b/src/interpreter/stack.rs @@ -154,11 +154,11 @@ impl<'txin> Stack<'txin> { self.push(Element::Satisfied); Some(Ok(SatisfiedConstraint::PublicKey { key_sig })) } - Err(e) => return Some(Err(e)), + Err(e) => Some(Err(e)), } } Element::Satisfied => { - return Some(Err(Error::PkEvaluationError(PkEvalErrInner::from(*pk)))); + Some(Err(Error::PkEvaluationError(PkEvalErrInner::from(*pk)))) } } } else { @@ -212,12 +212,10 @@ impl<'txin> Stack<'txin> { key_sig, })) } - Err(e) => return Some(Err(e)), + Err(e) => Some(Err(e)), } } - Element::Satisfied => { - return Some(Err(Error::PkEvaluationError(pk.into()))) - } + Element::Satisfied => Some(Err(Error::PkEvaluationError(pk.into()))), } } else { Some(Err(Error::UnexpectedStackEnd)) @@ -383,10 +381,10 @@ impl<'txin> Stack<'txin> { if let Element::Push(sigser) = witness_sig { let key_sig = verify_sersig(verify_sig, pk, sigser); match key_sig { - Ok(key_sig) => return Some(Ok(SatisfiedConstraint::PublicKey { key_sig })), + Ok(key_sig) => Some(Ok(SatisfiedConstraint::PublicKey { key_sig })), Err(..) => { self.push(witness_sig); - return None; + None } } } else { diff --git a/src/miniscript/context.rs b/src/miniscript/context.rs index e9bda94de..849b77006 100644 --- a/src/miniscript/context.rs +++ b/src/miniscript/context.rs @@ -484,9 +484,7 @@ impl ScriptContext for Segwitv0 { } Ok(()) } - Terminal::MultiA(..) => { - return Err(ScriptContextError::MultiANotAllowed); - } + Terminal::MultiA(..) => Err(ScriptContextError::MultiANotAllowed), _ => Ok(()), } } @@ -593,9 +591,7 @@ impl ScriptContext for Tap { } Ok(()) } - Terminal::Multi(..) => { - return Err(ScriptContextError::TaprootMultiDisabled); - } + Terminal::Multi(..) => Err(ScriptContextError::TaprootMultiDisabled), _ => Ok(()), } } @@ -703,7 +699,7 @@ impl ScriptContext for BareCtx { } Ok(()) } - Terminal::MultiA(..) => return Err(ScriptContextError::MultiANotAllowed), + Terminal::MultiA(..) => Err(ScriptContextError::MultiANotAllowed), _ => Ok(()), } } diff --git a/src/miniscript/types/correctness.rs b/src/miniscript/types/correctness.rs index 0ee507234..82adad152 100644 --- a/src/miniscript/types/correctness.rs +++ b/src/miniscript/types/correctness.rs @@ -99,14 +99,10 @@ impl Correctness { /// in the given `Type`. This returns `true` on same arguments /// `a.is_subtype(a)` is `true`. pub fn is_subtype(&self, other: Self) -> bool { - if self.base == other.base + self.base == other.base && self.input.is_subtype(other.input) && self.dissatisfiable >= other.dissatisfiable && self.unit >= other.unit - { - return true; - } - return false; } } diff --git a/src/miniscript/types/malleability.rs b/src/miniscript/types/malleability.rs index 567297767..6c3cc8169 100644 --- a/src/miniscript/types/malleability.rs +++ b/src/miniscript/types/malleability.rs @@ -71,13 +71,9 @@ impl Malleability { /// in the given `Type`. This returns `true` on same arguments /// `a.is_subtype(a)` is `true`. pub fn is_subtype(&self, other: Self) -> bool { - if self.dissat.is_subtype(other.dissat) + self.dissat.is_subtype(other.dissat) && self.safe >= other.safe && self.non_malleable >= other.non_malleable - { - return true; - } - return false; } } diff --git a/src/miniscript/types/mod.rs b/src/miniscript/types/mod.rs index 8bfac074e..f4ce03212 100644 --- a/src/miniscript/types/mod.rs +++ b/src/miniscript/types/mod.rs @@ -239,10 +239,7 @@ impl Type { /// in the given `Type`. This returns `true` on same arguments /// `a.is_subtype(a)` is `true`. pub fn is_subtype(&self, other: Self) -> bool { - if self.corr.is_subtype(other.corr) && self.mall.is_subtype(other.mall) { - return true; - } - return false; + self.corr.is_subtype(other.corr) && self.mall.is_subtype(other.mall) } } /// Trait representing a type property, which defines how the property diff --git a/src/psbt/finalizer.rs b/src/psbt/finalizer.rs index c39e9ec19..3073099f4 100644 --- a/src/psbt/finalizer.rs +++ b/src/psbt/finalizer.rs @@ -202,7 +202,7 @@ fn get_descriptor(psbt: &Psbt, index: usize) -> Result, In } } else if script_pubkey.is_p2sh() { match &inp.redeem_script { - &None => return Err(InputError::MissingRedeemScript), + &None => Err(InputError::MissingRedeemScript), &Some(ref redeem_script) => { if redeem_script.to_p2sh() != *script_pubkey { return Err(InputError::InvalidRedeemScript { From 52f7dce75808b678d11c1c8a0c9a434a714ba19f Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:01:51 +1000 Subject: [PATCH 07/35] Use & instead of `ref` Clippy emits: warning: `ref` on an entire `let` pattern is discouraged, take a reference with `&` instead As suggested, use `&` instead of `ref`. --- src/descriptor/tr.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/descriptor/tr.rs b/src/descriptor/tr.rs index 1b42b931a..1d29f5eb7 100644 --- a/src/descriptor/tr.rs +++ b/src/descriptor/tr.rs @@ -384,14 +384,14 @@ where }) } 2 => { - let ref key = top.args[0]; + let key = &top.args[0]; if !key.args.is_empty() { return Err(Error::Unexpected(format!( "#{} script associated with `key-path` while parsing taproot descriptor", key.args.len() ))); } - let ref tree = top.args[1]; + let tree = &top.args[1]; let ret = parse_tr_script_spend(tree)?; Ok(Tr { internal_key: expression::terminal(key, Pk::from_str)?, From 5647e29606d9503aa7c8180a70827f2d4f14f877 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:03:28 +1000 Subject: [PATCH 08/35] Remove redundant slicing of whole range Clippy emits: warning: redundant slicing of the whole range As suggested, remove the redundant slicing of whole range. --- src/descriptor/tr.rs | 2 +- src/expression.rs | 2 +- src/miniscript/lex.rs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/descriptor/tr.rs b/src/descriptor/tr.rs index 1d29f5eb7..01f8150dc 100644 --- a/src/descriptor/tr.rs +++ b/src/descriptor/tr.rs @@ -511,7 +511,7 @@ fn split_once(inp: &str, delim: char) -> Option<(&str, &str)> { } // No comma or trailing comma found if found >= inp.len() - 1 { - Some((&inp[..], "")) + Some((inp, "")) } else { Some((&inp[..found], &inp[found + 1..])) } diff --git a/src/expression.rs b/src/expression.rs index 99acfdf26..6e4c3d96a 100644 --- a/src/expression.rs +++ b/src/expression.rs @@ -126,7 +126,7 @@ impl<'a> Tree<'a> { // String-ending terminal Found::Nothing => Ok(( Tree { - name: &sl[..], + name: sl, args: vec![], }, "", diff --git a/src/miniscript/lex.rs b/src/miniscript/lex.rs index cf4fa84fc..4106d9fa4 100644 --- a/src/miniscript/lex.rs +++ b/src/miniscript/lex.rs @@ -66,7 +66,7 @@ impl<'s> fmt::Display for Token<'s> { match *self { Token::Num(n) => write!(f, "#{}", n), Token::Hash20(b) | Token::Bytes33(b) | Token::Bytes32(b) | Token::Bytes65(b) => { - for ch in &b[..] { + for ch in b { write!(f, "{:02x}", *ch)?; } Ok(()) From 8944ca0d4f6cc54ff712e45448f2230ea2432933 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:04:52 +1000 Subject: [PATCH 09/35] Remove explicit lifetimes Clippy emits: warning: explicit lifetimes given in parameter types where they could be elided (or replaced with `'_` if needed by type declaration) As suggested, remove explicit lifetimes and use `'_`, --- src/interpreter/inner.rs | 8 ++++---- src/miniscript/lex.rs | 2 +- src/psbt/finalizer.rs | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/interpreter/inner.rs b/src/interpreter/inner.rs index 797fbcabe..3d9ce2945 100644 --- a/src/interpreter/inner.rs +++ b/src/interpreter/inner.rs @@ -37,8 +37,8 @@ fn pk_from_slice(slice: &[u8], require_compressed: bool) -> Result( - elem: &stack::Element<'a>, +fn pk_from_stackelem( + elem: &stack::Element<'_>, require_compressed: bool, ) -> Result { let slice = if let stack::Element::Push(slice) = *elem { @@ -51,8 +51,8 @@ fn pk_from_stackelem<'a>( // Parse the script with appropriate context to check for context errors like // correct usage of x-only keys or multi_a -fn script_from_stackelem<'a, Ctx: ScriptContext>( - elem: &stack::Element<'a>, +fn script_from_stackelem( + elem: &stack::Element<'_>, ) -> Result, Error> { match *elem { stack::Element::Push(sl) => { diff --git a/src/miniscript/lex.rs b/src/miniscript/lex.rs index 4106d9fa4..2e5c2d918 100644 --- a/src/miniscript/lex.rs +++ b/src/miniscript/lex.rs @@ -113,7 +113,7 @@ impl<'s> Iterator for TokenIter<'s> { } /// Tokenize a script -pub fn lex<'s>(script: &'s script::Script) -> Result>, Error> { +pub fn lex(script: &'_ script::Script) -> Result>, Error> { let mut ret = Vec::with_capacity(script.len()); for ins in script.instructions_minimal() { diff --git a/src/psbt/finalizer.rs b/src/psbt/finalizer.rs index 3073099f4..70bca8d96 100644 --- a/src/psbt/finalizer.rs +++ b/src/psbt/finalizer.rs @@ -117,7 +117,7 @@ pub(super) fn get_utxo(psbt: &Psbt, index: usize) -> Result<&bitcoin::TxOut, Inp } /// Get the Prevouts for the psbt -pub(super) fn prevouts<'a>(psbt: &'a Psbt) -> Result, super::Error> { +pub(super) fn prevouts(psbt: &Psbt) -> Result, super::Error> { let mut utxos = vec![]; for i in 0..psbt.inputs.len() { let utxo_ref = get_utxo(psbt, i).map_err(|e| Error::InputError(e, i))?; From be1a4ee0af639ba727c93a8b3221c2e41de4e779 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:25:55 +1000 Subject: [PATCH 10/35] Use ok_or_else instead of ok_or Clippy emits: warning: use of `ok_or` followed by a function call As suggested, use `ok_or_else` with a closure. --- src/descriptor/checksum.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/descriptor/checksum.rs b/src/descriptor/checksum.rs index a26c7f584..2701fd4ab 100644 --- a/src/descriptor/checksum.rs +++ b/src/descriptor/checksum.rs @@ -43,10 +43,9 @@ pub fn desc_checksum(desc: &str) -> Result { let mut clscount = 0; for ch in desc.chars() { - let pos = INPUT_CHARSET.find(ch).ok_or(Error::BadDescriptor(format!( - "Invalid character in checksum: '{}'", - ch - )))? as u64; + let pos = INPUT_CHARSET.find(ch).ok_or_else(|| { + Error::BadDescriptor(format!("Invalid character in checksum: '{}'", ch)) + })? as u64; c = poly_mod(c, pos & 31); cls = cls * 3 + (pos >> 5); clscount += 1; From 0a1b5e497944da82a5fad08fb67bcd1c1e34992e Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:26:57 +1000 Subject: [PATCH 11/35] Do not use & for pattern match arms Clippy emits: warning: you don't need to add `&` to all patterns Remove the reference on match arms. --- src/descriptor/key.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index 73e710e30..3a44f8a6a 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -73,12 +73,12 @@ pub enum SinglePubKey { impl fmt::Display for DescriptorSecretKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { - &DescriptorSecretKey::Single(ref sk) => { + DescriptorSecretKey::Single(ref sk) => { maybe_fmt_master_id(f, &sk.origin)?; sk.key.fmt(f)?; Ok(()) } - &DescriptorSecretKey::XPrv(ref xprv) => { + DescriptorSecretKey::XPrv(ref xprv) => { maybe_fmt_master_id(f, &xprv.origin)?; xprv.xkey.fmt(f)?; fmt_derivation_path(f, &xprv.derivation_path)?; From d29d10a95b9357a9bff9abfe73cd9fd5974f95a8 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:29:10 +1000 Subject: [PATCH 12/35] Remove reference from expression and patterns Clippy emits: warning: you don't need to add `&` to both the expression and the patterns Remove reference from expression and patterns --- src/descriptor/key.rs | 6 +++--- src/psbt/finalizer.rs | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index 3a44f8a6a..2f73e92b3 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -657,14 +657,14 @@ impl DescriptorXKey { ) -> Option { let (fingerprint, path) = keysource; - let (compare_fingerprint, compare_path) = match &self.origin { - &Some((fingerprint, ref path)) => ( + let (compare_fingerprint, compare_path) = match self.origin { + Some((fingerprint, ref path)) => ( fingerprint, path.into_iter() .chain(self.derivation_path.into_iter()) .collect(), ), - &None => ( + None => ( self.xkey.xkey_fingerprint(secp), self.derivation_path.into_iter().collect::>(), ), diff --git a/src/psbt/finalizer.rs b/src/psbt/finalizer.rs index 70bca8d96..6cc4fe8b9 100644 --- a/src/psbt/finalizer.rs +++ b/src/psbt/finalizer.rs @@ -201,9 +201,9 @@ fn get_descriptor(psbt: &Psbt, index: usize) -> Result, In Err(InputError::MissingWitnessScript) } } else if script_pubkey.is_p2sh() { - match &inp.redeem_script { - &None => Err(InputError::MissingRedeemScript), - &Some(ref redeem_script) => { + match inp.redeem_script { + None => Err(InputError::MissingRedeemScript), + Some(ref redeem_script) => { if redeem_script.to_p2sh() != *script_pubkey { return Err(InputError::InvalidRedeemScript { redeem: redeem_script.clone(), From 3fdd0f516bd0ff5d26e37c984332036752adeb1a Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:30:33 +1000 Subject: [PATCH 13/35] Remove useless conversion call from error return Clippy emits: warning: useless conversion to the same type: `psbt::Error` As suggested, remove the call to `into`. --- src/psbt/mod.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 2fee428fc..927e10b09 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -378,8 +378,7 @@ fn sanity_check(psbt: &Psbt) -> Result<(), Error> { return Err(Error::WrongInputCount { in_tx: psbt.unsigned_tx.input.len(), in_map: psbt.inputs.len(), - } - .into()); + }); } // Check well-formedness of input data From 63dee9eb228a08a40a3028ab47647e3adc8c4da4 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:35:43 +1000 Subject: [PATCH 14/35] Use iter instead of into_iter Clippy emits a bunch of warnings of form: warning: this `.into_iter()` call is equivalent to `.iter()` and will not consume the `slice` As suggested, use `iter` instead of `into_iter`. --- src/miniscript/iter.rs | 2 +- src/policy/mod.rs | 5 ++--- src/policy/semantic.rs | 4 ++-- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/src/miniscript/iter.rs b/src/miniscript/iter.rs index 013f79337..c80033bc4 100644 --- a/src/miniscript/iter.rs +++ b/src/miniscript/iter.rs @@ -158,7 +158,7 @@ impl Miniscript { Terminal::PkH(ref hash) => vec![PkPkh::HashedPubkey(hash.clone())], Terminal::PkK(ref key) => vec![PkPkh::PlainPubkey(key.clone())], Terminal::Multi(_, ref keys) | Terminal::MultiA(_, ref keys) => keys - .into_iter() + .iter() .map(|key| PkPkh::PlainPubkey(key.clone())) .collect(), _ => vec![], diff --git a/src/policy/mod.rs b/src/policy/mod.rs index bdefc6845..4df50aba9 100644 --- a/src/policy/mod.rs +++ b/src/policy/mod.rs @@ -157,13 +157,12 @@ impl Liftable for Terminal { Semantic::Threshold(1, vec![left.node.lift()?, right.node.lift()?]) } Terminal::Thresh(k, ref subs) => { - let semantic_subs: Result<_, Error> = - subs.into_iter().map(|s| s.node.lift()).collect(); + let semantic_subs: Result<_, Error> = subs.iter().map(|s| s.node.lift()).collect(); Semantic::Threshold(k, semantic_subs?) } Terminal::Multi(k, ref keys) | Terminal::MultiA(k, ref keys) => Semantic::Threshold( k, - keys.into_iter() + keys.iter() .map(|k| Semantic::KeyHash(k.to_pubkeyhash())) .collect(), ), diff --git a/src/policy/semantic.rs b/src/policy/semantic.rs index 2dace4e5f..ca8c93fb8 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -235,7 +235,7 @@ impl fmt::Debug for Policy { } else { write!(f, "thresh({},", k)?; } - for (i, sub) in subs.into_iter().enumerate() { + for (i, sub) in subs.iter().enumerate() { if i == 0 { write!(f, "{}", sub)?; } else { @@ -268,7 +268,7 @@ impl fmt::Display for Policy { } else { write!(f, "thresh({},", k)?; } - for (i, sub) in subs.into_iter().enumerate() { + for (i, sub) in subs.iter().enumerate() { if i == 0 { write!(f, "{}", sub)?; } else { From 738ff15174f8405c305b843b4118a587018bea0e Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:38:20 +1000 Subject: [PATCH 15/35] Remove redundant closures Clippy emits a bunch of warnings of form: warning: redundant closure As suggested, remove the redundant closures and just pass in the function. --- src/descriptor/key.rs | 2 +- src/interpreter/inner.rs | 4 ++-- src/miniscript/astelem.rs | 2 +- src/policy/concrete.rs | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index 2f73e92b3..3c5a72413 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -562,7 +562,7 @@ impl DescriptorXKey { DescriptorKeyParseError("Malformed master fingerprint, expected 8 hex chars") })?; let origin_path = raw_origin - .map(|p| bip32::ChildNumber::from_str(p)) + .map(bip32::ChildNumber::from_str) .collect::>() .map_err(|_| { DescriptorKeyParseError("Error while parsing master derivation path") diff --git a/src/interpreter/inner.rs b/src/interpreter/inner.rs index 3d9ce2945..5b47dff64 100644 --- a/src/interpreter/inner.rs +++ b/src/interpreter/inner.rs @@ -233,8 +233,8 @@ pub(super) fn from_txdata<'txin>( let ctrl_blk = wit_stack.pop().ok_or(Error::UnexpectedStackEnd)?; let ctrl_blk = ctrl_blk.as_push()?; let tap_script = wit_stack.pop().ok_or(Error::UnexpectedStackEnd)?; - let ctrl_blk = ControlBlock::from_slice(ctrl_blk) - .map_err(|e| Error::ControlBlockParse(e))?; + let ctrl_blk = + ControlBlock::from_slice(ctrl_blk).map_err(Error::ControlBlockParse)?; let tap_script = script_from_stackelem::(&tap_script)?; let ms = tap_script.to_no_checks_ms(); // Creating new contexts is cheap diff --git a/src/miniscript/astelem.rs b/src/miniscript/astelem.rs index c3ce5f451..63c97c7e6 100644 --- a/src/miniscript/astelem.rs +++ b/src/miniscript/astelem.rs @@ -555,7 +555,7 @@ where let subs: Result>>, _> = top.args[1..] .iter() - .map(|sub| expression::FromTree::from_tree(sub)) + .map(expression::FromTree::from_tree) .collect(); Ok(Terminal::Thresh(k, subs?)) diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 3710bb6a1..7ae388073 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -571,7 +571,7 @@ where ("TRIVIAL", 0) => Ok(Policy::Trivial), ("pk", 1) => expression::terminal(&top.args[0], |pk| Pk::from_str(pk).map(Policy::Key)), ("after", 1) => { - let num = expression::terminal(&top.args[0], |x| expression::parse_num(x))?; + let num = expression::terminal(&top.args[0], expression::parse_num)?; if num > 2u32.pow(31) { return Err(Error::PolicyError(PolicyError::TimeTooFar)); } else if num == 0 { @@ -580,7 +580,7 @@ where Ok(Policy::After(num)) } ("older", 1) => { - let num = expression::terminal(&top.args[0], |x| expression::parse_num(x))?; + let num = expression::terminal(&top.args[0], expression::parse_num)?; if num > 2u32.pow(31) { return Err(Error::PolicyError(PolicyError::TimeTooFar)); } else if num == 0 { From 7b91918a4a37f60348dabd8e7029eeeaef248eef Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:40:38 +1000 Subject: [PATCH 16/35] Use is_empty Clippy emits a couple of warnings of form: warning: length comparison to zero As suggested, use `is_empty` instead of manually comparing to zero. --- src/descriptor/key.rs | 3 +-- src/interpreter/inner.rs | 2 +- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index 3c5a72413..5ba61c458 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -670,8 +670,7 @@ impl DescriptorXKey { ), }; - let path_excluding_wildcard = if self.wildcard != Wildcard::None && path.as_ref().len() > 0 - { + let path_excluding_wildcard = if self.wildcard != Wildcard::None && !path.is_empty() { path.into_iter() .take(path.as_ref().len() - 1) .cloned() diff --git a/src/interpreter/inner.rs b/src/interpreter/inner.rs index 5b47dff64..2cf7db62b 100644 --- a/src/interpreter/inner.rs +++ b/src/interpreter/inner.rs @@ -212,7 +212,7 @@ pub(super) fn from_txdata<'txin>( let has_annex = wit_stack .last() .and_then(|x| x.as_push().ok()) - .map(|x| x.len() > 0 && x[0] == TAPROOT_ANNEX_PREFIX) + .map(|x| !x.is_empty() && x[0] == TAPROOT_ANNEX_PREFIX) .unwrap_or(false); let has_annex = has_annex && (wit_stack.len() >= 2); if has_annex { From ea57d6e1bc4b4fa778da347a9d8cf27d039fe32a Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:42:13 +1000 Subject: [PATCH 17/35] Use contains instead of manual implementation Clippy emits: warning: manual `!RangeInclusive::contains` implementation As suggested, use contains instead of manual implementation. --- src/expression.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/expression.rs b/src/expression.rs index 6e4c3d96a..17bff33cf 100644 --- a/src/expression.rs +++ b/src/expression.rs @@ -195,7 +195,7 @@ impl<'a> Tree<'a> { pub fn parse_num(s: &str) -> Result { if s.len() > 1 { let ch = s.chars().next().unwrap(); - if ch < '1' || ch > '9' { + if !('1'..='9').contains(&ch) { return Err(Error::Unexpected( "Number must start with a digit 1-9".to_string(), )); From ad51d83a9d481e2b0c9b278f4d27625a76c37ea2 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:47:43 +1000 Subject: [PATCH 18/35] Derive Default We can derive these implementations. Found by clippy. --- src/interpreter/stack.rs | 8 +------- src/miniscript/types/extra_props.rs | 14 +------------- 2 files changed, 2 insertions(+), 20 deletions(-) diff --git a/src/interpreter/stack.rs b/src/interpreter/stack.rs index d4f953971..41d601bc3 100644 --- a/src/interpreter/stack.rs +++ b/src/interpreter/stack.rs @@ -83,7 +83,7 @@ impl<'txin> Element<'txin> { /// Stack Data structure representing the stack input to Miniscript. This Stack /// is created from the combination of ScriptSig and Witness stack. -#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)] pub struct Stack<'txin>(Vec>); impl<'txin> From>> for Stack<'txin> { @@ -92,12 +92,6 @@ impl<'txin> From>> for Stack<'txin> { } } -impl<'txin> Default for Stack<'txin> { - fn default() -> Self { - Stack(vec![]) - } -} - impl<'txin> Stack<'txin> { /// Whether the stack is empty pub fn is_empty(&self) -> bool { diff --git a/src/miniscript/types/extra_props.rs b/src/miniscript/types/extra_props.rs index 68c5a5e6a..ddb1f861c 100644 --- a/src/miniscript/types/extra_props.rs +++ b/src/miniscript/types/extra_props.rs @@ -13,7 +13,7 @@ use std::cmp; use std::iter::once; /// Helper struct Whether any satisfaction of this fragment contains any timelocks -#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Default, Hash)] pub struct TimeLockInfo { /// csv with heights pub csv_with_height: bool, @@ -27,18 +27,6 @@ pub struct TimeLockInfo { pub contains_combination: bool, } -impl Default for TimeLockInfo { - fn default() -> Self { - Self { - csv_with_height: false, - csv_with_time: false, - cltv_with_height: false, - cltv_with_time: false, - contains_combination: false, - } - } -} - /// Helper struct to store information about op code limits. Note that this only /// counts the non-push opcodes. This is not relevant for TapScript context #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] From 35015bf7e702de0c619face925971429c69d3e76 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:49:43 +1000 Subject: [PATCH 19/35] Remove redundant pattern matching Clippy emits two warnings of the form: warning: redundant pattern matching, consider using ... As suggested use `is_none` and `is_ok` where appropriate. --- src/miniscript/analyzable.rs | 5 +---- src/miniscript/iter.rs | 2 +- 2 files changed, 2 insertions(+), 5 deletions(-) diff --git a/src/miniscript/analyzable.rs b/src/miniscript/analyzable.rs index 7a3eb8633..c761a0a39 100644 --- a/src/miniscript/analyzable.rs +++ b/src/miniscript/analyzable.rs @@ -83,10 +83,7 @@ impl Miniscript { // It maybe possible to return a detail error type containing why the miniscript // failed. But doing so may require returning a collection of errors pub fn within_resource_limits(&self) -> bool { - match Ctx::check_local_validity(self) { - Ok(_) => true, - Err(_) => false, - } + Ctx::check_local_validity(self).is_ok() } /// Whether the miniscript contains a combination of timelocks diff --git a/src/miniscript/iter.rs b/src/miniscript/iter.rs index c80033bc4..b9018a921 100644 --- a/src/miniscript/iter.rs +++ b/src/miniscript/iter.rs @@ -258,7 +258,7 @@ impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iterator for Iter<'a, Pk, Ctx> { /// To enumerate the branches iterator uses [Miniscript::branches] function. fn next(&mut self) -> Option { let mut curr = self.next; - if let None = curr { + if curr.is_none() { while let Some((node, child)) = self.path.pop() { curr = node.get_nth_child(child); if curr.is_some() { From bc7be32fab6e4ecf7ba9235013def628ba77a8f4 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:51:16 +1000 Subject: [PATCH 20/35] Remove unnecessary call to String::from Clippy emits: warning: useless conversion to the same type: `std::string::String` As suggested, remove the useless call to `String::from` --- src/miniscript/lex.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miniscript/lex.rs b/src/miniscript/lex.rs index 2e5c2d918..ae8cbffe3 100644 --- a/src/miniscript/lex.rs +++ b/src/miniscript/lex.rs @@ -206,7 +206,7 @@ pub fn lex(script: &'_ script::Script) -> Result>, Error> { Some(op @ &Token::Equal) | Some(op @ &Token::CheckSig) | Some(op @ &Token::CheckMultiSig) => { - return Err(Error::NonMinimalVerify(String::from(format!("{:?}", op)))) + return Err(Error::NonMinimalVerify(format!("{:?}", op))) } _ => {} } From 230cab996721b64a1de8efb04fe6c5c212399d22 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:54:36 +1000 Subject: [PATCH 21/35] Use map instead of and_then Clippy emits a couple of warnings of the form: warning: using `Option.and_then(|x| Some(y))`, which is more succinctly expressed as `map(|x| y)` As suggested, use `map` instead of `and_then` --- src/miniscript/astelem.rs | 5 +---- src/miniscript/types/extra_props.rs | 4 ++-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/miniscript/astelem.rs b/src/miniscript/astelem.rs index 63c97c7e6..acbe6029b 100644 --- a/src/miniscript/astelem.rs +++ b/src/miniscript/astelem.rs @@ -200,10 +200,7 @@ impl Terminal { Terminal::Thresh(k, ref subs) => { let subs: Result>>, _> = subs .iter() - .map(|s| { - s.real_translate_pk(&mut *fpk, &mut *fpkh) - .and_then(|x| Ok(Arc::new(x))) - }) + .map(|s| s.real_translate_pk(&mut *fpk, &mut *fpkh).map(Arc::new)) .collect(); Terminal::Thresh(k, subs?) } diff --git a/src/miniscript/types/extra_props.rs b/src/miniscript/types/extra_props.rs index ddb1f861c..5d7728636 100644 --- a/src/miniscript/types/extra_props.rs +++ b/src/miniscript/types/extra_props.rs @@ -686,8 +686,8 @@ impl Property for ExtData { (None, None) => None, }, max_sat_size: cmp::max( - l.max_sat_size.and_then(|(w, s)| Some((w + 2, s + 1))), - r.max_sat_size.and_then(|(w, s)| Some((w + 1, s + 1))), + l.max_sat_size.map(|(w, s)| (w + 2, s + 1)), + r.max_sat_size.map(|(w, s)| (w + 1, s + 1)), ), max_dissat_size: match (l.max_dissat_size, r.max_dissat_size) { (Some(l), Some(r)) => { From 54f23840ae190f4240b3438279320254aa3c4591 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:57:11 +1000 Subject: [PATCH 22/35] Remove redundant clone This function consumes self so no need to clone it both times. --- src/policy/semantic.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/policy/semantic.rs b/src/policy/semantic.rs index ca8c93fb8..6e7491989 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -188,7 +188,7 @@ impl Policy { // Witness is currently encoded as policy. Only accepts leaf fragment and // a normalized policy fn satisfy_constraint(self, witness: &Policy, available: bool) -> Policy { - debug_assert!(self.clone().normalized() == self.clone()); + debug_assert!(self.clone().normalized() == self); match *witness { // only for internal purposes, safe to use unreachable! Policy::Threshold(..) => unreachable!(), From 592b4790f3f229b2bcad28238777f6440235d28d Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 13:59:25 +1000 Subject: [PATCH 23/35] Use copied Now we have Rust 1.31 we can use `copied`. Clears clippy warning. --- src/miniscript/satisfy.rs | 4 ++-- src/psbt/mod.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/miniscript/satisfy.rs b/src/miniscript/satisfy.rs index 02d5d8c93..234f06029 100644 --- a/src/miniscript/satisfy.rs +++ b/src/miniscript/satisfy.rs @@ -168,7 +168,7 @@ impl Satisfier for After { impl Satisfier for HashMap { fn lookup_ecdsa_sig(&self, key: &Pk) -> Option { - self.get(key).map(|x| *x) + self.get(key).copied() } } @@ -180,7 +180,7 @@ impl Satisfier // If we change the signature the of lookup_tap_leaf_script_sig to accept a tuple. We would // face the same problem while satisfying PkK. // We use this signature to optimize for the psbt common use case. - self.get(&(key.clone(), *h)).map(|x| *x) + self.get(&(key.clone(), *h)).copied() } } diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 927e10b09..333462a1c 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -262,7 +262,7 @@ impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfie self.psbt.inputs[self.index] .tap_script_sigs .get(&(pk.to_x_only_pubkey(), *lh)) - .map(|x| *x) // replace by copied in 1.36 + .copied() } fn lookup_tap_control_block_map( @@ -289,7 +289,7 @@ impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfie self.psbt.inputs[self.index] .partial_sigs .get(&pk.to_public_key()) - .map(|sig| *sig) + .copied() } fn lookup_pkh_ecdsa_sig( From ebc4dc9f78ee87bbbc3f8833a4da890c29fdcb9f Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 14:02:07 +1000 Subject: [PATCH 24/35] Use to_string instead of format macro Clippy emits: warning: useless use of `format!` As suggested, use `to_string`. --- src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index 4132ce6df..68050a3cf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -186,7 +186,7 @@ impl MiniscriptKey for String { type Hash = String; fn to_pubkeyhash(&self) -> Self::Hash { - format!("{}", &self) + (&self).to_string() } } From 45fd5f7fc7676bbcfa10f327482bd58b542536ab Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Fri, 22 Apr 2022 14:04:15 +1000 Subject: [PATCH 25/35] Use push with character literal Clippy emits: warning: calling `push_str()` using a single-character string literal As suggested, use `push` with character literal. --- src/miniscript/astelem.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/miniscript/astelem.rs b/src/miniscript/astelem.rs index acbe6029b..72c19dd44 100644 --- a/src/miniscript/astelem.rs +++ b/src/miniscript/astelem.rs @@ -473,12 +473,12 @@ where if name == "pk" { frag_name = "pk_k"; aliased_wrap = wrap.to_owned(); - aliased_wrap.push_str("c"); + aliased_wrap.push('c'); frag_wrap = &aliased_wrap; } else if name == "pkh" { frag_name = "pk_h"; aliased_wrap = wrap.to_owned(); - aliased_wrap.push_str("c"); + aliased_wrap.push('c'); frag_wrap = &aliased_wrap; } else { frag_name = name; From 54412f137cb97623fb1f935a6c099a028645d520 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Tue, 10 May 2022 12:17:50 +1000 Subject: [PATCH 26/35] Simplify duplicate code Clippy emits: error: this `if` has identical blocks Simplify the code by removing the duplicate blocks. --- src/miniscript/astelem.rs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/miniscript/astelem.rs b/src/miniscript/astelem.rs index 72c19dd44..3ef00ca00 100644 --- a/src/miniscript/astelem.rs +++ b/src/miniscript/astelem.rs @@ -405,13 +405,10 @@ impl fmt::Display for Terminal { } // Add a ':' wrapper if there are other wrappers apart from c:pk_k() // tvc:pk_k() -> tv:pk() - Some(('c', ms)) => { - if let Terminal::PkK(ref _pk) = ms.node { - fmt::Write::write_char(f, ':')?; - } else if let Terminal::PkH(ref _pkh) = ms.node { - fmt::Write::write_char(f, ':')?; - } - } + Some(('c', ms)) => match ms.node { + Terminal::PkK(_) | Terminal::PkH(_) => fmt::Write::write_char(f, ':')?, + _ => {} + }, _ => {} }; write!(f, "{}", sub) From af2260fae9989558c513cd6034113f9f51bd227a Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 13:11:33 +1000 Subject: [PATCH 27/35] Return block directly Clippy emits: warning: returning the result of a `let` binding from a block As suggested, return the block directly. --- src/miniscript/satisfy.rs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/miniscript/satisfy.rs b/src/miniscript/satisfy.rs index 234f06029..a41140cdb 100644 --- a/src/miniscript/satisfy.rs +++ b/src/miniscript/satisfy.rs @@ -833,16 +833,15 @@ impl Satisfaction { // signatures let mut sat_indices = (0..subs.len()).collect::>(); sat_indices.sort_by_key(|&i| { - let stack_weight = match (&sats[i].stack, &ret_stack[i].stack) { + // For malleable satifactions, directly choose smallest weights + match (&sats[i].stack, &ret_stack[i].stack) { (&Witness::Unavailable, _) | (&Witness::Impossible, _) => i64::MAX, // This is only possible when one of the branches has PkH (_, &Witness::Unavailable) | (_, &Witness::Impossible) => i64::MIN, (&Witness::Stack(ref s), &Witness::Stack(ref d)) => { witness_size(s) as i64 - witness_size(d) as i64 } - }; - // For malleable satifactions, directly choose smallest weights - stack_weight + } }); // swap the satisfactions From 98d4a063a52f2a882ba0ff7f94113a23ef447f99 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 13:12:35 +1000 Subject: [PATCH 28/35] Remove unneeded `ref` Clippy emits: warning: this pattern creates a reference to a reference As suggested remove the `ref` and use `v` directly. --- src/miniscript/satisfy.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miniscript/satisfy.rs b/src/miniscript/satisfy.rs index a41140cdb..6a38bf9ea 100644 --- a/src/miniscript/satisfy.rs +++ b/src/miniscript/satisfy.rs @@ -1166,7 +1166,7 @@ impl Satisfaction { let max_idx = sigs .iter() .enumerate() - .max_by_key(|&(_, ref v)| v.len()) + .max_by_key(|&(_, v)| v.len()) .unwrap() .0; sigs[max_idx] = vec![]; From da6e068df151867003ec0768f9fc20c5c684a3a3 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 13:42:48 +1000 Subject: [PATCH 29/35] Remove the redundant calls to clone on Copy type Clippy emits a bunch of warnings of type: warning: using `clone` on type which implements the `Copy` trait As suggested, remove the redundant calls to clone. --- src/miniscript/types/extra_props.rs | 46 ++++++++++++++--------------- src/miniscript/types/mod.rs | 46 ++++++++++++++--------------- src/policy/concrete.rs | 8 ++--- src/policy/semantic.rs | 8 ++--- src/psbt/mod.rs | 5 ++-- 5 files changed, 56 insertions(+), 57 deletions(-) diff --git a/src/miniscript/types/extra_props.rs b/src/miniscript/types/extra_props.rs index 5d7728636..b8cfe0d5c 100644 --- a/src/miniscript/types/extra_props.rs +++ b/src/miniscript/types/extra_props.rs @@ -951,47 +951,47 @@ impl Property for ExtData { Terminal::Hash256(..) => Ok(Self::from_hash256()), Terminal::Ripemd160(..) => Ok(Self::from_ripemd160()), Terminal::Hash160(..) => Ok(Self::from_hash160()), - Terminal::Alt(ref sub) => wrap_err(Self::cast_alt(sub.ext.clone())), - Terminal::Swap(ref sub) => wrap_err(Self::cast_swap(sub.ext.clone())), - Terminal::Check(ref sub) => wrap_err(Self::cast_check(sub.ext.clone())), - Terminal::DupIf(ref sub) => wrap_err(Self::cast_dupif(sub.ext.clone())), - Terminal::Verify(ref sub) => wrap_err(Self::cast_verify(sub.ext.clone())), - Terminal::NonZero(ref sub) => wrap_err(Self::cast_nonzero(sub.ext.clone())), - Terminal::ZeroNotEqual(ref sub) => wrap_err(Self::cast_zeronotequal(sub.ext.clone())), + Terminal::Alt(ref sub) => wrap_err(Self::cast_alt(sub.ext)), + Terminal::Swap(ref sub) => wrap_err(Self::cast_swap(sub.ext)), + Terminal::Check(ref sub) => wrap_err(Self::cast_check(sub.ext)), + Terminal::DupIf(ref sub) => wrap_err(Self::cast_dupif(sub.ext)), + Terminal::Verify(ref sub) => wrap_err(Self::cast_verify(sub.ext)), + Terminal::NonZero(ref sub) => wrap_err(Self::cast_nonzero(sub.ext)), + Terminal::ZeroNotEqual(ref sub) => wrap_err(Self::cast_zeronotequal(sub.ext)), Terminal::AndB(ref l, ref r) => { - let ltype = l.ext.clone(); - let rtype = r.ext.clone(); + let ltype = l.ext; + let rtype = r.ext; wrap_err(Self::and_b(ltype, rtype)) } Terminal::AndV(ref l, ref r) => { - let ltype = l.ext.clone(); - let rtype = r.ext.clone(); + let ltype = l.ext; + let rtype = r.ext; wrap_err(Self::and_v(ltype, rtype)) } Terminal::OrB(ref l, ref r) => { - let ltype = l.ext.clone(); - let rtype = r.ext.clone(); + let ltype = l.ext; + let rtype = r.ext; wrap_err(Self::or_b(ltype, rtype)) } Terminal::OrD(ref l, ref r) => { - let ltype = l.ext.clone(); - let rtype = r.ext.clone(); + let ltype = l.ext; + let rtype = r.ext; wrap_err(Self::or_d(ltype, rtype)) } Terminal::OrC(ref l, ref r) => { - let ltype = l.ext.clone(); - let rtype = r.ext.clone(); + let ltype = l.ext; + let rtype = r.ext; wrap_err(Self::or_c(ltype, rtype)) } Terminal::OrI(ref l, ref r) => { - let ltype = l.ext.clone(); - let rtype = r.ext.clone(); + let ltype = l.ext; + let rtype = r.ext; wrap_err(Self::or_i(ltype, rtype)) } Terminal::AndOr(ref a, ref b, ref c) => { - let atype = a.ext.clone(); - let btype = b.ext.clone(); - let ctype = c.ext.clone(); + let atype = a.ext; + let btype = b.ext; + let ctype = c.ext; wrap_err(Self::and_or(atype, btype, ctype)) } Terminal::Thresh(k, ref subs) => { @@ -1008,7 +1008,7 @@ impl Property for ExtData { }); } - let res = Self::threshold(k, subs.len(), |n| Ok(subs[n].ext.clone())); + let res = Self::threshold(k, subs.len(), |n| Ok(subs[n].ext)); res.map_err(|kind| Error { fragment: fragment.clone(), diff --git a/src/miniscript/types/mod.rs b/src/miniscript/types/mod.rs index f4ce03212..156203cd2 100644 --- a/src/miniscript/types/mod.rs +++ b/src/miniscript/types/mod.rs @@ -842,47 +842,47 @@ impl Property for Type { Terminal::Hash256(..) => Ok(Self::from_hash256()), Terminal::Ripemd160(..) => Ok(Self::from_ripemd160()), Terminal::Hash160(..) => Ok(Self::from_hash160()), - Terminal::Alt(ref sub) => wrap_err(Self::cast_alt(sub.ty.clone())), - Terminal::Swap(ref sub) => wrap_err(Self::cast_swap(sub.ty.clone())), - Terminal::Check(ref sub) => wrap_err(Self::cast_check(sub.ty.clone())), - Terminal::DupIf(ref sub) => wrap_err(Self::cast_dupif(sub.ty.clone())), - Terminal::Verify(ref sub) => wrap_err(Self::cast_verify(sub.ty.clone())), - Terminal::NonZero(ref sub) => wrap_err(Self::cast_nonzero(sub.ty.clone())), - Terminal::ZeroNotEqual(ref sub) => wrap_err(Self::cast_zeronotequal(sub.ty.clone())), + Terminal::Alt(ref sub) => wrap_err(Self::cast_alt(sub.ty)), + Terminal::Swap(ref sub) => wrap_err(Self::cast_swap(sub.ty)), + Terminal::Check(ref sub) => wrap_err(Self::cast_check(sub.ty)), + Terminal::DupIf(ref sub) => wrap_err(Self::cast_dupif(sub.ty)), + Terminal::Verify(ref sub) => wrap_err(Self::cast_verify(sub.ty)), + Terminal::NonZero(ref sub) => wrap_err(Self::cast_nonzero(sub.ty)), + Terminal::ZeroNotEqual(ref sub) => wrap_err(Self::cast_zeronotequal(sub.ty)), Terminal::AndB(ref l, ref r) => { - let ltype = l.ty.clone(); - let rtype = r.ty.clone(); + let ltype = l.ty; + let rtype = r.ty; wrap_err(Self::and_b(ltype, rtype)) } Terminal::AndV(ref l, ref r) => { - let ltype = l.ty.clone(); - let rtype = r.ty.clone(); + let ltype = l.ty; + let rtype = r.ty; wrap_err(Self::and_v(ltype, rtype)) } Terminal::OrB(ref l, ref r) => { - let ltype = l.ty.clone(); - let rtype = r.ty.clone(); + let ltype = l.ty; + let rtype = r.ty; wrap_err(Self::or_b(ltype, rtype)) } Terminal::OrD(ref l, ref r) => { - let ltype = l.ty.clone(); - let rtype = r.ty.clone(); + let ltype = l.ty; + let rtype = r.ty; wrap_err(Self::or_d(ltype, rtype)) } Terminal::OrC(ref l, ref r) => { - let ltype = l.ty.clone(); - let rtype = r.ty.clone(); + let ltype = l.ty; + let rtype = r.ty; wrap_err(Self::or_c(ltype, rtype)) } Terminal::OrI(ref l, ref r) => { - let ltype = l.ty.clone(); - let rtype = r.ty.clone(); + let ltype = l.ty; + let rtype = r.ty; wrap_err(Self::or_i(ltype, rtype)) } Terminal::AndOr(ref a, ref b, ref c) => { - let atype = a.ty.clone(); - let btype = b.ty.clone(); - let ctype = c.ty.clone(); + let atype = a.ty; + let btype = b.ty; + let ctype = c.ty; wrap_err(Self::and_or(atype, btype, ctype)) } Terminal::Thresh(k, ref subs) => { @@ -899,7 +899,7 @@ impl Property for Type { }); } - let res = Self::threshold(k, subs.len(), |n| Ok(subs[n].ty.clone())); + let res = Self::threshold(k, subs.len(), |n| Ok(subs[n].ty)); res.map_err(|kind| Error { fragment: fragment.clone(), diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 7ae388073..6f553ee97 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -202,10 +202,10 @@ impl Policy { Policy::Unsatisfiable => Ok(Policy::Unsatisfiable), Policy::Trivial => Ok(Policy::Trivial), Policy::Key(ref pk) => fpk(pk).map(Policy::Key), - Policy::Sha256(ref h) => Ok(Policy::Sha256(h.clone())), - Policy::Hash256(ref h) => Ok(Policy::Hash256(h.clone())), - Policy::Ripemd160(ref h) => Ok(Policy::Ripemd160(h.clone())), - Policy::Hash160(ref h) => Ok(Policy::Hash160(h.clone())), + Policy::Sha256(ref h) => Ok(Policy::Sha256(*h)), + Policy::Hash256(ref h) => Ok(Policy::Hash256(*h)), + Policy::Ripemd160(ref h) => Ok(Policy::Ripemd160(*h)), + Policy::Hash160(ref h) => Ok(Policy::Hash160(*h)), Policy::After(n) => Ok(Policy::After(n)), Policy::Older(n) => Ok(Policy::Older(n)), Policy::Threshold(k, ref subs) => { diff --git a/src/policy/semantic.rs b/src/policy/semantic.rs index 6e7491989..a3cec00f9 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -116,10 +116,10 @@ impl Policy { Policy::Unsatisfiable => Ok(Policy::Unsatisfiable), Policy::Trivial => Ok(Policy::Trivial), Policy::KeyHash(ref pkh) => fpkh(pkh).map(Policy::KeyHash), - Policy::Sha256(ref h) => Ok(Policy::Sha256(h.clone())), - Policy::Hash256(ref h) => Ok(Policy::Hash256(h.clone())), - Policy::Ripemd160(ref h) => Ok(Policy::Ripemd160(h.clone())), - Policy::Hash160(ref h) => Ok(Policy::Hash160(h.clone())), + Policy::Sha256(ref h) => Ok(Policy::Sha256(*h)), + Policy::Hash256(ref h) => Ok(Policy::Hash256(*h)), + Policy::Ripemd160(ref h) => Ok(Policy::Ripemd160(*h)), + Policy::Hash160(ref h) => Ok(Policy::Hash160(*h)), Policy::After(n) => Ok(Policy::After(n)), Policy::Older(n) => Ok(Policy::Older(n)), Policy::Threshold(k, ref subs) => { diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 333462a1c..77d6bfca5 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -959,10 +959,9 @@ fn update_input_with_descriptor_helper( (pk.to_x_only_pubkey(), xpk) } (PkPkh::HashedPubkey(hash), PkPkh::HashedPubkey(xpk)) => ( - hash_lookup + *hash_lookup .get(&hash) - .expect("translate_pk inserted an entry for every hash") - .clone(), + .expect("translate_pk inserted an entry for every hash"), xpk, ), _ => unreachable!("the iterators work in the same order"), From 90ba69228912def84265883f3edb728f6a0b1c08 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 13:46:44 +1000 Subject: [PATCH 30/35] Use unwrap_or_else instead of unwrap_or Clippy emits: warning: use of `unwrap_or` followed by a function call As suggested use `unwrap_or_else`. --- src/miniscript/types/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/miniscript/types/mod.rs b/src/miniscript/types/mod.rs index 156203cd2..507ef28e2 100644 --- a/src/miniscript/types/mod.rs +++ b/src/miniscript/types/mod.rs @@ -528,7 +528,7 @@ pub trait Property: Sized { }); res.map_err(|kind| Error { - fragment: last_err_frag.unwrap_or(fragment.clone()), + fragment: last_err_frag.unwrap_or_else(|| fragment.clone()), error: kind, }) } From 289a1a8bda3e5af0bb1b68708c5c811482631fd4 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 13:56:51 +1000 Subject: [PATCH 31/35] Use flat_map instead of chaining map and flatten Clippy emits: warning: called `map(..).flatten()` on an `Iterator` As suggested, use `flat_map` instead. --- src/policy/concrete.rs | 17 +++++------------ 1 file changed, 5 insertions(+), 12 deletions(-) diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 6f553ee97..59d9f16ca 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -230,20 +230,13 @@ impl Policy { pub fn keys(&self) -> Vec<&Pk> { match *self { Policy::Key(ref pk) => vec![pk], - Policy::Threshold(_k, ref subs) => subs - .iter() - .map(|sub| sub.keys()) - .flatten() - .collect::>(), - Policy::And(ref subs) => subs - .iter() - .map(|sub| sub.keys()) - .flatten() - .collect::>(), + Policy::Threshold(_k, ref subs) => { + subs.iter().flat_map(|sub| sub.keys()).collect::>() + } + Policy::And(ref subs) => subs.iter().flat_map(|sub| sub.keys()).collect::>(), Policy::Or(ref subs) => subs .iter() - .map(|(ref _k, ref sub)| sub.keys()) - .flatten() + .flat_map(|(ref _k, ref sub)| sub.keys()) .collect::>(), // map all hashes and time _ => vec![], From 769cd6db4cb7c039b4d0ee0c05fb55127d495b58 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 14:01:45 +1000 Subject: [PATCH 32/35] Do not check for < 0 for usize types Clippy emits: error: this comparison involving the minimum or maximum element for this type contains a case that is always true or always false The vars `k` and `thresh` are both of type `uszie` and can never be below zero, use `==` instead. --- src/policy/concrete.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 59d9f16ca..a51d326c4 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -341,7 +341,7 @@ impl Policy { } } Policy::Threshold(k, ref subs) => { - if k <= 0 || k > subs.len() { + if k == 0 || k > subs.len() { Err(PolicyError::IncorrectThresh) } else { subs.iter() @@ -619,7 +619,7 @@ where } let thresh = expression::parse_num(top.args[0].name)?; - if thresh >= nsubs || thresh <= 0 { + if thresh >= nsubs || thresh == 0 { return Err(Error::PolicyError(PolicyError::IncorrectThresh)); } From b75964cca195bd79c062cc635ba4d67d7dfb6cb7 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 14:04:53 +1000 Subject: [PATCH 33/35] Use sort_unstable on primitive types Clippy emits a few warnings of type: warning: used `sort` on primitive type `u32` As suggested, use `sort_unstable` on `u32` and `usize` primitives. --- src/policy/semantic.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/policy/semantic.rs b/src/policy/semantic.rs index a3cec00f9..7a389542c 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -489,7 +489,7 @@ impl Policy { /// which appear in the policy pub fn relative_timelocks(&self) -> Vec { let mut ret = self.real_relative_timelocks(); - ret.sort(); + ret.sort_unstable(); ret.dedup(); ret } @@ -517,7 +517,7 @@ impl Policy { /// which appear in the policy pub fn absolute_timelocks(&self) -> Vec { let mut ret = self.real_absolute_timelocks(); - ret.sort(); + ret.sort_unstable(); ret.dedup(); ret } @@ -597,7 +597,7 @@ impl Policy { // Not enough branches are satisfiable None } else { - sublens.sort(); + sublens.sort_unstable(); Some(sublens[0..k].iter().cloned().sum::()) } } From 17bd217697035fe183c76625f623e4995ae4bdae Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 14:09:56 +1000 Subject: [PATCH 34/35] Use find instead of chaining filter and next Clippy emits a bunch of warnings of type: warning: called `filter(..).next()` on an `Iterator`. This is more succinctly expressed by calling `.find(..)` instead As suggested, use `find` instead of chaining `filter` and `next`. --- src/psbt/finalizer.rs | 56 +++++++++++++++++-------------------------- src/psbt/mod.rs | 6 ++--- 2 files changed, 24 insertions(+), 38 deletions(-) diff --git a/src/psbt/finalizer.rs b/src/psbt/finalizer.rs index 6cc4fe8b9..faada4efb 100644 --- a/src/psbt/finalizer.rs +++ b/src/psbt/finalizer.rs @@ -148,37 +148,29 @@ fn get_descriptor(psbt: &Psbt, index: usize) -> Result, In } } else if script_pubkey.is_p2pkh() { // 2. `Pkh`: creates a `PkH` descriptor if partial_sigs has the corresponding pk - let partial_sig_contains_pk = inp - .partial_sigs - .iter() - .filter(|&(&pk, _sig)| { - // Indirect way to check the equivalence of pubkey-hashes. - // Create a pubkey hash and check if they are the same. - // THIS IS A BUG AND *WILL* PRODUCE WRONG SATISFACTIONS FOR UNCOMPRESSED KEYS - // Partial sigs loses the compressed flag that is necessary - // TODO: See https://github.com/rust-bitcoin/rust-bitcoin/pull/836 - // The type checker will fail again after we update to 0.28 and this can be removed - let addr = bitcoin::Address::p2pkh(&pk, bitcoin::Network::Bitcoin); - *script_pubkey == addr.script_pubkey() - }) - .next(); + let partial_sig_contains_pk = inp.partial_sigs.iter().find(|&(&pk, _sig)| { + // Indirect way to check the equivalence of pubkey-hashes. + // Create a pubkey hash and check if they are the same. + // THIS IS A BUG AND *WILL* PRODUCE WRONG SATISFACTIONS FOR UNCOMPRESSED KEYS + // Partial sigs loses the compressed flag that is necessary + // TODO: See https://github.com/rust-bitcoin/rust-bitcoin/pull/836 + // The type checker will fail again after we update to 0.28 and this can be removed + let addr = bitcoin::Address::p2pkh(&pk, bitcoin::Network::Bitcoin); + *script_pubkey == addr.script_pubkey() + }); match partial_sig_contains_pk { Some((pk, _sig)) => Ok(Descriptor::new_pkh(*pk)), None => Err(InputError::MissingPubkey), } } else if script_pubkey.is_v0_p2wpkh() { // 3. `Wpkh`: creates a `wpkh` descriptor if the partial sig has corresponding pk. - let partial_sig_contains_pk = inp - .partial_sigs - .iter() - .filter(|&(&pk, _sig)| { - // Indirect way to check the equivalence of pubkey-hashes. - // Create a pubkey hash and check if they are the same. - let addr = bitcoin::Address::p2wpkh(&pk, bitcoin::Network::Bitcoin) - .expect("Address corresponding to valid pubkey"); - *script_pubkey == addr.script_pubkey() - }) - .next(); + let partial_sig_contains_pk = inp.partial_sigs.iter().find(|&(&pk, _sig)| { + // Indirect way to check the equivalence of pubkey-hashes. + // Create a pubkey hash and check if they are the same. + let addr = bitcoin::Address::p2wpkh(&pk, bitcoin::Network::Bitcoin) + .expect("Address corresponding to valid pubkey"); + *script_pubkey == addr.script_pubkey() + }); match partial_sig_contains_pk { Some((pk, _sig)) => Ok(Descriptor::new_wpkh(*pk)?), None => Err(InputError::MissingPubkey), @@ -228,15 +220,11 @@ fn get_descriptor(psbt: &Psbt, index: usize) -> Result, In } } else if redeem_script.is_v0_p2wpkh() { // 6. `ShWpkh` case - let partial_sig_contains_pk = inp - .partial_sigs - .iter() - .filter(|&(&pk, _sig)| { - let addr = bitcoin::Address::p2wpkh(&pk, bitcoin::Network::Bitcoin) - .expect("Address corresponding to valid pubkey"); - *redeem_script == addr.script_pubkey() - }) - .next(); + let partial_sig_contains_pk = inp.partial_sigs.iter().find(|&(&pk, _sig)| { + let addr = bitcoin::Address::p2wpkh(&pk, bitcoin::Network::Bitcoin) + .expect("Address corresponding to valid pubkey"); + *redeem_script == addr.script_pubkey() + }); match partial_sig_contains_pk { Some((pk, _sig)) => Ok(Descriptor::new_sh_wpkh(*pk)?), None => Err(InputError::MissingPubkey), diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 77d6bfca5..64155b2d3 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -278,10 +278,9 @@ impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfie self.psbt.inputs[self.index] .tap_script_sigs .iter() - .filter(|&((pubkey, lh), _sig)| { + .find(|&((pubkey, lh), _sig)| { pubkey.to_pubkeyhash() == Pk::hash_to_hash160(&pkh.0) && *lh == pkh.1 }) - .next() .map(|((x_only_pk, _leaf_hash), sig)| (*x_only_pk, *sig)) } @@ -299,8 +298,7 @@ impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfie self.psbt.inputs[self.index] .partial_sigs .iter() - .filter(|&(pubkey, _sig)| pubkey.to_pubkeyhash() == Pk::hash_to_hash160(pkh)) - .next() + .find(|&(pubkey, _sig)| pubkey.to_pubkeyhash() == Pk::hash_to_hash160(pkh)) .map(|(pk, sig)| (*pk, *sig)) } From 7da532763924c9a0d3b5569745182e552ed14ea0 Mon Sep 17 00:00:00 2001 From: "Tobin C. Harding" Date: Mon, 2 May 2022 14:13:32 +1000 Subject: [PATCH 35/35] Use semvar-compliant version number Clippy emits: error: the since field must contain a semver-compliant version As suggested, use a semvar-compliant version number. --- src/psbt/finalizer.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/psbt/finalizer.rs b/src/psbt/finalizer.rs index faada4efb..1fe0f1273 100644 --- a/src/psbt/finalizer.rs +++ b/src/psbt/finalizer.rs @@ -320,7 +320,7 @@ fn interpreter_inp_check>( /// finalized psbt which involves checking the signatures/ preimages/timelocks. /// The functions fails it is not possible to satisfy any of the inputs non-malleably /// See [finalize_mall] if you want to allow malleable satisfactions -#[deprecated(since = "7.0", note = "Please use PsbtExt::finalize instead")] +#[deprecated(since = "7.0.0", note = "Please use PsbtExt::finalize instead")] pub fn finalize( psbt: &mut Psbt, secp: &Secp256k1,