Skip to content

Commit f875ae2

Browse files
committed
Merge #210: Address err refactor
4269728 apply tomlfmt to Cargo.toml (Riccardo Casatta) e9a90cc apply rustfmt to encode.rs (Riccardo Casatta) 6789492 apply rustfmt to pset/raw.rs (Riccardo Casatta) 8ae550b apply rustfmt to src/blind.rs (Riccardo Casatta) 084f7d4 Avoid instantiating base58 errors in Address::from_base58 (Riccardo Casatta) 5eefe85 apply rustfmt to address.rs (Riccardo Casatta) Pull request description: This is propedeutic to upgrade to bitcoin 0.32 #209 where the base58 error variant specific to address are removed Also it applies formatting around on which I think we agreed upon, but also on the toml file which I had doubt, let me know if I have to remove it ACKs for top commit: apoelstra: ACK 4269728 successfully ran local tests Tree-SHA512: 0cdc7077d4ec4550a4df6f5e6eb244c7a8c0793b507c9a4327b30bdaf9f597df0dee7c72e33414df0a87cb10f9a9be12588c9a564d71cb308564cf0226b7dec1
2 parents 25dc2d2 + 4269728 commit f875ae2

5 files changed

Lines changed: 145 additions & 62 deletions

File tree

Cargo.toml

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -10,32 +10,35 @@ documentation = "https://docs.rs/elements/"
1010
edition = "2018"
1111

1212
[features]
13-
default = [ "json-contract" ]
13+
default = ["json-contract"]
1414

15-
json-contract = [ "serde_json" ]
15+
json-contract = ["serde_json"]
1616
"serde" = [
1717
"bitcoin/serde",
1818
"bitcoin/serde",
1919
"secp256k1-zkp/serde",
20-
"actual-serde"
20+
"actual-serde",
2121
]
2222
base64 = ["bitcoin/base64"]
2323

2424
[dependencies]
2525
bitcoin = "0.31.0"
26-
secp256k1-zkp = { version = "0.10.0", features = [ "global-context", "hashes" ] }
26+
secp256k1-zkp = { version = "0.10.0", features = ["global-context", "hashes"] }
2727

2828
# Used for ContractHash::from_json_contract.
2929
serde_json = { version = "1.0", optional = true }
3030

31-
actual-serde = { package="serde", version = "1.0.103", features=["derive"], optional = true }
31+
actual-serde = { package = "serde", version = "1.0.103", features = [
32+
"derive",
33+
], optional = true }
34+
3235

3336
[dev-dependencies]
3437
rand = "0.8"
3538
rand_chacha = "0.3"
3639
serde_test = "1.0.19"
3740
serde_json = "1.0"
38-
serde_cbor = "0.8" # older than latest version to support 1.41.1
41+
serde_cbor = "0.8" # older than latest version to support 1.41.1
3942
bincode = "1.3"
4043

4144
[[example]]

src/address.rs

Lines changed: 89 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -21,11 +21,11 @@ use std::fmt;
2121
use std::fmt::Write as _;
2222
use std::str::FromStr;
2323

24-
use bitcoin::base58;
25-
use bitcoin::PublicKey;
26-
use crate::bech32::{Bech32, Bech32m, ByteIterExt, Fe32, Hrp, Fe32IterExt};
24+
use crate::bech32::{Bech32, Bech32m, ByteIterExt, Fe32, Fe32IterExt, Hrp};
2725
use crate::blech32::{Blech32, Blech32m};
2826
use crate::hashes::Hash;
27+
use bitcoin::base58;
28+
use bitcoin::PublicKey;
2929
use secp256k1_zkp;
3030
use secp256k1_zkp::Secp256k1;
3131
use secp256k1_zkp::Verification;
@@ -35,8 +35,8 @@ use serde;
3535
use crate::schnorr::{TapTweak, TweakedPublicKey, UntweakedPublicKey};
3636
use crate::taproot::TapNodeHash;
3737

38-
use crate::{PubkeyHash, ScriptHash, WPubkeyHash, WScriptHash};
3938
use crate::{opcodes, script};
39+
use crate::{PubkeyHash, ScriptHash, WPubkeyHash, WScriptHash};
4040

