Merge pull request #521 from RCasatta/errors_enum

Errors enum improvements
This commit is contained in:
Sebastian 2021-06-15 14:01:56 +02:00 committed by GitHub
commit b0ae2a6842
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 30 additions and 20 deletions

View File

@ -507,7 +507,7 @@ impl FromStr for Address {
Network::Testnet,
Payload::ScriptHash(ScriptHash::from_slice(&data[1..]).unwrap()),
),
x => return Err(Error::Base58(base58::Error::InvalidVersion(vec![x]))),
x => return Err(Error::Base58(base58::Error::InvalidAddressVersion(x))),
};
Ok(Address {

View File

@ -18,8 +18,9 @@ use std::error;
use core::{fmt, str, iter, slice};
use hashes::{sha256d, Hash};
use secp256k1;
use util::endian;
use util::{endian, key};
/// An error that might occur during base58 decoding
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
@ -32,12 +33,14 @@ pub enum Error {
/// Note that if the length is excessively long the provided length may be
/// an estimate (and the checksum step may be skipped).
InvalidLength(usize),
/// Version byte(s) were not recognized
InvalidVersion(Vec<u8>),
/// Extended Key version byte(s) were not recognized
InvalidExtendedKeyVersion([u8; 4]),
/// Address version byte were not recognized
InvalidAddressVersion(u8),
/// Checked data was less than 4 bytes
TooShort(usize),
/// Any other error
Other(String)
/// Secp256k1 error while parsing a secret key
Secp256k1(secp256k1::Error),
}
impl fmt::Display for Error {
@ -46,9 +49,10 @@ impl fmt::Display for Error {
Error::BadByte(b) => write!(f, "invalid base58 character 0x{:x}", b),
Error::BadChecksum(exp, actual) => write!(f, "base58ck checksum 0x{:x} does not match expected 0x{:x}", actual, exp),
Error::InvalidLength(ell) => write!(f, "length {} invalid for this base58 type", ell),
Error::InvalidVersion(ref v) => write!(f, "version {:?} invalid for this base58 type", v),
Error::InvalidAddressVersion(ref v) => write!(f, "address version {} is invalid for this base58 type", v),
Error::InvalidExtendedKeyVersion(ref v) => write!(f, "extended key version {:#04x?} is invalid for this base58 type", v),
Error::TooShort(_) => write!(f, "base58ck data not even long enough for a checksum"),
Error::Other(ref s) => f.write_str(s)
Error::Secp256k1(ref e) => fmt::Display::fmt(&e, f),
}
}
}
@ -238,6 +242,15 @@ pub fn check_encode_slice_to_fmt(fmt: &mut fmt::Formatter, data: &[u8]) -> fmt::
format_iter(fmt, iter)
}
#[doc(hidden)]
impl From<key::Error> for Error {
fn from(e: key::Error) -> Self {
match e {
key::Error::Secp256k1(e) => Error::Secp256k1(e),
key::Error::Base58(e) => e,
}
}
}
#[cfg(test)]
mod tests {

View File

@ -430,8 +430,6 @@ pub enum Error {
Ecdsa(secp256k1::Error), // TODO: This is not necessary ECDSA error and should be renamed
/// A child number was provided that was out of range
InvalidChildNumber(u32),
/// Error creating a master seed --- for application use
RngError(String), // TODO: This option seems unused and should be removed, opening a way to make this type copiable
/// Invalid childnumber format.
InvalidChildNumberFormat,
/// Invalid derivation path format.
@ -450,7 +448,6 @@ impl fmt::Display for Error {
Error::CannotDeriveFromHardenedKey => f.write_str("cannot derive hardened key from public key"),
Error::Ecdsa(ref e) => fmt::Display::fmt(e, f),
Error::InvalidChildNumber(ref n) => write!(f, "child number {} is invalid (not within [0, 2^31 - 1])", n),
Error::RngError(ref s) => write!(f, "rng error {}", s),
Error::InvalidChildNumberFormat => f.write_str("invalid child number format"),
Error::InvalidDerivationPathFormat => f.write_str("invalid derivation path format"),
Error::UnknownVersion(ref bytes) => write!(f, "unknown version magic bytes: {:?}", bytes),

View File

@ -247,7 +247,7 @@ impl PrivateKey {
let network = match data[0] {
128 => Network::Bitcoin,
239 => Network::Testnet,
x => { return Err(Error::Base58(base58::Error::InvalidVersion(vec![x]))); }
x => { return Err(Error::Base58(base58::Error::InvalidAddressVersion(x))); }
};
Ok(PrivateKey {

View File

@ -55,9 +55,9 @@ pub enum Error {
/// transaction.
UnexpectedUnsignedTx {
/// Expected
expected: Transaction,
expected: Box<Transaction>,
/// Actual
actual: Transaction,
actual: Box<Transaction>,
},
/// Unable to parse as a standard SigHash type.
NonStandardSigHashType(u32),
@ -68,9 +68,9 @@ pub enum Error {
/// Hash-type
hash_type: PsbtHash,
/// Pre-image
preimage: Vec<u8>,
preimage: Box<[u8]>,
/// Hash value
hash: Vec<u8>,
hash: Box<[u8]>,
},
/// Data inconsistency/conflicting data during merge procedure
MergeConflict(String),

View File

@ -169,8 +169,8 @@ impl Map for Global {
fn merge(&mut self, other: Self) -> Result<(), psbt::Error> {
if self.unsigned_tx != other.unsigned_tx {
return Err(psbt::Error::UnexpectedUnsignedTx {
expected: self.unsigned_tx.clone(),
actual: other.unsigned_tx,
expected: Box::new(self.unsigned_tx.clone()),
actual: Box::new(other.unsigned_tx),
});
}

View File

@ -311,8 +311,8 @@ where
let val: Vec<u8> = Deserialize::deserialize(&raw_value)?;
if <H as hashes::Hash>::hash(&val) != key_val {
return Err(psbt::Error::InvalidPreimageHashPair {
preimage: val,
hash: Vec::from(key_val.borrow()),
preimage: val.into_boxed_slice(),
hash: Box::from(key_val.borrow()),
hash_type: hash_type,
}
.into());