diff --git a/bitcoind-tests/tests/setup/test_util.rs b/bitcoind-tests/tests/setup/test_util.rs index 3b77047a0..c49b07741 100644 --- a/bitcoind-tests/tests/setup/test_util.rs +++ b/bitcoind-tests/tests/setup/test_util.rs @@ -108,14 +108,7 @@ impl TestData { let ripemd160_pre = [0x78 as u8; 32]; let ripemd160 = ripemd160::Hash::hash(&ripemd160_pre); - let pubdata = PubData { - pks, - sha256, - hash256, - ripemd160, - hash160, - x_only_pks, - }; + let pubdata = PubData { pks, sha256, hash256, ripemd160, hash160, x_only_pks }; let secretdata = SecretData { sks, sha256_pre, @@ -124,10 +117,7 @@ impl TestData { hash160_pre, x_only_keypairs, }; - Self { - pubdata, - secretdata, - } + Self { pubdata, secretdata } } } @@ -287,43 +277,20 @@ pub fn parse_test_desc( // substitute hash fragments in the string as the per rules fn subs_hash_frag(ms: &str, pubdata: &PubData) -> String { - let ms = ms.replace( - "sha256(H)", - &format!("sha256({})", &pubdata.sha256.to_string()), - ); - let ms = ms.replace( - "hash256(H)", - &format!("hash256({})", &pubdata.hash256.to_string()), - ); - let ms = ms.replace( - "ripemd160(H)", - &format!("ripemd160({})", &pubdata.ripemd160.to_string()), - ); - let ms = ms.replace( - "hash160(H)", - &format!("hash160({})", &pubdata.hash160.to_string()), - ); + let ms = ms.replace("sha256(H)", &format!("sha256({})", &pubdata.sha256.to_string())); + let ms = ms.replace("hash256(H)", &format!("hash256({})", &pubdata.hash256.to_string())); + let ms = ms.replace("ripemd160(H)", &format!("ripemd160({})", &pubdata.ripemd160.to_string())); + let ms = ms.replace("hash160(H)", &format!("hash160({})", &pubdata.hash160.to_string())); let mut rand_hash32 = [0u8; 32]; rand::thread_rng().fill_bytes(&mut rand_hash32); let mut rand_hash20 = [0u8; 20]; rand::thread_rng().fill_bytes(&mut rand_hash20); - let ms = ms.replace( - "sha256(H!)", - &format!("sha256({})", rand_hash32.to_lower_hex_string()), - ); - let ms = ms.replace( - "hash256(H!)", - &format!("hash256({})", rand_hash32.to_lower_hex_string()), - ); - let ms = ms.replace( - "ripemd160(H!)", - &format!("ripemd160({})", rand_hash20.to_lower_hex_string()), - ); - let ms = ms.replace( - "hash160(H!)", - &format!("hash160({})", rand_hash20.to_lower_hex_string()), - ); + let ms = ms.replace("sha256(H!)", &format!("sha256({})", rand_hash32.to_lower_hex_string())); + let ms = ms.replace("hash256(H!)", &format!("hash256({})", rand_hash32.to_lower_hex_string())); + let ms = + ms.replace("ripemd160(H!)", &format!("ripemd160({})", rand_hash20.to_lower_hex_string())); + let ms = ms.replace("hash160(H!)", &format!("hash160({})", rand_hash20.to_lower_hex_string())); ms } diff --git a/bitcoind-tests/tests/test_cpp.rs b/bitcoind-tests/tests/test_cpp.rs index 27adc0d4e..6ac0e1610 100644 --- a/bitcoind-tests/tests/test_cpp.rs +++ b/bitcoind-tests/tests/test_cpp.rs @@ -44,9 +44,7 @@ where } /// Quickly create a BTC amount. -fn btc>(btc: F) -> Amount { - Amount::from_btc(btc.into()).unwrap() -} +fn btc>(btc: F) -> Amount { Amount::from_btc(btc.into()).unwrap() } // Find the Outpoint by value. // Ideally, we should find by scriptPubkey, but this @@ -72,10 +70,7 @@ pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) { let pks = &testdata.pubdata.pks; // Generate some blocks let blocks = cl - .generate_to_address( - 500, - &cl.get_new_address(None, None).unwrap().assume_checked(), - ) + .generate_to_address(500, &cl.get_new_address(None, None).unwrap().assume_checked()) .unwrap(); assert_eq!(blocks.len(), 500); @@ -98,10 +93,7 @@ pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) { } // Wait for the funds to mature. let blocks = cl - .generate_to_address( - 50, - &cl.get_new_address(None, None).unwrap().assume_checked(), - ) + .generate_to_address(50, &cl.get_new_address(None, None).unwrap().assume_checked()) .unwrap(); assert_eq!(blocks.len(), 50); // Create a PSBT for each transaction. @@ -140,10 +132,9 @@ pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) { .get_new_address(None, Some(json::AddressType::Bech32)) .unwrap() .assume_checked(); - psbt.unsigned_tx.output.push(TxOut { - value: 99_999_000, - script_pubkey: addr.script_pubkey(), - }); + psbt.unsigned_tx + .output + .push(TxOut { value: 99_999_000, script_pubkey: addr.script_pubkey() }); let mut input = psbt::Input::default(); input.witness_utxo = Some(witness_utxo); input.witness_script = Some(desc.explicit_script().unwrap()); @@ -187,32 +178,25 @@ pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) { for sk in sks_reqd { let sig = secp.sign_ecdsa(&msg, &sk); let pk = pks[sks.iter().position(|&x| x == sk).unwrap()]; - psbts[i].inputs[0].partial_sigs.insert( - pk, - bitcoin::ecdsa::Signature { - sig, - hash_ty: sighash_ty, - }, - ); + psbts[i].inputs[0] + .partial_sigs + .insert(pk, bitcoin::ecdsa::Signature { sig, hash_ty: sighash_ty }); } // Add the hash preimages to the psbt - psbts[i].inputs[0].sha256_preimages.insert( - testdata.pubdata.sha256, - testdata.secretdata.sha256_pre.to_vec(), - ); + psbts[i].inputs[0] + .sha256_preimages + .insert(testdata.pubdata.sha256, testdata.secretdata.sha256_pre.to_vec()); psbts[i].inputs[0].hash256_preimages.insert( sha256d::Hash::from_byte_array(testdata.pubdata.hash256.to_byte_array()), testdata.secretdata.hash256_pre.to_vec(), ); println!("{}", ms); - psbts[i].inputs[0].hash160_preimages.insert( - testdata.pubdata.hash160, - testdata.secretdata.hash160_pre.to_vec(), - ); - psbts[i].inputs[0].ripemd160_preimages.insert( - testdata.pubdata.ripemd160, - testdata.secretdata.ripemd160_pre.to_vec(), - ); + psbts[i].inputs[0] + .hash160_preimages + .insert(testdata.pubdata.hash160, testdata.secretdata.hash160_pre.to_vec()); + psbts[i].inputs[0] + .ripemd160_preimages + .insert(testdata.pubdata.ripemd160, testdata.secretdata.ripemd160_pre.to_vec()); // Finalize the transaction using psbt // Let miniscript do it's magic! if let Err(e) = psbts[i].finalize_mall_mut(&secp) { @@ -232,10 +216,7 @@ pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) { } // Finally mine the blocks and await confirmations let _blocks = cl - .generate_to_address( - 10, - &cl.get_new_address(None, None).unwrap().assume_checked(), - ) + .generate_to_address(10, &cl.get_new_address(None, None).unwrap().assume_checked()) .unwrap(); // Get the required transactions from the node mined in the blocks. for txid in spend_txids { @@ -247,9 +228,7 @@ pub fn test_from_cpp_ms(cl: &Client, testdata: &TestData) { } #[test] -fn test_setup() { - setup::setup(); -} +fn test_setup() { setup::setup(); } #[test] fn tests_from_cpp() { diff --git a/bitcoind-tests/tests/test_desc.rs b/bitcoind-tests/tests/test_desc.rs index 06c8e8f82..bbb2b1bf2 100644 --- a/bitcoind-tests/tests/test_desc.rs +++ b/bitcoind-tests/tests/test_desc.rs @@ -25,9 +25,7 @@ mod setup; use rand::RngCore; use setup::test_util::{self, TestData}; /// Quickly create a BTC amount. -fn btc>(btc: F) -> Amount { - Amount::from_btc(btc.into()).unwrap() -} +fn btc>(btc: F) -> Amount { Amount::from_btc(btc.into()).unwrap() } // Find the Outpoint by spk fn get_vout(cl: &Client, txid: Txid, value: u64, spk: ScriptBuf) -> (OutPoint, TxOut) { @@ -137,10 +135,9 @@ pub fn test_desc_satisfy( .assume_checked(); // Had to decrease 'value', so that fees can be increased // (Was getting insufficient fees error, for deep script trees) - psbt.unsigned_tx.output.push(TxOut { - value: 99_997_000, - script_pubkey: addr.script_pubkey(), - }); + psbt.unsigned_tx + .output + .push(TxOut { value: 99_997_000, script_pubkey: addr.script_pubkey() }); let mut input = psbt::Input::default(); input .update_with_descriptor_unchecked(&definite_desc) @@ -180,10 +177,8 @@ pub fn test_desc_satisfy( rand::thread_rng().fill_bytes(&mut aux_rand); let schnorr_sig = secp.sign_schnorr_with_aux_rand(&msg, &internal_keypair, &aux_rand); - psbt.inputs[0].tap_key_sig = Some(taproot::Signature { - sig: schnorr_sig, - hash_ty: hash_ty, - }); + psbt.inputs[0].tap_key_sig = + Some(taproot::Signature { sig: schnorr_sig, hash_ty: hash_ty }); } else { // No internal key } @@ -208,13 +203,9 @@ pub fn test_desc_satisfy( let sig = secp.sign_schnorr_with_aux_rand(&msg, &keypair, &aux_rand); let x_only_pk = x_only_pks[xonly_keypairs.iter().position(|&x| x == keypair).unwrap()]; - psbt.inputs[0].tap_script_sigs.insert( - (x_only_pk, leaf_hash), - taproot::Signature { - sig, - hash_ty: hash_ty, - }, - ); + psbt.inputs[0] + .tap_script_sigs + .insert((x_only_pk, leaf_hash), taproot::Signature { sig, hash_ty: hash_ty }); } } _ => { @@ -263,33 +254,26 @@ pub fn test_desc_satisfy( let sig = secp.sign_ecdsa(&msg, &sk); let pk = pks[sks.iter().position(|&x| x == sk).unwrap()]; assert!(secp.verify_ecdsa(&msg, &sig, &pk.inner).is_ok()); - psbt.inputs[0].partial_sigs.insert( - pk, - ecdsa::Signature { - sig, - hash_ty: hash_ty, - }, - ); + psbt.inputs[0] + .partial_sigs + .insert(pk, ecdsa::Signature { sig, hash_ty: hash_ty }); } } } // Add the hash preimages to the psbt - psbt.inputs[0].sha256_preimages.insert( - testdata.pubdata.sha256, - testdata.secretdata.sha256_pre.to_vec(), - ); + psbt.inputs[0] + .sha256_preimages + .insert(testdata.pubdata.sha256, testdata.secretdata.sha256_pre.to_vec()); psbt.inputs[0].hash256_preimages.insert( sha256d::Hash::from_byte_array(testdata.pubdata.hash256.to_byte_array()), testdata.secretdata.hash256_pre.to_vec(), ); - psbt.inputs[0].hash160_preimages.insert( - testdata.pubdata.hash160, - testdata.secretdata.hash160_pre.to_vec(), - ); - psbt.inputs[0].ripemd160_preimages.insert( - testdata.pubdata.ripemd160, - testdata.secretdata.ripemd160_pre.to_vec(), - ); + psbt.inputs[0] + .hash160_preimages + .insert(testdata.pubdata.hash160, testdata.secretdata.hash160_pre.to_vec()); + psbt.inputs[0] + .ripemd160_preimages + .insert(testdata.pubdata.ripemd160, testdata.secretdata.ripemd160_pre.to_vec()); println!("Testing descriptor: {}", definite_desc); // Finalize the transaction using psbt // Let miniscript do it's magic! diff --git a/examples/psbt_sign_finalize.rs b/examples/psbt_sign_finalize.rs index ab05401b8..08abd5abe 100644 --- a/examples/psbt_sign_finalize.rs +++ b/examples/psbt_sign_finalize.rs @@ -21,14 +21,8 @@ fn main() { let bridge_descriptor = Descriptor::from_str(&s).unwrap(); //let bridge_descriptor = Descriptor::::from_str(&s).expect("parse descriptor string"); assert!(bridge_descriptor.sanity_check().is_ok()); - println!( - "Bridge pubkey script: {}", - bridge_descriptor.script_pubkey() - ); - println!( - "Bridge address: {}", - bridge_descriptor.address(Network::Regtest).unwrap() - ); + println!("Bridge pubkey script: {}", bridge_descriptor.script_pubkey()); + println!("Bridge address: {}", bridge_descriptor.address(Network::Regtest).unwrap()); println!( "Weight for witness satisfaction cost {}", bridge_descriptor.max_weight_to_satisfy().unwrap() @@ -37,37 +31,25 @@ fn main() { let master_private_key_str = "cQhdvB3McbBJdx78VSSumqoHQiSXs75qwLptqwxSQBNBMDxafvaw"; let _master_private_key = PrivateKey::from_str(master_private_key_str).expect("Can't create private key"); - println!( - "Master public key: {}", - _master_private_key.public_key(&secp256k1) - ); + println!("Master public key: {}", _master_private_key.public_key(&secp256k1)); let backup1_private_key_str = "cWA34TkfWyHa3d4Vb2jNQvsWJGAHdCTNH73Rht7kAz6vQJcassky"; let backup1_private = PrivateKey::from_str(backup1_private_key_str).expect("Can't create private key"); - println!( - "Backup1 public key: {}", - backup1_private.public_key(&secp256k1) - ); + println!("Backup1 public key: {}", backup1_private.public_key(&secp256k1)); let backup2_private_key_str = "cPJFWUKk8sdL7pcDKrmNiWUyqgovimmhaaZ8WwsByDaJ45qLREkh"; let backup2_private = PrivateKey::from_str(backup2_private_key_str).expect("Can't create private key"); - println!( - "Backup2 public key: {}", - backup2_private.public_key(&secp256k1) - ); + println!("Backup2 public key: {}", backup2_private.public_key(&secp256k1)); let backup3_private_key_str = "cT5cH9UVm81W5QAf5KABXb23RKNSMbMzMx85y6R2mF42L94YwKX6"; let _backup3_private = PrivateKey::from_str(backup3_private_key_str).expect("Can't create private key"); - println!( - "Backup3 public key: {}", - _backup3_private.public_key(&secp256k1) - ); + println!("Backup3 public key: {}", _backup3_private.public_key(&secp256k1)); let spend_tx = Transaction { version: 2, @@ -104,15 +86,13 @@ fn main() { txin.sequence = Sequence::from_height(26); //Sequence::MAX; // psbt.unsigned_tx.input.push(txin); - psbt.unsigned_tx.output.push(TxOut { - script_pubkey: receiver.script_pubkey(), - value: amount / 5 - 500, - }); + psbt.unsigned_tx + .output + .push(TxOut { script_pubkey: receiver.script_pubkey(), value: amount / 5 - 500 }); - psbt.unsigned_tx.output.push(TxOut { - script_pubkey: bridge_descriptor.script_pubkey(), - value: amount * 4 / 5, - }); + psbt.unsigned_tx + .output + .push(TxOut { script_pubkey: bridge_descriptor.script_pubkey(), value: amount * 4 / 5 }); // Generating signatures & witness data @@ -148,13 +128,9 @@ fn main() { let pk2 = backup2_private.public_key(&secp256k1); assert!(secp256k1.verify_ecdsa(&msg, &sig2, &pk2.inner).is_ok()); - psbt.inputs[0].partial_sigs.insert( - pk1, - bitcoin::ecdsa::Signature { - sig: sig1, - hash_ty: hash_ty, - }, - ); + psbt.inputs[0] + .partial_sigs + .insert(pk1, bitcoin::ecdsa::Signature { sig: sig1, hash_ty: hash_ty }); println!("{:#?}", psbt); diff --git a/examples/taproot.rs b/examples/taproot.rs index f0abd7885..3482d3ddb 100644 --- a/examples/taproot.rs +++ b/examples/taproot.rs @@ -74,10 +74,7 @@ fn main() { ); assert_eq!( iter.next().unwrap(), - ( - 1u8, - &Miniscript::::from_str("multi_a(2,hA,S)").unwrap() - ) + (1u8, &Miniscript::::from_str("multi_a(2,hA,S)").unwrap()) ); assert_eq!(iter.next(), None); } diff --git a/rustfmt.toml b/rustfmt.toml index b2a63aa46..88289b24b 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -4,9 +4,9 @@ tab_spaces = 4 newline_style = "Auto" indent_style = "Block" use_small_heuristics = "Default" -fn_call_width = 60 +fn_call_width = 80 attr_fn_like_width = 70 -struct_lit_width = 18 +struct_lit_width = 80 struct_variant_width = 35 array_width = 60 chain_width = 60 @@ -22,7 +22,7 @@ format_macro_bodies = true hex_literal_case = "Preserve" empty_item_single_line = true struct_lit_single_line = true -fn_single_line = false +fn_single_line = true where_single_line = false imports_indent = "Block" imports_layout = "Mixed" diff --git a/src/descriptor/bare.rs b/src/descriptor/bare.rs index 1a54df64f..c4ca14b14 100644 --- a/src/descriptor/bare.rs +++ b/src/descriptor/bare.rs @@ -43,14 +43,10 @@ impl Bare { } /// get the inner - pub fn into_inner(self) -> Miniscript { - self.ms - } + pub fn into_inner(self) -> Miniscript { self.ms } /// get the inner - pub fn as_inner(&self) -> &Miniscript { - &self.ms - } + pub fn as_inner(&self) -> &Miniscript { &self.ms } /// Checks whether the descriptor is safe. pub fn sanity_check(&self) -> Result<(), Error> { @@ -96,19 +92,13 @@ impl Bare { impl Bare { /// Obtains the corresponding script pubkey for this descriptor. - pub fn script_pubkey(&self) -> ScriptBuf { - self.ms.encode() - } + pub fn script_pubkey(&self) -> ScriptBuf { self.ms.encode() } /// Obtains the underlying miniscript for this descriptor. - pub fn inner_script(&self) -> ScriptBuf { - self.script_pubkey() - } + pub fn inner_script(&self) -> ScriptBuf { self.script_pubkey() } /// Obtains the pre bip-340 signature script code for this descriptor. - pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { - self.script_pubkey() - } + pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { self.script_pubkey() } /// Returns satisfying non-malleable witness and scriptSig with minimum /// weight to spend an output controlled by the given descriptor if it is @@ -162,9 +152,7 @@ impl Bare { } impl fmt::Debug for Bare { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}", self.ms) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.ms) } } impl fmt::Display for Bare { @@ -177,9 +165,7 @@ impl fmt::Display for Bare { } impl Liftable for Bare { - fn lift(&self) -> Result, Error> { - self.ms.lift() - } + fn lift(&self) -> Result, Error> { self.ms.lift() } } impl_from_tree!( @@ -240,14 +226,10 @@ impl Pkh { } /// Get a reference to the inner key - pub fn as_inner(&self) -> &Pk { - &self.pk - } + pub fn as_inner(&self) -> &Pk { &self.pk } /// Get the inner key - pub fn into_inner(self) -> Pk { - self.pk - } + pub fn into_inner(self) -> Pk { self.pk } /// Computes an upper bound on the difference between a non-satisfied /// `TxIn`'s `segwit_weight` and a satisfied `TxIn`'s `segwit_weight` @@ -276,9 +258,7 @@ impl Pkh { /// Assumes all ec-signatures are 73 bytes, including push opcode and /// sighash suffix. Includes the weight of the VarInts encoding the /// scriptSig and witness stack length. - pub fn max_satisfaction_weight(&self) -> usize { - 4 * (1 + 73 + BareCtx::pk_len(&self.pk)) - } + pub fn max_satisfaction_weight(&self) -> usize { 4 * (1 + 73 + BareCtx::pk_len(&self.pk)) } } impl Pkh { @@ -296,14 +276,10 @@ impl Pkh { } /// Obtains the underlying miniscript for this descriptor. - pub fn inner_script(&self) -> ScriptBuf { - self.script_pubkey() - } + pub fn inner_script(&self) -> ScriptBuf { self.script_pubkey() } /// Obtains the pre bip-340 signature script code for this descriptor. - pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { - self.script_pubkey() - } + pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { self.script_pubkey() } /// Returns satisfying non-malleable witness and scriptSig with minimum /// weight to spend an output controlled by the given descriptor if it is @@ -357,12 +333,7 @@ impl Pkh { Witness::Unavailable }; - Satisfaction { - stack, - has_sig: true, - relative_timelock: None, - absolute_timelock: None, - } + Satisfaction { stack, has_sig: true, relative_timelock: None, absolute_timelock: None } } /// Returns a plan if the provided assets are sufficient to produce a malleable satisfaction @@ -378,9 +349,7 @@ impl Pkh { } impl fmt::Debug for Pkh { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "pkh({:?})", self.pk) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "pkh({:?})", self.pk) } } impl fmt::Display for Pkh { @@ -402,9 +371,7 @@ impl_from_tree!( Pkh, fn from_tree(top: &expression::Tree) -> Result { if top.name == "pkh" && top.args.len() == 1 { - Ok(Pkh::new(expression::terminal(&top.args[0], |pk| { - Pk::from_str(pk) - })?)?) + Ok(Pkh::new(expression::terminal(&top.args[0], |pk| Pk::from_str(pk))?)?) } else { Err(Error::Unexpected(format!( "{}({} args) while parsing pkh descriptor", @@ -426,9 +393,7 @@ impl_from_str!( ); impl ForEachKey for Pkh { - fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { - pred(&self.pk) - } + fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { pred(&self.pk) } } impl TranslatePk for Pkh

diff --git a/src/descriptor/checksum.rs b/src/descriptor/checksum.rs index 10aaaacfc..08d16f948 100644 --- a/src/descriptor/checksum.rs +++ b/src/descriptor/checksum.rs @@ -80,20 +80,12 @@ pub struct Engine { } impl Default for Engine { - fn default() -> Engine { - Engine::new() - } + fn default() -> Engine { Engine::new() } } impl Engine { /// Construct an engine with no input - pub fn new() -> Self { - Engine { - c: 1, - cls: 0, - clscount: 0, - } - } + pub fn new() -> Self { Engine { c: 1, cls: 0, clscount: 0 } } /// Checksum some data /// @@ -150,12 +142,7 @@ pub struct Formatter<'f, 'a> { impl<'f, 'a> Formatter<'f, 'a> { /// Contruct a new `Formatter`, wrapping a given `fmt::Formatter` - pub fn new(f: &'f mut fmt::Formatter<'a>) -> Self { - Formatter { - fmt: f, - eng: Engine::new(), - } - } + pub fn new(f: &'f mut fmt::Formatter<'a>) -> Self { Formatter { fmt: f, eng: Engine::new() } } /// Writes the checksum into the underlying `fmt::Formatter` pub fn write_checksum(&mut self) -> fmt::Result { @@ -229,10 +216,7 @@ mod test { assert_eq!( desc_checksum(&invalid_desc).err().unwrap().to_string(), - format!( - "Invalid descriptor: Invalid character in checksum: '{}'", - sparkle_heart - ) + format!("Invalid descriptor: Invalid character in checksum: '{}'", sparkle_heart) ); } } diff --git a/src/descriptor/key.rs b/src/descriptor/key.rs index f39c5f05f..cd4c828e8 100644 --- a/src/descriptor/key.rs +++ b/src/descriptor/key.rs @@ -86,14 +86,10 @@ impl DerivPaths { } /// Get the list of derivation paths. - pub fn paths(&self) -> &Vec { - &self.0 - } + pub fn paths(&self) -> &Vec { &self.0 } /// Get the list of derivation paths. - pub fn into_paths(self) -> Vec { - self.0 - } + pub fn into_paths(self) -> Vec { self.0 } } /// Instance of one or more extended keys, as specified in BIP 389. @@ -173,9 +169,7 @@ impl InnerXKey for bip32::ExtendedPubKey { self.fingerprint() } - fn can_derive_hardened() -> bool { - false - } + fn can_derive_hardened() -> bool { false } } impl InnerXKey for bip32::ExtendedPrivKey { @@ -183,9 +177,7 @@ impl InnerXKey for bip32::ExtendedPrivKey { self.fingerprint(secp) } - fn can_derive_hardened() -> bool { - true - } + fn can_derive_hardened() -> bool { true } } /// Whether a descriptor has a wildcard in it @@ -204,10 +196,7 @@ impl SinglePriv { fn to_public(&self, secp: &Secp256k1) -> SinglePub { let pub_key = self.key.public_key(secp); - SinglePub { - origin: self.origin.clone(), - key: SinglePubKey::FullKey(pub_key), - } + SinglePub { origin: self.origin.clone(), key: SinglePubKey::FullKey(pub_key) } } } @@ -271,16 +260,12 @@ impl DescriptorXKey { pub struct DescriptorKeyParseError(&'static str); impl fmt::Display for DescriptorKeyParseError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - f.write_str(self.0) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.0) } } #[cfg(feature = "std")] impl error::Error for DescriptorKeyParseError { - fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - None - } + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { None } } impl fmt::Display for DescriptorPublicKey { @@ -363,12 +348,7 @@ impl DescriptorSecretKey { match self { DescriptorSecretKey::Single(..) | DescriptorSecretKey::XPrv(..) => vec![self], DescriptorSecretKey::MultiXPrv(xpub) => { - let DescriptorMultiXKey { - origin, - xkey, - derivation_paths, - wildcard, - } = xpub; + let DescriptorMultiXKey { origin, xkey, derivation_paths, wildcard } = xpub; derivation_paths .into_paths() .into_iter() @@ -621,9 +601,7 @@ impl DescriptorPublicKey { /// Whether or not the key has a wildcard #[deprecated(note = "use has_wildcard instead")] - pub fn is_deriveable(&self) -> bool { - self.has_wildcard() - } + pub fn is_deriveable(&self) -> bool { self.has_wildcard() } /// Whether or not the key has a wildcard pub fn has_wildcard(&self) -> bool { @@ -700,12 +678,7 @@ impl DescriptorPublicKey { match self { DescriptorPublicKey::Single(..) | DescriptorPublicKey::XPub(..) => vec![self], DescriptorPublicKey::MultiXPub(xpub) => { - let DescriptorMultiXKey { - origin, - xkey, - derivation_paths, - wildcard, - } = xpub; + let DescriptorMultiXKey { origin, xkey, derivation_paths, wildcard } = xpub; derivation_paths .into_paths() .into_iter() @@ -732,10 +705,7 @@ impl FromStr for DescriptorSecretKey { if key_part.len() <= 52 { let sk = bitcoin::PrivateKey::from_str(key_part) .map_err(|_| DescriptorKeyParseError("Error while parsing a WIF private key"))?; - Ok(DescriptorSecretKey::Single(SinglePriv { - key: sk, - origin: None, - })) + Ok(DescriptorSecretKey::Single(SinglePriv { key: sk, origin: None })) } else { let (xpriv, derivation_paths, wildcard) = parse_xkey_deriv::(key_part)?; @@ -762,9 +732,7 @@ impl FromStr for DescriptorSecretKey { fn parse_key_origin(s: &str) -> Result<(&str, Option), DescriptorKeyParseError> { for ch in s.as_bytes() { if *ch < 20 || *ch > 127 { - return Err(DescriptorKeyParseError( - "Encountered an unprintable character", - )); + return Err(DescriptorKeyParseError("Encountered an unprintable character")); } } @@ -779,14 +747,12 @@ fn parse_key_origin(s: &str) -> Result<(&str, Option), Descrip .ok_or(DescriptorKeyParseError("Unclosed '['"))? .split('/'); - let origin_id_hex = raw_origin.next().ok_or(DescriptorKeyParseError( - "No master fingerprint found after '['", - ))?; + let origin_id_hex = raw_origin + .next() + .ok_or(DescriptorKeyParseError("No master fingerprint found after '['"))?; if origin_id_hex.len() != 8 { - return Err(DescriptorKeyParseError( - "Master fingerprint should be 8 characters long", - )); + return Err(DescriptorKeyParseError("Master fingerprint should be 8 characters long")); } let parent_fingerprint = bip32::Fingerprint::from_hex(origin_id_hex).map_err(|_| { DescriptorKeyParseError("Malformed master fingerprint, expected 8 hex chars") @@ -801,9 +767,7 @@ fn parse_key_origin(s: &str) -> Result<(&str, Option), Descrip .ok_or(DescriptorKeyParseError("No key after origin."))?; if parts.next().is_some() { - Err(DescriptorKeyParseError( - "Multiple ']' in Descriptor Public Key", - )) + Err(DescriptorKeyParseError("Multiple ']' in Descriptor Public Key")) } else { Ok((key, Some((parent_fingerprint, origin_path)))) } @@ -817,9 +781,9 @@ fn parse_xkey_deriv( key_deriv: &str, ) -> Result<(K, Vec, Wildcard), DescriptorKeyParseError> { let mut key_deriv = key_deriv.split('/'); - let xkey_str = key_deriv.next().ok_or(DescriptorKeyParseError( - "No key found after origin description", - ))?; + let xkey_str = key_deriv + .next() + .ok_or(DescriptorKeyParseError("No key found after origin description"))?; let xkey = K::from_str(xkey_str).map_err(|_| DescriptorKeyParseError("Error while parsing xkey."))?; @@ -1018,8 +982,7 @@ impl MiniscriptKey for DescriptorPublicKey { fn is_uncompressed(&self) -> bool { match self { DescriptorPublicKey::Single(SinglePub { - key: SinglePubKey::FullKey(ref key), - .. + key: SinglePubKey::FullKey(ref key), .. }) => key.is_uncompressed(), _ => false, } @@ -1028,10 +991,7 @@ impl MiniscriptKey for DescriptorPublicKey { fn is_x_only_key(&self) -> bool { matches!( self, - DescriptorPublicKey::Single(SinglePub { - key: SinglePubKey::XOnly(ref _key), - .. - }) + DescriptorPublicKey::Single(SinglePub { key: SinglePubKey::XOnly(ref _key), .. }) ) } @@ -1093,9 +1053,7 @@ impl DefiniteDescriptorKey { } /// The fingerprint of the master key associated with this key, `0x00000000` if none. - pub fn master_fingerprint(&self) -> bip32::Fingerprint { - self.0.master_fingerprint() - } + pub fn master_fingerprint(&self) -> bip32::Fingerprint { self.0.master_fingerprint() } /// Full path from the master key if not a multipath extended key. pub fn full_derivation_path(&self) -> Option { @@ -1109,14 +1067,10 @@ impl DefiniteDescriptorKey { } /// Reference to the underlying `DescriptorPublicKey` - pub fn as_descriptor_public_key(&self) -> &DescriptorPublicKey { - &self.0 - } + pub fn as_descriptor_public_key(&self) -> &DescriptorPublicKey { &self.0 } /// Converts the definite key into a generic one - pub fn into_descriptor_public_key(self) -> DescriptorPublicKey { - self.0 - } + pub fn into_descriptor_public_key(self) -> DescriptorPublicKey { self.0 } } impl FromStr for DefiniteDescriptorKey { @@ -1131,9 +1085,7 @@ impl FromStr for DefiniteDescriptorKey { } impl fmt::Display for DefiniteDescriptorKey { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.0.fmt(f) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } impl MiniscriptKey for DefiniteDescriptorKey { @@ -1142,17 +1094,11 @@ impl MiniscriptKey for DefiniteDescriptorKey { type Ripemd160 = ripemd160::Hash; type Hash160 = hash160::Hash; - fn is_uncompressed(&self) -> bool { - self.0.is_uncompressed() - } + fn is_uncompressed(&self) -> bool { self.0.is_uncompressed() } - fn is_x_only_key(&self) -> bool { - self.0.is_x_only_key() - } + fn is_x_only_key(&self) -> bool { self.0.is_x_only_key() } - fn num_der_paths(&self) -> usize { - self.0.num_der_paths() - } + fn num_der_paths(&self) -> usize { self.0.num_der_paths() } } impl ToPublicKey for DefiniteDescriptorKey { @@ -1161,33 +1107,21 @@ impl ToPublicKey for DefiniteDescriptorKey { self.derive_public_key(&secp).unwrap() } - fn to_sha256(hash: &sha256::Hash) -> sha256::Hash { - *hash - } + fn to_sha256(hash: &sha256::Hash) -> sha256::Hash { *hash } - fn to_hash256(hash: &hash256::Hash) -> hash256::Hash { - *hash - } + fn to_hash256(hash: &hash256::Hash) -> hash256::Hash { *hash } - fn to_ripemd160(hash: &ripemd160::Hash) -> ripemd160::Hash { - *hash - } + fn to_ripemd160(hash: &ripemd160::Hash) -> ripemd160::Hash { *hash } - fn to_hash160(hash: &hash160::Hash) -> hash160::Hash { - *hash - } + fn to_hash160(hash: &hash160::Hash) -> hash160::Hash { *hash } } impl From for DescriptorPublicKey { - fn from(d: DefiniteDescriptorKey) -> Self { - d.0 - } + fn from(d: DefiniteDescriptorKey) -> Self { d.0 } } impl Borrow for DefiniteDescriptorKey { - fn borrow(&self) -> &DescriptorPublicKey { - &self.0 - } + fn borrow(&self) -> &DescriptorPublicKey { &self.0 } } #[cfg(feature = "serde")] @@ -1240,9 +1174,7 @@ mod test { let desc = "[NonHexor]xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL/1/*"; assert_eq!( DescriptorPublicKey::from_str(desc), - Err(DescriptorKeyParseError( - "Malformed master fingerprint, expected 8 hex chars" - )) + Err(DescriptorKeyParseError("Malformed master fingerprint, expected 8 hex chars")) ); // And ones with invalid xpubs.. @@ -1256,36 +1188,28 @@ mod test { let desc = "[78412e3a]0208a117f3897c3a13c9384b8695eed98dc31bc2500feb19a1af424cd47a5d83/1/*"; assert_eq!( DescriptorPublicKey::from_str(desc), - Err(DescriptorKeyParseError( - "Public keys must be 64/66/130 characters in size" - )) + Err(DescriptorKeyParseError("Public keys must be 64/66/130 characters in size")) ); // ..or invalid separators let desc = "[78412e3a]]03f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8"; assert_eq!( DescriptorPublicKey::from_str(desc), - Err(DescriptorKeyParseError( - "Multiple \']\' in Descriptor Public Key" - )) + Err(DescriptorKeyParseError("Multiple \']\' in Descriptor Public Key")) ); // fuzzer errors let desc = "[11111f11]033333333333333333333333333333323333333333333333333333333433333333]]333]]3]]101333333333333433333]]]10]333333mmmm"; assert_eq!( DescriptorPublicKey::from_str(desc), - Err(DescriptorKeyParseError( - "Multiple \']\' in Descriptor Public Key" - )) + Err(DescriptorKeyParseError("Multiple \']\' in Descriptor Public Key")) ); // fuzz failure, hybrid keys let desc = "0777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777"; assert_eq!( DescriptorPublicKey::from_str(desc), - Err(DescriptorKeyParseError( - "Only publickeys with prefixes 02/03/04 are allowed" - )) + Err(DescriptorKeyParseError("Only publickeys with prefixes 02/03/04 are allowed")) ); } @@ -1302,18 +1226,14 @@ mod test { let desc = "[NonHexor]tprv8ZgxMBicQKsPcwcD4gSnMti126ZiETsuX7qwrtMypr6FBwAP65puFn4v6c3jrN9VwtMRMph6nyT63NrfUL4C3nBzPcduzVSuHD7zbX2JKVc/1/*"; assert_eq!( DescriptorSecretKey::from_str(desc), - Err(DescriptorKeyParseError( - "Malformed master fingerprint, expected 8 hex chars" - )) + Err(DescriptorKeyParseError("Malformed master fingerprint, expected 8 hex chars")) ); // ..or invalid raw keys let desc = "[78412e3a]L32jTfVLei6BYTPUpwpJSkrHx8iL9GZzeErVS8y4Y/1/*"; assert_eq!( DescriptorSecretKey::from_str(desc), - Err(DescriptorKeyParseError( - "Error while parsing a WIF private key" - )) + Err(DescriptorKeyParseError("Error while parsing a WIF private key")) ); } @@ -1321,26 +1241,17 @@ mod test { fn test_wildcard() { let public_key = DescriptorPublicKey::from_str("[abcdef00/0'/1']tpubDBrgjcxBxnXyL575sHdkpKohWu5qHKoQ7TJXKNrYznh5fVEGBv89hA8ENW7A8MFVpFUSvgLqc4Nj1WZcpePX6rrxviVtPowvMuGF5rdT2Vi/2").unwrap(); assert_eq!(public_key.master_fingerprint().to_string(), "abcdef00"); - assert_eq!( - public_key.full_derivation_path().unwrap().to_string(), - "m/0'/1'/2" - ); + assert_eq!(public_key.full_derivation_path().unwrap().to_string(), "m/0'/1'/2"); assert!(!public_key.has_wildcard()); let public_key = DescriptorPublicKey::from_str("[abcdef00/0'/1']tpubDBrgjcxBxnXyL575sHdkpKohWu5qHKoQ7TJXKNrYznh5fVEGBv89hA8ENW7A8MFVpFUSvgLqc4Nj1WZcpePX6rrxviVtPowvMuGF5rdT2Vi/*").unwrap(); assert_eq!(public_key.master_fingerprint().to_string(), "abcdef00"); - assert_eq!( - public_key.full_derivation_path().unwrap().to_string(), - "m/0'/1'" - ); + assert_eq!(public_key.full_derivation_path().unwrap().to_string(), "m/0'/1'"); assert!(public_key.has_wildcard()); let public_key = DescriptorPublicKey::from_str("[abcdef00/0'/1']tpubDBrgjcxBxnXyL575sHdkpKohWu5qHKoQ7TJXKNrYznh5fVEGBv89hA8ENW7A8MFVpFUSvgLqc4Nj1WZcpePX6rrxviVtPowvMuGF5rdT2Vi/*h").unwrap(); assert_eq!(public_key.master_fingerprint().to_string(), "abcdef00"); - assert_eq!( - public_key.full_derivation_path().unwrap().to_string(), - "m/0'/1'" - ); + assert_eq!(public_key.full_derivation_path().unwrap().to_string(), "m/0'/1'"); assert!(public_key.has_wildcard()); } @@ -1352,47 +1263,32 @@ mod test { let public_key = secret_key.to_public(&secp).unwrap(); assert_eq!(public_key.to_string(), "[2cbe2a6d/0'/1']tpubDBrgjcxBxnXyL575sHdkpKohWu5qHKoQ7TJXKNrYznh5fVEGBv89hA8ENW7A8MFVpFUSvgLqc4Nj1WZcpePX6rrxviVtPowvMuGF5rdT2Vi/2"); assert_eq!(public_key.master_fingerprint().to_string(), "2cbe2a6d"); - assert_eq!( - public_key.full_derivation_path().unwrap().to_string(), - "m/0'/1'/2" - ); + assert_eq!(public_key.full_derivation_path().unwrap().to_string(), "m/0'/1'/2"); assert!(!public_key.has_wildcard()); let secret_key = DescriptorSecretKey::from_str("tprv8ZgxMBicQKsPcwcD4gSnMti126ZiETsuX7qwrtMypr6FBwAP65puFn4v6c3jrN9VwtMRMph6nyT63NrfUL4C3nBzPcduzVSuHD7zbX2JKVc/0'/1'/2'").unwrap(); let public_key = secret_key.to_public(&secp).unwrap(); assert_eq!(public_key.to_string(), "[2cbe2a6d/0'/1'/2']tpubDDPuH46rv4dbFtmF6FrEtJEy1CvLZonyBoVxF6xsesHdYDdTBrq2mHhm8AbsPh39sUwL2nZyxd6vo4uWNTU9v4t893CwxjqPnwMoUACLvMV"); assert_eq!(public_key.master_fingerprint().to_string(), "2cbe2a6d"); - assert_eq!( - public_key.full_derivation_path().unwrap().to_string(), - "m/0'/1'/2'" - ); + assert_eq!(public_key.full_derivation_path().unwrap().to_string(), "m/0'/1'/2'"); let secret_key = DescriptorSecretKey::from_str("tprv8ZgxMBicQKsPcwcD4gSnMti126ZiETsuX7qwrtMypr6FBwAP65puFn4v6c3jrN9VwtMRMph6nyT63NrfUL4C3nBzPcduzVSuHD7zbX2JKVc/0/1/2").unwrap(); let public_key = secret_key.to_public(&secp).unwrap(); assert_eq!(public_key.to_string(), "tpubD6NzVbkrYhZ4WQdzxL7NmJN7b85ePo4p6RSj9QQHF7te2RR9iUeVSGgnGkoUsB9LBRosgvNbjRv9bcsJgzgBd7QKuxDm23ZewkTRzNSLEDr/0/1/2"); assert_eq!(public_key.master_fingerprint().to_string(), "2cbe2a6d"); - assert_eq!( - public_key.full_derivation_path().unwrap().to_string(), - "m/0/1/2" - ); + assert_eq!(public_key.full_derivation_path().unwrap().to_string(), "m/0/1/2"); let secret_key = DescriptorSecretKey::from_str("[aabbccdd]tprv8ZgxMBicQKsPcwcD4gSnMti126ZiETsuX7qwrtMypr6FBwAP65puFn4v6c3jrN9VwtMRMph6nyT63NrfUL4C3nBzPcduzVSuHD7zbX2JKVc/0/1/2").unwrap(); let public_key = secret_key.to_public(&secp).unwrap(); assert_eq!(public_key.to_string(), "[aabbccdd]tpubD6NzVbkrYhZ4WQdzxL7NmJN7b85ePo4p6RSj9QQHF7te2RR9iUeVSGgnGkoUsB9LBRosgvNbjRv9bcsJgzgBd7QKuxDm23ZewkTRzNSLEDr/0/1/2"); assert_eq!(public_key.master_fingerprint().to_string(), "aabbccdd"); - assert_eq!( - public_key.full_derivation_path().unwrap().to_string(), - "m/0/1/2" - ); + assert_eq!(public_key.full_derivation_path().unwrap().to_string(), "m/0/1/2"); let secret_key = DescriptorSecretKey::from_str("[aabbccdd/90']tprv8ZgxMBicQKsPcwcD4gSnMti126ZiETsuX7qwrtMypr6FBwAP65puFn4v6c3jrN9VwtMRMph6nyT63NrfUL4C3nBzPcduzVSuHD7zbX2JKVc/0'/1'/2").unwrap(); let public_key = secret_key.to_public(&secp).unwrap(); assert_eq!(public_key.to_string(), "[aabbccdd/90'/0'/1']tpubDBrgjcxBxnXyL575sHdkpKohWu5qHKoQ7TJXKNrYznh5fVEGBv89hA8ENW7A8MFVpFUSvgLqc4Nj1WZcpePX6rrxviVtPowvMuGF5rdT2Vi/2"); assert_eq!(public_key.master_fingerprint().to_string(), "aabbccdd"); - assert_eq!( - public_key.full_derivation_path().unwrap().to_string(), - "m/90'/0'/1'/2" - ); + assert_eq!(public_key.full_derivation_path().unwrap().to_string(), "m/90'/0'/1'/2"); } #[test] diff --git a/src/descriptor/mod.rs b/src/descriptor/mod.rs index 417e7d1d2..616bb37cc 100644 --- a/src/descriptor/mod.rs +++ b/src/descriptor/mod.rs @@ -79,44 +79,32 @@ pub enum Descriptor { impl From> for Descriptor { #[inline] - fn from(inner: Bare) -> Self { - Descriptor::Bare(inner) - } + fn from(inner: Bare) -> Self { Descriptor::Bare(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Pkh) -> Self { - Descriptor::Pkh(inner) - } + fn from(inner: Pkh) -> Self { Descriptor::Pkh(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Wpkh) -> Self { - Descriptor::Wpkh(inner) - } + fn from(inner: Wpkh) -> Self { Descriptor::Wpkh(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Sh) -> Self { - Descriptor::Sh(inner) - } + fn from(inner: Sh) -> Self { Descriptor::Sh(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Wsh) -> Self { - Descriptor::Wsh(inner) - } + fn from(inner: Wsh) -> Self { Descriptor::Wsh(inner) } } impl From> for Descriptor { #[inline] - fn from(inner: Tr) -> Self { - Descriptor::Tr(inner) - } + fn from(inner: Tr) -> Self { Descriptor::Tr(inner) } } /// Descriptor Type of the descriptor @@ -176,21 +164,15 @@ impl Descriptor { } /// Create a new PkH descriptor - pub fn new_pkh(pk: Pk) -> Result { - Ok(Descriptor::Pkh(Pkh::new(pk)?)) - } + pub fn new_pkh(pk: Pk) -> Result { Ok(Descriptor::Pkh(Pkh::new(pk)?)) } /// Create a new Wpkh descriptor /// Will return Err if uncompressed key is used - pub fn new_wpkh(pk: Pk) -> Result { - Ok(Descriptor::Wpkh(Wpkh::new(pk)?)) - } + pub fn new_wpkh(pk: Pk) -> Result { Ok(Descriptor::Wpkh(Wpkh::new(pk)?)) } /// Create a new sh wrapped wpkh from `Pk`. /// Errors when uncompressed keys are supplied - pub fn new_sh_wpkh(pk: Pk) -> Result { - Ok(Descriptor::Sh(Sh::new_wpkh(pk)?)) - } + pub fn new_sh_wpkh(pk: Pk) -> Result { Ok(Descriptor::Sh(Sh::new_wpkh(pk)?)) } // Miniscripts @@ -225,14 +207,10 @@ impl Descriptor { // Wrap with sh /// Create a new sh wrapper for the given wpkh descriptor - pub fn new_sh_with_wpkh(wpkh: Wpkh) -> Self { - Descriptor::Sh(Sh::new_with_wpkh(wpkh)) - } + pub fn new_sh_with_wpkh(wpkh: Wpkh) -> Self { Descriptor::Sh(Sh::new_with_wpkh(wpkh)) } /// Create a new sh wrapper for the given wsh descriptor - pub fn new_sh_with_wsh(wsh: Wsh) -> Self { - Descriptor::Sh(Sh::new_with_wsh(wsh)) - } + pub fn new_sh_with_wsh(wsh: Wsh) -> Self { Descriptor::Sh(Sh::new_with_wsh(wsh)) } // sorted multi @@ -608,14 +586,10 @@ impl ForEachKey for Descriptor { impl Descriptor { /// Whether or not the descriptor has any wildcards #[deprecated(note = "use has_wildcards instead")] - pub fn is_deriveable(&self) -> bool { - self.has_wildcard() - } + pub fn is_deriveable(&self) -> bool { self.has_wildcard() } /// Whether or not the descriptor has any wildcards i.e. `/*`. - pub fn has_wildcard(&self) -> bool { - self.for_any_key(|key| key.has_wildcard()) - } + pub fn has_wildcard(&self) -> bool { self.for_any_key(|key| key.has_wildcard()) } /// Replaces all wildcards (i.e. `/*`) in the descriptor with a particular derivation index, /// turning it into a *definite* descriptor. @@ -828,9 +802,7 @@ impl Descriptor { } /// Whether this descriptor contains a key that has multiple derivation paths. - pub fn is_multipath(&self) -> bool { - self.for_any_key(DescriptorPublicKey::is_multipath) - } + pub fn is_multipath(&self) -> bool { self.for_any_key(DescriptorPublicKey::is_multipath) } /// Get as many descriptors as different paths in this descriptor. /// @@ -1037,11 +1009,7 @@ mod tests { let output = desc.to_string(); let normalize_aliases = s.replace("c:pk_k(", "pk(").replace("c:pk_h(", "pkh("); assert_eq!( - format!( - "{}#{}", - &normalize_aliases, - desc_checksum(&normalize_aliases).unwrap() - ), + format!("{}#{}", &normalize_aliases, desc_checksum(&normalize_aliases).unwrap()), output ); } @@ -1087,11 +1055,8 @@ mod tests { StdDescriptor::from_str(&format!("sh(wpkh({}))", uncompressed_pk)).unwrap_err(); StdDescriptor::from_str(&format!("wsh(pk{})", uncompressed_pk)).unwrap_err(); StdDescriptor::from_str(&format!("sh(wsh(pk{}))", uncompressed_pk)).unwrap_err(); - StdDescriptor::from_str(&format!( - "or_i(pk({}),pk({}))", - uncompressed_pk, uncompressed_pk - )) - .unwrap_err(); + StdDescriptor::from_str(&format!("or_i(pk({}),pk({}))", uncompressed_pk, uncompressed_pk)) + .unwrap_err(); } #[test] @@ -1516,19 +1481,13 @@ mod tests { #[test] fn roundtrip_tests() { let descriptor = Descriptor::::from_str("multi"); - assert_eq!( - descriptor.unwrap_err().to_string(), - "unexpected «no arguments given»" - ) + assert_eq!(descriptor.unwrap_err().to_string(), "unexpected «no arguments given»") } #[test] fn empty_thresh() { let descriptor = Descriptor::::from_str("thresh"); - assert_eq!( - descriptor.unwrap_err().to_string(), - "unexpected «no arguments given»" - ) + assert_eq!(descriptor.unwrap_err().to_string(), "unexpected «no arguments given»") } #[test] @@ -1564,17 +1523,11 @@ mod tests { satisfier.insert( a, - bitcoin::ecdsa::Signature { - sig: sig_a, - hash_ty: EcdsaSighashType::All, - }, + bitcoin::ecdsa::Signature { sig: sig_a, hash_ty: EcdsaSighashType::All }, ); satisfier.insert( b, - bitcoin::ecdsa::Signature { - sig: sig_b, - hash_ty: EcdsaSighashType::All, - }, + bitcoin::ecdsa::Signature { sig: sig_b, hash_ty: EcdsaSighashType::All }, ); satisfier @@ -1919,10 +1872,7 @@ pk(03f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8))"; ) .unwrap(); - assert_eq!( - descriptor.find_derivation_index_for_spk(&secp, &script_at_0_1, 0..1), - Ok(None) - ); + assert_eq!(descriptor.find_derivation_index_for_spk(&secp, &script_at_0_1, 0..1), Ok(None)); assert_eq!( descriptor.find_derivation_index_for_spk(&secp, &script_at_0_1, 0..2), Ok(Some((1, expected_concrete.clone()))) @@ -2035,10 +1985,7 @@ pk(03f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8))"; // We can detect regular single-path descriptors. let notmulti_desc = Descriptor::from_str("wsh(andor(pk(tpubDEN9WSToTyy9ZQfaYqSKfmVqmq1VVLNtYfj3Vkqh67et57eJ5sTKZQBkHqSwPUsoSskJeaYnPttHe2VrkCsKA27kUaN9SDc5zhqeLzKa1rr/0'/*),older(10000),pk(tpubD8LYfn6njiA2inCoxwM7EuN3cuLVcaHAwLYeups13dpevd3nHLRdK9NdQksWXrhLQVxcUZRpnp5CkJ1FhE61WRAsHxDNAkvGkoQkAeWDYjV/8/4567/*)))").unwrap(); assert!(!notmulti_desc.is_multipath()); - assert_eq!( - notmulti_desc.clone().into_single_descriptors().unwrap(), - vec![notmulti_desc] - ); + assert_eq!(notmulti_desc.clone().into_single_descriptors().unwrap(), vec![notmulti_desc]); // We refuse to parse multipath descriptors with a mismatch in the number of derivation paths between keys. Descriptor::::from_str("wsh(andor(pk(tpubDEN9WSToTyy9ZQfaYqSKfmVqmq1VVLNtYfj3Vkqh67et57eJ5sTKZQBkHqSwPUsoSskJeaYnPttHe2VrkCsKA27kUaN9SDc5zhqeLzKa1rr/0'/<0;1>/*),older(10000),pk(tpubD8LYfn6njiA2inCoxwM7EuN3cuLVcaHAwLYeups13dpevd3nHLRdK9NdQksWXrhLQVxcUZRpnp5CkJ1FhE61WRAsHxDNAkvGkoQkAeWDYjV/8/<0;1;2;3;4>/*)))").unwrap_err(); diff --git a/src/descriptor/segwitv0.rs b/src/descriptor/segwitv0.rs index 6ef6e6684..0cc665468 100644 --- a/src/descriptor/segwitv0.rs +++ b/src/descriptor/segwitv0.rs @@ -32,38 +32,28 @@ pub struct Wsh { impl Wsh { /// Get the Inner - pub fn into_inner(self) -> WshInner { - self.inner - } + pub fn into_inner(self) -> WshInner { self.inner } /// Get a reference to inner - pub fn as_inner(&self) -> &WshInner { - &self.inner - } + pub fn as_inner(&self) -> &WshInner { &self.inner } /// Create a new wsh descriptor pub fn new(ms: Miniscript) -> Result { // do the top-level checks Segwitv0::top_level_checks(&ms)?; - Ok(Self { - inner: WshInner::Ms(ms), - }) + Ok(Self { inner: WshInner::Ms(ms) }) } /// Create a new sortedmulti wsh descriptor pub fn new_sortedmulti(k: usize, pks: Vec) -> Result { // The context checks will be carried out inside new function for // sortedMultiVec - Ok(Self { - inner: WshInner::SortedMulti(SortedMultiVec::new(k, pks)?), - }) + Ok(Self { inner: WshInner::SortedMulti(SortedMultiVec::new(k, pks)?) }) } /// Get the descriptor without the checksum #[deprecated(since = "8.0.0", note = "use format!(\"{:#}\") instead")] - pub fn to_string_no_checksum(&self) -> String { - format!("{:#}", self) - } + pub fn to_string_no_checksum(&self) -> String { format!("{:#}", self) } /// Checks whether the descriptor is safe. pub fn sanity_check(&self) -> Result<(), Error> { @@ -135,9 +125,7 @@ impl Wsh { impl Wsh { /// Obtains the corresponding script pubkey for this descriptor. - pub fn script_pubkey(&self) -> ScriptBuf { - self.inner_script().to_v0_p2wsh() - } + pub fn script_pubkey(&self) -> ScriptBuf { self.inner_script().to_v0_p2wsh() } /// Obtains the corresponding script pubkey for this descriptor. pub fn address(&self, network: Network) -> Address { @@ -156,9 +144,7 @@ impl Wsh { } /// Obtains the pre bip-340 signature script code for this descriptor. - pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { - self.inner_script() - } + pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { self.inner_script() } /// Returns satisfying non-malleable witness and scriptSig with minimum /// weight to spend an output controlled by the given descriptor if it is @@ -248,15 +234,11 @@ impl_from_tree!( if top.name == "wsh" && top.args.len() == 1 { let top = &top.args[0]; if top.name == "sortedmulti" { - return Ok(Wsh { - inner: WshInner::SortedMulti(SortedMultiVec::from_tree(top)?), - }); + return Ok(Wsh { inner: WshInner::SortedMulti(SortedMultiVec::from_tree(top)?) }); } let sub = Miniscript::from_tree(top)?; Segwitv0::top_level_checks(&sub)?; - Ok(Wsh { - inner: WshInner::Ms(sub), - }) + Ok(Wsh { inner: WshInner::Ms(sub) }) } else { Err(Error::Unexpected(format!( "{}({} args) while parsing wsh descriptor", @@ -344,27 +326,19 @@ impl Wpkh { } /// Get the inner key - pub fn into_inner(self) -> Pk { - self.pk - } + pub fn into_inner(self) -> Pk { self.pk } /// Get the inner key - pub fn as_inner(&self) -> &Pk { - &self.pk - } + pub fn as_inner(&self) -> &Pk { &self.pk } /// Get the descriptor without the checksum #[deprecated(since = "8.0.0", note = "use format!(\"{:#}\") instead")] - pub fn to_string_no_checksum(&self) -> String { - format!("{:#}", self) - } + pub fn to_string_no_checksum(&self) -> String { format!("{:#}", self) } /// Checks whether the descriptor is safe. pub fn sanity_check(&self) -> Result<(), Error> { if self.pk.is_uncompressed() { - Err(Error::ContextError(ScriptContextError::CompressedOnly( - self.pk.to_string(), - ))) + Err(Error::ContextError(ScriptContextError::CompressedOnly(self.pk.to_string()))) } else { Ok(()) } @@ -389,9 +363,7 @@ impl Wpkh { /// Assumes all ec-signatures are 73 bytes, including push opcode and /// sighash suffix. Includes the weight of the VarInts encoding the /// scriptSig and witness stack length. - pub fn max_satisfaction_weight(&self) -> usize { - 4 + 1 + 73 + Segwitv0::pk_len(&self.pk) - } + pub fn max_satisfaction_weight(&self) -> usize { 4 + 1 + 73 + Segwitv0::pk_len(&self.pk) } } impl Wpkh { @@ -409,9 +381,7 @@ impl Wpkh { } /// Obtains the underlying miniscript for this descriptor. - pub fn inner_script(&self) -> ScriptBuf { - self.script_pubkey() - } + pub fn inner_script(&self) -> ScriptBuf { self.script_pubkey() } /// Obtains the pre bip-340 signature script code for this descriptor. pub fn ecdsa_sighash_script_code(&self) -> ScriptBuf { @@ -470,12 +440,7 @@ impl Wpkh { Witness::Unavailable }; - Satisfaction { - stack, - has_sig: true, - relative_timelock: None, - absolute_timelock: None, - } + Satisfaction { stack, has_sig: true, relative_timelock: None, absolute_timelock: None } } /// Returns a plan if the provided assets are sufficient to produce a malleable satisfaction @@ -491,9 +456,7 @@ impl Wpkh { } impl fmt::Debug for Wpkh { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "wpkh({:?})", self.pk) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "wpkh({:?})", self.pk) } } impl fmt::Display for Wpkh { @@ -515,9 +478,7 @@ impl_from_tree!( Wpkh, fn from_tree(top: &expression::Tree) -> Result { if top.name == "wpkh" && top.args.len() == 1 { - Ok(Wpkh::new(expression::terminal(&top.args[0], |pk| { - Pk::from_str(pk) - })?)?) + Ok(Wpkh::new(expression::terminal(&top.args[0], |pk| Pk::from_str(pk))?)?) } else { Err(Error::Unexpected(format!( "{}({} args) while parsing wpkh descriptor", @@ -539,9 +500,7 @@ impl_from_str!( ); impl ForEachKey for Wpkh { - fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { - pred(&self.pk) - } + fn for_each_key<'a, F: FnMut(&'a Pk) -> bool>(&'a self, mut pred: F) -> bool { pred(&self.pk) } } impl TranslatePk for Wpkh

diff --git a/src/descriptor/sh.rs b/src/descriptor/sh.rs index 4b4c24637..53b4107ce 100644 --- a/src/descriptor/sh.rs +++ b/src/descriptor/sh.rs @@ -122,22 +122,16 @@ impl_from_str!( impl Sh { /// Get the Inner - pub fn into_inner(self) -> ShInner { - self.inner - } + pub fn into_inner(self) -> ShInner { self.inner } /// Get a reference to inner - pub fn as_inner(&self) -> &ShInner { - &self.inner - } + pub fn as_inner(&self) -> &ShInner { &self.inner } /// Create a new p2sh descriptor with the raw miniscript pub fn new(ms: Miniscript) -> Result { // do the top-level checks Legacy::top_level_checks(&ms)?; - Ok(Self { - inner: ShInner::Ms(ms), - }) + Ok(Self { inner: ShInner::Ms(ms) }) } /// Create a new p2sh sortedmulti descriptor with threshold `k` @@ -145,24 +139,16 @@ impl Sh { pub fn new_sortedmulti(k: usize, pks: Vec) -> Result { // The context checks will be carried out inside new function for // sortedMultiVec - Ok(Self { - inner: ShInner::SortedMulti(SortedMultiVec::new(k, pks)?), - }) + Ok(Self { inner: ShInner::SortedMulti(SortedMultiVec::new(k, pks)?) }) } /// Create a new p2sh wrapped wsh descriptor with the raw miniscript pub fn new_wsh(ms: Miniscript) -> Result { - Ok(Self { - inner: ShInner::Wsh(Wsh::new(ms)?), - }) + Ok(Self { inner: ShInner::Wsh(Wsh::new(ms)?) }) } /// Create a new p2sh wrapper for the given wsh descriptor - pub fn new_with_wsh(wsh: Wsh) -> Self { - Self { - inner: ShInner::Wsh(wsh), - } - } + pub fn new_with_wsh(wsh: Wsh) -> Self { Self { inner: ShInner::Wsh(wsh) } } /// Checks whether the descriptor is safe. pub fn sanity_check(&self) -> Result<(), Error> { @@ -180,24 +166,16 @@ impl Sh { pub fn new_wsh_sortedmulti(k: usize, pks: Vec) -> Result { // The context checks will be carried out inside new function for // sortedMultiVec - Ok(Self { - inner: ShInner::Wsh(Wsh::new_sortedmulti(k, pks)?), - }) + Ok(Self { inner: ShInner::Wsh(Wsh::new_sortedmulti(k, pks)?) }) } /// Create a new p2sh wrapped wpkh from `Pk` pub fn new_wpkh(pk: Pk) -> Result { - Ok(Self { - inner: ShInner::Wpkh(Wpkh::new(pk)?), - }) + Ok(Self { inner: ShInner::Wpkh(Wpkh::new(pk)?) }) } /// Create a new p2sh wrapper for the given wpkh descriptor - pub fn new_with_wpkh(wpkh: Wpkh) -> Self { - Self { - inner: ShInner::Wpkh(wpkh), - } - } + pub fn new_with_wpkh(wpkh: Wpkh) -> Self { Self { inner: ShInner::Wpkh(wpkh) } } /// Computes an upper bound on the difference between a non-satisfied /// `TxIn`'s `segwit_weight` and a satisfied `TxIn`'s `segwit_weight` diff --git a/src/descriptor/sortedmulti.rs b/src/descriptor/sortedmulti.rs index 3887d8752..3bd5fa8e0 100644 --- a/src/descriptor/sortedmulti.rs +++ b/src/descriptor/sortedmulti.rs @@ -53,11 +53,7 @@ impl SortedMultiVec { // even tapscript in future Ctx::check_local_validity(&ms)?; - Ok(Self { - k, - pks, - phantom: PhantomData, - }) + Ok(Self { k, pks, phantom: PhantomData }) } /// Parse an expression tree into a SortedMultiVec pub fn from_tree(tree: &expression::Tree) -> Result @@ -70,9 +66,7 @@ impl SortedMultiVec { } let k = expression::parse_num(tree.args[0].name)?; if k > (tree.args.len() - 1) as u32 { - return Err(errstr( - "higher threshold than there were keys in sortedmulti", - )); + return Err(errstr("higher threshold than there were keys in sortedmulti")); } let pks: Result, _> = tree.args[1..] .iter() @@ -188,9 +182,7 @@ impl SortedMultiVec { /// This function may panic on malformed `Miniscript` objects which do /// not correspond to semantically sane Scripts. (Such scripts should be /// rejected at parse time. Any exceptions are bugs.) - pub fn max_satisfaction_witness_elements(&self) -> usize { - 2 + self.k - } + pub fn max_satisfaction_witness_elements(&self) -> usize { 2 + self.k } /// Maximum size, in bytes, of a satisfying witness. /// In general, it is not recommended to use this function directly, but @@ -200,9 +192,7 @@ impl SortedMultiVec { /// All signatures are assumed to be 73 bytes in size, including the /// length prefix (segwit) or push opcode (pre-segwit) and sighash /// postfix. - pub fn max_satisfaction_size(&self) -> usize { - 1 + 73 * self.k - } + pub fn max_satisfaction_size(&self) -> usize { 1 + 73 * self.k } } impl policy::Liftable for SortedMultiVec { @@ -219,9 +209,7 @@ impl policy::Liftable for SortedMulti } impl fmt::Debug for SortedMultiVec { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(self, f) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self, f) } } impl fmt::Display for SortedMultiVec { diff --git a/src/descriptor/tr.rs b/src/descriptor/tr.rs index 798617d94..48deb63e0 100644 --- a/src/descriptor/tr.rs +++ b/src/descriptor/tr.rs @@ -120,32 +120,20 @@ impl TapTree { /// Creates a `TapTree` by combining `left` and `right` tree nodes. pub(crate) fn combine(left: TapTree, right: TapTree) -> Self { let height = 1 + cmp::max(left.height(), right.height()); - TapTree::Tree { - left: Arc::new(left), - right: Arc::new(right), - height, - } + TapTree::Tree { left: Arc::new(left), right: Arc::new(right), height } } /// Returns the height of this tree. fn height(&self) -> usize { match *self { - TapTree::Tree { - left: _, - right: _, - height, - } => height, + TapTree::Tree { left: _, right: _, height } => height, TapTree::Leaf(..) => 0, } } /// Iterates over all miniscripts in DFS walk order compatible with the /// PSBT requirements (BIP 371). - pub fn iter(&self) -> TapTreeIter { - TapTreeIter { - stack: vec![(0, self)], - } - } + pub fn iter(&self) -> TapTreeIter { TapTreeIter { stack: vec![(0, self)] } } // Helper function to translate keys fn translate_helper(&self, t: &mut T) -> Result, TranslateErr> @@ -154,11 +142,7 @@ impl TapTree { Q: MiniscriptKey, { let frag = match *self { - TapTree::Tree { - ref left, - ref right, - ref height, - } => TapTree::Tree { + TapTree::Tree { ref left, ref right, ref height } => TapTree::Tree { left: Arc::new(left.translate_helper(t)?), right: Arc::new(right.translate_helper(t)?), height: *height, @@ -172,11 +156,9 @@ impl TapTree { impl fmt::Display for TapTree { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TapTree::Tree { - ref left, - ref right, - height: _, - } => write!(f, "{{{},{}}}", *left, *right), + TapTree::Tree { ref left, ref right, height: _ } => { + write!(f, "{{{},{}}}", *left, *right) + } TapTree::Leaf(ref script) => write!(f, "{}", *script), } } @@ -185,11 +167,9 @@ impl fmt::Display for TapTree { impl fmt::Debug for TapTree { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { - TapTree::Tree { - ref left, - ref right, - height: _, - } => write!(f, "{{{:?},{:?}}}", *left, *right), + TapTree::Tree { ref left, ref right, height: _ } => { + write!(f, "{{{:?},{:?}}}", *left, *right) + } TapTree::Leaf(ref script) => write!(f, "{:?}", *script), } } @@ -202,31 +182,21 @@ impl Tr { let nodes = tree.as_ref().map(|t| t.height()).unwrap_or(0); if nodes <= TAPROOT_CONTROL_MAX_NODE_COUNT { - Ok(Self { - internal_key, - tree, - spend_info: Mutex::new(None), - }) + Ok(Self { internal_key, tree, spend_info: Mutex::new(None) }) } else { Err(Error::MaxRecursiveDepthExceeded) } } /// Obtain the internal key of [`Tr`] descriptor - pub fn internal_key(&self) -> &Pk { - &self.internal_key - } + pub fn internal_key(&self) -> &Pk { &self.internal_key } /// Obtain the [`TapTree`] of the [`Tr`] descriptor - pub fn tap_tree(&self) -> &Option> { - &self.tree - } + pub fn tap_tree(&self) -> &Option> { &self.tree } /// Obtain the [`TapTree`] of the [`Tr`] descriptor #[deprecated(since = "11.0.0", note = "use tap_tree instead")] - pub fn taptree(&self) -> &Option> { - self.tap_tree() - } + pub fn taptree(&self) -> &Option> { self.tap_tree() } /// Iterate over all scripts in merkle tree. If there is no script path, the iterator /// yields [`None`] @@ -486,11 +456,7 @@ where fn next(&mut self) -> Option { while let Some((depth, last)) = self.stack.pop() { match *last { - TapTree::Tree { - ref left, - ref right, - height: _, - } => { + TapTree::Tree { ref left, ref right, height: _ } => { self.stack.push((depth + 1, right)); self.stack.push((depth + 1, left)); } @@ -608,18 +574,10 @@ fn parse_tr_tree(s: &str) -> Result { if !rest.contains(',') { let key = expression::Tree::from_str(rest)?; if !key.args.is_empty() { - return Err(Error::Unexpected( - "invalid taproot internal key".to_string(), - )); + return Err(Error::Unexpected("invalid taproot internal key".to_string())); } - let internal_key = expression::Tree { - name: key.name, - args: vec![], - }; - return Ok(expression::Tree { - name: "tr", - args: vec![internal_key], - }); + let internal_key = expression::Tree { name: key.name, args: vec![] }; + return Ok(expression::Tree { name: "tr", args: vec![internal_key] }); } // use str::split_once() method to refactor this when compiler version bumps up let (key, script) = split_once(rest, ',') @@ -627,26 +585,15 @@ fn parse_tr_tree(s: &str) -> Result { let key = expression::Tree::from_str(key)?; if !key.args.is_empty() { - return Err(Error::Unexpected( - "invalid taproot internal key".to_string(), - )); + return Err(Error::Unexpected("invalid taproot internal key".to_string())); } - let internal_key = expression::Tree { - name: key.name, - args: vec![], - }; + let internal_key = expression::Tree { name: key.name, args: vec![] }; if script.is_empty() { - return Ok(expression::Tree { - name: "tr", - args: vec![internal_key], - }); + return Ok(expression::Tree { name: "tr", args: vec![internal_key] }); } let (tree, rest) = expression::Tree::from_slice_delim(script, 1, '{')?; if rest.is_empty() { - Ok(expression::Tree { - name: "tr", - args: vec![internal_key, tree], - }) + Ok(expression::Tree { name: "tr", args: vec![internal_key, tree] }) } else { Err(errstr(rest)) } @@ -673,14 +620,9 @@ impl Liftable for TapTree { fn lift(&self) -> Result, Error> { fn lift_helper(s: &TapTree) -> Result, Error> { match *s { - TapTree::Tree { - ref left, - ref right, - height: _, - } => Ok(Policy::Threshold( - 1, - vec![lift_helper(left)?, lift_helper(right)?], - )), + TapTree::Tree { ref left, ref right, height: _ } => { + Ok(Policy::Threshold(1, vec![lift_helper(left)?, lift_helper(right)?])) + } TapTree::Leaf(ref leaf) => leaf.lift(), } } @@ -693,10 +635,9 @@ impl Liftable for TapTree { impl Liftable for Tr { fn lift(&self) -> Result, Error> { match &self.tree { - Some(root) => Ok(Policy::Threshold( - 1, - vec![Policy::Key(self.internal_key.clone()), root.lift()?], - )), + Some(root) => { + Ok(Policy::Threshold(1, vec![Policy::Key(self.internal_key.clone()), root.lift()?])) + } None => Ok(Policy::Key(self.internal_key.clone())), } } @@ -754,9 +695,7 @@ where Satisfaction { stack: Witness::Stack(vec![Placeholder::SchnorrSigPk( desc.internal_key.clone(), - SchnorrSigType::KeySpend { - merkle_root: spend_info.merkle_root(), - }, + SchnorrSigType::KeySpend { merkle_root: spend_info.merkle_root() }, size, )]), has_sig: true, @@ -776,26 +715,17 @@ where for (_depth, ms) in desc.iter_scripts() { let mut satisfaction = if allow_mall { match ms.build_template(provider) { - s @ Satisfaction { - stack: Witness::Stack(_), - .. - } => s, + s @ Satisfaction { stack: Witness::Stack(_), .. } => s, _ => continue, // No witness for this script in tr descriptor, look for next one } } else { match ms.build_template_mall(provider) { - s @ Satisfaction { - stack: Witness::Stack(_), - .. - } => s, + s @ Satisfaction { stack: Witness::Stack(_), .. } => s, _ => continue, // No witness for this script in tr descriptor, look for next one } }; let wit = match satisfaction { - Satisfaction { - stack: Witness::Stack(ref mut wit), - .. - } => wit, + Satisfaction { stack: Witness::Stack(ref mut wit), .. } => wit, _ => unreachable!(), }; diff --git a/src/expression.rs b/src/expression.rs index fe7d14785..7875284de 100644 --- a/src/expression.rs +++ b/src/expression.rs @@ -137,27 +137,14 @@ impl<'a> Tree<'a> { match next_expr(sl, delim) { // String-ending terminal - Found::Nothing => Ok(( - Tree { - name: sl, - args: vec![], - }, - "", - )), + Found::Nothing => Ok((Tree { name: sl, args: vec![] }, "")), // Terminal - Found::Comma(n) | Found::RBracket(n) => Ok(( - Tree { - name: &sl[..n], - args: vec![], - }, - &sl[n..], - )), + Found::Comma(n) | Found::RBracket(n) => { + Ok((Tree { name: &sl[..n], args: vec![] }, &sl[n..])) + } // Function call Found::LBracket(n) => { - let mut ret = Tree { - name: &sl[..n], - args: vec![], - }; + let mut ret = Tree { name: &sl[..n], args: vec![] }; sl = &sl[n + 1..]; loop { @@ -221,9 +208,7 @@ pub fn parse_num(s: &str) -> Result { if s.len() > 1 { let ch = s.chars().next().unwrap(); if !('1'..='9').contains(&ch) { - return Err(Error::Unexpected( - "Number must start with a digit 1-9".to_string(), - )); + return Err(Error::Unexpected("Number must start with a digit 1-9".to_string())); } } u32::from_str(s).map_err(|_| errstr(s)) diff --git a/src/interpreter/error.rs b/src/interpreter/error.rs index ea241776f..bc40f020a 100644 --- a/src/interpreter/error.rs +++ b/src/interpreter/error.rs @@ -114,11 +114,9 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Error::AbsoluteLocktimeNotMet(n) => write!( - f, - "required absolute locktime CLTV of {} blocks, not met", - n - ), + Error::AbsoluteLocktimeNotMet(n) => { + write!(f, "required absolute locktime CLTV of {} blocks, not met", n) + } Error::AbsoluteLocktimeComparisonInvalid(n, lock_time) => write!( f, "could not satisfy, lock time values are different units n: {} lock_time: {}", @@ -140,18 +138,14 @@ impl fmt::Display for Error { } Error::IncorrectWScriptHash => f.write_str("witness script did not match scriptpubkey"), Error::InsufficientSignaturesMultiSig => f.write_str("Insufficient signatures for CMS"), - Error::InvalidSchnorrSighashType(ref sig) => write!( - f, - "Invalid sighash type for schnorr signature '{:x}'", - sig.as_hex() - ), + Error::InvalidSchnorrSighashType(ref sig) => { + write!(f, "Invalid sighash type for schnorr signature '{:x}'", sig.as_hex()) + } Error::InvalidEcdsaSignature(pk) => write!(f, "bad ecdsa signature with pk {}", pk), Error::InvalidSchnorrSignature(pk) => write!(f, "bad schnorr signature with pk {}", pk), - Error::NonStandardSighash(ref sig) => write!( - f, - "Non standard sighash type for signature '{:x}'", - sig.as_hex() - ), + Error::NonStandardSighash(ref sig) => { + write!(f, "Non standard sighash type for signature '{:x}'", sig.as_hex()) + } Error::NonEmptyWitness => f.write_str("legacy spend had nonempty witness"), Error::NonEmptyScriptSig => f.write_str("segwit spend had nonempty scriptsig"), Error::Miniscript(ref e) => write!(f, "parse error: {}", e), @@ -236,37 +230,27 @@ impl error::Error for Error { #[doc(hidden)] impl From for Error { - fn from(e: secp256k1::Error) -> Error { - Error::Secp(e) - } + fn from(e: secp256k1::Error) -> Error { Error::Secp(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::sighash::Error) -> Error { - Error::SighashError(e) - } + fn from(e: bitcoin::sighash::Error) -> Error { Error::SighashError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::ecdsa::Error) -> Error { - Error::EcdsaSig(e) - } + fn from(e: bitcoin::ecdsa::Error) -> Error { Error::EcdsaSig(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::taproot::Error) -> Error { - Error::SchnorrSig(e) - } + fn from(e: bitcoin::taproot::Error) -> Error { Error::SchnorrSig(e) } } #[doc(hidden)] impl From for Error { - fn from(e: crate::Error) -> Error { - Error::Miniscript(e) - } + fn from(e: crate::Error) -> Error { Error::Miniscript(e) } } /// A type of representing which keys errored during interpreter checksig evaluation diff --git a/src/interpreter/inner.rs b/src/interpreter/inner.rs index 266670eaf..88cf4ad4a 100644 --- a/src/interpreter/inner.rs +++ b/src/interpreter/inner.rs @@ -182,11 +182,7 @@ pub(super) fn from_txdata<'txin>( let miniscript = miniscript.to_no_checks_ms(); let scripthash = sha256::Hash::hash(script.as_bytes()); if *spk == bitcoin::ScriptBuf::new_v0_p2wsh(&scripthash.into()) { - Ok(( - Inner::Script(miniscript, ScriptType::Wsh), - wit_stack, - Some(script), - )) + Ok((Inner::Script(miniscript, ScriptType::Wsh), wit_stack, Some(script))) } else { Err(Error::IncorrectWScriptHash) } @@ -321,11 +317,7 @@ pub(super) fn from_txdata<'txin>( if wit_stack.is_empty() { let scripthash = hash160::Hash::hash(script.as_bytes()); if *spk == bitcoin::ScriptBuf::new_p2sh(&scripthash.into()) { - Ok(( - Inner::Script(miniscript, ScriptType::Sh), - ssig_stack, - Some(script), - )) + Ok((Inner::Script(miniscript, ScriptType::Sh), ssig_stack, Some(script))) } else { Err(Error::IncorrectScriptHash) } @@ -344,11 +336,7 @@ pub(super) fn from_txdata<'txin>( &ExtParams::allow_all(), )?; let miniscript = miniscript.to_no_checks_ms(); - Ok(( - Inner::Script(miniscript, ScriptType::Bare), - ssig_stack, - Some(spk.to_owned()), - )) + Ok((Inner::Script(miniscript, ScriptType::Bare), ssig_stack, Some(spk.to_owned()))) } else { Err(Error::NonEmptyWitness) } @@ -506,44 +494,29 @@ mod tests { // Compressed pk, empty scriptsig let (inner, stack, script_code) = from_txdata(&comp.pk_spk, &blank_script, &empty_wit).expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Pk) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Pk)); assert_eq!(stack, Stack::from(vec![])); assert_eq!(script_code, Some(comp.pk_spk.clone())); // Uncompressed pk, empty scriptsig let (inner, stack, script_code) = from_txdata(&uncomp.pk_spk, &blank_script, &empty_wit).expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_uncomp.into(), PubkeyType::Pk) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_uncomp.into(), PubkeyType::Pk)); assert_eq!(stack, Stack::from(vec![])); assert_eq!(script_code, Some(uncomp.pk_spk.clone())); // Compressed pk, correct scriptsig let (inner, stack, script_code) = from_txdata(&comp.pk_spk, &comp.pk_sig, &empty_wit).expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Pk) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Pk)); assert_eq!(stack, Stack::from(vec![comp.pk_sig[1..].as_bytes().into()])); assert_eq!(script_code, Some(comp.pk_spk.clone())); // Uncompressed pk, correct scriptsig let (inner, stack, script_code) = from_txdata(&uncomp.pk_spk, &uncomp.pk_sig, &empty_wit).expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_uncomp.into(), PubkeyType::Pk) - ); - assert_eq!( - stack, - Stack::from(vec![uncomp.pk_sig[1..].as_bytes().into()]) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_uncomp.into(), PubkeyType::Pk)); + assert_eq!(stack, Stack::from(vec![uncomp.pk_sig[1..].as_bytes().into()])); assert_eq!(script_code, Some(uncomp.pk_spk)); // Scriptpubkey has invalid key @@ -584,40 +557,28 @@ mod tests { // pkh, right pubkey, no signature let (inner, stack, script_code) = from_txdata(&comp.pkh_spk, &comp.pkh_sig_justkey, &empty_wit).expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Pkh) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Pkh)); assert_eq!(stack, Stack::from(vec![])); assert_eq!(script_code, Some(comp.pkh_spk.clone())); let (inner, stack, script_code) = from_txdata(&uncomp.pkh_spk, &uncomp.pkh_sig_justkey, &empty_wit) .expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_uncomp.into(), PubkeyType::Pkh) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_uncomp.into(), PubkeyType::Pkh)); assert_eq!(stack, Stack::from(vec![])); assert_eq!(script_code, Some(uncomp.pkh_spk.clone())); // pkh, right pubkey, signature let (inner, stack, script_code) = from_txdata(&comp.pkh_spk, &comp.pkh_sig_justkey, &empty_wit).expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Pkh) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Pkh)); assert_eq!(stack, Stack::from(vec![])); assert_eq!(script_code, Some(comp.pkh_spk.clone())); let (inner, stack, script_code) = from_txdata(&uncomp.pkh_spk, &uncomp.pkh_sig_justkey, &empty_wit) .expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_uncomp.into(), PubkeyType::Pkh) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_uncomp.into(), PubkeyType::Pkh)); assert_eq!(stack, Stack::from(vec![])); assert_eq!(script_code, Some(uncomp.pkh_spk.clone())); @@ -641,41 +602,26 @@ mod tests { // wpkh, uncompressed pubkey let err = from_txdata(&comp.wpkh_spk, &blank_script, &uncomp.wpkh_stack_justkey).unwrap_err(); - assert_eq!( - err.to_string(), - "uncompressed pubkey in non-legacy descriptor" - ); + assert_eq!(err.to_string(), "uncompressed pubkey in non-legacy descriptor"); // wpkh, wrong pubkey let err = from_txdata(&uncomp.wpkh_spk, &blank_script, &comp.wpkh_stack_justkey).unwrap_err(); - assert_eq!( - err.to_string(), - "public key did not match scriptpubkey (segwit v0)" - ); + assert_eq!(err.to_string(), "public key did not match scriptpubkey (segwit v0)"); // wpkh, right pubkey, no signature let (inner, stack, script_code) = from_txdata(&comp.wpkh_spk, &blank_script, &comp.wpkh_stack_justkey) .expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Wpkh) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Wpkh)); assert_eq!(stack, Stack::from(vec![])); assert_eq!(script_code, Some(comp.pkh_spk.clone())); // wpkh, right pubkey, signature let (inner, stack, script_code) = from_txdata(&comp.wpkh_spk, &blank_script, &comp.wpkh_stack).expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Wpkh) - ); - assert_eq!( - stack, - Stack::from(vec![comp.wpkh_stack.second_to_last().unwrap().into()]) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::Wpkh)); + assert_eq!(stack, Stack::from(vec![comp.wpkh_stack.second_to_last().unwrap().into()])); assert_eq!(script_code, Some(comp.pkh_spk)); // Scriptsig is nonempty @@ -700,46 +646,27 @@ mod tests { assert_eq!(err.to_string(), "unexpected end of stack"); // sh_wpkh, uncompressed pubkey - let err = from_txdata( - &uncomp.sh_wpkh_spk, - &uncomp.sh_wpkh_sig, - &uncomp.sh_wpkh_stack_justkey, - ) - .unwrap_err(); - assert_eq!( - err.to_string(), - "uncompressed pubkey in non-legacy descriptor" - ); + let err = + from_txdata(&uncomp.sh_wpkh_spk, &uncomp.sh_wpkh_sig, &uncomp.sh_wpkh_stack_justkey) + .unwrap_err(); + assert_eq!(err.to_string(), "uncompressed pubkey in non-legacy descriptor"); // sh_wpkh, wrong redeem script for scriptpubkey - let err = from_txdata( - &uncomp.sh_wpkh_spk, - &comp.sh_wpkh_sig, - &comp.sh_wpkh_stack_justkey, - ) - .unwrap_err(); + let err = from_txdata(&uncomp.sh_wpkh_spk, &comp.sh_wpkh_sig, &comp.sh_wpkh_stack_justkey) + .unwrap_err(); assert_eq!(err.to_string(), "redeem script did not match scriptpubkey",); // sh_wpkh, wrong redeem script for witness script - let err = from_txdata( - &uncomp.sh_wpkh_spk, - &uncomp.sh_wpkh_sig, - &comp.sh_wpkh_stack_justkey, - ) - .unwrap_err(); + let err = + from_txdata(&uncomp.sh_wpkh_spk, &uncomp.sh_wpkh_sig, &comp.sh_wpkh_stack_justkey) + .unwrap_err(); assert_eq!(err.to_string(), "witness script did not match scriptpubkey",); // sh_wpkh, right pubkey, no signature - let (inner, stack, script_code) = from_txdata( - &comp.sh_wpkh_spk, - &comp.sh_wpkh_sig, - &comp.sh_wpkh_stack_justkey, - ) - .expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::ShWpkh) - ); + let (inner, stack, script_code) = + from_txdata(&comp.sh_wpkh_spk, &comp.sh_wpkh_sig, &comp.sh_wpkh_stack_justkey) + .expect("parse txdata"); + assert_eq!(inner, Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::ShWpkh)); assert_eq!(stack, Stack::from(vec![])); assert_eq!(script_code, Some(comp.pkh_spk.clone())); @@ -747,14 +674,8 @@ mod tests { let (inner, stack, script_code) = from_txdata(&comp.sh_wpkh_spk, &comp.sh_wpkh_sig, &comp.sh_wpkh_stack) .expect("parse txdata"); - assert_eq!( - inner, - Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::ShWpkh) - ); - assert_eq!( - stack, - Stack::from(vec![comp.sh_wpkh_stack.second_to_last().unwrap().into()]) - ); + assert_eq!(inner, Inner::PublicKey(fixed.pk_comp.into(), PubkeyType::ShWpkh)); + assert_eq!(stack, Stack::from(vec![comp.sh_wpkh_stack.second_to_last().unwrap().into()])); assert_eq!(script_code, Some(comp.pkh_spk.clone())); } diff --git a/src/interpreter/mod.rs b/src/interpreter/mod.rs index 37cd457fa..906989a04 100644 --- a/src/interpreter/mod.rs +++ b/src/interpreter/mod.rs @@ -111,15 +111,11 @@ impl fmt::Display for BitcoinKey { } impl From for BitcoinKey { - fn from(pk: bitcoin::PublicKey) -> Self { - BitcoinKey::Fullkey(pk) - } + fn from(pk: bitcoin::PublicKey) -> Self { BitcoinKey::Fullkey(pk) } } impl From for BitcoinKey { - fn from(xpk: bitcoin::key::XOnlyPublicKey) -> Self { - BitcoinKey::XOnlyPublicKey(xpk) - } + fn from(xpk: bitcoin::key::XOnlyPublicKey) -> Self { BitcoinKey::XOnlyPublicKey(xpk) } } impl MiniscriptKey for BitcoinKey { @@ -144,13 +140,7 @@ impl<'txin> Interpreter<'txin> { lock_time: absolute::LockTime, // CLTV, absolute lock time. ) -> Result { let (inner, stack, script_code) = inner::from_txdata(spk, script_sig, witness)?; - Ok(Interpreter { - inner, - stack, - script_code, - age, - lock_time, - }) + Ok(Interpreter { inner, stack, script_code, age, lock_time }) } /// Same as [`Interpreter::iter`], but allows for a custom verification function. @@ -168,11 +158,7 @@ impl<'txin> Interpreter<'txin> { None }, state: if let inner::Inner::Script(ref script, _) = self.inner { - vec![NodeEvaluationState { - node: script, - n_evaluated: 0, - n_satisfied: 0, - }] + vec![NodeEvaluationState { node: script, n_evaluated: 0, n_satisfied: 0 }] } else { vec![] }, @@ -308,9 +294,7 @@ impl<'txin> Interpreter<'txin> { input_idx: usize, prevouts: &'iter sighash::Prevouts, // actually a 'prevouts, but 'prevouts: 'iter ) -> Iter<'txin, 'iter> { - self.iter_custom(Box::new(move |sig| { - self.verify_sig(secp, tx, input_idx, prevouts, sig) - })) + self.iter_custom(Box::new(move |sig| self.verify_sig(secp, tx, input_idx, prevouts, sig))) } /// Creates an iterator over the satisfied spending conditions without checking signatures @@ -565,11 +549,8 @@ where n_evaluated: usize, n_satisfied: usize, ) { - self.state.push(NodeEvaluationState { - node, - n_evaluated, - n_satisfied, - }) + self.state + .push(NodeEvaluationState { node, n_evaluated, n_satisfied }) } /// Helper function to step the iterator @@ -1109,16 +1090,7 @@ mod tests { ser_schnorr_sigs.push(schnorr_sig.to_vec()); schnorr_sigs.push(schnorr_sig); } - ( - pks, - der_sigs, - ecdsa_sigs, - msg, - secp, - x_only_pks, - schnorr_sigs, - ser_schnorr_sigs, - ) + (pks, der_sigs, ecdsa_sigs, msg, secp, x_only_pks, schnorr_sigs, ser_schnorr_sigs) } #[test] @@ -1144,11 +1116,7 @@ mod tests { verify_sig: verify_fn, stack, public_key: None, - state: vec![NodeEvaluationState { - node: ms, - n_evaluated: 0, - n_satisfied: 0, - }], + state: vec![NodeEvaluationState { node: ms, n_evaluated: 0, n_satisfied: 0 }], age: Sequence::from_height(1002), lock_time: absolute::LockTime::from_height(1002).unwrap(), has_errored: false, @@ -1221,9 +1189,7 @@ mod tests { let older_satisfied: Result, Error> = constraints.collect(); assert_eq!( older_satisfied.unwrap(), - vec![SatisfiedConstraint::RelativeTimelock { - n: Sequence::from_height(1000) - }] + vec![SatisfiedConstraint::RelativeTimelock { n: Sequence::from_height(1000) }] ); //Check Sha256 @@ -1303,10 +1269,7 @@ mod tests { stack::Element::Push(&preimage), stack::Element::Push(&der_sigs[0]), ]); - let elem = no_checks_ms(&format!( - "and_b(c:pk_k({}),sjtv:sha256({}))", - pks[0], sha256_hash - )); + let elem = no_checks_ms(&format!("and_b(c:pk_k({}),sjtv:sha256({}))", pks[0], sha256_hash)); let constraints = from_stack(Box::new(vfyfn), stack, &elem); let and_b_satisfied: Result, Error> = constraints.collect(); @@ -1316,10 +1279,7 @@ mod tests { SatisfiedConstraint::PublicKey { key_sig: KeySigPair::Ecdsa(pks[0], ecdsa_sigs[0]) }, - SatisfiedConstraint::HashLock { - hash: HashLockType::Sha256(sha256_hash), - preimage, - } + SatisfiedConstraint::HashLock { hash: HashLockType::Sha256(sha256_hash), preimage } ] ); @@ -1341,10 +1301,7 @@ mod tests { SatisfiedConstraint::PublicKey { key_sig: KeySigPair::Ecdsa(pks[0], ecdsa_sigs[0]) }, - SatisfiedConstraint::HashLock { - hash: HashLockType::Sha256(sha256_hash), - preimage, - } + SatisfiedConstraint::HashLock { hash: HashLockType::Sha256(sha256_hash), preimage } ] ); @@ -1371,10 +1328,7 @@ mod tests { stack::Element::Push(&preimage), stack::Element::Dissatisfied, ]); - let elem = no_checks_ms(&format!( - "or_b(c:pk_k({}),sjtv:sha256({}))", - pks[0], sha256_hash - )); + let elem = no_checks_ms(&format!("or_b(c:pk_k({}),sjtv:sha256({}))", pks[0], sha256_hash)); let constraints = from_stack(Box::new(vfyfn), stack, &elem); let or_b_satisfied: Result, Error> = constraints.collect(); @@ -1388,10 +1342,7 @@ mod tests { //Check OrD let stack = Stack::from(vec![stack::Element::Push(&der_sigs[0])]); - let elem = no_checks_ms(&format!( - "or_d(c:pk_k({}),jtv:sha256({}))", - pks[0], sha256_hash - )); + let elem = no_checks_ms(&format!("or_d(c:pk_k({}),jtv:sha256({}))", pks[0], sha256_hash)); let constraints = from_stack(Box::new(vfyfn), stack, &elem); let or_d_satisfied: Result, Error> = constraints.collect(); @@ -1407,10 +1358,8 @@ mod tests { stack::Element::Push(&der_sigs[0]), stack::Element::Dissatisfied, ]); - let elem = no_checks_ms(&format!( - "t:or_c(jtv:sha256({}),vc:pk_k({}))", - sha256_hash, pks[0] - )); + let elem = + no_checks_ms(&format!("t:or_c(jtv:sha256({}),vc:pk_k({}))", sha256_hash, pks[0])); let constraints = from_stack(Box::new(vfyfn), stack, &elem); let or_c_satisfied: Result, Error> = constraints.collect(); @@ -1426,10 +1375,7 @@ mod tests { stack::Element::Push(&der_sigs[0]), stack::Element::Dissatisfied, ]); - let elem = no_checks_ms(&format!( - "or_i(jtv:sha256({}),c:pk_k({}))", - sha256_hash, pks[0] - )); + let elem = no_checks_ms(&format!("or_i(jtv:sha256({}),c:pk_k({}))", sha256_hash, pks[0])); let constraints = from_stack(Box::new(vfyfn), stack, &elem); let or_i_satisfied: Result, Error> = constraints.collect(); diff --git a/src/interpreter/stack.rs b/src/interpreter/stack.rs index 18e5d3f18..760459916 100644 --- a/src/interpreter/stack.rs +++ b/src/interpreter/stack.rs @@ -30,9 +30,7 @@ pub enum Element<'txin> { } impl<'txin> From<&'txin Vec> for Element<'txin> { - fn from(v: &'txin Vec) -> Element<'txin> { - From::from(&v[..]) - } + fn from(v: &'txin Vec) -> Element<'txin> { From::from(&v[..]) } } impl<'txin> From<&'txin [u8]> for Element<'txin> { @@ -78,42 +76,28 @@ impl<'txin> Element<'txin> { pub struct Stack<'txin>(Vec>); impl<'txin> From>> for Stack<'txin> { - fn from(v: Vec>) -> Self { - Stack(v) - } + fn from(v: Vec>) -> Self { Stack(v) } } impl<'txin> Stack<'txin> { /// Whether the stack is empty - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } + pub fn is_empty(&self) -> bool { self.0.is_empty() } /// Number of elements on the stack - pub fn len(&mut self) -> usize { - self.0.len() - } + pub fn len(&mut self) -> usize { self.0.len() } /// Removes the top stack element, if the stack is nonempty - pub fn pop(&mut self) -> Option> { - self.0.pop() - } + pub fn pop(&mut self) -> Option> { self.0.pop() } /// Pushes an element onto the top of the stack - pub fn push(&mut self, elem: Element<'txin>) { - self.0.push(elem); - } + pub fn push(&mut self, elem: Element<'txin>) { self.0.push(elem); } /// Returns a new stack representing the top `k` elements of the stack, /// removing these elements from the original - pub fn split_off(&mut self, k: usize) -> Vec> { - self.0.split_off(k) - } + pub fn split_off(&mut self, k: usize) -> Vec> { self.0.split_off(k) } /// Returns a reference to the top stack element, if the stack is nonempty - pub fn last(&self) -> Option<&Element<'txin>> { - self.0.last() - } + pub fn last(&self) -> Option<&Element<'txin>> { self.0.last() } /// Helper function to evaluate a Pk Node which takes the /// top of the stack as input signature and validates it. diff --git a/src/iter/tree.rs b/src/iter/tree.rs index e4884e991..cc58a6cf7 100644 --- a/src/iter/tree.rs +++ b/src/iter/tree.rs @@ -63,9 +63,7 @@ pub trait TreeLike: Clone + Sized { } /// Obtains an iterator of all the nodes rooted at the node, in pre-order. - fn pre_order_iter(self) -> PreOrderIter { - PreOrderIter { stack: vec![self] } - } + fn pre_order_iter(self) -> PreOrderIter { PreOrderIter { stack: vec![self] } } /// Obtains a verbose iterator of all the nodes rooted at the DAG, in pre-order. /// @@ -74,10 +72,7 @@ pub trait TreeLike: Clone + Sized { /// then adding a stack to manually track which items and their children have been /// yielded, you may be better off using this iterator instead. fn verbose_pre_order_iter(self) -> VerbosePreOrderIter { - VerbosePreOrderIter { - stack: vec![PreOrderIterItem::initial(self, None)], - index: 0, - } + VerbosePreOrderIter { stack: vec![PreOrderIterItem::initial(self, None)], index: 0 } } /// Obtains an iterator of all the nodes rooted at the DAG, in post order. @@ -85,10 +80,7 @@ pub trait TreeLike: Clone + Sized { /// Each node is only yielded once, at the leftmost position that it /// appears in the DAG. fn post_order_iter(self) -> PostOrderIter { - PostOrderIter { - index: 0, - stack: vec![IterStackItem::unprocessed(self, None)], - } + PostOrderIter { index: 0, stack: vec![IterStackItem::unprocessed(self, None)] } } } diff --git a/src/lib.rs b/src/lib.rs index f8930e49d..7b798915e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -151,22 +151,16 @@ 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 { /// Returns true if the pubkey is uncompressed. Defaults to `false`. - fn is_uncompressed(&self) -> bool { - false - } + fn is_uncompressed(&self) -> bool { false } /// Returns true if the pubkey is an x-only pubkey. Defaults to `false`. // This is required to know what in DescriptorPublicKey to know whether the inner // key in allowed in descriptor context - fn is_x_only_key(&self) -> bool { - false - } + fn is_x_only_key(&self) -> bool { false } /// Returns the number of different derivation paths in this key. Only >1 for keys /// in BIP389 multipath descriptors. - fn num_der_paths(&self) -> usize { - 0 - } + fn num_der_paths(&self) -> usize { 0 } /// The associated [`bitcoin::hashes::sha256::Hash`] for this [`MiniscriptKey`], used in the /// sha256 fragment. @@ -194,9 +188,7 @@ impl MiniscriptKey for bitcoin::secp256k1::PublicKey { impl MiniscriptKey for bitcoin::PublicKey { /// Returns the compressed-ness of the underlying secp256k1 key. - fn is_uncompressed(&self) -> bool { - !self.compressed - } + fn is_uncompressed(&self) -> bool { !self.compressed } type Sha256 = sha256::Hash; type Hash256 = hash256::Hash; @@ -210,9 +202,7 @@ impl MiniscriptKey for bitcoin::secp256k1::XOnlyPublicKey { type Ripemd160 = ripemd160::Hash; type Hash160 = hash160::Hash; - fn is_x_only_key(&self) -> bool { - true - } + fn is_x_only_key(&self) -> bool { true } } impl MiniscriptKey for String { @@ -258,47 +248,27 @@ pub trait ToPublicKey: MiniscriptKey { } impl ToPublicKey for bitcoin::PublicKey { - fn to_public_key(&self) -> bitcoin::PublicKey { - *self - } + fn to_public_key(&self) -> bitcoin::PublicKey { *self } - fn to_sha256(hash: &sha256::Hash) -> sha256::Hash { - *hash - } + fn to_sha256(hash: &sha256::Hash) -> sha256::Hash { *hash } - fn to_hash256(hash: &hash256::Hash) -> hash256::Hash { - *hash - } + fn to_hash256(hash: &hash256::Hash) -> hash256::Hash { *hash } - fn to_ripemd160(hash: &ripemd160::Hash) -> ripemd160::Hash { - *hash - } + fn to_ripemd160(hash: &ripemd160::Hash) -> ripemd160::Hash { *hash } - fn to_hash160(hash: &hash160::Hash) -> hash160::Hash { - *hash - } + fn to_hash160(hash: &hash160::Hash) -> hash160::Hash { *hash } } impl ToPublicKey for bitcoin::secp256k1::PublicKey { - fn to_public_key(&self) -> bitcoin::PublicKey { - bitcoin::PublicKey::new(*self) - } + fn to_public_key(&self) -> bitcoin::PublicKey { bitcoin::PublicKey::new(*self) } - fn to_sha256(hash: &sha256::Hash) -> sha256::Hash { - *hash - } + fn to_sha256(hash: &sha256::Hash) -> sha256::Hash { *hash } - fn to_hash256(hash: &hash256::Hash) -> hash256::Hash { - *hash - } + fn to_hash256(hash: &hash256::Hash) -> hash256::Hash { *hash } - fn to_ripemd160(hash: &ripemd160::Hash) -> ripemd160::Hash { - *hash - } + fn to_ripemd160(hash: &ripemd160::Hash) -> ripemd160::Hash { *hash } - fn to_hash160(hash: &hash160::Hash) -> hash160::Hash { - *hash - } + fn to_hash160(hash: &hash160::Hash) -> hash160::Hash { *hash } } impl ToPublicKey for bitcoin::secp256k1::XOnlyPublicKey { @@ -311,25 +281,15 @@ impl ToPublicKey for bitcoin::secp256k1::XOnlyPublicKey { .expect("Failed to construct 33 Publickey from 0x02 appended x-only key") } - fn to_x_only_pubkey(&self) -> bitcoin::secp256k1::XOnlyPublicKey { - *self - } + fn to_x_only_pubkey(&self) -> bitcoin::secp256k1::XOnlyPublicKey { *self } - fn to_sha256(hash: &sha256::Hash) -> sha256::Hash { - *hash - } + fn to_sha256(hash: &sha256::Hash) -> sha256::Hash { *hash } - fn to_hash256(hash: &hash256::Hash) -> hash256::Hash { - *hash - } + fn to_hash256(hash: &hash256::Hash) -> hash256::Hash { *hash } - fn to_ripemd160(hash: &ripemd160::Hash) -> ripemd160::Hash { - *hash - } + fn to_ripemd160(hash: &ripemd160::Hash) -> ripemd160::Hash { *hash } - fn to_hash160(hash: &hash160::Hash) -> hash160::Hash { - *hash - } + fn to_hash160(hash: &hash160::Hash) -> hash160::Hash { *hash } } /// Describes an object that can translate various keys and hashes from one key to the type @@ -391,9 +351,7 @@ impl TranslateErr { } impl From for TranslateErr { - fn from(v: E) -> Self { - Self::TranslatorErr(v) - } + fn from(v: E) -> Self { Self::TranslatorErr(v) } } // Required for unwrap @@ -682,64 +640,46 @@ where Pk: MiniscriptKey, Ctx: ScriptContext, { - fn from(e: miniscript::types::Error) -> Error { - Error::TypeCheck(e.to_string()) - } + fn from(e: miniscript::types::Error) -> Error { Error::TypeCheck(e.to_string()) } } #[doc(hidden)] impl From for Error { - fn from(e: policy::LiftError) -> Error { - Error::LiftError(e) - } + fn from(e: policy::LiftError) -> Error { Error::LiftError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: miniscript::context::ScriptContextError) -> Error { - Error::ContextError(e) - } + fn from(e: miniscript::context::ScriptContextError) -> Error { Error::ContextError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: miniscript::analyzable::AnalysisError) -> Error { - Error::AnalysisError(e) - } + fn from(e: miniscript::analyzable::AnalysisError) -> Error { Error::AnalysisError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::secp256k1::Error) -> Error { - Error::Secp(e) - } + fn from(e: bitcoin::secp256k1::Error) -> Error { Error::Secp(e) } } #[doc(hidden)] impl From for Error { - fn from(e: bitcoin::address::Error) -> Error { - Error::AddrError(e) - } + fn from(e: bitcoin::address::Error) -> Error { Error::AddrError(e) } } #[doc(hidden)] #[cfg(feature = "compiler")] impl From for Error { - fn from(e: crate::policy::compiler::CompilerError) -> Error { - Error::CompilerError(e) - } + fn from(e: crate::policy::compiler::CompilerError) -> Error { Error::CompilerError(e) } } #[doc(hidden)] impl From for Error { - fn from(e: policy::concrete::PolicyError) -> Error { - Error::PolicyError(e) - } + fn from(e: policy::concrete::PolicyError) -> Error { Error::PolicyError(e) } } -fn errstr(s: &str) -> Error { - Error::Unexpected(s.to_owned()) -} +fn errstr(s: &str) -> Error { Error::Unexpected(s.to_owned()) } /// The size of an encoding of a number in Script pub fn script_num_size(n: usize) -> usize { @@ -783,43 +723,31 @@ pub struct AbsLockTime(absolute::LockTime); impl AbsLockTime { /// Constructs an `AbsLockTime` from an nLockTime value or the argument to OP_CHEKCLOCKTIMEVERIFY. - pub fn from_consensus(n: u32) -> Self { - Self(absolute::LockTime::from_consensus(n)) - } + pub fn from_consensus(n: u32) -> Self { Self(absolute::LockTime::from_consensus(n)) } /// Returns the inner `u32` value. This is the value used when creating this `LockTime` /// i.e., `n OP_CHECKLOCKTIMEVERIFY` or nLockTime. /// /// This calls through to `absolute::LockTime::to_consensus_u32()` and the same usage warnings /// apply. - pub fn to_consensus_u32(self) -> u32 { - self.0.to_consensus_u32() - } + pub fn to_consensus_u32(self) -> u32 { self.0.to_consensus_u32() } /// Returns the inner `u32` value. /// /// Equivalent to `AbsLockTime::to_consensus_u32()`. - pub fn to_u32(self) -> u32 { - self.to_consensus_u32() - } + pub fn to_u32(self) -> u32 { self.to_consensus_u32() } } impl From for AbsLockTime { - fn from(lock_time: absolute::LockTime) -> Self { - Self(lock_time) - } + fn from(lock_time: absolute::LockTime) -> Self { Self(lock_time) } } impl From for absolute::LockTime { - fn from(lock_time: AbsLockTime) -> absolute::LockTime { - lock_time.0 - } + fn from(lock_time: AbsLockTime) -> absolute::LockTime { lock_time.0 } } impl cmp::PartialOrd for AbsLockTime { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl cmp::Ord for AbsLockTime { @@ -831,9 +759,7 @@ impl cmp::Ord for AbsLockTime { } impl fmt::Display for AbsLockTime { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, f) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } #[cfg(test)] @@ -911,28 +837,18 @@ mod prelude { impl Deref for MutexGuard<'_, T> { type Target = T; - fn deref(&self) -> &T { - &self.lock.deref() - } + fn deref(&self) -> &T { &self.lock.deref() } } impl DerefMut for MutexGuard<'_, T> { - fn deref_mut(&mut self) -> &mut T { - self.lock.deref_mut() - } + fn deref_mut(&mut self) -> &mut T { self.lock.deref_mut() } } impl Mutex { - pub fn new(inner: T) -> Mutex { - Mutex { - inner: RefCell::new(inner), - } - } + pub fn new(inner: T) -> Mutex { Mutex { inner: RefCell::new(inner) } } pub fn lock<'a>(&'a self) -> LockResult> { - Ok(MutexGuard { - lock: self.inner.borrow_mut(), - }) + Ok(MutexGuard { lock: self.inner.borrow_mut() }) } } } diff --git a/src/miniscript/analyzable.rs b/src/miniscript/analyzable.rs index 86b3447c0..d56a6d388 100644 --- a/src/miniscript/analyzable.rs +++ b/src/miniscript/analyzable.rs @@ -55,9 +55,7 @@ impl ExtParams { } /// Create a new ExtParams that allows all the sanity rules - pub fn sane() -> ExtParams { - ExtParams::new() - } + pub fn sane() -> ExtParams { ExtParams::new() } /// Create a new ExtParams that insanity rules /// This enables parsing well specified but "insane" miniscripts. @@ -186,26 +184,18 @@ impl error::Error for AnalysisError { impl Miniscript { /// Whether all spend paths of miniscript require a signature - pub fn requires_sig(&self) -> bool { - self.ty.mall.safe - } + pub fn requires_sig(&self) -> bool { self.ty.mall.safe } /// Whether the miniscript is malleable - pub fn is_non_malleable(&self) -> bool { - self.ty.mall.non_malleable - } + pub fn is_non_malleable(&self) -> bool { self.ty.mall.non_malleable } /// Whether the miniscript can exceed the resource limits(Opcodes, Stack limit etc) // 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 { - Ctx::check_local_validity(self).is_ok() - } + pub fn within_resource_limits(&self) -> bool { Ctx::check_local_validity(self).is_ok() } /// Whether the miniscript contains a combination of timelocks - pub fn has_mixed_timelocks(&self) -> bool { - self.ext.timelock_info.contains_unspendable_path() - } + pub fn has_mixed_timelocks(&self) -> bool { self.ext.timelock_info.contains_unspendable_path() } /// Whether the miniscript has repeated Pk or Pkh pub fn has_repeated_keys(&self) -> bool { diff --git a/src/miniscript/context.rs b/src/miniscript/context.rs index f3563b83c..342760e6c 100644 --- a/src/miniscript/context.rs +++ b/src/miniscript/context.rs @@ -102,20 +102,13 @@ impl fmt::Display for ScriptContextError { write!(f, "DupIf is malleable under Legacy rules") } ScriptContextError::CompressedOnly(ref pk) => { - write!( - f, - "Only Compressed pubkeys are allowed in segwit context. Found {}", - pk - ) + write!(f, "Only Compressed pubkeys are allowed in segwit context. Found {}", pk) } ScriptContextError::XOnlyKeysNotAllowed(ref pk, ref ctx) => { write!(f, "x-only key {} not allowed in {}", pk, ctx) } ScriptContextError::UncompressedKeysNotAllowed => { - write!( - f, - "uncompressed keys cannot be used in Taproot descriptors." - ) + write!(f, "uncompressed keys cannot be used in Taproot descriptors.") } ScriptContextError::MaxWitnessItemssExceeded { actual, limit } => write!( f, @@ -144,10 +137,7 @@ impl fmt::Display for ScriptContextError { MAX_SCRIPTSIG_SIZE scriptsig" ), ScriptContextError::ImpossibleSatisfaction => { - write!( - f, - "Impossible to satisfy Miniscript under the current context" - ) + write!(f, "Impossible to satisfy Miniscript under the current context") } ScriptContextError::TaprootMultiDisabled => { write!(f, "Invalid use of Multi node in taproot context") @@ -160,10 +150,7 @@ impl fmt::Display for ScriptContextError { ) } ScriptContextError::CheckMultiSigLimitExceeded => { - write!( - f, - "CHECkMULTISIG ('multi()' descriptor) only supports up to 20 pubkeys" - ) + write!(f, "CHECkMULTISIG ('multi()' descriptor) only supports up to 20 pubkeys") } ScriptContextError::MultiANotAllowed => { write!(f, "Multi a(CHECKSIGADD) only allowed post tapscript") @@ -394,10 +381,7 @@ impl ScriptContext for Legacy { // Only compressed and uncompressed public keys are allowed in Legacy context fn check_pk(pk: &Pk) -> Result<(), ScriptContextError> { if pk.is_x_only_key() { - Err(ScriptContextError::XOnlyKeysNotAllowed( - pk.to_string(), - Self::name_str(), - )) + Err(ScriptContextError::XOnlyKeysNotAllowed(pk.to_string(), Self::name_str())) } else { Ok(()) } @@ -475,13 +459,9 @@ impl ScriptContext for Legacy { } } - fn name_str() -> &'static str { - "Legacy/p2sh" - } + fn name_str() -> &'static str { "Legacy/p2sh" } - fn sig_type() -> SigType { - SigType::Ecdsa - } + fn sig_type() -> SigType { SigType::Ecdsa } } /// Segwitv0 ScriptContext @@ -501,10 +481,7 @@ impl ScriptContext for Segwitv0 { if pk.is_uncompressed() { Err(ScriptContextError::UncompressedKeysNotAllowed) } else if pk.is_x_only_key() { - Err(ScriptContextError::XOnlyKeysNotAllowed( - pk.to_string(), - Self::name_str(), - )) + Err(ScriptContextError::XOnlyKeysNotAllowed(pk.to_string(), Self::name_str())) } else { Ok(()) } @@ -588,17 +565,11 @@ impl ScriptContext for Segwitv0 { ms.ext.max_sat_size.map(|x| x.0) } - fn pk_len(_pk: &Pk) -> usize { - 34 - } + fn pk_len(_pk: &Pk) -> usize { 34 } - fn name_str() -> &'static str { - "Segwitv0" - } + fn name_str() -> &'static str { "Segwitv0" } - fn sig_type() -> SigType { - SigType::Ecdsa - } + fn sig_type() -> SigType { SigType::Ecdsa } } /// Tap ScriptContext @@ -672,10 +643,8 @@ impl ScriptContext for Tap { // will have it's corresponding 64 bytes signature. // sigops budget = witness_script.len() + witness.size() + 50 // Each signature will cover it's own cost(64 > 50) and thus will will never exceed the budget - if let (Some(s), Some(h)) = ( - ms.ext.exec_stack_elem_count_sat, - ms.ext.stack_elem_count_sat, - ) { + if let (Some(s), Some(h)) = (ms.ext.exec_stack_elem_count_sat, ms.ext.stack_elem_count_sat) + { if s + h > MAX_STACK_SIZE { return Err(ScriptContextError::StackSizeLimitExceeded { actual: s + h, @@ -704,17 +673,11 @@ impl ScriptContext for Tap { ms.ext.max_sat_size.map(|x| x.0) } - fn sig_type() -> SigType { - SigType::Schnorr - } + fn sig_type() -> SigType { SigType::Schnorr } - fn pk_len(_pk: &Pk) -> usize { - 33 - } + fn pk_len(_pk: &Pk) -> usize { 33 } - fn name_str() -> &'static str { - "TapscriptCtx" - } + fn name_str() -> &'static str { "TapscriptCtx" } } /// Bare ScriptContext @@ -739,10 +702,7 @@ impl ScriptContext for BareCtx { // No x-only keys in Bare context fn check_pk(pk: &Pk) -> Result<(), ScriptContextError> { if pk.is_x_only_key() { - Err(ScriptContextError::XOnlyKeysNotAllowed( - pk.to_string(), - Self::name_str(), - )) + Err(ScriptContextError::XOnlyKeysNotAllowed(pk.to_string(), Self::name_str())) } else { Ok(()) } @@ -807,13 +767,9 @@ impl ScriptContext for BareCtx { } } - fn name_str() -> &'static str { - "BareCtx" - } + fn name_str() -> &'static str { "BareCtx" } - fn sig_type() -> SigType { - SigType::Ecdsa - } + fn sig_type() -> SigType { SigType::Ecdsa } } /// "No Checks Ecdsa" Context @@ -833,9 +789,7 @@ impl ScriptContext for NoChecks { } // No checks in NoChecks - fn check_pk(_pk: &Pk) -> Result<(), ScriptContextError> { - Ok(()) - } + fn check_pk(_pk: &Pk) -> Result<(), ScriptContextError> { Ok(()) } fn check_global_policy_validity( _ms: &Miniscript, @@ -915,9 +869,7 @@ impl ScriptContext for NoChecks { Self::other_top_level_checks(ms) } - fn sig_type() -> SigType { - SigType::Ecdsa - } + fn sig_type() -> SigType { SigType::Ecdsa } } /// Private Mod to prevent downstream from implementing this public trait diff --git a/src/miniscript/decode.rs b/src/miniscript/decode.rs index 5dc532f27..fa8b98ab7 100644 --- a/src/miniscript/decode.rs +++ b/src/miniscript/decode.rs @@ -169,11 +169,7 @@ pub enum Terminal { /// `[E] [W] BOOLAND` AndB(Arc>, Arc>), /// `[various] NOTIF [various] ELSE [various] ENDIF` - AndOr( - Arc>, - Arc>, - Arc>, - ), + AndOr(Arc>, Arc>, Arc>), // Disjunctions /// `[E] [W] BOOLOR` OrB(Arc>, Arc>), @@ -213,20 +209,13 @@ struct TerminalStack(Vec TerminalStack { ///Wrapper around self.0.pop() - fn pop(&mut self) -> Option> { - self.0.pop() - } + fn pop(&mut self) -> Option> { self.0.pop() } ///reduce, type check and push a 0-arg node fn reduce0(&mut self, ms: Terminal) -> Result<(), Error> { let ty = Type::type_check(&ms)?; let ext = ExtData::type_check(&ms)?; - let ms = Miniscript { - node: ms, - ty, - ext, - phantom: PhantomData, - }; + let ms = Miniscript { node: ms, ty, ext, phantom: PhantomData }; Ctx::check_global_validity(&ms)?; self.0.push(ms); Ok(()) @@ -242,12 +231,7 @@ impl TerminalStack { let ty = Type::type_check(&wrapped_ms)?; let ext = ExtData::type_check(&wrapped_ms)?; - let ms = Miniscript { - node: wrapped_ms, - ty, - ext, - phantom: PhantomData, - }; + let ms = Miniscript { node: wrapped_ms, ty, ext, phantom: PhantomData }; Ctx::check_global_validity(&ms)?; self.0.push(ms); Ok(()) @@ -265,12 +249,7 @@ impl TerminalStack { let ty = Type::type_check(&wrapped_ms)?; let ext = ExtData::type_check(&wrapped_ms)?; - let ms = Miniscript { - node: wrapped_ms, - ty, - ext, - phantom: PhantomData, - }; + let ms = Miniscript { node: wrapped_ms, ty, ext, phantom: PhantomData }; Ctx::check_global_validity(&ms)?; self.0.push(ms); Ok(()) @@ -555,12 +534,8 @@ pub fn parse( let ty = Type::type_check(&wrapped_ms)?; let ext = ExtData::type_check(&wrapped_ms)?; - term.0.push(Miniscript { - node: wrapped_ms, - ty, - ext, - phantom: PhantomData, - }); + term.0 + .push(Miniscript { node: wrapped_ms, ty, ext, phantom: PhantomData }); } Some(NonTerm::ThreshW { n, k }) => { match_token!( diff --git a/src/miniscript/iter.rs b/src/miniscript/iter.rs index f64b350ec..1e8f016b7 100644 --- a/src/miniscript/iter.rs +++ b/src/miniscript/iter.rs @@ -18,16 +18,12 @@ 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. - pub fn iter(&self) -> Iter { - Iter::new(self) - } + pub fn iter(&self) -> Iter { Iter::new(self) } /// Creates a new [PkIter] iterator that will iterate over all plain public keys (and not /// key hash values) present in [Miniscript] items within AST by traversing all its branches. /// For the specific algorithm please see [PkIter::next] function. - pub fn iter_pk(&self) -> PkIter { - PkIter::new(self) - } + pub fn iter_pk(&self) -> PkIter { PkIter::new(self) } /// Enumerates all child nodes of the current AST node (`self`) and returns a `Vec` referencing /// them. @@ -119,10 +115,7 @@ pub struct Iter<'a, Pk: MiniscriptKey, Ctx: ScriptContext> { impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> Iter<'a, Pk, Ctx> { fn new(miniscript: &'a Miniscript) -> Self { - Iter { - next: Some(miniscript), - path: vec![], - } + Iter { next: Some(miniscript), path: vec![] } } } @@ -180,11 +173,7 @@ pub struct PkIter<'a, Pk: MiniscriptKey, Ctx: ScriptContext> { impl<'a, Pk: MiniscriptKey, Ctx: ScriptContext> PkIter<'a, Pk, Ctx> { fn new(miniscript: &'a Miniscript) -> Self { let mut iter = Iter::new(miniscript); - PkIter { - curr_node: iter.next(), - node_iter: iter, - key_index: 0, - } + PkIter { curr_node: iter.next(), node_iter: iter, key_index: 0 } } } @@ -276,12 +265,7 @@ pub mod test { (ms_str!("sha256({})", sha256_hash), vec![], vec![], false), (ms_str!("hash256({})", sha256d_hash), vec![], vec![], false), (ms_str!("hash160({})", hash160_hash), vec![], vec![], false), - ( - ms_str!("ripemd160({})", ripemd160_hash), - vec![], - vec![], - false, - ), + (ms_str!("ripemd160({})", ripemd160_hash), vec![], vec![], false), (ms_str!("c:pk_k({})", k[0]), vec![k[0]], vec![], true), (ms_str!("c:pk_h({})", k[0]), vec![k[0]], vec![], true), ( @@ -297,12 +281,7 @@ pub mod test { false, ), ( - ms_str!( - "andor(c:pk_k({}),jtv:sha256({}),c:pk_h({}))", - k[1], - sha256_hash, - k[2] - ), + ms_str!("andor(c:pk_k({}),jtv:sha256({}),c:pk_h({}))", k[1], sha256_hash, k[2]), vec![k[1], k[2]], vec![], false, diff --git a/src/miniscript/lex.rs b/src/miniscript/lex.rs index e00eb42e7..c37ed6f74 100644 --- a/src/miniscript/lex.rs +++ b/src/miniscript/lex.rs @@ -72,38 +72,26 @@ pub struct TokenIter<'s>(Vec>); impl<'s> TokenIter<'s> { /// Create a new TokenIter - pub fn new(v: Vec>) -> TokenIter<'s> { - TokenIter(v) - } + pub fn new(v: Vec>) -> TokenIter<'s> { TokenIter(v) } /// Look at the top at Iterator - pub fn peek(&self) -> Option<&'s Token> { - self.0.last() - } + pub fn peek(&self) -> Option<&'s Token> { self.0.last() } /// Push a value to the iterator /// This will be first value consumed by popun_ - pub fn un_next(&mut self, tok: Token<'s>) { - self.0.push(tok) - } + pub fn un_next(&mut self, tok: Token<'s>) { self.0.push(tok) } /// The len of the iterator - pub fn len(&self) -> usize { - self.0.len() - } + pub fn len(&self) -> usize { self.0.len() } /// Returns true if iterator is empty. - pub fn is_empty(&self) -> bool { - self.0.is_empty() - } + pub fn is_empty(&self) -> bool { self.0.is_empty() } } impl<'s> Iterator for TokenIter<'s> { type Item = Token<'s>; - fn next(&mut self) -> Option> { - self.0.pop() - } + fn next(&mut self) -> Option> { self.0.pop() } } /// Tokenize a script diff --git a/src/miniscript/mod.rs b/src/miniscript/mod.rs index 890037a26..fa75a712c 100644 --- a/src/miniscript/mod.rs +++ b/src/miniscript/mod.rs @@ -89,23 +89,14 @@ impl Miniscript { ty: types::Type, ext: types::extra_props::ExtData, ) -> Miniscript { - Miniscript { - node, - ty, - ext, - phantom: PhantomData, - } + Miniscript { node, ty, ext, phantom: PhantomData } } /// Extracts the `AstElem` representing the root of the miniscript - pub fn into_inner(self) -> Terminal { - self.node - } + pub fn into_inner(self) -> Terminal { self.node } /// Get a reference to the inner `AstElem` representing the root of miniscript - pub fn as_inner(&self) -> &Terminal { - &self.node - } + pub fn as_inner(&self) -> &Terminal { &self.node } /// Encode as a Bitcoin script pub fn encode(&self) -> script::ScriptBuf @@ -364,18 +355,14 @@ impl PartialOrd for Miniscript { /// /// The type information and extra properties are implied by the AST. impl Ord for Miniscript { - fn cmp(&self, other: &Miniscript) -> cmp::Ordering { - self.node.cmp(&other.node) - } + fn cmp(&self, other: &Miniscript) -> cmp::Ordering { self.node.cmp(&other.node) } } /// `PartialEq` of `Miniscript` must depend only on node and not the type information. /// /// The type information and extra properties are implied by the AST. impl PartialEq for Miniscript { - fn eq(&self, other: &Miniscript) -> bool { - self.node.eq(&other.node) - } + fn eq(&self, other: &Miniscript) -> bool { self.node.eq(&other.node) } } /// `Eq` of `Miniscript` must depend only on node and not the type information. @@ -387,21 +374,15 @@ impl Eq for Miniscript {} /// /// The type information and extra properties are implied by the AST. impl hash::Hash for Miniscript { - fn hash(&self, state: &mut H) { - self.node.hash(state); - } + fn hash(&self, state: &mut H) { self.node.hash(state); } } impl fmt::Debug for Miniscript { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{:?}", self.node) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{:?}", self.node) } } impl fmt::Display for Miniscript { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{}", self.node) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self.node) } } impl ForEachKey for Miniscript { @@ -877,10 +858,7 @@ mod tests { roundtrip(&ms_str!("1"), "OP_PUSHNUM_1"); roundtrip(&ms_str!("tv:1"), "OP_PUSHNUM_1 OP_VERIFY OP_PUSHNUM_1"); roundtrip(&ms_str!("0"), "OP_0"); - roundtrip( - &ms_str!("andor(0,1,0)"), - "OP_0 OP_NOTIF OP_0 OP_ELSE OP_PUSHNUM_1 OP_ENDIF", - ); + roundtrip(&ms_str!("andor(0,1,0)"), "OP_0 OP_NOTIF OP_0 OP_ELSE OP_PUSHNUM_1 OP_ENDIF"); assert!(Segwitv0Script::from_str("1()").is_err()); assert!(Segwitv0Script::from_str("tv:1()").is_err()); @@ -1030,14 +1008,7 @@ mod tests { ); roundtrip( - &ms_str!( - "multi(3,{},{},{},{},{})", - keys[0], - keys[1], - keys[2], - keys[3], - keys[4] - ), + &ms_str!("multi(3,{},{},{},{},{})", keys[0], keys[1], keys[2], keys[3], keys[4]), "OP_PUSHNUM_3 \ OP_PUSHBYTES_33 028c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa \ OP_PUSHBYTES_33 03ab1ac1872a38a2f196bed5a6047f0da2c8130fe8de49fc4d5dfb201f7611d8e2 \ @@ -1302,32 +1273,19 @@ mod tests { // ms, absolute_timelock, relative_timelock let test_cases = vec![ + (format!("t:or_c(pk({}),v:pkh({}))", key_present, key_missing), None, None), ( - format!("t:or_c(pk({}),v:pkh({}))", key_present, key_missing), - None, - None, - ), - ( - format!( - "thresh(2,pk({}),s:pk({}),snl:after(1))", - key_present, key_missing - ), + format!("thresh(2,pk({}),s:pk({}),snl:after(1))", key_present, key_missing), Some(AbsLockTime::from_consensus(1)), None, ), ( - format!( - "or_d(pk({}),and_v(v:pk({}),older(12960)))", - key_present, key_missing - ), + format!("or_d(pk({}),and_v(v:pk({}),older(12960)))", key_present, key_missing), None, None, ), ( - format!( - "or_d(pk({}),and_v(v:pk({}),older(12960)))", - key_missing, key_present - ), + format!("or_d(pk({}),and_v(v:pk({}),older(12960)))", key_missing, key_present), None, Some(bitcoin::Sequence(12960)), ), @@ -1374,13 +1332,9 @@ mod tests { } } - fn check_older(&self, _: bitcoin::Sequence) -> bool { - true - } + fn check_older(&self, _: bitcoin::Sequence) -> bool { true } - fn check_after(&self, _: bitcoin::absolute::LockTime) -> bool { - true - } + fn check_after(&self, _: bitcoin::absolute::LockTime) -> bool { true } } let schnorr_sig = secp256k1::schnorr::Signature::from_str("84526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f0784526253c27c7aef56c7b71a5cd25bebb66dddda437826defc5b2568bde81f07").unwrap(); diff --git a/src/miniscript/satisfy.rs b/src/miniscript/satisfy.rs index a0641b04b..68ae90429 100644 --- a/src/miniscript/satisfy.rs +++ b/src/miniscript/satisfy.rs @@ -28,14 +28,10 @@ pub type Preimage32 = [u8; 32]; /// have data for. pub trait Satisfier { /// Given a public key, look up an ECDSA signature with that key - fn lookup_ecdsa_sig(&self, _: &Pk) -> Option { - None - } + fn lookup_ecdsa_sig(&self, _: &Pk) -> Option { None } /// Lookup the tap key spend sig - fn lookup_tap_key_spend_sig(&self) -> Option { - None - } + fn lookup_tap_key_spend_sig(&self) -> Option { None } /// Given a public key and a associated leaf hash, look up an schnorr signature with that key fn lookup_tap_leaf_script_sig( @@ -54,14 +50,10 @@ pub trait Satisfier { } /// Given a raw `Pkh`, lookup corresponding [`bitcoin::PublicKey`] - fn lookup_raw_pkh_pk(&self, _: &hash160::Hash) -> Option { - None - } + fn lookup_raw_pkh_pk(&self, _: &hash160::Hash) -> Option { None } /// Given a raw `Pkh`, lookup corresponding [`bitcoin::secp256k1::XOnlyPublicKey`] - fn lookup_raw_pkh_x_only_pk(&self, _: &hash160::Hash) -> Option { - None - } + fn lookup_raw_pkh_x_only_pk(&self, _: &hash160::Hash) -> Option { None } /// Given a keyhash, look up the EC signature and the associated key /// Even if signatures for public key Hashes are not available, the users @@ -86,42 +78,30 @@ pub trait Satisfier { } /// Given a SHA256 hash, look up its preimage - fn lookup_sha256(&self, _: &Pk::Sha256) -> Option { - None - } + fn lookup_sha256(&self, _: &Pk::Sha256) -> Option { None } /// Given a HASH256 hash, look up its preimage - fn lookup_hash256(&self, _: &Pk::Hash256) -> Option { - None - } + fn lookup_hash256(&self, _: &Pk::Hash256) -> Option { None } /// Given a RIPEMD160 hash, look up its preimage - fn lookup_ripemd160(&self, _: &Pk::Ripemd160) -> Option { - None - } + fn lookup_ripemd160(&self, _: &Pk::Ripemd160) -> Option { None } /// Given a HASH160 hash, look up its preimage - fn lookup_hash160(&self, _: &Pk::Hash160) -> Option { - None - } + fn lookup_hash160(&self, _: &Pk::Hash160) -> Option { None } /// Assert whether an relative locktime is satisfied /// /// NOTE: If a descriptor mixes time-based and height-based timelocks, the implementation of /// this method MUST only allow timelocks of either unit, but not both. Allowing both could cause /// miniscript to construct an invalid witness. - fn check_older(&self, _: Sequence) -> bool { - false - } + fn check_older(&self, _: Sequence) -> bool { false } /// Assert whether a absolute locktime is satisfied /// /// NOTE: If a descriptor mixes time-based and height-based timelocks, the implementation of /// this method MUST only allow timelocks of either unit, but not both. Allowing both could cause /// miniscript to construct an invalid witness. - fn check_after(&self, _: absolute::LockTime) -> bool { - false - } + fn check_after(&self, _: absolute::LockTime) -> bool { false } } // Allow use of `()` as a "no conditions available" satisfier @@ -333,29 +313,19 @@ impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier> Satisfier for &' (**self).lookup_tap_control_block_map() } - fn lookup_sha256(&self, h: &Pk::Sha256) -> Option { - (**self).lookup_sha256(h) - } + fn lookup_sha256(&self, h: &Pk::Sha256) -> Option { (**self).lookup_sha256(h) } - fn lookup_hash256(&self, h: &Pk::Hash256) -> Option { - (**self).lookup_hash256(h) - } + fn lookup_hash256(&self, h: &Pk::Hash256) -> Option { (**self).lookup_hash256(h) } fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option { (**self).lookup_ripemd160(h) } - fn lookup_hash160(&self, h: &Pk::Hash160) -> Option { - (**self).lookup_hash160(h) - } + fn lookup_hash160(&self, h: &Pk::Hash160) -> Option { (**self).lookup_hash160(h) } - fn check_older(&self, t: Sequence) -> bool { - (**self).check_older(t) - } + fn check_older(&self, t: Sequence) -> bool { (**self).check_older(t) } - fn check_after(&self, n: absolute::LockTime) -> bool { - (**self).check_after(n) - } + fn check_after(&self, n: absolute::LockTime) -> bool { (**self).check_after(n) } } impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier> Satisfier for &'a mut S { @@ -403,29 +373,19 @@ impl<'a, Pk: MiniscriptKey + ToPublicKey, S: Satisfier> Satisfier for &' (**self).lookup_tap_control_block_map() } - fn lookup_sha256(&self, h: &Pk::Sha256) -> Option { - (**self).lookup_sha256(h) - } + fn lookup_sha256(&self, h: &Pk::Sha256) -> Option { (**self).lookup_sha256(h) } - fn lookup_hash256(&self, h: &Pk::Hash256) -> Option { - (**self).lookup_hash256(h) - } + fn lookup_hash256(&self, h: &Pk::Hash256) -> Option { (**self).lookup_hash256(h) } fn lookup_ripemd160(&self, h: &Pk::Ripemd160) -> Option { (**self).lookup_ripemd160(h) } - fn lookup_hash160(&self, h: &Pk::Hash160) -> Option { - (**self).lookup_hash160(h) - } + fn lookup_hash160(&self, h: &Pk::Hash160) -> Option { (**self).lookup_hash160(h) } - fn check_older(&self, t: Sequence) -> bool { - (**self).check_older(t) - } + fn check_older(&self, t: Sequence) -> bool { (**self).check_older(t) } - fn check_after(&self, n: absolute::LockTime) -> bool { - (**self).check_after(n) - } + fn check_after(&self, n: absolute::LockTime) -> bool { (**self).check_after(n) } } macro_rules! impl_tuple_satisfier { @@ -760,9 +720,7 @@ pub enum Witness { } impl PartialOrd for Witness> { - fn partial_cmp(&self, other: &Self) -> Option { - Some(self.cmp(other)) - } + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for Witness> { @@ -803,9 +761,7 @@ impl Witness> { match sat.provider_lookup_tap_leaf_script_sig(pk, leaf_hash) { Some(size) => Witness::Stack(vec![Placeholder::SchnorrSigPk( pk.clone(), - SchnorrSigType::ScriptSpend { - leaf_hash: *leaf_hash, - }, + SchnorrSigType::ScriptSpend { leaf_hash: *leaf_hash }, size, )]), // Signatures cannot be forged @@ -903,24 +859,16 @@ impl Witness> { impl Witness> { /// Produce something like a 32-byte 0 push - fn hash_dissatisfaction() -> Self { - Witness::Stack(vec![Placeholder::HashDissatisfaction]) - } + fn hash_dissatisfaction() -> Self { Witness::Stack(vec![Placeholder::HashDissatisfaction]) } /// Construct a satisfaction equivalent to an empty stack - fn empty() -> Self { - Witness::Stack(vec![]) - } + fn empty() -> Self { Witness::Stack(vec![]) } /// Construct a satisfaction equivalent to `OP_1` - fn push_1() -> Self { - Witness::Stack(vec![Placeholder::PushOne]) - } + fn push_1() -> Self { Witness::Stack(vec![Placeholder::PushOne]) } /// Construct a satisfaction equivalent to a single empty push - fn push_0() -> Self { - Witness::Stack(vec![Placeholder::PushZero]) - } + fn push_0() -> Self { Witness::Stack(vec![Placeholder::PushZero]) } /// Concatenate, or otherwise combine, two satisfactions fn combine(one: Self, two: Self) -> Self { @@ -1115,9 +1063,9 @@ impl Satisfaction> { .iter() .filter_map(|sat| sat.absolute_timelock) .max(), - stack: ret_stack.into_iter().fold(Witness::empty(), |acc, next| { - Witness::combine(next.stack, acc) - }), + stack: ret_stack + .into_iter() + .fold(Witness::empty(), |acc, next| Witness::combine(next.stack, acc)), } } } @@ -1200,9 +1148,9 @@ impl Satisfaction> { .iter() .filter_map(|sat| sat.absolute_timelock) .max(), - stack: ret_stack.into_iter().fold(Witness::empty(), |acc, next| { - Witness::combine(next.stack, acc) - }), + stack: ret_stack + .into_iter() + .fold(Witness::empty(), |acc, next| Witness::combine(next.stack, acc)), } } @@ -1344,12 +1292,7 @@ impl Satisfaction> { } else { (Witness::Unavailable, None) }; - Satisfaction { - stack, - has_sig: false, - relative_timelock: None, - absolute_timelock, - } + Satisfaction { stack, has_sig: false, relative_timelock: None, absolute_timelock } } Terminal::Older(t) => { let (stack, relative_timelock) = if stfr.check_older(t) { @@ -1364,12 +1307,7 @@ impl Satisfaction> { } else { (Witness::Unavailable, None) }; - Satisfaction { - stack, - has_sig: false, - relative_timelock, - absolute_timelock: None, - } + Satisfaction { stack, has_sig: false, relative_timelock, absolute_timelock: None } } Terminal::Ripemd160(ref h) => Satisfaction { stack: Witness::ripemd160_preimage(stfr, h), @@ -1861,12 +1799,7 @@ impl Satisfaction> { /// Try creating the final witness using a [`Satisfier`] pub fn try_completing>(&self, stfr: &Sat) -> Option>> { - let Satisfaction { - stack, - has_sig, - relative_timelock, - absolute_timelock, - } = self; + let Satisfaction { stack, has_sig, relative_timelock, absolute_timelock } = self; let stack = match stack { Witness::Stack(stack) => Witness::Stack( stack diff --git a/src/miniscript/types/correctness.rs b/src/miniscript/types/correctness.rs index a4c3b2fa9..74b6b62ce 100644 --- a/src/miniscript/types/correctness.rs +++ b/src/miniscript/types/correctness.rs @@ -114,30 +114,15 @@ impl Property for Correctness { } fn from_true() -> Self { - Correctness { - base: Base::B, - input: Input::Zero, - dissatisfiable: false, - unit: true, - } + Correctness { base: Base::B, input: Input::Zero, dissatisfiable: false, unit: true } } fn from_false() -> Self { - Correctness { - base: Base::B, - input: Input::Zero, - dissatisfiable: true, - unit: true, - } + Correctness { base: Base::B, input: Input::Zero, dissatisfiable: true, unit: true } } fn from_pk_k() -> Self { - Correctness { - base: Base::K, - input: Input::OneNonZero, - dissatisfiable: true, - unit: true, - } + Correctness { base: Base::K, input: Input::OneNonZero, dissatisfiable: true, unit: true } } fn from_pk_h() -> Self { @@ -150,39 +135,19 @@ impl Property for Correctness { } fn from_multi(_: usize, _: usize) -> Self { - Correctness { - base: Base::B, - input: Input::AnyNonZero, - dissatisfiable: true, - unit: true, - } + Correctness { base: Base::B, input: Input::AnyNonZero, dissatisfiable: true, unit: true } } fn from_multi_a(_: usize, _: usize) -> Self { - Correctness { - base: Base::B, - input: Input::Any, - dissatisfiable: true, - unit: true, - } + Correctness { base: Base::B, input: Input::Any, dissatisfiable: true, unit: true } } fn from_hash() -> Self { - Correctness { - base: Base::B, - input: Input::OneNonZero, - dissatisfiable: true, - unit: true, - } + Correctness { base: Base::B, input: Input::OneNonZero, dissatisfiable: true, unit: true } } fn from_time(_: u32) -> Self { - Correctness { - base: Base::B, - input: Input::Zero, - dissatisfiable: false, - unit: false, - } + Correctness { base: Base::B, input: Input::Zero, dissatisfiable: false, unit: false } } fn cast_alt(self) -> Result { diff --git a/src/miniscript/types/extra_props.rs b/src/miniscript/types/extra_props.rs index 71f3a2714..d527caea6 100644 --- a/src/miniscript/types/extra_props.rs +++ b/src/miniscript/types/extra_props.rs @@ -43,24 +43,16 @@ pub struct OpLimits { impl OpLimits { /// Creates a new instance of [`OpLimits`] pub fn new(op_static: usize, op_sat: Option, op_nsat: Option) -> Self { - OpLimits { - count: op_static, - sat: op_sat, - nsat: op_nsat, - } + OpLimits { count: op_static, sat: op_sat, nsat: op_nsat } } /// Worst case opcode count when this element is satisfied - pub fn op_count(&self) -> Option { - opt_add(Some(self.count), self.sat) - } + pub fn op_count(&self) -> Option { opt_add(Some(self.count), self.sat) } } impl TimelockInfo { /// Returns true if the current `TimelockInfo` contains any possible unspendable paths. - pub fn contains_unspendable_path(self) -> bool { - self.contains_combination - } + pub fn contains_unspendable_path(self) -> bool { self.contains_combination } /// Combines two `TimelockInfo` structs setting `contains_combination` if required (logical and). pub(crate) fn combine_and(a: Self, b: Self) -> Self { @@ -335,9 +327,7 @@ impl Property for ExtData { } } - fn from_time(_t: u32) -> Self { - unreachable!() - } + fn from_time(_t: u32) -> Self { unreachable!() } fn from_after(t: absolute::LockTime) -> Self { ExtData { @@ -535,11 +525,7 @@ impl Property for ExtData { Ok(ExtData { pk_cost: l.pk_cost + r.pk_cost, has_free_verify: r.has_free_verify, - ops: OpLimits::new( - l.ops.count + r.ops.count, - opt_add(l.ops.sat, r.ops.sat), - None, - ), + ops: OpLimits::new(l.ops.count + r.ops.count, opt_add(l.ops.sat, r.ops.sat), None), stack_elem_count_sat: l .stack_elem_count_sat .and_then(|l| r.stack_elem_count_sat.map(|r| l + r)), @@ -564,10 +550,7 @@ impl Property for ExtData { has_free_verify: false, ops: OpLimits::new( l.ops.count + r.ops.count + 1, - cmp::max( - opt_add(l.ops.sat, r.ops.nsat), - opt_add(l.ops.nsat, r.ops.sat), - ), + cmp::max(opt_add(l.ops.sat, r.ops.nsat), opt_add(l.ops.nsat, r.ops.sat)), opt_add(l.ops.nsat, r.ops.nsat), ), stack_elem_count_sat: cmp::max( @@ -590,14 +573,8 @@ impl Property for ExtData { .and_then(|(lw, ls)| r.max_dissat_size.map(|(rw, rs)| (lw + rw, ls + rs))), timelock_info: TimelockInfo::combine_or(l.timelock_info, r.timelock_info), exec_stack_elem_count_sat: cmp::max( - opt_max( - l.exec_stack_elem_count_sat, - r.exec_stack_elem_count_dissat.map(|x| x + 1), - ), - opt_max( - l.exec_stack_elem_count_dissat, - r.exec_stack_elem_count_sat.map(|x| x + 1), - ), + opt_max(l.exec_stack_elem_count_sat, r.exec_stack_elem_count_dissat.map(|x| x + 1)), + opt_max(l.exec_stack_elem_count_dissat, r.exec_stack_elem_count_sat.map(|x| x + 1)), ), exec_stack_elem_count_dissat: opt_max( l.exec_stack_elem_count_dissat, @@ -726,10 +703,7 @@ impl Property for ExtData { has_free_verify: false, ops: OpLimits::new( a.ops.count + b.ops.count + c.ops.count + 3, - cmp::max( - opt_add(a.ops.sat, b.ops.sat), - opt_add(a.ops.nsat, c.ops.sat), - ), + cmp::max(opt_add(a.ops.sat, b.ops.sat), opt_add(a.ops.nsat, c.ops.sat)), opt_add(a.ops.nsat, c.ops.nsat), ), stack_elem_count_sat: cmp::max( @@ -806,14 +780,10 @@ impl Property for ExtData { let sub_nsat = sub.ops.nsat.expect("Thresh children must be d"); ops_count_nsat_sum += sub_nsat; ops_count_sat_vec.push((sub.ops.sat, sub_nsat)); - exec_stack_elem_count_sat_vec.push(( - sub.exec_stack_elem_count_sat, - sub.exec_stack_elem_count_dissat, - )); - exec_stack_elem_count_dissat = opt_max( - exec_stack_elem_count_dissat, - sub.exec_stack_elem_count_dissat, - ); + exec_stack_elem_count_sat_vec + .push((sub.exec_stack_elem_count_sat, sub.exec_stack_elem_count_dissat)); + exec_stack_elem_count_dissat = + opt_max(exec_stack_elem_count_dissat, sub.exec_stack_elem_count_dissat); } stack_elem_count_sat_vec.sort_by(sat_minus_option_dissat); @@ -908,10 +878,7 @@ impl Property for ExtData { Pk: MiniscriptKey, { let wrap_err = |result: Result| { - result.map_err(|kind| Error { - fragment: fragment.clone(), - error: kind, - }) + result.map_err(|kind| Error { fragment: fragment.clone(), error: kind }) }; let ret = match *fragment { @@ -1022,10 +989,7 @@ impl Property for ExtData { let res = Self::threshold(k, subs.len(), |n| Ok(subs[n].ext)); - res.map_err(|kind| Error { - fragment: fragment.clone(), - error: kind, - }) + res.map_err(|kind| Error { fragment: fragment.clone(), error: kind }) } }; if let Ok(ref ret) = ret { @@ -1083,9 +1047,7 @@ fn opt_max(a: Option, b: Option) -> Option { } /// Returns Some(x+y) is both x and y are Some. Otherwise, returns `None`. -fn opt_add(a: Option, b: Option) -> Option { - a.and_then(|x| b.map(|y| x + y)) -} +fn opt_add(a: Option, b: Option) -> Option { a.and_then(|x| b.map(|y| x + y)) } /// Returns Some((x0+y0, x1+y1)) is both x and y are Some. Otherwise, returns `None`. fn opt_tuple_add(a: Option<(usize, usize)>, b: Option<(usize, usize)>) -> Option<(usize, usize)> { diff --git a/src/miniscript/types/malleability.rs b/src/miniscript/types/malleability.rs index d1b8e4dba..a0bc53122 100644 --- a/src/miniscript/types/malleability.rs +++ b/src/miniscript/types/malleability.rs @@ -68,80 +68,42 @@ impl Malleability { impl Property for Malleability { fn from_true() -> Self { - Malleability { - dissat: Dissat::None, - safe: false, - non_malleable: true, - } + Malleability { dissat: Dissat::None, safe: false, non_malleable: true } } fn from_false() -> Self { - Malleability { - dissat: Dissat::Unique, - safe: true, - non_malleable: true, - } + Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } } fn from_pk_k() -> Self { - Malleability { - dissat: Dissat::Unique, - safe: true, - non_malleable: true, - } + Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } } fn from_pk_h() -> Self { - Malleability { - dissat: Dissat::Unique, - safe: true, - non_malleable: true, - } + Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } } fn from_multi(_: usize, _: usize) -> Self { - Malleability { - dissat: Dissat::Unique, - safe: true, - non_malleable: true, - } + Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } } fn from_multi_a(_: usize, _: usize) -> Self { - Malleability { - dissat: Dissat::Unique, - safe: true, - non_malleable: true, - } + Malleability { dissat: Dissat::Unique, safe: true, non_malleable: true } } fn from_hash() -> Self { - Malleability { - dissat: Dissat::Unknown, - safe: false, - non_malleable: true, - } + Malleability { dissat: Dissat::Unknown, safe: false, non_malleable: true } } fn from_time(_: u32) -> Self { - Malleability { - dissat: Dissat::None, - safe: false, - non_malleable: true, - } + Malleability { dissat: Dissat::None, safe: false, non_malleable: true } } - fn cast_alt(self) -> Result { - Ok(self) - } + fn cast_alt(self) -> Result { Ok(self) } - fn cast_swap(self) -> Result { - Ok(self) - } + fn cast_swap(self) -> Result { Ok(self) } - fn cast_check(self) -> Result { - Ok(self) - } + fn cast_check(self) -> Result { Ok(self) } fn cast_dupif(self) -> Result { Ok(Malleability { @@ -175,9 +137,7 @@ impl Property for Malleability { }) } - fn cast_zeronotequal(self) -> Result { - Ok(self) - } + fn cast_zeronotequal(self) -> Result { Ok(self) } fn cast_true(self) -> Result { Ok(Malleability { diff --git a/src/miniscript/types/mod.rs b/src/miniscript/types/mod.rs index e4d8120fb..e95585c9b 100644 --- a/src/miniscript/types/mod.rs +++ b/src/miniscript/types/mod.rs @@ -200,9 +200,7 @@ impl fmt::Display for Error { #[cfg(feature = "std")] impl error::Error for Error { - fn cause(&self) -> Option<&dyn error::Error> { - None - } + fn cause(&self) -> Option<&dyn error::Error> { None } } /// Structure representing the type of a Miniscript fragment, including all @@ -256,42 +254,30 @@ pub trait Property: Sized { /// Type property of a `Sha256` hash. Default implementation simply /// passes through to `from_hash` - fn from_sha256() -> Self { - Self::from_hash() - } + fn from_sha256() -> Self { Self::from_hash() } /// Type property of a `Hash256` hash. Default implementation simply /// passes through to `from_hash` - fn from_hash256() -> Self { - Self::from_hash() - } + fn from_hash256() -> Self { Self::from_hash() } /// Type property of a `Ripemd160` hash. Default implementation simply /// passes through to `from_hash` - fn from_ripemd160() -> Self { - Self::from_hash() - } + fn from_ripemd160() -> Self { Self::from_hash() } /// Type property of a `Hash160` hash. Default implementation simply /// passes through to `from_hash` - fn from_hash160() -> Self { - Self::from_hash() - } + fn from_hash160() -> Self { Self::from_hash() } /// Type property of a timelock fn from_time(t: u32) -> Self; /// Type property of an absolute timelock. Default implementation simply /// passes through to `from_time` - fn from_after(t: absolute::LockTime) -> Self { - Self::from_time(t.to_consensus_u32()) - } + fn from_after(t: absolute::LockTime) -> Self { Self::from_time(t.to_consensus_u32()) } /// Type property of a relative timelock. Default implementation simply /// passes through to `from_time` - fn from_older(t: Sequence) -> Self { - Self::from_time(t.to_consensus_u32()) - } + fn from_older(t: Sequence) -> Self { Self::from_time(t.to_consensus_u32()) } /// Cast using the `Alt` wrapper fn cast_alt(self) -> Result; @@ -315,24 +301,18 @@ pub trait Property: Sized { fn cast_zeronotequal(self) -> Result; /// Cast by changing `[X]` to `AndV([X], True)` - fn cast_true(self) -> Result { - Self::and_v(self, Self::from_true()) - } + fn cast_true(self) -> Result { Self::and_v(self, Self::from_true()) } /// Cast by changing `[X]` to `or_i([X], 0)` or `or_i(0, [X])` fn cast_or_i_false(self) -> Result; /// Cast by changing `[X]` to `or_i([X], 0)`. Default implementation /// simply passes through to `cast_or_i_false` - fn cast_unlikely(self) -> Result { - Self::or_i(self, Self::from_false()) - } + fn cast_unlikely(self) -> Result { Self::or_i(self, Self::from_false()) } /// Cast by changing `[X]` to `or_i(0, [X])`. Default implementation /// simply passes through to `cast_or_i_false` - fn cast_likely(self) -> Result { - Self::or_i(Self::from_false(), self) - } + fn cast_likely(self) -> Result { Self::or_i(Self::from_false(), self) } /// Computes the type of an `AndB` fragment fn and_b(left: Self, right: Self) -> Result; @@ -378,10 +358,7 @@ pub trait Property: Sized { Ctx: ScriptContext, { let wrap_err = |result: Result| { - result.map_err(|kind| Error { - fragment: fragment.clone(), - error: kind, - }) + result.map_err(|kind| Error { fragment: fragment.clone(), error: kind }) }; let ret = match *fragment { @@ -546,130 +523,70 @@ impl Property for Type { debug_assert!(self.mall.non_malleable || self.corr.input != Input::Zero); } - fn from_true() -> Self { - Type { - corr: Property::from_true(), - mall: Property::from_true(), - } - } + fn from_true() -> Self { Type { corr: Property::from_true(), mall: Property::from_true() } } - fn from_false() -> Self { - Type { - corr: Property::from_false(), - mall: Property::from_false(), - } - } + fn from_false() -> Self { Type { corr: Property::from_false(), mall: Property::from_false() } } fn from_pk_k() -> Self { - Type { - corr: Property::from_pk_k::(), - mall: Property::from_pk_k::(), - } + Type { corr: Property::from_pk_k::(), mall: Property::from_pk_k::() } } fn from_pk_h() -> Self { - Type { - corr: Property::from_pk_h::(), - mall: Property::from_pk_h::(), - } + Type { corr: Property::from_pk_h::(), mall: Property::from_pk_h::() } } fn from_multi(k: usize, n: usize) -> Self { - Type { - corr: Property::from_multi(k, n), - mall: Property::from_multi(k, n), - } + Type { corr: Property::from_multi(k, n), mall: Property::from_multi(k, n) } } fn from_multi_a(k: usize, n: usize) -> Self { - Type { - corr: Property::from_multi_a(k, n), - mall: Property::from_multi_a(k, n), - } + Type { corr: Property::from_multi_a(k, n), mall: Property::from_multi_a(k, n) } } - fn from_hash() -> Self { - Type { - corr: Property::from_hash(), - mall: Property::from_hash(), - } - } + fn from_hash() -> Self { Type { corr: Property::from_hash(), mall: Property::from_hash() } } fn from_sha256() -> Self { - Type { - corr: Property::from_sha256(), - mall: Property::from_sha256(), - } + Type { corr: Property::from_sha256(), mall: Property::from_sha256() } } fn from_hash256() -> Self { - Type { - corr: Property::from_hash256(), - mall: Property::from_hash256(), - } + Type { corr: Property::from_hash256(), mall: Property::from_hash256() } } fn from_ripemd160() -> Self { - Type { - corr: Property::from_ripemd160(), - mall: Property::from_ripemd160(), - } + Type { corr: Property::from_ripemd160(), mall: Property::from_ripemd160() } } fn from_hash160() -> Self { - Type { - corr: Property::from_hash160(), - mall: Property::from_hash160(), - } + Type { corr: Property::from_hash160(), mall: Property::from_hash160() } } fn from_time(t: u32) -> Self { - Type { - corr: Property::from_time(t), - mall: Property::from_time(t), - } + Type { corr: Property::from_time(t), mall: Property::from_time(t) } } fn from_after(t: absolute::LockTime) -> Self { - Type { - corr: Property::from_after(t), - mall: Property::from_after(t), - } + Type { corr: Property::from_after(t), mall: Property::from_after(t) } } fn from_older(t: Sequence) -> Self { - Type { - corr: Property::from_older(t), - mall: Property::from_older(t), - } + Type { corr: Property::from_older(t), mall: Property::from_older(t) } } fn cast_alt(self) -> Result { - Ok(Type { - corr: Property::cast_alt(self.corr)?, - mall: Property::cast_alt(self.mall)?, - }) + Ok(Type { corr: Property::cast_alt(self.corr)?, mall: Property::cast_alt(self.mall)? }) } fn cast_swap(self) -> Result { - Ok(Type { - corr: Property::cast_swap(self.corr)?, - mall: Property::cast_swap(self.mall)?, - }) + Ok(Type { corr: Property::cast_swap(self.corr)?, mall: Property::cast_swap(self.mall)? }) } fn cast_check(self) -> Result { - Ok(Type { - corr: Property::cast_check(self.corr)?, - mall: Property::cast_check(self.mall)?, - }) + Ok(Type { corr: Property::cast_check(self.corr)?, mall: Property::cast_check(self.mall)? }) } fn cast_dupif(self) -> Result { - Ok(Type { - corr: Property::cast_dupif(self.corr)?, - mall: Property::cast_dupif(self.mall)?, - }) + Ok(Type { corr: Property::cast_dupif(self.corr)?, mall: Property::cast_dupif(self.mall)? }) } fn cast_verify(self) -> Result { @@ -694,10 +611,7 @@ impl Property for Type { } fn cast_true(self) -> Result { - Ok(Type { - corr: Property::cast_true(self.corr)?, - mall: Property::cast_true(self.mall)?, - }) + Ok(Type { corr: Property::cast_true(self.corr)?, mall: Property::cast_true(self.mall)? }) } fn cast_or_i_false(self) -> Result { @@ -800,10 +714,7 @@ impl Property for Type { Ctx: ScriptContext, { let wrap_err = |result: Result| { - result.map_err(|kind| Error { - fragment: fragment.clone(), - error: kind, - }) + result.map_err(|kind| Error { fragment: fragment.clone(), error: kind }) }; let ret = match *fragment { @@ -914,10 +825,7 @@ impl Property for Type { let res = Self::threshold(k, subs.len(), |n| Ok(subs[n].ty)); - res.map_err(|kind| Error { - fragment: fragment.clone(), - error: kind, - }) + res.map_err(|kind| Error { fragment: fragment.clone(), error: kind }) } }; if let Ok(ref ret) = ret { diff --git a/src/plan.rs b/src/plan.rs index a3c75860b..32e9aa75d 100644 --- a/src/plan.rs +++ b/src/plan.rs @@ -45,20 +45,14 @@ use crate::{DefiniteDescriptorKey, DescriptorPublicKey, Error, MiniscriptKey, To /// All the methods have a default implementation that returns `false` or `None`. pub trait AssetProvider { /// Given a public key, look up an ECDSA signature with that key, return whether we found it - fn provider_lookup_ecdsa_sig(&self, _: &Pk) -> bool { - false - } + fn provider_lookup_ecdsa_sig(&self, _: &Pk) -> bool { false } /// Lookup the tap key spend sig and return its size - fn provider_lookup_tap_key_spend_sig(&self, _: &Pk) -> Option { - None - } + fn provider_lookup_tap_key_spend_sig(&self, _: &Pk) -> Option { None } /// Given a public key and a associated leaf hash, look up a schnorr signature with that key /// and return its size - fn provider_lookup_tap_leaf_script_sig(&self, _: &Pk, _: &TapLeafHash) -> Option { - None - } + fn provider_lookup_tap_leaf_script_sig(&self, _: &Pk, _: &TapLeafHash) -> Option { None } /// Obtain a reference to the control block for a ver and script fn provider_lookup_tap_control_block_map( @@ -68,9 +62,7 @@ pub trait AssetProvider { } /// Given a raw `Pkh`, lookup corresponding [`bitcoin::PublicKey`] - fn provider_lookup_raw_pkh_pk(&self, _: &hash160::Hash) -> Option { - None - } + fn provider_lookup_raw_pkh_pk(&self, _: &hash160::Hash) -> Option { None } /// Given a raw `Pkh`, lookup corresponding [`bitcoin::secp256k1::XOnlyPublicKey`] fn provider_lookup_raw_pkh_x_only_pk(&self, _: &hash160::Hash) -> Option { @@ -99,34 +91,22 @@ pub trait AssetProvider { } /// Given a SHA256 hash, look up its preimage, return whether we found it - fn provider_lookup_sha256(&self, _: &Pk::Sha256) -> bool { - false - } + fn provider_lookup_sha256(&self, _: &Pk::Sha256) -> bool { false } /// Given a HASH256 hash, look up its preimage, return whether we found it - fn provider_lookup_hash256(&self, _: &Pk::Hash256) -> bool { - false - } + fn provider_lookup_hash256(&self, _: &Pk::Hash256) -> bool { false } /// Given a RIPEMD160 hash, look up its preimage, return whether we found it - fn provider_lookup_ripemd160(&self, _: &Pk::Ripemd160) -> bool { - false - } + fn provider_lookup_ripemd160(&self, _: &Pk::Ripemd160) -> bool { false } /// Given a HASH160 hash, look up its preimage, return whether we found it - fn provider_lookup_hash160(&self, _: &Pk::Hash160) -> bool { - false - } + fn provider_lookup_hash160(&self, _: &Pk::Hash160) -> bool { false } /// Assert whether a relative locktime is satisfied - fn check_older(&self, _: Sequence) -> bool { - false - } + fn check_older(&self, _: Sequence) -> bool { false } /// Assert whether an absolute locktime is satisfied - fn check_after(&self, _: LockTime) -> bool { - false - } + fn check_after(&self, _: LockTime) -> bool { false } } /// Wrapper around [`Assets`] that logs every query and value returned @@ -229,13 +209,9 @@ where Satisfier::lookup_hash160(self, hash).is_some() } - fn check_older(&self, s: Sequence) -> bool { - Satisfier::check_older(self, s) - } + fn check_older(&self, s: Sequence) -> bool { Satisfier::check_older(self, s) } - fn check_after(&self, l: LockTime) -> bool { - Satisfier::check_after(self, l) - } + fn check_after(&self, l: LockTime) -> bool { Satisfier::check_after(self, l) } } /// Representation of a particular spending path on a descriptor. Contains the witness template @@ -256,9 +232,7 @@ pub struct Plan { impl Plan { /// Returns the witness template - pub fn witness_template(&self) -> &Vec> { - &self.template - } + pub fn witness_template(&self) -> &Vec> { &self.template } /// Returns the witness version pub fn witness_version(&self) -> Option { @@ -267,16 +241,11 @@ impl Plan { /// The weight, in witness units, needed for satisfying this plan (includes both /// the script sig weight and the witness weight) - pub fn satisfaction_weight(&self) -> usize { - self.witness_size() + self.scriptsig_size() * 4 - } + pub fn satisfaction_weight(&self) -> usize { self.witness_size() + self.scriptsig_size() * 4 } /// The size in bytes of the script sig that satisfies this plan pub fn scriptsig_size(&self) -> usize { - match ( - self.descriptor.desc_type().segwit_version(), - self.descriptor.desc_type(), - ) { + match (self.descriptor.desc_type().segwit_version(), self.descriptor.desc_type()) { // Entire witness goes in the script_sig (None, _) => witness_size(self.template.as_ref()), // Taproot doesn't have a "wrapped" version (scriptSig len (1)) @@ -473,12 +442,7 @@ pub struct CanSign { } impl Default for CanSign { - fn default() -> Self { - CanSign { - ecdsa: true, - taproot: TaprootCanSign::default(), - } - } + fn default() -> Self { CanSign { ecdsa: true, taproot: TaprootCanSign::default() } } } #[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] @@ -686,10 +650,7 @@ impl FromIterator for Assets { keys.insert(((pk.master_fingerprint(), deriv_path), CanSign::default())); } } - Assets { - keys, - ..Default::default() - } + Assets { keys, ..Default::default() } } } @@ -700,70 +661,48 @@ pub trait IntoAssets { } impl IntoAssets for KeyMap { - fn into_assets(self) -> Assets { - Assets::from_iter(self.into_iter().map(|(k, _)| k)) - } + fn into_assets(self) -> Assets { Assets::from_iter(self.into_iter().map(|(k, _)| k)) } } impl IntoAssets for DescriptorPublicKey { - fn into_assets(self) -> Assets { - vec![self].into_assets() - } + fn into_assets(self) -> Assets { vec![self].into_assets() } } impl IntoAssets for Vec { - fn into_assets(self) -> Assets { - Assets::from_iter(self.into_iter()) - } + fn into_assets(self) -> Assets { Assets::from_iter(self.into_iter()) } } impl IntoAssets for sha256::Hash { fn into_assets(self) -> Assets { - Assets { - sha256_preimages: vec![self].into_iter().collect(), - ..Default::default() - } + Assets { sha256_preimages: vec![self].into_iter().collect(), ..Default::default() } } } impl IntoAssets for hash256::Hash { fn into_assets(self) -> Assets { - Assets { - hash256_preimages: vec![self].into_iter().collect(), - ..Default::default() - } + Assets { hash256_preimages: vec![self].into_iter().collect(), ..Default::default() } } } impl IntoAssets for ripemd160::Hash { fn into_assets(self) -> Assets { - Assets { - ripemd160_preimages: vec![self].into_iter().collect(), - ..Default::default() - } + Assets { ripemd160_preimages: vec![self].into_iter().collect(), ..Default::default() } } } impl IntoAssets for hash160::Hash { fn into_assets(self) -> Assets { - Assets { - hash160_preimages: vec![self].into_iter().collect(), - ..Default::default() - } + Assets { hash160_preimages: vec![self].into_iter().collect(), ..Default::default() } } } impl IntoAssets for Assets { - fn into_assets(self) -> Assets { - self - } + fn into_assets(self) -> Assets { self } } impl Assets { /// Contruct an empty instance - pub fn new() -> Self { - Self::default() - } + pub fn new() -> Self { Self::default() } /// Add some assets pub fn add(mut self, asset: A) -> Self { @@ -814,13 +753,7 @@ mod test { keys: Vec, hashes: Vec, // [ (key_indexes, hash_indexes, older, after, expected) ] - tests: Vec<( - Vec, - Vec, - Option, - Option, - Option, - )>, + tests: Vec<(Vec, Vec, Option, Option, Option)>, ) { let desc = Descriptor::::from_str(&desc).unwrap(); @@ -920,10 +853,7 @@ mod test { .unwrap(), ]; let hashes = vec![]; - let desc = format!( - "wsh(multi(3,{},{},{},{}))", - keys[0], keys[1], keys[2], keys[3] - ); + let desc = format!("wsh(multi(3,{},{},{},{}))", keys[0], keys[1], keys[2], keys[3]); let tests = vec![ (vec![], vec![], None, None, None), @@ -948,10 +878,7 @@ mod test { .unwrap(), ]; let hashes = vec![]; - let desc = format!( - "wsh(thresh(2,pk({}),s:pk({}),snl:older(144)))", - keys[0], keys[1] - ); + let desc = format!("wsh(thresh(2,pk({}),s:pk({}),snl:older(144)))", keys[0], keys[1]); let tests = vec![ (vec![], vec![], None, None, None), @@ -975,20 +902,11 @@ mod test { test_inner(&desc, keys.clone(), hashes.clone(), tests); - let desc = format!( - "wsh(thresh(2,pk({}),s:pk({}),snl:after(144)))", - keys[0], keys[1] - ); + let desc = format!("wsh(thresh(2,pk({}),s:pk({}),snl:after(144)))", keys[0], keys[1]); let tests = vec![ // expected weight: 4 (scriptSig len) + 1 (witness len) + 73 (sig) + 1 (OP_0) + 1 (OP_ZERO) - ( - vec![0], - vec![], - None, - Some(LockTime::from_height(1000).unwrap()), - Some(80), - ), + (vec![0], vec![], None, Some(LockTime::from_height(1000).unwrap()), Some(80)), // expected weight: 4 (scriptSig len) + 1 (witness len) + 73 (sig) * 2 + 2 (OP_PUSHBYTE_1 0x01) ( vec![0, 1], @@ -1083,33 +1001,15 @@ mod test { ), // Spend with third leaf (key + timelock), // but timelock is too low (=impossible) - ( - vec![4], - vec![], - None, - Some(LockTime::from_height(9).unwrap()), - None, - ), + (vec![4], vec![], None, Some(LockTime::from_height(9).unwrap()), None), // Spend with third leaf (key + timelock), // but timelock is in the wrong unit (=impossible) - ( - vec![4], - vec![], - None, - Some(LockTime::from_time(1296000000).unwrap()), - None, - ), + (vec![4], vec![], None, Some(LockTime::from_time(1296000000).unwrap()), None), // Spend with third leaf (key + timelock), // but don't give the timelock (=impossible) (vec![4], vec![], None, None, None), // Give all the keys (internal key will be used, as it's cheaper) - ( - vec![0, 1, 2, 3, 4], - vec![], - None, - None, - internal_key_sat_weight, - ), + (vec![0, 1, 2, 3, 4], vec![], None, None, internal_key_sat_weight), // Give all the leaf keys (uses 1st leaf) (vec![1, 2, 3, 4], vec![], None, None, first_leaf_sat_weight), // Give 2nd+3rd leaf without timelock (uses 2nd leaf) @@ -1157,10 +1057,8 @@ mod test { let root_xpub = ExtendedPubKey::from_str("xpub661MyMwAqRbcFkPHucMnrGNzDwb6teAX1RbKQmqtEF8kK3Z7LZ59qafCjB9eCRLiTVG3uxBxgKvRgbubRhqSKXnGGb1aoaqLrpMBDrVxga8").unwrap(); let fingerprint = root_xpub.fingerprint(); let xpub = format!("[{}/86'/0'/0']xpub6BgBgsespWvERF3LHQu6CnqdvfEvtMcQjYrcRzx53QJjSxarj2afYWcLteoGVky7D3UKDP9QyrLprQ3VCECoY49yfdDEHGCtMMj92pReUsQ", fingerprint); - let desc = format!( - "tr({}/0/0,{{pkh({}/0/1),multi_a(2,{}/1/0,{}/1/1)}})", - xpub, xpub, xpub, xpub - ); + let desc = + format!("tr({}/0/0,{{pkh({}/0/1),multi_a(2,{}/1/0,{}/1/1)}})", xpub, xpub, xpub, xpub); let desc = Descriptor::from_str(&desc).unwrap(); @@ -1174,24 +1072,10 @@ mod test { .plan(&assets) .unwrap() .update_psbt_input(&mut psbt_input); - assert!( - psbt_input.tap_internal_key.is_some(), - "Internal key is missing" - ); - assert!( - psbt_input.tap_merkle_root.is_some(), - "Merkle root is missing" - ); - assert_eq!( - psbt_input.tap_key_origins.len(), - 1, - "Unexpected number of tap_key_origins" - ); - assert_eq!( - psbt_input.tap_scripts.len(), - 0, - "Unexpected number of tap_scripts" - ); + assert!(psbt_input.tap_internal_key.is_some(), "Internal key is missing"); + assert!(psbt_input.tap_merkle_root.is_some(), "Merkle root is missing"); + assert_eq!(psbt_input.tap_key_origins.len(), 1, "Unexpected number of tap_key_origins"); + assert_eq!(psbt_input.tap_scripts.len(), 0, "Unexpected number of tap_scripts"); let mut psbt_input = bitcoin::psbt::Input::default(); let assets = Assets::new().add(first_branch); @@ -1199,48 +1083,20 @@ mod test { .plan(&assets) .unwrap() .update_psbt_input(&mut psbt_input); - assert!( - psbt_input.tap_internal_key.is_none(), - "Internal key is present" - ); - assert!( - psbt_input.tap_merkle_root.is_some(), - "Merkle root is missing" - ); - assert_eq!( - psbt_input.tap_key_origins.len(), - 1, - "Unexpected number of tap_key_origins" - ); - assert_eq!( - psbt_input.tap_scripts.len(), - 1, - "Unexpected number of tap_scripts" - ); + assert!(psbt_input.tap_internal_key.is_none(), "Internal key is present"); + assert!(psbt_input.tap_merkle_root.is_some(), "Merkle root is missing"); + assert_eq!(psbt_input.tap_key_origins.len(), 1, "Unexpected number of tap_key_origins"); + assert_eq!(psbt_input.tap_scripts.len(), 1, "Unexpected number of tap_scripts"); let mut psbt_input = bitcoin::psbt::Input::default(); let assets = Assets::new().add(second_branch); desc.plan(&assets) .unwrap() .update_psbt_input(&mut psbt_input); - assert!( - psbt_input.tap_internal_key.is_none(), - "Internal key is present" - ); - assert!( - psbt_input.tap_merkle_root.is_some(), - "Merkle root is missing" - ); - assert_eq!( - psbt_input.tap_key_origins.len(), - 2, - "Unexpected number of tap_key_origins" - ); - assert_eq!( - psbt_input.tap_scripts.len(), - 1, - "Unexpected number of tap_scripts" - ); + assert!(psbt_input.tap_internal_key.is_none(), "Internal key is present"); + assert!(psbt_input.tap_merkle_root.is_some(), "Merkle root is missing"); + assert_eq!(psbt_input.tap_key_origins.len(), 2, "Unexpected number of tap_key_origins"); + assert_eq!(psbt_input.tap_scripts.len(), 1, "Unexpected number of tap_scripts"); } #[test] @@ -1260,15 +1116,8 @@ mod test { desc.plan(&assets) .unwrap() .update_psbt_input(&mut psbt_input); - assert!( - psbt_input.witness_script.is_some(), - "Witness script missing" - ); + assert!(psbt_input.witness_script.is_some(), "Witness script missing"); assert!(psbt_input.redeem_script.is_none(), "Redeem script present"); - assert_eq!( - psbt_input.bip32_derivation.len(), - 2, - "Unexpected number of bip32_derivation" - ); + assert_eq!(psbt_input.bip32_derivation.len(), 2, "Unexpected number of bip32_derivation"); } } diff --git a/src/policy/compiler.rs b/src/policy/compiler.rs index 33423314d..6880af9b0 100644 --- a/src/policy/compiler.rs +++ b/src/policy/compiler.rs @@ -31,9 +31,7 @@ impl Eq for OrdF64 {} // We could derive PartialOrd, but we can't derive Ord, and clippy wants us // to derive both or neither. Better to be explicit. impl PartialOrd for OrdF64 { - fn partial_cmp(&self, other: &OrdF64) -> Option { - self.0.partial_cmp(&other.0) - } + fn partial_cmp(&self, other: &OrdF64) -> Option { self.0.partial_cmp(&other.0) } } impl Ord for OrdF64 { fn cmp(&self, other: &OrdF64) -> cmp::Ordering { @@ -89,16 +87,12 @@ impl error::Error for CompilerError { #[doc(hidden)] impl From for CompilerError { - fn from(e: policy::concrete::PolicyError) -> CompilerError { - CompilerError::PolicyError(e) - } + fn from(e: policy::concrete::PolicyError) -> CompilerError { CompilerError::PolicyError(e) } } /// Hash required for using OrdF64 as key for hashmap impl hash::Hash for OrdF64 { - fn hash(&self, state: &mut H) { - self.0.to_bits().hash(state); - } + fn hash(&self, state: &mut H) { self.0.to_bits().hash(state); } } /// Compilation key: This represents the state of the best possible compilation @@ -132,11 +126,7 @@ impl CompilationKey { /// Helper to create compilation key from components fn from_type(ty: Type, expensive_verify: bool, dissat_prob: Option) -> CompilationKey { - CompilationKey { - ty, - expensive_verify, - dissat_prob: dissat_prob.map(OrdF64), - } + CompilationKey { ty, expensive_verify, dissat_prob: dissat_prob.map(OrdF64) } } } @@ -157,19 +147,11 @@ struct CompilerExtData { impl Property for CompilerExtData { fn from_true() -> Self { - CompilerExtData { - branch_prob: None, - sat_cost: 0.0, - dissat_cost: None, - } + CompilerExtData { branch_prob: None, sat_cost: 0.0, dissat_cost: None } } fn from_false() -> Self { - CompilerExtData { - branch_prob: None, - sat_cost: f64::MAX, - dissat_cost: Some(0.0), - } + CompilerExtData { branch_prob: None, sat_cost: f64::MAX, dissat_cost: Some(0.0) } } fn from_pk_k() -> Self { @@ -216,19 +198,11 @@ impl Property for CompilerExtData { } fn from_hash() -> Self { - CompilerExtData { - branch_prob: None, - sat_cost: 33.0, - dissat_cost: Some(33.0), - } + CompilerExtData { branch_prob: None, sat_cost: 33.0, dissat_cost: Some(33.0) } } fn from_time(_t: u32) -> Self { - CompilerExtData { - branch_prob: None, - sat_cost: 0.0, - dissat_cost: None, - } + CompilerExtData { branch_prob: None, sat_cost: 0.0, dissat_cost: None } } fn cast_alt(self) -> Result { @@ -264,19 +238,11 @@ impl Property for CompilerExtData { } fn cast_verify(self) -> Result { - Ok(CompilerExtData { - branch_prob: None, - sat_cost: self.sat_cost, - dissat_cost: None, - }) + Ok(CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: None }) } fn cast_nonzero(self) -> Result { - Ok(CompilerExtData { - branch_prob: None, - sat_cost: self.sat_cost, - dissat_cost: Some(1.0), - }) + Ok(CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: Some(1.0) }) } fn cast_zeronotequal(self) -> Result { @@ -288,11 +254,7 @@ impl Property for CompilerExtData { } fn cast_true(self) -> Result { - Ok(CompilerExtData { - branch_prob: None, - sat_cost: self.sat_cost, - dissat_cost: None, - }) + Ok(CompilerExtData { branch_prob: None, sat_cost: self.sat_cost, dissat_cost: None }) } fn cast_or_i_false(self) -> Result { @@ -787,32 +749,12 @@ where } macro_rules! compile_binary { ($l:expr, $r:expr, $w: expr, $f: expr) => { - compile_binary( - policy_cache, - policy, - &mut ret, - $l, - $r, - $w, - sat_prob, - dissat_prob, - $f, - )? + compile_binary(policy_cache, policy, &mut ret, $l, $r, $w, sat_prob, dissat_prob, $f)? }; } macro_rules! compile_tern { ($a:expr, $b:expr, $c: expr, $w: expr) => { - compile_tern( - policy_cache, - policy, - &mut ret, - $a, - $b, - $c, - $w, - sat_prob, - dissat_prob, - )? + compile_tern(policy_cache, policy, &mut ret, $a, $b, $c, $w, sat_prob, dissat_prob)? }; } @@ -1228,10 +1170,7 @@ mod tests { let policy = SPolicy::from_str(s).expect("parse"); let miniscript: Miniscript = policy.compile()?; - assert_eq!( - policy.lift().unwrap().sorted(), - miniscript.lift().unwrap().sorted() - ); + assert_eq!(policy.lift().unwrap().sorted(), miniscript.lift().unwrap().sorted()); Ok(()) } @@ -1253,14 +1192,8 @@ mod tests { #[test] fn compile_basic() { assert!(policy_compile_lift_check("pk(A)").is_ok()); - assert_eq!( - policy_compile_lift_check("after(9)"), - Err(CompilerError::TopLevelNonSafe) - ); - assert_eq!( - policy_compile_lift_check("older(1)"), - Err(CompilerError::TopLevelNonSafe) - ); + assert_eq!(policy_compile_lift_check("after(9)"), Err(CompilerError::TopLevelNonSafe)); + assert_eq!(policy_compile_lift_check("older(1)"), Err(CompilerError::TopLevelNonSafe)); assert_eq!( policy_compile_lift_check( "sha256(1111111111111111111111111111111111111111111111111111111111111111)" @@ -1289,10 +1222,7 @@ mod tests { let compilation: TapAstElemExt = best_t(&mut BTreeMap::new(), &policy, 1.0, None).unwrap(); assert_eq!(compilation.cost_1d(1.0, None), 87.0 + 67.0390625); - assert_eq!( - policy.lift().unwrap().sorted(), - compilation.ms.lift().unwrap().sorted() - ); + assert_eq!(policy.lift().unwrap().sorted(), compilation.ms.lift().unwrap().sorted()); // compile into taproot context to avoid limit errors let policy = SPolicy::from_str( @@ -1301,10 +1231,7 @@ mod tests { let compilation: TapAstElemExt = best_t(&mut BTreeMap::new(), &policy, 1.0, None).unwrap(); assert_eq!(compilation.cost_1d(1.0, None), 433.0 + 275.7909749348958); - assert_eq!( - policy.lift().unwrap().sorted(), - compilation.ms.lift().unwrap().sorted() - ); + assert_eq!(policy.lift().unwrap().sorted(), compilation.ms.lift().unwrap().sorted()); } #[test] @@ -1387,10 +1314,8 @@ mod tests { assert_eq!(abs.n_keys(), 5); assert_eq!(abs.minimum_n_keys(), Some(3)); - let bitcoinsig = bitcoin::ecdsa::Signature { - sig, - hash_ty: bitcoin::sighash::EcdsaSighashType::All, - }; + let bitcoinsig = + bitcoin::ecdsa::Signature { sig, hash_ty: bitcoin::sighash::EcdsaSighashType::All }; let sigvec = bitcoinsig.to_vec(); let no_sat = BTreeMap::::new(); @@ -1454,13 +1379,8 @@ mod tests { // Up until 20 keys, thresh should be compiled to a multi no matter the value of k for k in 1..4 { - let small_thresh: BPolicy = policy_str!( - "thresh({},pk({}),pk({}),pk({}))", - k, - keys[0], - keys[1], - keys[2] - ); + let small_thresh: BPolicy = + policy_str!("thresh({},pk({}),pk({}),pk({}))", k, keys[0], keys[1], keys[2]); let small_thresh_ms: SegwitMiniScript = small_thresh.compile().unwrap(); let small_thresh_ms_expected: SegwitMiniScript = ms_str!("multi({},{},{},{})", k, keys[0], keys[1], keys[2]); @@ -1572,17 +1492,13 @@ mod tests { let res = Concrete::Or(vec![(1, key.clone()), (1, key.clone())]).compile::(); assert_eq!( res, - Err(CompilerError::PolicyError( - policy::concrete::PolicyError::DuplicatePubKeys - )) + Err(CompilerError::PolicyError(policy::concrete::PolicyError::DuplicatePubKeys)) ); // Same for legacy let res = Concrete::Or(vec![(1, key.clone()), (1, key)]).compile::(); assert_eq!( res, - Err(CompilerError::PolicyError( - policy::concrete::PolicyError::DuplicatePubKeys - )) + Err(CompilerError::PolicyError(policy::concrete::PolicyError::DuplicatePubKeys)) ); } diff --git a/src/policy/concrete.rs b/src/policy/concrete.rs index 7a6d6a2e5..bdc778d0c 100644 --- a/src/policy/concrete.rs +++ b/src/policy/concrete.rs @@ -78,9 +78,7 @@ where /// Construct a `Policy::Older` from `n`. Helper function equivalent to /// `Policy::Older(Sequence::from_consensus(n))`. - pub fn older(n: u32) -> Policy { - Policy::Older(Sequence::from_consensus(n)) - } + pub fn older(n: u32) -> Policy { Policy::Older(Sequence::from_consensus(n)) } } /// Lightweight repr of Concrete policy which corresponds directly to a @@ -242,11 +240,9 @@ impl fmt::Display for PolicyError { PolicyError::InsufficientArgsforOr => { f.write_str("Semantic Policy 'Or' fragment must have at least 2 args ") } - PolicyError::EntailmentMaxTerminals => write!( - f, - "Policy entailment only supports {} terminals", - ENTAILMENT_MAX_TERMINALS - ), + PolicyError::EntailmentMaxTerminals => { + write!(f, "Policy entailment only supports {} terminals", ENTAILMENT_MAX_TERMINALS) + } PolicyError::HeightTimelockCombination => { f.write_str("Cannot lift policies that have a heightlock and timelock combination") } @@ -381,9 +377,7 @@ impl Policy { self.is_valid()?; // Check for validity match self.is_safe_nonmalleable() { (false, _) => Err(Error::from(CompilerError::TopLevelNonSafe)), - (_, false) => Err(Error::from( - CompilerError::ImpossibleNonMalleableCompilation, - )), + (_, false) => Err(Error::from(CompilerError::ImpossibleNonMalleableCompilation)), _ => { let (internal_key, policy) = self.clone().extract_key(unspendable_key)?; policy.check_num_tapleaves()?; @@ -439,9 +433,7 @@ impl Policy { self.is_valid()?; // Check for validity match self.is_safe_nonmalleable() { (false, _) => Err(Error::from(CompilerError::TopLevelNonSafe)), - (_, false) => Err(Error::from( - CompilerError::ImpossibleNonMalleableCompilation, - )), + (_, false) => Err(Error::from(CompilerError::ImpossibleNonMalleableCompilation)), _ => { let (internal_key, policy) = self.clone().extract_key(unspendable_key)?; let tree = Descriptor::new_tr( @@ -490,9 +482,7 @@ impl Policy { self.is_valid()?; match self.is_safe_nonmalleable() { (false, _) => Err(Error::from(CompilerError::TopLevelNonSafe)), - (_, false) => Err(Error::from( - CompilerError::ImpossibleNonMalleableCompilation, - )), + (_, false) => Err(Error::from(CompilerError::ImpossibleNonMalleableCompilation)), _ => match desc_ctx { DescriptorCtx::Bare => Descriptor::new_bare(compiler::best_compilation(self)?), DescriptorCtx::Sh => Descriptor::new_sh(compiler::best_compilation(self)?), @@ -939,10 +929,7 @@ impl Policy { .iter() .map(|sub| sub.is_safe_nonmalleable()) .fold((0, 0), |(safe_count, non_mall_count), (safe, non_mall)| { - ( - safe_count + safe as usize, - non_mall_count + non_mall as usize, - ) + (safe_count + safe as usize, non_mall_count + non_mall as usize) }); ( safe_count >= (subs.len() - k + 1), @@ -961,9 +948,7 @@ impl Policy { let (all_safe, atleast_one_safe, all_non_mall) = subs .iter() .map(|(_, sub)| sub.is_safe_nonmalleable()) - .fold((true, false, true), |acc, x| { - (acc.0 && x.0, acc.1 || x.0, acc.2 && x.1) - }); + .fold((true, false, true), |acc, x| (acc.0 && x.0, acc.1 || x.0, acc.2 && x.1)); (all_safe, atleast_one_safe && all_non_mall) } } @@ -1235,10 +1220,7 @@ fn generate_combination( .enumerate() .filter_map(|(j, sub)| if j != i { Some(Arc::clone(sub)) } else { None }) .collect(); - ret.push(( - prob / policy_vec.len() as f64, - Arc::new(PolicyArc::Threshold(k, policies)), - )); + ret.push((prob / policy_vec.len() as f64, Arc::new(PolicyArc::Threshold(k, policies)))); } ret } diff --git a/src/policy/mod.rs b/src/policy/mod.rs index 27165c2e2..c2d4fdbf5 100644 --- a/src/policy/mod.rs +++ b/src/policy/mod.rs @@ -177,9 +177,7 @@ impl Liftable for Descriptor { } impl Liftable for Semantic { - fn lift(&self) -> Result, Error> { - Ok(self.clone()) - } + fn lift(&self) -> Result, Error> { Ok(self.clone()) } } impl Liftable for Concrete { @@ -338,12 +336,10 @@ mod tests { .parse() .unwrap(); - let ms_str: Miniscript = format!( - "andor(multi(1,{}),older(42),c:pk_k({}))", - key_a.inner, key_b.inner - ) - .parse() - .unwrap(); + let ms_str: Miniscript = + format!("andor(multi(1,{}),older(42),c:pk_k({}))", key_a.inner, key_b.inner) + .parse() + .unwrap(); assert_eq!( Semantic::Threshold( 1, @@ -402,10 +398,7 @@ mod tests { let policy: Concrete = policy_str!("or(and(pk(A),pk(B)),and(pk(A),pk(D)))"); let descriptor = policy.compile_tr(Some(unspendable_key.clone())); - assert_eq!( - descriptor.unwrap_err().to_string(), - "Policy contains duplicate keys" - ); + assert_eq!(descriptor.unwrap_err().to_string(), "Policy contains duplicate keys"); } // Non-trivial multi-node compilation diff --git a/src/policy/semantic.rs b/src/policy/semantic.rs index aa2de8680..9636c0d2a 100644 --- a/src/policy/semantic.rs +++ b/src/policy/semantic.rs @@ -59,9 +59,7 @@ where /// Construct a `Policy::Older` from `n`. /// /// Helper function equivalent to `Policy::Older(Sequence::from_consensus(n))`. - pub fn older(n: u32) -> Policy { - Policy::Older(Sequence::from_consensus(n)) - } + pub fn older(n: u32) -> Policy { Policy::Older(Sequence::from_consensus(n)) } } impl ForEachKey for Policy { @@ -336,9 +334,9 @@ impl_from_tree!( ("older", 1) => expression::terminal(&top.args[0], |x| { expression::parse_num(x).map(|x| Policy::older(x)) }), - ("sha256", 1) => expression::terminal(&top.args[0], |x| { - Pk::Sha256::from_str(x).map(Policy::Sha256) - }), + ("sha256", 1) => { + expression::terminal(&top.args[0], |x| Pk::Sha256::from_str(x).map(Policy::Sha256)) + } ("hash256", 1) => expression::terminal(&top.args[0], |x| { Pk::Hash256::from_str(x).map(Policy::Hash256) }), @@ -461,18 +459,14 @@ impl Policy { /// Only checks whether the policy is `Policy::Trivial`, to check if the /// normalized form is trivial, the caller is expected to normalize the /// policy first. - pub fn is_trivial(&self) -> bool { - matches!(*self, Policy::Trivial) - } + pub fn is_trivial(&self) -> bool { matches!(*self, Policy::Trivial) } /// Detects a false/unsatisfiable policy. /// /// Only checks whether the policy is `Policy::Unsatisfiable`, to check if /// the normalized form is unsatisfiable, the caller is expected to /// normalize the policy first. - pub fn is_unsatisfiable(&self) -> bool { - matches!(*self, Policy::Unsatisfiable) - } + pub fn is_unsatisfiable(&self) -> bool { matches!(*self, Policy::Unsatisfiable) } /// Helper function to do the recursion in `timelocks`. fn real_relative_timelocks(&self) -> Vec { @@ -695,10 +689,7 @@ mod tests { assert_eq!(policy.absolute_timelocks(), vec![]); assert_eq!(policy.relative_timelocks(), vec![1000]); assert_eq!(policy.clone().at_age(Sequence::ZERO), Policy::Unsatisfiable); - assert_eq!( - policy.clone().at_age(Sequence::from_height(999)), - Policy::Unsatisfiable - ); + assert_eq!(policy.clone().at_age(Sequence::from_height(999)), Policy::Unsatisfiable); assert_eq!(policy.clone().at_age(Sequence::from_height(1000)), policy); assert_eq!(policy.clone().at_age(Sequence::from_height(10000)), policy); assert_eq!(policy.n_keys(), 0); @@ -717,18 +708,9 @@ mod tests { ); assert_eq!(policy.relative_timelocks(), vec![1000]); assert_eq!(policy.absolute_timelocks(), vec![]); - assert_eq!( - policy.clone().at_age(Sequence::ZERO), - Policy::Key("".to_owned()) - ); - assert_eq!( - policy.clone().at_age(Sequence::from_height(999)), - Policy::Key("".to_owned()) - ); - assert_eq!( - policy.clone().at_age(Sequence::from_height(1000)), - policy.clone().normalized() - ); + assert_eq!(policy.clone().at_age(Sequence::ZERO), Policy::Key("".to_owned())); + assert_eq!(policy.clone().at_age(Sequence::from_height(999)), Policy::Key("".to_owned())); + assert_eq!(policy.clone().at_age(Sequence::from_height(1000)), policy.clone().normalized()); assert_eq!( policy.clone().at_age(Sequence::from_height(10000)), policy.clone().normalized() @@ -811,10 +793,7 @@ mod tests { assert_eq!(policy, Policy::after(1000)); assert_eq!(policy.absolute_timelocks(), vec![1000]); assert_eq!(policy.relative_timelocks(), vec![]); - assert_eq!( - policy.clone().at_lock_time(absolute::LockTime::ZERO), - Policy::Unsatisfiable - ); + assert_eq!(policy.clone().at_lock_time(absolute::LockTime::ZERO), Policy::Unsatisfiable); assert_eq!( policy .clone() @@ -849,10 +828,7 @@ mod tests { assert_eq!(policy.absolute_timelocks(), vec![500_000_010]); assert_eq!(policy.relative_timelocks(), vec![]); // Pass a block height to at_lock_time while policy uses a UNIX timestapm. - assert_eq!( - policy.clone().at_lock_time(absolute::LockTime::ZERO), - Policy::Unsatisfiable - ); + assert_eq!(policy.clone().at_lock_time(absolute::LockTime::ZERO), Policy::Unsatisfiable); assert_eq!( policy .clone() diff --git a/src/psbt/mod.rs b/src/psbt/mod.rs index 1668f2f66..a9eba63de 100644 --- a/src/psbt/mod.rs +++ b/src/psbt/mod.rs @@ -56,11 +56,9 @@ impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Error::InputError(ref inp_err, index) => write!(f, "{} at index {}", inp_err, index), - Error::WrongInputCount { in_tx, in_map } => write!( - f, - "PSBT had {} inputs in transaction but {} inputs in map", - in_tx, in_map - ), + Error::WrongInputCount { in_tx, in_map } => { + write!(f, "PSBT had {} inputs in transaction but {} inputs in map", in_tx, in_map) + } Error::InputIdxOutofBounds { psbt_inp, index } => write!( f, "psbt input index {} out of bounds: psbt.inputs.len() {}", @@ -176,25 +174,18 @@ impl error::Error for InputError { impl fmt::Display for InputError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - InputError::InvalidSignature { - ref pubkey, - ref sig, - } => write!(f, "PSBT: bad signature {} for key {:?}", pubkey, sig), + InputError::InvalidSignature { ref pubkey, ref sig } => { + write!(f, "PSBT: bad signature {} for key {:?}", pubkey, sig) + } InputError::KeyErr(ref e) => write!(f, "Key Err: {}", e), InputError::Interpreter(ref e) => write!(f, "Interpreter: {}", e), InputError::SecpErr(ref e) => write!(f, "Secp Err: {}", e), - InputError::InvalidRedeemScript { - ref redeem, - ref p2sh_expected, - } => write!( + InputError::InvalidRedeemScript { ref redeem, ref p2sh_expected } => write!( f, "Redeem script {} does not match the p2sh script {}", redeem, p2sh_expected ), - InputError::InvalidWitnessScript { - ref witness_script, - ref p2wsh_expected, - } => write!( + InputError::InvalidWitnessScript { ref witness_script, ref p2wsh_expected } => write!( f, "Witness script {} does not match the p2wsh script {}", witness_script, p2wsh_expected @@ -207,18 +198,13 @@ impl fmt::Display for InputError { } InputError::MissingWitnessScript => write!(f, "PSBT is missing witness script"), InputError::MissingPubkey => write!(f, "Missing pubkey for a pkh/wpkh"), - InputError::NonEmptyRedeemScript => write!( - f, - "PSBT has non-empty redeem script at for legacy transactions" - ), + InputError::NonEmptyRedeemScript => { + write!(f, "PSBT has non-empty redeem script at for legacy transactions") + } InputError::NonEmptyWitnessScript => { write!(f, "PSBT has non-empty witness script at for legacy input") } - InputError::WrongSighashFlag { - required, - got, - pubkey, - } => write!( + InputError::WrongSighashFlag { required, got, pubkey } => write!( f, "PSBT: signature with key {:?} had \ sighashflag {:?} rather than required {:?}", @@ -232,23 +218,17 @@ impl fmt::Display for InputError { #[doc(hidden)] impl From for InputError { - fn from(e: super::Error) -> InputError { - InputError::MiniscriptError(e) - } + fn from(e: super::Error) -> InputError { InputError::MiniscriptError(e) } } #[doc(hidden)] impl From for InputError { - fn from(e: bitcoin::secp256k1::Error) -> InputError { - InputError::SecpErr(e) - } + fn from(e: bitcoin::secp256k1::Error) -> InputError { InputError::SecpErr(e) } } #[doc(hidden)] impl From for InputError { - fn from(e: bitcoin::key::Error) -> InputError { - InputError::KeyErr(e) - } + fn from(e: bitcoin::key::Error) -> InputError { InputError::KeyErr(e) } } /// Psbt satisfier for at inputs at a particular index @@ -266,9 +246,7 @@ pub struct PsbtInputSatisfier<'psbt> { impl<'psbt> PsbtInputSatisfier<'psbt> { /// create a new PsbtInputsatisfier from /// psbt and index - pub fn new(psbt: &'psbt Psbt, index: usize) -> Self { - Self { psbt, index } - } + pub fn new(psbt: &'psbt Psbt, index: usize) -> Self { Self { psbt, index } } } impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfier<'psbt> { @@ -304,10 +282,7 @@ impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfie fn lookup_raw_pkh_tap_leaf_script_sig( &self, pkh: &(hash160::Hash, TapLeafHash), - ) -> Option<( - bitcoin::secp256k1::XOnlyPublicKey, - bitcoin::taproot::Signature, - )> { + ) -> Option<(bitcoin::secp256k1::XOnlyPublicKey, bitcoin::taproot::Signature)> { self.psbt.inputs[self.index] .tap_script_sigs .iter() @@ -378,9 +353,7 @@ impl<'psbt, Pk: MiniscriptKey + ToPublicKey> Satisfier for PsbtInputSatisfie fn lookup_hash256(&self, h: &Pk::Hash256) -> Option { self.psbt.inputs[self.index] .hash256_preimages - .get(&sha256d::Hash::from_byte_array( - Pk::to_hash256(h).to_byte_array(), - )) // upstream psbt operates on hash256 + .get(&sha256d::Hash::from_byte_array(Pk::to_hash256(h).to_byte_array())) // upstream psbt operates on hash256 .and_then(try_vec_as_preimage32) } @@ -684,10 +657,7 @@ impl PsbtExt for Psbt { index: usize, ) -> Result<(), Error> { if index >= self.inputs.len() { - return Err(Error::InputIdxOutofBounds { - psbt_inp: self.inputs.len(), - index, - }); + return Err(Error::InputIdxOutofBounds { psbt_inp: self.inputs.len(), index }); } finalizer::finalize_input(self, index, secp, /*allow_mall*/ false) } @@ -709,10 +679,7 @@ impl PsbtExt for Psbt { index: usize, ) -> Result<(), Error> { if index >= self.inputs.len() { - return Err(Error::InputIdxOutofBounds { - psbt_inp: self.inputs.len(), - index, - }); + return Err(Error::InputIdxOutofBounds { psbt_inp: self.inputs.len(), index }); } finalizer::finalize_input(self, index, secp, /*allow_mall*/ false) } @@ -1033,11 +1000,7 @@ impl Translator &mut BTreeMap>; // `tap_tree` only appears in psbt::Output, so it's returned as an option of a mutable ref - fn tap_tree(&mut self) -> Option<&mut Option> { - None - } + fn tap_tree(&mut self) -> Option<&mut Option> { None } // `tap_scripts` and `tap_merkle_root` only appear in psbt::Input fn tap_scripts(&mut self) -> Option<&mut BTreeMap> { None } - fn tap_merkle_root(&mut self) -> Option<&mut Option> { - None - } + fn tap_merkle_root(&mut self) -> Option<&mut Option> { None } } impl PsbtFields for psbt::Input { - fn redeem_script(&mut self) -> &mut Option { - &mut self.redeem_script - } - fn witness_script(&mut self) -> &mut Option { - &mut self.witness_script - } + fn redeem_script(&mut self) -> &mut Option { &mut self.redeem_script } + fn witness_script(&mut self) -> &mut Option { &mut self.witness_script } fn bip32_derivation(&mut self) -> &mut BTreeMap { &mut self.bip32_derivation } @@ -1088,9 +1043,7 @@ impl PsbtFields for psbt::Input { fn proprietary(&mut self) -> &mut BTreeMap> { &mut self.proprietary } - fn unknown(&mut self) -> &mut BTreeMap> { - &mut self.unknown - } + fn unknown(&mut self) -> &mut BTreeMap> { &mut self.unknown } fn tap_scripts(&mut self) -> Option<&mut BTreeMap> { Some(&mut self.tap_scripts) @@ -1101,12 +1054,8 @@ impl PsbtFields for psbt::Input { } impl PsbtFields for psbt::Output { - fn redeem_script(&mut self) -> &mut Option { - &mut self.redeem_script - } - fn witness_script(&mut self) -> &mut Option { - &mut self.witness_script - } + fn redeem_script(&mut self) -> &mut Option { &mut self.redeem_script } + fn witness_script(&mut self) -> &mut Option { &mut self.witness_script } fn bip32_derivation(&mut self) -> &mut BTreeMap { &mut self.bip32_derivation } @@ -1121,13 +1070,9 @@ impl PsbtFields for psbt::Output { fn proprietary(&mut self) -> &mut BTreeMap> { &mut self.proprietary } - fn unknown(&mut self) -> &mut BTreeMap> { - &mut self.unknown - } + fn unknown(&mut self) -> &mut BTreeMap> { &mut self.unknown } - fn tap_tree(&mut self) -> Option<&mut Option> { - Some(&mut self.tap_tree) - } + fn tap_tree(&mut self) -> Option<&mut Option> { Some(&mut self.tap_tree) } } fn update_item_with_descriptor_helper( @@ -1417,9 +1362,7 @@ impl error::Error for SighashError { } impl From for SighashError { - fn from(e: sighash::Error) -> Self { - SighashError::SighashComputationError(e) - } + fn from(e: sighash::Error) -> Self { SighashError::SighashComputationError(e) } } /// Sighash message(signing data) for a given psbt transaction input. @@ -1491,13 +1434,7 @@ mod tests { assert_eq!(psbt_input.tap_internal_key, Some(internal_key)); assert_eq!( psbt_input.tap_key_origins.get(&internal_key), - Some(&( - vec![], - ( - fingerprint, - DerivationPath::from_str("m/86'/0'/0'/0/0").unwrap() - ) - )) + Some(&(vec![], (fingerprint, DerivationPath::from_str("m/86'/0'/0'/0/0").unwrap()))) ); assert_eq!(psbt_input.tap_key_origins.len(), 1); assert_eq!(psbt_input.tap_scripts.len(), 0); @@ -1515,10 +1452,8 @@ mod tests { let root_xpub = ExtendedPubKey::from_str("xpub661MyMwAqRbcFkPHucMnrGNzDwb6teAX1RbKQmqtEF8kK3Z7LZ59qafCjB9eCRLiTVG3uxBxgKvRgbubRhqSKXnGGb1aoaqLrpMBDrVxga8").unwrap(); let fingerprint = root_xpub.fingerprint(); let xpub = format!("[{}/86'/0'/0']xpub6BgBgsespWvERF3LHQu6CnqdvfEvtMcQjYrcRzx53QJjSxarj2afYWcLteoGVky7D3UKDP9QyrLprQ3VCECoY49yfdDEHGCtMMj92pReUsQ", fingerprint); - let desc = format!( - "tr({}/0/0,{{pkh({}/0/1),multi_a(2,{}/0/1,{}/1/0)}})", - xpub, xpub, xpub, xpub - ); + let desc = + format!("tr({}/0/0,{{pkh({}/0/1),multi_a(2,{}/0/1,{}/1/0)}})", xpub, xpub, xpub, xpub); let desc = Descriptor::from_str(&desc).unwrap(); let internal_key = XOnlyPublicKey::from_str( @@ -1532,13 +1467,7 @@ mod tests { assert_eq!(psbt_input.tap_internal_key, Some(internal_key)); assert_eq!( psbt_input.tap_key_origins.get(&internal_key), - Some(&( - vec![], - ( - fingerprint, - DerivationPath::from_str("m/86'/0'/0'/0/0").unwrap() - ) - )) + Some(&(vec![], (fingerprint, DerivationPath::from_str("m/86'/0'/0'/0/0").unwrap()))) ); assert_eq!(psbt_input.tap_key_origins.len(), 3); assert_eq!(psbt_input.tap_scripts.len(), 2); @@ -1628,10 +1557,7 @@ mod tests { psbt_output.update_with_descriptor_unchecked(&desc).unwrap(); assert_eq!(expected_bip32, psbt_input.bip32_derivation); - assert_eq!( - psbt_input.witness_script, - Some(derived.explicit_script().unwrap()) - ); + assert_eq!(psbt_input.witness_script, Some(derived.explicit_script().unwrap())); assert_eq!(psbt_output.bip32_derivation, psbt_input.bip32_derivation); assert_eq!(psbt_output.witness_script, psbt_input.witness_script); @@ -1652,10 +1578,7 @@ mod tests { assert_eq!(psbt_input.bip32_derivation, expected_bip32); assert_eq!(psbt_input.witness_script, None); - assert_eq!( - psbt_input.redeem_script, - Some(derived.explicit_script().unwrap()) - ); + assert_eq!(psbt_input.redeem_script, Some(derived.explicit_script().unwrap())); assert_eq!(psbt_output.bip32_derivation, psbt_input.bip32_derivation); assert_eq!(psbt_output.witness_script, psbt_input.witness_script); @@ -1685,10 +1608,7 @@ mod tests { version: 1, lock_time: absolute::LockTime::ZERO, input: vec![TxIn { - previous_output: OutPoint { - txid: non_witness_utxo.txid(), - vout: 0, - }, + previous_output: OutPoint { txid: non_witness_utxo.txid(), vout: 0 }, ..Default::default() }], output: vec![], diff --git a/src/util.rs b/src/util.rs index 0a6287716..11643b643 100644 --- a/src/util.rs +++ b/src/util.rs @@ -10,9 +10,7 @@ use crate::miniscript::context; use crate::miniscript::satisfy::Placeholder; use crate::prelude::*; use crate::{MiniscriptKey, ScriptContext, ToPublicKey}; -pub(crate) fn varint_len(n: usize) -> usize { - bitcoin::VarInt(n as u64).len() -} +pub(crate) fn varint_len(n: usize) -> usize { bitcoin::VarInt(n as u64).len() } pub(crate) trait ItemSize { fn size(&self) -> usize; @@ -41,9 +39,7 @@ impl ItemSize for Placeholder { } impl ItemSize for Vec { - fn size(&self) -> usize { - self.len() - } + fn size(&self) -> usize { self.len() } } // Helper function to calculate witness size