diff --git a/base58/src/lib.rs b/base58/src/lib.rs index 37e88c92b..36006c8dd 100644 --- a/base58/src/lib.rs +++ b/base58/src/lib.rs @@ -24,9 +24,9 @@ extern crate std; static BASE58_CHARS: &[u8] = b"123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; -use core::{fmt, iter, slice, str}; #[cfg(not(feature = "std"))] pub use alloc::{string::String, vec::Vec}; +use core::{fmt, iter, slice, str}; #[cfg(feature = "std")] pub use std::{string::String, vec::Vec}; diff --git a/groestlcoin/src/address/error.rs b/groestlcoin/src/address/error.rs index d6f1aecbb..397199593 100644 --- a/groestlcoin/src/address/error.rs +++ b/groestlcoin/src/address/error.rs @@ -69,7 +69,7 @@ impl std::error::Error for FromScriptError { } impl From<witness_program::Error> for FromScriptError { - fn from(e : witness_program::Error) -> Self { Self::WitnessProgram(e) } + fn from(e: witness_program::Error) -> Self { Self::WitnessProgram(e) } } impl From<witness_version::TryFromError> for FromScriptError { diff --git a/groestlcoin/src/address/mod.rs b/groestlcoin/src/address/mod.rs index bc645a278..b3a8931af 100644 --- a/groestlcoin/src/address/mod.rs +++ b/groestlcoin/src/address/mod.rs @@ -36,6 +36,7 @@ use bech32grs::primitives::hrp::Hrp; use hashes::{sha256, Hash, HashEngine}; use secp256k1::{Secp256k1, Verification, XOnlyPublicKey}; +use self::error::P2shError; use crate::blockdata::constants::{ MAX_SCRIPT_ELEMENT_SIZE, PUBKEY_ADDRESS_PREFIX_MAIN, PUBKEY_ADDRESS_PREFIX_TEST, SCRIPT_ADDRESS_PREFIX_MAIN, SCRIPT_ADDRESS_PREFIX_TEST, @@ -49,8 +50,6 @@ use crate::crypto::key::{ use crate::network::{Network, NetworkKind}; use crate::prelude::*; use crate::taproot::TapNodeHash; - -use self::error::P2shError; #[rustfmt::skip] // Keep public re-exports separate. #[doc(inline)] pub use self::{ diff --git a/groestlcoin/src/bip152.rs b/groestlcoin/src/bip152.rs index 8e70a7f3d..6aa2d24c0 100644 --- a/groestlcoin/src/bip152.rs +++ b/groestlcoin/src/bip152.rs @@ -379,10 +379,7 @@ mod test { use crate::blockdata::locktime::absolute; use crate::blockdata::transaction; use crate::consensus::encode::{deserialize, serialize}; - use crate::{ - Amount, CompactTarget, OutPoint, ScriptBuf, Sequence, TxIn, TxOut, Txid, - Witness, - }; + use crate::{Amount, CompactTarget, OutPoint, ScriptBuf, Sequence, TxIn, TxOut, Txid, Witness}; fn dummy_tx(nonce: &[u8]) -> Transaction { Transaction { diff --git a/groestlcoin/src/bip32.rs b/groestlcoin/src/bip32.rs index 3c97bc759..636472260 100644 --- a/groestlcoin/src/bip32.rs +++ b/groestlcoin/src/bip32.rs @@ -17,8 +17,8 @@ use secp256k1::{Secp256k1, XOnlyPublicKey}; use crate::crypto::key::{CompressedPublicKey, Keypair, PrivateKey}; use crate::internal_macros::impl_bytes_newtype; -use crate::prelude::*; use crate::network::NetworkKind; +use crate::prelude::*; /// Version bytes for extended public keys on the Bitcoin network. const VERSION_BYTES_MAINNET_PUBLIC: [u8; 4] = [0x04, 0x88, 0xB2, 0x1E]; diff --git a/groestlcoin/src/blockdata/locktime/absolute.rs b/groestlcoin/src/blockdata/locktime/absolute.rs index 622bf108c..3d60e28f5 100644 --- a/groestlcoin/src/blockdata/locktime/absolute.rs +++ b/groestlcoin/src/blockdata/locktime/absolute.rs @@ -17,7 +17,9 @@ use mutagen::mutate; #[cfg(doc)] use crate::absolute; use crate::consensus::encode::{self, Decodable, Encodable}; -use crate::error::{ParseIntError, PrefixedHexError, UnprefixedHexError, ContainsPrefixError, MissingPrefixError}; +use crate::error::{ + ContainsPrefixError, MissingPrefixError, ParseIntError, PrefixedHexError, UnprefixedHexError, +}; use crate::parse::{self, impl_parse_str, impl_parse_str_from_int_infallible}; use crate::prelude::*; @@ -434,7 +436,9 @@ impl Height { /// Creates a `Height` from a hex string. /// /// The input string is may or may not contain a typical hex prefix e.g., `0x`. - pub fn from_hex(s: &str) -> Result<Self, ParseHeightError> { parse_hex(s, Self::from_consensus) } + pub fn from_hex(s: &str) -> Result<Self, ParseHeightError> { + parse_hex(s, Self::from_consensus) + } /// Constructs a new block height. /// @@ -603,7 +607,8 @@ where S: AsRef<str> + Into<String>, F: FnOnce(u32) -> Result<T, ConversionError>, { - let n = i64::from_str_radix(parse::strip_hex_prefix(s.as_ref()), 16).map_err(ParseError::invalid_int(s))?; + let n = i64::from_str_radix(parse::strip_hex_prefix(s.as_ref()), 16) + .map_err(ParseError::invalid_int(s))?; let n = u32::try_from(n).map_err(|_| ParseError::Conversion(n))?; f(n).map_err(ParseError::from).map_err(Into::into) } @@ -765,7 +770,13 @@ impl ParseError { move |source| Self::InvalidInteger { source, input: s.into() } } - fn display(&self, f: &mut fmt::Formatter<'_>, subject: &str, lower_bound: u32, upper_bound: u32) -> fmt::Result { + fn display( + &self, + f: &mut fmt::Formatter<'_>, + subject: &str, + lower_bound: u32, + upper_bound: u32, + ) -> fmt::Result { use core::num::IntErrorKind; use ParseError::*; diff --git a/groestlcoin/src/blockdata/script/owned.rs b/groestlcoin/src/blockdata/script/owned.rs index 66aab19c3..d7189488c 100644 --- a/groestlcoin/src/blockdata/script/owned.rs +++ b/groestlcoin/src/blockdata/script/owned.rs @@ -16,8 +16,8 @@ use crate::blockdata::script::{ use crate::key::{ PubkeyHash, PublicKey, TapTweak, TweakedPublicKey, UntweakedPublicKey, WPubkeyHash, }; -use crate::taproot::TapNodeHash; use crate::prelude::*; +use crate::taproot::TapNodeHash; /// An owned, growable script. /// diff --git a/groestlcoin/src/blockdata/transaction.rs b/groestlcoin/src/blockdata/transaction.rs index 70cb4d938..1b964dbdc 100644 --- a/groestlcoin/src/blockdata/transaction.rs +++ b/groestlcoin/src/blockdata/transaction.rs @@ -24,12 +24,12 @@ use crate::blockdata::script::{Script, ScriptBuf}; use crate::blockdata::witness::Witness; use crate::blockdata::FeeRate; use crate::consensus::{encode, Decodable, Encodable}; -use crate::error::{PrefixedHexError, UnprefixedHexError, ContainsPrefixError, MissingPrefixError}; +use crate::error::{ContainsPrefixError, MissingPrefixError, PrefixedHexError, UnprefixedHexError}; use crate::internal_macros::{impl_consensus_encoding, impl_hashencode}; use crate::parse::{self, impl_parse_str_from_int_infallible}; +use crate::prelude::*; #[cfg(doc)] use crate::sighash::{EcdsaSighashType, TapSighashType}; -use crate::prelude::*; use crate::{Amount, SignedAmount, VarInt}; #[rustfmt::skip] // Keep public re-exports separate. diff --git a/groestlcoin/src/blockdata/witness.rs b/groestlcoin/src/blockdata/witness.rs index 2974de43a..3721c706b 100644 --- a/groestlcoin/src/blockdata/witness.rs +++ b/groestlcoin/src/blockdata/witness.rs @@ -13,8 +13,8 @@ use io::{BufRead, Write}; use crate::consensus::encode::{Error, MAX_VEC_SIZE}; use crate::consensus::{Decodable, Encodable, WriteExt}; use crate::crypto::ecdsa; -use crate::taproot::{self, TAPROOT_ANNEX_PREFIX}; use crate::prelude::*; +use crate::taproot::{self, TAPROOT_ANNEX_PREFIX}; use crate::{Script, VarInt}; /// The Witness is the data used to unlock bitcoin since the [segwit upgrade]. @@ -235,11 +235,7 @@ impl Witness { /// Creates a new empty [`Witness`]. #[inline] pub const fn new() -> Self { - Witness { - content: Vec::new(), - witness_elements: 0, - indices_start: 0, - } + Witness { content: Vec::new(), witness_elements: 0, indices_start: 0 } } /// Creates a witness required to spend a P2WPKH output. @@ -556,7 +552,7 @@ impl Default for Witness { #[cfg(test)] mod test { - use hex::{test_hex_unwrap as hex}; + use hex::test_hex_unwrap as hex; use super::*; use crate::consensus::{deserialize, serialize}; diff --git a/groestlcoin/src/consensus/params.rs b/groestlcoin/src/consensus/params.rs index e35a73382..5c2835a23 100644 --- a/groestlcoin/src/consensus/params.rs +++ b/groestlcoin/src/consensus/params.rs @@ -136,7 +136,6 @@ impl From<Network> for Params { fn from(value: Network) -> Self { Self::new(value) } } - impl From<&Network> for Params { fn from(value: &Network) -> Self { Self::new(*value) } } diff --git a/groestlcoin/src/crypto/key.rs b/groestlcoin/src/crypto/key.rs index 698031540..babf4e08e 100644 --- a/groestlcoin/src/crypto/key.rs +++ b/groestlcoin/src/crypto/key.rs @@ -224,9 +224,7 @@ pub struct SortKey(ArrayVec<u8, 65>); impl fmt::Display for PublicKey { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - self.with_serialized(|bytes| { - fmt::Display::fmt(&bytes.as_hex(), f) - }) + self.with_serialized(|bytes| fmt::Display::fmt(&bytes.as_hex(), f)) } } @@ -234,22 +232,20 @@ impl FromStr for PublicKey { type Err = ParsePublicKeyError; fn from_str(s: &str) -> Result<PublicKey, ParsePublicKeyError> { match s.len() { - 66 => { - PublicKey::from_slice(&<[u8; 33]>::from_hex(s).map_err(|op| { - match op { - HexToArrayError::Conversion(HexToBytesError::InvalidChar(char)) => ParsePublicKeyError::InvalidChar(char), - HexToArrayError::Conversion(HexToBytesError::OddLengthString(_)) | HexToArrayError::InvalidLength(_,_) => unreachable!("invalid length"), - } - })?).map_err(From::from) - }, - 130 => { - PublicKey::from_slice(&<[u8; 65]>::from_hex(s).map_err(|op| { - match op { - HexToArrayError::Conversion(HexToBytesError::InvalidChar(char)) => ParsePublicKeyError::InvalidChar(char), - HexToArrayError::Conversion(HexToBytesError::OddLengthString(_)) | HexToArrayError::InvalidLength(_,_) => unreachable!("invalid length"), - } - })?).map_err(From::from) - } + 66 => PublicKey::from_slice(&<[u8; 33]>::from_hex(s).map_err(|op| match op { + HexToArrayError::Conversion(HexToBytesError::InvalidChar(char)) => + ParsePublicKeyError::InvalidChar(char), + HexToArrayError::Conversion(HexToBytesError::OddLengthString(_)) + | HexToArrayError::InvalidLength(_, _) => unreachable!("invalid length"), + })?) + .map_err(From::from), + 130 => PublicKey::from_slice(&<[u8; 65]>::from_hex(s).map_err(|op| match op { + HexToArrayError::Conversion(HexToBytesError::InvalidChar(char)) => + ParsePublicKeyError::InvalidChar(char), + HexToArrayError::Conversion(HexToBytesError::OddLengthString(_)) + | HexToArrayError::InvalidLength(_, _) => unreachable!("invalid length"), + })?) + .map_err(From::from), len => Err(ParsePublicKeyError::InvalidHexLength(len)), } } @@ -441,7 +437,10 @@ impl PrivateKey { pub fn to_bytes(self) -> Vec<u8> { self.inner[..].to_vec() } /// Deserialize a private key from a slice - pub fn from_slice(data: &[u8], network: impl Into<NetworkKind>) -> Result<PrivateKey, secp256k1::Error> { + pub fn from_slice( + data: &[u8], + network: impl Into<NetworkKind>, + ) -> Result<PrivateKey, secp256k1::Error> { Ok(PrivateKey::new(secp256k1::SecretKey::from_slice(data)?, network)) } @@ -954,7 +953,7 @@ impl std::error::Error for FromWifError { use FromWifError::*; match self { Base58(e) => Some(e), - Secp256k1(e)=> Some(e), + Secp256k1(e) => Some(e), } } } @@ -986,7 +985,8 @@ impl fmt::Display for ParsePublicKeyError { match self { Encoding(e) => write_err!(f, "string error"; e), InvalidChar(char) => write!(f, "hex error {}", char), - InvalidHexLength(got) => write!(f, "pubkey string should be 66 or 130 digits long, got: {}", got), + InvalidHexLength(got) => + write!(f, "pubkey string should be 66 or 130 digits long, got: {}", got), } } } @@ -1023,7 +1023,7 @@ impl fmt::Display for ParseCompressedPublicKeyError { use ParseCompressedPublicKeyError::*; match self { Secp256k1(e) => write_err!(f, "secp256k1 error"; e), - Hex(e) => write_err!(f, "invalid hex"; e) + Hex(e) => write_err!(f, "invalid hex"; e), } } } diff --git a/groestlcoin/src/crypto/sighash.rs b/groestlcoin/src/crypto/sighash.rs index 0b9da98d6..7ef1a6dd2 100644 --- a/groestlcoin/src/crypto/sighash.rs +++ b/groestlcoin/src/crypto/sighash.rs @@ -19,8 +19,8 @@ use io::Write; use crate::blockdata::witness::Witness; use crate::consensus::{encode, Encodable}; -use crate::taproot::{LeafVersion, TapLeafHash, TAPROOT_ANNEX_PREFIX}; use crate::prelude::*; +use crate::taproot::{LeafVersion, TapLeafHash, TAPROOT_ANNEX_PREFIX}; use crate::{transaction, Amount, Script, ScriptBuf, Sequence, Transaction, TxIn, TxOut}; /// Used for signature hash for invalid use of SIGHASH_SINGLE. @@ -607,8 +607,12 @@ impl<R: Borrow<Transaction>> SighashCache<R> { // sha_sequences (32): the SHA256 of the serialization of all input nSequence. if !anyone_can_pay { self.common_cache().prevouts.consensus_encode(writer)?; - self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?).amounts.consensus_encode(writer)?; - self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?).script_pubkeys.consensus_encode(writer)?; + self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?) + .amounts + .consensus_encode(writer)?; + self.taproot_cache(prevouts.get_all().map_err(SigningDataError::sighash)?) + .script_pubkeys + .consensus_encode(writer)?; self.common_cache().sequences.consensus_encode(writer)?; } @@ -668,7 +672,8 @@ impl<R: Borrow<Transaction>> SighashCache<R> { .ok_or(TaprootError::SingleMissingOutput(SingleMissingOutputError { input_index, outputs_length: self.tx.borrow().output.len(), - })).map_err(SigningDataError::Sighash)? + })) + .map_err(SigningDataError::Sighash)? .consensus_encode(&mut enc)?; let hash = sha256::Hash::from_engine(enc); hash.consensus_encode(writer)?; @@ -704,7 +709,8 @@ impl<R: Borrow<Transaction>> SighashCache<R> { annex, leaf_hash_code_separator, sighash_type, - ).map_err(SigningDataError::unwrap_sighash)?; + ) + .map_err(SigningDataError::unwrap_sighash)?; Ok(TapSighash::from_engine(enc)) } @@ -723,7 +729,8 @@ impl<R: Borrow<Transaction>> SighashCache<R> { None, None, sighash_type, - ).map_err(SigningDataError::unwrap_sighash)?; + ) + .map_err(SigningDataError::unwrap_sighash)?; Ok(TapSighash::from_engine(enc)) } @@ -746,7 +753,8 @@ impl<R: Borrow<Transaction>> SighashCache<R> { None, Some((leaf_hash.into(), 0xFFFFFFFF)), sighash_type, - ).map_err(SigningDataError::unwrap_sighash)?; + ) + .map_err(SigningDataError::unwrap_sighash)?; Ok(TapSighash::from_engine(enc)) } @@ -830,7 +838,8 @@ impl<R: Borrow<Transaction>> SighashCache<R> { &script_code, value, sighash_type, - ).map_err(SigningDataError::unwrap_sighash)?; + ) + .map_err(SigningDataError::unwrap_sighash)?; Ok(SegwitV0Sighash::from_engine(enc)) } @@ -849,7 +858,8 @@ impl<R: Borrow<Transaction>> SighashCache<R> { witness_script, value, sighash_type, - ).map_err(SigningDataError::unwrap_sighash)?; + ) + .map_err(SigningDataError::unwrap_sighash)?; Ok(SegwitV0Sighash::from_engine(enc)) } @@ -1216,9 +1226,7 @@ pub enum P2wpkhError { internals::impl_from_infallible!(P2wpkhError); impl From<transaction::InputsIndexError> for P2wpkhError { - fn from(value: transaction::InputsIndexError) -> Self { - P2wpkhError::Sighash(value) - } + fn from(value: transaction::InputsIndexError) -> Self { P2wpkhError::Sighash(value) } } impl fmt::Display for P2wpkhError { @@ -1401,17 +1409,13 @@ impl<E> SigningDataError<E> { } } - fn sighash<E2: Into<E>>(error: E2) -> Self { - Self::Sighash(error.into()) - } + fn sighash<E2: Into<E>>(error: E2) -> Self { Self::Sighash(error.into()) } } // We cannot simultaneously impl `From<E>`. it was determined that this alternative requires less // manual `map_err` calls. impl<E> From<io::Error> for SigningDataError<E> { - fn from(value: io::Error) -> Self { - Self::Io(value) - } + fn from(value: io::Error) -> Self { Self::Io(value) } } impl<E: fmt::Display> fmt::Display for SigningDataError<E> { diff --git a/groestlcoin/src/crypto/taproot.rs b/groestlcoin/src/crypto/taproot.rs index dee10f787..c97c03f2e 100644 --- a/groestlcoin/src/crypto/taproot.rs +++ b/groestlcoin/src/crypto/taproot.rs @@ -10,9 +10,9 @@ use core::fmt; use internals::write_err; use io::Write; +use crate::prelude::*; use crate::sighash::{InvalidSighashTypeError, TapSighashType}; use crate::taproot::serialized_signature::{self, SerializedSignature}; -use crate::prelude::*; /// A BIP340-341 serialized taproot signature with the corresponding hash type. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] diff --git a/groestlcoin/src/lib.rs b/groestlcoin/src/lib.rs index 1fde0c7c1..80332233c 100644 --- a/groestlcoin/src/lib.rs +++ b/groestlcoin/src/lib.rs @@ -29,17 +29,13 @@ //! happen the implementations diverge one day. #![cfg_attr(all(not(feature = "std"), not(test)), no_std)] - // Experimental features we need. #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![cfg_attr(bench, feature(test))] - // Coding conventions. #![warn(missing_docs)] - // Instead of littering the codebase for non-fuzzing code just globally allow. #![cfg_attr(fuzzing, allow(dead_code, unused_imports))] - // Exclude lints we don't think are valuable. #![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134 #![allow(clippy::manual_range_contains)] // More readable than clippy's format. diff --git a/groestlcoin/src/merkle_tree/block.rs b/groestlcoin/src/merkle_tree/block.rs index 6d5715e0c..91ee25b43 100644 --- a/groestlcoin/src/merkle_tree/block.rs +++ b/groestlcoin/src/merkle_tree/block.rs @@ -542,9 +542,10 @@ impl std::error::Error for MerkleBlockError { #[cfg(test)] mod tests { - use hex::{test_hex_unwrap as hex}; + use hex::test_hex_unwrap as hex; #[cfg(feature = "rand-std")] use secp256k1::rand::prelude::*; + use super::*; use crate::consensus::encode::{deserialize, serialize}; diff --git a/groestlcoin/src/p2p/address.rs b/groestlcoin/src/p2p/address.rs index 29d196cbd..fd937f646 100644 --- a/groestlcoin/src/p2p/address.rs +++ b/groestlcoin/src/p2p/address.rs @@ -226,7 +226,7 @@ impl Decodable for AddrV2 { } let addr: [u16; 8] = read_be_address(r)?; // check the first byte for the CJDNS marker - if addr[0] >> 8 != 0xFC{ + if addr[0] >> 8 != 0xFC { return Err(encode::Error::ParseFailed("Invalid CJDNS address")); } AddrV2::Cjdns(Ipv6Addr::new( diff --git a/groestlcoin/src/p2p/message.rs b/groestlcoin/src/p2p/message.rs index c48c4bb94..ee147bb79 100644 --- a/groestlcoin/src/p2p/message.rs +++ b/groestlcoin/src/p2p/message.rs @@ -753,8 +753,7 @@ mod test { 0x64, 0x64, 0x72, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfd, 0xfb, 0x14, 0xd3 ]); - let preimage = - RawNetworkMessage::new(Magic::GROESTLCOIN, NetworkMessage::GetAddr); + let preimage = RawNetworkMessage::new(Magic::GROESTLCOIN, NetworkMessage::GetAddr); assert!(msg.is_ok()); let msg: RawNetworkMessage = msg.unwrap(); assert_eq!(preimage.magic, msg.magic); diff --git a/groestlcoin/src/p2p/message_network.rs b/groestlcoin/src/p2p/message_network.rs index 94be2a39a..0be69c516 100644 --- a/groestlcoin/src/p2p/message_network.rs +++ b/groestlcoin/src/p2p/message_network.rs @@ -11,10 +11,10 @@ use io::{BufRead, Write}; use crate::consensus::{encode, Decodable, Encodable, ReadExt}; use crate::internal_macros::impl_consensus_encoding; +use crate::p2p; use crate::p2p::address::Address; use crate::p2p::ServiceFlags; use crate::prelude::*; -use crate::p2p; /// Some simple messages diff --git a/groestlcoin/src/pow.rs b/groestlcoin/src/pow.rs index 13baf4cb7..c1daaf90a 100644 --- a/groestlcoin/src/pow.rs +++ b/groestlcoin/src/pow.rs @@ -17,7 +17,7 @@ use crate::blockdata::block::BlockHash; use crate::consensus::encode::{self, Decodable, Encodable}; #[cfg(doc)] use crate::consensus::Params; -use crate::error::{PrefixedHexError, UnprefixedHexError, ContainsPrefixError, MissingPrefixError}; +use crate::error::{ContainsPrefixError, MissingPrefixError, PrefixedHexError, UnprefixedHexError}; use crate::{parse, Network}; /// Implement traits and methods shared by `Target` and `Work`. diff --git a/groestlcoin/src/psbt/mod.rs b/groestlcoin/src/psbt/mod.rs index 2baef735e..115f9667e 100644 --- a/groestlcoin/src/psbt/mod.rs +++ b/groestlcoin/src/psbt/mod.rs @@ -435,8 +435,9 @@ impl Psbt { Wsh | ShWsh => { let witness_script = input.witness_script.as_ref().ok_or(SignError::MissingWitnessScript)?; - let sighash = - cache.p2wsh_signature_hash(input_index, witness_script, utxo.value, hash_ty).map_err(SignError::SegwitV0Sighash)?; + let sighash = cache + .p2wsh_signature_hash(input_index, witness_script, utxo.value, hash_ty) + .map_err(SignError::SegwitV0Sighash)?; Ok((Message::from_digest(sighash.to_byte_array()), hash_ty)) } Tr => { diff --git a/groestlcoin/src/taproot/mod.rs b/groestlcoin/src/taproot/mod.rs index a84d1620f..60ce28ee0 100644 --- a/groestlcoin/src/taproot/mod.rs +++ b/groestlcoin/src/taproot/mod.rs @@ -1443,8 +1443,8 @@ impl std::error::Error for TaprootError { mod test { use core::str::FromStr; - use hashes::sha256t::Tag; use hashes::sha256; + use hashes::sha256t::Tag; use hex::FromHex; use secp256k1::VerifyOnly; diff --git a/hashes/src/lib.rs b/hashes/src/lib.rs index 053b664ca..dfdb3b83b 100644 --- a/hashes/src/lib.rs +++ b/hashes/src/lib.rs @@ -66,17 +66,13 @@ //! ``` #![cfg_attr(all(not(test), not(feature = "std")), no_std)] - // Experimental features we need. #![cfg_attr(docsrs, feature(doc_auto_cfg))] #![cfg_attr(bench, feature(test))] - // Coding conventions. #![warn(missing_docs)] - // Instead of littering the codebase for non-fuzzing code just globally allow. #![cfg_attr(hashes_fuzz, allow(dead_code, unused_imports))] - // Exclude lints we don't think are valuable. #![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134 #![allow(clippy::manual_range_contains)] // More readable than clippy's format. diff --git a/internals/src/lib.rs b/internals/src/lib.rs index 25c997e24..326a7b351 100644 --- a/internals/src/lib.rs +++ b/internals/src/lib.rs @@ -7,13 +7,10 @@ //! #![no_std] - // Experimental features we need. #![cfg_attr(docsrs, feature(doc_auto_cfg))] - // Coding conventions. #![warn(missing_docs)] - // Exclude lints we don't think are valuable. #![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134 #![allow(clippy::manual_range_contains)] // More readable than clippy's format. diff --git a/io/src/lib.rs b/io/src/lib.rs index ed223b653..373e7a05b 100644 --- a/io/src/lib.rs +++ b/io/src/lib.rs @@ -9,13 +9,10 @@ //! `std::io`'s traits without unnecessary complexity. #![cfg_attr(not(feature = "std"), no_std)] - // Experimental features we need. #![cfg_attr(docsrs, feature(doc_auto_cfg))] - // Coding conventions. #![warn(missing_docs)] - // Exclude lints we don't think are valuable. #![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134 #![allow(clippy::manual_range_contains)] // More readable than clippy's format. @@ -325,11 +322,11 @@ pub fn sink() -> Sink { Sink } #[cfg(test)] mod tests { - use super::*; - #[cfg(all(not(feature = "std"), feature = "alloc"))] use alloc::{string::ToString, vec}; + use super::*; + #[test] fn buf_read_fill_and_consume_slice() { let data = [0_u8, 1, 2]; diff --git a/units/src/amount.rs b/units/src/amount.rs index 563c9e991..aecc6cbec 100644 --- a/units/src/amount.rs +++ b/units/src/amount.rs @@ -5,21 +5,19 @@ //! This module mainly introduces the [Amount] and [SignedAmount] types. //! We refer to the documentation on the types for more information. +#[cfg(feature = "alloc")] +use alloc::string::{String, ToString}; use core::cmp::Ordering; -use core::fmt; #[cfg(feature = "alloc")] use core::fmt::Write as _; use core::str::FromStr; -use core::{default, ops}; +use core::{default, fmt, ops}; #[cfg(feature = "serde")] use ::serde::{Deserialize, Serialize}; use internals::error::InputString; use internals::write_err; -#[cfg(feature = "alloc")] -use alloc::string::{String, ToString}; - /// A set of denominations in which amounts can be expressed. /// /// # Examples @@ -196,7 +194,8 @@ impl fmt::Display for ParseError { ParseError::Denomination(error) => write_err!(f, "invalid denomination"; error), // We consider this to not be a source because it currently doesn't contain useful // information - ParseError::MissingDenomination(_) => f.write_str("the input doesn't contain a denomination"), + ParseError::MissingDenomination(_) => + f.write_str("the input doesn't contain a denomination"), } } } @@ -231,28 +230,19 @@ pub enum ParseAmountError { } impl From<TooPreciseError> for ParseAmountError { - fn from(value: TooPreciseError) -> Self { - Self::TooPrecise(value) - } + fn from(value: TooPreciseError) -> Self { Self::TooPrecise(value) } } impl From<MissingDigitsError> for ParseAmountError { - fn from(value: MissingDigitsError) -> Self { - Self::MissingDigits(value) - } + fn from(value: MissingDigitsError) -> Self { Self::MissingDigits(value) } } impl From<InputTooLargeError> for ParseAmountError { - fn from(value: InputTooLargeError) -> Self { - Self::InputTooLarge(value) - } + fn from(value: InputTooLargeError) -> Self { Self::InputTooLarge(value) } } - impl From<InvalidCharacterError> for ParseAmountError { - fn from(value: InvalidCharacterError) -> Self { - Self::InvalidCharacter(value) - } + fn from(value: InvalidCharacterError) -> Self { Self::InvalidCharacter(value) } } internals::impl_from_infallible!(ParseAmountError); @@ -305,21 +295,12 @@ impl OutOfRangeError { } /// Returns true if the input value was large than the maximum allowed value. - pub fn is_above_max(&self) -> bool { - self.is_greater_than_max - } + pub fn is_above_max(&self) -> bool { self.is_greater_than_max } /// Returns true if the input value was smaller than the minimum allowed value. - pub fn is_below_min(&self) -> bool { - !self.is_greater_than_max - } + pub fn is_below_min(&self) -> bool { !self.is_greater_than_max } - pub(crate) fn too_big(is_signed: bool) -> Self { - Self { - is_signed, - is_greater_than_max: true, - } - } + pub(crate) fn too_big(is_signed: bool) -> Self { Self { is_signed, is_greater_than_max: true } } pub(crate) fn too_small() -> Self { Self { @@ -352,9 +333,7 @@ impl fmt::Display for OutOfRangeError { impl std::error::Error for OutOfRangeError {} impl From<OutOfRangeError> for ParseAmountError { - fn from(value: OutOfRangeError) -> Self { - ParseAmountError::OutOfRange(value) - } + fn from(value: OutOfRangeError) -> Self { ParseAmountError::OutOfRange(value) } } /// Error returned when the input string has higher precision than satoshis. @@ -367,7 +346,11 @@ impl fmt::Display for TooPreciseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.position { 0 => f.write_str("the amount is less than 1 satoshi but it's not zero"), - pos => write!(f, "the digits starting from position {} represent a sub-satoshi amount", pos), + pos => write!( + f, + "the digits starting from position {} represent a sub-satoshi amount", + pos + ), } } } @@ -384,8 +367,16 @@ pub struct InputTooLargeError { impl fmt::Display for InputTooLargeError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.len - INPUT_STRING_LEN_LIMIT { - 1 => write!(f, "the input is one character longer than the maximum allowed length ({})", INPUT_STRING_LEN_LIMIT), - n => write!(f, "the input is {} characters longer than the maximum allowed length ({})", n, INPUT_STRING_LEN_LIMIT), + 1 => write!( + f, + "the input is one character longer than the maximum allowed length ({})", + INPUT_STRING_LEN_LIMIT + ), + n => write!( + f, + "the input is {} characters longer than the maximum allowed length ({})", + n, INPUT_STRING_LEN_LIMIT + ), } } } @@ -405,7 +396,8 @@ impl fmt::Display for MissingDigitsError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.kind { MissingDigitsKind::Empty => f.write_str("the input is empty"), - MissingDigitsKind::OnlyMinusSign => f.write_str("there are no digits following the minus (-) sign"), + MissingDigitsKind::OnlyMinusSign => + f.write_str("there are no digits following the minus (-) sign"), } } } @@ -431,7 +423,11 @@ impl fmt::Display for InvalidCharacterError { match self.invalid_char { '.' => f.write_str("there is more than one decimal separator (dot) in the input"), '-' => f.write_str("there is more than one minus sign (-) in the input"), - c => write!(f, "the character '{}' at position {} is not a valid digit", c, self.position), + c => write!( + f, + "the character '{}' at position {} is not a valid digit", + c, self.position + ), } } } @@ -515,17 +511,18 @@ impl std::error::Error for PossiblyConfusingDenominationError { /// The position indicates the first digit that is too precise. fn is_too_precise(s: &str, precision: usize) -> Option<usize> { match s.find('.') { - Some(pos) if precision >= pos => { Some(0) }, - Some(pos) => { - s[..pos].char_indices().rev().take(precision).find(|(_, d)| *d != '0').map(|(i, _)| i) - .or_else(|| { - s[(pos + 1)..].char_indices().find(|(_, d)| *d != '0').map(|(i, _)| i + pos + 1) - }) - }, - None if precision >= s.len() => { Some(0) }, - None => { - s.char_indices().rev().take(precision).find(|(_, d)| *d != '0').map(|(i, _)| i) - }, + Some(pos) if precision >= pos => Some(0), + Some(pos) => s[..pos] + .char_indices() + .rev() + .take(precision) + .find(|(_, d)| *d != '0') + .map(|(i, _)| i) + .or_else(|| { + s[(pos + 1)..].char_indices().find(|(_, d)| *d != '0').map(|(i, _)| i + pos + 1) + }), + None if precision >= s.len() => Some(0), + None => s.char_indices().rev().take(precision).find(|(_, d)| *d != '0').map(|(i, _)| i), } } @@ -538,7 +535,9 @@ fn parse_signed_to_satoshi( denom: Denomination, ) -> Result<(bool, u64), InnerParseError> { if s.is_empty() { - return Err(InnerParseError::MissingDigits(MissingDigitsError { kind: MissingDigitsKind::Empty })); + return Err(InnerParseError::MissingDigits(MissingDigitsError { + kind: MissingDigitsKind::Empty, + })); } if s.len() > INPUT_STRING_LEN_LIMIT { return Err(InnerParseError::InputTooLarge(s.len())); @@ -547,7 +546,9 @@ fn parse_signed_to_satoshi( let is_negative = s.starts_with('-'); if is_negative { if s.len() == 1 { - return Err(InnerParseError::MissingDigits(MissingDigitsError { kind: MissingDigitsKind::OnlyMinusSign })); + return Err(InnerParseError::MissingDigits(MissingDigitsError { + kind: MissingDigitsKind::OnlyMinusSign, + })); } s = &s[1..]; } @@ -565,7 +566,10 @@ fn parse_signed_to_satoshi( if let Some(position) = is_too_precise(s, last_n) { match s.parse::<i64>() { Ok(0) => return Ok((is_negative, 0)), - _ => return Err(InnerParseError::TooPrecise(TooPreciseError { position: position + is_negative as usize })), + _ => + return Err(InnerParseError::TooPrecise(TooPreciseError { + position: position + is_negative as usize, + })), } } s = &s[0..s.find('.').unwrap_or(s.len()) - last_n]; @@ -592,16 +596,27 @@ fn parse_signed_to_satoshi( decimals = match decimals { None => None, Some(d) if d < max_decimals => Some(d + 1), - _ => return Err(InnerParseError::TooPrecise(TooPreciseError { position: i + is_negative as usize, })), + _ => + return Err(InnerParseError::TooPrecise(TooPreciseError { + position: i + is_negative as usize, + })), }; } '.' => match decimals { None if max_decimals <= 0 => break, None => decimals = Some(0), // Double decimal dot. - _ => return Err(InnerParseError::InvalidCharacter(InvalidCharacterError { invalid_char: '.', position: i + is_negative as usize })), + _ => + return Err(InnerParseError::InvalidCharacter(InvalidCharacterError { + invalid_char: '.', + position: i + is_negative as usize, + })), }, - c => return Err(InnerParseError::InvalidCharacter(InvalidCharacterError { invalid_char: c, position: i + is_negative as usize })), + c => + return Err(InnerParseError::InvalidCharacter(InvalidCharacterError { + invalid_char: c, + position: i + is_negative as usize, + })), } } @@ -630,7 +645,8 @@ internals::impl_from_infallible!(InnerParseError); impl InnerParseError { fn convert(self, is_signed: bool) -> ParseAmountError { match self { - Self::Overflow { is_negative } => OutOfRangeError { is_signed, is_greater_than_max: !is_negative }.into(), + Self::Overflow { is_negative } => + OutOfRangeError { is_signed, is_greater_than_max: !is_negative }.into(), Self::TooPrecise(error) => ParseAmountError::TooPrecise(error), Self::MissingDigits(error) => ParseAmountError::MissingDigits(error), Self::InputTooLarge(len) => ParseAmountError::InputTooLarge(InputTooLargeError { len }), @@ -643,7 +659,9 @@ fn split_amount_and_denomination(s: &str) -> Result<(&str, Denomination), ParseE let (i, j) = if let Some(i) = s.find(' ') { (i, i + 1) } else { - let i = s.find(|c: char| c.is_alphabetic()).ok_or(ParseError::MissingDenomination(MissingDenominationError))?; + let i = s + .find(|c: char| c.is_alphabetic()) + .ok_or(ParseError::MissingDenomination(MissingDenominationError))?; (i, i) }; Ok((&s[..i], s[j..].parse()?)) @@ -889,8 +907,8 @@ impl Amount { /// Note: This only parses the value string. If you want to parse a value /// with denomination, use [FromStr]. pub fn from_str_in(s: &str, denom: Denomination) -> Result<Amount, ParseAmountError> { - let (negative, satoshi) = parse_signed_to_satoshi(s, denom) - .map_err(|error| error.convert(false))?; + let (negative, satoshi) = + parse_signed_to_satoshi(s, denom).map_err(|error| error.convert(false))?; if negative { return Err(ParseAmountError::OutOfRange(OutOfRangeError::negative())); } @@ -1027,16 +1045,12 @@ impl Amount { /// Unchecked addition. /// /// Computes `self + rhs`. Panics in debug mode, wraps in release mode. - pub fn unchecked_add(self, rhs: Amount) -> Amount { - Self(self.0 + rhs.0) - } + pub fn unchecked_add(self, rhs: Amount) -> Amount { Self(self.0 + rhs.0) } /// Unchecked subtraction. /// /// Computes `self - rhs`. Panics in debug mode, wraps in release mode. - pub fn unchecked_sub(self, rhs: Amount) -> Amount { - Self(self.0 - rhs.0) - } + pub fn unchecked_sub(self, rhs: Amount) -> Amount { Self(self.0 - rhs.0) } /// Convert to a signed amount. pub fn to_signed(self) -> Result<SignedAmount, OutOfRangeError> { @@ -1053,9 +1067,7 @@ impl default::Default for Amount { } impl fmt::Debug for Amount { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - write!(f, "{} GRO", self.to_sat()) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{} GRO", self.to_sat()) } } // No one should depend on a binding contract for Display for this type. @@ -1134,9 +1146,7 @@ impl FromStr for Amount { impl TryFrom<SignedAmount> for Amount { type Error = OutOfRangeError; - fn try_from(value: SignedAmount) -> Result<Self, Self::Error> { - value.to_unsigned() - } + fn try_from(value: SignedAmount) -> Result<Self, Self::Error> { value.to_unsigned() } } impl core::iter::Sum for Amount { @@ -1255,10 +1265,12 @@ impl SignedAmount { pub fn from_str_in(s: &str, denom: Denomination) -> Result<SignedAmount, ParseAmountError> { match parse_signed_to_satoshi(s, denom).map_err(|error| error.convert(true))? { // (negative, amount) - (false, sat) if sat > i64::MAX as u64 => Err(ParseAmountError::OutOfRange(OutOfRangeError::too_big(true))), + (false, sat) if sat > i64::MAX as u64 => + Err(ParseAmountError::OutOfRange(OutOfRangeError::too_big(true))), (false, sat) => Ok(SignedAmount(sat as i64)), (true, sat) if sat == i64::MIN.unsigned_abs() => Ok(SignedAmount(i64::MIN)), - (true, sat) if sat > i64::MIN.unsigned_abs() => Err(ParseAmountError::OutOfRange(OutOfRangeError::too_small())), + (true, sat) if sat > i64::MIN.unsigned_abs() => + Err(ParseAmountError::OutOfRange(OutOfRangeError::too_small())), (true, sat) => Ok(SignedAmount(-(sat as i64))), } } @@ -1414,16 +1426,12 @@ impl SignedAmount { /// Unchecked addition. /// /// Computes `self + rhs`. Panics in debug mode, wraps in release mode. - pub fn unchecked_add(self, rhs: SignedAmount) -> SignedAmount { - Self(self.0 + rhs.0) - } + pub fn unchecked_add(self, rhs: SignedAmount) -> SignedAmount { Self(self.0 + rhs.0) } /// Unchecked subtraction. /// /// Computes `self - rhs`. Panics in debug mode, wraps in release mode. - pub fn unchecked_sub(self, rhs: SignedAmount) -> SignedAmount { - Self(self.0 - rhs.0) - } + pub fn unchecked_sub(self, rhs: SignedAmount) -> SignedAmount { Self(self.0 - rhs.0) } /// Subtraction that doesn't allow negative [SignedAmount]s. /// Returns [None] if either [self], `rhs` or the result is strictly negative. @@ -1539,9 +1547,7 @@ impl FromStr for SignedAmount { impl TryFrom<Amount> for SignedAmount { type Error = OutOfRangeError; - fn try_from(value: Amount) -> Result<Self, Self::Error> { - value.to_signed() - } + fn try_from(value: Amount) -> Result<Self, Self::Error> { value.to_signed() } } impl core::iter::Sum for SignedAmount { @@ -1612,11 +1618,12 @@ pub mod serde { //! ``` use core::fmt; + use serde::{Deserialize, Deserializer, Serialize, Serializer}; - use super::{Amount, SignedAmount, ParseAmountError}; #[cfg(feature = "alloc")] use super::Denomination; + use super::{Amount, ParseAmountError, SignedAmount}; /// This trait is used only to avoid code duplication and naming collisions /// of the different serde serialization crates. @@ -1661,9 +1668,7 @@ pub mod serde { #[cfg(not(feature = "std"))] impl fmt::Display for DisplayFullError { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - fmt::Display::fmt(&self.0, f) - } + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Display::fmt(&self.0, f) } } impl SerdeAmount for Amount { @@ -1732,10 +1737,9 @@ pub mod serde { //! Serialize and deserialize [`Amount`](crate::Amount) as real numbers denominated in satoshi. //! Use with `#[serde(with = "amount::serde::as_sat")]`. //! - use super::private; - use serde::{Deserializer, Serializer}; + use super::private; use crate::amount::serde::SerdeAmount; pub fn serialize<A: SerdeAmount, S: Serializer>(a: &A, s: S) -> Result<S::Ok, S::Error> { @@ -1750,12 +1754,12 @@ pub mod serde { //! Serialize and deserialize [`Option<Amount>`](crate::Amount) as real numbers denominated in satoshi. //! Use with `#[serde(default, with = "amount::serde::as_sat::opt")]`. - use super::private; use core::fmt; use core::marker::PhantomData; use serde::{de, Deserializer, Serializer}; + use super::private; use crate::amount::serde::SerdeAmountForOpt; pub fn serialize<A: SerdeAmountForOpt, S: Serializer>( @@ -1803,10 +1807,9 @@ pub mod serde { //! Serialize and deserialize [`Amount`](crate::Amount) as JSON numbers denominated in GRS. //! Use with `#[serde(with = "amount::serde::as_btc")]`. - use super::private; - use serde::{Deserializer, Serializer}; + use super::private; use crate::amount::serde::SerdeAmount; pub fn serialize<A: SerdeAmount, S: Serializer>(a: &A, s: S) -> Result<S::Ok, S::Error> { @@ -1821,12 +1824,12 @@ pub mod serde { //! Serialize and deserialize `Option<Amount>` as JSON numbers denominated in GRS. //! Use with `#[serde(default, with = "amount::serde::as_btc::opt")]`. - use super::private; use core::fmt; use core::marker::PhantomData; use serde::{de, Deserializer, Serializer}; + use super::private; use crate::amount::serde::SerdeAmountForOpt; pub fn serialize<A: SerdeAmountForOpt, S: Serializer>( @@ -1962,10 +1965,7 @@ mod verification { if n1 >= 0 { Ok(Amount::from_sat(n1.try_into().unwrap())) } else { - Err(OutOfRangeError { - is_signed: true, - is_greater_than_max: false - }) + Err(OutOfRangeError { is_signed: true, is_greater_than_max: false }) }, ); } @@ -1999,7 +1999,6 @@ mod verification { mod tests { #[cfg(feature = "alloc")] use alloc::format; - #[cfg(feature = "std")] use std::panic; @@ -2020,7 +2019,10 @@ mod tests { let s = format!("-0 {}", denom); match Amount::from_str(&s) { - Err(e) => assert_eq!(e, ParseError::Amount(ParseAmountError::OutOfRange(OutOfRangeError::negative()))), + Err(e) => assert_eq!( + e, + ParseError::Amount(ParseAmountError::OutOfRange(OutOfRangeError::negative())) + ), Ok(_) => panic!("Unsigned amount from {}", s), } match SignedAmount::from_str(&s) { @@ -2048,13 +2050,7 @@ mod tests { let ua_max = Amount::MAX; let result = SignedAmount::try_from(ua_max); - assert_eq!( - result, - Err(OutOfRangeError { - is_signed: true, - is_greater_than_max: true - }) - ); + assert_eq!(result, Err(OutOfRangeError { is_signed: true, is_greater_than_max: true })); } #[test] @@ -2065,13 +2061,7 @@ mod tests { let sa_negative = SignedAmount(-123); let result = Amount::try_from(sa_negative); - assert_eq!( - result, - Err(OutOfRangeError { - is_signed: false, - is_greater_than_max: false - }) - ); + assert_eq!(result, Err(OutOfRangeError { is_signed: false, is_greater_than_max: false })); } #[test] @@ -2166,7 +2156,10 @@ mod tests { assert_eq!(sf(-100.0, D::MilliSatoshi), Err(TooPreciseError { position: 1 }.into())); assert_eq!(f(42.123456781, D::Bitcoin), Err(TooPreciseError { position: 11 }.into())); assert_eq!(sf(-184467440738.0, D::Bitcoin), Err(OutOfRangeError::too_small().into())); - assert_eq!(f(18446744073709551617.0, D::Satoshi), Err(OutOfRangeError::too_big(false).into())); + assert_eq!( + f(18446744073709551617.0, D::Satoshi), + Err(OutOfRangeError::too_big(false).into()) + ); // Amount can be grater than the max SignedAmount. assert!(f(SignedAmount::MAX.to_float_in(D::Satoshi) + 1.0, D::Satoshi).is_ok()); @@ -2201,12 +2194,30 @@ mod tests { let p = Amount::from_str_in; let sp = SignedAmount::from_str_in; - assert_eq!(p("x", btc), Err(E::from(InvalidCharacterError { invalid_char: 'x', position: 0 }))); - assert_eq!(p("-", btc), Err(E::from(MissingDigitsError { kind: MissingDigitsKind::OnlyMinusSign }))); - assert_eq!(sp("-", btc), Err(E::from(MissingDigitsError { kind: MissingDigitsKind::OnlyMinusSign }))); - assert_eq!(p("-1.0x", btc), Err(E::from(InvalidCharacterError { invalid_char: 'x', position: 4 }))); - assert_eq!(p("0.0 ", btc), Err(E::from(InvalidCharacterError { invalid_char: ' ', position: 3 }))); - assert_eq!(p("0.000.000", btc), Err(E::from(InvalidCharacterError { invalid_char: '.', position: 5 }))); + assert_eq!( + p("x", btc), + Err(E::from(InvalidCharacterError { invalid_char: 'x', position: 0 })) + ); + assert_eq!( + p("-", btc), + Err(E::from(MissingDigitsError { kind: MissingDigitsKind::OnlyMinusSign })) + ); + assert_eq!( + sp("-", btc), + Err(E::from(MissingDigitsError { kind: MissingDigitsKind::OnlyMinusSign })) + ); + assert_eq!( + p("-1.0x", btc), + Err(E::from(InvalidCharacterError { invalid_char: 'x', position: 4 })) + ); + assert_eq!( + p("0.0 ", btc), + Err(E::from(InvalidCharacterError { invalid_char: ' ', position: 3 })) + ); + assert_eq!( + p("0.000.000", btc), + Err(E::from(InvalidCharacterError { invalid_char: '.', position: 5 })) + ); #[cfg(feature = "alloc")] let more_than_max = format!("1{}", Amount::MAX); #[cfg(feature = "alloc")] @@ -2244,11 +2255,16 @@ mod tests { { let amount = Amount::from_sat(i64::MAX as u64); assert_eq!(Amount::from_str_in(&amount.to_string_in(sat), sat), Ok(amount)); - assert!(SignedAmount::from_str_in(&(amount + Amount(1)).to_string_in(sat), sat).is_err()); + assert!( + SignedAmount::from_str_in(&(amount + Amount(1)).to_string_in(sat), sat).is_err() + ); assert!(Amount::from_str_in(&(amount + Amount(1)).to_string_in(sat), sat).is_ok()); } - assert_eq!(p("12.000", Denomination::MilliSatoshi), Err(TooPreciseError { position: 0 }.into())); + assert_eq!( + p("12.000", Denomination::MilliSatoshi), + Err(TooPreciseError { position: 0 }.into()) + ); // exactly 50 chars. assert_eq!( p("100000000000000.0000000000000000000000000000000000", Denomination::Bitcoin), @@ -2488,7 +2504,10 @@ mod tests { use super::ParseAmountError as E; - assert_eq!(Amount::from_str("x GRS"), Err(E::from(E::from(InvalidCharacterError { invalid_char: 'x', position: 0 })).into())); + assert_eq!( + Amount::from_str("x GRS"), + Err(E::from(E::from(InvalidCharacterError { invalid_char: 'x', position: 0 })).into()) + ); assert_eq!( Amount::from_str("xGRS"), Err(Unknown(UnknownDenominationError("xGRS".into())).into()), @@ -2497,7 +2516,10 @@ mod tests { Amount::from_str("5 GRS GRS"), Err(Unknown(UnknownDenominationError("GRS GRS".into())).into()), ); - assert_eq!(Amount::from_str("5GRS GRS"), Err(E::from(InvalidCharacterError { invalid_char: 'G', position: 1 }).into())); + assert_eq!( + Amount::from_str("5GRS GRS"), + Err(E::from(InvalidCharacterError { invalid_char: 'G', position: 1 }).into()) + ); assert_eq!( Amount::from_str("5 5 GRS"), Err(Unknown(UnknownDenominationError("5 GRS".into())).into()), @@ -2720,7 +2742,10 @@ mod tests { // errors let t: Result<T, serde_json::Error> = serde_json::from_str("{\"amt\": 1000000.000000001, \"samt\": 1}"); - assert!(t.unwrap_err().to_string().contains(&ParseAmountError::TooPrecise(TooPreciseError { position: 16 }).to_string())); + assert!(t + .unwrap_err() + .to_string() + .contains(&ParseAmountError::TooPrecise(TooPreciseError { position: 16 }).to_string())); let t: Result<T, serde_json::Error> = serde_json::from_str("{\"amt\": -1, \"samt\": 1}"); assert!(t.unwrap_err().to_string().contains(&OutOfRangeError::negative().to_string())); } @@ -2818,11 +2843,8 @@ mod tests { let sum = amounts.into_iter().sum::<Amount>(); assert_eq!(Amount::from_sat(1400), sum); - let amounts = [ - SignedAmount::from_sat(-42), - SignedAmount::from_sat(1337), - SignedAmount::from_sat(21), - ]; + let amounts = + [SignedAmount::from_sat(-42), SignedAmount::from_sat(1337), SignedAmount::from_sat(21)]; let sum = amounts.into_iter().sum::<SignedAmount>(); assert_eq!(SignedAmount::from_sat(1316), sum); } @@ -2836,8 +2858,7 @@ mod tests { let sum = amounts.into_iter().checked_sum(); assert_eq!(Some(Amount::from_sat(1400)), sum); - let amounts = - [Amount::from_sat(u64::MAX), Amount::from_sat(1337), Amount::from_sat(21)]; + let amounts = [Amount::from_sat(u64::MAX), Amount::from_sat(1337), Amount::from_sat(21)]; let sum = amounts.into_iter().checked_sum(); assert_eq!(None, sum); @@ -2857,11 +2878,8 @@ mod tests { let sum = amounts.into_iter().checked_sum(); assert_eq!(None, sum); - let amounts = [ - SignedAmount::from_sat(42), - SignedAmount::from_sat(3301), - SignedAmount::from_sat(21), - ]; + let amounts = + [SignedAmount::from_sat(42), SignedAmount::from_sat(3301), SignedAmount::from_sat(21)]; let sum = amounts.into_iter().checked_sum(); assert_eq!(Some(SignedAmount::from_sat(3364)), sum); } diff --git a/units/src/lib.rs b/units/src/lib.rs index 1f034d437..6c535dfa2 100644 --- a/units/src/lib.rs +++ b/units/src/lib.rs @@ -6,14 +6,11 @@ // Experimental features we need. #![cfg_attr(docsrs, feature(doc_auto_cfg))] - // Coding conventions. #![warn(missing_docs)] - // Exclude lints we don't think are valuable. #![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134 #![allow(clippy::manual_range_contains)] // More readable than clippy's format. - #![no_std] // Disable 16-bit support at least for now as we can't guarantee it yet.