Skip to content

Commit

Permalink
Improving error information for address parser
Browse files Browse the repository at this point in the history
  • Loading branch information
dr-orlovsky committed Sep 21, 2021
1 parent eeeb722 commit c1991d7
Showing 1 changed file with 13 additions and 7 deletions.
20 changes: 13 additions & 7 deletions src/util/address.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,12 @@ pub enum Error {
/// The bech32 payload was empty
EmptyBech32Payload,
/// The wrong checksum algorithm was used. See BIP-0350.
InvalidBech32Variant,
InvalidBech32Variant {
/// Bech32 variant that is required by the used Witness version
expected: bech32::Variant,
/// The actual Bech32 variant encoded in the address representation
found: bech32::Variant
},
/// Script version must be 0 to 16 inclusive
InvalidWitnessVersion(u8),
/// Unable to parse witness version from string
Expand All @@ -81,12 +86,12 @@ pub enum Error {
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::Base58(ref e) => write!(f, "base58: {}", e),
Error::Bech32(ref e) => write!(f, "bech32: {}", e),
Error::Base58(_) => write!(f, "base58 address encoding error"),
Error::Bech32(_) => write!(f, "bech32 address encoding error"),
Error::EmptyBech32Payload => write!(f, "the bech32 payload was empty"),
Error::InvalidBech32Variant => write!(f, "invalid bech32 checksum variant"),
Error::InvalidBech32Variant { expected, found } => write!(f, "invalid bech32 checksum variant found {:?} when {:?} was expected", found, expected),
Error::InvalidWitnessVersion(v) => write!(f, "invalid witness script version: {}", v),
Error::UnparsableWitnessVersion(ref e) => write!(f, "Incorrect format of a witness version byte: {}", e),
Error::UnparsableWitnessVersion(_) => write!(f, "incorrect format of a witness version byte"),
Error::MalformedWitnessVersion => f.write_str("bitcoin script opcode does not match any known witness version, the script is malformed"),
Error::InvalidWitnessProgramLength(l) => write!(f,
"the witness program must be between 2 and 40 bytes in length: length={}", l,
Expand Down Expand Up @@ -716,8 +721,9 @@ impl FromStr for Address {
}

// Encoding check
if version.bech32_variant() != variant {
return Err(Error::InvalidBech32Variant);
let expected = version.bech32_variant();
if expected != variant {
return Err(Error::InvalidBech32Variant { expected, found: variant });
}

return Ok(Address {
Expand Down

0 comments on commit c1991d7

Please sign in to comment.