What changed, and why it matters
This commit is purely a code-formatting cleanup. It runs the project's formatter across 58 files, adjusting whitespace, line breaks, import order, and adding two missing semicolons the formatter exposed. There are no functional code changes, no bug fixes, and no security-relevant alterations.
No security action needed. Treat as routine maintenance; standard review/CI verification is sufficient.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The diff shows only stylistic changes produced by just fmt: collapsing multi-line function signatures onto single lines, rewrapping long expressions, reordering use statements alphabetically, removing blank lines, and adding trailing semicolons after two statements the formatter rewrote into block form. No logic, API, or behavior changes are present. The commit message explicitly states it is a formatter run.
Changed components
Inspect captured patch +312 / −490
diff --git a/bitcoin/examples/ecdsa-psbt-simple.rs b/bitcoin/examples/ecdsa-psbt-simple.rs
index ab2341d0..e57f8dcd 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 393c0ada..70a4b3d4 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<Psbt> {
+ fn sign_psbt(&self, mut psbt: Psbt) -> Result<Psbt> {
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 9ab4bfe4..6bb28580 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 f10be950..2b5ef494 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/bip158.rs b/bitcoin/src/bip158.rs
index 637b50e0..d240d1ad 100644
--- a/bitcoin/src/bip158.rs
+++ b/bitcoin/src/bip158.rs
@@ -100,7 +100,6 @@ pub struct BlockFilter {
pub content: Vec<u8>,
}
-
impl BlockFilter {
/// Constructs a new filter from pre-computed data.
pub fn new(content: &[u8]) -> Self { Self { content: content.to_vec() } }
@@ -125,9 +124,7 @@ impl BlockFilter {
}
/// Computes the canonical hash for the given filter.
- pub fn filter_hash(&self) -> sha256d::Hash {
- sha256d::Hash::hash(&self.content)
- }
+ pub fn filter_hash(&self) -> sha256d::Hash { sha256d::Hash::hash(&self.content) }
/// Returns true if any query matches against this [`BlockFilter`].
pub fn match_any<I>(&self, block_hash: BlockHash, query: I) -> Result<bool, Error>
@@ -452,9 +449,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.
///
@@ -500,9 +495,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<usize, io::Error> {
@@ -538,7 +531,6 @@ impl<'a, W: Write> BitStreamWriter<'a, W> {
}
}
-
#[cfg(test)]
mod test {
use std::collections::HashMap;
diff --git a/bitcoin/src/bip32.rs b/bitcoin/src/bip32.rs
index 013548b7..5d02b1a7 100644
--- a/bitcoin/src/bip32.rs
+++ b/bitcoin/src/bip32.rs
@@ -622,9 +622,7 @@ impl From<base58::Error> for ParseError {
}
impl From<InvalidBase58PayloadLengthError> for ParseError {
- fn from(e: InvalidBase58PayloadLengthError) -> Self {
- Self::InvalidBase58PayloadLength(e)
- }
+ fn from(e: InvalidBase58PayloadLengthError) -> Self { Self::InvalidBase58PayloadLength(e) }
}
/// A BIP-0032 error
@@ -740,9 +738,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.
@@ -755,20 +751,14 @@ impl Xpriv {
///
/// The `path` argument can be both of type `DerivationPath` or `Vec<ChildNumber>`.
#[deprecated(since = "TBD", note = "use `derive_xpriv()` instead")]
- pub fn derive_priv<P: AsRef<[ChildNumber]>>(
- &self,
- path: P,
- ) -> Result<Self, DerivationError> {
+ pub fn derive_priv<P: AsRef<[ChildNumber]>>(&self, path: P) -> Result<Self, DerivationError> {
self.derive_xpriv(path)
}
/// Derives an extended private key from a path.
///
/// The `path` argument can be both of type `DerivationPath` or `Vec<ChildNumber>`.
- pub fn derive_xpriv<P: AsRef<[ChildNumber]>>(
- &self,
- path: P,
- ) -> Result<Self, DerivationError> {
+ pub fn derive_xpriv<P: AsRef<[ChildNumber]>>(&self, path: P) -> Result<Self, DerivationError> {
let mut sk: Self = *self;
for cnum in path.as_ref() {
sk = sk.ckd_priv(*cnum)?;
@@ -777,10 +767,7 @@ impl Xpriv {
}
/// Private->Private child key derivation
- fn ckd_priv(
- &self,
- i: ChildNumber,
- ) -> Result<Self, DerivationError> {
+ fn ckd_priv(&self, i: ChildNumber) -> Result<Self, DerivationError> {
let mut engine = HmacEngine::<sha512::HashEngine>::new(&self.chain_code[..]);
match i {
ChildNumber::Normal { .. } => {
@@ -798,9 +785,10 @@ impl Xpriv {
engine.input(&u32::from(i).to_be_bytes());
let hmac: Hmac<sha512::Hash> = 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");
@@ -857,9 +845,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 {
@@ -870,9 +856,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 {
@@ -906,20 +890,14 @@ impl Xpub {
///
/// The `path` argument can be any type implementing `AsRef<ChildNumber>`, such as `DerivationPath`, for instance.
#[deprecated(since = "TBD", note = "use `derive_xpub()` instead")]
- pub fn derive_pub<P: AsRef<[ChildNumber]>>(
- &self,
- path: P,
- ) -> Result<Self, DerivationError> {
+ pub fn derive_pub<P: AsRef<[ChildNumber]>>(&self, path: P) -> Result<Self, DerivationError> {
self.derive_xpub(path)
}
/// Attempts to derive an extended public key from a path.
///
/// The `path` argument can be any type implementing `AsRef<ChildNumber>`, such as `DerivationPath`, for instance.
- pub fn derive_xpub<P: AsRef<[ChildNumber]>>(
- &self,
- path: P,
- ) -> Result<Self, DerivationError> {
+ pub fn derive_xpub<P: AsRef<[ChildNumber]>>(&self, path: P) -> Result<Self, DerivationError> {
let mut pk: Self = *self;
for cnum in path.as_ref() {
pk = pk.ckd_pub(*cnum)?
@@ -951,10 +929,7 @@ impl Xpub {
}
/// Public->Public child key derivation
- pub fn ckd_pub(
- &self,
- i: ChildNumber,
- ) -> Result<Self, DerivationError> {
+ pub fn ckd_pub(&self, i: ChildNumber) -> Result<Self, DerivationError> {
let (sk, chain_code) = self.ckd_pub_tweak(i)?;
let tweaked =
self.public_key.add_exp_tweak(&sk.into()).expect("cryptographically unreachable");
@@ -1310,10 +1285,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);
}
@@ -1328,10 +1300,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);
}
}
@@ -1392,7 +1361,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 ef954879..069fdbba 100644
--- a/bitcoin/src/blockdata/block.rs
+++ b/bitcoin/src/blockdata/block.rs
@@ -17,7 +17,7 @@ use crate::consensus::encode::{self, Decodable, Encodable, WriteExt as _};
use crate::merkle_tree::{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 _};
use crate::{internal_macros, BlockTime, Target, Weight, Work};
@@ -472,8 +472,7 @@ mod tests {
let block = decode.unwrap();
// should be also ok for a non-witness block as commitment is optional in that case
- let (witness_commitment_matches, witness_root) =
- block.check_witness_commitment();
+ let (witness_commitment_matches, witness_root) = block.check_witness_commitment();
assert!(witness_commitment_matches);
let (header, transactions) = block.into_parts();
@@ -521,8 +520,7 @@ mod tests {
assert!(decode.is_ok());
let block = decode.unwrap();
- let (witness_commitment_matches, witness_root) =
- block.check_witness_commitment();
+ let (witness_commitment_matches, witness_root) = block.check_witness_commitment();
assert!(witness_commitment_matches);
let (header, transactions) = block.into_parts();
diff --git a/bitcoin/src/blockdata/mod.rs b/bitcoin/src/blockdata/mod.rs
index bc18d858..9758dc2a 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 dd19edd1..31f1f660 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::crypto::{ecdsa, taproot};
use crate::prelude::{Borrow, BorrowMut};
@@ -422,14 +422,16 @@ impl BorrowMut<PushBytes> for PushBytesBuf {
impl AsRef<PushBytes> for ecdsa::SerializedSignature {
#[inline]
fn as_ref(&self) -> &PushBytes {
- <&PushBytes>::try_from(<Self as AsRef<[u8]>>::as_ref(self)).expect("max length 73 bytes is valid")
+ <&PushBytes>::try_from(<Self as AsRef<[u8]>>::as_ref(self))
+ .expect("max length 73 bytes is valid")
}
}
impl AsRef<PushBytes> for taproot::SerializedSignature {
#[inline]
fn as_ref(&self) -> &PushBytes {
- <&PushBytes>::try_from(<Self as AsRef<[u8]>>::as_ref(self)).expect("max length 65 bytes is valid")
+ <&PushBytes>::try_from(<Self as AsRef<[u8]>>::as_ref(self))
+ .expect("max length 65 bytes is valid")
}
}
diff --git a/bitcoin/src/blockdata/script/tests.rs b/bitcoin/src/blockdata/script/tests.rs
index bb5221ca..703c3cf3 100644
--- a/bitcoin/src/blockdata/script/tests.rs
+++ b/bitcoin/src/blockdata/script/tests.rs
@@ -399,13 +399,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 7ecb923d..4cee8811 100644
--- a/bitcoin/src/blockdata/script/witness_program.rs
+++ b/bitcoin/src/blockdata/script/witness_program.rs
@@ -84,9 +84,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 f779179d..61bd5513 100644
--- a/bitcoin/src/blockdata/transaction.rs
+++ b/bitcoin/src/blockdata/transaction.rs
@@ -686,10 +686,7 @@ impl Encodable for OutPoint {
}
impl Decodable for OutPoint {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- 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 f3d56cd1..baa50030 100644
--- a/bitcoin/src/consensus/encode.rs
+++ b/bitcoin/src/consensus/encode.rs
@@ -475,9 +475,7 @@ impl<T: Encodable + 'static> Encodable for Vec<T> {
impl<T: Decodable + 'static> Decodable for Vec<T> {
#[inline]
- fn consensus_decode_from_finite_reader<R: BufRead + ?Sized>(
- r: &mut R,
- ) -> Result<Self, Error> {
+ fn consensus_decode_from_finite_reader<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, Error> {
if TypeId::of::<T>() == TypeId::of::<u8>() {
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/ecdsa.rs b/bitcoin/src/crypto/ecdsa.rs
index 9aada52f..feec3552 100644
--- a/bitcoin/src/crypto/ecdsa.rs
+++ b/bitcoin/src/crypto/ecdsa.rs
@@ -121,9 +121,7 @@ impl SerializedSignature {
///
/// In other words this deserializes the `SerializedSignature`.
#[inline]
- pub fn to_signature(self) -> Result<Signature, DecodeError> {
- Signature::from_slice(&self)
- }
+ pub fn to_signature(self) -> Result<Signature, DecodeError> { Signature::from_slice(&self) }
/// Returns the length of the serialized signature data.
#[inline]
@@ -184,9 +182,7 @@ impl PartialEq<SerializedSignature> for [u8] {
}
impl PartialOrd for SerializedSignature {
- fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
- Some(self.cmp(other))
- }
+ fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { Some(self.cmp(other)) }
}
impl Ord for SerializedSignature {
diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs
index 30e0b87b..65ac68db 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(
@@ -450,9 +446,7 @@ impl CompressedPublicKey {
}
/// Computes the public key as supposed to be used with this secret.
- pub fn from_private_key(
- sk: PrivateKey,
- ) -> Result<Self, UncompressedPublicKeyError> {
+ pub fn from_private_key(sk: PrivateKey) -> Result<Self, UncompressedPublicKeyError> {
sk.public_key().try_into()
}
@@ -899,10 +893,7 @@ pub trait TapTweak {
/// # Returns
///
/// The tweaked key and its parity.
- fn tap_tweak(
- self,
- merkle_root: Option<TapNodeHash>,
- ) -> Self::TweakedAux;
+ fn tap_tweak(self, merkle_root: Option<TapNodeHash>) -> Self::TweakedAux;
/// Directly converts an [`UntweakedPublicKey`] to a [`TweakedPublicKey`].
///
@@ -928,10 +919,7 @@ impl TapTweak for UntweakedPublicKey {
/// # Returns
///
/// The tweaked key and its parity.
- fn tap_tweak(
- self,
- merkle_root: Option<TapNodeHash>,
- ) -> (TweakedPublicKey, Parity) {
+ fn tap_tweak(self, merkle_root: Option<TapNodeHash>) -> (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");
@@ -956,10 +944,7 @@ impl TapTweak for UntweakedKeypair {
/// # Returns
///
/// The tweaked keypair.
- fn tap_tweak(
- self,
- merkle_root: Option<TapNodeHash>,
- ) -> TweakedKeypair {
+ fn tap_tweak(self, merkle_root: Option<TapNodeHash>) -> 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");
@@ -1814,7 +1799,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
@@ -1825,7 +1811,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 8a91607e..5b300515 100644
--- a/bitcoin/src/crypto/sighash.rs
+++ b/bitcoin/src/crypto/sighash.rs
@@ -1424,10 +1424,8 @@ impl<E> EncodeSigningDataResult<E> {
{
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/crypto/taproot.rs b/bitcoin/src/crypto/taproot.rs
index ae8d6e3f..c1e1abf9 100644
--- a/bitcoin/src/crypto/taproot.rs
+++ b/bitcoin/src/crypto/taproot.rs
@@ -6,8 +6,8 @@
use core::borrow::Borrow;
use core::convert::Infallible;
-use core::ops::Deref;
use core::fmt;
+use core::ops::Deref;
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
@@ -15,11 +15,10 @@ use internals::array::ArrayExt;
use internals::{impl_to_hex_from_lower_hex, write_err};
use io::Write;
+pub use self::into_iter::IntoIter;
use crate::prelude::{DisplayHex, Vec};
use crate::sighash::{InvalidSighashTypeError, TapSighashType};
-pub use self::into_iter::IntoIter;
-
const MAX_LEN: usize = 65; // 64 for sig, 1B sighash flag
/// A BIP-0340-0341 serialized Taproot signature with the corresponding hash type.
@@ -187,9 +186,7 @@ impl PartialEq<SerializedSignature> for [u8] {
}
impl PartialOrd for SerializedSignature {
- fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
- Some(self.cmp(other))
- }
+ fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> { Some(self.cmp(other)) }
}
impl Ord for SerializedSignature {
@@ -269,7 +266,6 @@ impl<'a> TryFrom<&'a SerializedSignature> for Signature {
}
}
-
/// Separate mod to prevent outside code from accidentally breaking invariants.
mod into_iter {
use super::*;
diff --git a/bitcoin/src/hash_types.rs b/bitcoin/src/hash_types.rs
index 9f63e8b0..00aac645 100644
--- a/bitcoin/src/hash_types.rs
+++ b/bitcoin/src/hash_types.rs
@@ -90,6 +90,5 @@ mod tests {
XKeyIdentifier::from_byte_array(DUMMY20).to_string(),
"b472a266d0bd89c13706a4132ccfb16f7c3b9fcb",
);
-
}
}
diff --git a/bitcoin/src/internal_macros.rs b/bitcoin/src/internal_macros.rs
index 34d3e38e..190a2b71 100644
--- a/bitcoin/src/internal_macros.rs
+++ b/bitcoin/src/internal_macros.rs
@@ -259,5 +259,3 @@ macro_rules! define_extension_trait {
};
}
pub(crate) use define_extension_trait;
-
-
diff --git a/bitcoin/src/lib.rs b/bitcoin/src/lib.rs
index 06b3c405..ed9cb784 100644
--- a/bitcoin/src/lib.rs
+++ b/bitcoin/src/lib.rs
@@ -138,18 +138,20 @@ pub mod taproot;
#[doc(inline)]
pub use primitives::{
block::{
- Block, BlockHash, Checked as BlockChecked, Header as BlockHeader,
- Unchecked as BlockUnchecked, Validation as BlockValidation, Version as BlockVersion,
- WitnessCommitment, compute_merkle_root, compute_witness_root, InvalidBlockError,
+ compute_merkle_root, compute_witness_root, Block, BlockHash, Checked as BlockChecked,
+ Header as BlockHeader, InvalidBlockError, Unchecked as BlockUnchecked,
+ Validation as BlockValidation, Version as BlockVersion, WitnessCommitment,
},
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 04223129..7b04f6fd 100644
--- a/bitcoin/src/merkle_tree/block.rs
+++ b/bitcoin/src/merkle_tree/block.rs
@@ -127,10 +127,7 @@ impl Encodable for MerkleBlock {
impl Decodable for MerkleBlock {
fn consensus_decode<R: BufRead + ?Sized>(r: &mut R) -> Result<Self, encode::Error> {
- 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 e38c87dd..3d19185e 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<EcdsaSighashType> 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<TapSighashType> 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 79374e71..1da03944 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<K>(
- &mut self,
- k: &K,
- ) -> Result<SigningKeysMap, (SigningKeysMap, SigningErrors)>
+ pub fn sign<K>(&mut self, k: &K) -> Result<SigningKeysMap, (SigningKeysMap, SigningErrors)>
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(all(feature = "rand", feature = "std"))]
- let signature = secp256k1::schnorr::sign(&sighash.to_byte_array(), &key_pair);
- #[cfg(not(all(feature = "rand", feature = "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(all(feature = "rand", feature = "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<Option<PrivateKey>, Self::Error>;
+ fn get_key(&self, key_request: &KeyRequest) -> Result<Option<PrivateKey>, Self::Error>;
}
impl GetKey for Xpriv {
type Error = GetKeyError;
- fn get_key(
- &self,
- key_request: &KeyRequest,
- ) -> Result<Option<PrivateKey>, Self::Error> {
+ fn get_key(&self, key_request: &KeyRequest) -> Result<Option<PrivateKey>, Self::Error> {
match key_request {
KeyRequest::Pubkey(_) => Err(GetKeyError::NotSupported),
KeyRequest::XOnlyPubkey(_) => Err(GetKeyError::NotSupported),
@@ -1307,12 +1297,8 @@ mod tests {
use hex_lit::hex;
#[cfg(all(feature = "rand", feature = "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::*;
@@ -2404,14 +2390,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 1e8760b0..57bca879 100644
--- a/bitcoin/src/sign_message.rs
+++ b/bitcoin/src/sign_message.rs
@@ -72,9 +72,7 @@ mod message_signing {
}
impl From<secp256k1::Error> 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.
@@ -192,9 +190,7 @@ mod message_signing {
impl core::str::FromStr for MessageSignature {
type Err = MessageSignatureError;
- fn from_str(s: &str) -> Result<Self, MessageSignatureError> {
- Self::from_base64(s)
- }
+ fn from_str(s: &str) -> Result<Self, MessageSignatureError> { Self::from_base64(s) }
}
}
}
@@ -211,10 +207,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);
@@ -240,6 +233,7 @@ mod tests {
#[cfg(all(feature = "secp-recovery", feature = "base64", feature = "rand", feature = "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 6e3c63a6..32835a4e 100644
--- a/bitcoin/src/taproot/mod.rs
+++ b/bitcoin/src/taproot/mod.rs
@@ -141,9 +141,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`].
///
@@ -312,10 +310,7 @@ impl TaprootSpendInfo {
///
/// This is useful when you want to manually build a Taproot tree without using
/// [`TaprootBuilder`].
- pub fn from_node_info<K: Into<UntweakedPublicKey>>(
- internal_key: K,
- node: NodeInfo,
- ) -> Self {
+ pub fn from_node_info<K: Into<UntweakedPublicKey>>(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);
@@ -423,9 +418,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.
@@ -566,9 +559,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))
}
@@ -1303,9 +1294,7 @@ impl<Branch: AsRef<TaprootMerkleBranch> + ?Sized> ControlBlock<Branch> {
pub struct FutureLeafVersion(u8);
impl FutureLeafVersion {
- pub(self) fn from_consensus(
- version: u8,
- ) -> Result<Self, InvalidTaprootLeafVersionError> {
+ pub(self) fn from_consensus(version: u8) -> Result<Self, InvalidTaprootLeafVersionError> {
match version {
TAPROOT_LEAF_TAPSCRIPT => unreachable!(
"FutureLeafVersion::from_consensus should never be called for 0xC0 value"
@@ -1755,20 +1744,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::<XOnlyPublicKey>().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]
@@ -1832,8 +1814,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:
@@ -1869,10 +1850,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))
}
}
@@ -1941,10 +1920,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/tests/psbt-sign-taproot.rs b/bitcoin/tests/psbt-sign-taproot.rs
index bd21a112..294d9276 100644
--- a/bitcoin/tests/psbt-sign-taproot.rs
+++ b/bitcoin/tests/psbt-sign-taproot.rs
@@ -26,10 +26,7 @@ fn psbt_sign_taproot() {
impl GetKey for Keystore {
type Error = SignError;
- fn get_key(
- &self,
- key_request: &KeyRequest,
- ) -> Result<Option<PrivateKey>, Self::Error> {
+ fn get_key(&self, key_request: &KeyRequest) -> Result<Option<PrivateKey>, Self::Error> {
match key_request {
KeyRequest::Bip32((mfp, _)) =>
if *mfp == self.mfp {
@@ -63,8 +60,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 0e9d0a07..19f986ea 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<A, B> Decoder for Decoder2<A, B>
@@ -1217,7 +1219,7 @@ mod tests {
let result = decoder.end().unwrap();
assert_eq!(result.len(), total_len);
- assert_eq!(result[total_len - 1 ], 0xDD);
+ assert_eq!(result[total_len - 1], 0xDD);
}
#[cfg(feature = "alloc")]
@@ -1375,7 +1377,7 @@ mod tests {
let Test(result) = decoder.end().unwrap();
assert_eq!(result.len(), total_len);
- assert_eq!(result[total_len - 1 ], Inner(0xDD));
+ assert_eq!(result[total_len - 1], Inner(0xDD));
}
#[cfg(feature = "alloc")]
diff --git a/consensus_encoding/src/encode/encoders.rs b/consensus_encoding/src/encode/encoders.rs
index 1d20bd2c..735e5929 100644
--- a/consensus_encoding/src/encode/encoders.rs
+++ b/consensus_encoding/src/encode/encoders.rs
@@ -599,7 +599,10 @@ mod tests {
// This test only runs on systems with >= 64 bit usize.
if core::mem::size_of::<usize>() >= 8 {
let mut e = CompactSizeEncoder::new(0x0000_F0F0_F0F0_F0E0u64 as usize);
- assert_eq!(e.current_chunk(), &[0xFF, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00][..]);
+ assert_eq!(
+ e.current_chunk(),
+ &[0xFF, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00][..]
+ );
assert!(!e.advance());
assert!(e.current_chunk().is_empty());
}
@@ -608,7 +611,10 @@ mod tests {
// This test only runs on systems with > 64 bit usize.
if core::mem::size_of::<usize>() > 8 {
let mut e = CompactSizeEncoder::new((u128::from(u64::MAX) + 5) as usize);
- assert_eq!(e.current_chunk(), &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF][..]);
+ assert_eq!(
+ e.current_chunk(),
+ &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF][..]
+ );
assert!(!e.advance());
assert!(e.current_chunk().is_empty());
}
diff --git a/consensus_encoding/src/encode/mod.rs b/consensus_encoding/src/encode/mod.rs
index aef04e20..e5c7f98b 100644
--- a/consensus_encoding/src/encode/mod.rs
+++ b/consensus_encoding/src/encode/mod.rs
@@ -72,9 +72,7 @@ pub struct EncodableByteIter<'s, T: Encodable + 's> {
impl<'s, T: Encodable + 's> EncodableByteIter<'s, T> {
/// Constructs a new byte iterator around a provided encodable.
- pub fn new(encodable: &'s T) -> Self {
- Self { enc: encodable.encoder(), position: 0 }
- }
+ pub fn new(encodable: &'s T) -> Self { Self { enc: encodable.encoder(), position: 0 } }
}
impl<'s, T: Encodable + 's> Iterator for EncodableByteIter<'s, T> {
diff --git a/consensus_encoding/src/lib.rs b/consensus_encoding/src/lib.rs
index 965636a8..d47db981 100644
--- a/consensus_encoding/src/lib.rs
+++ b/consensus_encoding/src/lib.rs
@@ -42,4 +42,4 @@ pub use self::encode::encoders::{
ArrayEncoder, BytesEncoder, CompactSizeEncoder, Encoder2, Encoder3, Encoder4, Encoder6,
SliceEncoder,
};
-pub use self::encode::{Encodable, Encoder, EncodableByteIter};
+pub use self::encode::{Encodable, EncodableByteIter, Encoder};
diff --git a/consensus_encoding/tests/iter.rs b/consensus_encoding/tests/iter.rs
index 1e105aa2..5c8c114e 100644
--- a/consensus_encoding/tests/iter.rs
+++ b/consensus_encoding/tests/iter.rs
@@ -1,7 +1,6 @@
+use bitcoin_consensus_encoding::{ArrayEncoder, Encodable, EncodableByteIter, Encoder2};
use hex::BytesToHexIter;
-use bitcoin_consensus_encoding::{Encodable, ArrayEncoder, Encoder2, EncodableByteIter};
-
struct TestArray<const N: usize>([u8; N]);
impl<const N: usize> Encodable for TestArray<N> {
@@ -21,7 +20,8 @@ impl<const N: usize, const M: usize> Encodable for TestCatArray<N, M> {
where
Self: 's;
- fn encoder(&self) -> Self::Encoder<'_> { Encoder2::new(
+ fn encoder(&self) -> Self::Encoder<'_> {
+ Encoder2::new(
ArrayEncoder::without_length_prefix(self.0),
ArrayEncoder::without_length_prefix(self.1),
)
diff --git a/fuzz/fuzz_targets/units/standard_checks.rs b/fuzz/fuzz_targets/units/standard_checks.rs
index 933ab633..24b1c917 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 b1939fd6..dc96379f 100644
--- a/hashes/src/hmac/mod.rs
+++ b/hashes/src/hmac/mod.rs
@@ -82,9 +82,7 @@ impl<T: HashEngine> HmacEngine<T> {
}
/// 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<T: HashEngine> HashEngine for HmacEngine<T> {
diff --git a/io/src/lib.rs b/io/src/lib.rs
index 1fca04d3..15201bca 100644
--- a/io/src/lib.rs
+++ b/io/src/lib.rs
@@ -45,10 +45,10 @@ use encoding::{Decodable, Decoder, 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<T> = core::result::Result<T, Error>;
@@ -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<Self>
- 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.
///
@@ -449,7 +452,9 @@ where
///
/// Returns [`ReadError::Decode`] if the decoder encounters an error while parsing
/// the data, or [`ReadError::Io`] if an I/O error occurs while reading.
-pub fn decode_from_read<T, R>(mut reader: R) -> core::result::Result<T, ReadError<<T::Decoder as Decoder>::Error>>
+pub fn decode_from_read<T, R>(
+ mut reader: R,
+) -> core::result::Result<T, ReadError<<T::Decoder as Decoder>::Error>>
where
T: Decodable,
R: BufRead,
@@ -798,7 +803,9 @@ mod tests {
self.inner.push_bytes(bytes)
}
- fn end(self) -> core::result::Result<Self::Output, Self::Error> { self.inner.end().map(TestArray) }
+ fn end(self) -> core::result::Result<Self::Output, Self::Error> {
+ self.inner.end().map(TestArray)
+ }
fn read_limit(&self) -> usize { self.inner.read_limit() }
}
diff --git a/p2p/src/address.rs b/p2p/src/address.rs
index 945e02d4..f04515b4 100644
--- a/p2p/src/address.rs
+++ b/p2p/src/address.rs
@@ -206,15 +206,11 @@ impl From<IpAddr> for AddrV2 {
}
impl From<Ipv4Addr> for AddrV2 {
- fn from(addr: Ipv4Addr) -> Self {
- Self::Ipv4(addr)
- }
+ fn from(addr: Ipv4Addr) -> Self { Self::Ipv4(addr) }
}
impl From<Ipv6Addr> for AddrV2 {
- fn from(addr: Ipv6Addr) -> Self {
- Self::Ipv6(addr)
- }
+ fn from(addr: Ipv6Addr) -> Self { Self::Ipv6(addr) }
}
impl Encodable for AddrV2 {
diff --git a/p2p/src/bip152.rs b/p2p/src/bip152.rs
index 171ce047..a702559a 100644
--- a/p2p/src/bip152.rs
+++ b/p2p/src/bip152.rs
@@ -12,15 +12,14 @@ use std::error;
#[cfg(feature = "arbitrary")]
use arbitrary::{Arbitrary, Unstructured};
+use bitcoin::consensus::encode::{self, Decodable, Encodable, ReadExt, WriteExt};
+use bitcoin::transaction::TxIdentifier;
+use bitcoin::{block, Block, BlockChecked, BlockHash, Transaction};
use hashes::{sha256, siphash24};
use internals::array::ArrayExt as _;
use internals::ToU64 as _;
use io::{BufRead, Write};
-use bitcoin::consensus::encode::{self, Decodable, Encodable, ReadExt, WriteExt};
-use bitcoin::transaction::TxIdentifier;
-use bitcoin::{block, Block, BlockChecked, BlockHash, Transaction};
-
/// A BIP-0152 error
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
@@ -350,12 +349,18 @@ impl Decodable for BlockTransactionsRequest {
let differential = r.read_compact_size()?;
last_index = match last_index.checked_add(differential) {
Some(i) => i,
- None => return Err(crate::consensus::parse_failed_error("block index overflow")),
+ None =>
+ return Err(crate::consensus::parse_failed_error(
+ "block index overflow",
+ )),
};
indexes.push(last_index);
last_index = match last_index.checked_add(1) {
Some(i) => i,
- None => return Err(crate::consensus::parse_failed_error("block index overflow")),
+ None =>
+ return Err(crate::consensus::parse_failed_error(
+ "block index overflow",
+ )),
};
}
indexes
@@ -422,9 +427,7 @@ impl BlockTransactions {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for ShortId {
- fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(Self(u.arbitrary()?))
- }
+ fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { Ok(Self(u.arbitrary()?)) }
}
#[cfg(feature = "arbitrary")]
@@ -449,29 +452,21 @@ impl<'a> Arbitrary<'a> for HeaderAndShortIds {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for BlockTransactions {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(Self {
- block_hash: u.arbitrary()?,
- transactions: Vec::<Transaction>::arbitrary(u)?,
- })
+ Ok(Self { block_hash: u.arbitrary()?, transactions: Vec::<Transaction>::arbitrary(u)? })
}
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for BlockTransactionsRequest {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(Self {
- block_hash: u.arbitrary()?,
- indexes: Vec::<u64>::arbitrary(u)?,
- })
+ Ok(Self { block_hash: u.arbitrary()?, indexes: Vec::<u64>::arbitrary(u)? })
}
}
#[cfg(test)]
mod test {
use alloc::vec;
- use hex::FromHex;
- use super::*;
use bitcoin::consensus::encode::{deserialize, serialize};
use bitcoin::locktime::absolute;
use bitcoin::merkle_tree::TxMerkleNode;
@@ -480,6 +475,9 @@ mod test {
transaction, Amount, BlockChecked, BlockTime, CompactTarget, OutPoint, ScriptPubKeyBuf,
ScriptSigBuf, Sequence, TxIn, TxOut, Txid, Witness,
};
+ use hex::FromHex;
+
+ use super::*;
fn dummy_tx(nonce: &[u8]) -> Transaction {
let dummy_txid = Txid::from_byte_array(hashes::sha256::Hash::hash(nonce).to_byte_array());
diff --git a/p2p/src/lib.rs b/p2p/src/lib.rs
index 3a2918aa..c605bead 100644
--- a/p2p/src/lib.rs
+++ b/p2p/src/lib.rs
@@ -466,16 +466,12 @@ impl std::error::Error for UnknownNetworkError {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for ProtocolVersion {
- fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(Self(u.arbitrary()?))
- }
+ fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { Ok(Self(u.arbitrary()?)) }
}
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for ServiceFlags {
- fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(Self(u.arbitrary()?))
- }
+ fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { Ok(Self(u.arbitrary()?)) }
}
#[cfg(feature = "arbitrary")]
diff --git a/p2p/src/message.rs b/p2p/src/message.rs
index 84be6516..e0bf2f0b 100644
--- a/p2p/src/message.rs
+++ b/p2p/src/message.rs
@@ -1591,9 +1591,7 @@ impl<'a> Arbitrary<'a> for CommandString {
#[cfg(feature = "arbitrary")]
impl<'a> Arbitrary<'a> for HeadersMessage {
- fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
- Ok(Self(u.arbitrary()?))
- }
+ fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> { Ok(Self(u.arbitrary()?)) }
}
#[cfg(feature = "arbitrary")]
@@ -1636,10 +1634,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::<u8>::arbitrary(u)?,
- }),
+ _ => Ok(Self::Unknown { command: u.arbitrary()?, payload: Vec::<u8>::arbitrary(u)? }),
}
}
}
@@ -1670,7 +1665,8 @@ mod test {
use crate::message_bloom::{BloomFlags, FilterAdd, FilterLoad};
use crate::message_compact_blocks::{GetBlockTxn, SendCmpct};
use crate::message_filter::{
- CFCheckpt, CFHeaders, CFilter, FilterHash, FilterHeader, GetCFCheckpt, GetCFHeaders, GetCFilters,
+ CFCheckpt, CFHeaders, CFilter, FilterHash, FilterHeader, GetCFCheckpt, GetCFHeaders,
+ GetCFilters,
};
use crate::message_network::{Alert, Reject, RejectReason, VersionMessage};
use crate::{ProtocolVersion, ServiceFlags};
diff --git a/p2p/src/message_network.rs b/p2p/src/message_network.rs
index b5fa1154..58a43d67 100644
--- a/p2p/src/message_network.rs
+++ b/p2p/src/message_network.rs
@@ -334,11 +334,7 @@ impl_vec_wrapper!(Alert, Vec<u8>);
impl<'a> Arbitrary<'a> for ClientSoftwareVersion {
fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result<Self> {
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 8bb15166..3abbb9d4 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;
@@ -146,13 +148,17 @@ impl Block<Unchecked> {
}
/// Computes the witness commitment for a list of transactions.
- pub fn compute_witness_commitment(&self, witness_reserved_value: &[u8]) -> Option<(WitnessMerkleNode, WitnessCommitment)> {
+ pub fn compute_witness_commitment(
+ &self,
+ witness_reserved_value: &[u8],
+ ) -> Option<(WitnessMerkleNode, WitnessCommitment)> {
compute_witness_root(&self.transactions).map(|witness_root| {
let mut encoder = sha256d::Hash::engine();
encoder = hashes::encode_to_engine(&witness_root, encoder);
encoder.input(witness_reserved_value);
- let witness_commitment =
- WitnessCommitment::from_byte_array(sha256d::Hash::from_engine(encoder).to_byte_array());
+ let witness_commitment = WitnessCommitment::from_byte_array(
+ sha256d::Hash::from_engine(encoder).to_byte_array(),
+ );
(witness_root, witness_commitment)
})
}
@@ -314,10 +320,7 @@ impl Decoder for BlockDecoder {
impl Decodable for Block {
type Decoder = BlockDecoder;
fn decoder() -> Self::Decoder {
- BlockDecoder(Decoder2::new(
- Header::decoder(),
- VecDecoder::<Transaction>::new(),
- ))
+ BlockDecoder(Decoder2::new(Header::decoder(), VecDecoder::<Transaction>::new()))
}
}
@@ -1016,7 +1019,10 @@ mod tests {
sequence: units::Sequence::ENABLE_LOCKTIME_AND_RBF,
witness: crate::Witness::new(),
}],
- outputs: vec![crate::TxOut { amount: units::Amount::ONE_BTC, script_pubkey: crate::ScriptPubKeyBuf::new() }],
+ outputs: vec![crate::TxOut {
+ amount: units::Amount::ONE_BTC,
+ script_pubkey: crate::ScriptPubKeyBuf::new(),
+ }],
};
let transactions = vec![non_coinbase_tx];
@@ -1166,14 +1172,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
@@ -1207,7 +1211,8 @@ mod tests {
let magic = [0x6a, 0x24, 0xaa, 0x21, 0xa9, 0xed];
let mut pubkey_bytes = [0; 38];
pubkey_bytes[0..6].copy_from_slice(&magic);
- let witness_commitment = WitnessCommitment::from_byte_array(pubkey_bytes[6..38].try_into().unwrap());
+ let witness_commitment =
+ WitnessCommitment::from_byte_array(pubkey_bytes[6..38].try_into().unwrap());
let commitment_script = crate::script::ScriptBuf::from_bytes(pubkey_bytes.to_vec());
// Create a coinbase transaction with witness commitment
@@ -1215,7 +1220,10 @@ mod tests {
version: crate::transaction::Version::ONE,
lock_time: crate::absolute::LockTime::ZERO,
inputs: vec![crate::TxIn::EMPTY_COINBASE],
- outputs: vec![crate::TxOut { amount: units::Amount::MIN, script_pubkey: commitment_script }],
+ outputs: vec![crate::TxOut {
+ amount: units::Amount::MIN,
+ script_pubkey: commitment_script,
+ }],
};
// Test if the witness commitment is extracted properly
@@ -1264,14 +1272,17 @@ mod tests {
txin.witness.push(witness_bytes);
// pubkey bytes must match the magic bytes followed by the hash of the witness bytes.
- let script_pubkey_bytes: [u8; 38] = hex_unstable::FromHex::from_hex("6a24aa21a9ed3cde9e0b9f4ad8f9d0fd66d6b9326cd68597c04fa22ab64b8e455f08d2e31ceb").unwrap();
+ let script_pubkey_bytes: [u8; 38] = hex_unstable::FromHex::from_hex(
+ "6a24aa21a9ed3cde9e0b9f4ad8f9d0fd66d6b9326cd68597c04fa22ab64b8e455f08d2e31ceb",
+ )
+ .unwrap();
let tx1 = Transaction {
version: crate::transaction::Version::ONE,
lock_time: crate::absolute::LockTime::ZERO,
inputs: vec![txin],
outputs: vec![crate::TxOut {
amount: units::Amount::MIN,
- script_pubkey: crate::script::ScriptBuf::from_bytes(script_pubkey_bytes.to_vec())
+ script_pubkey: crate::script::ScriptBuf::from_bytes(script_pubkey_bytes.to_vec()),
}],
};
@@ -1281,14 +1292,17 @@ mod tests {
inputs: vec![crate::TxIn::EMPTY_COINBASE],
outputs: vec![crate::TxOut {
amount: units::Amount::MIN,
- script_pubkey: crate::script::ScriptBuf::new()
+ script_pubkey: crate::script::ScriptBuf::new(),
}],
};
let block = Block::new_unchecked(dummy_header(), vec![tx1, tx2]);
let result = block.check_witness_commitment();
- let exp_bytes: [u8; 32] = hex_unstable::FromHex::from_hex("fb848679079938b249a12f14b72d56aeb116df79254e17cdf72b46523bcb49db").unwrap();
+ let exp_bytes: [u8; 32] = hex_unstable::FromHex::from_hex(
+ "fb848679079938b249a12f14b72d56aeb116df79254e17cdf72b46523bcb49db",
+ )
+ .unwrap();
let expected = WitnessMerkleNode::from_byte_array(exp_bytes);
assert_eq!(result, (true, Some(expected)));
}
@@ -1302,14 +1316,17 @@ mod tests {
txin.witness.push(witness_bytes);
txin.witness.push([12u8]);
- let script_pubkey_bytes: [u8; 38] = hex_unstable::FromHex::from_hex("6a24aa21a9ed3cde9e0b9f4ad8f9d0fd66d6b9326cd68597c04fa22ab64b8e455f08d2e31ceb").unwrap();
+ let script_pubkey_bytes: [u8; 38] = hex_unstable::FromHex::from_hex(
+ "6a24aa21a9ed3cde9e0b9f4ad8f9d0fd66d6b9326cd68597c04fa22ab64b8e455f08d2e31ceb",
+ )
+ .unwrap();
let tx1 = Transaction {
version: crate::transaction::Version::ONE,
lock_time: crate::absolute::LockTime::ZERO,
inputs: vec![txin],
outputs: vec![crate::TxOut {
amount: units::Amount::MIN,
- script_pubkey: crate::script::ScriptBuf::from_bytes(script_pubkey_bytes.to_vec())
+ script_pubkey: crate::script::ScriptBuf::from_bytes(script_pubkey_bytes.to_vec()),
}],
};
@@ -1319,7 +1336,7 @@ mod tests {
inputs: vec![crate::TxIn::EMPTY_COINBASE],
outputs: vec![crate::TxOut {
amount: units::Amount::MIN,
- script_pubkey: crate::script::ScriptBuf::new()
+ script_pubkey: crate::script::ScriptBuf::new(),
}],
};
diff --git a/primitives/src/hash_types/transaction_merkle_node.rs b/primitives/src/hash_types/transaction_merkle_node.rs
index 624b6922..8f962b18 100644
--- a/primitives/src/hash_types/transaction_merkle_node.rs
+++ b/primitives/src/hash_types/transaction_merkle_node.rs
@@ -43,7 +43,9 @@ impl TxMerkleNode {
///
/// Unless you are certain your transaction list is nonempty and has no duplicates,
/// you should not unwrap the `Option` returned by this method!
- pub fn calculate_root<I: Iterator<Item = Txid>>(iter: I) -> Option<Self> { MerkleNode::calculate_root(iter) }
+ pub fn calculate_root<I: Iterator<Item = Txid>>(iter: I) -> Option<Self> {
+ MerkleNode::calculate_root(iter)
+ }
}
encoding::encoder_newtype! {
diff --git a/primitives/src/hash_types/witness_merkle_node.rs b/primitives/src/hash_types/witness_merkle_node.rs
index b57af827..4217bb45 100644
--- a/primitives/src/hash_types/witness_merkle_node.rs
+++ b/primitives/src/hash_types/witness_merkle_node.rs
@@ -43,7 +43,9 @@ impl WitnessMerkleNode {
///
/// Unless you are certain your transaction list is nonempty and has no duplicates,
/// you should not unwrap the `Option` returned by this method!
- pub fn calculate_root<I: Iterator<Item = Wtxid>>(iter: I) -> Option<Self> { MerkleNode::calculate_root(iter) }
+ pub fn calculate_root<I: Iterator<Item = Wtxid>>(iter: I) -> Option<Self> {
+ MerkleNode::calculate_root(iter)
+ }
}
encoding::encoder_newtype! {
@@ -54,7 +56,9 @@ encoding::encoder_newtype! {
impl encoding::Encodable for WitnessMerkleNode {
type Encoder<'e> = WitnessMerkleNodeEncoder;
fn encoder(&self) -> Self::Encoder<'_> {
- WitnessMerkleNodeEncoder(encoding::ArrayEncoder::without_length_prefix(self.to_byte_array()))
+ WitnessMerkleNodeEncoder(encoding::ArrayEncoder::without_length_prefix(
+ self.to_byte_array(),
+ ))
}
}
diff --git a/primitives/src/lib.rs b/primitives/src/lib.rs
index 31011c06..f550eae4 100644
--- a/primitives/src/lib.rs
+++ b/primitives/src/lib.rs
@@ -18,7 +18,7 @@
#![warn(deprecated_in_future)]
#![doc(test(attr(warn(unused))))]
// Package-specific lint overrides.
-#![allow(clippy::missing_errors_doc)] // TODO: Write errors section in docs.
+#![allow(clippy::missing_errors_doc)] // TODO: Write errors section in docs.
#[cfg(feature = "alloc")]
extern crate alloc;
diff --git a/primitives/src/merkle_tree.rs b/primitives/src/merkle_tree.rs
index 468e7f26..49ac63c8 100644
--- a/primitives/src/merkle_tree.rs
+++ b/primitives/src/merkle_tree.rs
@@ -11,16 +11,15 @@
// C'est la vie.
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
+
+use hashes::{sha256d, HashEngine};
#[cfg(not(feature = "alloc"))]
use internals::array_vec::ArrayVec;
-use hashes::{HashEngine, sha256d};
-
-use crate::hash_types::{Txid, Wtxid};
-use crate::transaction::TxIdentifier;
-
#[doc(inline)]
pub use crate::hash_types::{TxMerkleNode, TxMerkleNodeEncoder, WitnessMerkleNode};
+use crate::hash_types::{Txid, Wtxid};
+use crate::transaction::TxIdentifier;
/// A node in a Merkle tree of transactions or witness data within a block.
///
@@ -64,7 +63,9 @@ pub(crate) trait MerkleNode: Copy + PartialEq {
for (mut n, leaf) in iter.enumerate() {
#[cfg(not(feature = "alloc"))]
// This is the only time that the stack actually grows, rather than being combined.
- if stack.len() == 15 { return None; }
+ if stack.len() == 15 {
+ return None;
+ }
stack.push((0, Self::from_leaf(leaf)));
while n & 1 == 1 {
@@ -180,7 +181,10 @@ mod tests {
#[test]
fn tx_merkle_node_empty() {
- assert!(TxMerkleNode::calculate_root([].into_iter()).is_none(), "Empty iterator should return None");
+ assert!(
+ TxMerkleNode::calculate_root([].into_iter()).is_none(),
+ "Empty iterator should return None"
+ );
}
#[test]
@@ -206,7 +210,7 @@ mod tests {
let expected = subtree_ab.combine(&subtree_cd);
let root = TxMerkleNode::calculate_root(
- [leaf1, leaf2, leaf3, leaf4, leaf5, leaf6, leaf7].into_iter()
+ [leaf1, leaf2, leaf3, leaf4, leaf5, leaf6, leaf7].into_iter(),
);
assert_eq!(root, Some(expected));
}
@@ -216,29 +220,21 @@ mod tests {
fn tx_merkle_node_balanced_multi_level_tree() {
use alloc::vec::Vec;
- let leaves: Vec<_> = (0..16)
- .map(|i| Txid::from_byte_array([i; 32]))
- .collect();
+ let leaves: Vec<_> = (0..16).map(|i| Txid::from_byte_array([i; 32])).collect();
// Create nodes for the txids.
- let mut level = leaves
- .iter()
- .map(|l| TxMerkleNode::from_leaf(*l))
- .collect::<Vec<_>>();
+ let mut level = leaves.iter().map(|l| TxMerkleNode::from_leaf(*l)).collect::<Vec<_>>();
// Combine the leaves into a tree, ordered from left-to-right in the initial vector.
while level.len() > 1 {
- level = level
- .chunks(2)
- .map(|chunk| chunk[0].combine(&chunk[1]))
- .collect();
+ level = level.chunks(2).map(|chunk| chunk[0].combine(&chunk[1])).collect();
}
// Take the final node, which should be the root of the full tree.
let expected = level.pop().unwrap();
let root = TxMerkleNode::calculate_root(leaves.into_iter());
- assert_eq!( root, Some(expected) );
+ assert_eq!(root, Some(expected));
}
#[test]
diff --git a/primitives/src/transaction.rs b/primitives/src/transaction.rs
index 370c60fd..a796e5ce 100644
--- a/primitives/src/transaction.rs
+++ b/primitives/src/transaction.rs
@@ -25,9 +25,9 @@ use encoding::{
};
#[cfg(feature = "alloc")]
use hashes::sha256d;
+use internals::array::ArrayExt as _;
#[cfg(feature = "alloc")]
use internals::compact_size;
-use internals::array::ArrayExt as _;
use internals::write_err;
#[cfg(feature = "serde")]
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
@@ -382,7 +382,9 @@ pub struct TransactionDecoder {
#[cfg(feature = "alloc")]
impl TransactionDecoder {
/// Constructs a new [`TransactionDecoder`].
- pub const fn new() -> Self { Self { state: TransactionDecoderState::Version(VersionDecoder::new()) } }
+ pub const fn new() -> Self {
+ Self { state: TransactionDecoderState::Version(VersionDecoder::new()) }
+ }
}
#[cfg(feature = "alloc")]
diff --git a/primitives/tests/api.rs b/primitives/tests/api.rs
index a14e67f6..379b1860 100644
--- a/primitives/tests/api.rs
+++ b/primitives/tests/api.rs
@@ -211,7 +211,9 @@ fn api_can_use_units_modules_from_crate_root() {
#[test]
fn api_can_use_units_types_from_crate_root() {
- use bitcoin_primitives::{Amount, BlockHeight, BlockHeightInterval, FeeRate, SignedAmount, Weight};
+ use bitcoin_primitives::{
+ Amount, BlockHeight, BlockHeightInterval, FeeRate, SignedAmount, Weight,
+ };
}
#[test]
diff --git a/units/src/amount/error.rs b/units/src/amount/error.rs
index fc60b318..0f9d4c1a 100644
--- a/units/src/amount/error.rs
+++ b/units/src/amount/error.rs
@@ -149,8 +149,8 @@ impl fmt::Display for ParseAmountError {
E::InputTooLarge(ref error) => write_err!(f, "the input is too large"; error),
E::InvalidCharacter(ref error) => {
write_err!(f, "invalid character in the input"; error)
- },
- E::BadPosition(ref error) => write_err!(f, "valid character in bad position"; error)
+ }
+ E::BadPosition(ref error) => write_err!(f, "valid character in bad position"; error),
}
}
}
@@ -230,9 +230,7 @@ impl fmt::Display for OutOfRangeError {
impl std::error::Error for OutOfRangeError {}
impl From<OutOfRangeError> 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.
@@ -352,11 +350,7 @@ impl fmt::Display for BadPositionError {
1 => f.write_str("the input amount is prefixed with an underscore (_)"),
_ => f.write_str("there are consecutive underscores (_) in the input"),
},
- c => write!(
- f,
- "The character '{}' is at a bad position: {}",
- c, self.position
- ),
+ c => write!(f, "The character '{}' is at a bad position: {}", c, self.position),
}
}
}
diff --git a/units/src/amount/mod.rs b/units/src/amount/mod.rs
index e640e6f3..953196f5 100644
--- a/units/src/amount/mod.rs
+++ b/units/src/amount/mod.rs
@@ -26,9 +26,9 @@ use core::str::FromStr;
use arbitrary::{Arbitrary, Unstructured};
use self::error::{
- InputTooLargeError, InvalidCharacterError, MissingDenominationError, MissingDigitsError,
- MissingDigitsKind, ParseAmountErrorInner, ParseErrorInner, PossiblyConfusingDenominationError,
- TooPreciseError, UnknownDenominationError, BadPositionError,
+ BadPositionError, InputTooLargeError, InvalidCharacterError, MissingDenominationError,
+ MissingDigitsError, MissingDigitsKind, ParseAmountErrorInner, ParseErrorInner,
+ PossiblyConfusingDenominationError, TooPreciseError, UnknownDenominationError,
};
#[rustfmt::skip] // Keep public re-exports separate.
@@ -286,19 +286,26 @@ fn parse_signed_to_satoshi(
underscores = None;
}
'_' if i == 0 =>
- // Leading underscore
- return Err(InnerParseError::BadPosition(BadPositionError { char: '_', position: i + usize::from(is_negative) })),
+ // Leading underscore
+ return Err(InnerParseError::BadPosition(BadPositionError {
+ char: '_',
+ position: i + usize::from(is_negative),
+ })),
'_' => match underscores {
None => underscores = Some(1),
// Consecutive underscores
- _ => return Err(InnerParseError::BadPosition(BadPositionError { char: '_', position: i + usize::from(is_negative) })),
+ _ =>
+ return Err(InnerParseError::BadPosition(BadPositionError {
+ char: '_',
+ position: i + usize::from(is_negative),
+ })),
},
'.' => match decimals {
None if max_decimals <= 0 => break,
None => {
decimals = Some(0);
underscores = None;
- },
+ }
// Double decimal dot.
_ =>
return Err(InnerParseError::InvalidCharacter(InvalidCharacterError {
diff --git a/units/src/amount/result.rs b/units/src/amount/result.rs
index ac2ac818..55135a80 100644
--- a/units/src/amount/result.rs
+++ b/units/src/amount/result.rs
@@ -8,7 +8,9 @@ use core::ops;
use NumOpResult as R;
use super::{Amount, SignedAmount};
-use crate::internal_macros::{impl_add_assign_for_results, impl_sub_assign_for_results, impl_div_assign, impl_mul_assign};
+use crate::internal_macros::{
+ impl_add_assign_for_results, impl_div_assign, impl_mul_assign, impl_sub_assign_for_results,
+};
use crate::result::{MathOp, NumOpError, NumOpResult, OptionExt};
impl From<Amount> for NumOpResult<Amount> {
diff --git a/units/src/block.rs b/units/src/block.rs
index bc53095d..41c38bef 100644
--- a/units/src/block.rs
+++ b/units/src/block.rs
@@ -140,9 +140,7 @@ impl TryFrom<BlockHeight> 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, Self::Error> {
- Self::from_u32(h.to_u32())
- }
+ fn try_from(h: BlockHeight) -> Result<Self, Self::Error> { Self::from_u32(h.to_u32()) }
}
#[cfg(feature = "encoding")]
@@ -354,9 +352,7 @@ impl TryFrom<BlockMtp> 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, Self::Error> {
- Self::from_u32(h.to_u32())
- }
+ fn try_from(h: BlockMtp) -> Result<Self, Self::Error> { Self::from_u32(h.to_u32()) }
}
impl_u32_wrapper! {
diff --git a/units/src/internal_macros.rs b/units/src/internal_macros.rs
index 02c44f54..ac88c218 100644
--- a/units/src/internal_macros.rs
+++ b/units/src/internal_macros.rs
@@ -93,7 +93,7 @@ macro_rules! impl_add_assign_for_results {
fn add_assign(&mut self, rhs: $ty) {
match self {
Self::Error(_) => *self = Self::Error(NumOpError::while_doing(MathOp::Add)),
- Self::Valid(ref lhs) => *self = lhs + rhs
+ Self::Valid(ref lhs) => *self = lhs + rhs,
}
}
}
@@ -120,7 +120,7 @@ macro_rules! impl_sub_assign_for_results {
fn sub_assign(&mut self, rhs: $ty) {
match self {
Self::Error(_) => *self = Self::Error(NumOpError::while_doing(MathOp::Sub)),
- Self::Valid(ref lhs) => *self = lhs - rhs
+ Self::Valid(ref lhs) => *self = lhs - rhs,
}
}
}
diff --git a/units/src/locktime/absolute/error.rs b/units/src/locktime/absolute/error.rs
index 73429b2f..c16480da 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 fd9b88dd..06b39a13 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<bool, IncompatibleHeightError> {
-
-
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<bool, IncompatibleTimeError> {
-
-
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<MedianTimePast> 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 435189d8..2113fb9c 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 94523938..c5d68d4b 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<bool, IsSatisfiedByHeightError> {
-
-
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<bool, IsSatisfiedByTimeError> {
-
-
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<NumberOf512Seconds> 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<Sequence> for LockTime {
type Error = DisabledLockTimeError;
#[inline]
- fn try_from(seq: Sequence) -> Result<Self, DisabledLockTimeError> {
- Self::from_sequence(seq)
- }
+ fn try_from(seq: Sequence) -> Result<Self, DisabledLockTimeError> { Self::from_sequence(seq) }
}
impl From<LockTime> for Sequence {
@@ -867,7 +853,10 @@ mod tests {
#[allow(deprecated_in_future)]
fn sanity_check() {
assert_eq!(LockTime::from(NumberOfBlocks::MAX).to_consensus_u32(), u32::from(u16::MAX));
- assert_eq!(NumberOf512Seconds::from_512_second_intervals(100).to_512_second_intervals(), 100u16);
+ assert_eq!(
+ NumberOf512Seconds::from_512_second_intervals(100).to_512_second_intervals(),
+ 100u16
+ );
assert_eq!(
LockTime::from(NumberOf512Seconds::from_512_second_intervals(100)).to_consensus_u32(),
4_194_404u32
diff --git a/units/src/result.rs b/units/src/result.rs
index 4d50dc82..2c1881d3 100644
--- a/units/src/result.rs
+++ b/units/src/result.rs
@@ -272,7 +272,9 @@ crate::internal_macros::impl_op_for_references! {
// Implement AddAssign on NumOpResults for all wrapped types that already implement AddAssign on themselves
impl<T: ops::AddAssign> ops::AddAssign<T> for NumOpResult<T> {
fn add_assign(&mut self, rhs: T) {
- if let Self::Valid(ref mut lhs) = self { *lhs += rhs }
+ if let Self::Valid(ref mut lhs) = self {
+ *lhs += rhs;
+ }
}
}
@@ -288,7 +290,9 @@ impl<T: ops::AddAssign + Copy> ops::AddAssign<Self> for NumOpResult<T> {
// Implement SubAssign on NumOpResults for all wrapped types that already implement SubAssign on themselves
impl<T: ops::SubAssign> ops::SubAssign<T> for NumOpResult<T> {
fn sub_assign(&mut self, rhs: T) {
- if let Self::Valid(ref mut lhs) = self { *lhs -= rhs }
+ if let Self::Valid(ref mut lhs) = self {
+ *lhs -= rhs;
+ }
}
}
diff --git a/units/src/sequence.rs b/units/src/sequence.rs
index 3910195a..63f6f591 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]
diff --git a/units/tests/api.rs b/units/tests/api.rs
index 79b0a7f3..db29de38 100644
--- a/units/tests/api.rs
+++ b/units/tests/api.rs
@@ -158,8 +158,8 @@ fn api_can_use_modules_from_crate_root() {
#[test]
fn api_can_use_types_from_crate_root() {
use bitcoin_units::{
- Amount, BlockHeight, BlockHeightInterval, BlockMtp, BlockMtpInterval,
- BlockTime, FeeRate, NumOpResult, SignedAmount, Weight,
+ Amount, BlockHeight, BlockHeightInterval, BlockMtp, BlockMtpInterval, BlockTime, FeeRate,
+ NumOpResult, SignedAmount, Weight,
};
}
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.