diff --git a/bitcoin/examples/bip32.rs b/bitcoin/examples/bip32.rs index dcb74b349e..ee5695472a 100644 --- a/bitcoin/examples/bip32.rs +++ b/bitcoin/examples/bip32.rs @@ -2,8 +2,7 @@ use std::env; use bitcoin::address::{Address, KnownHrp}; use bitcoin::bip32::{ChildNumber, DerivationPath, Xpriv, Xpub}; -use bitcoin::hex; -use bitcoin::{CompressedPublicKey, NetworkKind}; +use bitcoin::{hex, CompressedPublicKey, NetworkKind}; fn main() { // This example derives root xprv from a 32-byte seed, diff --git a/bitcoin/src/blockdata/block.rs b/bitcoin/src/blockdata/block.rs index afcf91a5a7..1b757bcf81 100644 --- a/bitcoin/src/blockdata/block.rs +++ b/bitcoin/src/blockdata/block.rs @@ -30,10 +30,10 @@ pub use primitives::block::{ }; #[doc(no_inline)] pub use primitives::block::{InvalidBlockError, ParseBlockError, ParseHeaderError}; -#[doc(inline)] -pub use units::block::{BlockHeight, BlockHeightInterval, BlockMtp, BlockMtpInterval}; #[doc(no_inline)] pub use units::block::TooBigForRelativeHeightError; +#[doc(inline)] +pub use units::block::{BlockHeight, BlockHeightInterval, BlockMtp, BlockMtpInterval}; #[deprecated(since = "TBD", note = "use `BlockHeightInterval` instead")] #[doc(hidden)] diff --git a/bitcoin/src/blockdata/script/owned.rs b/bitcoin/src/blockdata/script/owned.rs index 3222796551..507259cc44 100644 --- a/bitcoin/src/blockdata/script/owned.rs +++ b/bitcoin/src/blockdata/script/owned.rs @@ -10,7 +10,6 @@ use super::{ opcode_to_verify, write_scriptint, Builder, Error, Instruction, PushBytes, ScriptBuf, ScriptExtPriv as _, ScriptPubKeyBuf, }; -use crate::hex; use crate::key::{ PubkeyHash, PublicKey, TapTweak, TweakedPublicKey, UntweakedPublicKey, WPubkeyHash, }; @@ -21,7 +20,7 @@ use crate::script::witness_program::{WitnessProgram, P2A_PROGRAM}; use crate::script::witness_version::WitnessVersion; use crate::script::{self, ScriptHash, WScriptHash}; use crate::taproot::TapNodeHash; -use crate::{consensus, internal_macros}; +use crate::{consensus, hex, internal_macros}; internal_macros::define_extension_trait! { /// Extension functionality for the [`ScriptBuf`] type. diff --git a/bitcoin/src/blockdata/transaction.rs b/bitcoin/src/blockdata/transaction.rs index 3851034460..b4343c91b5 100644 --- a/bitcoin/src/blockdata/transaction.rs +++ b/bitcoin/src/blockdata/transaction.rs @@ -1281,10 +1281,9 @@ mod tests { use super::*; use crate::consensus::encode::{deserialize, serialize}; use crate::constants::WITNESS_SCALE_FACTOR; - use crate::hex; - use crate::parse_int; use crate::script::ScriptSigBuf; use crate::sighash::EcdsaSighashType; + use crate::{hex, parse_int}; const SOME_TX: &str = "0100000001a15d57094aa7a21a28cb20b59aab8fc7d1149a3bdbcddba9c622e4f5f6a99ece010000006c493046022100f93bb0e7d8db7bd46e40132d1f8242026e045f03a0efe71bbb8e3f475e970d790221009337cd7f1f929f00cc6ff01f03729b069a7c21b59b1736ddfee5db5946c5da8c0121033b9b137ee87d5a812d6f506efdd37f0affa7ffc310711c06c7f3e097c9447c52ffffffff0100e1f505000000001976a9140389035a9225b3839e2bbf32d826a1e222031fd888ac00000000"; @@ -1639,7 +1638,8 @@ mod tests { #[test] fn huge_witness() { - let hex = hex::decode_to_vec(include_str!("../../tests/data/huge_witness.hex").trim()).unwrap(); + let hex = + hex::decode_to_vec(include_str!("../../tests/data/huge_witness.hex").trim()).unwrap(); deserialize::(&hex).unwrap(); } diff --git a/bitcoin/src/consensus/serde.rs b/bitcoin/src/consensus/serde.rs index 197fb62ca5..dc486ef784 100644 --- a/bitcoin/src/consensus/serde.rs +++ b/bitcoin/src/consensus/serde.rs @@ -136,15 +136,11 @@ pub mod hex { } impl super::IntoDeError for DecodeInitError { - fn into_de_error(self) -> E { - serde::de::Error::custom(self.0) - } + fn into_de_error(self) -> E { serde::de::Error::custom(self.0) } } impl super::IntoDeError for DecodeError { - fn into_de_error(self) -> E { - serde::de::Error::custom(self.0) - } + fn into_de_error(self) -> E { serde::de::Error::custom(self.0) } } } diff --git a/bitcoin/src/crypto/key.rs b/bitcoin/src/crypto/key.rs index faceb40502..127c38a184 100644 --- a/bitcoin/src/crypto/key.rs +++ b/bitcoin/src/crypto/key.rs @@ -705,15 +705,19 @@ impl FromStr for PublicKey { match s.len() { 66 => { let bytes = hex::decode_to_array::<33>(s).map_err(|e| match e { - DecodeFixedLengthBytesError::InvalidChar(e) => ParsePublicKeyError::InvalidChar(e), - DecodeFixedLengthBytesError::InvalidLength(_) => unreachable!("length checked already"), + DecodeFixedLengthBytesError::InvalidChar(e) => + ParsePublicKeyError::InvalidChar(e), + DecodeFixedLengthBytesError::InvalidLength(_) => + unreachable!("length checked already"), })?; Ok(Self::from_slice(&bytes)?) } 130 => { let bytes = hex::decode_to_array::<65>(s).map_err(|e| match e { - DecodeFixedLengthBytesError::InvalidChar(e) => ParsePublicKeyError::InvalidChar(e), - DecodeFixedLengthBytesError::InvalidLength(_) => unreachable!("length checked already"), + DecodeFixedLengthBytesError::InvalidChar(e) => + ParsePublicKeyError::InvalidChar(e), + DecodeFixedLengthBytesError::InvalidLength(_) => + unreachable!("length checked already"), })?; Ok(Self::from_slice(&bytes)?) } diff --git a/bitcoin/src/crypto/sighash.rs b/bitcoin/src/crypto/sighash.rs index 886129cb38..dca2609788 100644 --- a/bitcoin/src/crypto/sighash.rs +++ b/bitcoin/src/crypto/sighash.rs @@ -339,8 +339,7 @@ impl<'s> ScriptPath<'s> { pub fn leaf_hash(&self) -> TapLeafHash { let mut enc = sha256t::Hash::::engine(); - enc - .write_all(&[self.leaf_version.to_consensus()]) + enc.write_all(&[self.leaf_version.to_consensus()]) .expect("writing to hash engine should never fail"); enc = hashes::encode_to_engine(self.script, enc); @@ -649,12 +648,16 @@ impl> SighashCache { if !anyone_can_pay { writer.write_all(&self.common_cache().prevouts.to_byte_array())?; writer.write_all( - &self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?).amounts.to_byte_array() + &self + .taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?) + .amounts + .to_byte_array(), )?; writer.write_all( - &self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?) + &self + .taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?) .script_pubkeys - .to_byte_array() + .to_byte_array(), )?; writer.write_all(&self.common_cache().sequences.to_byte_array())?; } @@ -714,7 +717,8 @@ impl> SighashCache { // sha_single_output (32): the SHA256 of the corresponding output in CTxOut format. if sighash == TapSighashType::Single { let mut enc = sha256::Hash::engine(); - let txout = self.tx + let txout = self + .tx .borrow() .outputs .get(input_index) @@ -863,7 +867,8 @@ impl> SighashCache { && input_index < self.tx.borrow().outputs.len() { let mut single_enc = LegacySighash::engine(); - single_enc = hashes::encode_to_engine(&self.tx.borrow().outputs[input_index], single_enc); + single_enc = + hashes::encode_to_engine(&self.tx.borrow().outputs[input_index], single_enc); let hash = LegacySighash::from_engine(single_enc); writer.write_all(hash.as_byte_array())?; } else { @@ -1136,7 +1141,10 @@ impl> SighashCache { let mut enc_script_pubkeys = sha256::Hash::engine(); for prevout in prevouts { enc_amounts = hashes::encode_to_engine(&prevout.borrow().amount, enc_amounts); - enc_script_pubkeys = hashes::encode_to_engine(&(*prevout.borrow().script_pubkey), enc_script_pubkeys); + enc_script_pubkeys = hashes::encode_to_engine( + &(*prevout.borrow().script_pubkey), + enc_script_pubkeys, + ); } TaprootCache { amounts: sha256::Hash::from_engine(enc_amounts), @@ -1536,12 +1544,11 @@ mod tests { use super::*; use crate::consensus::deserialize; - use crate::hex; use crate::locktime::absolute; use crate::script::{ ScriptBufExt as _, ScriptPubKey, ScriptPubKeyBuf, TapScriptBuf, WitnessScriptBuf, }; - use crate::TxIn; + use crate::{hex, TxIn}; extern crate serde_json; diff --git a/bitcoin/src/psbt/mod.rs b/bitcoin/src/psbt/mod.rs index 7465d3e703..c5b10ef2e7 100644 --- a/bitcoin/src/psbt/mod.rs +++ b/bitcoin/src/psbt/mod.rs @@ -1308,7 +1308,6 @@ mod tests { use super::*; use crate::bip32::{ChildNumber, DerivationPath}; - use crate::hex; use crate::locktime::absolute; use crate::network::NetworkKind; use crate::psbt::serialize::{Deserialize, Serialize}; @@ -1317,7 +1316,7 @@ mod tests { }; use crate::transaction::{self, OutPoint, TxIn}; use crate::witness::Witness; - use crate::Sequence; + use crate::{hex, Sequence}; #[track_caller] pub fn hex_psbt(s: &str) -> Result { diff --git a/bitcoin/tests/bip_174.rs b/bitcoin/tests/bip_174.rs index 1106b25dd3..2ee0372043 100644 --- a/bitcoin/tests/bip_174.rs +++ b/bitcoin/tests/bip_174.rs @@ -6,13 +6,12 @@ use std::collections::BTreeMap; use bitcoin::amount::{Amount, Denomination}; use bitcoin::bip32::{Fingerprint, IntoDerivationPath, KeySource, Xpriv, Xpub}; use bitcoin::consensus::encode::{deserialize, serialize_hex}; -use bitcoin::hex; use bitcoin::opcodes::all::OP_0; use bitcoin::psbt::{Psbt, PsbtSighashType}; use bitcoin::script::{PushBytes, ScriptBuf, ScriptBufExt as _}; use bitcoin::{ - absolute, script, transaction, NetworkKind, OutPoint, PrivateKey, PublicKey, ScriptPubKeyBuf, - ScriptSigBuf, Sequence, Transaction, TxIn, TxOut, Witness, + absolute, hex, script, transaction, NetworkKind, OutPoint, PrivateKey, PublicKey, + ScriptPubKeyBuf, ScriptSigBuf, Sequence, Transaction, TxIn, TxOut, Witness, }; #[track_caller] diff --git a/bitcoin/tests/serde.rs b/bitcoin/tests/serde.rs index c680e1e174..d9193b701d 100644 --- a/bitcoin/tests/serde.rs +++ b/bitcoin/tests/serde.rs @@ -24,7 +24,6 @@ use std::collections::BTreeMap; use bincode::serialize; use bitcoin::bip32::{ChildNumber, KeySource, Xpriv, Xpub}; use bitcoin::hashes::{hash160, ripemd160, sha256, sha256d}; -use bitcoin::hex; use bitcoin::locktime::{absolute, relative}; use bitcoin::psbt::{raw, Input, Output, Psbt, PsbtSighashType}; use bitcoin::script::ScriptBufExt as _; @@ -32,7 +31,7 @@ use bitcoin::sighash::{EcdsaSighashType, TapSighashType}; use bitcoin::taproot::{self, ControlBlock, LeafVersion, TapTree, TaprootBuilder}; use bitcoin::witness::Witness; use bitcoin::{ - ecdsa, transaction, Address, Amount, NetworkKind, OutPoint, PrivateKey, PublicKey, + ecdsa, hex, transaction, Address, Amount, NetworkKind, OutPoint, PrivateKey, PublicKey, ScriptPubKeyBuf, ScriptSigBuf, Sequence, TapScriptBuf, Target, Transaction, TxIn, TxOut, Txid, Work, }; @@ -99,8 +98,9 @@ fn serde_regression_out_point() { #[test] fn serde_regression_witness() { - let w0 = hex::decode_to_vec("03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105") - .unwrap(); + let w0 = + hex::decode_to_vec("03d2e15674941bad4a996372cb87e1856d3652606d98562fe39c5e9e7e413f2105") + .unwrap(); let w1 = hex::decode_to_vec("000000").unwrap(); let vec = [w0, w1]; let witness = Witness::from_slice(&vec); diff --git a/consensus_encoding/src/decode/decoders.rs b/consensus_encoding/src/decode/decoders.rs index 36fba50e47..0314c17306 100644 --- a/consensus_encoding/src/decode/decoders.rs +++ b/consensus_encoding/src/decode/decoders.rs @@ -382,10 +382,8 @@ where { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match &self.state { - Decoder2State::First(a, b) => - f.debug_tuple("First").field(a).field(b).finish(), - Decoder2State::Second(out, b) => - f.debug_tuple("Second").field(out).field(b).finish(), + Decoder2State::First(a, b) => f.debug_tuple("First").field(a).field(b).finish(), + Decoder2State::Second(out, b) => f.debug_tuple("Second").field(out).field(b).finish(), Decoder2State::Errored => write!(f, "Errored"), } } @@ -1122,12 +1120,10 @@ mod tests { let got = decoder.end().unwrap_err(); assert!(matches!( got, - CompactSizeDecoderError(E::ValueExceedsLimit( - LengthPrefixExceedsMaxError { - limit: MAX_VEC_SIZE, - value: EXCESS_VEC_SIZE, - } - )), + CompactSizeDecoderError(E::ValueExceedsLimit(LengthPrefixExceedsMaxError { + limit: MAX_VEC_SIZE, + value: EXCESS_VEC_SIZE, + })), )); } @@ -1147,12 +1143,10 @@ mod tests { let got = decoder.end().unwrap_err(); assert!(matches!( got, - CompactSizeDecoderError(E::ValueExceedsLimit( - LengthPrefixExceedsMaxError { - limit: 240, - value: 241, - } - )), + CompactSizeDecoderError(E::ValueExceedsLimit(LengthPrefixExceedsMaxError { + limit: 240, + value: 241, + })), )); } @@ -1329,51 +1323,51 @@ mod tests { #[test] #[cfg(feature = "alloc")] fn vec_decoder_empty() { - // Empty with a couple of arbitrary extra bytes. - let encoded = vec![0x00, 0xFF, 0xFF]; - - let mut slice = encoded.as_slice(); - let mut decoder = Test::decoder(); - assert!(!decoder.push_bytes(&mut slice).unwrap()); - - let got = decoder.end().unwrap(); - let want = Test(vec![]); - - assert_eq!(got, want); - } - - #[test] - #[cfg(feature = "alloc")] - fn vec_decoder_one_item() { - let encoded = vec![0x01, 0xEF, 0xBE, 0xAD, 0xDE]; - - let mut slice = encoded.as_slice(); - let mut decoder = Test::decoder(); - decoder.push_bytes(&mut slice).unwrap(); - - let got = decoder.end().unwrap(); - let want = Test(vec![Inner(0xDEAD_BEEF)]); - - assert_eq!(got, want); - } - - #[test] - #[cfg(feature = "alloc")] - fn vec_decoder_two_items() { - let encoded = vec![0x02, 0xEF, 0xBE, 0xAD, 0xDE, 0xBE, 0xBA, 0xFE, 0xCA]; - - let mut slice = encoded.as_slice(); - let mut decoder = Test::decoder(); - decoder.push_bytes(&mut slice).unwrap(); - - let got = decoder.end().unwrap(); - let want = Test(vec![Inner(0xDEAD_BEEF), Inner(0xCAFE_BABE)]); - - assert_eq!(got, want); - } - - #[test] - #[cfg(feature = "alloc")] + // Empty with a couple of arbitrary extra bytes. + let encoded = vec![0x00, 0xFF, 0xFF]; + + let mut slice = encoded.as_slice(); + let mut decoder = Test::decoder(); + assert!(!decoder.push_bytes(&mut slice).unwrap()); + + let got = decoder.end().unwrap(); + let want = Test(vec![]); + + assert_eq!(got, want); + } + + #[test] + #[cfg(feature = "alloc")] + fn vec_decoder_one_item() { + let encoded = vec![0x01, 0xEF, 0xBE, 0xAD, 0xDE]; + + let mut slice = encoded.as_slice(); + let mut decoder = Test::decoder(); + decoder.push_bytes(&mut slice).unwrap(); + + let got = decoder.end().unwrap(); + let want = Test(vec![Inner(0xDEAD_BEEF)]); + + assert_eq!(got, want); + } + + #[test] + #[cfg(feature = "alloc")] + fn vec_decoder_two_items() { + let encoded = vec![0x02, 0xEF, 0xBE, 0xAD, 0xDE, 0xBE, 0xBA, 0xFE, 0xCA]; + + let mut slice = encoded.as_slice(); + let mut decoder = Test::decoder(); + decoder.push_bytes(&mut slice).unwrap(); + + let got = decoder.end().unwrap(); + let want = Test(vec![Inner(0xDEAD_BEEF), Inner(0xCAFE_BABE)]); + + assert_eq!(got, want); + } + + #[test] + #[cfg(feature = "alloc")] fn vec_decoder_reserves_in_batches() { // A small number of extra elements so we extend exactly by the remainder // instead of another full batch. diff --git a/consensus_encoding/src/decode/mod.rs b/consensus_encoding/src/decode/mod.rs index 175c66f29d..1952e53e62 100644 --- a/consensus_encoding/src/decode/mod.rs +++ b/consensus_encoding/src/decode/mod.rs @@ -111,10 +111,11 @@ pub trait Decoder: Sized { /// parsing the data, including insufficient data. This function /// also errors if the provided slice is not completely consumed /// during decode. -pub fn decode_from_slice(bytes: &[u8]) -> Result::Error>> { +pub fn decode_from_slice( + bytes: &[u8], +) -> Result::Error>> { let mut remaining = bytes; - let data = decode_from_slice_unbounded::(&mut remaining) - .map_err(DecodeError::Parse)?; + let data = decode_from_slice_unbounded::(&mut remaining).map_err(DecodeError::Parse)?; if remaining.is_empty() { Ok(data) @@ -134,7 +135,9 @@ pub fn decode_from_slice(bytes: &[u8]) -> Result(bytes: &mut &[u8]) -> Result::Error> +pub fn decode_from_slice_unbounded( + bytes: &mut &[u8], +) -> Result::Error> where T: Decodable, { @@ -330,12 +333,12 @@ impl From for DecodeError { impl fmt::Display for DecodeError where - Err: fmt::Display + Err: fmt::Display, { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Self::Parse(ref e) => write_err!(f, "error parsing encoded object"; e), - Self::Unconsumed(ref e) => write_err!(f, "unconsumed"; e) + Self::Unconsumed(ref e) => write_err!(f, "unconsumed"; e), } } } @@ -343,7 +346,7 @@ where #[cfg(feature = "std")] impl std::error::Error for DecodeError where - Err: std::error::Error + 'static + Err: std::error::Error + 'static, { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { diff --git a/consensus_encoding/src/lib.rs b/consensus_encoding/src/lib.rs index 53d4203f94..144c1892e0 100644 --- a/consensus_encoding/src/lib.rs +++ b/consensus_encoding/src/lib.rs @@ -71,7 +71,9 @@ pub use self::decode::decoders::{ pub use self::decode::{ decode_from_read, decode_from_read_unbuffered, decode_from_read_unbuffered_with, ReadError, }; -pub use self::decode::{decode_from_slice, decode_from_slice_unbounded, Decodable, Decoder, DecodeError}; +pub use self::decode::{ + decode_from_slice, decode_from_slice_unbounded, Decodable, DecodeError, Decoder, +}; pub use self::encode::encoders::{ ArrayEncoder, ArrayRefEncoder, BytesEncoder, CompactSizeEncoder, Encoder2, Encoder3, Encoder4, Encoder6, SliceEncoder, diff --git a/consensus_encoding/tests/decode.rs b/consensus_encoding/tests/decode.rs index 62c5bef3f5..89668adb97 100644 --- a/consensus_encoding/tests/decode.rs +++ b/consensus_encoding/tests/decode.rs @@ -5,14 +5,14 @@ #[cfg(feature = "std")] use std::io::{Cursor, Read}; +#[cfg(feature = "std")] +use bitcoin_consensus_encoding::{decode_from_read, decode_from_read_unbuffered, ReadError}; use bitcoin_consensus_encoding::{ - ArrayDecoder, CompactSizeDecoder, Decodable, Decoder, Decoder2, UnexpectedEofError, + decode_from_slice, decode_from_slice_unbounded, ArrayDecoder, CompactSizeDecoder, Decodable, + DecodeError, Decoder, Decoder2, UnexpectedEofError, }; #[cfg(feature = "alloc")] use bitcoin_consensus_encoding::{ByteVecDecoder, VecDecoder, VecDecoderError}; -#[cfg(feature = "std")] -use bitcoin_consensus_encoding::{decode_from_read, decode_from_read_unbuffered, ReadError}; -use bitcoin_consensus_encoding::{decode_from_slice, decode_from_slice_unbounded, DecodeError}; const EMPTY: &[u8] = &[]; @@ -591,7 +591,7 @@ fn vec_decoder_two_items() { fn vec_decoder_clone_mid_decode() { // Feed the length prefix and first item, clone, then feed the second item to both. let prefix = vec![0x02, 0xEF, 0xBE, 0xAD, 0xDE]; // length=2, first item - let second = vec![0xBE, 0xBA, 0xFE, 0xCA]; // second item + let second = vec![0xBE, 0xBA, 0xFE, 0xCA]; // second item let mut slice = prefix.as_slice(); let mut decoder = Test::decoder(); @@ -654,7 +654,8 @@ fn decode_vec_from_read_unbuffered_success() { let encoded = [0x01, 0xEF, 0xBE, 0xAD, 0xDE, 0xff, 0xff, 0xff, 0xff]; let mut cursor = Cursor::new(&encoded); - let got = bitcoin_consensus_encoding::decode_from_read_unbuffered::(&mut cursor).unwrap(); + let got = + bitcoin_consensus_encoding::decode_from_read_unbuffered::(&mut cursor).unwrap(); assert_eq!(cursor.position(), 5); let want = Test(vec![Inner(0xDEAD_BEEF)]); diff --git a/consensus_encoding/tests/encode.rs b/consensus_encoding/tests/encode.rs index 75e0bdcbbb..68edcae3ab 100644 --- a/consensus_encoding/tests/encode.rs +++ b/consensus_encoding/tests/encode.rs @@ -629,10 +629,7 @@ fn encode_compact_size() { // This test only runs on systems with >= 64 bit usize. if core::mem::size_of::() >= 8 { let mut e = CompactSizeEncoder::new(0x0000_F0F0_F0F0_F0E0u64 as usize); - assert_eq!( - e.current_chunk(), - &[0xFF, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00][..] - ); + assert_eq!(e.current_chunk(), &[0xFF, 0xE0, 0xF0, 0xF0, 0xF0, 0xF0, 0xF0, 0x00, 0x00][..]); assert_eq!(e.len(), 9); assert!(!e.advance()); assert!(e.current_chunk().is_empty()); @@ -642,10 +639,7 @@ fn encode_compact_size() { // This test only runs on systems with > 64 bit usize. if core::mem::size_of::() > 8 { let mut e = CompactSizeEncoder::new((u128::from(u64::MAX) + 5) as usize); - assert_eq!( - e.current_chunk(), - &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF][..] - ); + assert_eq!(e.current_chunk(), &[0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF][..]); assert_eq!(e.len(), 9); assert!(!e.advance()); assert!(e.current_chunk().is_empty()); diff --git a/fuzz/fuzz_targets/bitcoin/arbitrary_block.rs b/fuzz/fuzz_targets/bitcoin/arbitrary_block.rs index 4dd36eeb44..d8ff278336 100644 --- a/fuzz/fuzz_targets/bitcoin/arbitrary_block.rs +++ b/fuzz/fuzz_targets/bitcoin/arbitrary_block.rs @@ -1,11 +1,10 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; use arbitrary::{Arbitrary, Unstructured}; - use bitcoin::block::{self, Block, BlockCheckedExt as _}; use bitcoin::consensus::{deserialize, serialize}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/bitcoin/arbitrary_script.rs b/fuzz/fuzz_targets/bitcoin/arbitrary_script.rs index 6ffb7a8370..5ff5a11218 100644 --- a/fuzz/fuzz_targets/bitcoin/arbitrary_script.rs +++ b/fuzz/fuzz_targets/bitcoin/arbitrary_script.rs @@ -1,13 +1,12 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; use arbitrary::{Arbitrary, Unstructured}; - use bitcoin::address::Address; use bitcoin::consensus::serialize; use bitcoin::script::{self, ScriptBuf, ScriptExt as _, ScriptPubKeyExt as _}; use bitcoin::Network; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/bitcoin/arbitrary_transaction.rs b/fuzz/fuzz_targets/bitcoin/arbitrary_transaction.rs index c115e90585..38de8655a3 100644 --- a/fuzz/fuzz_targets/bitcoin/arbitrary_transaction.rs +++ b/fuzz/fuzz_targets/bitcoin/arbitrary_transaction.rs @@ -1,12 +1,11 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; use arbitrary::{Arbitrary, Unstructured}; - use bitcoin::consensus::{deserialize, serialize}; use bitcoin::transaction::TransactionExt as _; use bitcoin::Transaction; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/bitcoin/arbitrary_witness.rs b/fuzz/fuzz_targets/bitcoin/arbitrary_witness.rs index 0fca331a4e..155c254b42 100644 --- a/fuzz/fuzz_targets/bitcoin/arbitrary_witness.rs +++ b/fuzz/fuzz_targets/bitcoin/arbitrary_witness.rs @@ -1,12 +1,11 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; use arbitrary::{Arbitrary, Unstructured}; - +use bitcoin::blockdata::witness::WitnessExt; use bitcoin::consensus::{deserialize, serialize}; use bitcoin::Witness; -use bitcoin::blockdata::witness::WitnessExt; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/bitcoin/deserialize_psbt.rs b/fuzz/fuzz_targets/bitcoin/deserialize_psbt.rs index 698b803e88..21a00a5e39 100644 --- a/fuzz/fuzz_targets/bitcoin/deserialize_psbt.rs +++ b/fuzz/fuzz_targets/bitcoin/deserialize_psbt.rs @@ -1,8 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; use arbitrary::{Arbitrary, Unstructured}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/bitcoin/deserialize_witness.rs b/fuzz/fuzz_targets/bitcoin/deserialize_witness.rs index b325bbaa8a..bbccd027bd 100644 --- a/fuzz/fuzz_targets/bitcoin/deserialize_witness.rs +++ b/fuzz/fuzz_targets/bitcoin/deserialize_witness.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin::witness::Witness; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/bitcoin/parse_outpoint.rs b/fuzz/fuzz_targets/bitcoin/parse_outpoint.rs index ac852882bb..da7cd87d8d 100644 --- a/fuzz/fuzz_targets/bitcoin/parse_outpoint.rs +++ b/fuzz/fuzz_targets/bitcoin/parse_outpoint.rs @@ -1,10 +1,9 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin::consensus::encode; use bitcoin::transaction::OutPoint; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/bitcoin/script_bytes_to_asm_fmt.rs b/fuzz/fuzz_targets/bitcoin/script_bytes_to_asm_fmt.rs index 19c001198c..b068d67630 100644 --- a/fuzz/fuzz_targets/bitcoin/script_bytes_to_asm_fmt.rs +++ b/fuzz/fuzz_targets/bitcoin/script_bytes_to_asm_fmt.rs @@ -1,9 +1,10 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; use std::fmt::{self, Write as _}; +use libfuzzer_sys::fuzz_target; + // faster than String, we don't need to actually produce the value, just check absence of panics struct NullWriter; diff --git a/fuzz/fuzz_targets/consensus_encoding/decode_array.rs b/fuzz/fuzz_targets/consensus_encoding/decode_array.rs index 80b25dfb08..30e94b789e 100644 --- a/fuzz/fuzz_targets/consensus_encoding/decode_array.rs +++ b/fuzz/fuzz_targets/consensus_encoding/decode_array.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin_consensus_encoding::{ArrayDecoder, Decoder}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/consensus_encoding/decode_byte_vec.rs b/fuzz/fuzz_targets/consensus_encoding/decode_byte_vec.rs index 8e1daf23ac..cf0d2e0c54 100644 --- a/fuzz/fuzz_targets/consensus_encoding/decode_byte_vec.rs +++ b/fuzz/fuzz_targets/consensus_encoding/decode_byte_vec.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin_consensus_encoding::{ByteVecDecoder, Decoder}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/consensus_encoding/decode_compact_size.rs b/fuzz/fuzz_targets/consensus_encoding/decode_compact_size.rs index ab1d2fa7b1..8e5b0abf29 100644 --- a/fuzz/fuzz_targets/consensus_encoding/decode_compact_size.rs +++ b/fuzz/fuzz_targets/consensus_encoding/decode_compact_size.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin_consensus_encoding::{CompactSizeDecoder, Decoder}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/consensus_encoding/decode_decoder2.rs b/fuzz/fuzz_targets/consensus_encoding/decode_decoder2.rs index 3b4219c13d..542f54ca83 100644 --- a/fuzz/fuzz_targets/consensus_encoding/decode_decoder2.rs +++ b/fuzz/fuzz_targets/consensus_encoding/decode_decoder2.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin_consensus_encoding::{ArrayDecoder, Decoder, Decoder2}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} @@ -49,4 +48,3 @@ fn do_test(data: &[u8]) { fuzz_target!(|data| { do_test(data); }); - diff --git a/fuzz/fuzz_targets/hashes/json.rs b/fuzz/fuzz_targets/hashes/json.rs index 3adfeba7a3..954a02c2e7 100644 --- a/fuzz/fuzz_targets/hashes/json.rs +++ b/fuzz/fuzz_targets/hashes/json.rs @@ -1,11 +1,10 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] +use bitcoin::hashes::{ripemd160, sha1, sha256d, sha512, Hmac}; use libfuzzer_sys::fuzz_target; use serde::{Deserialize, Serialize}; -use bitcoin::hashes::{ripemd160, sha1, sha256d, sha512, Hmac}; - #[derive(Deserialize, Serialize)] struct Hmacs { sha1: Hmac, @@ -29,6 +28,4 @@ fn do_test(data: &[u8]) { } } -fuzz_target!(|data| { - do_test(data) -}); +fuzz_target!(|data| { do_test(data) }); diff --git a/fuzz/fuzz_targets/hashes/ripemd160.rs b/fuzz/fuzz_targets/hashes/ripemd160.rs index a32cd9486e..a3f363a00e 100644 --- a/fuzz/fuzz_targets/hashes/ripemd160.rs +++ b/fuzz/fuzz_targets/hashes/ripemd160.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin::hashes::{ripemd160, HashEngine}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} @@ -17,6 +16,4 @@ fn do_test(data: &[u8]) { assert_eq!(hash.as_byte_array(), eng_hash.as_byte_array()); } -fuzz_target!(|data| { - do_test(data) -}); +fuzz_target!(|data| { do_test(data) }); diff --git a/fuzz/fuzz_targets/hashes/sha1.rs b/fuzz/fuzz_targets/hashes/sha1.rs index 4f3a47da95..25df946e87 100644 --- a/fuzz/fuzz_targets/hashes/sha1.rs +++ b/fuzz/fuzz_targets/hashes/sha1.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin::hashes::{sha1, HashEngine}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} @@ -17,6 +16,4 @@ fn do_test(data: &[u8]) { assert_eq!(hash.as_byte_array(), eng_hash.as_byte_array()); } -fuzz_target!(|data| { - do_test(data) -}); +fuzz_target!(|data| { do_test(data) }); diff --git a/fuzz/fuzz_targets/hashes/sha256.rs b/fuzz/fuzz_targets/hashes/sha256.rs index bb37386f7c..c1c45e5d69 100644 --- a/fuzz/fuzz_targets/hashes/sha256.rs +++ b/fuzz/fuzz_targets/hashes/sha256.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin::hashes::{sha256, HashEngine}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} @@ -17,6 +16,4 @@ fn do_test(data: &[u8]) { assert_eq!(hash.as_byte_array(), eng_hash.as_byte_array()); } -fuzz_target!(|data| { - do_test(data) -}); +fuzz_target!(|data| { do_test(data) }); diff --git a/fuzz/fuzz_targets/hashes/sha512.rs b/fuzz/fuzz_targets/hashes/sha512.rs index f20a314e62..c5aeea2d00 100644 --- a/fuzz/fuzz_targets/hashes/sha512.rs +++ b/fuzz/fuzz_targets/hashes/sha512.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin::hashes::{sha512, HashEngine}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} @@ -17,6 +16,4 @@ fn do_test(data: &[u8]) { assert_eq!(hash.as_byte_array(), eng_hash.as_byte_array()); } -fuzz_target!(|data| { - do_test(data) -}); +fuzz_target!(|data| { do_test(data) }); diff --git a/fuzz/fuzz_targets/hashes/sha512_256.rs b/fuzz/fuzz_targets/hashes/sha512_256.rs index 4a3281f897..012a579b52 100644 --- a/fuzz/fuzz_targets/hashes/sha512_256.rs +++ b/fuzz/fuzz_targets/hashes/sha512_256.rs @@ -1,9 +1,8 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - use bitcoin::hashes::{sha512_256, HashEngine}; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} @@ -17,6 +16,4 @@ fn do_test(data: &[u8]) { assert_eq!(hash.as_byte_array(), eng_hash.as_byte_array()); } -fuzz_target!(|data| { - do_test(data) -}); +fuzz_target!(|data| { do_test(data) }); diff --git a/fuzz/fuzz_targets/p2p/arbitrary_addrv2.rs b/fuzz/fuzz_targets/p2p/arbitrary_addrv2.rs index 9d0ef68966..8f9e79edde 100644 --- a/fuzz/fuzz_targets/p2p/arbitrary_addrv2.rs +++ b/fuzz/fuzz_targets/p2p/arbitrary_addrv2.rs @@ -1,12 +1,11 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; - -use arbitrary::{Arbitrary, Unstructured}; use std::convert::TryFrom; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; +use arbitrary::{Arbitrary, Unstructured}; +use libfuzzer_sys::fuzz_target; use p2p::address::AddrV2; #[cfg(not(fuzzing))] diff --git a/fuzz/fuzz_targets/units/arbitrary_weight.rs b/fuzz/fuzz_targets/units/arbitrary_weight.rs index acf9b2e228..3f2d2ada7c 100644 --- a/fuzz/fuzz_targets/units/arbitrary_weight.rs +++ b/fuzz/fuzz_targets/units/arbitrary_weight.rs @@ -1,10 +1,9 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; use arbitrary::{Arbitrary, Unstructured}; - use bitcoin::Weight; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/units/parse_int.rs b/fuzz/fuzz_targets/units/parse_int.rs index 9b422cef92..b64d0296e7 100644 --- a/fuzz/fuzz_targets/units/parse_int.rs +++ b/fuzz/fuzz_targets/units/parse_int.rs @@ -1,10 +1,9 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; use arbitrary::Unstructured; - use bitcoin::parse_int; +use libfuzzer_sys::fuzz_target; #[cfg(not(fuzzing))] fn main() {} diff --git a/fuzz/fuzz_targets/units/standard_checks.rs b/fuzz/fuzz_targets/units/standard_checks.rs index 85d60a6b2c..87652076d4 100644 --- a/fuzz/fuzz_targets/units/standard_checks.rs +++ b/fuzz/fuzz_targets/units/standard_checks.rs @@ -1,13 +1,13 @@ #![cfg_attr(fuzzing, no_main)] #![cfg_attr(not(fuzzing), allow(unused))] -use libfuzzer_sys::fuzz_target; +use bitcoin::absolute::{Height, MedianTimePast}; +use bitcoin::relative::{NumberOf512Seconds, NumberOfBlocks}; use bitcoin::{ Amount, BlockHeight, BlockHeightInterval, BlockMtp, BlockMtpInterval, BlockTime, FeeRate, Sequence, SignedAmount, Weight, }; -use bitcoin::absolute::{Height, MedianTimePast}; -use bitcoin::relative::{NumberOf512Seconds, NumberOfBlocks}; +use libfuzzer_sys::fuzz_target; use standard_test::StandardChecks as _; /// Implements the traits on the wrapper type $ty. Intended only to be called from inside wrap_for_checks! diff --git a/hashes/src/hkdf/mod.rs b/hashes/src/hkdf/mod.rs index c7681788d3..4eb8bc0930 100644 --- a/hashes/src/hkdf/mod.rs +++ b/hashes/src/hkdf/mod.rs @@ -147,8 +147,7 @@ mod tests { use hex_unstable::DisplayHex; use super::*; - use crate::hex; - use crate::sha256; + use crate::{hex, sha256}; #[test] fn rfc5869_basic() { diff --git a/hashes/src/internal_macros.rs b/hashes/src/internal_macros.rs index 5d85667d50..a8ab527626 100644 --- a/hashes/src/internal_macros.rs +++ b/hashes/src/internal_macros.rs @@ -175,7 +175,7 @@ macro_rules! engine_input_impl( let buf_idx = $crate::incomplete_block_len(self); let block_size = ::BLOCK_SIZE; self.bytes_hashed += inp.len() as u64; - + // we know we won't complete a block, so just copy into the buffer and return if buf_idx + inp.len() < block_size { return self.buffer[buf_idx..buf_idx + inp.len()].copy_from_slice(&inp) @@ -194,7 +194,7 @@ macro_rules! engine_input_impl( let full_blocks = inp.len() / block_size * block_size; if full_blocks > 0 { Self::process_blocks(&mut self.h, &inp[..full_blocks]) - } + } // buffer the remainder self.buffer[..inp.len() - full_blocks].copy_from_slice(&inp[full_blocks..]) diff --git a/hashes/src/lib.rs b/hashes/src/lib.rs index 7564f80f43..f22dfdd59e 100644 --- a/hashes/src/lib.rs +++ b/hashes/src/lib.rs @@ -85,7 +85,6 @@ pub extern crate hex_stable as hex; #[cfg(feature = "hex")] pub extern crate hex_unstable; - #[doc(hidden)] pub mod _export { /// A re-export of core::* diff --git a/hashes/src/sha1/crypto.rs b/hashes/src/sha1/crypto.rs index 596de124e9..8067cf3f3f 100644 --- a/hashes/src/sha1/crypto.rs +++ b/hashes/src/sha1/crypto.rs @@ -6,7 +6,7 @@ use super::{HashEngine, BLOCK_SIZE}; impl HashEngine { // Basic unoptimized algorithm from Wikipedia - pub(super) fn process_blocks(state: &mut[u32; 5], blocks: &[u8]) { + pub(super) fn process_blocks(state: &mut [u32; 5], blocks: &[u8]) { debug_assert!(!blocks.is_empty() && blocks.len() % BLOCK_SIZE == 0); for block in blocks.chunks_exact(BLOCK_SIZE) { @@ -33,8 +33,12 @@ impl HashEngine { _ => unreachable!(), }; - let new_a = - a.rotate_left(5).wrapping_add(f).wrapping_add(e).wrapping_add(k).wrapping_add(wi); + let new_a = a + .rotate_left(5) + .wrapping_add(f) + .wrapping_add(e) + .wrapping_add(k) + .wrapping_add(wi); e = d; d = c; c = b.rotate_left(30); diff --git a/hashes/src/sha256/crypto.rs b/hashes/src/sha256/crypto.rs index a6b225f255..a32fd5678f 100644 --- a/hashes/src/sha256/crypto.rs +++ b/hashes/src/sha256/crypto.rs @@ -269,7 +269,7 @@ impl Midstate { } impl HashEngine { - pub(super) fn process_blocks(state: &mut[u32; 8], blocks: &[u8]) { + pub(super) fn process_blocks(state: &mut [u32; 8], blocks: &[u8]) { #[cfg(all(feature = "std", any(target_arch = "x86", target_arch = "x86_64")))] { if std::is_x86_feature_detected!("sse4.1") @@ -323,7 +323,7 @@ impl HashEngine { any(feature = "std", feature = "cpufeatures") ))] #[target_feature(enable = "sha,sse2,ssse3,sse4.1")] - unsafe fn process_block_simd_x86_intrinsics(state: &mut[u32; 8], block: &[u8]) { + unsafe fn process_block_simd_x86_intrinsics(state: &mut [u32; 8], block: &[u8]) { // Code translated and based on from // https://github.com/noloader/SHA-Intrinsics/blob/4899efc81d1af159c1fd955936c673139f35aea9/sha256-x86.c @@ -582,7 +582,7 @@ impl HashEngine { #[cfg(all(target_arch = "aarch64", any(feature = "std", feature = "cpufeatures")))] #[target_feature(enable = "sha2")] - unsafe fn process_block_simd_arm_intrinsics(state: &mut[u32; 8], block: &[u8]) { + unsafe fn process_block_simd_arm_intrinsics(state: &mut [u32; 8], block: &[u8]) { // Code translated and based on from // https://github.com/noloader/SHA-Intrinsics/blob/4e754bec921a9f281b69bd681ca0065763aa911c/sha256-arm.c @@ -769,7 +769,7 @@ impl HashEngine { } // Algorithm copied from libsecp256k1 - fn software_process_block(state: &mut[u32; 8], blocks: &[u8]) { + fn software_process_block(state: &mut [u32; 8], blocks: &[u8]) { debug_assert!(!blocks.is_empty() && blocks.len() % BLOCK_SIZE == 0); for block in blocks.chunks_exact(BLOCK_SIZE) { diff --git a/hashes/src/sha256/mod.rs b/hashes/src/sha256/mod.rs index 66cd1661a6..a5ef59efd6 100644 --- a/hashes/src/sha256/mod.rs +++ b/hashes/src/sha256/mod.rs @@ -30,7 +30,7 @@ impl Hash { let buf_idx = incomplete_block_len(&e); e.buffer[buf_idx] = 0x80; - e.buffer[buf_idx+1..].fill(0); + e.buffer[buf_idx + 1..].fill(0); if buf_idx >= BLOCK_SIZE - 8 { HashEngine::process_blocks(&mut e.h, &e.buffer); diff --git a/hashes/src/sha512/crypto.rs b/hashes/src/sha512/crypto.rs index 060da4fd70..374d48847f 100644 --- a/hashes/src/sha512/crypto.rs +++ b/hashes/src/sha512/crypto.rs @@ -75,7 +75,7 @@ mod fast_hash { impl HashEngine { // Algorithm copied from libsecp256k1 - pub(crate) fn process_blocks(state: &mut[u64; 8], blocks: &[u8]) { + pub(crate) fn process_blocks(state: &mut [u64; 8], blocks: &[u8]) { debug_assert!(!blocks.is_empty() && blocks.len() % BLOCK_SIZE == 0); for block in blocks.chunks_exact(BLOCK_SIZE) { diff --git a/hashes/tests/nist_cavp.rs b/hashes/tests/nist_cavp.rs index 8014002c98..9d89d0929e 100644 --- a/hashes/tests/nist_cavp.rs +++ b/hashes/tests/nist_cavp.rs @@ -10,9 +10,10 @@ macro_rules! nist_shavs_tests { ($mod_name:ident, $hash_type:ty, $short_file:expr, $long_file:expr) => { mod $mod_name { - use super::*; use bitcoin_hashes::HashEngine as _; + use super::*; + fn hash_oneshot(data: &[u8]) -> Vec { <$hash_type>::hash(data).to_byte_array().to_vec() } @@ -43,12 +44,42 @@ macro_rules! nist_shavs_tests { }; } -nist_shavs_tests!(sha1, bitcoin_hashes::sha1::Hash, "data/nist/SHA1ShortMsg.rsp", "data/nist/SHA1LongMsg.rsp"); -nist_shavs_tests!(sha256, bitcoin_hashes::sha256::Hash, "data/nist/SHA256ShortMsg.rsp", "data/nist/SHA256LongMsg.rsp"); -nist_shavs_tests!(sha384, bitcoin_hashes::sha384::Hash, "data/nist/SHA384ShortMsg.rsp", "data/nist/SHA384LongMsg.rsp"); -nist_shavs_tests!(sha512, bitcoin_hashes::sha512::Hash, "data/nist/SHA512ShortMsg.rsp", "data/nist/SHA512LongMsg.rsp"); -nist_shavs_tests!(sha512_256, bitcoin_hashes::sha512_256::Hash, "data/nist/SHA512_256ShortMsg.rsp", "data/nist/SHA512_256LongMsg.rsp"); -nist_shavs_tests!(sha3_256, bitcoin_hashes::sha3_256::Hash, "data/nist/SHA3_256ShortMsg.rsp", "data/nist/SHA3_256LongMsg.rsp"); +nist_shavs_tests!( + sha1, + bitcoin_hashes::sha1::Hash, + "data/nist/SHA1ShortMsg.rsp", + "data/nist/SHA1LongMsg.rsp" +); +nist_shavs_tests!( + sha256, + bitcoin_hashes::sha256::Hash, + "data/nist/SHA256ShortMsg.rsp", + "data/nist/SHA256LongMsg.rsp" +); +nist_shavs_tests!( + sha384, + bitcoin_hashes::sha384::Hash, + "data/nist/SHA384ShortMsg.rsp", + "data/nist/SHA384LongMsg.rsp" +); +nist_shavs_tests!( + sha512, + bitcoin_hashes::sha512::Hash, + "data/nist/SHA512ShortMsg.rsp", + "data/nist/SHA512LongMsg.rsp" +); +nist_shavs_tests!( + sha512_256, + bitcoin_hashes::sha512_256::Hash, + "data/nist/SHA512_256ShortMsg.rsp", + "data/nist/SHA512_256LongMsg.rsp" +); +nist_shavs_tests!( + sha3_256, + bitcoin_hashes::sha3_256::Hash, + "data/nist/SHA3_256ShortMsg.rsp", + "data/nist/SHA3_256LongMsg.rsp" +); /// Runs NIST SHAVS tests from .rsp files fn run_shavs_tests(content: &str, hash_fn: F) @@ -104,4 +135,3 @@ fn decode_hex(hex: &str) -> Vec { .map(|i| u8::from_str_radix(&hex[i..i + 2], 16).expect("invalid hex")) .collect() } - diff --git a/p2p/src/address.rs b/p2p/src/address.rs index 5b2e53a5d0..3e962755e3 100644 --- a/p2p/src/address.rs +++ b/p2p/src/address.rs @@ -15,7 +15,8 @@ use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV use arbitrary::{Arbitrary, Unstructured}; use bitcoin::consensus::encode::{self, Decodable, Encodable, ReadExt, WriteExt}; use encoding::{ - ArrayDecoder, ArrayEncoder, ByteVecDecoder, BytesEncoder, CompactSizeEncoder, Decoder2, Encoder2, + ArrayDecoder, ArrayEncoder, ByteVecDecoder, BytesEncoder, CompactSizeEncoder, Decoder2, + Encoder2, }; use internals::array::ArrayExt; use internals::write_err; @@ -266,7 +267,7 @@ impl encoding::Encodable for AddrV1Message { fn encoder(&self) -> Self::Encoder<'_> { AddrV1MessageEncoder::new(Encoder2::new( ArrayEncoder::without_length_prefix(self.time.to_le_bytes()), - self.address.encoder() + self.address.encoder(), )) } } @@ -302,8 +303,8 @@ impl encoding::Decodable for AddrV1Message { fn decoder() -> Self::Decoder { AddrV1MessageDecoder(AddrV1MessageInnerDecoder::new( ArrayDecoder::new(), - Address::decoder()) - ) + Address::decoder(), + )) } } @@ -1002,10 +1003,7 @@ impl<'a> Arbitrary<'a> for Address { #[cfg(feature = "arbitrary")] impl<'a> Arbitrary<'a> for AddrV1Message { fn arbitrary(u: &mut Unstructured<'a>) -> arbitrary::Result { - Ok(Self { - time: u.arbitrary()?, - address: u.arbitrary()?, - }) + Ok(Self { time: u.arbitrary()?, address: u.arbitrary()? }) } } @@ -1179,8 +1177,10 @@ mod test { let tor_bytes = hex!("042053cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88"); let ip = AddrV2::TorV3( - hex::decode_to_array::<32>("53cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88") - .unwrap(), + hex::decode_to_array::<32>( + "53cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88", + ) + .unwrap(), ); assert_eq!(serialize(&ip), tor_bytes); assert_eq!(encoding::encode_to_vec(&ip), tor_bytes); @@ -1188,8 +1188,10 @@ mod test { let i2p_bytes = hex!("0520a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87"); let ip = AddrV2::I2p( - hex::decode_to_array::<32>("a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87") - .unwrap(), + hex::decode_to_array::<32>( + "a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87", + ) + .unwrap(), ); assert_eq!(serialize(&ip), i2p_bytes); assert_eq!(encoding::encode_to_vec(&ip).as_slice(), i2p_bytes); diff --git a/p2p/src/bip152.rs b/p2p/src/bip152.rs index 9073a532ee..051216c230 100644 --- a/p2p/src/bip152.rs +++ b/p2p/src/bip152.rs @@ -14,12 +14,15 @@ use std::error; use arbitrary::{Arbitrary, Unstructured}; use bitcoin::consensus::encode::{self, Decodable, Encodable, ReadExt, WriteExt}; use bitcoin::{block, Block, BlockChecked, BlockHash, Transaction}; -use encoding::{ArrayDecoder, ArrayEncoder, CompactSizeDecoder, CompactSizeEncoder, Decoder2, Decoder4, Encoder2, Encoder4, SliceEncoder, VecDecoder}; +use encoding::{ + ArrayDecoder, ArrayEncoder, CompactSizeDecoder, CompactSizeEncoder, Decoder2, Decoder4, + Encoder2, Encoder4, SliceEncoder, VecDecoder, +}; use hashes::{sha256, siphash24}; use internals::array::ArrayExt as _; use internals::write_err; use io::{BufRead, Write}; -use primitives::block::{Header, BlockHashDecoder, BlockHashEncoder, HeaderDecoder, HeaderEncoder}; +use primitives::block::{BlockHashDecoder, BlockHashEncoder, Header, HeaderDecoder, HeaderEncoder}; use primitives::transaction::{TransactionDecoder, TransactionEncoder}; /// A BIP-0152 error @@ -83,14 +86,16 @@ encoding::encoder_newtype! { } impl encoding::Encodable for PrefilledTransaction { - type Encoder<'e> =PrefilledTransactionEncoder<'e> + type Encoder<'e> + = PrefilledTransactionEncoder<'e> where Self: 'e; fn encoder(&self) -> Self::Encoder<'_> { - PrefilledTransactionEncoder::new( - Encoder2::new(CompactSizeEncoder::new(self.idx.into()), self.tx.encoder()) - ) + PrefilledTransactionEncoder::new(Encoder2::new( + CompactSizeEncoder::new(self.idx.into()), + self.tx.encoder(), + )) } } @@ -100,7 +105,9 @@ type PrefilledTransactionInnerDecoder = Decoder2::Error) -> PrefilledTransactionDecoderError { + fn err_from_inner( + inner: ::Error, + ) -> PrefilledTransactionDecoderError { PrefilledTransactionDecoderError::Decoder(inner) } } @@ -117,8 +124,8 @@ impl encoding::Decoder for PrefilledTransactionDecoder { #[inline] fn end(self) -> Result { let (cs, tx) = self.0.end().map_err(Self::err_from_inner)?; - let idx = u16::try_from(cs) - .map_err(|_| PrefilledTransactionDecoderError::InvalidIndex(cs))?; + let idx = + u16::try_from(cs).map_err(|_| PrefilledTransactionDecoderError::InvalidIndex(cs))?; Ok(PrefilledTransaction { idx, tx }) } @@ -130,9 +137,10 @@ impl encoding::Decodable for PrefilledTransaction { type Decoder = PrefilledTransactionDecoder; fn decoder() -> Self::Decoder { - PrefilledTransactionDecoder( - Decoder2::new(CompactSizeDecoder::new(), TransactionDecoder::new()) - ) + PrefilledTransactionDecoder(Decoder2::new( + CompactSizeDecoder::new(), + TransactionDecoder::new(), + )) } } @@ -318,9 +326,7 @@ impl encoding::Decoder for ShortIdDecoder { impl encoding::Decodable for ShortId { type Decoder = ShortIdDecoder; - fn decoder() -> Self::Decoder { - ShortIdDecoder(ShortIdInnerDecoder::new()) - } + fn decoder() -> Self::Decoder { ShortIdDecoder(ShortIdInnerDecoder::new()) } } /// An error decoding a [`ShortId`]. @@ -362,11 +368,11 @@ pub struct HeaderAndShortIds { } type HeaderAndShortIdsInnerEncoder<'e> = Encoder4< - HeaderEncoder<'e>, - ArrayEncoder<8>, - Encoder2>, - Encoder2>, - >; + HeaderEncoder<'e>, + ArrayEncoder<8>, + Encoder2>, + Encoder2>, +>; encoding::encoder_newtype! { /// Encoder type for a [`HeaderAndShortIds`] message. @@ -376,34 +382,37 @@ encoding::encoder_newtype! { } impl encoding::Encodable for HeaderAndShortIds { - type Encoder<'e> = HeaderAndShortIdsEncoder<'e> + type Encoder<'e> + = HeaderAndShortIdsEncoder<'e> where Self: 'e; fn encoder(&self) -> Self::Encoder<'_> { - HeaderAndShortIdsEncoder::new( - Encoder4::new( - self.header.encoder(), - ArrayEncoder::without_length_prefix(self.nonce.to_le_bytes()), - Encoder2::new( - CompactSizeEncoder::new(self.short_ids.len()), - SliceEncoder::without_length_prefix(&self.short_ids)), - Encoder2::new( - CompactSizeEncoder::new(self.prefilled_txs.len()), - SliceEncoder::without_length_prefix(&self.prefilled_txs), - ) - ) - ) + HeaderAndShortIdsEncoder::new(Encoder4::new( + self.header.encoder(), + ArrayEncoder::without_length_prefix(self.nonce.to_le_bytes()), + Encoder2::new( + CompactSizeEncoder::new(self.short_ids.len()), + SliceEncoder::without_length_prefix(&self.short_ids), + ), + Encoder2::new( + CompactSizeEncoder::new(self.prefilled_txs.len()), + SliceEncoder::without_length_prefix(&self.prefilled_txs), + ), + )) } } -type HeaderAndShortIdsInnerDecoder = Decoder4, VecDecoder, VecDecoder>; +type HeaderAndShortIdsInnerDecoder = + Decoder4, VecDecoder, VecDecoder>; /// Decoder type for the [`HeaderAndShortIds`] message. pub struct HeaderAndShortIdsDecoder(HeaderAndShortIdsInnerDecoder); impl HeaderAndShortIdsDecoder { - fn err_from_inner(inner: ::Error) -> HeaderAndShortIdsDecoderError { + fn err_from_inner( + inner: ::Error, + ) -> HeaderAndShortIdsDecoderError { HeaderAndShortIdsDecoderError::Decoder(inner) } } @@ -419,17 +428,16 @@ impl encoding::Decoder for HeaderAndShortIdsDecoder { #[inline] fn end(self) -> Result { - let (header, nonce, short_ids, prefilled_txs) = self.0.end().map_err(Self::err_from_inner)?; - let overflow_check = short_ids.len().checked_add(prefilled_txs.len()).ok_or(HeaderAndShortIdsDecoderError::IndexOverflow)?; + let (header, nonce, short_ids, prefilled_txs) = + self.0.end().map_err(Self::err_from_inner)?; + let overflow_check = short_ids + .len() + .checked_add(prefilled_txs.len()) + .ok_or(HeaderAndShortIdsDecoderError::IndexOverflow)?; if overflow_check > u16::MAX.into() { return Err(HeaderAndShortIdsDecoderError::IndexOverflow); } - Ok(HeaderAndShortIds { - header, - nonce: u64::from_le_bytes(nonce), - short_ids, - prefilled_txs - }) + Ok(HeaderAndShortIds { header, nonce: u64::from_le_bytes(nonce), short_ids, prefilled_txs }) } #[inline] @@ -440,14 +448,12 @@ impl encoding::Decodable for HeaderAndShortIds { type Decoder = HeaderAndShortIdsDecoder; fn decoder() -> Self::Decoder { - HeaderAndShortIdsDecoder( - Decoder4::new( - Header::decoder(), - ArrayDecoder::new(), - VecDecoder::::new(), - VecDecoder::::new(), - ) - ) + HeaderAndShortIdsDecoder(Decoder4::new( + Header::decoder(), + ArrayDecoder::new(), + VecDecoder::::new(), + VecDecoder::::new(), + )) } } @@ -851,20 +857,19 @@ encoding::encoder_newtype! { } impl encoding::Encodable for BlockTransactions { - type Encoder<'e> = BlockTransactionsEncoder<'e> + type Encoder<'e> + = BlockTransactionsEncoder<'e> where Self: 'e; fn encoder(&self) -> Self::Encoder<'_> { - BlockTransactionsEncoder::new( + BlockTransactionsEncoder::new(Encoder2::new( + self.block_hash.encoder(), Encoder2::new( - self.block_hash.encoder(), - Encoder2::new( - CompactSizeEncoder::new(self.transactions.len()), - SliceEncoder::without_length_prefix(&self.transactions), - ) - ) - ) + CompactSizeEncoder::new(self.transactions.len()), + SliceEncoder::without_length_prefix(&self.transactions), + ), + )) } } @@ -896,15 +901,18 @@ impl encoding::Decodable for BlockTransactions { type Decoder = BlockTransactionsDecoder; fn decoder() -> Self::Decoder { - BlockTransactionsDecoder( - Decoder2::new(BlockHashDecoder::new(), VecDecoder::::new()) - ) + BlockTransactionsDecoder(Decoder2::new( + BlockHashDecoder::new(), + VecDecoder::::new(), + )) } } /// An error occuring decoding a [`BlockTransactions`] message. #[derive(Debug, Clone, PartialEq, Eq)] -pub struct BlockTransactionsDecoderError(::Error); +pub struct BlockTransactionsDecoderError( + ::Error, +); impl From for BlockTransactionsDecoderError { fn from(never: Infallible) -> Self { match never {} } diff --git a/p2p/src/lib.rs b/p2p/src/lib.rs index 124268838a..baf7073b27 100644 --- a/p2p/src/lib.rs +++ b/p2p/src/lib.rs @@ -650,9 +650,7 @@ impl std::error::Error for UnknownMagicError { pub struct UnknownNetworkError(Network); impl fmt::Display for UnknownNetworkError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "unknown network {}", self.0) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "unknown network {}", self.0) } } #[cfg(feature = "std")] diff --git a/p2p/src/merkle_tree.rs b/p2p/src/merkle_tree.rs index daeeb9e802..ee8a58dfb8 100644 --- a/p2p/src/merkle_tree.rs +++ b/p2p/src/merkle_tree.rs @@ -738,8 +738,8 @@ impl<'a> Arbitrary<'a> for MerkleBlock { mod tests { use core::cmp; - use hex_unstable::DisplayHex; use hex_lit::hex; + use hex_unstable::DisplayHex; use primitives::block::Unchecked; use super::*; diff --git a/p2p/src/message.rs b/p2p/src/message.rs index 98a0557bb4..5f80f3f4fc 100644 --- a/p2p/src/message.rs +++ b/p2p/src/message.rs @@ -442,9 +442,7 @@ impl encoding::Decoder for AddrPayloadDecoder { impl encoding::Decodable for AddrPayload { type Decoder = AddrPayloadDecoder; - fn decoder() -> Self::Decoder { - AddrPayloadDecoder(VecDecoder::new()) - } + fn decoder() -> Self::Decoder { AddrPayloadDecoder(VecDecoder::new()) } } /// An error decoding a [`AddrPayload`]. @@ -462,7 +460,7 @@ impl fmt::Display for AddrPayloadDecoderError { } #[cfg(feature = "std")] -impl std::error::Error for AddrPayloadDecoderError { +impl std::error::Error for AddrPayloadDecoderError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) } } @@ -1999,7 +1997,7 @@ mod test { use units::BlockHeight; use super::*; - use crate::address::{Address, AddrV2}; + use crate::address::{AddrV2, Address}; use crate::bip152::BlockTransactionsRequest; use crate::message_blockdata::{GetBlocksMessage, GetHeadersMessage, Inventory}; use crate::message_bloom::{BloomFlags, FilterAdd, FilterLoad}; @@ -2462,10 +2460,8 @@ mod test { let data = hex!("010101010101"); - let mut decoder = NetworkMessageDecoder::new( - CommandString::try_from_static("unknown").unwrap(), - 6, - ); + let mut decoder = + NetworkMessageDecoder::new(CommandString::try_from_static("unknown").unwrap(), 6); let _ = decoder.push_bytes(&mut data.as_slice()); let decoded = decoder.end().unwrap(); diff --git a/p2p/src/message_compact_blocks.rs b/p2p/src/message_compact_blocks.rs index 227faab31b..f8ff7183af 100644 --- a/p2p/src/message_compact_blocks.rs +++ b/p2p/src/message_compact_blocks.rs @@ -8,11 +8,11 @@ use core::fmt; #[cfg(feature = "arbitrary")] use arbitrary::{Arbitrary, Unstructured}; - -use crate::consensus::impl_consensus_encoding; use encoding::{ArrayDecoder, ArrayEncoder, Decoder2, Encoder2}; use internals::write_err; +use crate::consensus::impl_consensus_encoding; + /// sendcmpct message #[derive(PartialEq, Eq, Clone, Debug, Copy, PartialOrd, Ord, Hash)] pub struct SendCmpct { @@ -31,12 +31,10 @@ impl encoding::Encodable for SendCmpct { type Encoder<'e> = SendCmpctEncoder<'e>; fn encoder(&self) -> Self::Encoder<'_> { - SendCmpctEncoder::new( - Encoder2::new( - ArrayEncoder::without_length_prefix([u8::from(self.send_compact)]), - ArrayEncoder::without_length_prefix(self.version.to_le_bytes()), - ) - ) + SendCmpctEncoder::new(Encoder2::new( + ArrayEncoder::without_length_prefix([u8::from(self.send_compact)]), + ArrayEncoder::without_length_prefix(self.version.to_le_bytes()), + )) } } @@ -58,10 +56,7 @@ impl encoding::Decoder for SendCmpctDecoder { fn end(self) -> Result { let (send_cmpct, version) = self.0.end().map_err(SendCmpctDecoderError)?; let send_compact = u8::from_le_bytes(send_cmpct) != 0; - Ok(SendCmpct { - send_compact, - version: u64::from_le_bytes(version), - }) + Ok(SendCmpct { send_compact, version: u64::from_le_bytes(version) }) } #[inline] @@ -72,9 +67,7 @@ impl encoding::Decodable for SendCmpct { type Decoder = SendCmpctDecoder; fn decoder() -> Self::Decoder { - SendCmpctDecoder( - Decoder2::new(ArrayDecoder::new(), ArrayDecoder::new()) - ) + SendCmpctDecoder(Decoder2::new(ArrayDecoder::new(), ArrayDecoder::new())) } } diff --git a/primitives/src/block.rs b/primitives/src/block.rs index 6083361a42..fd0341d53a 100644 --- a/primitives/src/block.rs +++ b/primitives/src/block.rs @@ -14,21 +14,19 @@ use core::marker::PhantomData; #[cfg(feature = "arbitrary")] use arbitrary::{Arbitrary, Unstructured}; -use encoding::{Encodable, Decodable, Decoder, Decoder6}; #[cfg(feature = "alloc")] -use encoding::{ - CompactSizeEncoder, Decoder2, Encoder2, SliceEncoder, VecDecoder, -}; +use encoding::{CompactSizeEncoder, Decoder2, Encoder2, SliceEncoder, VecDecoder}; +use encoding::{Decodable, Decoder, Decoder6, Encodable}; use hashes::{sha256d, HashEngine as _}; use internals::write_err; -use crate::pow::{CompactTargetDecoder, CompactTargetDecoderError}; #[cfg(feature = "hex")] use crate::hex_codec::{HexPrimitive, ParsePrimitiveError}; +use crate::merkle_tree::{TxMerkleNodeDecoder, TxMerkleNodeDecoderError}; +use crate::pow::{CompactTargetDecoder, CompactTargetDecoderError}; #[cfg(feature = "alloc")] use crate::prelude::Vec; use crate::time::{BlockTimeDecoder, BlockTimeDecoderError}; -use crate::merkle_tree::{TxMerkleNodeDecoder, TxMerkleNodeDecoderError}; use crate::{BlockTime, CompactTarget, TxMerkleNode}; #[cfg(feature = "alloc")] use crate::{Transaction, WitnessMerkleNode}; @@ -277,7 +275,7 @@ mod sealed { #[cfg(all(feature = "hex", feature = "alloc"))] impl core::str::FromStr for Block where - Self: Decodable + Self: Decodable, { type Err = ParseBlockError; @@ -289,7 +287,7 @@ where #[cfg(all(feature = "hex", feature = "alloc"))] impl fmt::Display for Block where - Self: Encodable + Self: Encodable, { #[allow(clippy::use_self)] fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { @@ -299,12 +297,16 @@ where #[cfg(all(feature = "hex", feature = "alloc"))] impl fmt::LowerHex for Block { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&HexPrimitive(self), f) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::LowerHex::fmt(&HexPrimitive(self), f) + } } #[cfg(all(feature = "hex", feature = "alloc"))] impl fmt::UpperHex for Block { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&HexPrimitive(self), f) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::UpperHex::fmt(&HexPrimitive(self), f) + } } /// An error that occurs during parsing of a [`Block`] from a hex string. @@ -578,17 +580,23 @@ impl core::str::FromStr for Header { #[cfg(feature = "hex")] impl fmt::Display for Header { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&HexPrimitive(self), f) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::Display::fmt(&HexPrimitive(self), f) + } } #[cfg(feature = "hex")] impl fmt::LowerHex for Header { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::LowerHex::fmt(&HexPrimitive(self), f) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::LowerHex::fmt(&HexPrimitive(self), f) + } } #[cfg(feature = "hex")] impl fmt::UpperHex for Header { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::UpperHex::fmt(&HexPrimitive(self), f) } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + fmt::UpperHex::fmt(&HexPrimitive(self), f) + } } impl fmt::Debug for Header { diff --git a/primitives/src/hex_codec.rs b/primitives/src/hex_codec.rs index 11ae17408e..3c983ebf31 100644 --- a/primitives/src/hex_codec.rs +++ b/primitives/src/hex_codec.rs @@ -64,25 +64,17 @@ impl HexPrimitive<'_, T> { // Flush remaining buffer to decoder decoder .push_bytes(&mut (&buffer[..index])) - .map_err(encoding::DecodeError::Parse) + .map_err(encoding::DecodeError::Parse) .map_err(ParsePrimitiveError::Decode)?; - decoder - .end() - .map_err(encoding::DecodeError::Parse) - .map_err(ParsePrimitiveError::Decode) + decoder.end().map_err(encoding::DecodeError::Parse).map_err(ParsePrimitiveError::Decode) } } impl HexPrimitive<'_, T> { - /// Writes an Encodable object to the given formatter in the requested case. #[inline] - fn fmt_hex( - &self, - f: &mut fmt::Formatter, - case: Case, - ) -> fmt::Result { + fn fmt_hex(&self, f: &mut fmt::Formatter, case: Case) -> fmt::Result { // Closure to write a given pad character out a given number of times. let write_pad = |f: &mut fmt::Formatter, pad_len: usize| -> fmt::Result { for _ in 0..pad_len { @@ -93,22 +85,17 @@ impl HexPrimitive<'_, T> { // Count hex chars let len = EncodableByteIter::new(self.0).count() * 2; - let iter = BytesToHexIter::new( - EncodableByteIter::new(self.0), - case, - ); + let iter = BytesToHexIter::new(EncodableByteIter::new(self.0), case); let extra_len = if f.alternate() { 2 } else { 0 }; let total_len = len + extra_len; // We pad for width, and truncate for precision, but not vice-versa let pad_width = f.width().unwrap_or(total_len); - let trunc_width = f.precision() - .map_or(len, |v| v.saturating_sub(extra_len)); + let trunc_width = f.precision().map_or(len, |v| v.saturating_sub(extra_len)); let pad_diff = pad_width.saturating_sub(total_len); - // Left padding let left_pad = match f.align() { Some(fmt::Alignment::Left) => 0, @@ -128,7 +115,9 @@ impl HexPrimitive<'_, T> { // Hex data for (i, ch) in iter.enumerate() { - if i >= trunc_width { break; } + if i >= trunc_width { + break; + } f.write_char(ch)?; } @@ -178,7 +167,8 @@ impl fmt::Debug for ParsePrimitiveError { match self { Self::OddLengthString(ref e) => write_err!(f, "odd length string"; e), Self::InvalidChar(ref e) => write_err!(f, "invalid character"; e), - Self::Decode(_) => write!(f, "failure decoding hex string into {}", core::any::type_name::()), + Self::Decode(_) => + write!(f, "failure decoding hex string into {}", core::any::type_name::()), } } } @@ -211,20 +201,16 @@ mod tests { #[cfg(feature = "alloc")] use alloc::{format, string::ToString}; - use crate::block; - #[cfg(feature = "alloc")] use super::*; + use crate::block; #[test] #[cfg(feature = "alloc")] fn parse_primitive_error_display() { - let odd: ParsePrimitiveError = - HexPrimitive::from_str("0").unwrap_err(); - let invalid: ParsePrimitiveError = - HexPrimitive::from_str("zz").unwrap_err(); - let decode: ParsePrimitiveError = - HexPrimitive::from_str("00").unwrap_err(); + let odd: ParsePrimitiveError = HexPrimitive::from_str("0").unwrap_err(); + let invalid: ParsePrimitiveError = HexPrimitive::from_str("zz").unwrap_err(); + let decode: ParsePrimitiveError = HexPrimitive::from_str("00").unwrap_err(); assert!(!odd.to_string().is_empty()); assert!(!invalid.to_string().is_empty()); @@ -236,12 +222,9 @@ mod tests { fn parse_primitive_error_source() { use std::error::Error as _; - let odd: ParsePrimitiveError = - HexPrimitive::from_str("0").unwrap_err(); - let invalid: ParsePrimitiveError = - HexPrimitive::from_str("zz").unwrap_err(); - let decode: ParsePrimitiveError = - HexPrimitive::from_str("00").unwrap_err(); + let odd: ParsePrimitiveError = HexPrimitive::from_str("0").unwrap_err(); + let invalid: ParsePrimitiveError = HexPrimitive::from_str("zz").unwrap_err(); + let decode: ParsePrimitiveError = HexPrimitive::from_str("00").unwrap_err(); assert!(odd.source().is_some()); assert!(invalid.source().is_some()); diff --git a/primitives/src/merkle_tree.rs b/primitives/src/merkle_tree.rs index 96fc942428..ee339aa131 100644 --- a/primitives/src/merkle_tree.rs +++ b/primitives/src/merkle_tree.rs @@ -18,7 +18,8 @@ use internals::array_vec::ArrayVec; #[doc(inline)] pub use crate::hash_types::{ - TxMerkleNode, TxMerkleNodeDecoder, TxMerkleNodeEncoder, TxMerkleNodeDecoderError, WitnessMerkleNode + TxMerkleNode, TxMerkleNodeDecoder, TxMerkleNodeDecoderError, TxMerkleNodeEncoder, + WitnessMerkleNode, }; use crate::hash_types::{Txid, Wtxid}; use crate::transaction::TxIdentifier; diff --git a/units/src/amount/error.rs b/units/src/amount/error.rs index d0b5c4be22..43816ff33e 100644 --- a/units/src/amount/error.rs +++ b/units/src/amount/error.rs @@ -496,12 +496,10 @@ mod tests { #[cfg(feature = "encoding")] use encoding::{Decodable as _, Decoder as _}; - #[cfg(feature = "alloc")] - use crate::{ - amount::{Amount, Denomination, ParseDenominationError, ParseError} - }; #[cfg(feature = "alloc")] use super::{ParseAmountError, ParseAmountErrorInner, ParseErrorInner}; + #[cfg(feature = "alloc")] + use crate::amount::{Amount, Denomination, ParseDenominationError, ParseError}; #[test] #[cfg(feature = "alloc")] @@ -511,14 +509,14 @@ mod tests { macro_rules! assert_amount_err { ($e:expr, $enum_arm:ident, $err_msg:expr) => { assert!(!$e.to_string().is_empty()); - let ParseError(ParseErrorInner::Amount(err)) = $e - else { panic!($err_msg) }; + let ParseError(ParseErrorInner::Amount(err)) = $e else { panic!($err_msg) }; assert!(!err.to_string().is_empty()); #[cfg(feature = "std")] assert!(err.source().is_some()); - let ParseAmountError(ParseAmountErrorInner::$enum_arm(err)) = err - else { panic!($err_msg) }; + let ParseAmountError(ParseAmountErrorInner::$enum_arm(err)) = err else { + panic!($err_msg) + }; assert!(!err.to_string().is_empty()); // The inner-most types have no source #[cfg(feature = "std")] @@ -588,8 +586,9 @@ mod tests { let e = Denomination::from_str("XYZ").unwrap_err(); #[cfg(feature = "std")] assert!(e.source().is_some()); - let ParseDenominationError::Unknown(e) = e - else { panic!("error should be UnknownDenominationError") }; + let ParseDenominationError::Unknown(e) = e else { + panic!("error should be UnknownDenominationError") + }; assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_none()); @@ -598,8 +597,9 @@ mod tests { let e = Denomination::from_str("MBTC").unwrap_err(); #[cfg(feature = "std")] assert!(e.source().is_some()); - let ParseDenominationError::PossiblyConfusing(e) = e - else { panic!("error should be PossiblyConfusingDenominationError") }; + let ParseDenominationError::PossiblyConfusing(e) = e else { + panic!("error should be PossiblyConfusingDenominationError") + }; assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_none()); @@ -646,7 +646,8 @@ mod tests { // Out of range type let mut decoder = Amount::decoder(); - let _ = decoder.push_bytes(&mut (21_000_001 * 100_000_000_u64).to_le_bytes().as_slice()); + let _ = + decoder.push_bytes(&mut (21_000_001 * 100_000_000_u64).to_le_bytes().as_slice()); let e = decoder.end().unwrap_err(); assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] diff --git a/units/src/locktime/absolute/error.rs b/units/src/locktime/absolute/error.rs index fa266e49e7..6a8e08e257 100644 --- a/units/src/locktime/absolute/error.rs +++ b/units/src/locktime/absolute/error.rs @@ -300,11 +300,10 @@ mod tests { use super::LockTimeUnit; #[cfg(feature = "alloc")] use crate::{ + locktime::absolute::{Height, LockTime, MedianTimePast}, BlockHeight, - locktime::absolute::{Height, LockTime, MedianTimePast} }; - #[test] #[cfg(feature = "alloc")] fn locktime_unit_display() { diff --git a/units/src/locktime/relative/error.rs b/units/src/locktime/relative/error.rs index 0594896553..5b77f7bfba 100644 --- a/units/src/locktime/relative/error.rs +++ b/units/src/locktime/relative/error.rs @@ -189,8 +189,8 @@ mod tests { #[cfg(feature = "alloc")] use crate::{ + locktime::relative::{LockTime, NumberOf512Seconds, NumberOfBlocks}, BlockHeight, BlockMtp, BlockMtpInterval, Sequence, - locktime::relative::{LockTime, NumberOf512Seconds, NumberOfBlocks} }; #[test] @@ -212,7 +212,9 @@ mod tests { // InvalidHeightError - is_satisfied_by with invalid args let blocks = NumberOfBlocks::from(10u16); - let e = blocks.is_satisfied_by(BlockHeight::from_u32(5), BlockHeight::from_u32(10)).unwrap_err(); + let e = blocks + .is_satisfied_by(BlockHeight::from_u32(5), BlockHeight::from_u32(10)) + .unwrap_err(); assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_none()); @@ -257,36 +259,32 @@ mod tests { // IsSatisfiedByHeightError // Incompatible type - let e = time_lock.is_satisfied_by_height( - BlockHeight::from_u32(5), - BlockHeight::from_u32(10) - ).unwrap_err(); + let e = time_lock + .is_satisfied_by_height(BlockHeight::from_u32(5), BlockHeight::from_u32(10)) + .unwrap_err(); assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_none()); // Satisfaction type - let e = height_lock.is_satisfied_by_height( - BlockHeight::from_u32(5), - BlockHeight::from_u32(10) - ).unwrap_err(); + let e = height_lock + .is_satisfied_by_height(BlockHeight::from_u32(5), BlockHeight::from_u32(10)) + .unwrap_err(); assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_some()); // IsSatisfiedByTimeError // Incompatible type - let e = height_lock.is_satisfied_by_time( - BlockMtp::from_u32(5), - BlockMtp::from_u32(10) - ).unwrap_err(); + let e = height_lock + .is_satisfied_by_time(BlockMtp::from_u32(5), BlockMtp::from_u32(10)) + .unwrap_err(); assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_none()); // Satisfaction type - let e = time_lock.is_satisfied_by_time( - BlockMtp::from_u32(5), - BlockMtp::from_u32(10) - ).unwrap_err(); + let e = time_lock + .is_satisfied_by_time(BlockMtp::from_u32(5), BlockMtp::from_u32(10)) + .unwrap_err(); assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_some()); diff --git a/units/src/parse_int.rs b/units/src/parse_int.rs index 06a751d72d..5d5672e878 100644 --- a/units/src/parse_int.rs +++ b/units/src/parse_int.rs @@ -709,8 +709,9 @@ mod tests { assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_some()); - let PrefixedHexError(PrefixedHexErrorInner::MissingPrefix(e)) = e - else { panic!("should be a MissingPrefixError") }; + let PrefixedHexError(PrefixedHexErrorInner::MissingPrefix(e)) = e else { + panic!("should be a MissingPrefixError") + }; assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_none()); @@ -726,8 +727,9 @@ mod tests { assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_some()); - let UnprefixedHexError(UnprefixedHexErrorInner::ContainsPrefix(e)) = e - else { panic!("should be a ContainsPrefixError") }; + let UnprefixedHexError(UnprefixedHexErrorInner::ContainsPrefix(e)) = e else { + panic!("should be a ContainsPrefixError") + }; assert!(!e.to_string().is_empty()); #[cfg(feature = "std")] assert!(e.source().is_none()); diff --git a/units/src/result.rs b/units/src/result.rs index 358aba19a6..d0b74fd7bf 100644 --- a/units/src/result.rs +++ b/units/src/result.rs @@ -444,8 +444,8 @@ mod tests { #[cfg(feature = "std")] use std::error::Error; - use crate::{Amount, FeeRate, Weight}; use crate::result::{MathOp, NumOpError, NumOpResult}; + use crate::{Amount, FeeRate, Weight}; #[test] fn mathop_predicates() { diff --git a/units/src/sequence.rs b/units/src/sequence.rs index 76d7a4b84b..b6fcc1ad85 100644 --- a/units/src/sequence.rs +++ b/units/src/sequence.rs @@ -387,10 +387,10 @@ mod tests { #[cfg(all(feature = "encoding", feature = "std"))] use std::error::Error; - #[cfg(feature = "encoding")] - use encoding::{Decodable as _, Decoder as _}; #[cfg(all(feature = "encoding", feature = "alloc"))] use encoding::UnexpectedEofError; + #[cfg(feature = "encoding")] + use encoding::{Decodable as _, Decoder as _}; use super::*;