From b6dc0b3c65602317498cf22d6b8914368549bba9 Mon Sep 17 00:00:00 2001 From: Fmt Bot Date: Sun, 28 Dec 2025 00:10:58 +0000 Subject: [PATCH] 2025-12-28 automated rustfmt nightly --- bitcoin/examples/handshake.rs | 3 +- bitcoin/src/address/mod.rs | 13 ++- bitcoin/src/blockdata/constants.rs | 2 +- bitcoin/src/blockdata/locktime/absolute.rs | 12 +- .../src/blockdata/script/witness_program.rs | 2 +- bitcoin/src/blockdata/transaction.rs | 14 +-- bitcoin/src/blockdata/witness.rs | 46 ++++---- bitcoin/src/consensus/encode.rs | 8 +- bitcoin/src/consensus/params.rs | 2 +- bitcoin/src/crypto/key.rs | 4 +- bitcoin/src/crypto/sighash.rs | 4 +- bitcoin/src/dogecoin/address/error.rs | 25 ++-- bitcoin/src/dogecoin/address/mod.rs | 40 +++---- bitcoin/src/dogecoin/auxpow.rs | 22 ++-- bitcoin/src/dogecoin/constants.rs | 21 ++-- bitcoin/src/dogecoin/mod.rs | 108 ++++++++++-------- bitcoin/src/dogecoin/params.rs | 99 ++++++++-------- bitcoin/src/network.rs | 20 +--- bitcoin/src/p2p/message.rs | 25 ++-- bitcoin/src/p2p/message_blockdata.rs | 12 +- bitcoin/src/p2p/mod.rs | 6 +- bitcoin/src/pow.rs | 70 +++++++----- bitcoin/src/taproot/mod.rs | 6 +- bitcoin/tests/psbt-sign-taproot.rs | 5 +- io/src/lib.rs | 3 +- units/src/fee_rate.rs | 4 +- units/src/lib.rs | 7 +- 27 files changed, 286 insertions(+), 297 deletions(-) diff --git a/bitcoin/examples/handshake.rs b/bitcoin/examples/handshake.rs index 77a55d0b72..f93221e7f2 100644 --- a/bitcoin/examples/handshake.rs +++ b/bitcoin/examples/handshake.rs @@ -30,8 +30,7 @@ fn main() { let version_message = build_version_message(address); - let first_message = - RawNetworkMessage::new(bitcoin::Network::Bitcoin.magic(), version_message); + let first_message = RawNetworkMessage::new(bitcoin::Network::Bitcoin.magic(), version_message); if let Ok(mut stream) = TcpStream::connect(address) { // Send the message diff --git a/bitcoin/src/address/mod.rs b/bitcoin/src/address/mod.rs index c05f32ac87..f30784048b 100644 --- a/bitcoin/src/address/mod.rs +++ b/bitcoin/src/address/mod.rs @@ -75,7 +75,7 @@ pub enum AddressType { /// Pay to taproot. P2tr, /// Pay to anchor. - P2a + P2a, } impl fmt::Display for AddressType { @@ -249,17 +249,17 @@ pub enum AddressData { /// Data encoded by a P2PKH address. P2pkh { /// The pubkey hash used to encumber outputs to this address. - pubkey_hash: PubkeyHash + pubkey_hash: PubkeyHash, }, /// Data encoded by a P2SH address. P2sh { /// The script hash used to encumber outputs to this address. - script_hash: ScriptHash + script_hash: ScriptHash, }, /// Data encoded by a Segwit address. Segwit { /// The witness program used to encumber outputs to this address. - witness_program: WitnessProgram + witness_program: WitnessProgram, }, } @@ -565,7 +565,10 @@ impl Address { pub fn is_spend_standard(&self) -> bool { self.address_type().is_some() } /// Constructs an [`Address`] from an output script (`scriptPubkey`). - pub fn from_script(script: &Script, params: impl AsRef) -> Result { + pub fn from_script( + script: &Script, + params: impl AsRef, + ) -> Result { let network = params.as_ref().network; if script.is_p2pkh() { let bytes = script.as_bytes()[3..23].try_into().expect("statically 20B long"); diff --git a/bitcoin/src/blockdata/constants.rs b/bitcoin/src/blockdata/constants.rs index 4d98ba9074..34667881f9 100644 --- a/bitcoin/src/blockdata/constants.rs +++ b/bitcoin/src/blockdata/constants.rs @@ -261,8 +261,8 @@ mod test { use hex::test_hex_unwrap as hex; use super::*; - use crate::consensus::params; use crate::consensus::encode::serialize; + use crate::consensus::params; #[test] fn bitcoin_genesis_first_transaction() { diff --git a/bitcoin/src/blockdata/locktime/absolute.rs b/bitcoin/src/blockdata/locktime/absolute.rs index 074ca26a78..77728b16ff 100644 --- a/bitcoin/src/blockdata/locktime/absolute.rs +++ b/bitcoin/src/blockdata/locktime/absolute.rs @@ -297,25 +297,19 @@ impl FromStr for LockTime { impl TryFrom<&str> for LockTime { type Error = ParseIntError; - fn try_from(s: &str) -> Result { - LockTime::from_str(s) - } + fn try_from(s: &str) -> Result { LockTime::from_str(s) } } impl TryFrom for LockTime { type Error = ParseIntError; - fn try_from(s: String) -> Result { - LockTime::from_str(&s) - } + fn try_from(s: String) -> Result { LockTime::from_str(&s) } } impl TryFrom> for LockTime { type Error = ParseIntError; - fn try_from(s: Box) -> Result { - LockTime::from_str(&s) - } + fn try_from(s: Box) -> Result { LockTime::from_str(&s) } } impl From for LockTime { diff --git a/bitcoin/src/blockdata/script/witness_program.rs b/bitcoin/src/blockdata/script/witness_program.rs index 2cf7101f23..7f18f9a9ce 100644 --- a/bitcoin/src/blockdata/script/witness_program.rs +++ b/bitcoin/src/blockdata/script/witness_program.rs @@ -25,7 +25,7 @@ pub const MIN_SIZE: usize = 2; pub const MAX_SIZE: usize = 40; /// The P2A program which is given by 0x4e73. -pub(crate) const P2A_PROGRAM: [u8;2] = [78, 115]; +pub(crate) const P2A_PROGRAM: [u8; 2] = [78, 115]; /// The segregated witness program. /// diff --git a/bitcoin/src/blockdata/transaction.rs b/bitcoin/src/blockdata/transaction.rs index 1e11ac66b8..446b96898f 100644 --- a/bitcoin/src/blockdata/transaction.rs +++ b/bitcoin/src/blockdata/transaction.rs @@ -11,8 +11,8 @@ //! This module provides the structures and functions needed to support transactions. //! -use core::{cmp, fmt}; use core::str::FromStr; +use core::{cmp, fmt}; use hashes::{sha256d, Hash}; use internals::write_err; @@ -539,25 +539,19 @@ impl FromStr for Sequence { impl TryFrom<&str> for Sequence { type Error = ParseIntError; - fn try_from(s: &str) -> Result { - Sequence::from_str(s) - } + fn try_from(s: &str) -> Result { Sequence::from_str(s) } } impl TryFrom for Sequence { type Error = ParseIntError; - fn try_from(s: String) -> Result { - Sequence::from_str(&s) - } + fn try_from(s: String) -> Result { Sequence::from_str(&s) } } impl TryFrom> for Sequence { type Error = ParseIntError; - fn try_from(s: Box) -> Result { - Sequence::from_str(&s) - } + fn try_from(s: Box) -> Result { Sequence::from_str(&s) } } /// Bitcoin transaction output. diff --git a/bitcoin/src/blockdata/witness.rs b/bitcoin/src/blockdata/witness.rs index 77f426d65d..3e5393538b 100644 --- a/bitcoin/src/blockdata/witness.rs +++ b/bitcoin/src/blockdata/witness.rs @@ -14,7 +14,10 @@ use crate::consensus::encode::{Error, MAX_VEC_SIZE}; use crate::consensus::{Decodable, Encodable, WriteExt}; use crate::crypto::ecdsa; use crate::prelude::*; -use crate::taproot::{self, LeafScript, LeafVersion, TAPROOT_ANNEX_PREFIX, TAPROOT_CONTROL_BASE_SIZE, TAPROOT_LEAF_MASK}; +use crate::taproot::{ + self, LeafScript, LeafVersion, TAPROOT_ANNEX_PREFIX, TAPROOT_CONTROL_BASE_SIZE, + TAPROOT_LEAF_MASK, +}; use crate::{Script, VarInt}; /// The Witness is the data used to unlock bitcoin since the [segwit upgrade]. @@ -429,10 +432,13 @@ impl Witness { /// version. pub fn taproot_leaf_script(&self) -> Option> { match P2TrSpend::from_witness(self) { - Some(P2TrSpend::Script { leaf_script, control_block, .. }) if control_block.len() >= TAPROOT_CONTROL_BASE_SIZE => { - let version = LeafVersion::from_consensus(control_block[0] & TAPROOT_LEAF_MASK).ok()?; - Some(LeafScript { version, script: leaf_script, }) - }, + Some(P2TrSpend::Script { leaf_script, control_block, .. }) + if control_block.len() >= TAPROOT_CONTROL_BASE_SIZE => + { + let version = + LeafVersion::from_consensus(control_block[0] & TAPROOT_LEAF_MASK).ok()?; + Some(LeafScript { version, script: leaf_script }) + } _ => None, } } @@ -456,18 +462,14 @@ impl Witness { /// This does not guarantee that this represents a P2TR [`Witness`]. /// /// See [`Script::is_p2tr`] to check whether this is actually a Taproot witness. - pub fn taproot_annex(&self) -> Option<&[u8]> { - P2TrSpend::from_witness(self)?.annex() - } + pub fn taproot_annex(&self) -> Option<&[u8]> { P2TrSpend::from_witness(self)?.annex() } /// Get the p2wsh witness script following BIP141 rules. /// /// This does not guarantee that this represents a P2WS [`Witness`]. See /// [Script::is_p2wsh](crate::blockdata::script::Script::is_p2wsh) to /// check whether this is actually a P2WSH witness. - pub fn witness_script(&self) -> Option<&Script> { - self.last().map(Script::from_bytes) - } + pub fn witness_script(&self) -> Option<&Script> { self.last().map(Script::from_bytes) } } impl Index for Witness { @@ -520,14 +522,16 @@ impl<'a> P2TrSpend<'a> { // for the fact that annex is still there. match witness.len() { 0 => None, - 1 => Some(P2TrSpend::Key { /* signature: witness.last().expect("len > 0") ,*/ annex: None }), + 1 => Some(P2TrSpend::Key { + /* signature: witness.last().expect("len > 0") ,*/ annex: None, + }), 2 if witness.last().expect("len > 0").starts_with(&[TAPROOT_ANNEX_PREFIX]) => { let spend = P2TrSpend::Key { // signature: witness.second_to_last().expect("len > 1"), annex: witness.last(), }; Some(spend) - }, + } // 2 => this is script spend without annex - same as when there are 3+ elements and the // last one does NOT start with TAPROOT_ANNEX_PREFIX. This is handled in the catchall // arm. @@ -538,7 +542,7 @@ impl<'a> P2TrSpend<'a> { annex: witness.last(), }; Some(spend) - }, + } _ => { let spend = P2TrSpend::Script { leaf_script: Script::from_bytes(witness.second_to_last().expect("len > 1")), @@ -546,7 +550,7 @@ impl<'a> P2TrSpend<'a> { annex: None, }; Some(spend) - }, + } } } @@ -870,7 +874,8 @@ mod test { #[test] fn get_taproot_leaf_script() { let tapscript = hex!("deadbeef"); - let control_block = hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); + let control_block = + hex!("c0ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"); // annex starting with 0x50 causes the branching logic. let annex = hex!("50"); @@ -883,10 +888,8 @@ mod test { let witness = deserialize::(&witness_serialized[..]).unwrap(); let witness_annex = deserialize::(&witness_serialized_annex[..]).unwrap(); - let expected_leaf_script = LeafScript { - version: LeafVersion::TapScript, - script: Script::from_bytes(&tapscript), - }; + let expected_leaf_script = + LeafScript { version: LeafVersion::TapScript, script: Script::from_bytes(&tapscript) }; // With or without annex, the tapscript should be returned. assert_eq!(witness.taproot_leaf_script().unwrap(), expected_leaf_script); @@ -911,7 +914,8 @@ mod test { let witness = deserialize::(&witness_serialized[..]).unwrap(); let witness_annex = deserialize::(&witness_serialized_annex[..]).unwrap(); - let witness_key_spend_annex = deserialize::(&witness_serialized_key_spend_annex[..]).unwrap(); + let witness_key_spend_annex = + deserialize::(&witness_serialized_key_spend_annex[..]).unwrap(); // With or without annex, the tapscript should be returned. assert_eq!(witness.taproot_control_block(), Some(&control_block[..])); diff --git a/bitcoin/src/consensus/encode.rs b/bitcoin/src/consensus/encode.rs index b885e9318a..d0bb754a33 100644 --- a/bitcoin/src/consensus/encode.rs +++ b/bitcoin/src/consensus/encode.rs @@ -406,9 +406,7 @@ macro_rules! impl_int_encodable { ($ty:ident, $meth_dec:ident, $meth_enc:ident) => { impl Decodable for $ty { #[inline] - fn consensus_decode( - r: &mut R, - ) -> core::result::Result { + fn consensus_decode(r: &mut R) -> core::result::Result { ReadExt::$meth_dec(r) } } @@ -593,9 +591,7 @@ macro_rules! impl_array { impl Decodable for [u8; $size] { #[inline] - fn consensus_decode( - r: &mut R, - ) -> core::result::Result { + fn consensus_decode(r: &mut R) -> core::result::Result { let mut ret = [0; $size]; r.read_slice(&mut ret)?; Ok(ret) diff --git a/bitcoin/src/consensus/params.rs b/bitcoin/src/consensus/params.rs index 93a36c2202..325a6c7ee8 100644 --- a/bitcoin/src/consensus/params.rs +++ b/bitcoin/src/consensus/params.rs @@ -76,7 +76,7 @@ pub static SIGNET: Params = Params::SIGNET; /// The regtest parameters. pub static REGTEST: Params = Params::REGTEST; -#[allow(deprecated)] // For `pow_limit`. +#[allow(deprecated)] // For `pow_limit`. impl Params { /// The mainnet parameters (alias for `Params::MAINNET`). pub const BITCOIN: Params = Params::MAINNET; diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs index 3ac16a596a..244a3324d7 100644 --- a/bitcoin/src/crypto/key.rs +++ b/bitcoin/src/crypto/key.rs @@ -856,7 +856,7 @@ impl TweakedPublicKey { } #[doc(hidden)] - #[deprecated(since="0.32.6", note="use to_x_only_public_key() instead")] + #[deprecated(since = "0.32.6", note = "use to_x_only_public_key() instead")] pub fn to_inner(self) -> XOnlyPublicKey { self.0 } /// Returns the underlying x-only public key. @@ -884,7 +884,7 @@ impl TweakedKeypair { pub fn dangerous_assume_tweaked(pair: Keypair) -> TweakedKeypair { TweakedKeypair(pair) } #[doc(hidden)] - #[deprecated(since="0.32.6", note="use to_keypair() instead")] + #[deprecated(since = "0.32.6", note = "use to_keypair() instead")] pub fn to_inner(self) -> Keypair { self.0 } /// Returns the underlying key pair. diff --git a/bitcoin/src/crypto/sighash.rs b/bitcoin/src/crypto/sighash.rs index 294dac70e6..ab6cca6c6d 100644 --- a/bitcoin/src/crypto/sighash.rs +++ b/bitcoin/src/crypto/sighash.rs @@ -406,9 +406,7 @@ impl EcdsaSighashType { /// type (after masking with 0x1f), regardless of the ANYONECANPAY flag. /// /// See: - pub fn is_single(&self) -> bool { - matches!(self, Self::Single | Self::SinglePlusAnyoneCanPay) - } + pub fn is_single(&self) -> bool { matches!(self, Self::Single | Self::SinglePlusAnyoneCanPay) } /// Creates a [`EcdsaSighashType`] from a raw `u32`. /// diff --git a/bitcoin/src/dogecoin/address/error.rs b/bitcoin/src/dogecoin/address/error.rs index 521b19e7fa..21ddb750b0 100644 --- a/bitcoin/src/dogecoin/address/error.rs +++ b/bitcoin/src/dogecoin/address/error.rs @@ -6,13 +6,12 @@ use core::fmt; use internals::write_err; -use crate::dogecoin::address::{Address, NetworkUnchecked}; -use crate::dogecoin::Network; - pub use crate::address::error::{ FromScriptError, InvalidBase58PayloadLengthError, InvalidLegacyPrefixError, LegacyAddressTooLongError, P2shError, }; +use crate::dogecoin::address::{Address, NetworkUnchecked}; +use crate::dogecoin::Network; /// Address parsing error. #[derive(Debug, Clone, PartialEq, Eq)] @@ -62,33 +61,23 @@ impl std::error::Error for ParseError { } impl From for ParseError { - fn from(e: base58::Error) -> Self { - Self::Base58(e) - } + fn from(e: base58::Error) -> Self { Self::Base58(e) } } impl From for ParseError { - fn from(e: LegacyAddressTooLongError) -> Self { - Self::LegacyAddressTooLong(e) - } + fn from(e: LegacyAddressTooLongError) -> Self { Self::LegacyAddressTooLong(e) } } impl From for ParseError { - fn from(e: InvalidBase58PayloadLengthError) -> Self { - Self::InvalidBase58PayloadLength(e) - } + fn from(e: InvalidBase58PayloadLengthError) -> Self { Self::InvalidBase58PayloadLength(e) } } impl From for ParseError { - fn from(e: InvalidLegacyPrefixError) -> Self { - Self::InvalidLegacyPrefix(e) - } + fn from(e: InvalidLegacyPrefixError) -> Self { Self::InvalidLegacyPrefix(e) } } impl From for ParseError { - fn from(e: NetworkValidationError) -> Self { - Self::NetworkValidation(e) - } + fn from(e: NetworkValidationError) -> Self { Self::NetworkValidation(e) } } /// Address's network differs from required one. diff --git a/bitcoin/src/dogecoin/address/mod.rs b/bitcoin/src/dogecoin/address/mod.rs index f23a9a9918..c4f73e991f 100644 --- a/bitcoin/src/dogecoin/address/mod.rs +++ b/bitcoin/src/dogecoin/address/mod.rs @@ -205,9 +205,7 @@ struct DisplayUnchecked<'a, N: NetworkValidation>(&'a Address); #[cfg(feature = "serde")] impl fmt::Display for DisplayUnchecked<'_, N> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0 .0, fmt) - } + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0 .0, fmt) } } #[cfg(feature = "serde")] @@ -232,9 +230,7 @@ impl Address { } /// Marks the network of this address as unchecked. - pub fn into_unchecked(self) -> Address { - Address(self.0, PhantomData) - } + pub fn into_unchecked(self) -> Address { Address(self.0, PhantomData) } } /// Methods and functions that can be called only on `Address`. @@ -360,12 +356,10 @@ impl Address { pub fn matches_script_pubkey(&self, script: &Script) -> bool { use AddressInner::*; match self.0 { - P2pkh { ref hash, network: _ } if script.is_p2pkh() => { - &script.as_bytes()[3..23] == >::as_ref(hash) - } - P2sh { ref hash, network: _ } if script.is_p2sh() => { - &script.as_bytes()[2..22] == >::as_ref(hash) - } + P2pkh { ref hash, network: _ } if script.is_p2pkh() => + &script.as_bytes()[3..23] == >::as_ref(hash), + P2sh { ref hash, network: _ } if script.is_p2sh() => + &script.as_bytes()[2..22] == >::as_ref(hash), P2pkh { .. } | P2sh { .. } => false, } } @@ -428,12 +422,10 @@ impl Address { match self.0 { P2pkh { hash: _, ref network } => *network == n, P2sh { hash: _, network: Network::Dogecoin } => n == Network::Dogecoin, - P2sh { hash: _, network: Network::Testnet } => { - n == Network::Testnet || n == Network::Regtest - } - P2sh { hash: _, network: Network::Regtest } => { - n == Network::Testnet || n == Network::Regtest - } + P2sh { hash: _, network: Network::Testnet } => + n == Network::Testnet || n == Network::Regtest, + P2sh { hash: _, network: Network::Regtest } => + n == Network::Testnet || n == Network::Regtest, } } @@ -495,23 +487,17 @@ impl Address { /// For details about this mechanism, see section [*Parsing addresses*](Address#parsing-addresses) /// on [`Address`]. #[inline] - pub fn assume_checked(self) -> Address { - Address(self.0, PhantomData) - } + pub fn assume_checked(self) -> Address { Address(self.0, PhantomData) } } impl From
for script::ScriptBuf { - fn from(a: Address) -> Self { - a.script_pubkey() - } + fn from(a: Address) -> Self { a.script_pubkey() } } // Alternate formatting `{:#}` is used to return uppercase version of bech32 addresses which should // be used in QR codes, see [`Address::to_qr_uri`]. impl fmt::Display for Address { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, fmt) - } + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, fmt) } } impl fmt::Debug for Address { diff --git a/bitcoin/src/dogecoin/auxpow.rs b/bitcoin/src/dogecoin/auxpow.rs index a5993fe8e5..fc1f56c9f1 100644 --- a/bitcoin/src/dogecoin/auxpow.rs +++ b/bitcoin/src/dogecoin/auxpow.rs @@ -1039,7 +1039,9 @@ mod tests { BlockHash::from_str("283fa35edb604a913ead7e776b534f1661723da6721131eee75a39738ed2e8f8") .unwrap(); - assert!(auxpow_mainnet_2_679_506.check(aux_block_hash, AUXPOW_BLOCK_CHAIN_ID, true).is_ok()); + assert!(auxpow_mainnet_2_679_506 + .check(aux_block_hash, AUXPOW_BLOCK_CHAIN_ID, true) + .is_ok()); } #[test] @@ -1116,7 +1118,9 @@ mod tests { BlockHash::from_str("6aae55bea74235f0c80bd066349d4440c31f2d0f27d54265ecd484d8c1d11b47") .unwrap(); - assert!(auxpow_mainnet_1_000_000.check(aux_block_hash, AUXPOW_BLOCK_CHAIN_ID, true).is_ok()); + assert!(auxpow_mainnet_1_000_000 + .check(aux_block_hash, AUXPOW_BLOCK_CHAIN_ID, true) + .is_ok()); } #[test] @@ -1149,23 +1153,23 @@ mod tests { TxMerkleNode::from_str( "2f7aeb2615e5251d107339a2e4d7177ac341f71b2d0d5931695f6133a64f497e", ) - .unwrap(), + .unwrap(), TxMerkleNode::from_str( "c9d13f7eb2a2fc00f6d4a4f941c214868ae508a2c410eee2e37936d742167d0c", ) - .unwrap(), + .unwrap(), TxMerkleNode::from_str( "bc82db9b6fd74cfba991bc2e422f6db3f2d6916053fcc6feaa5eca588b8bff1c", ) - .unwrap(), + .unwrap(), TxMerkleNode::from_str( "be46c579c5859312688104b479e2527058a5da9ce9dd5f7ef4247cfa3384ca99", ) - .unwrap(), + .unwrap(), TxMerkleNode::from_str( "f9813969c631dcd4c536fa7f5f371d840c8270644651d3c2536fb5abb0d846c2", ) - .unwrap(), + .unwrap(), ]; let blockchain_branch = vec![]; @@ -1184,6 +1188,8 @@ mod tests { BlockHash::from_str("10b320f69f1eb5e1b7bb45fbc108e4379b5a77dee5a3b0a406038989b9641539") .unwrap(); - assert!(auxpow_mainnet_1_731_044.check(aux_block_hash, AUXPOW_BLOCK_CHAIN_ID, true).is_ok()); + assert!(auxpow_mainnet_1_731_044 + .check(aux_block_hash, AUXPOW_BLOCK_CHAIN_ID, true) + .is_ok()); } } diff --git a/bitcoin/src/dogecoin/constants.rs b/bitcoin/src/dogecoin/constants.rs index 799473e164..9a8b5bdafc 100644 --- a/bitcoin/src/dogecoin/constants.rs +++ b/bitcoin/src/dogecoin/constants.rs @@ -18,12 +18,12 @@ use crate::{ TxMerkleNode, TxOut, Witness, }; -pub(crate) const PUBKEY_ADDRESS_PREFIX_MAINNET : u8 = 0x1e; -pub(crate) const PUBKEY_ADDRESS_PREFIX_TESTNET : u8 = 0x71; -pub(crate) const PUBKEY_ADDRESS_PREFIX_REGTEST : u8 = 0x6f; -pub(crate) const SCRIPT_ADDRESS_PREFIX_MAINNET : u8 = 0x16; -pub(crate) const SCRIPT_ADDRESS_PREFIX_TESTNET : u8 = 0xc4; -pub(crate) const SCRIPT_ADDRESS_PREFIX_REGTEST : u8 = 0xc4; +pub(crate) const PUBKEY_ADDRESS_PREFIX_MAINNET: u8 = 0x1e; +pub(crate) const PUBKEY_ADDRESS_PREFIX_TESTNET: u8 = 0x71; +pub(crate) const PUBKEY_ADDRESS_PREFIX_REGTEST: u8 = 0x6f; +pub(crate) const SCRIPT_ADDRESS_PREFIX_MAINNET: u8 = 0x16; +pub(crate) const SCRIPT_ADDRESS_PREFIX_TESTNET: u8 = 0xc4; +pub(crate) const SCRIPT_ADDRESS_PREFIX_REGTEST: u8 = 0xc4; // This is the 65 byte (uncompressed) pubkey used as the one-and-only output of the genesis transaction. // @@ -90,7 +90,8 @@ pub fn genesis_block(params: impl AsRef) -> Block { time: 1386325540, bits: CompactTarget::from_consensus(0x1e0ffff0), nonce: 99943, - }.into(), + } + .into(), txdata, }, Network::Testnet => Block { @@ -101,7 +102,8 @@ pub fn genesis_block(params: impl AsRef) -> Block { time: 1391503289, bits: CompactTarget::from_consensus(0x1e0ffff0), nonce: 997879, - }.into(), + } + .into(), txdata, }, Network::Regtest => Block { @@ -112,7 +114,8 @@ pub fn genesis_block(params: impl AsRef) -> Block { time: 1296688602, bits: CompactTarget::from_consensus(0x207fffff), nonce: 2, - }.into(), + } + .into(), txdata, }, } diff --git a/bitcoin/src/dogecoin/mod.rs b/bitcoin/src/dogecoin/mod.rs index 8982af0df2..7cd79887c5 100644 --- a/bitcoin/src/dogecoin/mod.rs +++ b/bitcoin/src/dogecoin/mod.rs @@ -6,23 +6,24 @@ //! network messages related to Dogecoin. pub mod address; +pub mod auxpow; pub mod constants; pub mod params; -pub mod auxpow; + +use core::fmt; +use core::ops::{Deref, DerefMut}; pub use address::*; use crate::block::{Header as PureHeader, TxMerkleNode, Version}; use crate::consensus::{encode, Decodable, Encodable}; +use crate::dogecoin::auxpow::{AuxPow, VERSION_AUXPOW}; use crate::dogecoin::params::Params; use crate::internal_macros::impl_consensus_encoding; use crate::io::{Read, Write}; use crate::p2p::Magic; use crate::prelude::*; use crate::{io, BlockHash, Transaction}; -use core::fmt; -use core::ops::{Deref, DerefMut}; -use crate::dogecoin::auxpow::{AuxPow, VERSION_AUXPOW}; /// Dogecoin block header. /// @@ -41,21 +42,15 @@ pub struct Header { impl Deref for Header { type Target = PureHeader; - fn deref(&self) -> &Self::Target { - &self.pure_header - } + fn deref(&self) -> &Self::Target { &self.pure_header } } impl DerefMut for Header { - fn deref_mut(&mut self) -> &mut Self::Target { - &mut self.pure_header - } + fn deref_mut(&mut self) -> &mut Self::Target { &mut self.pure_header } } impl From for Header { - fn from(pure_header: PureHeader) -> Self { - Self { pure_header, aux_pow: None } - } + fn from(pure_header: PureHeader) -> Self { Self { pure_header, aux_pow: None } } } impl Decodable for Header { @@ -88,14 +83,10 @@ impl Encodable for Header { impl PureHeader { /// Checks if a block header indicates it was merged mined and contains AuxPow information. - pub fn has_auxpow_bit(&self) -> bool { - (self.version.to_consensus() & VERSION_AUXPOW) != 0 - } + pub fn has_auxpow_bit(&self) -> bool { (self.version.to_consensus() & VERSION_AUXPOW) != 0 } /// Extracts the chain ID from the block header's version field. - pub fn extract_chain_id(&self) -> i32 { - self.version.to_consensus() >> 16 - } + pub fn extract_chain_id(&self) -> i32 { self.version.to_consensus() >> 16 } /// Determines if a block header represents a legacy (pre-AuxPoW) block. pub fn is_legacy(&self) -> bool { @@ -105,9 +96,7 @@ impl PureHeader { } /// Extracts the base version number from a block header, removing AuxPoW and chain ID bits. - pub fn extract_base_version(&self) -> i32 { - self.version.to_consensus() % VERSION_AUXPOW - } + pub fn extract_base_version(&self) -> i32 { self.version.to_consensus() % VERSION_AUXPOW } } /// Dogecoin block. @@ -151,10 +140,7 @@ impl Block { /// Compute merkle root of the transaction list in this block. pub fn compute_merkle_root(&self) -> Option { - let hashes = self - .txdata - .iter() - .map(|obj| obj.compute_txid().to_raw_hash()); + let hashes = self.txdata.iter().map(|obj| obj.compute_txid().to_raw_hash()); crate::merkle_tree::calculate_root(hashes).map(|h| h.into()) } } @@ -197,9 +183,7 @@ impl Network { } impl AsRef for Network { - fn as_ref(&self) -> &Params { - self.params() - } + fn as_ref(&self) -> &Params { self.params() } } impl fmt::Display for Network { @@ -227,13 +211,13 @@ impl core::str::FromStr for Network { #[cfg(test)] mod tests { - use hex::{test_hex_unwrap as hex}; use hashes::Hash; + use hex::test_hex_unwrap as hex; + use super::*; use crate::block::{ValidationError, Version}; use crate::consensus::encode::{deserialize, serialize}; - use crate::{CompactTarget, Target, Work}; - use crate::{Network as BitcoinNetwork}; + use crate::{CompactTarget, Network as BitcoinNetwork, Target, Work}; #[test] fn dogecoin_block_test() { @@ -436,8 +420,13 @@ mod tests { let height = 480; let params = Params::new(Network::Dogecoin); let starting_bits = CompactTarget::from_consensus(0x1e0fffff); // Max target - let timespan = 4 * params.pow_target_timespan(height); // 4x Slower than expected - let got = CompactTarget::from_next_work_required_dogecoin(starting_bits, timespan, ¶ms, height); + let timespan = 4 * params.pow_target_timespan(height); // 4x Slower than expected + let got = CompactTarget::from_next_work_required_dogecoin( + starting_bits, + timespan, + ¶ms, + height, + ); let want = params.max_attainable_target.to_compact_lossy(); assert_eq!(got, want); } @@ -447,8 +436,13 @@ mod tests { let height = 145_000; let params = Params::new(Network::Dogecoin); let starting_bits = CompactTarget::from_consensus(0x1e0fffff); // Max target - let timespan = 5 * params.pow_target_timespan(height); // 5x Slower than expected - let got = CompactTarget::from_next_work_required_dogecoin(starting_bits, timespan, ¶ms, height); + let timespan = 5 * params.pow_target_timespan(height); // 5x Slower than expected + let got = CompactTarget::from_next_work_required_dogecoin( + starting_bits, + timespan, + ¶ms, + height, + ); let want = params.max_attainable_target.to_compact_lossy(); assert_eq!(got, want); } @@ -460,8 +454,13 @@ mod tests { let starting_bits = CompactTarget::from_consensus(0x1b02f5b6); // Arbitrary difficulty let params = Params::new(Network::Dogecoin); for height in pre_digishield_heights { - let timespan = 4 * params.pow_target_timespan(height); // 4x Slower than expected - let got = CompactTarget::from_next_work_required_dogecoin(starting_bits, timespan, ¶ms, height); + let timespan = 4 * params.pow_target_timespan(height); // 4x Slower than expected + let got = CompactTarget::from_next_work_required_dogecoin( + starting_bits, + timespan, + ¶ms, + height, + ); let want = Target::from_compact(starting_bits) .max_transition_threshold_dogecoin(¶ms, height) .to_compact_lossy(); @@ -469,7 +468,12 @@ mod tests { } for height in digishield_heights { let timespan = 5 * params.pow_target_timespan(height); // 5x Slower than expected - let got = CompactTarget::from_next_work_required_dogecoin(starting_bits, timespan, ¶ms, height); + let got = CompactTarget::from_next_work_required_dogecoin( + starting_bits, + timespan, + ¶ms, + height, + ); let want = Target::from_compact(starting_bits) .max_transition_threshold_dogecoin(¶ms, height) .to_compact_lossy(); @@ -611,21 +615,23 @@ mod tests { merkle_root: TxMerkleNode::all_zeros(), time: test_case.start_time as u32, bits: CompactTarget::from_consensus(0x1e0fffff), // Note: this value does not matter - nonce: 0 - }.into(); + nonce: 0, + } + .into(); let end_header = PureHeader { version: Version::ONE, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: test_case.end_time as u32, bits: test_case.starting_bits, - nonce: 0 - }.into(); + nonce: 0, + } + .into(); let adjustment = CompactTarget::from_header_difficulty_adjustment_dogecoin( start_header, end_header, ¶ms, - test_case.height + test_case.height, ); assert_eq!( adjustment, test_case.expected_adjustment_bits, @@ -643,7 +649,12 @@ mod tests { let params = Params::new(Network::Dogecoin); for height in pre_digishield_heights { let timespan = (0.06 * params.pow_target_timespan(height) as f64) as i64; // > 16x Faster than expected - let got = CompactTarget::from_next_work_required_dogecoin(starting_bits, timespan, ¶ms, height); + let got = CompactTarget::from_next_work_required_dogecoin( + starting_bits, + timespan, + ¶ms, + height, + ); let want = Target::from_compact(starting_bits) .min_transition_threshold_dogecoin(¶ms, height) .to_compact_lossy(); @@ -651,7 +662,12 @@ mod tests { } for height in digishield_heights { let timespan = -params.pow_target_timespan(height); // Negative timespan - let got = CompactTarget::from_next_work_required_dogecoin(starting_bits, timespan, ¶ms, height); + let got = CompactTarget::from_next_work_required_dogecoin( + starting_bits, + timespan, + ¶ms, + height, + ); let want = Target::from_compact(starting_bits) .min_transition_threshold_dogecoin(¶ms, height) .to_compact_lossy(); diff --git a/bitcoin/src/dogecoin/params.rs b/bitcoin/src/dogecoin/params.rs index d5af4c7d9a..3f2eb6f41b 100644 --- a/bitcoin/src/dogecoin/params.rs +++ b/bitcoin/src/dogecoin/params.rs @@ -9,7 +9,6 @@ use crate::dogecoin::Network; use crate::Target; - const ONE_SECOND: i64 = 1; const ONE_MINUTE: i64 = 60; const FOUR_HOURS: i64 = 4 * 60 * 60; @@ -81,61 +80,61 @@ impl Params { /// The mainnet parameters. /// Ref: pub const MAINNET: Params = Params { - network: Network::Dogecoin, - bip16_time: 1333238400, // Apr 1 2012 - bip34_height: 1034383, // 80d1364201e5df97e696c03bdd24dc885e8617b9de51e453c10a4f629b1e797a - bip65_height: 3464751, // 34cd2cbba4ba366f47e5aa0db5f02c19eba2adf679ceb6653ac003bdc9a0ef1f - bip66_height: 1034383, // 80d1364201e5df97e696c03bdd24dc885e8617b9de51e453c10a4f629b1e797a - rule_change_activation_threshold: 9576, // 95% of 10,080 - miner_confirmation_window: 10080, // 60 * 24 * 7 = 10,080 blocks, or one week - pow_limit: Target::MAX_ATTAINABLE_MAINNET_DOGE, - max_attainable_target: Target::MAX_ATTAINABLE_MAINNET_DOGE, - pow_target_spacing: ONE_MINUTE, // 1 minute - no_pow_retargeting: false, - auxpow_height: 371_337, - strict_chain_id: true, - auxpow_chain_id: 0x0062, - digishield_activation_height: 145000, + network: Network::Dogecoin, + bip16_time: 1333238400, // Apr 1 2012 + bip34_height: 1034383, // 80d1364201e5df97e696c03bdd24dc885e8617b9de51e453c10a4f629b1e797a + bip65_height: 3464751, // 34cd2cbba4ba366f47e5aa0db5f02c19eba2adf679ceb6653ac003bdc9a0ef1f + bip66_height: 1034383, // 80d1364201e5df97e696c03bdd24dc885e8617b9de51e453c10a4f629b1e797a + rule_change_activation_threshold: 9576, // 95% of 10,080 + miner_confirmation_window: 10080, // 60 * 24 * 7 = 10,080 blocks, or one week + pow_limit: Target::MAX_ATTAINABLE_MAINNET_DOGE, + max_attainable_target: Target::MAX_ATTAINABLE_MAINNET_DOGE, + pow_target_spacing: ONE_MINUTE, // 1 minute + no_pow_retargeting: false, + auxpow_height: 371_337, + strict_chain_id: true, + auxpow_chain_id: 0x0062, + digishield_activation_height: 145000, }; /// The Dogecoin testnet parameters. /// Ref: pub const TESTNET: Params = Params { - network: Network::Testnet, - bip16_time: 1333238400, // Apr 1 2012 - bip34_height: 708658, // 21b8b97dcdb94caa67c7f8f6dbf22e61e0cfe0e46e1fff3528b22864659e9b38 - bip65_height: 1854705, // 955bd496d23790aba1ecfacb722b089a6ae7ddabaedf7d8fb0878f48308a71f9 - bip66_height: 708658, // 21b8b97dcdb94caa67c7f8f6dbf22e61e0cfe0e46e1fff3528b22864659e9b38 - rule_change_activation_threshold: 2880, // 2 days (note this is significantly lower than Bitcoin standard) - miner_confirmation_window: 10080, // 60 * 24 * 7 = 10,080 blocks, or one week - pow_limit: Target::MAX_ATTAINABLE_TESTNET_DOGE, - max_attainable_target: Target::MAX_ATTAINABLE_TESTNET_DOGE, - pow_target_spacing: ONE_MINUTE, // 1 minute - no_pow_retargeting: false, - auxpow_height: 158_100, - strict_chain_id: false, - auxpow_chain_id: 0x0062, - digishield_activation_height: 145000, + network: Network::Testnet, + bip16_time: 1333238400, // Apr 1 2012 + bip34_height: 708658, // 21b8b97dcdb94caa67c7f8f6dbf22e61e0cfe0e46e1fff3528b22864659e9b38 + bip65_height: 1854705, // 955bd496d23790aba1ecfacb722b089a6ae7ddabaedf7d8fb0878f48308a71f9 + bip66_height: 708658, // 21b8b97dcdb94caa67c7f8f6dbf22e61e0cfe0e46e1fff3528b22864659e9b38 + rule_change_activation_threshold: 2880, // 2 days (note this is significantly lower than Bitcoin standard) + miner_confirmation_window: 10080, // 60 * 24 * 7 = 10,080 blocks, or one week + pow_limit: Target::MAX_ATTAINABLE_TESTNET_DOGE, + max_attainable_target: Target::MAX_ATTAINABLE_TESTNET_DOGE, + pow_target_spacing: ONE_MINUTE, // 1 minute + no_pow_retargeting: false, + auxpow_height: 158_100, + strict_chain_id: false, + auxpow_chain_id: 0x0062, + digishield_activation_height: 145000, }; /// The Dogecoin regtest parameters. /// Ref: pub const REGTEST: Params = Params { - network: Network::Regtest, - bip16_time: 1333238400, // Apr 1 2012 - bip34_height: 100000000, // not activated on regtest - bip65_height: 1351, - bip66_height: 1251, // used only in rpc tests - rule_change_activation_threshold: 540, // 75% - miner_confirmation_window: 720, - pow_limit: Target::MAX_ATTAINABLE_REGTEST_DOGE, - max_attainable_target: Target::MAX_ATTAINABLE_REGTEST_DOGE, - pow_target_spacing: ONE_SECOND, // regtest: 1 second blocks - no_pow_retargeting: true, - auxpow_height: 20, - strict_chain_id: true, - auxpow_chain_id: 0x0062, - digishield_activation_height: 10, + network: Network::Regtest, + bip16_time: 1333238400, // Apr 1 2012 + bip34_height: 100000000, // not activated on regtest + bip65_height: 1351, + bip66_height: 1251, // used only in rpc tests + rule_change_activation_threshold: 540, // 75% + miner_confirmation_window: 720, + pow_limit: Target::MAX_ATTAINABLE_REGTEST_DOGE, + max_attainable_target: Target::MAX_ATTAINABLE_REGTEST_DOGE, + pow_target_spacing: ONE_SECOND, // regtest: 1 second blocks + no_pow_retargeting: true, + auxpow_height: 20, + strict_chain_id: true, + auxpow_chain_id: 0x0062, + digishield_activation_height: 10, }; /// Creates parameters set for the given network. @@ -149,7 +148,7 @@ impl Params { /// Checks if Digishield difficulty adjustment is activated at the given block height. pub const fn is_digishield_activated(&self, height: u32) -> bool { - height >= self.digishield_activation_height + height >= self.digishield_activation_height } /// Returns the target timespan (in seconds) used for PoW retargeting at the given block height. @@ -173,15 +172,13 @@ impl Params { 0..=144_999 => true, 145_000..=157_499 => false, 157_500.. => true, - } + }, Network::Regtest => true, } } /// Checks if legacy blocks can be mined at the given block height. - pub const fn allow_legacy_blocks(&self, height: u32) -> bool { - height < self.auxpow_height - } + pub const fn allow_legacy_blocks(&self, height: u32) -> bool { height < self.auxpow_height } } impl AsRef for Params { diff --git a/bitcoin/src/network.rs b/bitcoin/src/network.rs index 3b60fd98d1..f2b2f7cca5 100644 --- a/bitcoin/src/network.rs +++ b/bitcoin/src/network.rs @@ -333,26 +333,14 @@ mod tests { #[test] fn serialize_test() { assert_eq!(serialize(&Network::Bitcoin.magic()), &[0xf9, 0xbe, 0xb4, 0xd9]); - assert_eq!( - serialize(&Network::Testnet.magic()), - &[0x0b, 0x11, 0x09, 0x07] - ); - assert_eq!( - serialize(&Network::Testnet4.magic()), - &[0x1c, 0x16, 0x3f, 0x28] - ); + assert_eq!(serialize(&Network::Testnet.magic()), &[0x0b, 0x11, 0x09, 0x07]); + assert_eq!(serialize(&Network::Testnet4.magic()), &[0x1c, 0x16, 0x3f, 0x28]); assert_eq!(serialize(&Network::Signet.magic()), &[0x0a, 0x03, 0xcf, 0x40]); assert_eq!(serialize(&Network::Regtest.magic()), &[0xfa, 0xbf, 0xb5, 0xda]); assert_eq!(deserialize(&[0xf9, 0xbe, 0xb4, 0xd9]).ok(), Some(Network::Bitcoin.magic())); - assert_eq!( - deserialize(&[0x0b, 0x11, 0x09, 0x07]).ok(), - Some(Network::Testnet.magic()) - ); - assert_eq!( - deserialize(&[0x1c, 0x16, 0x3f, 0x28]).ok(), - Some(Network::Testnet4.magic()) - ); + assert_eq!(deserialize(&[0x0b, 0x11, 0x09, 0x07]).ok(), Some(Network::Testnet.magic())); + assert_eq!(deserialize(&[0x1c, 0x16, 0x3f, 0x28]).ok(), Some(Network::Testnet4.magic())); assert_eq!(deserialize(&[0x0a, 0x03, 0xcf, 0x40]).ok(), Some(Network::Signet.magic())); assert_eq!(deserialize(&[0xfa, 0xbf, 0xb5, 0xda]).ok(), Some(Network::Regtest.magic())); } diff --git a/bitcoin/src/p2p/message.rs b/bitcoin/src/p2p/message.rs index 36c9f81076..4a7ad6cd5b 100644 --- a/bitcoin/src/p2p/message.rs +++ b/bitcoin/src/p2p/message.rs @@ -312,14 +312,10 @@ impl RawNetworkMessage { } /// Consumes the [RawNetworkMessage] instance and returns the inner payload. - pub fn into_payload(self) -> NetworkMessage { - self.payload - } + pub fn into_payload(self) -> NetworkMessage { self.payload } /// The actual message data - pub fn payload(&self) -> &NetworkMessage { - &self.payload - } + pub fn payload(&self) -> &NetworkMessage { &self.payload } /// Magic bytes to identify the network these messages are meant for pub fn magic(&self) -> &Magic { &self.magic } @@ -544,6 +540,7 @@ impl Decodable for RawNetworkMessage
; type RawNetworkMessage = super::RawNetworkMessage; - fn hash(slice: [u8; 32]) -> Hash { - Hash::from_slice(&slice).unwrap() - } + fn hash(slice: [u8; 32]) -> Hash { Hash::from_slice(&slice).unwrap() } #[test] fn dogecoin_ser_der_raw_network_message_test() { - type NetworkMessage = super::NetworkMessage; - type RawNetworkMessage = super::RawNetworkMessage; + type NetworkMessage = + super::NetworkMessage; + type RawNetworkMessage = + super::RawNetworkMessage; // Dogecoin mainnet block 62959fd2246701d38917fe59920523ad66111b68e360fe3a60ebdca2dd6d4546 (height 1000013) let bytes = hex!("03016200916a0b2966c72c1bb533469388c7e5d771e0d5570e897fe98453baa8226c2d7e9d73ce00d335ed419b390659c89e3af25ab2ffc8db0f1144cbf2ab8867b140e23dbe6d569e42031b0000000001000000010000000000000000000000000000000000000000000000000000000000000000ffffffff3f0359c90d04566dbe3d2cfabe6d6df5cee89f3766065a3f9ddc4ab57a1adf830944af0ef431e9d4f59c2f4e8985e70800000000000000085600096a01000000ffffffff0100f90295000000001976a91457757ed3d226faf12bd43983896ec81e7fca369a88ac0000000010ce3fcdb40c53bb040487a2ff745a7384314d4c24809aba52a35c74a5be4ca5000000000003d7bec81d9cd6968e141a0d0c1645b9dcca96ab9fb57dbc6f63a4ef669a0ad099de79681c0a67d2f2de006742ab85320b9ecc7df8f9979eff946d1f6964d3ab5956b1698e938dbe001e487469ad0c84c1b008757a7a78908378db499a602949bd00000000030000005d24356ff4b4111265187fd2e89dc7e58019221fba2e4ad0ec789ed38bfd9be152ac7cf211bf53770edf319ccc29cf8692076446430a195ed1c55ad458612d1e3dbe6d56f542011b3a4a43490101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff09034d420f04566dbe3dffffffff010010a5d4e80000001976a914d1895519d5281aa005487b1ff07f3307aced8d6e88ac00000000"); @@ -586,10 +582,7 @@ mod test { assert!(header.aux_pow.is_some()); // Test only Block and Header messages, which are different than Bitcoin. - let msgs = vec![ - NetworkMessage::Block(block), - NetworkMessage::Headers(vec![header]), - ]; + let msgs = vec![NetworkMessage::Block(block), NetworkMessage::Headers(vec![header])]; for msg in msgs { let raw_msg = RawNetworkMessage::new(Magic::from_bytes([57, 0, 0, 0]), msg); diff --git a/bitcoin/src/p2p/message_blockdata.rs b/bitcoin/src/p2p/message_blockdata.rs index 40a9d89b40..b7d4f6452b 100644 --- a/bitcoin/src/p2p/message_blockdata.rs +++ b/bitcoin/src/p2p/message_blockdata.rs @@ -126,7 +126,11 @@ pub struct GetHeadersMessage { impl GetBlocksMessage { /// Construct a new `getblocks` message - pub fn new(version: u32, locator_hashes: Vec, stop_hash: BlockHash) -> GetBlocksMessage { + pub fn new( + version: u32, + locator_hashes: Vec, + stop_hash: BlockHash, + ) -> GetBlocksMessage { GetBlocksMessage { version, locator_hashes, stop_hash } } } @@ -135,7 +139,11 @@ impl_consensus_encoding!(GetBlocksMessage, version, locator_hashes, stop_hash); impl GetHeadersMessage { /// Construct a new `getheaders` message - pub fn new(version: u32, locator_hashes: Vec, stop_hash: BlockHash) -> GetHeadersMessage { + pub fn new( + version: u32, + locator_hashes: Vec, + stop_hash: BlockHash, + ) -> GetHeadersMessage { GetHeadersMessage { version, locator_hashes, stop_hash } } } diff --git a/bitcoin/src/p2p/mod.rs b/bitcoin/src/p2p/mod.rs index 988dc0d054..372bf11880 100644 --- a/bitcoin/src/p2p/mod.rs +++ b/bitcoin/src/p2p/mod.rs @@ -29,8 +29,8 @@ use io::{Read, Write}; use crate::consensus::encode::{self, Decodable, Encodable}; use crate::consensus::Params; -use crate::prelude::*; use crate::network::Network; +use crate::prelude::*; #[rustfmt::skip] #[doc(inline)] @@ -234,9 +234,7 @@ impl Magic { pub fn to_bytes(self) -> [u8; 4] { self.0 } /// Returns the magic bytes for the network defined by `params`. - pub fn from_params(params: impl AsRef) -> Self { - params.as_ref().network.into() - } + pub fn from_params(params: impl AsRef) -> Self { params.as_ref().network.into() } } impl FromStr for Magic { diff --git a/bitcoin/src/pow.rs b/bitcoin/src/pow.rs index 3670656a3b..005fbf1de7 100644 --- a/bitcoin/src/pow.rs +++ b/bitcoin/src/pow.rs @@ -19,8 +19,11 @@ use crate::block::Header; use crate::blockdata::block::BlockHash; use crate::consensus::encode::{self, Decodable, Encodable}; use crate::consensus::Params; -use crate::dogecoin::{params::Params as DogecoinParams, Header as DogecoinHeader}; -use crate::error::{ContainsPrefixError, MissingPrefixError, ParseIntError, PrefixedHexError, UnprefixedHexError}; +use crate::dogecoin::params::Params as DogecoinParams; +use crate::dogecoin::Header as DogecoinHeader; +use crate::error::{ + ContainsPrefixError, MissingPrefixError, ParseIntError, PrefixedHexError, UnprefixedHexError, +}; /// Implement traits and methods shared by `Target` and `Work`. macro_rules! do_impl { @@ -324,13 +327,17 @@ impl Target { /// difficulty adjustment period, depending on the height. /// /// Digishield: The target can decrease by 25 % max of the previous target in one adjustment. - /// + /// /// ref: /// /// # Returns /// /// In line with Dogecoin Core this function may return a target value of zero. - pub fn min_transition_threshold_dogecoin(&self, params: impl AsRef, height: u32) -> Self { + pub fn min_transition_threshold_dogecoin( + &self, + params: impl AsRef, + height: u32, + ) -> Self { if params.as_ref().is_digishield_activated(height) { Self(self.0 - (self.0 >> 2)) } else { @@ -365,7 +372,11 @@ impl Target { /// /// We also check that the calculated target is not greater than the maximum allowed target, /// this value is network specific - hence the `params` parameter. - pub fn max_transition_threshold_dogecoin(&self, params: impl AsRef, height: u32) -> Self { + pub fn max_transition_threshold_dogecoin( + &self, + params: impl AsRef, + height: u32, + ) -> Self { let max_attainable = params.as_ref().max_attainable_target; if params.as_ref().is_digishield_activated(height) { cmp::min(Self(self.0 + (self.0 >> 1)), max_attainable) @@ -491,7 +502,7 @@ impl CompactTarget { last: CompactTarget, timespan: i64, params: impl AsRef, - height: u32 + height: u32, ) -> CompactTarget { let params = params.as_ref(); if params.no_pow_retargeting { @@ -501,14 +512,16 @@ impl CompactTarget { // ref: let retarget_timespan = params.pow_target_timespan(height); // Line 44 let mut modulated_timespan = timespan; // Lines 45-46 - if params.is_digishield_activated(height) { // Lines 50-56 + if params.is_digishield_activated(height) { + // Lines 50-56 modulated_timespan = retarget_timespan + (modulated_timespan - retarget_timespan) / 8; // Line 53 let (min_timespan, max_timespan) = ( retarget_timespan - (retarget_timespan >> 2), retarget_timespan + (retarget_timespan >> 1), ); modulated_timespan = modulated_timespan.clamp(min_timespan, max_timespan); // Lines 69-72 - } else { // Lines 57-66 + } else { + // Lines 57-66 let max_timespan = retarget_timespan << 2; let min_timespan = match height { 0..=5_000 => retarget_timespan >> 4, @@ -567,7 +580,7 @@ impl CompactTarget { /// # Note /// /// See [`CompactTarget::from_next_work_required_dogecoin`]. - /// + /// /// Unlike Bitcoin, Dogecoin uses overlapping intervals (see Time Wrap Attack bug fix /// introduced by Litecoin). /// @@ -585,7 +598,7 @@ impl CompactTarget { last_epoch_boundary: DogecoinHeader, current: DogecoinHeader, params: impl AsRef, - height: u32 + height: u32, ) -> CompactTarget { let timespan = (current.time as i64) - (last_epoch_boundary.time as i64); let bits = current.bits; @@ -1949,8 +1962,11 @@ mod tests { #[test] fn compact_target_from_upwards_difficulty_adjustment_using_headers() { - use crate::{block::Version, constants::genesis_block, TxMerkleNode}; use hashes::Hash; + + use crate::block::Version; + use crate::constants::genesis_block; + use crate::TxMerkleNode; let params = Params::new(crate::Network::Signet); let epoch_start = genesis_block(¶ms).header; // Block 2015, the only information used are `bits` and `time` @@ -1960,27 +1976,30 @@ mod tests { merkle_root: TxMerkleNode::all_zeros(), time: 1599332177, bits: epoch_start.bits, - nonce: epoch_start.nonce + nonce: epoch_start.nonce, }; - let adjustment = CompactTarget::from_header_difficulty_adjustment(epoch_start, current, params); + let adjustment = + CompactTarget::from_header_difficulty_adjustment(epoch_start, current, params); let adjustment_bits = CompactTarget::from_consensus(503394215); // Block 2016 compact target assert_eq!(adjustment, adjustment_bits); } #[test] fn compact_target_from_downwards_difficulty_adjustment_using_headers() { - use crate::{block::Version, TxMerkleNode}; use hashes::Hash; + + use crate::block::Version; + use crate::TxMerkleNode; let params = Params::new(crate::Network::Signet); let starting_bits = CompactTarget::from_consensus(503394215); // Block 2016 compact target - // Block 2016, the only information used is `time` + // Block 2016, the only information used is `time` let epoch_start = Header { version: Version::ONE, prev_blockhash: BlockHash::all_zeros(), merkle_root: TxMerkleNode::all_zeros(), time: 1599332844, bits: starting_bits, - nonce: 0 + nonce: 0, }; // Block 4031, the only information used are `bits` and `time` let current = Header { @@ -1989,9 +2008,10 @@ mod tests { merkle_root: TxMerkleNode::all_zeros(), time: 1600591200, bits: starting_bits, - nonce: 0 + nonce: 0, }; - let adjustment = CompactTarget::from_header_difficulty_adjustment(epoch_start, current, params); + let adjustment = + CompactTarget::from_header_difficulty_adjustment(epoch_start, current, params); let adjustment_bits = CompactTarget::from_consensus(503397348); // Block 4032 compact target assert_eq!(adjustment, adjustment_bits); } @@ -2002,9 +2022,8 @@ mod tests { let starting_bits = CompactTarget::from_consensus(503403001); let timespan = (0.2 * params.pow_target_timespan as f64) as u64; let got = CompactTarget::from_next_work_required(starting_bits, timespan, params); - let want = Target::from_compact(starting_bits) - .min_transition_threshold() - .to_compact_lossy(); + let want = + Target::from_compact(starting_bits).min_transition_threshold().to_compact_lossy(); assert_eq!(got, want); } @@ -2012,11 +2031,10 @@ mod tests { fn compact_target_from_minimum_downward_difficulty_adjustment() { let params = Params::new(crate::Network::Signet); let starting_bits = CompactTarget::from_consensus(403403001); // High difficulty for Signet - let timespan = 5 * params.pow_target_timespan; // Really slow. + let timespan = 5 * params.pow_target_timespan; // Really slow. let got = CompactTarget::from_next_work_required(starting_bits, timespan, ¶ms); - let want = Target::from_compact(starting_bits) - .max_transition_threshold(params) - .to_compact_lossy(); + let want = + Target::from_compact(starting_bits).max_transition_threshold(params).to_compact_lossy(); assert_eq!(got, want); } @@ -2024,7 +2042,7 @@ mod tests { fn compact_target_from_adjustment_is_max_target() { let params = Params::new(crate::Network::Signet); let starting_bits = CompactTarget::from_consensus(503543726); // Genesis compact target on Signet - let timespan = 5 * params.pow_target_timespan; // Really slow. + let timespan = 5 * params.pow_target_timespan; // Really slow. let got = CompactTarget::from_next_work_required(starting_bits, timespan, ¶ms); let want = params.max_attainable_target.to_compact_lossy(); assert_eq!(got, want); diff --git a/bitcoin/src/taproot/mod.rs b/bitcoin/src/taproot/mod.rs index f44e318acb..3f4c83b4c4 100644 --- a/bitcoin/src/taproot/mod.rs +++ b/bitcoin/src/taproot/mod.rs @@ -1556,7 +1556,11 @@ mod test { let control_block = ControlBlock::decode(&Vec::::from_hex(control_block_hex).unwrap()).unwrap(); assert_eq!(control_block_hex, control_block.serialize().to_lower_hex_string()); - assert!(control_block.verify_taproot_commitment(secp, out_pk.to_x_only_public_key(), &script)); + assert!(control_block.verify_taproot_commitment( + secp, + out_pk.to_x_only_public_key(), + &script + )); } #[test] diff --git a/bitcoin/tests/psbt-sign-taproot.rs b/bitcoin/tests/psbt-sign-taproot.rs index 4cf7616b7a..78fbcdd601 100644 --- a/bitcoin/tests/psbt-sign-taproot.rs +++ b/bitcoin/tests/psbt-sign-taproot.rs @@ -31,13 +31,12 @@ fn psbt_sign_taproot() { _secp: &Secp256k1, ) -> Result, Self::Error> { match key_request { - KeyRequest::Bip32((mfp, _)) => { + KeyRequest::Bip32((mfp, _)) => if mfp == self.mfp { Ok(Some(self.sk)) } else { Err(SignError::KeyNotFound) - } - } + }, _ => Err(SignError::KeyNotFound), } } diff --git a/io/src/lib.rs b/io/src/lib.rs index 82d51acc7b..e7878625e2 100644 --- a/io/src/lib.rs +++ b/io/src/lib.rs @@ -211,8 +211,7 @@ impl> Read for Cursor { let start_pos = self.pos.try_into().unwrap_or(inner.len()); let read = core::cmp::min(inner.len().saturating_sub(start_pos), buf.len()); buf[..read].copy_from_slice(&inner[start_pos..start_pos + read]); - self.pos = - self.pos.saturating_add(read.try_into().unwrap_or(u64::MAX /* unreachable */)); + self.pos = self.pos.saturating_add(read.try_into().unwrap_or(u64::MAX /* unreachable */)); Ok(read) } } diff --git a/units/src/fee_rate.rs b/units/src/fee_rate.rs index da686fdb23..d3a3bfd157 100644 --- a/units/src/fee_rate.rs +++ b/units/src/fee_rate.rs @@ -175,7 +175,7 @@ mod tests { fn fee_rate_from_sat_per_vb_overflow_test() { let fee_rate = FeeRate::from_sat_per_vb(u64::MAX); assert!(fee_rate.is_none()); - } + } #[test] fn from_sat_per_vb_u32() { @@ -185,7 +185,7 @@ mod tests { #[test] #[cfg(debug_assertions)] - #[allow(deprecated)] // Keep test until we remove the function. + #[allow(deprecated)] // Keep test until we remove the function. #[should_panic] fn from_sat_per_vb_unchecked_panic_test() { FeeRate::from_sat_per_vb_unchecked(u64::MAX); } diff --git a/units/src/lib.rs b/units/src/lib.rs index b2c278795e..393b5ced14 100644 --- a/units/src/lib.rs +++ b/units/src/lib.rs @@ -45,17 +45,14 @@ pub mod parse; #[cfg(feature = "alloc")] pub mod weight; +pub use self::amount::ParseAmountError; #[doc(inline)] pub use self::amount::{Amount, SignedAmount}; -pub use self::amount::ParseAmountError; #[cfg(feature = "alloc")] pub use self::parse::ParseIntError; #[cfg(feature = "alloc")] #[doc(inline)] -pub use self::{ - fee_rate::FeeRate, - weight::Weight, -}; +pub use self::{fee_rate::FeeRate, weight::Weight}; #[rustfmt::skip] #[allow(unused_imports)]