Skip to content

Commit c1991d7

Browse files
committed
Improving error information for address parser
1 parent eeeb722 commit c1991d7

File tree

1 file changed

+13
-7
lines changed

1 file changed

+13
-7
lines changed

src/util/address.rs

Lines changed: 13 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,12 @@ pub enum Error {
6161
/// The bech32 payload was empty
6262
EmptyBech32Payload,
6363
/// The wrong checksum algorithm was used. See BIP-0350.
64-
InvalidBech32Variant,
64+
InvalidBech32Variant {
65+
/// Bech32 variant that is required by the used Witness version
66+
expected: bech32::Variant,
67+
/// The actual Bech32 variant encoded in the address representation
68+
found: bech32::Variant
69+
},
6570
/// Script version must be 0 to 16 inclusive
6671
InvalidWitnessVersion(u8),
6772
/// Unable to parse witness version from string
@@ -81,12 +86,12 @@ pub enum Error {
8186
impl fmt::Display for Error {
8287
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8388
match *self {
84-
Error::Base58(ref e) => write!(f, "base58: {}", e),
85-
Error::Bech32(ref e) => write!(f, "bech32: {}", e),
89+
Error::Base58(_) => write!(f, "base58 address encoding error"),
90+
Error::Bech32(_) => write!(f, "bech32 address encoding error"),
8691
Error::EmptyBech32Payload => write!(f, "the bech32 payload was empty"),
87-
Error::InvalidBech32Variant => write!(f, "invalid bech32 checksum variant"),
92+
Error::InvalidBech32Variant { expected, found } => write!(f, "invalid bech32 checksum variant found {:?} when {:?} was expected", found, expected),
8893
Error::InvalidWitnessVersion(v) => write!(f, "invalid witness script version: {}", v),
89-
Error::UnparsableWitnessVersion(ref e) => write!(f, "Incorrect format of a witness version byte: {}", e),
94+
Error::UnparsableWitnessVersion(_) => write!(f, "incorrect format of a witness version byte"),
9095
Error::MalformedWitnessVersion => f.write_str("bitcoin script opcode does not match any known witness version, the script is malformed"),
9196
Error::InvalidWitnessProgramLength(l) => write!(f,
9297
"the witness program must be between 2 and 40 bytes in length: length={}", l,
@@ -716,8 +721,9 @@ impl FromStr for Address {
716721
}
717722

718723
// Encoding check
719-
if version.bech32_variant() != variant {
720-
return Err(Error::InvalidBech32Variant);
724+
let expected = version.bech32_variant();
725+
if expected != variant {
726+
return Err(Error::InvalidBech32Variant { expected, found: variant });
721727
}
722728

723729
return Ok(Address {

0 commit comments

Comments
 (0)