4141
/// Encoding error
4242
#[derive(Debug, PartialEq)]
@@ -62,6 +62,12 @@ pub enum AddressError {
6262

6363
/// An invalid blinding pubkey was encountered.
6464
InvalidBlindingPubKey(secp256k1_zkp::UpstreamError),
65+
66+
/// The length (in bytes) of the object was not correct.
67+
InvalidLength(usize),
68+
69+
/// Address version byte were not recognized.
70+
InvalidAddressVersion(u8),
6571
}
6672

6773
impl From<crate::bech32::primitives::decode::SegwitHrpstringError> for AddressError {
@@ -89,10 +95,18 @@ impl fmt::Display for AddressError {
8995
write!(f, "invalid witness script version: {}", wver)
9096
}
9197
AddressError::InvalidWitnessProgramLength(ref len) => {
92-
write!(f, "the witness program must be between 2 and 40 bytes in length, not {}", len)
98+
write!(
99+
f,
100+
"the witness program must be between 2 and 40 bytes in length, not {}",
101+
len
102+
)
93103
}
94104
AddressError::InvalidSegwitV0ProgramLength(ref len) => {
95-
write!(f, "a v0 witness program must be length 20 or 32, not {}", len)
105+
write!(
106+
f,
107+
"a v0 witness program must be length 20 or 32, not {}",
108+
len
109+
)
96110
}
97111
AddressError::InvalidBlindingPubKey(ref e) => {
98112
write!(f, "an invalid blinding pubkey was encountered: {}", e)
@@ -103,6 +117,12 @@ impl fmt::Display for AddressError {
103117
AddressError::InvalidSegwitV0Encoding => {
104118
write!(f, "v0 witness program must use b(l)ech32 not b(l)ech32m")
105119
}
120+
AddressError::InvalidLength(len) => {
121+
write!(f, "Address data has invalid length {}", len)
122+
}
123+
AddressError::InvalidAddressVersion(v) => {
124+
write!(f, "address version {} is invalid for this type", v)
125+
}
106126
}
107127
}
108128
}
@@ -212,7 +232,8 @@ impl Address {
212232
params: &'static AddressParams,
213233
) -> Address {
214234
let mut hash_engine = PubkeyHash::engine();
215-
pk.write_into(&mut hash_engine).expect("engines don't error");
235+
pk.write_into(&mut hash_engine)
236+
.expect("engines don't error");
216237

217238
Address {
218239
params,
@@ -244,7 +265,8 @@ impl Address {
244265
params: &'static AddressParams,
245266
) -> Address {
246267
let mut hash_engine = WPubkeyHash::engine();
247-
pk.write_into(&mut hash_engine).expect("engines don't error");
268+
pk.write_into(&mut hash_engine)
269+
.expect("engines don't error");
248270

249271
Address {
250272
params,
@@ -264,7 +286,8 @@ impl Address {
264286
params: &'static AddressParams,
265287
) -> Address {
266288
let mut hash_engine = ScriptHash::engine();
267-
pk.write_into(&mut hash_engine).expect("engines don't error");
289+
pk.write_into(&mut hash_engine)
290+
.expect("engines don't error");
268291

269292
let builder = script::Builder::new()
270293
.push_int(0)
@@ -401,7 +424,9 @@ impl Address {
401424
Payload::WitnessProgram {
402425
version: witver,
403426
program: ref witprog,
404-
} => script::Builder::new().push_int(witver.to_u8() as i64).push_slice(witprog),
427+
} => script::Builder::new()
428+
.push_int(witver.to_u8() as i64)
429+
.push_slice(witprog),
405430
}
406431
.into_script()
407432
}
@@ -450,10 +475,7 @@ impl Address {
450475

451476
Ok(Address {
452477
params,
453-
payload: Payload::WitnessProgram {
454-
version,
455-
program,
456-
},
478+
payload: Payload::WitnessProgram { version, program },
457479
blinding_pubkey,
458480
})
459481
}
@@ -468,13 +490,13 @@ impl Address {
468490
let (blinded, prefix) = match data[0] == params.blinded_prefix {
469491
true => {
470492
if data.len() != 55 {
471-
return Err(base58::Error::InvalidLength(data.len()).into());
493+
return Err(AddressError::InvalidLength(data.len()));
472494
}
473495
(true, data[1])
474496
}
475497
false => {
476498
if data.len() != 21 {
477-
return Err(base58::Error::InvalidLength(data.len()).into());
499+
return Err(AddressError::InvalidLength(data.len()));
478500
}
479501
(false, data[0])
480502
}
@@ -496,7 +518,7 @@ impl Address {
496518
} else if prefix == params.p2sh_prefix {
497519
Payload::ScriptHash(ScriptHash::from_slice(payload_data).unwrap())
498520
} else {
499-
return Err(base58::Error::InvalidAddressVersion(prefix).into());
521+
return Err(AddressError::InvalidAddressVersion(prefix));
500522
};
501523

502524
Ok(Address {
@@ -522,7 +544,7 @@ impl Address {
522544

523545
// Base58.
524546
if s.len() > 150 {
525-
return Err(base58::Error::InvalidLength(s.len() * 11 / 15).into());
547+
return Err(AddressError::InvalidLength(s.len() * 11 / 15));
526548
}
527549
let data = base58::decode_check(s)?;
528550
Address::from_base58(&data, params)
@@ -574,14 +596,23 @@ impl fmt::Display for Address {
574596
// FIXME: surely we can fix this logic to not be so repetitive.
575597
if self.is_blinded() {
576598
if let Some(ref blinder) = self.blinding_pubkey {
577-
let byte_iter = IntoIterator::into_iter(blinder.serialize()).chain(witprog.iter().copied());
599+
let byte_iter = IntoIterator::into_iter(blinder.serialize())
600+
.chain(witprog.iter().copied());
578601
let fe_iter = byte_iter.bytes_to_fes();
579602
if witver.to_u8() == 0 {
580-
for c in fe_iter.with_checksum::<Blech32>(&hrp).with_witness_version(witver).chars() {
603+
for c in fe_iter
604+
.with_checksum::<Blech32>(&hrp)
605+
.with_witness_version(witver)
606+
.chars()
607+
{
581608
fmt.write_char(c)?;
582609
}
583610
} else {
584-
for c in fe_iter.with_checksum::<Blech32m>(&hrp).with_witness_version(witver).chars() {
611+
for c in fe_iter
612+
.with_checksum::<Blech32m>(&hrp)
613+
.with_witness_version(witver)
614+
.chars()
615+
{
585616
fmt.write_char(c)?;
586617
}
587618
}
@@ -592,11 +623,19 @@ impl fmt::Display for Address {
592623
let byte_iter = witprog.iter().copied();
593624
let fe_iter = byte_iter.bytes_to_fes();
594625
if witver.to_u8() == 0 {
595-
for c in fe_iter.with_checksum::<Bech32>(&hrp).with_witness_version(witver).chars() {
626+
for c in fe_iter
627+
.with_checksum::<Bech32>(&hrp)
628+
.with_witness_version(witver)
629+
.chars()
630+
{
596631
fmt.write_char(c)?;
597632
}
598633
} else {
599-
for c in fe_iter.with_checksum::<Bech32m>(&hrp).with_witness_version(witver).chars() {
634+
for c in fe_iter
635+
.with_checksum::<Bech32m>(&hrp)
636+
.with_witness_version(witver)
637+
.chars()
638+
{
600639
fmt.write_char(c)?;
601640
}
602641
}
@@ -660,11 +699,11 @@ impl FromStr for Address {
660699

661700
// Base58.
662701
if s.len() > 150 {
663-
return Err(base58::Error::InvalidLength(s.len() * 11 / 15).into());
702+
return Err(AddressError::InvalidLength(s.len() * 11 / 15));
664703
}
665704
let data = base58::decode_check(s)?;
666705
if data.is_empty() {
667-
return Err(base58::Error::InvalidLength(data.len()).into());
706+
return Err(AddressError::InvalidLength(data.len()));
668707
}
669708

670709
let p = data[0];
@@ -734,9 +773,9 @@ impl serde::Serialize for Address {
734773
#[cfg(test)]
735774
mod test {
736775
use super::*;
776+
use crate::Script;
737777
use bitcoin::key;
738778
use secp256k1_zkp::{PublicKey, Secp256k1};
739-
use crate::Script;
740779
#[cfg(feature = "serde")]
741780
use serde_json;
742781

@@ -755,7 +794,9 @@ mod test {
755794
);
756795
#[cfg(feature = "serde")]
757796
assert_eq!(
758-
serde_json::from_value::<Address>(serde_json::to_value(addr).unwrap()).ok().as_ref(),
797+
serde_json::from_value::<Address>(serde_json::to_value(addr).unwrap())
798+
.ok()
799+
.as_ref(),
759800
Some(addr)
760801
);
761802
}
@@ -831,7 +872,12 @@ mod test {
831872

832873
for &(a, blinded, ref params) in &addresses {
833874
let result = a.parse();
834-
assert!(result.is_ok(), "vector: {}, err: \"{}\"", a, result.unwrap_err());
875+
assert!(
876+
result.is_ok(),
877+
"vector: {}, err: \"{}\"",
878+
a,
879+
result.unwrap_err()
880+
);
835881
let addr: Address = result.unwrap();
836882
assert_eq!(a, &addr.to_string(), "vector: {}", a);
837883
assert_eq!(blinded, addr.is_blinded());
@@ -858,7 +904,8 @@ mod test {
858904
"blech32 error: invalid checksum", // is valid blech32m, but should be blech32
859905
);
860906

861-
let address: Result<Address, _> = "ert130xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqqu2tys".parse();
907+
let address: Result<Address, _> =
908+
"ert130xlxvlhemja6c4dqv22uapctqupfhlxm9h8z3k2e72q4k9hcz7vqqu2tys".parse();
862909
assert_eq!(
863910
address.err().unwrap().to_string(),
864911
"bech32 error: invalid segwit witness version: 3", // FIXME https://github.com/rust-bitcoin/rust-bech32/issues/162 should be 17
@@ -879,14 +926,18 @@ mod test {
879926
);
880927
}
881928

882-
883929
#[test]
884930
fn test_fixed_addresses() {
885-
let pk = bitcoin::PublicKey::from_str("0212bf0ea45b733dfde8ecb5e896306c4165c666c99fc5d1ab887f71393a975cea")
886-
.unwrap();
931+
let pk = bitcoin::PublicKey::from_str(
932+
"0212bf0ea45b733dfde8ecb5e896306c4165c666c99fc5d1ab887f71393a975cea",
933+
)
934+
.unwrap();
887935
let script = Script::default();
888936
let secp = Secp256k1::verification_only();
889-
let internal_key = UntweakedPublicKey::from_str("93c7378d96518a75448821c4f7c8f4bae7ce60f804d03d1f0628dd5dd0f5de51").unwrap();
937+
let internal_key = UntweakedPublicKey::from_str(
938+
"93c7378d96518a75448821c4f7c8f4bae7ce60f804d03d1f0628dd5dd0f5de51",
939+
)
940+
.unwrap();
890941
let tap_node_hash = TapNodeHash::all_zeros();
891942

892943
let mut expected = IntoIterator::into_iter([
@@ -934,9 +985,12 @@ mod test {
934985
"tlq1pqgft7r4ytdenml0gaj67393sd3qkt3nxex0ut5dt3plhzwf6jaww5vx8c8vs0ywzejta7jjcc5f4asnacdtu0wlaas0upmsq90enaz2lekytucqf82vs",
935986
]);
936987

937-
for params in [&AddressParams::ELEMENTS, &AddressParams::LIQUID, &AddressParams::LIQUID_TESTNET] {
988+
for params in [
989+
&AddressParams::ELEMENTS,
990+
&AddressParams::LIQUID,
991+
&AddressParams::LIQUID_TESTNET,
992+
] {
938993
for blinder in [None, Some(pk.inner)] {
939-
940994
let addr = Address::p2pkh(&pk, blinder, params);
941995
assert_eq!(&addr.to_string(), expected.next().unwrap());
942996

@@ -959,6 +1013,5 @@ mod test {
9591013
assert_eq!(&addr.to_string(), expected.next().unwrap());
9601014
}
9611015
}
962-
9631016
}
9641017
}

src/blind.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,11 +26,11 @@ use secp256k1_zkp::{Generator, RangeProof, Secp256k1, Signing, SurjectionProof};
2626

2727
use crate::{AddressParams, Script, TxIn};
2828

29+
use crate::hashes;
2930
use crate::{
3031
confidential::{Asset, AssetBlindingFactor, Nonce, Value, ValueBlindingFactor},
3132
Address, AssetId, Transaction, TxOut, TxOutWitness,
3233
};
33-
use crate::hashes;
3434

3535
/// Transaction Output related errors
3636
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
@@ -229,7 +229,11 @@ impl RangeProofMessage {
229229
}
230230

231231
/// Information about Transaction Input Asset
232-
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize), serde(crate = "actual_serde"))]
232+
#[cfg_attr(
233+
feature = "serde",
234+
derive(Serialize, Deserialize),
235+
serde(crate = "actual_serde")
236+
)]
233237
#[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
234238
pub struct TxOutSecrets {
235239
/// Asset

0 commit comments

Comments
 (0)