What changed, and why it matters
This commit is a routine automated code-formatting run using the nightly version of rustfmt. It only changes whitespace, line breaks, import ordering, and other stylistic details across 24 files. No program logic, security behavior, or public API was changed.
No action required; this is a non-functional formatting-only commit. Reviewers may verify with a formatting tool that the changes are purely stylistic.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The diff consists entirely of rustfmt-induced style changes: rewrapping long function signatures and bodies, reordering use statements, adding/removing blank lines, reformatting macro invocations and struct initializers, and adjusting indentation. There are no semantic code changes, no new dependencies, no unsafe blocks, no cryptographic changes, and no changes to parsing or validation logic. The commit title and message explicitly describe it as an ‘automated rustfmt nightly’ run.
Changed components
Inspect captured patch +226 / −216
diff --git a/bitcoin/src/bip32.rs b/bitcoin/src/bip32.rs
index 37463dfb..c39c6dbe 100644
--- a/bitcoin/src/bip32.rs
+++ b/bitcoin/src/bip32.rs
@@ -872,7 +872,9 @@ impl Xpub {
pub fn to_pub(self) -> CompressedPublicKey { self.to_public_key() }
/// Constructs a new ECDSA compressed public key matching internal public key representation.
- pub fn to_public_key(self) -> CompressedPublicKey { CompressedPublicKey::from_secp(self.public_key) }
+ pub fn to_public_key(self) -> CompressedPublicKey {
+ CompressedPublicKey::from_secp(self.public_key)
+ }
/// Constructs a new BIP-0340 x-only public key for BIP-0340 signatures and Taproot use matching
/// the internal public key representation.
diff --git a/bitcoin/src/consensus/mod.rs b/bitcoin/src/consensus/mod.rs
index a7e16c03..10a28c85 100644
--- a/bitcoin/src/consensus/mod.rs
+++ b/bitcoin/src/consensus/mod.rs
@@ -7,10 +7,10 @@
pub mod encode;
mod error;
-#[cfg(kani)]
-mod verification;
#[cfg(feature = "serde")]
pub mod serde;
+#[cfg(kani)]
+mod verification;
use core::fmt;
diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs
index d0b3ff33..027b7c74 100644
--- a/bitcoin/src/crypto/key.rs
+++ b/bitcoin/src/crypto/key.rs
@@ -26,12 +26,12 @@ use crate::taproot::{TapNodeHash, TapTweakHash};
#[rustfmt::skip] // Keep public re-exports separate.
pub use secp256k1::{constants, Parity, Verification};
-#[cfg(all(feature = "rand", feature = "std"))]
-pub use secp256k1::rand;
pub use encapsulate::{
- CompressedPublicKey, Keypair, SerializedXOnlyPublicKey, TweakedKeypair,
- TweakedPublicKey, XOnlyPublicKey,
+ CompressedPublicKey, Keypair, SerializedXOnlyPublicKey, TweakedKeypair, TweakedPublicKey,
+ XOnlyPublicKey,
};
+#[cfg(all(feature = "rand", feature = "std"))]
+pub use secp256k1::rand;
/// Encapsulation module to provide a clear barrier for construction/destruction of types.
mod encapsulate {
@@ -203,11 +203,15 @@ impl XOnlyPublicKey {
/// Serializes the x-only public key as a byte-encoded x coordinate value (32 bytes).
#[inline]
- pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] { self.to_inner().serialize() }
+ pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] {
+ self.to_inner().serialize()
+ }
/// Converts this x-only public key to a full public key given the parity.
#[inline]
- pub fn public_key(&self, parity: Parity) -> PublicKey { self.to_inner().public_key(parity).into() }
+ pub fn public_key(&self, parity: Parity) -> PublicKey {
+ self.to_inner().public_key(parity).into()
+ }
/// Verifies that a tweak produced by [`XOnlyPublicKey::add_tweak`] was computed correctly.
///
@@ -1041,13 +1045,17 @@ impl<'de> serde::Deserialize<'de> for CompressedPublicKey {
pub type UntweakedPublicKey = XOnlyPublicKey;
impl fmt::LowerHex for TweakedPublicKey {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(self.as_x_only_public_key(), f) }
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fmt::LowerHex::fmt(self.as_x_only_public_key(), f)
+ }
}
// Allocate for serialized size
impl_to_hex_from_lower_hex!(TweakedPublicKey, |_| constants::SCHNORR_PUBLIC_KEY_SIZE * 2);
impl fmt::Display for TweakedPublicKey {
- fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(self.as_x_only_public_key(), f) }
+ fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
+ fmt::Display::fmt(self.as_x_only_public_key(), f)
+ }
}
/// Untweaked BIP-0340 key pair.
@@ -1107,7 +1115,9 @@ impl TapTweak for UntweakedPublicKey {
(TweakedPublicKey::dangerous_assume_tweaked(output_key), parity)
}
- fn dangerous_assume_tweaked(self) -> TweakedPublicKey { TweakedPublicKey::dangerous_assume_tweaked(self) }
+ fn dangerous_assume_tweaked(self) -> TweakedPublicKey {
+ TweakedPublicKey::dangerous_assume_tweaked(self)
+ }
}
impl TapTweak for UntweakedKeypair {
@@ -1131,7 +1141,9 @@ impl TapTweak for UntweakedKeypair {
TweakedKeypair::dangerous_assume_tweaked(Self::from(tweaked))
}
- fn dangerous_assume_tweaked(self) -> TweakedKeypair { TweakedKeypair::dangerous_assume_tweaked(self) }
+ fn dangerous_assume_tweaked(self) -> TweakedKeypair {
+ TweakedKeypair::dangerous_assume_tweaked(self)
+ }
}
impl TweakedPublicKey {
@@ -1143,7 +1155,9 @@ impl TweakedPublicKey {
/// Serializes the key as a byte-encoded x coordinate value (32 bytes).
#[inline]
- pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] { self.as_x_only_public_key().serialize() }
+ pub fn serialize(&self) -> [u8; constants::SCHNORR_PUBLIC_KEY_SIZE] {
+ self.as_x_only_public_key().serialize()
+ }
}
impl TweakedKeypair {
diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs
index c688cffc..0128fd49 100644
--- a/bitcoin/src/pow.rs
+++ b/bitcoin/src/pow.rs
@@ -99,7 +99,9 @@ macro_rules! do_impl {
type Err = $err_ty;
#[inline]
- fn from_str(s: &str) -> Result<Self, Self::Err> { U256::from_str(s).map($ty).map_err($err_ty) }
+ fn from_str(s: &str) -> Result<Self, Self::Err> {
+ U256::from_str(s).map($ty).map_err($err_ty)
+ }
}
#[doc = "Error returned when parsing a [`"]
@@ -427,21 +429,23 @@ pub fn next_target_after<F, E>(
mut get_block_header_by_height: F,
) -> Result<CompactTarget, E>
where
- F: FnMut(BlockHeight) -> Result<Header, E>
+ F: FnMut(BlockHeight) -> Result<Header, E>,
{
// explicitly dropping the high bits because they make no sense since block height is only u32
let adjustment_interval = params.difficulty_adjustment_interval() as u32;
// if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
if !is_retarget_height(current_height.saturating_add(1.into()), adjustment_interval) {
- if params.allow_min_difficulty_blocks { // Only true for testnet and regtest.
+ if params.allow_min_difficulty_blocks {
+ // Only true for testnet and regtest.
let new_block_timestamp = new_block_timestamp
.expect("new_block_timestamp must contain a value when on testnet/regtest");
// Special difficulty rule for testnet: If the new block's timestamp is more
// than 2*10 minutes then allow mining of a min-difficulty block.
let pow_limit = params.max_attainable_target.to_compact_lossy();
- let pow_target_spacing = u32::try_from(params.pow_target_spacing & u64::from(u32::MAX)).unwrap();
+ let pow_target_spacing =
+ u32::try_from(params.pow_target_spacing & u64::from(u32::MAX)).unwrap();
// if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
if new_block_timestamp > current_header.time.to_u32() + pow_target_spacing * 2 {
@@ -1109,12 +1113,9 @@ impl core::str::FromStr for U256 {
}
for chunk in s.as_bytes().rchunks(38).rev() {
- let chunk_str = core::str::from_utf8(chunk)
- .map_err(ParseU256Error::InvalidEncoding)?;
+ let chunk_str = core::str::from_utf8(chunk).map_err(ParseU256Error::InvalidEncoding)?;
- let val: u128 = chunk_str
- .parse()
- .map_err(ParseU256Error::InvalidDigit)?;
+ let val: u128 = chunk_str.parse().map_err(ParseU256Error::InvalidDigit)?;
// Shift decimals and add chunk
let (res, carry1) = result.overflowing_mul(POW10_38.into());
@@ -1269,7 +1270,8 @@ impl fmt::Display for ParseU256Error {
match self {
Self::Overflow => write!(f, "parsed value exceeded unsigned 256-bit range"),
Self::Empty => write!(f, "parsed string is empty"),
- Self::InvalidEncoding(ref e) => write_err!(f, "parsed number contained non-ascii chars"; e),
+ Self::InvalidEncoding(ref e) =>
+ write_err!(f, "parsed number contained non-ascii chars"; e),
Self::InvalidDigit(ref e) => write_err!(f, "parsed number contained invalid digit"; e),
}
}
@@ -1316,10 +1318,9 @@ pub mod test_utils {
#[cfg(test)]
mod tests {
- use super::*;
-
use core::str::FromStr;
+ use super::*;
#[cfg(feature = "std")]
use crate::pow::test_utils::u128_to_work;
use crate::pow::test_utils::{u32_to_target, u64_to_target};
@@ -2168,13 +2169,19 @@ mod tests {
};
// Test mainnet (enforce_bip94 = false): should use current.bits
- let mainnet_result =
- CompactTarget::from_header_difficulty_adjustment(epoch_start, current, &Params::MAINNET);
+ let mainnet_result = CompactTarget::from_header_difficulty_adjustment(
+ epoch_start,
+ current,
+ &Params::MAINNET,
+ );
assert_eq!(mainnet_result, bits_end);
// Test testnet4 (enforce_bip94 = true): should use epoch_start.bits
- let testnet_result =
- CompactTarget::from_header_difficulty_adjustment(epoch_start, current, &Params::TESTNET4);
+ let testnet_result = CompactTarget::from_header_difficulty_adjustment(
+ epoch_start,
+ current,
+ &Params::TESTNET4,
+ );
assert_eq!(testnet_result, bits_start);
}
@@ -2200,11 +2207,10 @@ mod tests {
macro_rules! check_from_str {
($ty:ident, $err_ty:ident, $mod_name:ident) => {
mod $mod_name {
- use super::{ParseU256Error, U256};
- use super::{$ty, $err_ty};
-
use core::str::FromStr;
+ use super::{$err_ty, $ty, ParseU256Error, U256};
+
#[test]
fn target_from_str_decimal() {
assert_eq!($ty::from_str("0").unwrap(), $ty(U256::ZERO));
@@ -2629,8 +2635,14 @@ mod tests {
})
};
- let got = next_target_after(current_header, current_height, ¶ms, new_block_timestamp, fetch_header)
- .expect("failed to calculate next target");
+ let got = next_target_after(
+ current_header,
+ current_height,
+ ¶ms,
+ new_block_timestamp,
+ fetch_header,
+ )
+ .expect("failed to calculate next target");
// Should return the real_target from the walked-back header
assert_eq!(got, want);
diff --git a/bitcoin/src/psbt/mod.rs b/bitcoin/src/psbt/mod.rs
index bbbc890a..907cf09e 100644
--- a/bitcoin/src/psbt/mod.rs
+++ b/bitcoin/src/psbt/mod.rs
@@ -2557,7 +2557,7 @@ mod tests {
Err(ExtractTxError::MissingInputAmount { tx: _ })
))
}
-
+
#[test]
fn spending_psbt_with_missing_txout() {
let psbt = Psbt {
@@ -2575,15 +2575,13 @@ mod tests {
sequence: Sequence::ENABLE_LOCKTIME_NO_RBF,
witness: Witness::default(),
}],
- outputs: vec![
- TxOut {
- amount: Amount::from_sat_u32(99_999_699),
- script_pubkey: ScriptPubKeyBuf::from_hex_no_length_prefix(
- "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac",
- )
- .unwrap(),
- },
- ],
+ outputs: vec![TxOut {
+ amount: Amount::from_sat_u32(99_999_699),
+ script_pubkey: ScriptPubKeyBuf::from_hex_no_length_prefix(
+ "76a914d0c59903c5bac2868760e90fd521a4665aa7652088ac",
+ )
+ .unwrap(),
+ }],
},
xpub: Default::default(),
version: 0,
@@ -2594,7 +2592,7 @@ mod tests {
version: transaction::Version::TWO,
lock_time: absolute::LockTime::ZERO,
inputs: vec![],
- outputs: vec![], // No outputs here
+ outputs: vec![], // No outputs here
}),
..Default::default()
}],
diff --git a/consensus_encoding/tests/encode.rs b/consensus_encoding/tests/encode.rs
index 21a37695..3d531b55 100644
--- a/consensus_encoding/tests/encode.rs
+++ b/consensus_encoding/tests/encode.rs
@@ -116,7 +116,8 @@ fn encode_newtype_lifetime_flexibility() {
let test_data = b"hello world";
let custom_encoder = CustomEncoder::new(BytesEncoder::without_length_prefix(test_data));
- let no_lifetime_encoder = NoLifetimeEncoder::new(ArrayEncoder::without_length_prefix([1, 2, 3, 4]));
+ let no_lifetime_encoder =
+ NoLifetimeEncoder::new(ArrayEncoder::without_length_prefix([1, 2, 3, 4]));
assert_eq!(custom_encoder.current_chunk(), test_data.as_slice());
assert_eq!(no_lifetime_encoder.current_chunk(), &[1, 2, 3, 4][..]);
diff --git a/hashes/src/lib.rs b/hashes/src/lib.rs
index 336a2b42..91331d22 100644
--- a/hashes/src/lib.rs
+++ b/hashes/src/lib.rs
@@ -265,7 +265,10 @@ fn incomplete_block_len<H: HashEngine>(eng: &H) -> usize {
///
/// For when we cannot rely on having the `hex` feature enabled. Ignores formatter options and just
/// writes with plain old `f.write_char()`.
-pub fn debug_hex<'a>(bytes: impl IntoIterator<Item = &'a u8>, f: &mut fmt::Formatter) -> fmt::Result {
+pub fn debug_hex<'a>(
+ bytes: impl IntoIterator<Item = &'a u8>,
+ f: &mut fmt::Formatter,
+) -> fmt::Result {
const HEX_TABLE: [u8; 16] = *b"0123456789abcdef";
for &b in bytes {
diff --git a/hashes/src/sha256/mod.rs b/hashes/src/sha256/mod.rs
index 6d18d141..1fd99694 100644
--- a/hashes/src/sha256/mod.rs
+++ b/hashes/src/sha256/mod.rs
@@ -73,15 +73,19 @@ impl HashEngine {
let aligned_bytes = self.bytes_hashed - unprocessed_len as u64;
let mut midstate_bytes = [0; 32];
- for (val, ret_bytes) in self.h.iter().zip(midstate_bytes.bitcoin_as_chunks_mut::<4>().0) {
+ for (val, ret_bytes) in self.h.iter().zip(midstate_bytes.bitcoin_as_chunks_mut::<4>().0)
+ {
*ret_bytes = val.to_be_bytes();
}
return Err(MidstateError {
invalid_n_bytes_hashed: self.bytes_hashed,
- block_aligned_midstate: Midstate { bytes: midstate_bytes, bytes_hashed: aligned_bytes },
+ block_aligned_midstate: Midstate {
+ bytes: midstate_bytes,
+ bytes_hashed: aligned_bytes,
+ },
unprocessed_bytes: self.buffer,
- unprocessed_bytes_len: unprocessed_len
+ unprocessed_bytes_len: unprocessed_len,
});
}
Ok(self.midstate_unchecked())
@@ -264,7 +268,9 @@ impl MidstateError {
pub const fn midstate(&self) -> &Midstate { &self.block_aligned_midstate }
/// returns the unprocessed bytes remaining in the buffer.
- pub fn unprocessed_bytes(&self) -> &[u8] { &self.unprocessed_bytes[..self.unprocessed_bytes_len] }
+ pub fn unprocessed_bytes(&self) -> &[u8] {
+ &self.unprocessed_bytes[..self.unprocessed_bytes_len]
+ }
}
impl fmt::Display for MidstateError {
diff --git a/hashes/tests/api.rs b/hashes/tests/api.rs
index bd53713d..ca5c91c4 100644
--- a/hashes/tests/api.rs
+++ b/hashes/tests/api.rs
@@ -18,8 +18,8 @@ use bitcoin_hashes::{
};
// Import using type alias style e.g., `Sha256`.
use bitcoin_hashes::{
- Hash160, Hkdf, Hmac, HmacEngine, Ripemd160, Sha1, Sha256, Sha256d, Sha256t, Sha384,
- Sha3_256, Sha512, Sha512_256, Siphash24,
+ Hash160, Hkdf, Hmac, HmacEngine, Ripemd160, Sha1, Sha256, Sha256d, Sha256t, Sha384, Sha3_256,
+ Sha512, Sha512_256, Siphash24,
};
// Arbitrary midstate value; taken from as sha256t unit tests.
diff --git a/p2p/src/address.rs b/p2p/src/address.rs
index 60f5ff06..50c1586e 100644
--- a/p2p/src/address.rs
+++ b/p2p/src/address.rs
@@ -14,7 +14,9 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
use bitcoin::consensus::encode::{self, Decodable, Encodable, ReadExt, WriteExt};
-use encoding::{ArrayDecoder, ArrayEncoder, BytesEncoder, ByteVecDecoder, CompactSizeEncoder, Decoder2};
+use encoding::{
+ ArrayDecoder, ArrayEncoder, ByteVecDecoder, BytesEncoder, CompactSizeEncoder, Decoder2,
+};
use internals::write_err;
use io::{BufRead, Read, Write};
@@ -228,7 +230,14 @@ pub struct AddrV2Encoder<'e> {
}
impl<'e> AddrV2Encoder<'e> {
- const EMPTY: Self = Self { network: None, size: None, bytes4: None, bytes16: None, bytes32: None, nbytes: None };
+ const EMPTY: Self = Self {
+ network: None,
+ size: None,
+ bytes4: None,
+ bytes16: None,
+ bytes32: None,
+ nbytes: None,
+ };
/// Construct a new [`AddrV2`] encoder.
pub fn new(addr_v2: &'e AddrV2) -> Self {
// Each address is prefixed with the network type and length of the byte array.
@@ -251,22 +260,18 @@ impl<'e> AddrV2Encoder<'e> {
..Self::EMPTY
}
}
- AddrV2::TorV3(onion) => {
- Self {
- network: Some(ArrayEncoder::without_length_prefix([4])),
- size: Some(CompactSizeEncoder::new(32)),
- bytes32: Some(ArrayEncoder::without_length_prefix(*onion)),
- ..Self::EMPTY
- }
- }
- AddrV2::I2p(i2p) => {
- Self {
- network: Some(ArrayEncoder::without_length_prefix([5])),
- size: Some(CompactSizeEncoder::new(32)),
- bytes32: Some(ArrayEncoder::without_length_prefix(*i2p)),
- ..Self::EMPTY
- }
- }
+ AddrV2::TorV3(onion) => Self {
+ network: Some(ArrayEncoder::without_length_prefix([4])),
+ size: Some(CompactSizeEncoder::new(32)),
+ bytes32: Some(ArrayEncoder::without_length_prefix(*onion)),
+ ..Self::EMPTY
+ },
+ AddrV2::I2p(i2p) => Self {
+ network: Some(ArrayEncoder::without_length_prefix([5])),
+ size: Some(CompactSizeEncoder::new(32)),
+ bytes32: Some(ArrayEncoder::without_length_prefix(*i2p)),
+ ..Self::EMPTY
+ },
AddrV2::Cjdns(ipv6) => {
let octets = ipv6.octets();
Self {
@@ -276,14 +281,12 @@ impl<'e> AddrV2Encoder<'e> {
..Self::EMPTY
}
}
- AddrV2::Unknown(network, bytes) => {
- Self {
- network: Some(ArrayEncoder::without_length_prefix([*network])),
- size: Some(CompactSizeEncoder::new(bytes.len())),
- nbytes: Some(BytesEncoder::<'e>::without_length_prefix(bytes.as_slice())),
- ..Self::EMPTY
- }
- }
+ AddrV2::Unknown(network, bytes) => Self {
+ network: Some(ArrayEncoder::without_length_prefix([*network])),
+ size: Some(CompactSizeEncoder::new(bytes.len())),
+ nbytes: Some(BytesEncoder::<'e>::without_length_prefix(bytes.as_slice())),
+ ..Self::EMPTY
+ },
}
}
}
@@ -343,9 +346,7 @@ impl<'e> encoding::Encoder for AddrV2Encoder<'e> {
impl encoding::Encodable for AddrV2 {
type Encoder<'e> = AddrV2Encoder<'e>;
- fn encoder(&self) -> Self::Encoder<'_> {
- AddrV2Encoder::new(self)
- }
+ fn encoder(&self) -> Self::Encoder<'_> { AddrV2Encoder::new(self) }
}
type AddrV2InnerDecoder = Decoder2<ArrayDecoder<1>, ByteVecDecoder>;
@@ -378,16 +379,17 @@ impl AddrV2Decoder {
segments[4],
segments[5],
segments[6],
- segments[7]
+ segments[7],
)
}
#[inline]
- fn to_fixed_size_slice<const N: usize>(addr_bytes: Vec<u8>) -> Result<[u8; N], AddrV2DecoderError> {
- Ok(addr_bytes
- .try_into()
- .map_err(|e: Vec<u8>| AddrV2DecoderError::InvalidAddressLength { expected: N, got: e.len() })?
- )
+ fn to_fixed_size_slice<const N: usize>(
+ addr_bytes: Vec<u8>,
+ ) -> Result<[u8; N], AddrV2DecoderError> {
+ Ok(addr_bytes.try_into().map_err(|e: Vec<u8>| {
+ AddrV2DecoderError::InvalidAddressLength { expected: N, got: e.len() }
+ })?)
}
}
@@ -430,7 +432,7 @@ impl encoding::Decoder for AddrV2Decoder {
6 => {
let octets = Self::to_fixed_size_slice::<16>(addr_bytes)?;
if octets[0] != 0xFC {
- return Err(AddrV2DecoderError::NotCjdns)
+ return Err(AddrV2DecoderError::NotCjdns);
}
Ok(AddrV2::Cjdns(Self::ipv6_from_segments(Self::be_bytes_to_segments(octets))))
}
@@ -446,12 +448,7 @@ impl encoding::Decodable for AddrV2 {
type Decoder = AddrV2Decoder;
fn decoder() -> Self::Decoder {
- AddrV2Decoder(
- Decoder2::new(
- ArrayDecoder::new(),
- ByteVecDecoder::new(),
- )
- )
+ AddrV2Decoder(Decoder2::new(ArrayDecoder::new(), ByteVecDecoder::new()))
}
}
@@ -483,7 +480,8 @@ impl fmt::Display for AddrV2DecoderError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Decoder(d) => write_err!(f, "addrv2 error"; d),
- Self::InvalidAddressLength { expected, got } => write!(f, "invalid length. expected {}, got {}", expected, got),
+ Self::InvalidAddressLength { expected, got } =>
+ write!(f, "invalid length. expected {}, got {}", expected, got),
Self::NotCjdns => write!(f, "CJDNS address must start with a reserved byte."),
Self::WrappedOnionCat => write!(f, "OnionCat address sent as IPv6 is invalid."),
Self::WrappedIpv4 => write!(f, "wrapped IPv4 sent as IPv6 is invalid."),
@@ -969,7 +967,8 @@ mod test {
assert_eq!(serialize(&ip), ip_bytes);
assert_eq!(encoding::encode_to_vec(&ip).as_slice(), ip_bytes);
- let tor_bytes = hex!("042053cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88");
+ let tor_bytes =
+ hex!("042053cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88");
let ip = AddrV2::TorV3(
FromHex::from_hex("53cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88")
.unwrap(),
@@ -977,7 +976,8 @@ mod test {
assert_eq!(serialize(&ip), tor_bytes);
assert_eq!(encoding::encode_to_vec(&ip), tor_bytes);
- let i2p_bytes = hex!("0520a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87");
+ let i2p_bytes =
+ hex!("0520a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87");
let ip = AddrV2::I2p(
FromHex::from_hex("a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87")
.unwrap(),
@@ -1047,8 +1047,10 @@ mod test {
assert!(encoding::decode_from_slice::<AddrV2>(&torish).is_err());
// Valid TORv3.
- let tor_bytes = hex!("042079bcc625184b05194975c28b66b66b0469f7f6556fb1ac3189a79b40dda32f1f");
- let want = AddrV2::TorV3(hex!("79bcc625184b05194975c28b66b66b0469f7f6556fb1ac3189a79b40dda32f1f"));
+ let tor_bytes =
+ hex!("042079bcc625184b05194975c28b66b66b0469f7f6556fb1ac3189a79b40dda32f1f");
+ let want =
+ AddrV2::TorV3(hex!("79bcc625184b05194975c28b66b66b0469f7f6556fb1ac3189a79b40dda32f1f"));
let ip: AddrV2 = deserialize(&tor_bytes).unwrap();
assert_eq!(ip, want);
let ip: AddrV2 = encoding::decode_from_slice(&tor_bytes).unwrap();
@@ -1060,8 +1062,10 @@ mod test {
assert!(encoding::decode_from_slice::<AddrV2>(&invalid).is_err());
// Valid I2P.
- let i2p_bytes = hex!("0520a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87");
- let want = AddrV2::I2p(hex!("a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87"));
+ let i2p_bytes =
+ hex!("0520a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87");
+ let want =
+ AddrV2::I2p(hex!("a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87"));
let i2p: AddrV2 = deserialize(&i2p_bytes).unwrap();
assert_eq!(i2p, want);
let ip: AddrV2 = encoding::decode_from_slice(&i2p_bytes).unwrap();
diff --git a/p2p/src/bip152.rs b/p2p/src/bip152.rs
index a8431372..4b991511 100644
--- a/p2p/src/bip152.rs
+++ b/p2p/src/bip152.rs
@@ -425,15 +425,13 @@ impl encoding::Encodable for BlockTransactionsRequest {
type Encoder<'e> = BlockTransactionsRequestEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- BlockTransactionsRequestEncoder::new(
+ BlockTransactionsRequestEncoder::new(Encoder2::new(
+ self.block_hash.encoder(),
Encoder2::new(
- self.block_hash.encoder(),
- Encoder2::new(
- CompactSizeEncoder::new(self.offsets.len()),
- SliceEncoder::without_length_prefix(&self.offsets),
- ),
- )
- )
+ CompactSizeEncoder::new(self.offsets.len()),
+ SliceEncoder::without_length_prefix(&self.offsets),
+ ),
+ ))
}
}
diff --git a/p2p/src/message.rs b/p2p/src/message.rs
index 9fbab9f8..0c30c15a 100644
--- a/p2p/src/message.rs
+++ b/p2p/src/message.rs
@@ -18,8 +18,7 @@ use arbitrary::{Arbitrary, Unstructured};
use bitcoin::consensus::encode::{self, Decodable, Encodable, ReadExt, WriteExt};
use encoding::{self, CompactSizeEncoder, Encoder2, SliceEncoder, VecDecoder};
use hashes::sha256d;
-use internals::ToU64 as _;
-use internals::write_err;
+use internals::{write_err, ToU64 as _};
use io::{self, BufRead, Read, Write};
use primitives::{block, transaction};
use units::FeeRate;
@@ -340,7 +339,7 @@ impl encoding::Encodable for InventoryPayload {
fn encoder(&self) -> Self::Encoder<'_> {
Encoder2::new(
CompactSizeEncoder::new(self.0.len()),
- SliceEncoder::without_length_prefix(&self.0)
+ SliceEncoder::without_length_prefix(&self.0),
)
}
}
@@ -361,7 +360,7 @@ impl encoding::Decoder for InventoryPayloadDecoder {
#[inline]
fn end(self) -> Result<Self::Output, Self::Error> {
- Ok(InventoryPayload(self.0.end().map_err(InventoryPayloadDecoderError)?))
+ Ok(InventoryPayload(self.0.end().map_err(InventoryPayloadDecoderError)?))
}
#[inline]
@@ -1218,7 +1217,9 @@ impl encoding::Decoder for RawNetworkMessageDecoder {
let (magic_bytes, command, payload_len_bytes, checksum) =
header_decoder.end().map_err(|_| {
- RawNetworkMessageDecoderError(RawNetworkMessageDecoderErrorInner::Header)
+ RawNetworkMessageDecoderError(
+ RawNetworkMessageDecoderErrorInner::Header,
+ )
})?;
let payload_len = u32::from_le_bytes(payload_len_bytes) as usize;
diff --git a/p2p/src/message_bloom.rs b/p2p/src/message_bloom.rs
index fa6dea32..455742aa 100644
--- a/p2p/src/message_bloom.rs
+++ b/p2p/src/message_bloom.rs
@@ -149,13 +149,11 @@ impl encoding::Encodable for BloomFlags {
type Encoder<'e> = BloomFlagsEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- BloomFlagsEncoder::new(ArrayEncoder::without_length_prefix(
- [match self {
- Self::None => 0,
- Self::All => 1,
- Self::PubkeyOnly => 2,
- }]
- ))
+ BloomFlagsEncoder::new(ArrayEncoder::without_length_prefix([match self {
+ Self::None => 0,
+ Self::All => 1,
+ Self::PubkeyOnly => 2,
+ }]))
}
}
@@ -273,12 +271,10 @@ impl encoding::Encodable for FilterAdd {
type Encoder<'e> = FilterAddEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- FilterAddEncoder::new(
- Encoder2::new(
- CompactSizeEncoder::new(self.data.len()),
- BytesEncoder::without_length_prefix(&self.data)
- )
- )
+ FilterAddEncoder::new(Encoder2::new(
+ CompactSizeEncoder::new(self.data.len()),
+ BytesEncoder::without_length_prefix(&self.data),
+ ))
}
}
diff --git a/p2p/src/message_network.rs b/p2p/src/message_network.rs
index 068ae92b..12674965 100644
--- a/p2p/src/message_network.rs
+++ b/p2p/src/message_network.rs
@@ -120,12 +120,10 @@ impl encoding::Encodable for UserAgent {
type Encoder<'e> = UserAgentEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- UserAgentEncoder::new(
- Encoder2::new(
- CompactSizeEncoder::new(self.user_agent.len()),
- BytesEncoder::without_length_prefix(self.user_agent.as_bytes())
- )
- )
+ UserAgentEncoder::new(Encoder2::new(
+ CompactSizeEncoder::new(self.user_agent.len()),
+ BytesEncoder::without_length_prefix(self.user_agent.as_bytes()),
+ ))
}
}
@@ -495,20 +493,18 @@ impl encoding::Encodable for Reject {
type Encoder<'e> = RejectEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- RejectEncoder::new(
- Encoder4::new(
- Encoder2::new(
- CompactSizeEncoder::new(self.message.len()),
- BytesEncoder::without_length_prefix(self.message.as_bytes())
- ),
- self.ccode.encoder(),
- Encoder2::new(
- CompactSizeEncoder::new(self.reason.len()),
- BytesEncoder::without_length_prefix(self.reason.as_bytes())
- ),
- ArrayEncoder::without_length_prefix(self.hash.to_byte_array()),
- )
- )
+ RejectEncoder::new(Encoder4::new(
+ Encoder2::new(
+ CompactSizeEncoder::new(self.message.len()),
+ BytesEncoder::without_length_prefix(self.message.as_bytes()),
+ ),
+ self.ccode.encoder(),
+ Encoder2::new(
+ CompactSizeEncoder::new(self.reason.len()),
+ BytesEncoder::without_length_prefix(self.reason.as_bytes()),
+ ),
+ ArrayEncoder::without_length_prefix(self.hash.to_byte_array()),
+ ))
}
}
diff --git a/primitives/src/block.rs b/primitives/src/block.rs
index 4b825a77..419607e7 100644
--- a/primitives/src/block.rs
+++ b/primitives/src/block.rs
@@ -823,7 +823,6 @@ impl fmt::Octal for Version {
impl fmt::Binary for Version {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Binary::fmt(&self.0, f) }
-
}
impl Default for Version {
diff --git a/primitives/src/hash_types/mod.rs b/primitives/src/hash_types/mod.rs
index 7bf3bc2d..1f3964c4 100644
--- a/primitives/src/hash_types/mod.rs
+++ b/primitives/src/hash_types/mod.rs
@@ -200,7 +200,7 @@ mod tests {
#[cfg(feature = "alloc")]
fn ab_test_case() -> (Txid, &'static str) {
let mut a = [0xab; 32];
- a[0] = 0xff; // Just so we can see which way the array is printing.
+ a[0] = 0xff; // Just so we can see which way the array is printing.
let tc = Txid::from_byte_array(a);
let want = "abababababababababababababababababababababababababababababababff";
diff --git a/primitives/src/hash_types/transaction_merkle_node.rs b/primitives/src/hash_types/transaction_merkle_node.rs
index d9b59532..88471527 100644
--- a/primitives/src/hash_types/transaction_merkle_node.rs
+++ b/primitives/src/hash_types/transaction_merkle_node.rs
@@ -56,7 +56,9 @@ encoding::encoder_newtype_exact! {
impl encoding::Encodable for TxMerkleNode {
type Encoder<'e> = TxMerkleNodeEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- TxMerkleNodeEncoder::new(encoding::ArrayEncoder::without_length_prefix(self.to_byte_array()))
+ TxMerkleNodeEncoder::new(encoding::ArrayEncoder::without_length_prefix(
+ self.to_byte_array(),
+ ))
}
}
diff --git a/primitives/src/script/owned.rs b/primitives/src/script/owned.rs
index fb8d6219..98f24d81 100644
--- a/primitives/src/script/owned.rs
+++ b/primitives/src/script/owned.rs
@@ -218,10 +218,10 @@ mod tests {
// All tests should compile and pass no matter which script type you put here.
type ScriptBuf = super::super::ScriptSigBuf;
- #[cfg(feature = "alloc")]
- use alloc::vec;
#[cfg(feature = "alloc")]
use alloc::string::ToString;
+ #[cfg(feature = "alloc")]
+ use alloc::vec;
#[cfg(feature = "std")]
use std::error::Error as _;
diff --git a/primitives/src/transaction.rs b/primitives/src/transaction.rs
index b53ee73a..890cd4e0 100644
--- a/primitives/src/transaction.rs
+++ b/primitives/src/transaction.rs
@@ -324,13 +324,13 @@ fn hash_transaction(tx: &Transaction, uses_segwit_serialization: bool) -> sha256
#[cfg(feature = "alloc")]
type TransactionEncoderInner<'e> = Encoder6<
- VersionEncoder<'e>,
- Option<ArrayEncoder<2>>,
- Encoder2<CompactSizeEncoder, SliceEncoder<'e, TxIn>>,
- Encoder2<CompactSizeEncoder, SliceEncoder<'e, TxOut>>,
- Option<WitnessesEncoder<'e>>,
- LockTimeEncoder<'e>,
- >;
+ VersionEncoder<'e>,
+ Option<ArrayEncoder<2>>,
+ Encoder2<CompactSizeEncoder, SliceEncoder<'e, TxIn>>,
+ Encoder2<CompactSizeEncoder, SliceEncoder<'e, TxOut>>,
+ Option<WitnessesEncoder<'e>>,
+ LockTimeEncoder<'e>,
+>;
#[cfg(feature = "alloc")]
encoding::encoder_newtype! {
@@ -1531,7 +1531,9 @@ encoding::encoder_newtype_exact! {
impl encoding::Encodable for Version {
type Encoder<'e> = VersionEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- VersionEncoder::new(encoding::ArrayEncoder::without_length_prefix(self.to_u32().to_le_bytes()))
+ VersionEncoder::new(encoding::ArrayEncoder::without_length_prefix(
+ self.to_u32().to_le_bytes(),
+ ))
}
}
diff --git a/units/src/amount/unsigned.rs b/units/src/amount/unsigned.rs
index 3443fce5..114df54f 100644
--- a/units/src/amount/unsigned.rs
+++ b/units/src/amount/unsigned.rs
@@ -566,7 +566,9 @@ encoding::encoder_newtype_exact! {
impl encoding::Encodable for Amount {
type Encoder<'e> = AmountEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- AmountEncoder::new(encoding::ArrayEncoder::without_length_prefix(self.to_sat().to_le_bytes()))
+ AmountEncoder::new(encoding::ArrayEncoder::without_length_prefix(
+ self.to_sat().to_le_bytes(),
+ ))
}
}
diff --git a/units/src/block.rs b/units/src/block.rs
index 85614b33..aa81f50f 100644
--- a/units/src/block.rs
+++ b/units/src/block.rs
@@ -834,66 +834,33 @@ mod tests {
#[test]
fn block_height_saturating_add() {
// Normal addition
- assert_eq!(
- BlockHeight(100).saturating_add(BlockHeightInterval(50)),
- BlockHeight(150),
- );
- assert_eq!(
- BlockHeight::ZERO.saturating_add(BlockHeightInterval(1)),
- BlockHeight(1),
- );
+ assert_eq!(BlockHeight(100).saturating_add(BlockHeightInterval(50)), BlockHeight(150),);
+ assert_eq!(BlockHeight::ZERO.saturating_add(BlockHeightInterval(1)), BlockHeight(1),);
// Saturates at MAX instead of overflowing
- assert_eq!(
- BlockHeight::MAX.saturating_add(BlockHeightInterval(1)),
- BlockHeight::MAX,
- );
- assert_eq!(
- BlockHeight::MAX.saturating_add(BlockHeightInterval(100)),
- BlockHeight::MAX,
- );
+ assert_eq!(BlockHeight::MAX.saturating_add(BlockHeightInterval(1)), BlockHeight::MAX,);
+ assert_eq!(BlockHeight::MAX.saturating_add(BlockHeightInterval(100)), BlockHeight::MAX,);
assert_eq!(
BlockHeight(u32::MAX - 10).saturating_add(BlockHeightInterval(20)),
BlockHeight::MAX,
);
// Adding zero
- assert_eq!(
- BlockHeight(500).saturating_add(BlockHeightInterval::ZERO),
- BlockHeight(500),
- );
+ assert_eq!(BlockHeight(500).saturating_add(BlockHeightInterval::ZERO), BlockHeight(500),);
}
#[test]
fn block_height_saturating_sub() {
// Normal subtraction
- assert_eq!(
- BlockHeight(100).saturating_sub(BlockHeightInterval(50)),
- BlockHeight(50),
- );
- assert_eq!(
- BlockHeight(100).saturating_sub(BlockHeightInterval(100)),
- BlockHeight(0),
- );
+ assert_eq!(BlockHeight(100).saturating_sub(BlockHeightInterval(50)), BlockHeight(50),);
+ assert_eq!(BlockHeight(100).saturating_sub(BlockHeightInterval(100)), BlockHeight(0),);
// Saturates at MIN instead of underflowing
- assert_eq!(
- BlockHeight::MIN.saturating_sub(BlockHeightInterval(1)),
- BlockHeight::MIN,
- );
- assert_eq!(
- BlockHeight::ZERO.saturating_sub(BlockHeightInterval(100)),
- BlockHeight::ZERO,
- );
- assert_eq!(
- BlockHeight(10).saturating_sub(BlockHeightInterval(20)),
- BlockHeight::ZERO,
- );
+ assert_eq!(BlockHeight::MIN.saturating_sub(BlockHeightInterval(1)), BlockHeight::MIN,);
+ assert_eq!(BlockHeight::ZERO.saturating_sub(BlockHeightInterval(100)), BlockHeight::ZERO,);
+ assert_eq!(BlockHeight(10).saturating_sub(BlockHeightInterval(20)), BlockHeight::ZERO,);
// Subtracting zero
- assert_eq!(
- BlockHeight(500).saturating_sub(BlockHeightInterval::ZERO),
- BlockHeight(500),
- );
+ assert_eq!(BlockHeight(500).saturating_sub(BlockHeightInterval::ZERO), BlockHeight(500),);
}
}
diff --git a/units/src/sequence.rs b/units/src/sequence.rs
index 5ea92124..0e1839ea 100644
--- a/units/src/sequence.rs
+++ b/units/src/sequence.rs
@@ -392,10 +392,10 @@ mod tests {
#[cfg(feature = "alloc")]
use alloc::format;
- #[cfg(all(feature = "encoding", feature = "alloc"))]
- use encoding::UnexpectedEofError;
#[cfg(feature = "encoding")]
use encoding::Decoder as _;
+ #[cfg(all(feature = "encoding", feature = "alloc"))]
+ use encoding::UnexpectedEofError;
use super::*;
diff --git a/units/src/time.rs b/units/src/time.rs
index 9a2a3d60..1d3a0ffb 100644
--- a/units/src/time.rs
+++ b/units/src/time.rs
@@ -90,7 +90,9 @@ encoding::encoder_newtype_exact! {
impl encoding::Encodable for BlockTime {
type Encoder<'e> = BlockTimeEncoder<'e>;
fn encoder(&self) -> Self::Encoder<'_> {
- BlockTimeEncoder::new(encoding::ArrayEncoder::without_length_prefix(self.to_u32().to_le_bytes()))
+ BlockTimeEncoder::new(encoding::ArrayEncoder::without_length_prefix(
+ self.to_u32().to_le_bytes(),
+ ))
}
}
@@ -168,10 +170,10 @@ impl<'a> Arbitrary<'a> for BlockTime {
#[cfg(test)]
mod tests {
- #[cfg(all(feature = "encoding", feature = "alloc"))]
- use encoding::UnexpectedEofError;
#[cfg(feature = "encoding")]
use encoding::Decoder as _;
+ #[cfg(all(feature = "encoding", feature = "alloc"))]
+ use encoding::UnexpectedEofError;
use super::*;
diff --git a/units/tests/encoding.rs b/units/tests/encoding.rs
index de94d4fd..0c0f0db7 100644
--- a/units/tests/encoding.rs
+++ b/units/tests/encoding.rs
@@ -5,14 +5,13 @@
#![cfg(feature = "alloc")]
#![cfg(feature = "encoding")]
-use encoding::{encode_to_vec, Decodable as _, Decoder as _};
-
use bitcoin_units::absolute::{LockTime, LockTimeDecoder};
use bitcoin_units::amount::AmountDecoder;
use bitcoin_units::block::BlockHeightDecoder;
use bitcoin_units::sequence::SequenceDecoder;
use bitcoin_units::time::BlockTimeDecoder;
use bitcoin_units::{Amount, BlockHeight, BlockTime, Sequence};
+use encoding::{encode_to_vec, Decodable as _, Decoder as _};
/// Tests round-trip encoding/decoding for a list of values.
///
@@ -119,7 +118,10 @@ test_hardcoded_decoding!(
([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], Amount::ONE_SAT),
([0x00, 0xe1, 0xf5, 0x05, 0x00, 0x00, 0x00, 0x00], Amount::ONE_BTC), // 100_000_000 sats
([0x00, 0xe1, 0xf5, 0x05, 0x00, 0x00, 0x00, 0x00], Amount::from_sat(100_000_000).unwrap()), // 1 BTC
- ([0x00, 0x40, 0x07, 0x5a, 0xf0, 0x75, 0x07, 0x00], Amount::from_sat(21_000_000 * 100_000_000).unwrap()), // 21M BTC
+ (
+ [0x00, 0x40, 0x07, 0x5a, 0xf0, 0x75, 0x07, 0x00],
+ Amount::from_sat(21_000_000 * 100_000_000).unwrap()
+ ), // 21M BTC
);
test_decoder_default!(amount_decoder_default, Amount, AmountDecoder, 8);
@@ -143,7 +145,10 @@ test_incremental_decoding!(
([0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], Amount::ONE_SAT),
([0x00, 0xe1, 0xf5, 0x05, 0x00, 0x00, 0x00, 0x00], Amount::ONE_BTC), // 100_000_000 sats
([0x00, 0xe1, 0xf5, 0x05, 0x00, 0x00, 0x00, 0x00], Amount::from_sat(100_000_000).unwrap()), // 1 BTC
- ([0x00, 0x40, 0x07, 0x5a, 0xf0, 0x75, 0x07, 0x00], Amount::from_sat(21_000_000 * 100_000_000).unwrap()), // 21M BTC
+ (
+ [0x00, 0x40, 0x07, 0x5a, 0xf0, 0x75, 0x07, 0x00],
+ Amount::from_sat(21_000_000 * 100_000_000).unwrap()
+ ), // 21M BTC
);
// BlockHeight encodes as 4-byte little-endian u32.
Why this scored 15/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.