diff --git a/dash/examples/bip32.rs b/dash/examples/bip32.rs index 648c348ef..edbab561b 100644 --- a/dash/examples/bip32.rs +++ b/dash/examples/bip32.rs @@ -3,12 +3,12 @@ extern crate dashcore; use std::str::FromStr; use std::{env, process}; -use dashcore::PublicKey; use dashcore::address::Address; use dashcore::bip32::{ChildNumber, DerivationPath, ExtendedPrivKey, ExtendedPubKey}; use dashcore::hashes::hex::FromHex; -use dashcore::secp256k1::Secp256k1; use dashcore::secp256k1::ffi::types::AlignedType; +use dashcore::secp256k1::Secp256k1; +use dashcore::PublicKey; fn main() { // This example derives root xprv from a 32-byte seed, diff --git a/dash/examples/ecdsa-psbt.rs b/dash/examples/ecdsa-psbt.rs index 171691d7e..7f1d64c28 100644 --- a/dash/examples/ecdsa-psbt.rs +++ b/dash/examples/ecdsa-psbt.rs @@ -124,14 +124,19 @@ impl ColdStorage { let input_xpriv = master_xpriv.derive_priv(secp, &path)?; let input_xpub = ExtendedPubKey::from_priv(secp, &input_xpriv); - let wallet = ColdStorage { master_xpriv, master_xpub }; + let wallet = ColdStorage { + master_xpriv, + master_xpub, + }; let fingerprint = wallet.master_fingerprint(); Ok((wallet, fingerprint, account_0_xpub, input_xpub)) } /// Returns the fingerprint for the master extended public key. - fn master_fingerprint(&self) -> Fingerprint { self.master_xpub.fingerprint() } + fn master_fingerprint(&self) -> Fingerprint { + self.master_xpub.fingerprint() + } /// Signs `psbt` with this signer. fn sign_psbt(&self, secp: &Secp256k1, mut psbt: Psbt) -> Result { @@ -169,7 +174,11 @@ impl WatchOnly { input_xpub: ExtendedPubKey, master_fingerprint: Fingerprint, ) -> Self { - WatchOnly { account_0_xpub, input_xpub, master_fingerprint } + WatchOnly { + account_0_xpub, + input_xpub, + master_fingerprint, + } } /// Creates the PSBT, in BIP174 parlance this is the 'Creater'. @@ -184,13 +193,19 @@ impl WatchOnly { version: 2, lock_time: 0, input: vec![TxIn { - previous_output: OutPoint { txid: INPUT_UTXO_TXID.parse()?, vout: INPUT_UTXO_VOUT }, + previous_output: OutPoint { + txid: INPUT_UTXO_TXID.parse()?, + vout: INPUT_UTXO_VOUT, + }, script_sig: ScriptBuf::new(), sequence: u32::MAX, // Disable LockTime and RBF. witness: Witness::default(), }], output: vec![ - TxOut { value: to_amount.to_sat(), script_pubkey: to_address.script_pubkey() }, + TxOut { + value: to_amount.to_sat(), + script_pubkey: to_address.script_pubkey(), + }, TxOut { value: change_amount.to_sat(), script_pubkey: change_address.script_pubkey(), @@ -206,7 +221,10 @@ impl WatchOnly { /// Updates the PSBT, in BIP174 parlance this is the 'Updater'. fn update_psbt(&self, mut psbt: Psbt) -> Result { - let mut input = Input { witness_utxo: Some(previous_output()), ..Default::default() }; + let mut input = Input { + witness_utxo: Some(previous_output()), + ..Default::default() + }; let pk = self.input_xpub.to_pub(); let wpkh = pk.wpubkey_hash().expect("a compressed pubkey"); @@ -281,15 +299,22 @@ fn previous_output() -> TxOut { .expect("failed to parse input utxo scriptPubkey"); let amount = Amount::from_str(INPUT_UTXO_VALUE).expect("failed to parse input utxo value"); - TxOut { value: amount.to_sat(), script_pubkey } + TxOut { + value: amount.to_sat(), + script_pubkey, + } } struct Error(Box); impl From for Error { - fn from(e: T) -> Self { Error(Box::new(e)) } + fn from(e: T) -> Self { + Error(Box::new(e)) + } } impl fmt::Debug for Error { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&self.0, f) } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, f) + } } diff --git a/dash/examples/handshake.rs b/dash/examples/handshake.rs index 0db4979fb..4ded0077a 100644 --- a/dash/examples/handshake.rs +++ b/dash/examples/handshake.rs @@ -5,7 +5,7 @@ use std::net::{IpAddr, Ipv4Addr, Shutdown, SocketAddr, TcpStream}; use std::time::{SystemTime, UNIX_EPOCH}; use std::{env, process}; -use dashcore::consensus::{Decodable, encode}; +use dashcore::consensus::{encode, Decodable}; use dashcore::network::{address, constants, message, message_network}; use dashcore::secp256k1; use dashcore::secp256k1::rand::Rng; diff --git a/dash/examples/taproot-psbt.rs b/dash/examples/taproot-psbt.rs index ca88d6f0b..42d168e83 100644 --- a/dash/examples/taproot-psbt.rs +++ b/dash/examples/taproot-psbt.rs @@ -88,8 +88,8 @@ use dashcore::secp256k1::Secp256k1; use dashcore::sighash::{self, SighashCache, TapSighash, TapSighashType}; use dashcore::taproot::{self, LeafVersion, TapLeafHash, TaprootBuilder, TaprootSpendInfo}; use dashcore::{ - Address, Amount, Network, OutPoint, ScriptBuf, Transaction, TxIn, TxOut, Witness, absolute, - script, + absolute, script, Address, Amount, Network, OutPoint, ScriptBuf, Transaction, TxIn, TxOut, + Witness, }; fn main() -> Result<(), Box> { @@ -119,8 +119,14 @@ fn main() -> Result<(), Box> { // Set these fields with valid data for the UTXO from step 5 above UTXO_1, vec![ - TxOut { value: amount_to_send_in_sats, script_pubkey: to_address.script_pubkey() }, - TxOut { value: change_amount, script_pubkey: change_address.script_pubkey() }, + TxOut { + value: amount_to_send_in_sats, + script_pubkey: to_address.script_pubkey(), + }, + TxOut { + value: change_amount, + script_pubkey: change_address.script_pubkey(), + }, ], )?); println!( @@ -234,7 +240,10 @@ fn generate_bip86_key_spend_tx( version: 2, lock_time: 0, input: vec![TxIn { - previous_output: OutPoint { txid: input_utxo.txid.parse()?, vout: input_utxo.vout }, + previous_output: OutPoint { + txid: input_utxo.txid.parse()?, + vout: input_utxo.vout, + }, script_sig: ScriptBuf::new(), sequence: 0xFFFFFFFF, // Ignore nSequence. witness: Witness::default(), @@ -262,7 +271,10 @@ fn generate_bip86_key_spend_tx( .expect("failed to parse input utxo scriptPubkey"); let amount = Amount::from_sat(from_amount); - Some(TxOut { value: amount.to_sat(), script_pubkey }) + Some(TxOut { + value: amount.to_sat(), + script_pubkey, + }) }, tap_key_origins: origins, ..Default::default() @@ -380,7 +392,10 @@ impl BenefactorWallet { lock_time: absolute::LockTime, input_utxo: P2trUtxo, ) -> Result<(Transaction, Psbt), Box> { - if let ChildNumber::Normal { index } = self.next { + if let ChildNumber::Normal { + index, + } = self.next + { if index > 0 && self.current_spend_info.is_some() { return Err("Transaction already exists, use refresh_inheritance_timelock to refresh the timelock".into()); } @@ -414,7 +429,10 @@ impl BenefactorWallet { &self.secp, self.master_xpriv, input_utxo, - vec![TxOut { script_pubkey: script_pubkey.clone(), value }], + vec![TxOut { + script_pubkey: script_pubkey.clone(), + value, + }], )?; // CREATOR + UPDATER @@ -422,7 +440,10 @@ impl BenefactorWallet { version: 2, lock_time: lock_time.to_consensus_u32(), input: vec![TxIn { - previous_output: OutPoint { txid: tx.txid(), vout: 0 }, + previous_output: OutPoint { + txid: tx.txid(), + vout: 0, + }, script_sig: ScriptBuf::new(), sequence: 0xFFFFFFFD, // enable locktime and opt-in RBF witness: Witness::default(), @@ -452,7 +473,10 @@ impl BenefactorWallet { let script_pubkey = script_pubkey; let amount = Amount::from_sat(value); - Some(TxOut { value: amount.to_sat(), script_pubkey }) + Some(TxOut { + value: amount.to_sat(), + script_pubkey, + }) }, tap_key_origins: origins, tap_merkle_root: taproot_spend_info.merkle_root(), @@ -509,8 +533,10 @@ impl BenefactorWallet { taproot_spend_info.merkle_root(), ); - psbt.unsigned_tx.output = - vec![TxOut { script_pubkey: output_script_pubkey.clone(), value: output_value }]; + psbt.unsigned_tx.output = vec![TxOut { + script_pubkey: output_script_pubkey.clone(), + value: output_value, + }]; psbt.outputs = vec![Output::default()]; psbt.unsigned_tx.lock_time = 0; @@ -562,7 +588,10 @@ impl BenefactorWallet { // EXTRACTOR let tx = psbt.extract_tx(); tx.verify(|_| { - Some(TxOut { value: input_value, script_pubkey: output_script_pubkey.clone() }) + Some(TxOut { + value: input_value, + script_pubkey: output_script_pubkey.clone(), + }) }) .expect("failed to verify transaction"); @@ -570,7 +599,10 @@ impl BenefactorWallet { version: 2, lock_time: lock_time.to_consensus_u32(), input: vec![TxIn { - previous_output: OutPoint { txid: tx.txid(), vout: 0 }, + previous_output: OutPoint { + txid: tx.txid(), + vout: 0, + }, script_sig: ScriptBuf::new(), sequence: 0xFFFFFFFD, // enable locktime and opt-in RBF witness: Witness::default(), @@ -598,7 +630,10 @@ impl BenefactorWallet { let script_pubkey = output_script_pubkey; let amount = Amount::from_sat(output_value); - Some(TxOut { value: amount.to_sat(), script_pubkey }) + Some(TxOut { + value: amount.to_sat(), + script_pubkey, + }) }, tap_key_origins: origins, tap_merkle_root: taproot_spend_info.merkle_root(), @@ -628,7 +663,10 @@ struct BeneficiaryWallet { impl BeneficiaryWallet { fn new(master_xpriv: ExtendedPrivKey) -> Result> { - Ok(Self { master_xpriv, secp: Secp256k1::new() }) + Ok(Self { + master_xpriv, + secp: Secp256k1::new(), + }) } fn master_xpub(&self) -> ExtendedPubKey { @@ -707,7 +745,10 @@ impl BeneficiaryWallet { // EXTRACTOR let tx = psbt.extract_tx(); tx.verify(|_| { - Some(TxOut { value: input_value, script_pubkey: input_script_pubkey.clone() }) + Some(TxOut { + value: input_value, + script_pubkey: input_script_pubkey.clone(), + }) }) .expect("failed to verify transaction"); @@ -746,7 +787,10 @@ fn sign_psbt_taproot( let sig = secp.sign_schnorr(&hash.into(), &keypair); - let final_signature = taproot::Signature { sig, hash_ty }; + let final_signature = taproot::Signature { + sig, + hash_ty, + }; if let Some(lh) = leaf_hash { psbt_input.tap_script_sigs.insert((pubkey, lh), final_signature); diff --git a/dash/src/address.rs b/dash/src/address.rs index 889c5b5de..c854cd397 100644 --- a/dash/src/address.rs +++ b/dash/src/address.rs @@ -47,7 +47,7 @@ use core::marker::PhantomData; use core::str::FromStr; use bech32; -use hashes::{Hash, HashEngine, sha256}; +use hashes::{sha256, Hash, HashEngine}; use internals::write_err; use secp256k1::{Secp256k1, Verification, XOnlyPublicKey}; @@ -149,7 +149,9 @@ impl std::error::Error for Error { Bech32(e) => Some(e), UnparsableWitnessVersion(e) => Some(e), EmptyBech32Payload - | InvalidBech32Variant { .. } + | InvalidBech32Variant { + .. + } | InvalidWitnessVersion(_) | MalformedWitnessVersion | InvalidWitnessProgramLength(_) @@ -158,19 +160,25 @@ impl std::error::Error for Error { | ExcessiveScriptSize | UnrecognizedScript | UnknownAddressType(_) - | NetworkValidation { .. } => None, + | NetworkValidation { + .. + } => None, } } } #[doc(hidden)] impl From for Error { - fn from(e: base58::Error) -> Error { Error::Base58(e) } + fn from(e: base58::Error) -> Error { + Error::Base58(e) + } } #[doc(hidden)] impl From for Error { - fn from(e: bech32::Error) -> Error { Error::Bech32(e) } + fn from(e: bech32::Error) -> Error { + Error::Bech32(e) + } } /// The different types of addresses. @@ -282,7 +290,9 @@ impl WitnessVersion { /// NB: this is not the same as an integer representation of the opcode signifying witness /// version in dashcore script. Thus, there is no function to directly convert witness version /// into a byte since the conversion requires context (dashcore script or just a version number). - pub fn to_num(self) -> u8 { self as u8 } + pub fn to_num(self) -> u8 { + self as u8 + } /// Determines the checksum variant. See BIP-0350 for specification. pub fn bech32_variant(&self) -> bech32::Variant { @@ -305,7 +315,9 @@ impl TryFrom for WitnessVersion { /// # Errors /// If the integer does not correspond to any witness version, errors with /// [`Error::InvalidWitnessVersion`]. - fn try_from(value: bech32::u5) -> Result { Self::try_from(value.to_u8()) } + fn try_from(value: bech32::u5) -> Result { + Self::try_from(value.to_u8()) + } } impl TryFrom for WitnessVersion { @@ -359,8 +371,9 @@ impl TryFrom for WitnessVersion { fn try_from(opcode: opcodes::All) -> Result { match opcode.to_u8() { 0 => Ok(WitnessVersion::V0), - version if version >= OP_PUSHNUM_1.to_u8() && version <= OP_PUSHNUM_16.to_u8() => - WitnessVersion::try_from(version - OP_PUSHNUM_1.to_u8() + 1), + version if version >= OP_PUSHNUM_1.to_u8() && version <= OP_PUSHNUM_16.to_u8() => { + WitnessVersion::try_from(version - OP_PUSHNUM_1.to_u8() + 1) + } _ => Err(Error::MalformedWitnessVersion), } } @@ -407,7 +420,9 @@ impl From for opcodes::All { /// Prints [`WitnessVersion`] number (from 0 to 16) as integer, without /// any prefix or suffix. impl fmt::Display for WitnessVersion { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", *self as u8) } + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "{}", *self as u8) + } } /// The method used to produce an address. @@ -449,14 +464,21 @@ impl WitnessProgram { if version == WitnessVersion::V0 && (program.len() != 20 && program.len() != 32) { return Err(Error::InvalidSegwitV0ProgramLength(program.len())); } - Ok(WitnessProgram { version, program }) + Ok(WitnessProgram { + version, + program, + }) } /// Returns the witness program version. - pub fn version(&self) -> WitnessVersion { self.version } + pub fn version(&self) -> WitnessVersion { + self.version + } /// Returns the witness program. - pub fn program(&self) -> &PushBytes { &self.program } + pub fn program(&self) -> &PushBytes { + &self.program + } } impl Payload { @@ -494,19 +516,24 @@ impl Payload { /// This function doesn't make any allocations. pub fn matches_script_pubkey(&self, script: &Script) -> bool { match *self { - Payload::PubkeyHash(ref hash) if script.is_p2pkh() => - &script.as_bytes()[3..23] == >::as_ref(hash), - Payload::ScriptHash(ref hash) if script.is_p2sh() => - &script.as_bytes()[2..22] == >::as_ref(hash), - Payload::WitnessProgram(ref prog) if script.is_witness_program() => - &script.as_bytes()[2..] == prog.program.as_bytes(), + Payload::PubkeyHash(ref hash) if script.is_p2pkh() => { + &script.as_bytes()[3..23] == >::as_ref(hash) + } + Payload::ScriptHash(ref hash) if script.is_p2sh() => { + &script.as_bytes()[2..22] == >::as_ref(hash) + } + Payload::WitnessProgram(ref prog) if script.is_witness_program() => { + &script.as_bytes()[2..] == prog.program.as_bytes() + } Payload::PubkeyHash(_) | Payload::ScriptHash(_) | Payload::WitnessProgram(_) => false, } } /// Creates a pay to (compressed) public key hash payload from a public key #[inline] - pub fn p2pkh(pk: &PublicKey) -> Payload { Payload::PubkeyHash(pk.pubkey_hash()) } + pub fn p2pkh(pk: &PublicKey) -> Payload { + Payload::PubkeyHash(pk.pubkey_hash()) + } /// Creates a pay to script hash P2SH payload from a script #[inline] @@ -774,7 +801,9 @@ struct DisplayUnchecked<'a>(&'a Address); #[cfg(feature = "serde")] impl fmt::Display for DisplayUnchecked<'_> { - fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { self.0.fmt_internal(fmt) } + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + self.0.fmt_internal(fmt) + } } #[cfg(feature = "serde")] @@ -797,10 +826,14 @@ impl serde::Serialize for Address { /// `Address`. impl Address { /// Returns a reference to the payload of this address. - pub fn payload(&self) -> &Payload { &self.0.payload } + pub fn payload(&self) -> &Payload { + &self.0.payload + } /// Returns a reference to the network of this address. - pub fn network(&self) -> &Network { &self.0.network } + pub fn network(&self) -> &Network { + &self.0.network + } /// Returns a reference to the unchecked address, which is dangerous to use if the address /// is invalid in the context of `NetworkUnchecked`. @@ -810,7 +843,10 @@ impl Address { /// Extracts and returns the network and payload components of the `Address`. pub fn into_parts(self) -> (Network, Payload) { - let AddressInner { payload, network } = self.0; + let AddressInner { + payload, + network, + } = self.0; (network, payload) } @@ -858,8 +894,12 @@ impl Address { Network::Testnet | Network::Devnet => "tb", Network::Regtest => "dsrt", }; - let encoding = - AddressEncoding { payload: self.payload(), p2pkh_prefix, p2sh_prefix, bech32_hrp }; + let encoding = AddressEncoding { + payload: self.payload(), + p2pkh_prefix, + p2sh_prefix, + bech32_hrp, + }; use fmt::Display; @@ -870,7 +910,13 @@ impl Address { /// marker type of the address. #[inline] pub fn new(network: Network, payload: Payload) -> Self { - Self(AddressInner { network, payload }, PhantomData) + Self( + AddressInner { + network, + payload, + }, + PhantomData, + ) } } @@ -947,7 +993,9 @@ impl Address { /// # Returns /// None if unknown, non-standard or related to the future witness version. #[inline] - pub fn address_type(&self) -> Option { self.address_type_internal() } + pub fn address_type(&self) -> Option { + self.address_type_internal() + } /// Checks whether or not the address is following Dash standardness rules when /// *spending* from this address. *NOT* to be called by senders. @@ -962,14 +1010,18 @@ impl Address { /// considered non-standard. /// /// - pub fn is_spend_standard(&self) -> bool { self.address_type().is_some() } + pub fn is_spend_standard(&self) -> bool { + self.address_type().is_some() + } /// Checks whether or not the address is following Dash standardness rules. /// /// SegWit addresses with unassigned witness versions or non-standard program sizes are /// considered non-standard. #[deprecated(since = "0.30.0", note = "Use Address::is_spend_standard instead")] - pub fn is_standard(&self) -> bool { self.address_type().is_some() } + pub fn is_standard(&self) -> bool { + self.address_type().is_some() + } /// Constructs an [`Address`] from an output script (`scriptPubkey`). pub fn from_script(script: &ScriptBuf, network: Network) -> Result { @@ -977,7 +1029,9 @@ impl Address { } /// Generates a script pubkey spending to this address. - pub fn script_pubkey(&self) -> ScriptBuf { self.payload().script_pubkey() } + pub fn script_pubkey(&self) -> ScriptBuf { + self.payload().script_pubkey() + } /// Creates a URI string *dashcore:address* optimized to be encoded in QR codes. /// @@ -1008,7 +1062,9 @@ impl Address { /// ``` pub fn to_qr_uri(&self) -> String { let schema = match self.payload() { - Payload::WitnessProgram { .. } => "DASH", + Payload::WitnessProgram { + .. + } => "DASH", _ => "dash", }; format!("{}:{:#}", schema, self) @@ -1096,7 +1152,11 @@ impl Address { if self.is_valid_for_network(required) { Ok(self.assume_checked()) } else { - Err(Error::NetworkValidation { found: *self.network(), required, address: self }) + Err(Error::NetworkValidation { + found: *self.network(), + required, + address: self, + }) } } @@ -1113,7 +1173,9 @@ impl Address { } /// Returns the payload as a vector. - pub fn payload_to_vec(&self) -> Vec { self.0.payload.inner_prog_as_bytes().to_vec() } + pub fn payload_to_vec(&self) -> Vec { + self.0.payload.inner_prog_as_bytes().to_vec() + } } // For NetworkUnchecked , it compare Addresses and if network and payload matches then return true. @@ -1124,17 +1186,23 @@ impl PartialEq> for Address { } impl PartialEq
for Address { - fn eq(&self, other: &Address) -> bool { other == self } + fn eq(&self, other: &Address) -> bool { + other == self + } } 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 { self.fmt_internal(fmt) } + fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { + self.fmt_internal(fmt) + } } impl fmt::Debug for Address { @@ -1180,7 +1248,10 @@ impl FromStr for Address { // Encoding check let expected = version.bech32_variant(); if expected != variant { - return Err(Error::InvalidBech32Variant { expected, found: variant }); + return Err(Error::InvalidBech32Variant { + expected, + found: variant, + }); } return Ok(Address::new(network, Payload::WitnessProgram(witness_program))); @@ -1196,14 +1267,18 @@ impl FromStr for Address { } let (network, payload) = match data[0] { - PUBKEY_ADDRESS_PREFIX_MAIN => - (Network::Dash, Payload::PubkeyHash(PubkeyHash::from_slice(&data[1..]).unwrap())), - SCRIPT_ADDRESS_PREFIX_MAIN => - (Network::Dash, Payload::ScriptHash(ScriptHash::from_slice(&data[1..]).unwrap())), - PUBKEY_ADDRESS_PREFIX_TEST => - (Network::Testnet, Payload::PubkeyHash(PubkeyHash::from_slice(&data[1..]).unwrap())), - SCRIPT_ADDRESS_PREFIX_TEST => - (Network::Testnet, Payload::ScriptHash(ScriptHash::from_slice(&data[1..]).unwrap())), + PUBKEY_ADDRESS_PREFIX_MAIN => { + (Network::Dash, Payload::PubkeyHash(PubkeyHash::from_slice(&data[1..]).unwrap())) + } + SCRIPT_ADDRESS_PREFIX_MAIN => { + (Network::Dash, Payload::ScriptHash(ScriptHash::from_slice(&data[1..]).unwrap())) + } + PUBKEY_ADDRESS_PREFIX_TEST => { + (Network::Testnet, Payload::PubkeyHash(PubkeyHash::from_slice(&data[1..]).unwrap())) + } + SCRIPT_ADDRESS_PREFIX_TEST => { + (Network::Testnet, Payload::ScriptHash(ScriptHash::from_slice(&data[1..]).unwrap())) + } x => return Err(Error::Base58(base58::Error::InvalidAddressVersion(x))), }; @@ -1448,12 +1523,22 @@ mod tests { let unchecked = Address::from_str(addr_str).unwrap(); assert_eq!( - format!("{:?}", Test { address: unchecked.clone() }), + format!( + "{:?}", + Test { + address: unchecked.clone() + } + ), format!("Test {{ address: Address({}) }}", addr_str) ); assert_eq!( - format!("{:?}", Test { address: unchecked.assume_checked() }), + format!( + "{:?}", + Test { + address: unchecked.assume_checked() + } + ), format!("Test {{ address: {} }}", addr_str) ); } diff --git a/dash/src/amount.rs b/dash/src/amount.rs index 14b310212..1863e0e9e 100644 --- a/dash/src/amount.rs +++ b/dash/src/amount.rs @@ -94,8 +94,9 @@ impl Denomination { "nBTC" | "nbtc" => Some(Denomination::NanoDash), "pBTC" | "pbtc" => Some(Denomination::PicoDash), "bit" | "bits" | "BIT" | "BITS" => Some(Denomination::Bit), - "SATOSHI" | "satoshi" | "SATOSHIS" | "satoshis" | "SAT" | "sat" | "SATS" | "sats" => - Some(Denomination::Satoshi), + "SATOSHI" | "satoshi" | "SATOSHIS" | "satoshis" | "SAT" | "sat" | "SATS" | "sats" => { + Some(Denomination::Satoshi) + } "mSAT" | "msat" | "mSATs" | "msats" => Some(Denomination::MilliSatoshi), _ => None, } @@ -108,7 +109,9 @@ const CONFUSING_FORMS: [&str; 9] = ["Msat", "Msats", "MSAT", "MSATS", "MSat", "MSats", "MBTC", "Mbtc", "PBTC"]; impl fmt::Display for Denomination { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str(self.as_str()) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.write_str(self.as_str()) + } } impl FromStr for Denomination { @@ -351,7 +354,9 @@ fn dec_width(mut num: u64) -> usize { } // NIH due to MSRV, impl copied from `core::i8::unsigned_abs` (introduced in Rust 1.51.1). -fn unsigned_abs(x: i8) -> u8 { x.wrapping_abs() as u8 } +fn unsigned_abs(x: i8) -> u8 { + x.wrapping_abs() as u8 +} fn repeat_char(f: &mut dyn fmt::Write, c: char, count: usize) -> fmt::Result { for _ in 0..count { @@ -432,8 +437,9 @@ fn fmt_satoshi_in( (true, true, _) | (true, false, fmt::Alignment::Right) => (width - num_width, 0), (true, false, fmt::Alignment::Left) => (0, width - num_width), // If the required padding is odd it needs to be skewed to the left - (true, false, fmt::Alignment::Center) => - ((width - num_width) / 2, (width - num_width + 1) / 2), + (true, false, fmt::Alignment::Center) => { + ((width - num_width) / 2, (width - num_width + 1) / 2) + } }; if !options.sign_aware_zero_pad { @@ -501,16 +507,24 @@ impl Amount { pub const MAX_MONEY: Amount = Amount(21_000_000 * 100_000_000); /// Create an [Amount] with satoshi precision and the given number of satoshis. - pub const fn from_sat(satoshi: u64) -> Amount { Amount(satoshi) } + pub const fn from_sat(satoshi: u64) -> Amount { + Amount(satoshi) + } /// Gets the number of satoshis in this [`Amount`]. - pub fn to_sat(self) -> u64 { self.0 } + pub fn to_sat(self) -> u64 { + self.0 + } /// The maximum value of an [Amount]. - pub const fn max_value() -> Amount { Amount(u64::MAX) } + pub const fn max_value() -> Amount { + Amount(u64::MAX) + } /// The minimum value of an [Amount]. - pub const fn min_value() -> Amount { Amount(u64::MIN) } + pub const fn min_value() -> Amount { + Amount(u64::MIN) + } /// Convert from a value expressing bitcoins to an [Amount]. pub fn from_btc(btc: f64) -> Result { @@ -558,7 +572,9 @@ impl Amount { /// let amount = Amount::from_sat(100_000); /// assert_eq!(amount.to_dash(), amount.to_float_in(Denomination::Dash)) /// ``` - pub fn to_dash(self) -> f64 { self.to_float_in(Denomination::Dash) } + pub fn to_dash(self) -> f64 { + self.to_float_in(Denomination::Dash) + } /// Convert this [Amount] in floating-point notation with a given /// denomination. @@ -579,7 +595,10 @@ impl Amount { Display { sats_abs: self.to_sat(), is_negative: false, - style: DisplayStyle::FixedDenomination { denomination, show_denomination: false }, + style: DisplayStyle::FixedDenomination { + denomination, + show_denomination: false, + }, } } @@ -637,17 +656,23 @@ impl Amount { /// Checked multiplication. /// Returns [None] if overflow occurred. - pub fn checked_mul(self, rhs: u64) -> Option { self.0.checked_mul(rhs).map(Amount) } + pub fn checked_mul(self, rhs: u64) -> Option { + self.0.checked_mul(rhs).map(Amount) + } /// Checked integer division. /// Be aware that integer division loses the remainder if no exact division /// can be made. /// Returns [None] if overflow occurred. - pub fn checked_div(self, rhs: u64) -> Option { self.0.checked_div(rhs).map(Amount) } + pub fn checked_div(self, rhs: u64) -> Option { + self.0.checked_div(rhs).map(Amount) + } /// Checked remainder. /// Returns [None] if overflow occurred. - pub fn checked_rem(self, rhs: u64) -> Option { self.0.checked_rem(rhs).map(Amount) } + pub fn checked_rem(self, rhs: u64) -> Option { + self.0.checked_rem(rhs).map(Amount) + } /// Convert to a signed amount. pub fn to_signed(self) -> Result { @@ -660,7 +685,9 @@ impl Amount { } impl default::Default for Amount { - fn default() -> Self { Amount::ZERO } + fn default() -> Self { + Amount::ZERO + } } impl fmt::Debug for Amount { @@ -687,7 +714,9 @@ impl ops::Add for Amount { } impl ops::AddAssign for Amount { - fn add_assign(&mut self, other: Amount) { *self = *self + other } + fn add_assign(&mut self, other: Amount) { + *self = *self + other + } } impl ops::Sub for Amount { @@ -699,7 +728,9 @@ impl ops::Sub for Amount { } impl ops::SubAssign for Amount { - fn sub_assign(&mut self, other: Amount) { *self = *self - other } + fn sub_assign(&mut self, other: Amount) { + *self = *self - other + } } impl ops::Rem for Amount { @@ -711,7 +742,9 @@ impl ops::Rem for Amount { } impl ops::RemAssign for Amount { - fn rem_assign(&mut self, modulus: u64) { *self = *self % modulus } + fn rem_assign(&mut self, modulus: u64) { + *self = *self % modulus + } } impl ops::Mul for Amount { @@ -723,23 +756,31 @@ impl ops::Mul for Amount { } impl ops::MulAssign for Amount { - fn mul_assign(&mut self, rhs: u64) { *self = *self * rhs } + fn mul_assign(&mut self, rhs: u64) { + *self = *self * rhs + } } impl ops::Div for Amount { type Output = Amount; - fn div(self, rhs: u64) -> Self::Output { self.checked_div(rhs).expect("Amount division error") } + fn div(self, rhs: u64) -> Self::Output { + self.checked_div(rhs).expect("Amount division error") + } } impl ops::DivAssign for Amount { - fn div_assign(&mut self, rhs: u64) { *self = *self / rhs } + fn div_assign(&mut self, rhs: u64) { + *self = *self / rhs + } } impl FromStr for Amount { type Err = ParseAmountError; - fn from_str(s: &str) -> Result { Amount::from_str_with_denomination(s) } + fn from_str(s: &str) -> Result { + Amount::from_str_with_denomination(s) + } } impl core::iter::Sum for Amount { @@ -776,7 +817,10 @@ impl Display { /// Makes subsequent calls to `Display::fmt` display denomination. pub fn show_denomination(mut self) -> Self { match &mut self.style { - DisplayStyle::FixedDenomination { show_denomination, .. } => *show_denomination = true, + DisplayStyle::FixedDenomination { + show_denomination, + .. + } => *show_denomination = true, // No-op because dynamic denomination is always shown DisplayStyle::DynamicDenomination => (), } @@ -804,7 +848,10 @@ impl fmt::Display for Display { #[derive(Clone, Debug)] enum DisplayStyle { - FixedDenomination { denomination: Denomination, show_denomination: bool }, + FixedDenomination { + denomination: Denomination, + show_denomination: bool, + }, DynamicDenomination, } @@ -836,16 +883,24 @@ impl SignedAmount { pub const MAX_MONEY: SignedAmount = SignedAmount(21_000_000 * 100_000_000); /// Create an [SignedAmount] with satoshi precision and the given number of satoshis. - pub const fn from_sat(satoshi: i64) -> SignedAmount { SignedAmount(satoshi) } + pub const fn from_sat(satoshi: i64) -> SignedAmount { + SignedAmount(satoshi) + } /// Gets the number of satoshis in this [`SignedAmount`]. - pub fn to_sat(self) -> i64 { self.0 } + pub fn to_sat(self) -> i64 { + self.0 + } /// The maximum value of an [SignedAmount]. - pub const fn max_value() -> SignedAmount { SignedAmount(i64::MAX) } + pub const fn max_value() -> SignedAmount { + SignedAmount(i64::MAX) + } /// The minimum value of an [SignedAmount]. - pub const fn min_value() -> SignedAmount { SignedAmount(i64::MIN) } + pub const fn min_value() -> SignedAmount { + SignedAmount(i64::MIN) + } /// Convert from a value expressing bitcoins to an [SignedAmount]. pub fn from_btc(btc: f64) -> Result { @@ -888,7 +943,9 @@ impl SignedAmount { /// Equivalent to `to_float_in(Denomination::Bitcoin)`. /// /// Please be aware of the risk of using floating-point numbers. - pub fn to_btc(self) -> f64 { self.to_float_in(Denomination::Dash) } + pub fn to_btc(self) -> f64 { + self.to_float_in(Denomination::Dash) + } /// Convert this [SignedAmount] in floating-point notation with a given /// denomination. @@ -907,14 +964,19 @@ impl SignedAmount { /// Returns the absolute value as satoshis. /// /// This is the implementation of `unsigned_abs()` copied from `core` to support older MSRV. - fn to_sat_abs(self) -> u64 { self.to_sat().wrapping_abs() as u64 } + fn to_sat_abs(self) -> u64 { + self.to_sat().wrapping_abs() as u64 + } /// Create an object that implements [`fmt::Display`] using specified denomination. pub fn display_in(self, denomination: Denomination) -> Display { Display { sats_abs: self.to_sat_abs(), is_negative: self.is_negative(), - style: DisplayStyle::FixedDenomination { denomination, show_denomination: false }, + style: DisplayStyle::FixedDenomination { + denomination, + show_denomination: false, + }, } } @@ -959,26 +1021,36 @@ impl SignedAmount { // Some arithmetic that doesn't fit in `core::ops` traits. /// Get the absolute value of this [SignedAmount]. - pub fn abs(self) -> SignedAmount { SignedAmount(self.0.abs()) } + pub fn abs(self) -> SignedAmount { + SignedAmount(self.0.abs()) + } /// Returns a number representing sign of this [SignedAmount]. /// /// - `0` if the amount is zero /// - `1` if the amount is positive /// - `-1` if the amount is negative - pub fn signum(self) -> i64 { self.0.signum() } + pub fn signum(self) -> i64 { + self.0.signum() + } /// Returns `true` if this [SignedAmount] is positive and `false` if /// this [SignedAmount] is zero or negative. - pub fn is_positive(self) -> bool { self.0.is_positive() } + pub fn is_positive(self) -> bool { + self.0.is_positive() + } /// Returns `true` if this [SignedAmount] is negative and `false` if /// this [SignedAmount] is zero or positive. - pub fn is_negative(self) -> bool { self.0.is_negative() } + pub fn is_negative(self) -> bool { + self.0.is_negative() + } /// Get the absolute value of this [SignedAmount]. /// Returns [None] if overflow occurred. (`self == min_value()`) - pub fn checked_abs(self) -> Option { self.0.checked_abs().map(SignedAmount) } + pub fn checked_abs(self) -> Option { + self.0.checked_abs().map(SignedAmount) + } /// Checked addition. /// Returns [None] if overflow occurred. @@ -1033,7 +1105,9 @@ impl SignedAmount { } impl default::Default for SignedAmount { - fn default() -> Self { SignedAmount::ZERO } + fn default() -> Self { + SignedAmount::ZERO + } } impl fmt::Debug for SignedAmount { @@ -1060,7 +1134,9 @@ impl ops::Add for SignedAmount { } impl ops::AddAssign for SignedAmount { - fn add_assign(&mut self, other: SignedAmount) { *self = *self + other } + fn add_assign(&mut self, other: SignedAmount) { + *self = *self + other + } } impl ops::Sub for SignedAmount { @@ -1072,7 +1148,9 @@ impl ops::Sub for SignedAmount { } impl ops::SubAssign for SignedAmount { - fn sub_assign(&mut self, other: SignedAmount) { *self = *self - other } + fn sub_assign(&mut self, other: SignedAmount) { + *self = *self - other + } } impl ops::Rem for SignedAmount { @@ -1084,7 +1162,9 @@ impl ops::Rem for SignedAmount { } impl ops::RemAssign for SignedAmount { - fn rem_assign(&mut self, modulus: i64) { *self = *self % modulus } + fn rem_assign(&mut self, modulus: i64) { + *self = *self % modulus + } } impl ops::Mul for SignedAmount { @@ -1096,7 +1176,9 @@ impl ops::Mul for SignedAmount { } impl ops::MulAssign for SignedAmount { - fn mul_assign(&mut self, rhs: i64) { *self = *self * rhs } + fn mul_assign(&mut self, rhs: i64) { + *self = *self * rhs + } } impl ops::Div for SignedAmount { @@ -1108,13 +1190,17 @@ impl ops::Div for SignedAmount { } impl ops::DivAssign for SignedAmount { - fn div_assign(&mut self, rhs: i64) { *self = *self / rhs } + fn div_assign(&mut self, rhs: i64) { + *self = *self / rhs + } } impl FromStr for SignedAmount { type Err = ParseAmountError; - fn from_str(s: &str) -> Result { SignedAmount::from_str_with_denomination(s) } + fn from_str(s: &str) -> Result { + SignedAmount::from_str_with_denomination(s) + } } impl core::iter::Sum for SignedAmount { @@ -1230,7 +1316,9 @@ pub mod serde { } impl SerdeAmountForOpt for Amount { - fn type_prefix() -> &'static str { "u" } + fn type_prefix() -> &'static str { + "u" + } fn ser_sat_opt(self, s: S) -> Result { s.serialize_some(&self.to_sat()) } @@ -1256,7 +1344,9 @@ pub mod serde { } impl SerdeAmountForOpt for SignedAmount { - fn type_prefix() -> &'static str { "i" } + fn type_prefix() -> &'static str { + "i" + } fn ser_sat_opt(self, s: S) -> Result { s.serialize_some(&self.to_sat()) } @@ -1288,7 +1378,7 @@ pub mod serde { use core::fmt; use core::marker::PhantomData; - use serde::{Deserializer, Serializer, de}; + use serde::{de, Deserializer, Serializer}; use crate::amount::serde::SerdeAmountForOpt; @@ -1355,7 +1445,7 @@ pub mod serde { use core::fmt; use core::marker::PhantomData; - use serde::{Deserializer, Serializer, de}; + use serde::{de, Deserializer, Serializer}; use crate::amount::serde::SerdeAmountForOpt; @@ -2070,9 +2160,15 @@ mod tests { } serde_test::assert_tokens( - &T { amt: Amount::from_sat(123456789), samt: SignedAmount::from_sat(-123456789) }, + &T { + amt: Amount::from_sat(123456789), + samt: SignedAmount::from_sat(-123456789), + }, &[ - serde_test::Token::Struct { name: "T", len: 2 }, + serde_test::Token::Struct { + name: "T", + len: 2, + }, serde_test::Token::Str("amt"), serde_test::Token::U64(123456789), serde_test::Token::Str("samt"), @@ -2137,7 +2233,10 @@ mod tests { amt: Some(Amount::from_sat(2_500_000_00)), samt: Some(SignedAmount::from_sat(-2_500_000_00)), }; - let without = T { amt: None, samt: None }; + let without = T { + amt: None, + samt: None, + }; // Test Roundtripping for s in [&with, &without].iter() { @@ -2179,7 +2278,10 @@ mod tests { amt: Some(Amount::from_sat(2_500_000_00)), samt: Some(SignedAmount::from_sat(-2_500_000_00)), }; - let without = T { amt: None, samt: None }; + let without = T { + amt: None, + samt: None, + }; // Test Roundtripping for s in [&with, &without].iter() { diff --git a/dash/src/base58.rs b/dash/src/base58.rs index 38dd87fbe..4e1f9a2cc 100644 --- a/dash/src/base58.rs +++ b/dash/src/base58.rs @@ -23,7 +23,7 @@ use core::{fmt, iter, slice, str}; -use hashes::{Hash, hex, sha256d}; +use hashes::{hex, sha256d, Hash}; use secp256k1; use crate::key; @@ -102,7 +102,11 @@ struct SmallVec { impl SmallVec { pub fn new() -> SmallVec { - SmallVec { len: 0, stack: [T::default(); 100], heap: Vec::new() } + SmallVec { + len: 0, + stack: [T::default(); 100], + heap: Vec::new(), + } } pub fn push(&mut self, val: T) { @@ -259,7 +263,9 @@ static BASE58_DIGITS: [Option; 128] = [ ]; /// Decode base58-encoded string into a byte vector -pub fn from(data: &str) -> Result, Error> { decode(data) } +pub fn from(data: &str) -> Result, Error> { + decode(data) +} /// Decodes a base58-encoded string into a byte vector. pub fn decode(data: &str) -> Result, Error> { @@ -294,7 +300,9 @@ pub fn decode(data: &str) -> Result, Error> { /// Decodes a base58check-encoded string into a byte vector verifying the checksum. #[deprecated(since = "0.30.0", note = "Use base58::decode_check() instead")] -pub fn from_check(data: &str) -> Result, Error> { decode_check(data) } +pub fn from_check(data: &str) -> Result, Error> { + decode_check(data) +} /// Decodes a base58check-encoded string into a byte vector verifying the checksum. pub fn decode_check(data: &str) -> Result, Error> { @@ -370,7 +378,9 @@ where } /// Directly encode a slice as base58 -pub fn encode_slice(data: &[u8]) -> String { encode_iter(data.iter().cloned()) } +pub fn encode_slice(data: &[u8]) -> String { + encode_iter(data.iter().cloned()) +} /// Encodes `data` as a base58 string including the checksum. /// @@ -445,7 +455,8 @@ mod tests { coinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoinBitcoin" .as_bytes(), ); - let exp = "ZqC5ZdfpZRi7fjA8hbhX5pEE96MdH9hEaC1YouxscPtbJF16qVWksHWR4wwvx7MotFcs2ChbJqK8KJ9X\ + let exp = + "ZqC5ZdfpZRi7fjA8hbhX5pEE96MdH9hEaC1YouxscPtbJF16qVWksHWR4wwvx7MotFcs2ChbJqK8KJ9X\ wZznwWn1JFDhhTmGo9v6GjAVikzCsBWZehu7bm22xL8b5zBR5AsBygYRwbFJsNwNkjpyFuDKwmsUTKvkULCvucPJrN5\ QUdxpGakhqkZFL7RU4yT"; assert_eq!(&res, exp); diff --git a/dash/src/bip152.rs b/dash/src/bip152.rs index a4f8a6c7e..0777850ed 100644 --- a/dash/src/bip152.rs +++ b/dash/src/bip152.rs @@ -10,13 +10,13 @@ use core::{convert, fmt, mem}; #[cfg(feature = "std")] use std::error; -use hashes::{Hash, sha256, siphash24}; +use hashes::{sha256, siphash24, Hash}; use internals::impl_array_newtype; use crate::consensus::encode::{self, Decodable, Encodable, VarInt}; use crate::internal_macros::{impl_bytes_newtype, impl_consensus_encoding}; use crate::prelude::*; -use crate::{Block, BlockHash, Transaction, block, io}; +use crate::{block, io, Block, BlockHash, Transaction}; /// A BIP-152 error #[derive(Clone, PartialEq, Eq, Debug, Copy, PartialOrd, Ord, Hash)] @@ -68,7 +68,9 @@ pub struct PrefilledTransaction { } impl convert::AsRef for PrefilledTransaction { - fn as_ref(&self) -> &Transaction { &self.tx } + fn as_ref(&self) -> &Transaction { + &self.tx + } } impl Encodable for PrefilledTransaction { @@ -87,7 +89,10 @@ impl Decodable for PrefilledTransaction { let idx = u16::try_from(idx) .map_err(|_| encode::Error::ParseFailed("BIP152 prefilled tx index out of bounds"))?; let tx = Transaction::consensus_decode(&mut d)?; - Ok(PrefilledTransaction { idx, tx }) + Ok(PrefilledTransaction { + idx, + tx, + }) } } @@ -376,10 +381,10 @@ mod test { use super::*; use crate::blockdata::locktime::absolute; use crate::blockdata::script::ScriptBuf; - use crate::blockdata::transaction::Transaction; use crate::blockdata::transaction::outpoint::OutPoint; use crate::blockdata::transaction::txin::TxIn; use crate::blockdata::transaction::txout::TxOut; + use crate::blockdata::transaction::Transaction; use crate::blockdata::witness::Witness; use crate::consensus::encode::{deserialize, serialize}; use crate::hash_types::{TxMerkleNode, Txid}; @@ -395,7 +400,10 @@ mod test { sequence: 1, witness: Witness::new(), }], - output: vec![TxOut { value: 1, script_pubkey: ScriptBuf::new() }], + output: vec![TxOut { + value: 1, + script_pubkey: ScriptBuf::new(), + }], special_transaction_payload: None, } } diff --git a/dash/src/bip158.rs b/dash/src/bip158.rs index 5d55a7510..242579434 100644 --- a/dash/src/bip158.rs +++ b/dash/src/bip158.rs @@ -43,7 +43,7 @@ use core::cmp::{self, Ordering}; use core::convert::TryInto; use core::fmt::{self, Display, Formatter}; -use hashes::{Hash, siphash24}; +use hashes::{siphash24, Hash}; use internals::write_err; use crate::blockdata::block::Block; @@ -91,7 +91,9 @@ impl std::error::Error for Error { } impl From for Error { - fn from(io: io::Error) -> Self { Error::Io(io) } + fn from(io: io::Error) -> Self { + Error::Io(io) + } } /// A block filter, as described by BIP 158. @@ -113,7 +115,11 @@ impl FilterHash { impl BlockFilter { /// Creates a new filter from pre-computed data. - pub fn new(content: &[u8]) -> BlockFilter { BlockFilter { content: content.to_vec() } } + pub fn new(content: &[u8]) -> BlockFilter { + BlockFilter { + content: content.to_vec(), + } + } /// Computes a SCRIPT_FILTER that contains spent and output scripts. pub fn new_script_filter(block: &Block, script_for_coin: M) -> Result @@ -128,7 +134,9 @@ impl BlockFilter { writer.add_input_scripts(script_for_coin)?; writer.finish()?; - Ok(BlockFilter { content: out }) + Ok(BlockFilter { + content: out, + }) } /// Computes this filter's ID in a chain of filters (see [BIP 157]). @@ -173,7 +181,10 @@ impl<'a, W: io::Write> BlockFilterWriter<'a, W> { let k0 = u64::from_le_bytes(block_hash_as_int[0..8].try_into().expect("8 byte slice")); let k1 = u64::from_le_bytes(block_hash_as_int[8..16].try_into().expect("8 byte slice")); let writer = GcsFilterWriter::new(writer, k0, k1, M, P); - BlockFilterWriter { block, writer } + BlockFilterWriter { + block, + writer, + } } /// Adds output scripts of the block to filter (excluding OP_RETURN scripts). @@ -210,10 +221,14 @@ impl<'a, W: io::Write> BlockFilterWriter<'a, W> { } /// Adds an arbitrary element to filter. - pub fn add_element(&mut self, data: &[u8]) { self.writer.add_element(data); } + pub fn add_element(&mut self, data: &[u8]) { + self.writer.add_element(data); + } /// Writes the block filter. - pub fn finish(&mut self) -> Result { self.writer.finish() } + pub fn finish(&mut self) -> Result { + self.writer.finish() + } } /// Reads and interprets a block filter. @@ -227,7 +242,9 @@ impl BlockFilterReader { let block_hash_as_int = block_hash.to_byte_array(); let k0 = u64::from_le_bytes(block_hash_as_int[0..8].try_into().expect("8 byte slice")); let k1 = u64::from_le_bytes(block_hash_as_int[8..16].try_into().expect("8 byte slice")); - BlockFilterReader { reader: GcsFilterReader::new(k0, k1, M, P) } + BlockFilterReader { + reader: GcsFilterReader::new(k0, k1, M, P), + } } /// Returns true if any query matches against this [`BlockFilterReader`]. @@ -260,7 +277,10 @@ pub struct GcsFilterReader { impl GcsFilterReader { /// Creates a new [`GcsFilterReader`] with specific seed to siphash. pub fn new(k0: u64, k1: u64, m: u64, p: u8) -> GcsFilterReader { - GcsFilterReader { filter: GcsFilter::new(k0, k1, p), m } + GcsFilterReader { + filter: GcsFilter::new(k0, k1, p), + m, + } } /// Returns true if any query matches against this [`GcsFilterReader`]. @@ -294,13 +314,14 @@ impl GcsFilterReader { loop { match data.cmp(&p) { Ordering::Equal => return Ok(true), - Ordering::Less => + Ordering::Less => { if remaining > 0 { data += self.filter.golomb_rice_decode(&mut reader)?; remaining -= 1; } else { return Ok(false); - }, + } + } Ordering::Greater => break, } } @@ -340,13 +361,14 @@ impl GcsFilterReader { loop { match data.cmp(&p) { Ordering::Equal => break, - Ordering::Less => + Ordering::Less => { if remaining > 0 { data += self.filter.golomb_rice_decode(&mut reader)?; remaining -= 1; } else { return Ok(false); - }, + } + } Ordering::Greater => return Ok(false), } } @@ -356,7 +378,9 @@ impl GcsFilterReader { } /// Fast reduction of hash to [0, nm) range. -fn map_to_range(hash: u64, nm: u64) -> u64 { ((hash as u128 * nm as u128) >> 64) as u64 } +fn map_to_range(hash: u64, nm: u64) -> u64 { + ((hash as u128 * nm as u128) >> 64) as u64 +} /// Golomb-Rice encoded filter writer. pub struct GcsFilterWriter<'a, W> { @@ -369,7 +393,12 @@ pub struct GcsFilterWriter<'a, W> { impl<'a, W: io::Write> GcsFilterWriter<'a, W> { /// Creates a new [`GcsFilterWriter`] wrapping a generic writer, with specific seed to siphash. pub fn new(writer: &'a mut W, k0: u64, k1: u64, m: u64, p: u8) -> GcsFilterWriter<'a, W> { - GcsFilterWriter { filter: GcsFilter::new(k0, k1, p), writer, elements: BTreeSet::new(), m } + GcsFilterWriter { + filter: GcsFilter::new(k0, k1, p), + writer, + elements: BTreeSet::new(), + m, + } } /// Adds data to the filter. @@ -415,7 +444,13 @@ struct GcsFilter { impl GcsFilter { /// Creates a new [`GcsFilter`]. - fn new(k0: u64, k1: u64, p: u8) -> GcsFilter { GcsFilter { k0, k1, p } } + fn new(k0: u64, k1: u64, p: u8) -> GcsFilter { + GcsFilter { + k0, + k1, + p, + } + } /// Golomb-Rice encodes a number `n` to a bit stream (parameter 2^k). fn golomb_rice_encode( @@ -467,7 +502,11 @@ pub struct BitStreamReader<'a, R> { impl<'a, R: io::Read> BitStreamReader<'a, R> { /// Creates a new [`BitStreamReader`] that reads bitwise from a given `reader`. pub fn new(reader: &'a mut R) -> BitStreamReader<'a, R> { - BitStreamReader { buffer: [0u8], reader, offset: 8 } + BitStreamReader { + buffer: [0u8], + reader, + offset: 8, + } } /// Reads nbit bits, returning the bits in a `u64` starting with the rightmost bit. @@ -514,7 +553,11 @@ pub struct BitStreamWriter<'a, W> { impl<'a, W: io::Write> BitStreamWriter<'a, W> { /// Creates a new [`BitStreamWriter`] that writes bitwise to a given `writer`. pub fn new(writer: &'a mut W) -> BitStreamWriter<'a, W> { - BitStreamWriter { buffer: [0u8], writer, offset: 0 } + BitStreamWriter { + buffer: [0u8], + writer, + offset: 0, + } } /// Writes nbits bits from data. @@ -558,10 +601,10 @@ mod test { use serde_json::Value; use super::*; - use crate::ScriptBuf; use crate::consensus::encode::deserialize; use crate::hash_types::BlockHash; use crate::internal_macros::hex; + use crate::ScriptBuf; #[ignore] #[test] @@ -593,7 +636,11 @@ mod test { } let filter = BlockFilter::new_script_filter(&block, |o| { - if let Some(s) = txmap.get(o) { Ok(s.clone()) } else { Err(Error::UtxoMissing(*o)) } + if let Some(s) = txmap.get(o) { + Ok(s.clone()) + } else { + Err(Error::UtxoMissing(*o)) + } }) .unwrap(); @@ -602,27 +649,23 @@ mod test { assert_eq!(test_filter.content, filter.content); let block_hash = &block.block_hash(); - assert!( - filter - .match_all( - block_hash, - &mut txmap.iter().filter_map(|(_, s)| if !s.is_empty() { - Some(s.as_bytes()) - } else { - None - }) - ) - .unwrap() - ); + assert!(filter + .match_all( + block_hash, + &mut txmap.iter().filter_map(|(_, s)| if !s.is_empty() { + Some(s.as_bytes()) + } else { + None + }) + ) + .unwrap()); for script in txmap.values() { let query = [script]; if !script.is_empty() { - assert!( - filter - .match_any(block_hash, &mut query.iter().map(|s| s.as_bytes())) - .unwrap() - ); + assert!(filter + .match_any(block_hash, &mut query.iter().map(|s| s.as_bytes())) + .unwrap()); } } @@ -665,20 +708,16 @@ mod test { { let query = [hex!("abcdef"), hex!("eeeeee")]; let reader = GcsFilterReader::new(0, 0, M, P); - assert!( - reader - .match_any(&mut bytes.as_slice(), &mut query.iter().map(|v| v.as_slice())) - .unwrap() - ); + assert!(reader + .match_any(&mut bytes.as_slice(), &mut query.iter().map(|v| v.as_slice())) + .unwrap()); } { let query = [hex!("abcdef"), hex!("123456")]; let reader = GcsFilterReader::new(0, 0, M, P); - assert!( - !reader - .match_any(&mut bytes.as_slice(), &mut query.iter().map(|v| v.as_slice())) - .unwrap() - ); + assert!(!reader + .match_any(&mut bytes.as_slice(), &mut query.iter().map(|v| v.as_slice())) + .unwrap()); } { let reader = GcsFilterReader::new(0, 0, M, P); @@ -686,11 +725,9 @@ mod test { for p in &patterns { query.push(p.clone()); } - assert!( - reader - .match_all(&mut bytes.as_slice(), &mut query.iter().map(|v| v.as_slice())) - .unwrap() - ); + assert!(reader + .match_all(&mut bytes.as_slice(), &mut query.iter().map(|v| v.as_slice())) + .unwrap()); } { let reader = GcsFilterReader::new(0, 0, M, P); @@ -699,11 +736,9 @@ mod test { query.push(p.clone()); } query.push(hex!("abcdef")); - assert!( - !reader - .match_all(&mut bytes.as_slice(), &mut query.iter().map(|v| v.as_slice())) - .unwrap() - ); + assert!(!reader + .match_all(&mut bytes.as_slice(), &mut query.iter().map(|v| v.as_slice())) + .unwrap()); } } diff --git a/dash/src/bip32.rs b/dash/src/bip32.rs index 30e4fbc30..d238a8524 100644 --- a/dash/src/bip32.rs +++ b/dash/src/bip32.rs @@ -28,7 +28,7 @@ use core::str::FromStr; #[cfg(feature = "std")] use std::error; -use hashes::{Hash, HashEngine, Hmac, HmacEngine, hex as hashesHex, sha512}; +use hashes::{hex as hashesHex, sha512, Hash, HashEngine, Hmac, HmacEngine}; use internals::impl_array_newtype; use secp256k1::{self, Secp256k1, XOnlyPublicKey}; #[cfg(feature = "serde")] @@ -153,7 +153,9 @@ impl ChildNumber { /// [`Normal`]: #variant.Normal pub fn from_normal_idx(index: u32) -> Result { if index & (1 << 31) == 0 { - Ok(ChildNumber::Normal { index }) + Ok(ChildNumber::Normal { + index, + }) } else { Err(Error::InvalidChildNumber(index)) } @@ -165,59 +167,95 @@ impl ChildNumber { /// [`Hardened`]: #variant.Hardened pub fn from_hardened_idx(index: u32) -> Result { if index & (1 << 31) == 0 { - Ok(ChildNumber::Hardened { index }) + Ok(ChildNumber::Hardened { + index, + }) } else { Err(Error::InvalidChildNumber(index)) } } /// Create a non-hardened `ChildNumber` from a 256-bit index. - pub fn from_normal_idx_256(index: [u8; 32]) -> ChildNumber { ChildNumber::Normal256 { index } } + pub fn from_normal_idx_256(index: [u8; 32]) -> ChildNumber { + ChildNumber::Normal256 { + index, + } + } /// Create a hardened `ChildNumber` from a 256-bit index. pub fn from_hardened_idx_256(index: [u8; 32]) -> ChildNumber { - ChildNumber::Hardened256 { index } + ChildNumber::Hardened256 { + index, + } } /// Returns `true` if the child number is a [`Normal`] value. /// /// [`Normal`]: #variant.Normal - pub fn is_normal(&self) -> bool { !self.is_hardened() } + pub fn is_normal(&self) -> bool { + !self.is_hardened() + } /// Returns `true` if the child number is a [`Hardened`] value. /// /// [`Hardened`]: #variant.Hardened pub fn is_hardened(&self) -> bool { match self { - ChildNumber::Hardened { .. } => true, - ChildNumber::Normal { .. } => false, - ChildNumber::Normal256 { .. } => false, - ChildNumber::Hardened256 { .. } => true, + ChildNumber::Hardened { + .. + } => true, + ChildNumber::Normal { + .. + } => false, + ChildNumber::Normal256 { + .. + } => false, + ChildNumber::Hardened256 { + .. + } => true, } } /// Returns `true` if the child number is a 256 bit value. pub fn is_256_bits(&self) -> bool { match self { - ChildNumber::Hardened { .. } => false, - ChildNumber::Normal { .. } => false, - ChildNumber::Normal256 { .. } => true, - ChildNumber::Hardened256 { .. } => true, + ChildNumber::Hardened { + .. + } => false, + ChildNumber::Normal { + .. + } => false, + ChildNumber::Normal256 { + .. + } => true, + ChildNumber::Hardened256 { + .. + } => true, } } /// Returns the child number that is a single increment from this one. pub fn increment(self) -> Result { match self { - ChildNumber::Normal { index: idx } => ChildNumber::from_normal_idx(idx + 1), - ChildNumber::Hardened { index: idx } => ChildNumber::from_hardened_idx(idx + 1), - ChildNumber::Normal256 { mut index } => { + ChildNumber::Normal { + index: idx, + } => ChildNumber::from_normal_idx(idx + 1), + ChildNumber::Hardened { + index: idx, + } => ChildNumber::from_hardened_idx(idx + 1), + ChildNumber::Normal256 { + mut index, + } => { // Increment the 256-bit big-endian number represented by index let mut carry = 1u8; for byte in index.iter_mut().rev() { let (new_byte, overflow) = byte.overflowing_add(carry); *byte = new_byte; - carry = if overflow { 1 } else { 0 }; + carry = if overflow { + 1 + } else { + 0 + }; if carry == 0 { break; } @@ -226,15 +264,23 @@ impl ChildNumber { // Overflow occurred return Err(Error::InvalidChildNumber(0)); // Or define a suitable error } - Ok(ChildNumber::Normal256 { index }) + Ok(ChildNumber::Normal256 { + index, + }) } - ChildNumber::Hardened256 { mut index } => { + ChildNumber::Hardened256 { + mut index, + } => { // Increment the 256-bit big-endian number represented by index let mut carry = 1u8; for byte in index.iter_mut().rev() { let (new_byte, overflow) = byte.overflowing_add(carry); *byte = new_byte; - carry = if overflow { 1 } else { 0 }; + carry = if overflow { + 1 + } else { + 0 + }; if carry == 0 { break; } @@ -243,7 +289,9 @@ impl ChildNumber { // Overflow occurred return Err(Error::InvalidChildNumber(0)); // Or define a suitable error } - Ok(ChildNumber::Hardened256 { index }) + Ok(ChildNumber::Hardened256 { + index, + }) } } } @@ -252,9 +300,13 @@ impl ChildNumber { impl From for ChildNumber { fn from(number: u32) -> Self { if number & (1 << 31) != 0 { - ChildNumber::Hardened { index: number ^ (1 << 31) } + ChildNumber::Hardened { + index: number ^ (1 << 31), + } } else { - ChildNumber::Normal { index: number } + ChildNumber::Normal { + index: number, + } } } } @@ -262,10 +314,18 @@ impl From for ChildNumber { impl From for u32 { fn from(cnum: ChildNumber) -> Self { match cnum { - ChildNumber::Normal { index } => index, - ChildNumber::Hardened { index } => index | (1 << 31), - ChildNumber::Normal256 { .. } => u32::MAX, - ChildNumber::Hardened256 { .. } => u32::MAX, + ChildNumber::Normal { + index, + } => index, + ChildNumber::Hardened { + index, + } => index | (1 << 31), + ChildNumber::Normal256 { + .. + } => u32::MAX, + ChildNumber::Hardened256 { + .. + } => u32::MAX, } } } @@ -273,16 +333,37 @@ impl From for u32 { impl fmt::Display for ChildNumber { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - ChildNumber::Hardened { index } => { + ChildNumber::Hardened { + index, + } => { fmt::Display::fmt(&index, f)?; let alt = f.alternate(); - f.write_str(if alt { "h" } else { "'" }) + f.write_str(if alt { + "h" + } else { + "'" + }) } - ChildNumber::Normal { index } => fmt::Display::fmt(&index, f), - ChildNumber::Hardened256 { index } => { - write!(f, "0x{}{}", hex::encode(index), if f.alternate() { "h" } else { "'" }) + ChildNumber::Normal { + index, + } => fmt::Display::fmt(&index, f), + ChildNumber::Hardened256 { + index, + } => { + write!( + f, + "0x{}{}", + hex::encode(index), + if f.alternate() { + "h" + } else { + "'" + } + ) } - ChildNumber::Normal256 { index } => { + ChildNumber::Normal256 { + index, + } => { write!(f, "0x{}", hex::encode(index)) } } @@ -294,7 +375,11 @@ impl FromStr for ChildNumber { fn from_str(inp: &str) -> Result { let is_hardened = inp.ends_with('\'') || inp.ends_with('h'); - let index_str = if is_hardened { &inp[..inp.len() - 1] } else { inp }; + let index_str = if is_hardened { + &inp[..inp.len() - 1] + } else { + inp + }; if index_str.starts_with("0x") || index_str.starts_with("0X") { // Parse as a 256-bit hex number @@ -306,9 +391,13 @@ impl FromStr for ChildNumber { let mut index_bytes = [0u8; 32]; index_bytes[32 - hex_bytes.len()..].copy_from_slice(&hex_bytes); if is_hardened { - Ok(ChildNumber::Hardened256 { index: index_bytes }) + Ok(ChildNumber::Hardened256 { + index: index_bytes, + }) } else { - Ok(ChildNumber::Normal256 { index: index_bytes }) + Ok(ChildNumber::Normal256 { + index: index_bytes, + }) } } else { // Parse as a u32 number @@ -376,7 +465,9 @@ impl DerivationPath { _ => DASH_BIP44_PATH_TESTNET, } .into(); - root_derivation_path.0.extend(&[ChildNumber::Hardened { index: account }]); + root_derivation_path.0.extend(&[ChildNumber::Hardened { + index: account, + }]); root_derivation_path } pub fn bip_44_payment_path( @@ -391,9 +482,15 @@ impl DerivationPath { } .into(); root_derivation_path.0.extend(&[ - ChildNumber::Hardened { index: account }, - ChildNumber::Normal { index: change.into() }, - ChildNumber::Normal { index: address_index }, + ChildNumber::Hardened { + index: account, + }, + ChildNumber::Normal { + index: change.into(), + }, + ChildNumber::Normal { + index: address_index, + }, ]); root_derivation_path } @@ -405,7 +502,9 @@ impl DerivationPath { _ => IDENTITY_REGISTRATION_PATH_TESTNET, } .into(); - root_derivation_path.0.extend(&[ChildNumber::Normal { index }]); + root_derivation_path.0.extend(&[ChildNumber::Normal { + index, + }]); root_derivation_path } @@ -415,7 +514,9 @@ impl DerivationPath { _ => IDENTITY_REGISTRATION_PATH_TESTNET, } .into(); - root_derivation_path.0.extend(&[ChildNumber::Hardened { index }]); + root_derivation_path.0.extend(&[ChildNumber::Hardened { + index, + }]); root_derivation_path } @@ -426,8 +527,12 @@ impl DerivationPath { } .into(); root_derivation_path.0.extend(&[ - ChildNumber::Hardened { index: identity_index }, - ChildNumber::Normal { index: top_up_index }, + ChildNumber::Hardened { + index: identity_index, + }, + ChildNumber::Normal { + index: top_up_index, + }, ]); root_derivation_path } @@ -438,7 +543,9 @@ impl DerivationPath { _ => IDENTITY_INVITATION_PATH_TESTNET, } .into(); - root_derivation_path.0.extend(&[ChildNumber::Hardened { index }]); + root_derivation_path.0.extend(&[ChildNumber::Hardened { + index, + }]); root_derivation_path } @@ -454,9 +561,15 @@ impl DerivationPath { } .into(); root_derivation_path.0.extend(&[ - ChildNumber::Hardened { index: key_type.into() }, - ChildNumber::Hardened { index: identity_index }, - ChildNumber::Hardened { index: key_index }, + ChildNumber::Hardened { + index: key_type.into(), + }, + ChildNumber::Hardened { + index: identity_index, + }, + ChildNumber::Hardened { + index: key_index, + }, ]); root_derivation_path } @@ -492,38 +605,54 @@ where type Output = as Index>::Output; #[inline] - fn index(&self, index: I) -> &Self::Output { &self.0[index] } + fn index(&self, index: I) -> &Self::Output { + &self.0[index] + } } impl Default for DerivationPath { - fn default() -> DerivationPath { DerivationPath::master() } + fn default() -> DerivationPath { + DerivationPath::master() + } } impl IntoDerivationPath for T where T: Into, { - fn into_derivation_path(self) -> Result { Ok(self.into()) } + fn into_derivation_path(self) -> Result { + Ok(self.into()) + } } impl IntoDerivationPath for String { - fn into_derivation_path(self) -> Result { self.parse() } + fn into_derivation_path(self) -> Result { + self.parse() + } } impl<'a> IntoDerivationPath for &'a str { - fn into_derivation_path(self) -> Result { self.parse() } + fn into_derivation_path(self) -> Result { + self.parse() + } } impl From> for DerivationPath { - fn from(numbers: Vec) -> Self { DerivationPath(numbers) } + fn from(numbers: Vec) -> Self { + DerivationPath(numbers) + } } impl From for Vec { - fn from(val: DerivationPath) -> Self { val.0 } + fn from(val: DerivationPath) -> Self { + val.0 + } } impl<'a> From<&'a [ChildNumber]> for DerivationPath { - fn from(numbers: &'a [ChildNumber]) -> Self { DerivationPath(numbers.to_vec()) } + fn from(numbers: &'a [ChildNumber]) -> Self { + DerivationPath(numbers.to_vec()) + } } impl ::core::iter::FromIterator for DerivationPath { @@ -538,11 +667,15 @@ impl ::core::iter::FromIterator for DerivationPath { impl<'a> ::core::iter::IntoIterator for &'a DerivationPath { type Item = &'a ChildNumber; type IntoIter = slice::Iter<'a, ChildNumber>; - fn into_iter(self) -> Self::IntoIter { self.0.iter() } + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } } impl AsRef<[ChildNumber]> for DerivationPath { - fn as_ref(&self) -> &[ChildNumber] { &self.0 } + fn as_ref(&self) -> &[ChildNumber] { + &self.0 + } } impl FromStr for DerivationPath { @@ -572,7 +705,10 @@ pub struct DerivationPathIterator<'a> { impl<'a> DerivationPathIterator<'a> { /// Start a new [DerivationPathIterator] at the given child. pub fn start_from(path: &'a DerivationPath, start: ChildNumber) -> DerivationPathIterator<'a> { - DerivationPathIterator { base: path, next_child: Some(start) } + DerivationPathIterator { + base: path, + next_child: Some(start), + } } } @@ -588,17 +724,25 @@ impl<'a> Iterator for DerivationPathIterator<'a> { impl DerivationPath { /// Returns length of the derivation path - pub fn len(&self) -> usize { self.0.len() } + pub fn len(&self) -> usize { + self.0.len() + } /// Returns `true` if the derivation path is empty - pub fn is_empty(&self) -> bool { self.0.is_empty() } + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } /// Returns derivation path for a master key (i.e. empty derivation path) - pub fn master() -> DerivationPath { DerivationPath(vec![]) } + pub fn master() -> DerivationPath { + DerivationPath(vec![]) + } /// Returns whether derivation path represents master key (i.e. it's length /// is empty). True for `m` path. - pub fn is_master(&self) -> bool { self.0.is_empty() } + pub fn is_master(&self) -> bool { + self.0.is_empty() + } /// Create a new [DerivationPath] that is a child of this one. pub fn child(&self, cn: ChildNumber) -> DerivationPath { @@ -622,12 +766,22 @@ impl DerivationPath { /// Get an [Iterator] over the unhardened children of this [DerivationPath]. pub fn normal_children(&self) -> DerivationPathIterator { - DerivationPathIterator::start_from(self, ChildNumber::Normal { index: 0 }) + DerivationPathIterator::start_from( + self, + ChildNumber::Normal { + index: 0, + }, + ) } /// Get an [Iterator] over the hardened children of this [DerivationPath]. pub fn hardened_children(&self) -> DerivationPathIterator { - DerivationPathIterator::start_from(self, ChildNumber::Hardened { index: 0 }) + DerivationPathIterator::start_from( + self, + ChildNumber::Hardened { + index: 0, + }, + ) } /// Concatenate `self` with `path` and return the resulting new path. @@ -665,7 +819,9 @@ impl fmt::Display for DerivationPath { } impl fmt::Debug for DerivationPath { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self, f) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&self, f) + } } /// Full information on the used extended public key: fingerprint of the @@ -708,8 +864,9 @@ pub enum Error { impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { - Error::CannotDeriveFromHardenedKey => - f.write_str("cannot derive hardened key from public key"), + Error::CannotDeriveFromHardenedKey => { + f.write_str("cannot derive hardened key from public key") + } Error::Secp256k1(ref e) => fmt::Display::fmt(e, f), Error::InvalidChildNumber(ref n) => { write!(f, "child number {} is invalid (not within [0, 2^31 - 1])", n) @@ -739,7 +896,11 @@ impl fmt::Display for Error { #[cfg(feature = "std")] impl error::Error for Error { fn cause(&self) -> Option<&dyn error::Error> { - if let Error::Secp256k1(ref e) = *self { Some(e) } else { None } + if let Error::Secp256k1(ref e) = *self { + Some(e) + } else { + None + } } } @@ -761,11 +922,15 @@ impl From for Error { } impl From for Error { - fn from(e: secp256k1::Error) -> Error { Error::Secp256k1(e) } + fn from(e: secp256k1::Error) -> Error { + Error::Secp256k1(e) + } } impl From for Error { - fn from(err: base58::Error) -> Self { Error::Base58(err) } + fn from(err: base58::Error) -> Self { + Error::Base58(err) + } } impl ExtendedPrivKey { @@ -787,7 +952,11 @@ impl ExtendedPrivKey { /// Constructs ECDSA compressed private key matching internal secret key representation. pub fn to_priv(&self) -> PrivateKey { - PrivateKey { compressed: true, network: self.network, inner: self.private_key } + PrivateKey { + compressed: true, + network: self.network, + inner: self.private_key, + } } /// Constructs BIP340 keypair for Schnorr signatures and Taproot use matching the internal @@ -820,27 +989,35 @@ impl ExtendedPrivKey { ) -> Result { let mut hmac_engine: HmacEngine = HmacEngine::new(&self.chain_code[..]); match i { - ChildNumber::Normal { index } => { + ChildNumber::Normal { + index, + } => { // Non-hardened key: compute public data and use that hmac_engine.input( &secp256k1::PublicKey::from_secret_key(secp, &self.private_key).serialize()[..], ); hmac_engine.input(&index.to_be_bytes()); } - ChildNumber::Hardened { index } => { + ChildNumber::Hardened { + index, + } => { // Hardened key: use only secret data to prevent public derivation hmac_engine.input(&[0u8]); hmac_engine.input(&self.private_key[..]); hmac_engine.input(&(index | (1 << 31)).to_be_bytes()); } - ChildNumber::Normal256 { index } => { + ChildNumber::Normal256 { + index, + } => { // Non-hardened key with 256-bit index hmac_engine.input( &secp256k1::PublicKey::from_secret_key(secp, &self.private_key).serialize()[..], ); hmac_engine.input(&index); } - ChildNumber::Hardened256 { index } => { + ChildNumber::Hardened256 { + index, + } => { // Hardened key with 256-bit index hmac_engine.input(&[0u8]); hmac_engine.input(&self.private_key[..]); @@ -951,9 +1128,13 @@ impl ExtendedPrivKey { let child_number_bytes = data[10..42].try_into().expect("32 bytes for child number"); let child_number = if is_hardened { - ChildNumber::Hardened256 { index: child_number_bytes } + ChildNumber::Hardened256 { + index: child_number_bytes, + } } else { - ChildNumber::Normal256 { index: child_number_bytes } + ChildNumber::Normal256 { + index: child_number_bytes, + } }; let chain_code = data[42..74].try_into().expect("32 bytes for chain code"); @@ -988,15 +1169,24 @@ impl ExtendedPrivKey { // Hardening byte let hardening_byte = match self.child_number { - ChildNumber::Normal256 { .. } => 0x00, - ChildNumber::Hardened256 { .. } => 0x01, + ChildNumber::Normal256 { + .. + } => 0x00, + ChildNumber::Hardened256 { + .. + } => 0x01, _ => panic!("Invalid child number for 256-bit format"), }; ret[9] = hardening_byte; // Child number (32 bytes) let child_number_bytes = match self.child_number { - ChildNumber::Normal256 { index } | ChildNumber::Hardened256 { index } => index, + ChildNumber::Normal256 { + index, + } + | ChildNumber::Hardened256 { + index, + } => index, _ => panic!("Invalid child number for 256-bit format"), }; ret[10..42].copy_from_slice(&child_number_bytes); @@ -1048,11 +1238,18 @@ impl ExtendedPubKey { } /// Constructs ECDSA compressed public key matching internal public key representation. - pub fn to_pub(&self) -> PublicKey { PublicKey { compressed: true, inner: self.public_key } } + pub fn to_pub(&self) -> PublicKey { + PublicKey { + compressed: true, + inner: self.public_key, + } + } /// Constructs BIP340 x-only public key for BIP-340 signatures and Taproot use matching /// the internal public key representation. - pub fn to_x_only_pub(&self) -> XOnlyPublicKey { XOnlyPublicKey::from(self.public_key) } + pub fn to_x_only_pub(&self) -> XOnlyPublicKey { + XOnlyPublicKey::from(self.public_key) + } /// Attempts to derive an extended public key from a path. /// @@ -1076,9 +1273,15 @@ impl ExtendedPubKey { i: ChildNumber, ) -> Result<(secp256k1::SecretKey, ChainCode), Error> { match i { - ChildNumber::Hardened { .. } | ChildNumber::Hardened256 { .. } => - Err(Error::CannotDeriveFromHardenedKey), - ChildNumber::Normal { index: n } => { + ChildNumber::Hardened { + .. + } + | ChildNumber::Hardened256 { + .. + } => Err(Error::CannotDeriveFromHardenedKey), + ChildNumber::Normal { + index: n, + } => { let mut hmac_engine: HmacEngine = HmacEngine::new(&self.chain_code[..]); hmac_engine.input(&self.public_key.serialize()[..]); @@ -1090,7 +1293,9 @@ impl ExtendedPubKey { let chain_code = ChainCode::from_hmac(hmac_result); Ok((private_key, chain_code)) } - ChildNumber::Normal256 { index: idx } => { + ChildNumber::Normal256 { + index: idx, + } => { // UInt256 mode (index >= 2^32) let mut hmac_engine: HmacEngine = HmacEngine::new(&self.chain_code[..]); @@ -1210,15 +1415,24 @@ impl ExtendedPubKey { // Hardening byte let hardening_byte = match self.child_number { - ChildNumber::Normal256 { .. } => 0x00, - ChildNumber::Hardened256 { .. } => 0x01, + ChildNumber::Normal256 { + .. + } => 0x00, + ChildNumber::Hardened256 { + .. + } => 0x01, _ => panic!("Invalid child number for 256-bit format"), }; ret[9] = hardening_byte; // Child number (32 bytes) let child_number_bytes = match self.child_number { - ChildNumber::Normal256 { index } | ChildNumber::Hardened256 { index } => index, + ChildNumber::Normal256 { + index, + } + | ChildNumber::Hardened256 { + index, + } => index, _ => panic!("Invalid child number for 256-bit format"), }; ret[10..42].copy_from_slice(&child_number_bytes); @@ -1257,9 +1471,13 @@ impl ExtendedPubKey { let child_number_bytes = data[10..42].try_into().expect("32 bytes for child number"); let child_number = if is_hardened { - ChildNumber::Hardened256 { index: child_number_bytes } + ChildNumber::Hardened256 { + index: child_number_bytes, + } } else { - ChildNumber::Normal256 { index: child_number_bytes } + ChildNumber::Normal256 { + index: child_number_bytes, + } }; let chain_code = data[42..74].try_into().expect("32 bytes for chain code"); @@ -1434,12 +1652,22 @@ mod tests { for &num in path.0.iter() { sk = sk.ckd_priv(secp, num).unwrap(); match num { - Normal { .. } | ChildNumber::Normal256 { .. } => { + Normal { + .. + } + | ChildNumber::Normal256 { + .. + } => { let pk2 = pk.ckd_pub(secp, num).unwrap(); pk = ExtendedPubKey::from_priv(secp, &sk); assert_eq!(pk, pk2); } - Hardened { .. } | ChildNumber::Hardened256 { .. } => { + Hardened { + .. + } + | ChildNumber::Hardened256 { + .. + } => { assert_eq!(pk.ckd_pub(secp, num), Err(Error::CannotDeriveFromHardenedKey)); pk = ExtendedPubKey::from_priv(secp, &sk); } diff --git a/dash/src/blockdata/block.rs b/dash/src/blockdata/block.rs index 8114c4740..88006a563 100644 --- a/dash/src/blockdata/block.rs +++ b/dash/src/blockdata/block.rs @@ -16,14 +16,14 @@ use hashes::{Hash, HashEngine}; use super::Weight; use crate::blockdata::script; use crate::blockdata::transaction::Transaction; -use crate::consensus::{Decodable, Encodable, encode}; +use crate::consensus::{encode, Decodable, Encodable}; use crate::error::Error::{self, BlockBadProofOfWork, BlockBadTarget}; pub use crate::hash_types::BlockHash; use crate::hash_types::{TxMerkleNode, WitnessCommitment, WitnessMerkleNode, Wtxid}; use crate::internal_macros::impl_consensus_encoding; use crate::pow::{CompactTarget, Target, Work}; use crate::prelude::*; -use crate::{VarInt, io, merkle_tree}; +use crate::{io, merkle_tree, VarInt}; /// Bitcoin block header. /// @@ -64,13 +64,19 @@ impl Header { } /// Computes the target (range [0, T] inclusive) that a blockhash must land in to be valid. - pub fn target(&self) -> Target { self.bits.into() } + pub fn target(&self) -> Target { + self.bits.into() + } /// Computes the popular "difficulty" measure for mining. - pub fn difficulty(&self) -> u128 { self.target().difficulty() } + pub fn difficulty(&self) -> u128 { + self.target().difficulty() + } /// Computes the popular "difficulty" measure for mining and returns a float value of f64. - pub fn difficulty_float(&self) -> f64 { self.target().difficulty_float() } + pub fn difficulty_float(&self) -> f64 { + self.target().difficulty_float() + } /// Checks that the proof-of-work for the block is valid, returning the block hash. pub fn validate_pow(&self, required_target: Target) -> Result { @@ -79,11 +85,17 @@ impl Header { return Err(BlockBadTarget); } let block_hash = self.block_hash(); - if target.is_met_by(block_hash) { Ok(block_hash) } else { Err(BlockBadProofOfWork) } + if target.is_met_by(block_hash) { + Ok(block_hash) + } else { + Err(BlockBadProofOfWork) + } } /// Returns the total work of the block. - pub fn work(&self) -> Work { self.target().to_work() } + pub fn work(&self) -> Work { + self.target().to_work() + } } /// Bitcoin block version number. @@ -125,12 +137,16 @@ impl Version { /// Creates a [`Version`] from a signed 32 bit integer value. /// /// This is the data type used in consensus code in Bitcoin Core. - pub fn from_consensus(v: i32) -> Self { Version(v) } + pub fn from_consensus(v: i32) -> Self { + Version(v) + } /// Returns the inner `i32` value. /// /// This is the data type used in consensus code in Bitcoin Core. - pub fn to_consensus(self) -> i32 { self.0 } + pub fn to_consensus(self) -> i32 { + self.0 + } /// Checks whether the version number is signalling a soft fork at the given bit. /// @@ -153,7 +169,9 @@ impl Version { } impl Default for Version { - fn default() -> Version { Self::NO_SOFT_FORK_SIGNALLING } + fn default() -> Version { + Self::NO_SOFT_FORK_SIGNALLING + } } impl Encodable for Version { @@ -193,7 +211,9 @@ impl_consensus_encoding!(Block, header, txdata); impl Block { /// Returns the block hash. - pub fn block_hash(&self) -> BlockHash { self.header.block_hash() } + pub fn block_hash(&self) -> BlockHash { + self.header.block_hash() + } /// Checks if merkle root of header matches merkle root of the transaction list. pub fn check_merkle_root(&self) -> bool { @@ -274,7 +294,9 @@ impl Block { } /// base_size == size of header + size of encoded transaction count. - fn base_size(&self) -> usize { 80 + VarInt(self.txdata.len() as u64).len() } + fn base_size(&self) -> usize { + 80 + VarInt(self.txdata.len() as u64).len() + } /// Returns the size of the block. /// @@ -298,7 +320,9 @@ impl Block { } /// Returns the coinbase transaction, if one is present. - pub fn coinbase(&self) -> Option<&Transaction> { self.txdata.first() } + pub fn coinbase(&self) -> Option<&Transaction> { + self.txdata.first() + } /// Returns the block height, as encoded in the coinbase transaction according to BIP34. pub fn bip34_block_height(&self) -> Result { @@ -323,7 +347,11 @@ impl Block { // Check that the number is encoded in the minimal way. let h = script::read_scriptint(b.as_bytes()) .map_err(|_e| Bip34Error::UnexpectedPush(b.as_bytes().to_vec()))?; - if h < 0 { Err(Bip34Error::NegativeHeight) } else { Ok(h as u64) } + if h < 0 { + Err(Bip34Error::NegativeHeight) + } else { + Ok(h as u64) + } } _ => Err(Bip34Error::NotPresent), } @@ -369,19 +397,27 @@ impl std::error::Error for Bip34Error { } impl From
for BlockHash { - fn from(header: Header) -> BlockHash { header.block_hash() } + fn from(header: Header) -> BlockHash { + header.block_hash() + } } impl From<&Header> for BlockHash { - fn from(header: &Header) -> BlockHash { header.block_hash() } + fn from(header: &Header) -> BlockHash { + header.block_hash() + } } impl From for BlockHash { - fn from(block: Block) -> BlockHash { block.block_hash() } + fn from(block: Block) -> BlockHash { + block.block_hash() + } } impl From<&Block> for BlockHash { - fn from(block: &Block) -> BlockHash { block.block_hash() } + fn from(block: &Block) -> BlockHash { + block.block_hash() + } } #[cfg(test)] @@ -635,11 +671,11 @@ mod tests { #[cfg(bench)] mod benches { - use test::{Bencher, black_box}; + use test::{black_box, Bencher}; use super::Block; + use crate::consensus::{deserialize, Decodable, Encodable}; use crate::EmptyWrite; - use crate::consensus::{Decodable, Encodable, deserialize}; #[bench] pub fn bench_stream_reader(bh: &mut Bencher) { diff --git a/dash/src/blockdata/constants.rs b/dash/src/blockdata/constants.rs index d41a74bc1..54a299e38 100644 --- a/dash/src/blockdata/constants.rs +++ b/dash/src/blockdata/constants.rs @@ -10,7 +10,7 @@ use core::default::Default; -use hashes::{Hash, sha256d}; +use hashes::{sha256d, Hash}; use hex_lit::hex; use internals::impl_array_newtype; @@ -18,10 +18,10 @@ use crate::blockdata::block::{self, Block}; use crate::blockdata::locktime::absolute; use crate::blockdata::opcodes::all::*; use crate::blockdata::script; -use crate::blockdata::transaction::Transaction; use crate::blockdata::transaction::outpoint::OutPoint; use crate::blockdata::transaction::txin::TxIn; use crate::blockdata::transaction::txout::TxOut; +use crate::blockdata::transaction::Transaction; use crate::blockdata::witness::Witness; use crate::internal_macros::impl_bytes_newtype; use crate::network::constants::Network; @@ -100,7 +100,10 @@ fn bitcoin_genesis_tx() -> Transaction { ); let out_script = script::Builder::new().push_slice(script_bytes).push_opcode(OP_CHECKSIG).into_script(); - ret.output.push(TxOut { value: 50 * COIN_VALUE, script_pubkey: out_script }); + ret.output.push(TxOut { + value: 50 * COIN_VALUE, + script_pubkey: out_script, + }); // end ret diff --git a/dash/src/blockdata/fee_rate.rs b/dash/src/blockdata/fee_rate.rs index 902b40f98..18a3a0e7b 100644 --- a/dash/src/blockdata/fee_rate.rs +++ b/dash/src/blockdata/fee_rate.rs @@ -4,8 +4,8 @@ use core::fmt; use core::ops::{Div, Mul}; use super::Weight; -use crate::Amount; use crate::prelude::*; +use crate::Amount; /// Represents fee rate. /// @@ -40,7 +40,9 @@ impl FeeRate { pub const DUST: FeeRate = FeeRate::from_sat_per_vb_unchecked(3); /// Constructs `FeeRate` from satoshis per 1000 weight units. - pub const fn from_sat_per_kwu(sat_kwu: u64) -> Self { FeeRate(sat_kwu) } + pub const fn from_sat_per_kwu(sat_kwu: u64) -> Self { + FeeRate(sat_kwu) + } /// Constructs `FeeRate` from satoshis per virtual bytes. /// @@ -55,39 +57,57 @@ impl FeeRate { } /// Constructs `FeeRate` from satoshis per virtual bytes without overflow check. - pub const fn from_sat_per_vb_unchecked(sat_vb: u64) -> Self { FeeRate(sat_vb * (1000 / 4)) } + pub const fn from_sat_per_vb_unchecked(sat_vb: u64) -> Self { + FeeRate(sat_vb * (1000 / 4)) + } /// Returns raw fee rate. /// /// Can be used instead of `into()` to avoid inference issues. - pub const fn to_sat_per_kwu(self) -> u64 { self.0 } + pub const fn to_sat_per_kwu(self) -> u64 { + self.0 + } /// Converts to sat/vB rounding down. - pub const fn to_sat_per_vb_floor(self) -> u64 { self.0 / (1000 / 4) } + pub const fn to_sat_per_vb_floor(self) -> u64 { + self.0 / (1000 / 4) + } /// Converts to sat/vB rounding up. - pub const fn to_sat_per_vb_ceil(self) -> u64 { (self.0 + (1000 / 4 - 1)) / (1000 / 4) } + pub const fn to_sat_per_vb_ceil(self) -> u64 { + (self.0 + (1000 / 4 - 1)) / (1000 / 4) + } /// Checked multiplication. /// /// Computes `self * rhs` returning `None` if overflow occurred. - pub fn checked_mul(self, rhs: u64) -> Option { self.0.checked_mul(rhs).map(Self) } + pub fn checked_mul(self, rhs: u64) -> Option { + self.0.checked_mul(rhs).map(Self) + } /// Checked division. /// /// Computes `self / rhs` returning `None` if `rhs == 0`. - pub fn checked_div(self, rhs: u64) -> Option { self.0.checked_div(rhs).map(Self) } + pub fn checked_div(self, rhs: u64) -> Option { + self.0.checked_div(rhs).map(Self) + } } /// Alternative will display the unit. impl fmt::Display for FeeRate { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - if f.alternate() { write!(f, "{} sat/kwu", self.0) } else { fmt::Display::fmt(&self.0, f) } + if f.alternate() { + write!(f, "{} sat/kwu", self.0) + } else { + fmt::Display::fmt(&self.0, f) + } } } impl From for u64 { - fn from(value: FeeRate) -> Self { value.to_sat_per_kwu() } + fn from(value: FeeRate) -> Self { + value.to_sat_per_kwu() + } } /// Computes ceiling so that fee computation is conservative. @@ -102,13 +122,17 @@ impl Mul for Weight { impl Mul for FeeRate { type Output = Amount; - fn mul(self, rhs: Weight) -> Self::Output { rhs * self } + fn mul(self, rhs: Weight) -> Self::Output { + rhs * self + } } impl Div for Amount { type Output = FeeRate; - fn div(self, rhs: Weight) -> Self::Output { FeeRate(self.to_sat() * 1000 / rhs.to_wu()) } + fn div(self, rhs: Weight) -> Self::Output { + FeeRate(self.to_sat() * 1000 / rhs.to_wu()) + } } crate::parse::impl_parse_str_from_int_infallible!(FeeRate, u64, from_sat_per_kwu); @@ -148,7 +172,9 @@ mod tests { #[test] #[should_panic] - fn from_sat_per_vb_unchecked_panic_test() { FeeRate::from_sat_per_vb_unchecked(u64::MAX); } + fn from_sat_per_vb_unchecked_panic_test() { + FeeRate::from_sat_per_vb_unchecked(u64::MAX); + } #[test] fn raw_feerate_test() { diff --git a/dash/src/blockdata/locktime/absolute.rs b/dash/src/blockdata/locktime/absolute.rs index 361dc1da4..4ce7c8c20 100644 --- a/dash/src/blockdata/locktime/absolute.rs +++ b/dash/src/blockdata/locktime/absolute.rs @@ -171,7 +171,9 @@ impl LockTime { /// Returns true if this lock time value is a block time (UNIX timestamp). #[inline] - pub fn is_block_time(&self) -> bool { !self.is_block_height() } + pub fn is_block_time(&self) -> bool { + !self.is_block_height() + } /// Returns true if this timelock constraint is satisfied by the respective `height`/`time`. /// @@ -274,12 +276,16 @@ impl_parse_str_from_int_infallible!(LockTime, u32, from_consensus); impl From for LockTime { #[inline] - fn from(h: Height) -> Self { LockTime::Blocks(h) } + fn from(h: Height) -> Self { + LockTime::Blocks(h) + } } impl From