diff --git a/bitcoin/examples/ecdsa-psbt-simple.rs b/bitcoin/examples/ecdsa-psbt-simple.rs index ab2341d09e..e57f8dcd4e 100644 --- a/bitcoin/examples/ecdsa-psbt-simple.rs +++ b/bitcoin/examples/ecdsa-psbt-simple.rs @@ -54,10 +54,7 @@ const SPEND_AMOUNT: Amount = Amount::from_sat_u32(25_000_000); const CHANGE_AMOUNT: Amount = Amount::from_sat_u32(4_990_000); // 10_000 sat fee. // Derive the external address xpriv. -fn get_external_address_xpriv( - master_xpriv: Xpriv, - index: u32, -) -> Xpriv { +fn get_external_address_xpriv(master_xpriv: Xpriv, index: u32) -> Xpriv { let derivation_path = BIP84_DERIVATION_PATH.into_derivation_path().expect("valid derivation path"); let child_xpriv = @@ -69,10 +66,7 @@ fn get_external_address_xpriv( } // Derive the internal address xpriv. -fn get_internal_address_xpriv( - master_xpriv: Xpriv, - index: u32, -) -> Xpriv { +fn get_internal_address_xpriv(master_xpriv: Xpriv, index: u32) -> Xpriv { let derivation_path = BIP84_DERIVATION_PATH.into_derivation_path().expect("valid derivation path"); let child_xpriv = diff --git a/bitcoin/examples/ecdsa-psbt.rs b/bitcoin/examples/ecdsa-psbt.rs index 393c0adaf6..70a4b3d4e0 100644 --- a/bitcoin/examples/ecdsa-psbt.rs +++ b/bitcoin/examples/ecdsa-psbt.rs @@ -113,8 +113,7 @@ impl ColdStorage { // Hardened children require secret data to derive. let path = "84h/0h/0h".into_derivation_path()?; - let account_0_xpriv = - master_xpriv.derive_xpriv(&path).expect("derivation path is short"); + let account_0_xpriv = master_xpriv.derive_xpriv(&path).expect("derivation path is short"); let account_0_xpub = Xpub::from_xpriv(&account_0_xpriv); let path = INPUT_UTXO_DERIVATION_PATH.into_derivation_path()?; @@ -131,10 +130,7 @@ impl ColdStorage { fn master_fingerprint(&self) -> Fingerprint { self.master_xpub.fingerprint() } /// Signs `psbt` with this signer. - fn sign_psbt( - &self, - mut psbt: Psbt, - ) -> Result { + fn sign_psbt(&self, mut psbt: Psbt) -> Result { match psbt.sign(&self.master_xpriv) { Ok(keys) => assert_eq!(keys.len(), 1), Err((_, e)) => { @@ -249,9 +245,7 @@ impl WatchOnly { /// "m/84h/0h/0h/1/0"). A real wallet would have access to the chain so could determine if an /// address has been used or not. We ignore this detail and just re-use the first change address /// without loss of generality. - fn change_address( - &self, - ) -> Result<(CompressedPublicKey, Address, DerivationPath)> { + fn change_address(&self) -> Result<(CompressedPublicKey, Address, DerivationPath)> { let path = [ChildNumber::ONE_NORMAL, ChildNumber::ZERO_NORMAL]; let derived = self.account_0_xpub.derive_xpub(path)?; diff --git a/bitcoin/examples/taproot-psbt-simple.rs b/bitcoin/examples/taproot-psbt-simple.rs index 9ab4bfe455..6bb28580c2 100644 --- a/bitcoin/examples/taproot-psbt-simple.rs +++ b/bitcoin/examples/taproot-psbt-simple.rs @@ -52,10 +52,7 @@ const SPEND_AMOUNT: Amount = Amount::from_sat_u32(25_000_000); const CHANGE_AMOUNT: Amount = Amount::from_sat_u32(4_990_000); // 10_000 sat fee. // Derive the external address xpriv. -fn get_external_address_xpriv( - master_xpriv: Xpriv, - index: u32, -) -> Xpriv { +fn get_external_address_xpriv(master_xpriv: Xpriv, index: u32) -> Xpriv { let derivation_path = BIP86_DERIVATION_PATH.into_derivation_path().expect("valid derivation path"); let child_xpriv = @@ -67,10 +64,7 @@ fn get_external_address_xpriv( } // Derive the internal address xpriv. -fn get_internal_address_xpriv( - master_xpriv: Xpriv, - index: u32, -) -> Xpriv { +fn get_internal_address_xpriv(master_xpriv: Xpriv, index: u32) -> Xpriv { let derivation_path = BIP86_DERIVATION_PATH.into_derivation_path().expect("valid derivation path"); let child_xpriv = diff --git a/bitcoin/examples/taproot-psbt.rs b/bitcoin/examples/taproot-psbt.rs index f10be95091..2b5ef494b5 100644 --- a/bitcoin/examples/taproot-psbt.rs +++ b/bitcoin/examples/taproot-psbt.rs @@ -291,8 +291,7 @@ fn generate_bip86_key_spend_tx( .get(&input.tap_internal_key.ok_or("internal key missing in PSBT")?) .ok_or("missing Taproot key origin")?; - let secret_key = - master_xpriv.derive_xpriv(derivation_path)?.to_private_key().inner; + let secret_key = master_xpriv.derive_xpriv(derivation_path)?.to_private_key().inner; sign_psbt_taproot( secret_key, input.tap_internal_key.unwrap(), @@ -482,10 +481,8 @@ impl BenefactorWallet { .derive_xpriv(&new_derivation_path) .expect("derivation path is short") .to_keypair(); - let beneficiary_key = self - .beneficiary_xpub - .derive_xpub(&new_derivation_path)? - .to_x_only_public_key(); + let beneficiary_key = + self.beneficiary_xpub.derive_xpub(&new_derivation_path)?.to_x_only_public_key(); // Build up the leaf script and combine with internal key into a Taproot commitment let lock_time = absolute::LockTime::from_height( diff --git a/bitcoin/src/bip152.rs b/bitcoin/src/bip152.rs index 7095e3aa12..acf76d2ef8 100644 --- a/bitcoin/src/bip152.rs +++ b/bitcoin/src/bip152.rs @@ -402,9 +402,7 @@ impl BlockTransactions { #[cfg(feature = "arbitrary")] impl<'a> Arbitrary<'a> for ShortId { - fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { - Ok(Self(u.arbitrary()?)) - } + fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { Ok(Self(u.arbitrary()?)) } } #[cfg(feature = "arbitrary")] @@ -429,20 +427,14 @@ impl<'a> Arbitrary<'a> for HeaderAndShortIds { #[cfg(feature = "arbitrary")] impl<'a> Arbitrary<'a> for BlockTransactions { fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { - Ok(Self { - block_hash: u.arbitrary()?, - transactions: Vec::::arbitrary(u)?, - }) + Ok(Self { block_hash: u.arbitrary()?, transactions: Vec::::arbitrary(u)? }) } } #[cfg(feature = "arbitrary")] impl<'a> Arbitrary<'a> for BlockTransactionsRequest { fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { - Ok(Self { - block_hash: u.arbitrary()?, - indexes: Vec::::arbitrary(u)?, - }) + Ok(Self { block_hash: u.arbitrary()?, indexes: Vec::::arbitrary(u)? }) } } diff --git a/bitcoin/src/bip158.rs b/bitcoin/src/bip158.rs index 928c3d0d49..328b991aee 100644 --- a/bitcoin/src/bip158.rs +++ b/bitcoin/src/bip158.rs @@ -490,9 +490,7 @@ pub struct BitStreamReader<'a, R: ?Sized> { impl<'a, R: BufRead + ?Sized> BitStreamReader<'a, R> { /// Constructs a new [`BitStreamReader`] that reads bitwise from a given `reader`. - pub fn new(reader: &'a mut R) -> Self { - BitStreamReader { buffer: [0u8], reader, offset: 8 } - } + pub fn new(reader: &'a mut R) -> Self { BitStreamReader { buffer: [0u8], reader, offset: 8 } } /// Reads nbit bits, returning the bits in a `u64` starting with the rightmost bit. /// @@ -538,9 +536,7 @@ pub struct BitStreamWriter<'a, W> { impl<'a, W: Write> BitStreamWriter<'a, W> { /// Constructs a new [`BitStreamWriter`] that writes bitwise to a given `writer`. - pub fn new(writer: &'a mut W) -> Self { - BitStreamWriter { buffer: [0u8], writer, offset: 0 } - } + pub fn new(writer: &'a mut W) -> Self { BitStreamWriter { buffer: [0u8], writer, offset: 0 } } /// Writes nbits bits from data. pub fn write(&mut self, data: u64, mut nbits: u8) -> Result { diff --git a/bitcoin/src/bip32.rs b/bitcoin/src/bip32.rs index c8ec0d17bd..f829838fc0 100644 --- a/bitcoin/src/bip32.rs +++ b/bitcoin/src/bip32.rs @@ -619,9 +619,7 @@ impl From for ParseError { } impl From for ParseError { - fn from(e: InvalidBase58PayloadLengthError) -> Self { - Self::InvalidBase58PayloadLength(e) - } + fn from(e: InvalidBase58PayloadLengthError) -> Self { Self::InvalidBase58PayloadLength(e) } } /// A BIP-0032 error @@ -737,9 +735,7 @@ impl Xpriv { } /// Constructs a new extended public key from this extended private key. - pub fn to_xpub(self) -> Xpub { - Xpub::from_xpriv(&self) - } + pub fn to_xpub(self) -> Xpub { Xpub::from_xpriv(&self) } /// Constructs a new BIP-0340 keypair for Schnorr signatures and Taproot use matching the internal /// secret key representation. @@ -752,20 +748,14 @@ impl Xpriv { /// /// The `path` argument can be both of type `DerivationPath` or `Vec`. #[deprecated(since = "TBD", note = "use `derive_xpriv()` instead")] - pub fn derive_priv>( - &self, - path: P, - ) -> Result { + pub fn derive_priv>(&self, path: P) -> Result { self.derive_xpriv(path) } /// Derives an extended private key from a path. /// /// The `path` argument can be both of type `DerivationPath` or `Vec`. - pub fn derive_xpriv>( - &self, - path: P, - ) -> Result { + pub fn derive_xpriv>(&self, path: P) -> Result { let mut sk: Self = *self; for cnum in path.as_ref() { sk = sk.ckd_priv(*cnum)?; @@ -774,10 +764,7 @@ impl Xpriv { } /// Private->Private child key derivation - fn ckd_priv( - &self, - i: ChildNumber, - ) -> Result { + fn ckd_priv(&self, i: ChildNumber) -> Result { let mut engine = HmacEngine::::new(&self.chain_code[..]); match i { ChildNumber::Normal { .. } => { @@ -795,9 +782,10 @@ impl Xpriv { engine.input(&u32::from(i).to_be_bytes()); let hmac: Hmac = engine.finalize(); - let sk = - secp256k1::SecretKey::from_secret_bytes(*hmac.as_byte_array().split_array::<32, 32>().0) - .expect("statistically impossible to hit"); + let sk = secp256k1::SecretKey::from_secret_bytes( + *hmac.as_byte_array().split_array::<32, 32>().0, + ) + .expect("statistically impossible to hit"); let tweaked = sk.add_tweak(&self.private_key.into()).expect("statistically impossible to hit"); @@ -854,9 +842,7 @@ impl Xpriv { } /// Returns the HASH160 of the public key belonging to the xpriv - pub fn identifier(&self) -> XKeyIdentifier { - Xpub::from_xpriv(self).identifier() - } + pub fn identifier(&self) -> XKeyIdentifier { Xpub::from_xpriv(self).identifier() } /// Returns the first four bytes of the identifier pub fn fingerprint(&self) -> Fingerprint { @@ -867,9 +853,7 @@ impl Xpriv { impl Xpub { /// Constructs a new extended public key from an extended private key. #[deprecated(since = "TBD", note = "use `from_xpriv()` instead")] - pub fn from_priv(sk: &Xpriv) -> Self { - Self::from_xpriv(sk) - } + pub fn from_priv(sk: &Xpriv) -> Self { Self::from_xpriv(sk) } /// Constructs a new extended public key from an extended private key. pub fn from_xpriv(xpriv: &Xpriv) -> Self { @@ -903,20 +887,14 @@ impl Xpub { /// /// The `path` argument can be any type implementing `AsRef`, such as `DerivationPath`, for instance. #[deprecated(since = "TBD", note = "use `derive_xpub()` instead")] - pub fn derive_pub>( - &self, - path: P, - ) -> Result { + pub fn derive_pub>(&self, path: P) -> Result { self.derive_xpub(path) } /// Attempts to derive an extended public key from a path. /// /// The `path` argument can be any type implementing `AsRef`, such as `DerivationPath`, for instance. - pub fn derive_xpub>( - &self, - path: P, - ) -> Result { + pub fn derive_xpub>(&self, path: P) -> Result { let mut pk: Self = *self; for cnum in path.as_ref() { pk = pk.ckd_pub(*cnum)? @@ -948,10 +926,7 @@ impl Xpub { } /// Public->Public child key derivation - pub fn ckd_pub( - &self, - i: ChildNumber, - ) -> Result { + pub fn ckd_pub(&self, i: ChildNumber) -> Result { let (sk, chain_code) = self.ckd_pub_tweak(i)?; let tweaked = self.public_key.add_exp_tweak(&sk.into()).expect("cryptographically unreachable"); @@ -1307,10 +1282,7 @@ mod tests { // Check derivation convenience method for Xpub, should error // appropriately if any ChildNumber is hardened if path.0.iter().any(|cnum| cnum.is_hardened()) { - assert_eq!( - pk.derive_xpub(&path), - Err(DerivationError::CannotDeriveHardenedChild) - ); + assert_eq!(pk.derive_xpub(&path), Err(DerivationError::CannotDeriveHardenedChild)); } else { assert_eq!(&pk.derive_xpub(&path).unwrap().to_string()[..], expected_pk); } @@ -1325,10 +1297,7 @@ mod tests { assert_eq!(pk, pk2); } Hardened { .. } => { - assert_eq!( - pk.ckd_pub(num), - Err(DerivationError::CannotDeriveHardenedChild) - ); + assert_eq!(pk.ckd_pub(num), Err(DerivationError::CannotDeriveHardenedChild)); pk = Xpub::from_xpriv(&sk); } } @@ -1389,7 +1358,6 @@ mod tests { #[test] fn vector_1() { - let seed = hex!("000102030405060708090a0b0c0d0e0f"); // m diff --git a/bitcoin/src/blockdata/block.rs b/bitcoin/src/blockdata/block.rs index a5e574f57c..2ea23cbd8b 100644 --- a/bitcoin/src/blockdata/block.rs +++ b/bitcoin/src/blockdata/block.rs @@ -18,7 +18,7 @@ use crate::consensus::encode::{self, Decodable, Encodable, WriteExt as _}; use crate::merkle_tree::{MerkleNode as _, TxMerkleNode, WitnessMerkleNode}; use crate::network::Params; use crate::prelude::Vec; -use crate::script::{self, ScriptIntError, ScriptExt as _}; +use crate::script::{self, ScriptExt as _, ScriptIntError}; use crate::transaction::{Coinbase, Transaction, TransactionExt as _, Wtxid}; use crate::{internal_macros, BlockTime, Target, Weight, Work}; diff --git a/bitcoin/src/blockdata/mod.rs b/bitcoin/src/blockdata/mod.rs index bc18d858ec..9758dc2ae3 100644 --- a/bitcoin/src/blockdata/mod.rs +++ b/bitcoin/src/blockdata/mod.rs @@ -45,7 +45,8 @@ pub mod locktime { pub use units::locktime::absolute::{error, Height, LockTime, MedianTimePast}; #[doc(no_inline)] pub use units::locktime::absolute::{ - ConversionError, IncompatibleHeightError, IncompatibleTimeError, ParseHeightError, ParseTimeError, + ConversionError, IncompatibleHeightError, IncompatibleTimeError, ParseHeightError, + ParseTimeError, }; #[deprecated(since = "TBD", note = "use `MedianTimePast` instead")] @@ -76,9 +77,7 @@ pub mod locktime { /// Re-export everything from the `units::locktime::relative` module. #[doc(inline)] - pub use units::locktime::relative::{ - error, LockTime, NumberOf512Seconds, NumberOfBlocks, - }; + pub use units::locktime::relative::{error, LockTime, NumberOf512Seconds, NumberOfBlocks}; #[doc(no_inline)] pub use units::locktime::relative::{ DisabledLockTimeError, InvalidHeightError, InvalidTimeError, IsSatisfiedByError, diff --git a/bitcoin/src/blockdata/script/push_bytes.rs b/bitcoin/src/blockdata/script/push_bytes.rs index 386d81e01c..aa3cfa2c56 100644 --- a/bitcoin/src/blockdata/script/push_bytes.rs +++ b/bitcoin/src/blockdata/script/push_bytes.rs @@ -2,8 +2,8 @@ //! Contains `PushBytes` & co -use core::ops::{Deref, DerefMut}; use core::fmt; +use core::ops::{Deref, DerefMut}; use crate::prelude::{Borrow, BorrowMut}; use crate::script; diff --git a/bitcoin/src/blockdata/script/tests.rs b/bitcoin/src/blockdata/script/tests.rs index 276c863030..55aae7980e 100644 --- a/bitcoin/src/blockdata/script/tests.rs +++ b/bitcoin/src/blockdata/script/tests.rs @@ -395,13 +395,15 @@ fn scriptint_round_trip() { Ok(i), PushBytes::read_scriptint( <&PushBytes>::try_from(build_scriptint(i).as_slice()).unwrap() - ).map(i64::from) + ) + .map(i64::from) ); assert_eq!( Ok(-i), PushBytes::read_scriptint( <&PushBytes>::try_from(build_scriptint(-i).as_slice()).unwrap() - ).map(i64::from) + ) + .map(i64::from) ); assert_eq!(Ok(i), read_scriptint_non_minimal(&build_scriptint(i)).map(i64::from)); assert_eq!(Ok(-i), read_scriptint_non_minimal(&build_scriptint(-i)).map(i64::from)); diff --git a/bitcoin/src/blockdata/script/witness_program.rs b/bitcoin/src/blockdata/script/witness_program.rs index d6ac03194f..477a6d2abc 100644 --- a/bitcoin/src/blockdata/script/witness_program.rs +++ b/bitcoin/src/blockdata/script/witness_program.rs @@ -86,9 +86,7 @@ impl WitnessProgram { } /// Constructs a new [`WitnessProgram`] from `script` for a P2WSH output. - pub fn p2wsh_from_hash(hash: WScriptHash) -> Self { - Self::new_p2wsh(hash.to_byte_array()) - } + pub fn p2wsh_from_hash(hash: WScriptHash) -> Self { Self::new_p2wsh(hash.to_byte_array()) } /// Constructs a new [`WitnessProgram`] from an untweaked key for a P2TR output. /// diff --git a/bitcoin/src/blockdata/transaction.rs b/bitcoin/src/blockdata/transaction.rs index de043691e6..7dc75cc577 100644 --- a/bitcoin/src/blockdata/transaction.rs +++ b/bitcoin/src/blockdata/transaction.rs @@ -700,10 +700,7 @@ impl Encodable for OutPoint { } impl Decodable for OutPoint { fn consensus_decode(r: &mut R) -> Result { - Ok(Self { - txid: Decodable::consensus_decode(r)?, - vout: Decodable::consensus_decode(r)?, - }) + Ok(Self { txid: Decodable::consensus_decode(r)?, vout: Decodable::consensus_decode(r)? }) } } diff --git a/bitcoin/src/consensus/encode.rs b/bitcoin/src/consensus/encode.rs index ff669c7fa3..14fc8a86cc 100644 --- a/bitcoin/src/consensus/encode.rs +++ b/bitcoin/src/consensus/encode.rs @@ -489,9 +489,7 @@ impl Encodable for Vec { impl Decodable for Vec { #[inline] - fn consensus_decode_from_finite_reader( - r: &mut R, - ) -> Result { + fn consensus_decode_from_finite_reader(r: &mut R) -> Result { if TypeId::of::() == TypeId::of::() { let len = r.read_compact_size()? as usize; // most real-world vec of bytes data, wouldn't be larger than 128KiB diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs index e0ce609c60..79cb2df59b 100644 --- a/bitcoin/src/crypto/key.rs +++ b/bitcoin/src/crypto/key.rs @@ -312,11 +312,7 @@ impl PublicKey { } /// Computes the public key as supposed to be used with this secret. - pub fn from_private_key( - sk: PrivateKey, - ) -> Self { - sk.public_key() - } + pub fn from_private_key(sk: PrivateKey) -> Self { sk.public_key() } /// Checks that `sig` is a valid ECDSA signature for `msg` using this public key. pub fn verify( @@ -452,9 +448,7 @@ impl CompressedPublicKey { } /// Computes the public key as supposed to be used with this secret. - pub fn from_private_key( - sk: PrivateKey, - ) -> Result { + pub fn from_private_key(sk: PrivateKey) -> Result { sk.public_key().try_into() } @@ -901,10 +895,7 @@ pub trait TapTweak { /// # Returns /// /// The tweaked key and its parity. - fn tap_tweak( - self, - merkle_root: Option, - ) -> Self::TweakedAux; + fn tap_tweak(self, merkle_root: Option) -> Self::TweakedAux; /// Directly converts an [`UntweakedPublicKey`] to a [`TweakedPublicKey`]. /// @@ -930,10 +921,7 @@ impl TapTweak for UntweakedPublicKey { /// # Returns /// /// The tweaked key and its parity. - fn tap_tweak( - self, - merkle_root: Option, - ) -> (TweakedPublicKey, Parity) { + fn tap_tweak(self, merkle_root: Option) -> (TweakedPublicKey, Parity) { let tweak = TapTweakHash::from_key_and_merkle_root(self, merkle_root).to_scalar(); let (output_key, parity) = self.add_tweak(&tweak).expect("Tap tweak failed"); @@ -958,10 +946,7 @@ impl TapTweak for UntweakedKeypair { /// # Returns /// /// The tweaked keypair. - fn tap_tweak( - self, - merkle_root: Option, - ) -> TweakedKeypair { + fn tap_tweak(self, merkle_root: Option) -> TweakedKeypair { let (pubkey, _parity) = XOnlyPublicKey::from_keypair(&self); let tweak = TapTweakHash::from_key_and_merkle_root(pubkey, merkle_root).to_scalar(); let tweaked = self.add_xonly_tweak(&tweak).expect("Tap tweak failed"); @@ -1828,7 +1813,8 @@ mod tests { fn xonly_pubkey_from_bytes() { let key_bytes = &<[u8; 32]>::from_hex( "5b1e57ec453cd33fdc7cfc901450a3931fd315422558f2fb7fefb064e6e7d60d", - ).expect("Failed to convert hex string to byte array"); + ) + .expect("Failed to convert hex string to byte array"); let xonly_pub_key = XOnlyPublicKey::from_byte_array(key_bytes) .expect("Failed to create an XOnlyPublicKey from a byte array"); // Confirm that the public key from bytes serializes back to the same bytes @@ -1839,7 +1825,8 @@ mod tests { fn xonly_pubkey_into_inner() { let key_bytes = &<[u8; 32]>::from_hex( "5b1e57ec453cd33fdc7cfc901450a3931fd315422558f2fb7fefb064e6e7d60d", - ).expect("Failed to convert hex string to byte array"); + ) + .expect("Failed to convert hex string to byte array"); let inner_key = secp256k1::XOnlyPublicKey::from_byte_array(*key_bytes) .expect("Failed to create a secp256k1 x-only public key from a byte array"); let btc_pubkey = XOnlyPublicKey::new(inner_key); diff --git a/bitcoin/src/crypto/sighash.rs b/bitcoin/src/crypto/sighash.rs index a966a4e767..b7fd1b63b7 100644 --- a/bitcoin/src/crypto/sighash.rs +++ b/bitcoin/src/crypto/sighash.rs @@ -1441,10 +1441,8 @@ impl EncodeSigningDataResult { { match self { Self::SighashSingleBug => EncodeSigningDataResult::SighashSingleBug, - Self::WriteResult(Err(e)) => - EncodeSigningDataResult::WriteResult(Err(f(e))), - Self::WriteResult(Ok(o)) => - EncodeSigningDataResult::WriteResult(Ok(o)), + Self::WriteResult(Err(e)) => EncodeSigningDataResult::WriteResult(Err(f(e))), + Self::WriteResult(Ok(o)) => EncodeSigningDataResult::WriteResult(Ok(o)), } } } diff --git a/bitcoin/src/lib.rs b/bitcoin/src/lib.rs index b2ccc98cfd..15b49aab1f 100644 --- a/bitcoin/src/lib.rs +++ b/bitcoin/src/lib.rs @@ -147,11 +147,13 @@ pub use primitives::{ merkle_tree::{TxMerkleNode, WitnessMerkleNode}, pow::CompactTarget, // No `pow` module outside of `primitives`. script::{ - RedeemScript, RedeemScriptBuf, ScriptPubKey, ScriptPubKeyBuf, ScriptSig, ScriptSigBuf, - TapScript, TapScriptBuf, WitnessScript, WitnessScriptBuf, ScriptHashableTag, - Tag, RedeemScriptTag, ScriptPubKeyTag, ScriptSigTag, TapScriptTag, WitnessScriptTag, + RedeemScript, RedeemScriptBuf, RedeemScriptTag, ScriptHashableTag, ScriptPubKey, + ScriptPubKeyBuf, ScriptPubKeyTag, ScriptSig, ScriptSigBuf, ScriptSigTag, Tag, TapScript, + TapScriptBuf, TapScriptTag, WitnessScript, WitnessScriptBuf, WitnessScriptTag, + }, + transaction::{ + Ntxid, OutPoint, Transaction, TxIn, TxOut, Txid, Version as TransactionVersion, Wtxid, }, - transaction::{Ntxid, OutPoint, Transaction, TxIn, TxOut, Txid, Version as TransactionVersion, Wtxid}, witness::Witness, }; #[doc(inline)] diff --git a/bitcoin/src/merkle_tree/block.rs b/bitcoin/src/merkle_tree/block.rs index 4b6edc1c4c..975c2b40c9 100644 --- a/bitcoin/src/merkle_tree/block.rs +++ b/bitcoin/src/merkle_tree/block.rs @@ -129,10 +129,7 @@ impl Encodable for MerkleBlock { impl Decodable for MerkleBlock { fn consensus_decode(r: &mut R) -> Result { - Ok(Self { - header: Decodable::consensus_decode(r)?, - txn: Decodable::consensus_decode(r)?, - }) + Ok(Self { header: Decodable::consensus_decode(r)?, txn: Decodable::consensus_decode(r)? }) } } diff --git a/bitcoin/src/psbt/map/input.rs b/bitcoin/src/psbt/map/input.rs index e38c87dd49..3d19185e78 100644 --- a/bitcoin/src/psbt/map/input.rs +++ b/bitcoin/src/psbt/map/input.rs @@ -176,15 +176,11 @@ impl FromStr for PsbtSighashType { } } impl From for PsbtSighashType { - fn from(ecdsa_hash_ty: EcdsaSighashType) -> Self { - Self { inner: ecdsa_hash_ty as u32 } - } + fn from(ecdsa_hash_ty: EcdsaSighashType) -> Self { Self { inner: ecdsa_hash_ty as u32 } } } impl From for PsbtSighashType { - fn from(taproot_hash_ty: TapSighashType) -> Self { - Self { inner: taproot_hash_ty as u32 } - } + fn from(taproot_hash_ty: TapSighashType) -> Self { Self { inner: taproot_hash_ty as u32 } } } impl PsbtSighashType { diff --git a/bitcoin/src/psbt/mod.rs b/bitcoin/src/psbt/mod.rs index faf9f35b29..6492303d7e 100644 --- a/bitcoin/src/psbt/mod.rs +++ b/bitcoin/src/psbt/mod.rs @@ -290,10 +290,7 @@ impl Psbt { /// /// If an error is returned some signatures may already have been added to the PSBT. Since /// `partial_sigs` is a [`BTreeMap`] it is safe to retry, previous sigs will be overwritten. - pub fn sign( - &mut self, - k: &K, - ) -> Result + pub fn sign(&mut self, k: &K) -> Result where K: GetKey, { @@ -305,25 +302,22 @@ impl Psbt { for i in 0..self.inputs.len() { match self.signing_algorithm(i) { - Ok(SigningAlgorithm::Ecdsa) => - match self.bip32_sign_ecdsa(k, i, &mut cache) { - Ok(v) => { - used.insert(i, SigningKeys::Ecdsa(v)); - } - Err(e) => { - errors.insert(i, e); - } - }, - Ok(SigningAlgorithm::Schnorr) => { - match self.bip32_sign_schnorr(k, i, &mut cache) { - Ok(v) => { - used.insert(i, SigningKeys::Schnorr(v)); - } - Err(e) => { - errors.insert(i, e); - } + Ok(SigningAlgorithm::Ecdsa) => match self.bip32_sign_ecdsa(k, i, &mut cache) { + Ok(v) => { + used.insert(i, SigningKeys::Ecdsa(v)); } - } + Err(e) => { + errors.insert(i, e); + } + }, + Ok(SigningAlgorithm::Schnorr) => match self.bip32_sign_schnorr(k, i, &mut cache) { + Ok(v) => { + used.insert(i, SigningKeys::Schnorr(v)); + } + Err(e) => { + errors.insert(i, e); + } + }, Err(e) => { errors.insert(i, e); } @@ -411,8 +405,7 @@ impl Psbt { let mut used = vec![]; // List of pubkeys used to sign the input. for (&xonly, (leaf_hashes, key_source)) in input.tap_key_origins.iter() { - let sk = if let Ok(Some(secret_key)) = - k.get_key(&KeyRequest::Bip32(key_source.clone())) + let sk = if let Ok(Some(secret_key)) = k.get_key(&KeyRequest::Bip32(key_source.clone())) { secret_key } else if let Ok(Some(sk)) = k.get_key(&KeyRequest::XOnlyPubkey(xonly)) { @@ -467,10 +460,13 @@ impl Psbt { self.sighash_taproot(input_index, cache, Some(lh))?; #[cfg(feature = "rand-std")] - let signature = secp256k1::schnorr::sign(&sighash.to_byte_array(), &key_pair); - #[cfg(not(feature = "rand-std"))] let signature = - secp256k1::schnorr::sign_no_aux_rand(&sighash.to_byte_array(), &key_pair); + secp256k1::schnorr::sign(&sighash.to_byte_array(), &key_pair); + #[cfg(not(feature = "rand-std"))] + let signature = secp256k1::schnorr::sign_no_aux_rand( + &sighash.to_byte_array(), + &key_pair, + ); let signature = taproot::Signature { signature, sighash_type }; input.tap_script_sigs.insert((xonly, lh), signature); @@ -795,19 +791,13 @@ pub trait GetKey { /// - `Some(key)` if the key is found. /// - `None` if the key was not found but no error was encountered. /// - `Err` if an error was encountered while looking for the key. - fn get_key( - &self, - key_request: &KeyRequest, - ) -> Result, Self::Error>; + fn get_key(&self, key_request: &KeyRequest) -> Result, Self::Error>; } impl GetKey for Xpriv { type Error = GetKeyError; - fn get_key( - &self, - key_request: &KeyRequest, - ) -> Result, Self::Error> { + fn get_key(&self, key_request: &KeyRequest) -> Result, Self::Error> { match key_request { KeyRequest::Pubkey(_) => Err(GetKeyError::NotSupported), KeyRequest::XOnlyPubkey(_) => Err(GetKeyError::NotSupported), @@ -1324,12 +1314,8 @@ mod tests { use hex_lit::hex; #[cfg(feature = "rand-std")] use { - crate::bip32::Fingerprint, - crate::locktime, - crate::script::ScriptPubKeyBufExt as _, - crate::witness_version::WitnessVersion, - crate::WitnessProgram, - secp256k1::SecretKey, + crate::bip32::Fingerprint, crate::locktime, crate::script::ScriptPubKeyBufExt as _, + crate::witness_version::WitnessVersion, crate::WitnessProgram, secp256k1::SecretKey, }; use super::*; @@ -2421,14 +2407,12 @@ mod tests { let path: DerivationPath = "m/1/2/3".parse().unwrap(); let path_prefix: DerivationPath = "m/1".parse().unwrap(); - let expected_private_key = - parent_xpriv.derive_xpriv(&path).unwrap().to_private_key(); + let expected_private_key = parent_xpriv.derive_xpriv(&path).unwrap().to_private_key(); let derived_xpriv = parent_xpriv.derive_xpriv(&path_prefix).unwrap(); - let derived_key = derived_xpriv - .get_key(&KeyRequest::Bip32((parent_xpriv.fingerprint(), path))) - .unwrap(); + let derived_key = + derived_xpriv.get_key(&KeyRequest::Bip32((parent_xpriv.fingerprint(), path))).unwrap(); assert_eq!(derived_key, Some(expected_private_key)); } diff --git a/bitcoin/src/sign_message.rs b/bitcoin/src/sign_message.rs index 853ea56595..ade3c1bcf8 100644 --- a/bitcoin/src/sign_message.rs +++ b/bitcoin/src/sign_message.rs @@ -76,9 +76,7 @@ mod message_signing { } impl From for MessageSignatureError { - fn from(e: secp256k1::Error) -> Self { - Self::InvalidEncoding(e) - } + fn from(e: secp256k1::Error) -> Self { Self::InvalidEncoding(e) } } /// A signature on a Bitcoin Signed Message. @@ -196,9 +194,7 @@ mod message_signing { impl core::str::FromStr for MessageSignature { type Err = MessageSignatureError; - fn from_str(s: &str) -> Result { - Self::from_base64(s) - } + fn from_str(s: &str) -> Result { Self::from_base64(s) } } } } @@ -215,10 +211,7 @@ pub fn signed_msg_hash(msg: impl AsRef<[u8]>) -> sha256d::Hash { /// Sign message using Bitcoin's message signing format. #[cfg(feature = "secp-recovery")] -pub fn sign( - msg: impl AsRef<[u8]>, - privkey: SecretKey, -) -> MessageSignature { +pub fn sign(msg: impl AsRef<[u8]>, privkey: SecretKey) -> MessageSignature { use secp256k1::ecdsa::RecoverableSignature; let msg_hash = signed_msg_hash(msg); @@ -244,6 +237,7 @@ mod tests { #[cfg(all(feature = "secp-recovery", feature = "base64", feature = "rand-std"))] fn message_signature() { use secp256k1::ecdsa::RecoverableSignature; + use crate::{Address, AddressType, Network, NetworkKind}; let message = "rust-bitcoin MessageSignature test"; diff --git a/bitcoin/src/taproot/mod.rs b/bitcoin/src/taproot/mod.rs index 24bf7fa6a7..341419e006 100644 --- a/bitcoin/src/taproot/mod.rs +++ b/bitcoin/src/taproot/mod.rs @@ -142,9 +142,7 @@ impl From<&LeafNode> for TapNodeHash { impl TapNodeHash { /// Computes branch hash given two hashes of the nodes underneath it. - pub fn from_node_hashes(a: Self, b: Self) -> Self { - combine_node_hashes(a, b).0 - } + pub fn from_node_hashes(a: Self, b: Self) -> Self { combine_node_hashes(a, b).0 } /// Assumes the given 32 byte array as hidden [`TapNodeHash`]. /// @@ -313,10 +311,7 @@ impl TaprootSpendInfo { /// /// This is useful when you want to manually build a Taproot tree without using /// [`TaprootBuilder`]. - pub fn from_node_info>( - internal_key: K, - node: NodeInfo, - ) -> Self { + pub fn from_node_info>(internal_key: K, node: NodeInfo) -> Self { // Create as if it is a key spend path with the given Merkle root let root_hash = Some(node.hash); let mut info = Self::new_key_spend(internal_key, root_hash); @@ -424,9 +419,7 @@ impl TaprootBuilder { /// Constructs a new instance of [`TaprootBuilder`] with a capacity hint for `size` elements. /// /// The size here should be maximum depth of the tree. - pub fn with_capacity(size: usize) -> Self { - Self { branch: Vec::with_capacity(size) } - } + pub fn with_capacity(size: usize) -> Self { Self { branch: Vec::with_capacity(size) } } /// Constructs a new [`TaprootSpendInfo`] from a list of scripts (with default script version) and /// weights of satisfaction for that script. @@ -567,9 +560,7 @@ impl TaprootBuilder { let node = self.try_into_node_info()?; if node.has_hidden_nodes { // Reconstruct the builder as it was if it has hidden nodes - return Err(IncompleteBuilderError::HiddenParts(Self { - branch: vec![Some(node)], - })); + return Err(IncompleteBuilderError::HiddenParts(Self { branch: vec![Some(node)] })); } Ok(TapTree(node)) } @@ -1316,9 +1307,7 @@ impl + ?Sized> ControlBlock { pub struct FutureLeafVersion(u8); impl FutureLeafVersion { - pub(self) fn from_consensus( - version: u8, - ) -> Result { + pub(self) fn from_consensus(version: u8) -> Result { match version { TAPROOT_LEAF_TAPSCRIPT => unreachable!( "FutureLeafVersion::from_consensus should never be called for 0xC0 value" @@ -1775,20 +1764,13 @@ mod test { ); } - fn _verify_tap_commitments( - out_spk_hex: &str, - script_hex: &str, - control_block_hex: &str, - ) { + fn _verify_tap_commitments(out_spk_hex: &str, script_hex: &str, control_block_hex: &str) { let out_pk = out_spk_hex[4..].parse::().unwrap(); let out_pk = TweakedPublicKey::dangerous_assume_tweaked(out_pk); let script = TapScriptBuf::from_hex_no_length_prefix(script_hex).unwrap(); let control_block = ControlBlock::from_hex(control_block_hex).unwrap(); assert_eq!(control_block_hex, control_block.serialize().to_lower_hex_string()); - assert!(control_block.verify_taproot_commitment( - out_pk.to_x_only_public_key(), - &script - )); + assert!(control_block.verify_taproot_commitment(out_pk.to_x_only_public_key(), &script)); } #[test] @@ -1852,8 +1834,7 @@ mod test { (19, TapScriptBuf::from_hex_no_length_prefix("55").unwrap()), ]; let tree_info = - TaprootSpendInfo::with_huffman_tree(internal_key, script_weights.clone()) - .unwrap(); + TaprootSpendInfo::with_huffman_tree(internal_key, script_weights.clone()).unwrap(); /* The resulting tree should put the scripts into a tree similar * to the following: @@ -1889,10 +1870,8 @@ mod test { for (_weights, script) in script_weights { let ver_script = (script, LeafVersion::TapScript); let ctrl_block = tree_info.control_block(&ver_script).unwrap(); - assert!(ctrl_block.verify_taproot_commitment( - output_key.to_x_only_public_key(), - &ver_script.0 - )) + assert!(ctrl_block + .verify_taproot_commitment(output_key.to_x_only_public_key(), &ver_script.0)) } } @@ -1961,10 +1940,8 @@ mod test { for script in [a, b, c, d, e] { let ver_script = (script, LeafVersion::TapScript); let ctrl_block = tree_info.control_block(&ver_script).unwrap(); - assert!(ctrl_block.verify_taproot_commitment( - output_key.to_x_only_public_key(), - &ver_script.0 - )) + assert!(ctrl_block + .verify_taproot_commitment(output_key.to_x_only_public_key(), &ver_script.0)) } } diff --git a/bitcoin/src/taproot/serialized_signature.rs b/bitcoin/src/taproot/serialized_signature.rs index 839fc5bff3..c867e66e4b 100644 --- a/bitcoin/src/taproot/serialized_signature.rs +++ b/bitcoin/src/taproot/serialized_signature.rs @@ -48,9 +48,7 @@ impl PartialEq for [u8] { } impl PartialOrd for SerializedSignature { - 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 SerializedSignature { diff --git a/bitcoin/tests/psbt-sign-taproot.rs b/bitcoin/tests/psbt-sign-taproot.rs index edeeb161c2..27e8915420 100644 --- a/bitcoin/tests/psbt-sign-taproot.rs +++ b/bitcoin/tests/psbt-sign-taproot.rs @@ -24,10 +24,7 @@ fn psbt_sign_taproot() { impl GetKey for Keystore { type Error = SignError; - fn get_key( - &self, - key_request: &KeyRequest, - ) -> Result, Self::Error> { + fn get_key(&self, key_request: &KeyRequest) -> Result, Self::Error> { match key_request { KeyRequest::Bip32((mfp, _)) => if *mfp == self.mfp { @@ -61,8 +58,7 @@ fn psbt_sign_taproot() { let internal_key = kp.x_only_public_key().0; // Ignore the parity. - let tree = - create_taproot_tree(script1, script2.clone(), script3, internal_key); + let tree = create_taproot_tree(script1, script2.clone(), script3, internal_key); let address = create_p2tr_address(tree.clone()); assert_eq!( diff --git a/consensus_encoding/src/decode/decoders.rs b/consensus_encoding/src/decode/decoders.rs index 6eca939b7a..3f2074a9c9 100644 --- a/consensus_encoding/src/decode/decoders.rs +++ b/consensus_encoding/src/decode/decoders.rs @@ -347,7 +347,9 @@ where B: Decoder, { /// Constructs a new composite decoder. - pub const fn new(first: A, second: B) -> Self { Self { state: Decoder2State::First(first, second) } } + pub const fn new(first: A, second: B) -> Self { + Self { state: Decoder2State::First(first, second) } + } } impl Decoder for Decoder2 diff --git a/fuzz/fuzz_targets/units/standard_checks.rs b/fuzz/fuzz_targets/units/standard_checks.rs index 933ab6336a..24b1c91747 100644 --- a/fuzz/fuzz_targets/units/standard_checks.rs +++ b/fuzz/fuzz_targets/units/standard_checks.rs @@ -1,25 +1,11 @@ +use bitcoin::absolute::{Height, MedianTimePast}; +use bitcoin::relative::{NumberOf512Seconds, NumberOfBlocks}; use bitcoin::{ - Amount, - BlockHeight, - BlockHeightInterval, - BlockMtp, - BlockMtpInterval, - BlockTime, - FeeRate, - Sequence, - SignedAmount, - Weight, - absolute::{ - Height, - MedianTimePast - }, - relative::{ - NumberOfBlocks, - NumberOf512Seconds - } + Amount, BlockHeight, BlockHeightInterval, BlockMtp, BlockMtpInterval, BlockTime, FeeRate, + Sequence, SignedAmount, Weight, }; -use standard_test::StandardChecks as _; use honggfuzz::fuzz; +use standard_test::StandardChecks as _; /// Implements the traits on the wrapper type $ty. Intended only to be called from inside wrap_for_checks! macro_rules! _impl_traits_on_wrapper { @@ -50,18 +36,17 @@ macro_rules! _impl_traits_on_wrapper { macro_rules! wrap_for_checks { ($ty:ident) => { #[derive(Default)] - pub(crate) struct $ty (super::$ty); + pub(crate) struct $ty(super::$ty); _impl_traits_on_wrapper!($ty); }; ($ty:ident, $default:expr) => { - pub(crate) struct $ty (super::$ty); + pub(crate) struct $ty(super::$ty); _impl_traits_on_wrapper!($ty, $default); }; } - mod fuzz { use standard_test::standard_checks; diff --git a/hashes/src/hmac/mod.rs b/hashes/src/hmac/mod.rs index b1939fd6a0..dc96379f76 100644 --- a/hashes/src/hmac/mod.rs +++ b/hashes/src/hmac/mod.rs @@ -82,9 +82,7 @@ impl HmacEngine { } /// A special constructor giving direct access to the underlying "inner" and "outer" engines. - pub fn from_inner_engines(iengine: T, oengine: T) -> Self { - Self { iengine, oengine } - } + pub fn from_inner_engines(iengine: T, oengine: T) -> Self { Self { iengine, oengine } } } impl HashEngine for HmacEngine { diff --git a/io/src/lib.rs b/io/src/lib.rs index 4095236218..b0bd7acd22 100644 --- a/io/src/lib.rs +++ b/io/src/lib.rs @@ -45,10 +45,10 @@ use encoding::Encoder; #[rustfmt::skip] // Keep public re-exports separate. pub use self::error::{Error, ErrorKind}; -#[cfg(feature = "hashes")] -pub use self::hash::hash_reader; #[cfg(feature = "std")] pub use self::bridge::{FromStd, ToStd}; +#[cfg(feature = "hashes")] +pub use self::hash::hash_reader; /// Result type returned by functions in this crate. pub type Result = core::result::Result; @@ -85,8 +85,11 @@ pub trait Read { /// Constructs a new adapter which will read at most `limit` bytes. #[inline] fn take(self, limit: u64) -> Take - where Self: Sized, - { Take { reader: self, remaining: limit } } + where + Self: Sized, + { + Take { reader: self, remaining: limit } + } /// Attempts to read up to limit bytes from the reader, allocating space in `buf` as needed. /// diff --git a/p2p/src/lib.rs b/p2p/src/lib.rs index 6d9b723ea1..8ec20f3725 100644 --- a/p2p/src/lib.rs +++ b/p2p/src/lib.rs @@ -465,16 +465,12 @@ impl std::error::Error for UnknownNetworkError { #[cfg(feature = "arbitrary")] impl<'a> Arbitrary<'a> for ProtocolVersion { - fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { - Ok(Self(u.arbitrary()?)) - } + fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { Ok(Self(u.arbitrary()?)) } } #[cfg(feature = "arbitrary")] impl<'a> Arbitrary<'a> for ServiceFlags { - fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { - Ok(Self(u.arbitrary()?)) - } + fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { Ok(Self(u.arbitrary()?)) } } #[cfg(feature = "arbitrary")] diff --git a/p2p/src/message.rs b/p2p/src/message.rs index ec93e0a7ac..5a0d10498c 100644 --- a/p2p/src/message.rs +++ b/p2p/src/message.rs @@ -442,8 +442,7 @@ impl Encodable for NetworkMessage { Self::BlockTxn(ref dat) => dat.consensus_encode(writer), Self::Alert(ref dat) => dat.consensus_encode(writer), Self::Reject(ref dat) => dat.consensus_encode(writer), - Self::FeeFilter(ref dat) => - dat.to_sat_per_kvb_ceil().consensus_encode(writer), + Self::FeeFilter(ref dat) => dat.to_sat_per_kvb_ceil().consensus_encode(writer), Self::AddrV2(ref dat) => dat.consensus_encode(writer), Self::Verack | Self::SendHeaders @@ -890,9 +889,7 @@ impl<'a> Arbitrary<'a> for CommandString { #[cfg(feature = "arbitrary")] impl<'a> Arbitrary<'a> for HeadersMessage { - fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { - Ok(Self(u.arbitrary()?)) - } + fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { Ok(Self(u.arbitrary()?)) } } #[cfg(feature = "arbitrary")] @@ -935,10 +932,7 @@ impl<'a> Arbitrary<'a> for NetworkMessage { 33 => Ok(Self::WtxidRelay), 34 => Ok(Self::AddrV2(u.arbitrary()?)), 35 => Ok(Self::SendAddrV2), - _ => Ok(Self::Unknown { - command: u.arbitrary()?, - payload: Vec::::arbitrary(u)?, - }), + _ => Ok(Self::Unknown { command: u.arbitrary()?, payload: Vec::::arbitrary(u)? }), } } } diff --git a/p2p/src/message_network.rs b/p2p/src/message_network.rs index b5fa115407..58a43d67eb 100644 --- a/p2p/src/message_network.rs +++ b/p2p/src/message_network.rs @@ -334,11 +334,7 @@ impl_vec_wrapper!(Alert, Vec); impl<'a> Arbitrary<'a> for ClientSoftwareVersion { fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { match bool::arbitrary(u)? { - true => Ok(Self::Date { - yyyy: u.arbitrary()?, - mm: u.arbitrary()?, - dd: u.arbitrary()?, - }), + true => Ok(Self::Date { yyyy: u.arbitrary()?, mm: u.arbitrary()?, dd: u.arbitrary()? }), false => Ok(Self::SemVer { major: u.arbitrary()?, minor: u.arbitrary()?, diff --git a/primitives/src/block.rs b/primitives/src/block.rs index a4d3e0356e..0076473e6a 100644 --- a/primitives/src/block.rs +++ b/primitives/src/block.rs @@ -16,7 +16,9 @@ use core::marker::PhantomData; use arbitrary::{Arbitrary, Unstructured}; use encoding::Encodable; #[cfg(feature = "alloc")] -use encoding::{CompactSizeEncoder, Decodable, Decoder, Decoder2, Decoder6, Encoder2, SliceEncoder, VecDecoder}; +use encoding::{ + CompactSizeEncoder, Decodable, Decoder, Decoder2, Decoder6, Encoder2, SliceEncoder, VecDecoder, +}; use hashes::{sha256d, HashEngine as _}; use internals::write_err; @@ -234,10 +236,7 @@ impl Decoder for BlockDecoder { impl Decodable for Block { type Decoder = BlockDecoder; fn decoder() -> Self::Decoder { - BlockDecoder(Decoder2::new( - Header::decoder(), - VecDecoder::::new(), - )) + BlockDecoder(Decoder2::new(Header::decoder(), VecDecoder::::new())) } } @@ -906,16 +905,14 @@ mod tests { let header = Header { version: Version::ONE, prev_blockhash: BlockHash::from_byte_array([ - 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, - 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, - 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, - 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, + 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, + 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, 0xDC, 0xBA, + 0xDC, 0xBA, 0xDC, 0xBA, ]), merkle_root: TxMerkleNode::from_byte_array([ - 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, - 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, - 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, - 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, + 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, + 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, 0xAB, 0xCD, + 0xAB, 0xCD, 0xAB, 0xCD, ]), time: BlockTime::from(1_742_979_600), // 26 Mar 2025 9:00 UTC bits: CompactTarget::from_consensus(12_345_678), @@ -923,14 +920,12 @@ mod tests { }; let block: u32 = 741_521; - let transactions = vec![ - Transaction { - version: crate::transaction::Version::ONE, - lock_time: units::absolute::LockTime::from_height(block).unwrap(), - inputs: vec![crate::transaction::TxIn::EMPTY_COINBASE], - outputs: Vec::new(), - }, - ]; + let transactions = vec![Transaction { + version: crate::transaction::Version::ONE, + lock_time: units::absolute::LockTime::from_height(block).unwrap(), + inputs: vec![crate::transaction::TxIn::EMPTY_COINBASE], + outputs: Vec::new(), + }]; let original_block = Block::new_unchecked(header, transactions); // Encode + decode the block diff --git a/primitives/src/witness.rs b/primitives/src/witness.rs index e3dacc81de..0489ff031b 100644 --- a/primitives/src/witness.rs +++ b/primitives/src/witness.rs @@ -1024,8 +1024,7 @@ mod test { let witness_elements = 2; let content = append_u32_vec(&elements, &[0, 2]); let indices_start = elements.len(); - let witness = - Witness::from_parts__unstable(content, witness_elements, indices_start); + let witness = Witness::from_parts__unstable(content, witness_elements, indices_start); assert_eq!(witness.get(0).unwrap(), [11_u8]); assert_eq!(witness.get(1).unwrap(), [21_u8, 22]); assert_eq!(witness.size(), 6); diff --git a/units/src/amount/error.rs b/units/src/amount/error.rs index 2914c051cd..6b577e6d68 100644 --- a/units/src/amount/error.rs +++ b/units/src/amount/error.rs @@ -218,9 +218,7 @@ impl fmt::Display for OutOfRangeError { impl std::error::Error for OutOfRangeError {} impl From for ParseAmountError { - fn from(value: OutOfRangeError) -> Self { - Self(ParseAmountErrorInner::OutOfRange(value)) - } + fn from(value: OutOfRangeError) -> Self { Self(ParseAmountErrorInner::OutOfRange(value)) } } /// Error returned when the input string has higher precision than satoshis. diff --git a/units/src/block.rs b/units/src/block.rs index 6f9f7dc110..5d8243ba1c 100644 --- a/units/src/block.rs +++ b/units/src/block.rs @@ -140,9 +140,7 @@ impl TryFrom for absolute::Height { /// /// An absolute locktime block height has a maximum value of [`absolute::LOCK_TIME_THRESHOLD`] /// minus one, while [`BlockHeight`] may take the full range of `u32`. - fn try_from(h: BlockHeight) -> Result { - Self::from_u32(h.to_u32()) - } + fn try_from(h: BlockHeight) -> Result { Self::from_u32(h.to_u32()) } } #[cfg(feature = "encoding")] @@ -354,9 +352,7 @@ impl TryFrom for absolute::MedianTimePast { /// /// An absolute locktime MTP has a minimum value of [`absolute::LOCK_TIME_THRESHOLD`], /// while [`BlockMtp`] may take the full range of `u32`. - fn try_from(h: BlockMtp) -> Result { - Self::from_u32(h.to_u32()) - } + fn try_from(h: BlockMtp) -> Result { Self::from_u32(h.to_u32()) } } impl_u32_wrapper! { diff --git a/units/src/locktime/absolute/error.rs b/units/src/locktime/absolute/error.rs index 73429b2fb0..c16480da77 100644 --- a/units/src/locktime/absolute/error.rs +++ b/units/src/locktime/absolute/error.rs @@ -275,11 +275,11 @@ enum LockTimeUnit { impl fmt::Display for LockTimeUnit { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - - match *self { - Self::Blocks => write!(f, "expected lock-by-height (must be < {})", LOCK_TIME_THRESHOLD), - Self::Seconds => write!(f, "expected lock-by-time (must be >= {})", LOCK_TIME_THRESHOLD), + Self::Blocks => + write!(f, "expected lock-by-height (must be < {})", LOCK_TIME_THRESHOLD), + Self::Seconds => + write!(f, "expected lock-by-time (must be >= {})", LOCK_TIME_THRESHOLD), } } } diff --git a/units/src/locktime/absolute/mod.rs b/units/src/locktime/absolute/mod.rs index a4ba995535..dcdb13291e 100644 --- a/units/src/locktime/absolute/mod.rs +++ b/units/src/locktime/absolute/mod.rs @@ -248,8 +248,7 @@ impl LockTime { pub const fn is_same_unit(self, other: Self) -> bool { matches!( (self, other), - (Self::Blocks(_), Self::Blocks(_)) - | (Self::Seconds(_), Self::Seconds(_)) + (Self::Blocks(_), Self::Blocks(_)) | (Self::Seconds(_), Self::Seconds(_)) ) } @@ -308,11 +307,10 @@ impl LockTime { /// Returns an error if this lock is not lock-by-height. #[inline] pub fn is_satisfied_by_height(self, height: Height) -> Result { - - match self { Self::Blocks(blocks) => Ok(blocks.is_satisfied_by(height)), - Self::Seconds(time) => Err(IncompatibleHeightError { lock: time, incompatible: height }), + Self::Seconds(time) => + Err(IncompatibleHeightError { lock: time, incompatible: height }), } } @@ -323,8 +321,6 @@ impl LockTime { /// Returns an error if this lock is not lock-by-time. #[inline] pub fn is_satisfied_by_time(self, mtp: MedianTimePast) -> Result { - - match self { Self::Seconds(time) => Ok(time.is_satisfied_by(mtp)), Self::Blocks(blocks) => Err(IncompatibleTimeError { lock: blocks, incompatible: mtp }), @@ -358,8 +354,6 @@ impl LockTime { /// ``` #[inline] pub fn is_implied_by(self, other: Self) -> bool { - - match (self, other) { (Self::Blocks(this), Self::Blocks(other)) => this <= other, (Self::Seconds(this), Self::Seconds(other)) => this <= other, @@ -473,8 +467,6 @@ impl From for LockTime { impl fmt::Debug for LockTime { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - - match *self { Self::Blocks(ref h) => write!(f, "{} blocks", h), Self::Seconds(ref t) => write!(f, "{} seconds", t), @@ -484,8 +476,6 @@ impl fmt::Debug for LockTime { impl fmt::Display for LockTime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - - if f.alternate() { match *self { Self::Blocks(ref h) => write!(f, "block-height {}", h), diff --git a/units/src/locktime/relative/error.rs b/units/src/locktime/relative/error.rs index 435189d8e6..2113fb9cad 100644 --- a/units/src/locktime/relative/error.rs +++ b/units/src/locktime/relative/error.rs @@ -42,8 +42,6 @@ pub enum IsSatisfiedByError { impl fmt::Display for IsSatisfiedByError { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - - match *self { Self::Blocks(ref e) => write_err!(f, "blocks"; e), Self::Time(ref e) => write_err!(f, "time"; e), @@ -54,8 +52,6 @@ impl fmt::Display for IsSatisfiedByError { #[cfg(feature = "std")] impl std::error::Error for IsSatisfiedByError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - - match *self { Self::Blocks(ref e) => Some(e), Self::Time(ref e) => Some(e), @@ -76,8 +72,6 @@ pub enum IsSatisfiedByHeightError { impl fmt::Display for IsSatisfiedByHeightError { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - - match *self { Self::Satisfaction(ref e) => write_err!(f, "satisfaction"; e), Self::Incompatible(time) => @@ -89,8 +83,6 @@ impl fmt::Display for IsSatisfiedByHeightError { #[cfg(feature = "std")] impl std::error::Error for IsSatisfiedByHeightError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - - match *self { Self::Satisfaction(ref e) => Some(e), Self::Incompatible(_) => None, @@ -111,8 +103,6 @@ pub enum IsSatisfiedByTimeError { impl fmt::Display for IsSatisfiedByTimeError { #[inline] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - - match *self { Self::Satisfaction(ref e) => write_err!(f, "satisfaction"; e), Self::Incompatible(blocks) => @@ -124,8 +114,6 @@ impl fmt::Display for IsSatisfiedByTimeError { #[cfg(feature = "std")] impl std::error::Error for IsSatisfiedByTimeError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { - - match *self { Self::Satisfaction(ref e) => Some(e), Self::Incompatible(_) => None, diff --git a/units/src/locktime/relative/mod.rs b/units/src/locktime/relative/mod.rs index 0d32181c50..e7401e16b1 100644 --- a/units/src/locktime/relative/mod.rs +++ b/units/src/locktime/relative/mod.rs @@ -102,8 +102,7 @@ impl LockTime { pub fn to_consensus_u32(self) -> u32 { match self { Self::Blocks(ref h) => u32::from(h.to_height()), - Self::Time(ref t) => - Sequence::LOCK_TYPE_MASK | u32::from(t.to_512_second_intervals()), + Self::Time(ref t) => Sequence::LOCK_TYPE_MASK | u32::from(t.to_512_second_intervals()), } } @@ -181,10 +180,7 @@ impl LockTime { /// Returns true if both lock times use the same unit i.e., both height based or both time based. #[inline] pub const fn is_same_unit(self, other: Self) -> bool { - matches!( - (self, other), - (Self::Blocks(_), Self::Blocks(_)) | (Self::Time(_), Self::Time(_)) - ) + matches!((self, other), (Self::Blocks(_), Self::Blocks(_)) | (Self::Time(_), Self::Time(_))) } /// Returns true if this lock time value is in units of block height. @@ -234,8 +230,6 @@ impl LockTime { chain_tip: BlockHeight, utxo_mined_at: BlockHeight, ) -> Result { - - match self { Self::Blocks(blocks) => blocks .is_satisfied_by(chain_tip, utxo_mined_at) @@ -258,8 +252,6 @@ impl LockTime { chain_tip: BlockMtp, utxo_mined_at: BlockMtp, ) -> Result { - - match self { Self::Time(time) => time .is_satisfied_by(chain_tip, utxo_mined_at) @@ -299,8 +291,6 @@ impl LockTime { /// ``` #[inline] pub fn is_implied_by(self, other: Self) -> bool { - - match (self, other) { (Self::Blocks(this), Self::Blocks(other)) => this <= other, (Self::Time(this), Self::Time(other)) => this <= other, @@ -350,8 +340,6 @@ impl From for LockTime { impl fmt::Display for LockTime { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - - if f.alternate() { match *self { Self::Blocks(ref h) => write!(f, "block-height {}", h), @@ -369,9 +357,7 @@ impl fmt::Display for LockTime { impl convert::TryFrom for LockTime { type Error = DisabledLockTimeError; #[inline] - fn try_from(seq: Sequence) -> Result { - Self::from_sequence(seq) - } + fn try_from(seq: Sequence) -> Result { Self::from_sequence(seq) } } impl From for Sequence { diff --git a/units/src/sequence.rs b/units/src/sequence.rs index 3c903ed31a..412e33911a 100644 --- a/units/src/sequence.rs +++ b/units/src/sequence.rs @@ -109,9 +109,7 @@ impl Sequence { /// Returns `true` if the sequence has a relative lock-time. #[inline] - pub fn is_relative_lock_time(self) -> bool { - self.0 & Self::LOCK_TIME_DISABLE_FLAG_MASK == 0 - } + pub fn is_relative_lock_time(self) -> bool { self.0 & Self::LOCK_TIME_DISABLE_FLAG_MASK == 0 } /// Returns `true` if the sequence number encodes a block based relative lock-time. #[inline]