From 5eefe85ab9edb2a4c4accf9b97082948702f2c28 Mon Sep 17 00:00:00 2001 From: Riccardo Casatta Date: Wed, 14 Aug 2024 11:25:47 +0200 Subject: [PATCH 1/6] apply rustfmt to address.rs --- src/address.rs | 101 ++++++++++++++++++++++++++++++++++--------------- 1 file changed, 71 insertions(+), 30 deletions(-) diff --git a/src/address.rs b/src/address.rs index 002c47e3..ac0d295a 100644 --- a/src/address.rs +++ b/src/address.rs @@ -21,11 +21,11 @@ use std::fmt; use std::fmt::Write as _; use std::str::FromStr; -use bitcoin::base58; -use bitcoin::PublicKey; -use crate::bech32::{Bech32, Bech32m, ByteIterExt, Fe32, Hrp, Fe32IterExt}; +use crate::bech32::{Bech32, Bech32m, ByteIterExt, Fe32, Fe32IterExt, Hrp}; use crate::blech32::{Blech32, Blech32m}; use crate::hashes::Hash; +use bitcoin::base58; +use bitcoin::PublicKey; use secp256k1_zkp; use secp256k1_zkp::Secp256k1; use secp256k1_zkp::Verification; @@ -35,8 +35,8 @@ use serde; use crate::schnorr::{TapTweak, TweakedPublicKey, UntweakedPublicKey}; use crate::taproot::TapNodeHash; -use crate::{PubkeyHash, ScriptHash, WPubkeyHash, WScriptHash}; use crate::{opcodes, script}; +use crate::{PubkeyHash, ScriptHash, WPubkeyHash, WScriptHash}; /// Encoding error #[derive(Debug, PartialEq)] @@ -89,10 +89,18 @@ impl fmt::Display for AddressError { write!(f, "invalid witness script version: {}", wver) } AddressError::InvalidWitnessProgramLength(ref len) => { - write!(f, "the witness program must be between 2 and 40 bytes in length, not {}", len) + write!( + f, + "the witness program must be between 2 and 40 bytes in length, not {}", + len + ) } AddressError::InvalidSegwitV0ProgramLength(ref len) => { - write!(f, "a v0 witness program must be length 20 or 32, not {}", len) + write!( + f, + "a v0 witness program must be length 20 or 32, not {}", + len + ) } AddressError::InvalidBlindingPubKey(ref e) => { write!(f, "an invalid blinding pubkey was encountered: {}", e) @@ -212,7 +220,8 @@ impl Address { params: &'static AddressParams, ) -> Address { let mut hash_engine = PubkeyHash::engine(); - pk.write_into(&mut hash_engine).expect("engines don't error"); + pk.write_into(&mut hash_engine) + .expect("engines don't error"); Address { params, @@ -244,7 +253,8 @@ impl Address { params: &'static AddressParams, ) -> Address { let mut hash_engine = WPubkeyHash::engine(); - pk.write_into(&mut hash_engine).expect("engines don't error"); + pk.write_into(&mut hash_engine) + .expect("engines don't error"); Address { params, @@ -264,7 +274,8 @@ impl Address { params: &'static AddressParams, ) -> Address { let mut hash_engine = ScriptHash::engine(); - pk.write_into(&mut hash_engine).expect("engines don't error"); + pk.write_into(&mut hash_engine) + .expect("engines don't error"); let builder = script::Builder::new() .push_int(0) @@ -401,7 +412,9 @@ impl Address { Payload::WitnessProgram { version: witver, program: ref witprog, - } => script::Builder::new().push_int(witver.to_u8() as i64).push_slice(witprog), + } => script::Builder::new() + .push_int(witver.to_u8() as i64) + .push_slice(witprog), } .into_script() } @@ -450,10 +463,7 @@ impl Address { Ok(Address { params, - payload: Payload::WitnessProgram { - version, - program, - }, + payload: Payload::WitnessProgram { version, program }, blinding_pubkey, }) } @@ -574,14 +584,23 @@ impl fmt::Display for Address { // FIXME: surely we can fix this logic to not be so repetitive. if self.is_blinded() { if let Some(ref blinder) = self.blinding_pubkey { - let byte_iter = IntoIterator::into_iter(blinder.serialize()).chain(witprog.iter().copied()); + let byte_iter = IntoIterator::into_iter(blinder.serialize()) + .chain(witprog.iter().copied()); let fe_iter = byte_iter.bytes_to_fes(); if witver.to_u8() == 0 { - for c in fe_iter.with_checksum::(&hrp).with_witness_version(witver).chars() { + for c in fe_iter + .with_checksum::(&hrp) + .with_witness_version(witver) + .chars() + { fmt.write_char(c)?; } } else { - for c in fe_iter.with_checksum::(&hrp).with_witness_version(witver).chars() { + for c in fe_iter + .with_checksum::(&hrp) + .with_witness_version(witver) + .chars() + { fmt.write_char(c)?; } } @@ -592,11 +611,19 @@ impl fmt::Display for Address { let byte_iter = witprog.iter().copied(); let fe_iter = byte_iter.bytes_to_fes(); if witver.to_u8() == 0 { - for c in fe_iter.with_checksum::(&hrp).with_witness_version(witver).chars() { + for c in fe_iter + .with_checksum::(&hrp) + .with_witness_version(witver) + .chars() + { fmt.write_char(c)?; } } else { - for c in fe_iter.with_checksum::(&hrp).with_witness_version(witver).chars() { + for c in fe_iter + .with_checksum::(&hrp) + .with_witness_version(witver) + .chars() + { fmt.write_char(c)?; } } @@ -734,9 +761,9 @@ impl serde::Serialize for Address { #[cfg(test)] mod test { use super::*; + use crate::Script; use bitcoin::key; use secp256k1_zkp::{PublicKey, Secp256k1}; - use crate::Script; #[cfg(feature = "serde")] use serde_json; @@ -755,7 +782,9 @@ mod test { ); #[cfg(feature = "serde")] assert_eq!( - serde_json::from_value::
(serde_json::to_value(addr).unwrap()).ok().as_ref(), + serde_json::from_value::
(serde_json::to_value(addr).unwrap()) + .ok() + .as_ref(), Some(addr) ); } @@ -831,7 +860,12 @@ mod test { for &(a, blinded, ref params) in &addresses { let result = a.parse(); - assert!(result.is_ok(), "vector: {}, err: \"{}\"", a, result.unwrap_err()); + assert!( + result.is_ok(), + "vector: {}, err: \"{}\"", + a, + result.unwrap_err() + ); let addr: Address = result.unwrap(); assert_eq!(a, &addr.to_string(), "vector: {}", a); assert_eq!(blinded, addr.is_blinded()); @@ -858,7 +892,8 @@ mod test { "blech32 error: invalid checksum", // is valid blech32m, but should be blech32 ); - let address: Result = "ert130xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqqu2tys".parse(); + let address: Result = + "ert130xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqqu2tys".parse(); assert_eq!( address.err().unwrap().to_string(), "bech32 error: invalid segwit witness version: 3", // FIXME https://github.com/rust-bitcoin/rust-bech32/issues/162 should be 17 @@ -879,14 +914,18 @@ mod test { ); } - #[test] fn test_fixed_addresses() { - let pk = bitcoin::PublicKey::from_str("0212bf0ea45b733dfde8ecb5e896306c4165c666c99fc5d1ab887f71393a975cea") - .unwrap(); + let pk = bitcoin::PublicKey::from_str( + "0212bf0ea45b733dfde8ecb5e896306c4165c666c99fc5d1ab887f71393a975cea", + ) + .unwrap(); let script = Script::default(); let secp = Secp256k1::verification_only(); - let internal_key = UntweakedPublicKey::from_str("93c7378d96518a75448821c4f7c8f4bae7ce60f804d03d1f0628dd5dd0f5de51").unwrap(); + let internal_key = UntweakedPublicKey::from_str( + "93c7378d96518a75448821c4f7c8f4bae7ce60f804d03d1f0628dd5dd0f5de51", + ) + .unwrap(); let tap_node_hash = TapNodeHash::all_zeros(); let mut expected = IntoIterator::into_iter([ @@ -934,9 +973,12 @@ mod test { "tlq1pqgft7r4ytdenml0gaj67393sd3qkt3nxex0ut5dt3plhzwf6jaww5vx8c8vs0ywzejta7jjcc5f4asnacdtu0wlaas0upmsq90enaz2lekytucqf82vs", ]); - for params in [&AddressParams::ELEMENTS, &AddressParams::LIQUID, &AddressParams::LIQUID_TESTNET] { + for params in [ + &AddressParams::ELEMENTS, + &AddressParams::LIQUID, + &AddressParams::LIQUID_TESTNET, + ] { for blinder in [None, Some(pk.inner)] { - let addr = Address::p2pkh(&pk, blinder, params); assert_eq!(&addr.to_string(), expected.next().unwrap()); @@ -959,6 +1001,5 @@ mod test { assert_eq!(&addr.to_string(), expected.next().unwrap()); } } - } } From 084f7d4279a955d501597c9e37d6dfbe82d8def2 Mon Sep 17 00:00:00 2001 From: Riccardo Casatta Date: Wed, 14 Aug 2024 11:28:29 +0200 Subject: [PATCH 2/6] Avoid instantiating base58 errors in Address::from_base58 This is propedeutic to upgrading to bitcoin 0.32 where this address-related variants are removed from base58::Error --- src/address.rs | 24 ++++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/src/address.rs b/src/address.rs index ac0d295a..edbe3006 100644 --- a/src/address.rs +++ b/src/address.rs @@ -62,6 +62,12 @@ pub enum AddressError { /// An invalid blinding pubkey was encountered. InvalidBlindingPubKey(secp256k1_zkp::UpstreamError), + + /// The length (in bytes) of the object was not correct. + InvalidLength(usize), + + /// Address version byte were not recognized. + InvalidAddressVersion(u8), } impl From for AddressError { @@ -111,6 +117,12 @@ impl fmt::Display for AddressError { AddressError::InvalidSegwitV0Encoding => { write!(f, "v0 witness program must use b(l)ech32 not b(l)ech32m") } + AddressError::InvalidLength(len) => { + write!(f, "Address data has invalid length {}", len) + } + AddressError::InvalidAddressVersion(v) => { + write!(f, "address version {} is invalid for this type", v) + } } } } @@ -478,13 +490,13 @@ impl Address { let (blinded, prefix) = match data[0] == params.blinded_prefix { true => { if data.len() != 55 { - return Err(base58::Error::InvalidLength(data.len()).into()); + return Err(AddressError::InvalidLength(data.len())); } (true, data[1]) } false => { if data.len() != 21 { - return Err(base58::Error::InvalidLength(data.len()).into()); + return Err(AddressError::InvalidLength(data.len())); } (false, data[0]) } @@ -506,7 +518,7 @@ impl Address { } else if prefix == params.p2sh_prefix { Payload::ScriptHash(ScriptHash::from_slice(payload_data).unwrap()) } else { - return Err(base58::Error::InvalidAddressVersion(prefix).into()); + return Err(AddressError::InvalidAddressVersion(prefix)); }; Ok(Address { @@ -532,7 +544,7 @@ impl Address { // Base58. if s.len() > 150 { - return Err(base58::Error::InvalidLength(s.len() * 11 / 15).into()); + return Err(AddressError::InvalidLength(s.len() * 11 / 15)); } let data = base58::decode_check(s)?; Address::from_base58(&data, params) @@ -687,11 +699,11 @@ impl FromStr for Address { // Base58. if s.len() > 150 { - return Err(base58::Error::InvalidLength(s.len() * 11 / 15).into()); + return Err(AddressError::InvalidLength(s.len() * 11 / 15)); } let data = base58::decode_check(s)?; if data.is_empty() { - return Err(base58::Error::InvalidLength(data.len()).into()); + return Err(AddressError::InvalidLength(data.len())); } let p = data[0]; From 8ae550b9ad939ea410f28e44df4d614780173f3e Mon Sep 17 00:00:00 2001 From: Riccardo Casatta Date: Wed, 14 Aug 2024 11:57:03 +0200 Subject: [PATCH 3/6] apply rustfmt to src/blind.rs --- src/blind.rs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/blind.rs b/src/blind.rs index c6463249..0b7a533e 100644 --- a/src/blind.rs +++ b/src/blind.rs @@ -26,11 +26,11 @@ use secp256k1_zkp::{Generator, RangeProof, Secp256k1, Signing, SurjectionProof}; use crate::{AddressParams, Script, TxIn}; +use crate::hashes; use crate::{ confidential::{Asset, AssetBlindingFactor, Nonce, Value, ValueBlindingFactor}, Address, AssetId, Transaction, TxOut, TxOutWitness, }; -use crate::hashes; /// Transaction Output related errors #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] @@ -229,7 +229,11 @@ impl RangeProofMessage { } /// Information about Transaction Input Asset -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "actual_serde"))] +#[cfg_attr( + feature = "serde", + derive(Serialize, Deserialize), + serde(crate = "actual_serde") +)] #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)] pub struct TxOutSecrets { /// Asset From 6789492bf1d5d21b1f852bc8ca009eba51f5741c Mon Sep 17 00:00:00 2001 From: Riccardo Casatta Date: Wed, 14 Aug 2024 12:00:49 +0200 Subject: [PATCH 4/6] apply rustfmt to pset/raw.rs --- src/pset/raw.rs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/src/pset/raw.rs b/src/pset/raw.rs index b9e3fdf6..48988226 100644 --- a/src/pset/raw.rs +++ b/src/pset/raw.rs @@ -27,7 +27,11 @@ use crate::hex; use crate::VarInt; /// A PSET key in its raw byte form. #[derive(Debug, PartialEq, Hash, Eq, Clone, Ord, PartialOrd)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "actual_serde"))] +#[cfg_attr( + feature = "serde", + derive(Serialize, Deserialize), + serde(crate = "actual_serde") +)] pub struct Key { /// The type of this PSET key. pub type_value: u8, @@ -50,7 +54,11 @@ impl Key { /// A PSET key-value pair in its raw byte form. #[derive(Debug, PartialEq)] -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "actual_serde"))] +#[cfg_attr( + feature = "serde", + derive(Serialize, Deserialize), + serde(crate = "actual_serde") +)] pub struct Pair { /// The key of this key-value pair. pub key: Key, @@ -64,7 +72,11 @@ pub type ProprietaryType = u8; /// Proprietary keys (i.e. keys starting with 0xFC byte) with their internal /// structure according to BIP 174. -#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "actual_serde"))] +#[cfg_attr( + feature = "serde", + derive(Serialize, Deserialize), + serde(crate = "actual_serde") +)] #[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] pub struct ProprietaryKey where From e9a90cc2f700b8d0a0ed07e93d4490f156967d2b Mon Sep 17 00:00:00 2001 From: Riccardo Casatta Date: Wed, 14 Aug 2024 12:42:36 +0200 Subject: [PATCH 5/6] apply rustfmt to encode.rs --- src/encode.rs | 41 ++++++++++++++++++++++++++--------------- 1 file changed, 26 insertions(+), 15 deletions(-) diff --git a/src/encode.rs b/src/encode.rs index b80a88b1..b161abf6 100644 --- a/src/encode.rs +++ b/src/encode.rs @@ -21,9 +21,9 @@ use std::{error, fmt, io, mem}; use bitcoin::consensus::encode as btcenc; use secp256k1_zkp::{self, RangeProof, SurjectionProof, Tweak}; -use crate::hashes::{Hash, sha256}; -use crate::transaction::{Transaction, TxIn, TxOut}; +use crate::hashes::{sha256, Hash}; use crate::pset; +use crate::transaction::{Transaction, TxIn, TxOut}; pub use bitcoin::{self, consensus::encode::MAX_VEC_SIZE}; @@ -61,7 +61,7 @@ pub enum Error { /// Hex parsing errors HexError(crate::hex::Error), /// Got a time-based locktime when expecting a height-based one, or vice-versa - BadLockTime(crate::LockTime) + BadLockTime(crate::LockTime), } impl fmt::Display for Error { @@ -72,7 +72,11 @@ impl fmt::Display for Error { Error::OversizedVectorAllocation { requested: ref r, max: ref m, - } => write!(f, "oversized vector allocation: requested {}, maximum {}", r, m), + } => write!( + f, + "oversized vector allocation: requested {}, maximum {}", + r, m + ), Error::ParseFailed(ref e) => write!(f, "parse failed: {}", e), Error::UnexpectedEOF => write!(f, "unexpected EOF"), Error::InvalidConfidentialPrefix(p) => { @@ -174,7 +178,9 @@ pub fn deserialize(data: &[u8]) -> Result { if consumed == data.len() { Ok(rv) } else { - Err(Error::ParseFailed("data not consumed entirely when explicitly deserializing")) + Err(Error::ParseFailed( + "data not consumed entirely when explicitly deserializing", + )) } } @@ -200,7 +206,10 @@ impl Decodable for sha256::Midstate { } } -pub(crate) fn consensus_encode_with_size(data: &[u8], mut s: S) -> Result { +pub(crate) fn consensus_encode_with_size( + data: &[u8], + mut s: S, +) -> Result { let vi_len = bitcoin::VarInt(data.len() as u64).consensus_encode(&mut s)?; s.emit_slice(data)?; Ok(vi_len + data.len()) @@ -252,7 +261,6 @@ impl Decodable for crate::locktime::Height { } } - impl Encodable for crate::locktime::Time { fn consensus_encode(&self, s: S) -> Result { crate::LockTime::from(*self).consensus_encode(s) @@ -267,7 +275,6 @@ impl Decodable for crate::locktime::Time { } } - // Vectors macro_rules! impl_vec { ($type: ty) => { @@ -310,7 +317,6 @@ impl_vec!(TxOut); impl_vec!(Transaction); impl_vec!(TapLeafHash); - macro_rules! impl_box_option { ($type: ty) => { impl Encodable for Option> { @@ -326,7 +332,7 @@ macro_rules! impl_box_option { impl Decodable for Option> { #[inline] fn consensus_decode(mut d: D) -> Result { - let v : Vec = Decodable::consensus_decode(&mut d)?; + let v: Vec = Decodable::consensus_decode(&mut d)?; if v.is_empty() { Ok(None) } else { @@ -334,7 +340,7 @@ macro_rules! impl_box_option { } } } - } + }; } // special implementations for elements only fields impl Encodable for Tweak { @@ -369,11 +375,12 @@ impl Encodable for SurjectionProof { impl Decodable for SurjectionProof { fn consensus_decode(d: D) -> Result { - Ok(SurjectionProof::from_slice(&>::consensus_decode(d)?)?) + Ok(SurjectionProof::from_slice(&>::consensus_decode( + d, + )?)?) } } - impl Encodable for sha256::Hash { fn consensus_encode(&self, s: S) -> Result { self.to_byte_array().consensus_encode(s) @@ -382,7 +389,9 @@ impl Encodable for sha256::Hash { impl Decodable for sha256::Hash { fn consensus_decode(d: D) -> Result { - Ok(Self::from_byte_array(<::Bytes>::consensus_decode(d)?)) + Ok(Self::from_byte_array( + <::Bytes>::consensus_decode(d)?, + )) } } @@ -394,7 +403,9 @@ impl Encodable for TapLeafHash { impl Decodable for TapLeafHash { fn consensus_decode(d: D) -> Result { - Ok(Self::from_byte_array(<::Bytes>::consensus_decode(d)?)) + Ok(Self::from_byte_array( + <::Bytes>::consensus_decode(d)?, + )) } } From 42697283241bd251309a2d0ca3e1aadc2cc1e65d Mon Sep 17 00:00:00 2001 From: Riccardo Casatta Date: Wed, 14 Aug 2024 11:58:08 +0200 Subject: [PATCH 6/6] apply tomlfmt to Cargo.toml --- Cargo.toml | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index a05481b1..d0f337a6 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,32 +10,35 @@ documentation = "https://docs.rs/elements/" edition = "2018" [features] -default = [ "json-contract" ] +default = ["json-contract"] -json-contract = [ "serde_json" ] +json-contract = ["serde_json"] "serde" = [ "bitcoin/serde", "bitcoin/serde", "secp256k1-zkp/serde", - "actual-serde" + "actual-serde", ] base64 = ["bitcoin/base64"] [dependencies] bitcoin = "0.31.0" -secp256k1-zkp = { version = "0.10.0", features = [ "global-context", "hashes" ] } +secp256k1-zkp = { version = "0.10.0", features = ["global-context", "hashes"] } # Used for ContractHash::from_json_contract. serde_json = { version = "1.0", optional = true } -actual-serde = { package="serde", version = "1.0.103", features=["derive"], optional = true } +actual-serde = { package = "serde", version = "1.0.103", features = [ + "derive", +], optional = true } + [dev-dependencies] rand = "0.8" rand_chacha = "0.3" serde_test = "1.0.19" serde_json = "1.0" -serde_cbor = "0.8" # older than latest version to support 1.41.1 +serde_cbor = "0.8" # older than latest version to support 1.41.1 bincode = "1.3" [[example]]