From b8910e201ea4374bb0508aa50c6779d080ef6484 Mon Sep 17 00:00:00 2001 From: Fmt Bot Date: Sun, 30 Mar 2025 01:27:51 +0000 Subject: [PATCH] 2025-03-30 automated rustfmt nightly --- base58/src/lib.rs | 3 +- bitcoin/src/address/mod.rs | 27 +++---- bitcoin/src/bip152.rs | 3 +- bitcoin/src/bip158.rs | 3 +- bitcoin/src/bip32.rs | 34 +++----- bitcoin/src/blockdata/script/push_bytes.rs | 1 - bitcoin/src/blockdata/witness.rs | 11 ++- bitcoin/src/crypto/key.rs | 31 ++------ bitcoin/src/crypto/taproot.rs | 2 +- bitcoin/src/hash_types.rs | 7 +- bitcoin/src/p2p/message.rs | 30 +++++-- bitcoin/src/psbt/serialize.rs | 4 +- bitcoin/src/taproot/merkle_branch/borrowed.rs | 44 +++++------ bitcoin/src/taproot/merkle_branch/buf.rs | 9 ++- bitcoin/src/taproot/merkle_branch/mod.rs | 32 ++++---- bitcoin/src/taproot/mod.rs | 36 +++++---- hashes/src/hmac/mod.rs | 4 +- hashes/src/sha256t/mod.rs | 4 +- internals/src/array.rs | 16 ++-- internals/src/macros.rs | 6 +- internals/src/slice.rs | 28 +++++-- primitives/src/locktime/relative.rs | 4 +- primitives/src/script/mod.rs | 8 +- primitives/src/witness.rs | 78 ++++++------------- units/src/amount/signed.rs | 5 +- 25 files changed, 199 insertions(+), 231 deletions(-) diff --git a/base58/src/lib.rs b/base58/src/lib.rs index 13db9fd1f..5feb1f8c4 100644 --- a/base58/src/lib.rs +++ b/base58/src/lib.rs @@ -113,7 +113,8 @@ pub fn decode(data: &str) -> Result, InvalidCharacterError> { /// Decodes a base58check-encoded string into a byte vector verifying the checksum. pub fn decode_check(data: &str) -> Result, Error> { let mut ret: Vec = decode(data)?; - let (remaining, &data_check) = ret.split_last_chunk::<4>().ok_or(TooShortError { length: ret.len() })?; + let (remaining, &data_check) = + ret.split_last_chunk::<4>().ok_or(TooShortError { length: ret.len() })?; let hash_check = *sha256d::Hash::hash(remaining).as_byte_array().sub_array::<0, 4>(); diff --git a/bitcoin/src/address/mod.rs b/bitcoin/src/address/mod.rs index df8e04067..94418f68c 100644 --- a/bitcoin/src/address/mod.rs +++ b/bitcoin/src/address/mod.rs @@ -409,7 +409,9 @@ struct DisplayUnchecked<'a, N: NetworkValidation>(&'a Address); #[cfg(feature = "serde")] impl fmt::Display for DisplayUnchecked<'_, N> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0.inner(), fmt) } + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self.0.inner(), fmt) + } } #[cfg(feature = "serde")] @@ -459,17 +461,11 @@ impl serde::Serialize for Address { /// Methods on [`Address`] that can be called on both `Address` and /// `Address`. impl Address { - fn from_inner(inner: AddressInner) -> Self { - Address(PhantomData, inner) - } + fn from_inner(inner: AddressInner) -> Self { Address(PhantomData, inner) } - fn into_inner(self) -> AddressInner { - self.1 - } + fn into_inner(self) -> AddressInner { self.1 } - fn inner(&self) -> &AddressInner { - &self.1 - } + fn inner(&self) -> &AddressInner { &self.1 } /// Returns a reference to the address as if it was unchecked. pub fn as_unchecked(&self) -> &Address { @@ -477,7 +473,9 @@ impl Address { } /// Marks the network of this address as unchecked. - pub fn into_unchecked(self) -> Address { Address::from_inner(self.into_inner()) } + pub fn into_unchecked(self) -> Address { + Address::from_inner(self.into_inner()) + } /// Returns the [`NetworkKind`] of this address. pub fn network_kind(&self) -> NetworkKind { @@ -807,9 +805,7 @@ impl Address { /// Returns a reference to the checked address. /// /// This function is dangerous in case the address is not a valid checked address. - pub fn assume_checked_ref(&self) -> &Address { - Address::from_inner_ref(self.inner()) - } + pub fn assume_checked_ref(&self) -> &Address { Address::from_inner_ref(self.inner()) } /// Parsed addresses do not always have *one* network. The problem is that legacy testnet, /// regtest and signet addresses use the same prefix instead of multiple different ones. When @@ -920,7 +916,8 @@ impl Address { return Err(LegacyAddressTooLongError { length: s.len() }.into()); } let data = base58::decode_check(s)?; - let data: &[u8; 21] = (&*data).try_into().map_err(|_| InvalidBase58PayloadLengthError { length: s.len() })?; + let data: &[u8; 21] = + (&*data).try_into().map_err(|_| InvalidBase58PayloadLengthError { length: s.len() })?; let (prefix, &data) = data.split_first(); diff --git a/bitcoin/src/bip152.rs b/bitcoin/src/bip152.rs index bb25066d1..b31f900af 100644 --- a/bitcoin/src/bip152.rs +++ b/bitcoin/src/bip152.rs @@ -10,7 +10,8 @@ use core::{convert, fmt, mem}; use std::error; use hashes::{sha256, siphash24}; -use internals::{ToU64 as _, array::ArrayExt as _}; +use internals::array::ArrayExt as _; +use internals::ToU64 as _; use io::{BufRead, Write}; use crate::consensus::encode::{self, Decodable, Encodable, ReadExt, WriteExt}; diff --git a/bitcoin/src/bip158.rs b/bitcoin/src/bip158.rs index abdde2a9c..67b55ef9e 100644 --- a/bitcoin/src/bip158.rs +++ b/bitcoin/src/bip158.rs @@ -42,7 +42,8 @@ use core::convert::Infallible; use core::fmt; use hashes::{sha256d, siphash24, HashEngine as _}; -use internals::{write_err, ToU64 as _, array::ArrayExt as _}; +use internals::array::ArrayExt as _; +use internals::{write_err, ToU64 as _}; use io::{BufRead, Write}; use crate::block::{Block, BlockHash, Checked}; diff --git a/bitcoin/src/bip32.rs b/bitcoin/src/bip32.rs index 73d74ffc8..b335b09b3 100644 --- a/bitcoin/src/bip32.rs +++ b/bitcoin/src/bip32.rs @@ -682,10 +682,9 @@ impl Xpriv { engine.input(&u32::from(i).to_be_bytes()); let hmac: Hmac = engine.finalize(); - let sk = secp256k1::SecretKey::from_byte_array( - hmac.as_byte_array().split_array::<32, 32>().0, - ) - .expect("statistically impossible to hit"); + let sk = + secp256k1::SecretKey::from_byte_array(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"); @@ -701,14 +700,8 @@ impl Xpriv { /// Decoding extended private key from binary data according to BIP 32 pub fn decode(data: &[u8]) -> Result { - let Common { - network, - depth, - parent_fingerprint, - child_number, - chain_code, - key, - } = Common::decode(data)?; + let Common { network, depth, parent_fingerprint, child_number, chain_code, key } = + Common::decode(data)?; let network = match network { VERSION_BYTES_MAINNET_PRIVATE => NetworkKind::Main, @@ -834,7 +827,7 @@ impl Xpub { let hmac = engine.finalize(); let private_key = secp256k1::SecretKey::from_byte_array( - hmac.as_byte_array().split_array::<32, 32>().0 + hmac.as_byte_array().split_array::<32, 32>().0, )?; let chain_code = ChainCode::from_hmac(hmac); Ok((private_key, chain_code)) @@ -863,14 +856,8 @@ impl Xpub { /// Decoding extended public key from binary data according to BIP 32 pub fn decode(data: &[u8]) -> Result { - let Common { - network, - depth, - parent_fingerprint, - child_number, - chain_code, - key, - } = Common::decode(data)?; + let Common { network, depth, parent_fingerprint, child_number, chain_code, key } = + Common::decode(data)?; let network = match network { VERSION_BYTES_MAINNET_PUBLIC => NetworkKind::Main, @@ -994,13 +981,14 @@ struct Common { parent_fingerprint: Fingerprint, child_number: ChildNumber, chain_code: ChainCode, - // public key (compressed) or 0 byte followed by a private key + // public key (compressed) or 0 byte followed by a private key key: [u8; 33], } impl Common { fn decode(data: &[u8]) -> Result { - let data: &[u8; 78] = data.try_into().map_err(|_| Error::WrongExtendedKeyLength(data.len()))?; + let data: &[u8; 78] = + data.try_into().map_err(|_| Error::WrongExtendedKeyLength(data.len()))?; let (&network, data) = data.split_array::<4, 74>(); let (&depth, data) = data.split_first::<73>(); diff --git a/bitcoin/src/blockdata/script/push_bytes.rs b/bitcoin/src/blockdata/script/push_bytes.rs index f469290f0..7fb46742a 100644 --- a/bitcoin/src/blockdata/script/push_bytes.rs +++ b/bitcoin/src/blockdata/script/push_bytes.rs @@ -58,7 +58,6 @@ mod primitive { } impl PushBytes { - /// Constructs an empty `&PushBytes`. pub fn empty() -> &'static Self { Self::from_slice_unchecked(&[]) } diff --git a/bitcoin/src/blockdata/witness.rs b/bitcoin/src/blockdata/witness.rs index 06d2a72e0..d4793fbbe 100644 --- a/bitcoin/src/blockdata/witness.rs +++ b/bitcoin/src/blockdata/witness.rs @@ -14,7 +14,7 @@ use crate::crypto::key::SerializedXOnlyPublicKey; use crate::prelude::Vec; #[cfg(doc)] use crate::script::ScriptExt as _; -use crate::taproot::{self, ControlBlock, LeafScript, TAPROOT_ANNEX_PREFIX, TaprootMerkleBranch}; +use crate::taproot::{self, ControlBlock, LeafScript, TaprootMerkleBranch, TAPROOT_ANNEX_PREFIX}; use crate::Script; type BorrowedControlBlock<'a> = ControlBlock<&'a TaprootMerkleBranch, &'a SerializedXOnlyPublicKey>; @@ -387,7 +387,8 @@ mod test { #[test] fn get_tapscript() { let tapscript = hex!("deadbeef"); - let control_block = hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + let control_block = + hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // annex starting with 0x50 causes the branching logic. let annex = hex!("50"); @@ -435,7 +436,8 @@ mod test { #[test] fn get_control_block() { let tapscript = hex!("deadbeef"); - let control_block = hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + let control_block = + hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); let expected_control_block = BorrowedControlBlock::decode_borrowed(&control_block).unwrap(); // annex starting with 0x50 causes the branching logic. let annex = hex!("50"); @@ -454,7 +456,8 @@ mod test { #[test] fn get_annex() { let tapscript = hex!("deadbeef"); - let control_block = hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + let control_block = + hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // annex starting with 0x50 causes the branching logic. let annex = hex!("50"); diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs index a2d8a0a7c..45a232941 100644 --- a/bitcoin/src/crypto/key.rs +++ b/bitcoin/src/crypto/key.rs @@ -26,10 +26,9 @@ use crate::taproot::{TapNodeHash, TapTweakHash}; #[rustfmt::skip] // Keep public re-exports separate. pub use secp256k1::{constants, Keypair, Parity, Secp256k1, Verification, XOnlyPublicKey}; -pub use serialized_x_only::SerializedXOnlyPublicKey; - #[cfg(feature = "rand-std")] pub use secp256k1::rand; +pub use serialized_x_only::SerializedXOnlyPublicKey; /// A Bitcoin ECDSA public key. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] @@ -528,17 +527,13 @@ impl PrivateKey { } }; - Ok(PrivateKey { - compressed, - network, - inner: secp256k1::SecretKey::from_byte_array(key)?, - }) + Ok(PrivateKey { compressed, network, inner: secp256k1::SecretKey::from_byte_array(key)? }) } /// Returns a new private key with the negated secret value. /// /// The resulting key corresponds to the same x-only public key (identical x-coordinate) - /// but with the opposite y-coordinate parity. This is useful for ensuring compatibility + /// but with the opposite y-coordinate parity. This is useful for ensuring compatibility /// with specific public key formats and BIP-340 requirements. #[inline] pub fn negate(&self) -> Self { @@ -1239,19 +1234,13 @@ mod serialized_x_only { impl SerializedXOnlyPublicKey { /// Marks the supplied bytes as a serialized x-only public key. - pub const fn from_byte_array(bytes: [u8; 32]) -> Self { - Self(bytes) - } + pub const fn from_byte_array(bytes: [u8; 32]) -> Self { Self(bytes) } /// Returns the raw bytes. - pub const fn to_byte_array(self) -> [u8; 32] { - self.0 - } + pub const fn to_byte_array(self) -> [u8; 32] { self.0 } /// Returns a reference to the raw bytes. - pub const fn as_byte_array(&self) -> &[u8; 32] { - &self.0 - } + pub const fn as_byte_array(&self) -> &[u8; 32] { &self.0 } } } @@ -1263,15 +1252,11 @@ impl SerializedXOnlyPublicKey { } impl AsRef<[u8; 32]> for SerializedXOnlyPublicKey { - fn as_ref(&self) -> &[u8; 32] { - self.as_byte_array() - } + fn as_ref(&self) -> &[u8; 32] { self.as_byte_array() } } impl From<&SerializedXOnlyPublicKey> for SerializedXOnlyPublicKey { - fn from(borrowed: &SerializedXOnlyPublicKey) -> Self { - *borrowed - } + fn from(borrowed: &SerializedXOnlyPublicKey) -> Self { *borrowed } } impl fmt::Debug for SerializedXOnlyPublicKey { diff --git a/bitcoin/src/crypto/taproot.rs b/bitcoin/src/crypto/taproot.rs index fe66028b8..e8dfa2ee9 100644 --- a/bitcoin/src/crypto/taproot.rs +++ b/bitcoin/src/crypto/taproot.rs @@ -9,8 +9,8 @@ use core::fmt; #[cfg(feature = "arbitrary")] use arbitrary::{Arbitrary, Unstructured}; -use internals::write_err; use internals::array::ArrayExt; +use internals::write_err; use io::Write; use crate::prelude::Vec; diff --git a/bitcoin/src/hash_types.rs b/bitcoin/src/hash_types.rs index 4f5134ad7..296e1f135 100644 --- a/bitcoin/src/hash_types.rs +++ b/bitcoin/src/hash_types.rs @@ -4,13 +4,10 @@ //! //! This module is deprecated. You can find hash types in their respective, hopefully obvious, modules. -#[deprecated(since = "TBD", note = "use `crate::T` instead")] -pub use crate::{ - BlockHash, TxMerkleNode, Txid, WitnessCommitment, WitnessMerkleNode, - Wtxid, -}; #[deprecated(since = "TBD", note = "use `crate::T` instead")] pub use crate::bip158::{FilterHash, FilterHeader}; +#[deprecated(since = "TBD", note = "use `crate::T` instead")] +pub use crate::{BlockHash, TxMerkleNode, Txid, WitnessCommitment, WitnessMerkleNode, Wtxid}; #[cfg(test)] mod tests { diff --git a/bitcoin/src/p2p/message.rs b/bitcoin/src/p2p/message.rs index e9522a7c5..100142bc1 100644 --- a/bitcoin/src/p2p/message.rs +++ b/bitcoin/src/p2p/message.rs @@ -702,7 +702,7 @@ mod test { use super::*; use crate::bip152::BlockTransactionsRequest; - use crate::bip158::{FilterHeader, FilterHash}; + use crate::bip158::{FilterHash, FilterHeader}; use crate::block::{Block, BlockHash}; use crate::consensus::encode::{deserialize, deserialize_partial, serialize}; use crate::p2p::address::AddrV2; @@ -738,19 +738,25 @@ mod test { 45, Address::new(&([123, 255, 000, 100], 833).into(), ServiceFlags::NETWORK), )]), - NetworkMessage::Inv(vec![Inventory::Block(BlockHash::from_byte_array(hash([8u8; 32]).to_byte_array()))]), - NetworkMessage::GetData(vec![Inventory::Transaction(Txid::from_byte_array(hash([45u8; 32]).to_byte_array()))]), + NetworkMessage::Inv(vec![Inventory::Block(BlockHash::from_byte_array( + hash([8u8; 32]).to_byte_array(), + ))]), + NetworkMessage::GetData(vec![Inventory::Transaction(Txid::from_byte_array( + hash([45u8; 32]).to_byte_array(), + ))]), NetworkMessage::NotFound(vec![Inventory::Error([0u8; 32])]), NetworkMessage::GetBlocks(GetBlocksMessage::new( vec![ BlockHash::from_byte_array(hash([1u8; 32]).to_byte_array()), - BlockHash::from_byte_array(hash([4u8; 32]).to_byte_array())], + BlockHash::from_byte_array(hash([4u8; 32]).to_byte_array()), + ], BlockHash::from_byte_array(hash([5u8; 32]).to_byte_array()), )), NetworkMessage::GetHeaders(GetHeadersMessage::new( vec![ BlockHash::from_byte_array(hash([10u8; 32]).to_byte_array()), - BlockHash::from_byte_array(hash([40u8; 32]).to_byte_array())], + BlockHash::from_byte_array(hash([40u8; 32]).to_byte_array()), + ], BlockHash::from_byte_array(hash([50u8; 32]).to_byte_array()), )), NetworkMessage::MemPool, @@ -791,8 +797,13 @@ mod test { NetworkMessage::CFHeaders(CFHeaders { filter_type: 13, stop_hash: BlockHash::from_byte_array(hash([53u8; 32]).to_byte_array()), - previous_filter_header: FilterHeader::from_byte_array(hash([12u8; 32]).to_byte_array()), - filter_hashes: vec![FilterHash::from_byte_array(hash([4u8; 32]).to_byte_array()), FilterHash::from_byte_array(hash([12u8; 32]).to_byte_array())], + previous_filter_header: FilterHeader::from_byte_array( + hash([12u8; 32]).to_byte_array(), + ), + filter_hashes: vec![ + FilterHash::from_byte_array(hash([4u8; 32]).to_byte_array()), + FilterHash::from_byte_array(hash([12u8; 32]).to_byte_array()), + ], }), NetworkMessage::GetCFCheckpt(GetCFCheckpt { filter_type: 17, @@ -801,7 +812,10 @@ mod test { NetworkMessage::CFCheckpt(CFCheckpt { filter_type: 27, stop_hash: BlockHash::from_byte_array(hash([77u8; 32]).to_byte_array()), - filter_headers: vec![FilterHeader::from_byte_array(hash([3u8; 32]).to_byte_array()), FilterHeader::from_byte_array(hash([99u8; 32]).to_byte_array())], + filter_headers: vec![ + FilterHeader::from_byte_array(hash([3u8; 32]).to_byte_array()), + FilterHeader::from_byte_array(hash([99u8; 32]).to_byte_array()), + ], }), NetworkMessage::Alert(vec![45, 66, 3, 2, 6, 8, 9, 12, 3, 130]), NetworkMessage::Reject(Reject { diff --git a/bitcoin/src/psbt/serialize.rs b/bitcoin/src/psbt/serialize.rs index 703bcb79d..e9492953a 100644 --- a/bitcoin/src/psbt/serialize.rs +++ b/bitcoin/src/psbt/serialize.rs @@ -216,8 +216,8 @@ impl Serialize for KeySource { impl Deserialize for KeySource { fn deserialize(bytes: &[u8]) -> Result { - let (fingerprint, mut d) = bytes.split_first_chunk::<4>() - .ok_or(io::Error::from(io::ErrorKind::UnexpectedEof))?; + let (fingerprint, mut d) = + bytes.split_first_chunk::<4>().ok_or(io::Error::from(io::ErrorKind::UnexpectedEof))?; let fprint: Fingerprint = fingerprint.into(); let mut dpath: Vec = Default::default(); diff --git a/bitcoin/src/taproot/merkle_branch/borrowed.rs b/bitcoin/src/taproot/merkle_branch/borrowed.rs index 6ca681e25..85a839db6 100644 --- a/bitcoin/src/taproot/merkle_branch/borrowed.rs +++ b/bitcoin/src/taproot/merkle_branch/borrowed.rs @@ -1,10 +1,13 @@ use core::borrow::{Borrow, BorrowMut}; + use internals::slice::SliceExt; - -use super::{DecodeError, InvalidMerkleBranchSizeError, InvalidMerkleTreeDepthError, TaprootMerkleBranchBuf, TapNodeHash, TAPROOT_CONTROL_MAX_NODE_COUNT, TAPROOT_CONTROL_NODE_SIZE}; - pub use privacy_boundary::TaprootMerkleBranch; +use super::{ + DecodeError, InvalidMerkleBranchSizeError, InvalidMerkleTreeDepthError, TapNodeHash, + TaprootMerkleBranchBuf, TAPROOT_CONTROL_MAX_NODE_COUNT, TAPROOT_CONTROL_NODE_SIZE, +}; + /// Makes sure only the allowed conversions are accessible to external code. mod privacy_boundary { use super::*; @@ -33,9 +36,7 @@ mod privacy_boundary { impl TaprootMerkleBranch { /// Returns an empty branch. - pub const fn new() -> &'static Self { - Self::from_hashes_unchecked(&[]) - } + pub const fn new() -> &'static Self { Self::from_hashes_unchecked(&[]) } /// Returns the number of nodes in this Merkle proof. #[inline] @@ -91,7 +92,9 @@ impl TaprootMerkleBranch { /// Decodes a byte slice that is statically known to be multiple of 32. /// /// This can be used as a building block for other ways of decoding. - fn decode_exact(nodes: &[[u8; TAPROOT_CONTROL_NODE_SIZE]]) -> Result<&Self, InvalidMerkleTreeDepthError> { + fn decode_exact( + nodes: &[[u8; TAPROOT_CONTROL_NODE_SIZE]], + ) -> Result<&Self, InvalidMerkleTreeDepthError> { // SAFETY: // The lifetime of the returned reference is the same as the lifetime of the input // reference, the size of `TapNodeHash` is equal to `TAPROOT_CONTROL_NODE_SIZE` and the @@ -99,7 +102,7 @@ impl TaprootMerkleBranch { Self::from_hashes(unsafe { &*(nodes as *const _ as *const [TapNodeHash]) }) } - fn from_hashes(nodes: &[TapNodeHash]) -> Result<&Self, InvalidMerkleTreeDepthError>{ + fn from_hashes(nodes: &[TapNodeHash]) -> Result<&Self, InvalidMerkleTreeDepthError> { if nodes.len() <= TAPROOT_CONTROL_MAX_NODE_COUNT { Ok(Self::from_hashes_unchecked(nodes)) } else { @@ -109,21 +112,15 @@ impl TaprootMerkleBranch { } impl Default for &'_ TaprootMerkleBranch { - fn default() -> Self { - TaprootMerkleBranch::new() - } + fn default() -> Self { TaprootMerkleBranch::new() } } impl AsRef for TaprootMerkleBranch { - fn as_ref(&self) -> &TaprootMerkleBranch { - self - } + fn as_ref(&self) -> &TaprootMerkleBranch { self } } impl AsMut for TaprootMerkleBranch { - fn as_mut(&mut self) -> &mut TaprootMerkleBranch { - self - } + fn as_mut(&mut self) -> &mut TaprootMerkleBranch { self } } impl AsRef for TaprootMerkleBranchBuf { @@ -248,18 +245,14 @@ impl alloc::borrow::ToOwned for TaprootMerkleBranch { // `Cow`. type Owned = TaprootMerkleBranchBuf; - fn to_owned(&self) -> Self::Owned { - self.into() - } + fn to_owned(&self) -> Self::Owned { self.into() } } impl<'a> IntoIterator for &'a TaprootMerkleBranch { type IntoIter = core::slice::Iter<'a, TapNodeHash>; type Item = &'a TapNodeHash; - fn into_iter(self) -> Self::IntoIter { - self.as_slice().iter() - } + fn into_iter(self) -> Self::IntoIter { self.as_slice().iter() } } impl<'a> IntoIterator for &'a mut TaprootMerkleBranch { @@ -274,7 +267,10 @@ impl<'a> IntoIterator for &'a mut TaprootMerkleBranch { mod tests { #[test] fn alignment() { - assert!(core::mem::align_of_val(super::TaprootMerkleBranch::new()) == core::mem::align_of::()); + assert!( + core::mem::align_of_val(super::TaprootMerkleBranch::new()) + == core::mem::align_of::() + ); } const _: () = { diff --git a/bitcoin/src/taproot/merkle_branch/buf.rs b/bitcoin/src/taproot/merkle_branch/buf.rs index a6e0e7526..11b2850c4 100644 --- a/bitcoin/src/taproot/merkle_branch/buf.rs +++ b/bitcoin/src/taproot/merkle_branch/buf.rs @@ -86,7 +86,10 @@ impl TaprootMerkleBranchBuf { } /// Appends elements to proof. - pub(in super::super) fn push(&mut self, h: TapNodeHash) -> Result<(), InvalidMerkleTreeDepthError> { + pub(in super::super) fn push( + &mut self, + h: TapNodeHash, + ) -> Result<(), InvalidMerkleTreeDepthError> { if self.len() >= TAPROOT_CONTROL_MAX_NODE_COUNT { Err(InvalidMerkleTreeDepthError(self.0.len())) } else { @@ -213,9 +216,7 @@ impl BorrowMut<[TapNodeHash]> for TaprootMerkleBranchBuf { } impl<'a> From<&'a TaprootMerkleBranch> for TaprootMerkleBranchBuf { - fn from(value: &'a TaprootMerkleBranch) -> Self { - Self(value.as_slice().into()) - } + fn from(value: &'a TaprootMerkleBranch) -> Self { Self(value.as_slice().into()) } } /// Iterator over node hashes within Taproot Merkle branch. diff --git a/bitcoin/src/taproot/merkle_branch/mod.rs b/bitcoin/src/taproot/merkle_branch/mod.rs index 0fd32c259..56a142345 100644 --- a/bitcoin/src/taproot/merkle_branch/mod.rs +++ b/bitcoin/src/taproot/merkle_branch/mod.rs @@ -1,12 +1,13 @@ //! Contains `TaprootMerkleBranchBuf` and its associated types. -mod buf; mod borrowed; - -pub use buf::TaprootMerkleBranchBuf; -pub use borrowed::TaprootMerkleBranch; +mod buf; use core::fmt; + +pub use borrowed::TaprootMerkleBranch; +pub use buf::TaprootMerkleBranchBuf; + use super::{ InvalidMerkleBranchSizeError, InvalidMerkleTreeDepthError, TapNodeHash, TaprootError, TAPROOT_CONTROL_MAX_NODE_COUNT, TAPROOT_CONTROL_NODE_SIZE, @@ -28,27 +29,30 @@ pub struct DecodeError { } impl From for DecodeError { - fn from(value: InvalidMerkleBranchSizeError) -> Self { - Self { - num_bytes: value.0, - } - } + fn from(value: InvalidMerkleBranchSizeError) -> Self { Self { num_bytes: value.0 } } } impl From for DecodeError { fn from(value: InvalidMerkleTreeDepthError) -> Self { - Self { - num_bytes: value.0 * TAPROOT_CONTROL_NODE_SIZE, - } + Self { num_bytes: value.0 * TAPROOT_CONTROL_NODE_SIZE } } } impl fmt::Display for DecodeError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if self.num_bytes % TAPROOT_CONTROL_NODE_SIZE == 0 { - write!(f, "the Merkle branch has {} nodes which is more than the limit {}", self.num_bytes / TAPROOT_CONTROL_NODE_SIZE, TAPROOT_CONTROL_MAX_NODE_COUNT) + write!( + f, + "the Merkle branch has {} nodes which is more than the limit {}", + self.num_bytes / TAPROOT_CONTROL_NODE_SIZE, + TAPROOT_CONTROL_MAX_NODE_COUNT + ) } else { - write!(f, "the Merkle branch is {} bytes long which is not an integer multiple of {}", self.num_bytes, TAPROOT_CONTROL_NODE_SIZE) + write!( + f, + "the Merkle branch is {} bytes long which is not an integer multiple of {}", + self.num_bytes, TAPROOT_CONTROL_NODE_SIZE + ) } } } diff --git a/bitcoin/src/taproot/mod.rs b/bitcoin/src/taproot/mod.rs index 15f188a10..0f22a40d8 100644 --- a/bitcoin/src/taproot/mod.rs +++ b/bitcoin/src/taproot/mod.rs @@ -14,15 +14,16 @@ use core::iter::FusedIterator; use hashes::{hash_newtype, sha256t, sha256t_tag, HashEngine}; use internals::array::ArrayExt; -use internals::{impl_to_hex_from_lower_hex, write_err}; #[allow(unused)] // MSRV polyfill use internals::slice::SliceExt; - +use internals::{impl_to_hex_from_lower_hex, write_err}; use io::Write; use secp256k1::{Scalar, Secp256k1}; use crate::consensus::Encodable; -use crate::crypto::key::{SerializedXOnlyPublicKey, TapTweak, TweakedPublicKey, UntweakedPublicKey, XOnlyPublicKey}; +use crate::crypto::key::{ + SerializedXOnlyPublicKey, TapTweak, TweakedPublicKey, UntweakedPublicKey, XOnlyPublicKey, +}; use crate::prelude::{BTreeMap, BTreeSet, BinaryHeap, Vec}; use crate::{Script, ScriptBuf}; @@ -31,9 +32,9 @@ use crate::{Script, ScriptBuf}; #[doc(inline)] pub use crate::crypto::taproot::{SigFromSliceError, Signature}; #[doc(inline)] -pub use merkle_branch::TaprootMerkleBranchBuf; -#[doc(inline)] pub use merkle_branch::TaprootMerkleBranch; +#[doc(inline)] +pub use merkle_branch::TaprootMerkleBranchBuf; type ControlBlockArrayVec = internals::array_vec::ArrayVec; @@ -1141,7 +1142,10 @@ impl<'leaf> ScriptLeaf<'leaf> { /// Control block data structure used in Tapscript satisfaction. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] #[cfg_attr(feature = "serde", derive(Serialize, Deserialize))] -pub struct ControlBlock where Branch: ?Sized { +pub struct ControlBlock +where + Branch: ?Sized, +{ /// The tapleaf version. pub leaf_version: LeafVersion, /// The parity of the output key (NOT THE INTERNAL KEY WHICH IS ALWAYS XONLY). @@ -1168,12 +1172,8 @@ impl ControlBlock { pub fn decode(sl: &[u8]) -> Result { use alloc::borrow::ToOwned; - let ControlBlock { - leaf_version, - output_key_parity, - internal_key, - merkle_branch, - } = ControlBlock::<&TaprootMerkleBranch, &SerializedXOnlyPublicKey>::decode_borrowed(sl)?; + let ControlBlock { leaf_version, output_key_parity, internal_key, merkle_branch } = + ControlBlock::<&TaprootMerkleBranch, &SerializedXOnlyPublicKey>::decode_borrowed(sl)?; let internal_key = internal_key.to_validated().map_err(TaprootError::InvalidInternalKey)?; let merkle_branch = merkle_branch.to_owned(); @@ -1183,8 +1183,13 @@ impl ControlBlock { } impl ControlBlock { - pub(crate) fn decode_borrowed<'a>(sl: &'a [u8]) -> Result where B: From<&'a TaprootMerkleBranch>, K: From<&'a SerializedXOnlyPublicKey> { - let (base, merkle_branch) = sl.split_first_chunk::() + pub(crate) fn decode_borrowed<'a>(sl: &'a [u8]) -> Result + where + B: From<&'a TaprootMerkleBranch>, + K: From<&'a SerializedXOnlyPublicKey>, + { + let (base, merkle_branch) = sl + .split_first_chunk::() .ok_or(InvalidControlBlockSizeError(sl.len()))?; let (&first, internal_key) = base.split_first(); @@ -1223,7 +1228,8 @@ impl + ?Sized> ControlBlock { self.encode_inner(|bytes| -> Result<(), core::convert::Infallible> { result.extend_from_slice(bytes); Ok(()) - }).unwrap_or_else(|never| match never {}); + }) + .unwrap_or_else(|never| match never {}); result } diff --git a/hashes/src/hmac/mod.rs b/hashes/src/hmac/mod.rs index d69c3ccc2..aebe2e60e 100644 --- a/hashes/src/hmac/mod.rs +++ b/hashes/src/hmac/mod.rs @@ -26,9 +26,7 @@ impl str::FromStr for Hmac { } impl PartialEq for Hmac { - fn eq(&self, other: &Self) -> bool { - crate::cmp::fixed_time_eq(self.as_ref(), other.as_ref()) - } + fn eq(&self, other: &Self) -> bool { crate::cmp::fixed_time_eq(self.as_ref(), other.as_ref()) } } impl Eq for Hmac {} diff --git a/hashes/src/sha256t/mod.rs b/hashes/src/sha256t/mod.rs index 526892db2..d8f0a1ca0 100644 --- a/hashes/src/sha256t/mod.rs +++ b/hashes/src/sha256t/mod.rs @@ -134,7 +134,9 @@ impl PartialOrd for Hash { } } impl Ord for Hash { - fn cmp(&self, other: &Hash) -> cmp::Ordering { cmp::Ord::cmp(&self.as_byte_array(), &other.as_byte_array()) } + fn cmp(&self, other: &Hash) -> cmp::Ordering { + cmp::Ord::cmp(&self.as_byte_array(), &other.as_byte_array()) + } } impl core::hash::Hash for Hash { fn hash(&self, h: &mut H) { self.as_byte_array().hash(h) } diff --git a/internals/src/array.rs b/internals/src/array.rs index becbf6b64..d5c639623 100644 --- a/internals/src/array.rs +++ b/internals/src/array.rs @@ -17,9 +17,7 @@ pub trait ArrayExt { /// Returns an item at given statically-known index. /// /// This is just like normal indexing except the check happens at compile time. - fn get_static(&self) -> &Self::Item { - &self.sub_array::()[0] - } + fn get_static(&self) -> &Self::Item { &self.sub_array::()[0] } /// Returns the first item in an array. /// @@ -30,9 +28,7 @@ pub trait ArrayExt { /// that this will not return `None` so trying to keep the `std` method around is pointless. /// Importing the trait will also cause compile failures - that's also intentional to expose /// the places where useless checks are made. - fn first(&self) -> &Self::Item { - self.get_static::<0>() - } + fn first(&self) -> &Self::Item { self.get_static::<0>() } /// Splits the array into two, non-overlaping smaller arrays covering the entire range. /// @@ -40,7 +36,9 @@ pub trait ArrayExt { /// checks that the arrays don't overlap and that they cover the full range. This is very useful /// for demonstrating correctness, especially when chained. Using this technique even revealed /// a bug in the past. ([#4195](https://github.com/rust-bitcoin/rust-bitcoin/issues/4195)) - fn split_array(&self) -> (&[Self::Item; LEFT], &[Self::Item; RIGHT]); + fn split_array( + &self, + ) -> (&[Self::Item; LEFT], &[Self::Item; RIGHT]); /// Splits the array into the first element and the remaining, one element shorter, array. /// @@ -84,7 +82,9 @@ impl ArrayExt for [T; N] { self[OFFSET..(OFFSET + LEN)].try_into().expect("this is also compiler-checked above") } - fn split_array(&self) -> (&[Self::Item; LEFT], &[Self::Item; RIGHT]) { + fn split_array( + &self, + ) -> (&[Self::Item; LEFT], &[Self::Item; RIGHT]) { #[allow(clippy::let_unit_value)] let _ = Hack2::::IS_FULL_RANGE; diff --git a/internals/src/macros.rs b/internals/src/macros.rs index b23725a83..ce0d412bc 100644 --- a/internals/src/macros.rs +++ b/internals/src/macros.rs @@ -209,10 +209,12 @@ macro_rules! _check_tts_eq { ($left:tt, $right:tt, $message:literal) => { macro_rules! token_eq { ($right) => {}; - ($any:tt) => { compile_error!($message) }; + ($any:tt) => { + compile_error!($message) + }; } token_eq!($left); - } + }; } #[doc(hidden)] diff --git a/internals/src/slice.rs b/internals/src/slice.rs index b703238e4..e6ce027d2 100644 --- a/internals/src/slice.rs +++ b/internals/src/slice.rs @@ -37,14 +37,18 @@ pub trait SliceExt { /// Returns `None` if the slice is shorter than `ARRAY_LEN` #[allow(clippy::type_complexity)] // it's not really complex and redefining would make it // harder to understand - fn split_first_chunk(&self) -> Option<(&[Self::Item; ARRAY_LEN], &[Self::Item])>; + fn split_first_chunk( + &self, + ) -> Option<(&[Self::Item; ARRAY_LEN], &[Self::Item])>; /// Splits the slice into a remainder and an array if it's long enough. /// /// Returns `None` if the slice is shorter than `ARRAY_LEN` #[allow(clippy::type_complexity)] // it's not really complex and redefining would make it // harder to understand - fn split_last_chunk(&self) -> Option<(&[Self::Item], &[Self::Item; ARRAY_LEN])>; + fn split_last_chunk( + &self, + ) -> Option<(&[Self::Item], &[Self::Item; ARRAY_LEN])>; } impl SliceExt for [T] { @@ -90,11 +94,16 @@ impl SliceExt for [T] { } fn get_array(&self, offset: usize) -> Option<&[Self::Item; ARRAY_LEN]> { - self.get(offset..(offset + ARRAY_LEN)) - .map(|slice| slice.try_into().expect("the arguments to `get` evaluate to the same length the return type uses")) + self.get(offset..(offset + ARRAY_LEN)).map(|slice| { + slice + .try_into() + .expect("the arguments to `get` evaluate to the same length the return type uses") + }) } - fn split_first_chunk(&self) -> Option<(&[Self::Item; ARRAY_LEN], &[Self::Item])> { + fn split_first_chunk( + &self, + ) -> Option<(&[Self::Item; ARRAY_LEN], &[Self::Item])> { if self.len() < ARRAY_LEN { return None; } @@ -102,12 +111,17 @@ impl SliceExt for [T] { Some((first.try_into().expect("we're passing `ARRAY_LEN` to `split_at` above"), remainder)) } - fn split_last_chunk(&self) -> Option<(&[Self::Item], &[Self::Item; ARRAY_LEN])> { + fn split_last_chunk( + &self, + ) -> Option<(&[Self::Item], &[Self::Item; ARRAY_LEN])> { if self.len() < ARRAY_LEN { return None; } let (remainder, last) = self.split_at(self.len() - ARRAY_LEN); - Some((remainder, last.try_into().expect("we're passing `self.len() - ARRAY_LEN` to `split_at` above"))) + Some(( + remainder, + last.try_into().expect("we're passing `self.len() - ARRAY_LEN` to `split_at` above"), + )) } } diff --git a/primitives/src/locktime/relative.rs b/primitives/src/locktime/relative.rs index 000adb078..7a08d2296 100644 --- a/primitives/src/locktime/relative.rs +++ b/primitives/src/locktime/relative.rs @@ -486,7 +486,7 @@ mod tests { #[test] fn from_seconds_ceil_and_floor() { - let time = 70*512+1; + let time = 70 * 512 + 1; let lock_by_time = LockTime::from_seconds_ceil(time).unwrap(); assert_eq!(lock_by_time, LockTime::from_512_second_intervals(71)); @@ -494,7 +494,7 @@ mod tests { assert_eq!(lock_by_time, LockTime::from_512_second_intervals(70)); let mut max_time = 0xffff * 512; - assert_eq!(LockTime::from_seconds_ceil(max_time),LockTime::from_seconds_floor(max_time)); + assert_eq!(LockTime::from_seconds_ceil(max_time), LockTime::from_seconds_floor(max_time)); max_time += 512; assert!(LockTime::from_seconds_ceil(max_time).is_err()); assert!(LockTime::from_seconds_floor(max_time).is_err()); diff --git a/primitives/src/script/mod.rs b/primitives/src/script/mod.rs index 2ad34017c..af9c4b429 100644 --- a/primitives/src/script/mod.rs +++ b/primitives/src/script/mod.rs @@ -276,16 +276,12 @@ impl<'a> From<&'a Script> for Cow<'a, Script> { #[cfg(target_has_atomic = "ptr")] impl<'a> From<&'a Script> for Arc