Skip to content

Commit 392465c

Browse files
author
ChallengeDev210
committed
Merge rust-bitcoin/rust-bitcoin#1003: Improve error Display implementations
57dd673 Do not print error when displaying for std builds (Tobin C. Harding) b80cfee Bind to error_kind instead of e (Tobin C. Harding) 241ec72 Bind to b instead of e (Tobin C. Harding) 01f481b Bind to s instead of e (Tobin C. Harding) 5c6d369 network: Remove unused error variants (Tobin C. Harding) e67e97b Put From impl below std::error::Error impl (Tobin C. Harding) 6ca98e5 Remove error TODO (Tobin C. Harding) Pull request description: As part of the ongoing error improvement work and as a direct result of [this comment](rust-bitcoin/rust-bitcoin#987 (comment)) improve the `Display` implementations of all our error types so as to not repeat the source error when printing. The first 5 patches are trivial clean ups around the errors. Patch 6 is the real work. EDIT: ~CC @Kixunil, have I got the right idea here bro?~ Patch 6 now includes a macro as suggested. ACKs for top commit: Kixunil: ACK 57dd673 apoelstra: ACK 57dd673 sanket1729: ACK 57dd673. Did not check if we covered all cases. We need to remember to use `write_err!` instead of `write!` in future. Tree-SHA512: 1ed26b0cc5f9a0f71684c431cbb9f94404c116c9136be696434c56a2f56fd93cb5406b0955edbd0dc6f8612e77345c93fa70a70650118968cc58e680333a41de
2 parents f8a7011 + 3f76dc6 commit 392465c

File tree

18 files changed

+69
-53
lines changed

18 files changed

+69
-53
lines changed

src/blockdata/script.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -211,7 +211,7 @@ impl std::error::Error for Error {
211211
NonMinimalPush
212212
| EarlyEndOfScript
213213
| NumericOverflow
214-
| BitcoinConsensus(_) // TODO: This should return `Some` but bitcoinconsensus::Error does not implement Error.
214+
| BitcoinConsensus(_)
215215
| UnknownSpentOutput(_)
216216
| SerializationError => None,
217217
}

src/blockdata/transaction.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -135,8 +135,8 @@ pub enum ParseOutPointError {
135135
impl fmt::Display for ParseOutPointError {
136136
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
137137
match *self {
138-
ParseOutPointError::Txid(ref e) => write!(f, "error parsing TXID: {}", e),
139-
ParseOutPointError::Vout(ref e) => write!(f, "error parsing vout: {}", e),
138+
ParseOutPointError::Txid(ref e) => write_err!(f, "error parsing TXID"; e),
139+
ParseOutPointError::Vout(ref e) => write_err!(f, "error parsing vout"; e),
140140
ParseOutPointError::Format => write!(f, "OutPoint not in <txid>:<vout> format"),
141141
ParseOutPointError::TooLong => write!(f, "vout should be at most 10 digits"),
142142
ParseOutPointError::VoutNotCanonical => write!(f, "no leading zeroes or + allowed in vout part"),

src/consensus/encode.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,8 +87,8 @@ pub enum Error {
8787
impl fmt::Display for Error {
8888
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8989
match *self {
90-
Error::Io(ref e) => write!(f, "I/O error: {}", e),
91-
Error::Psbt(ref e) => write!(f, "PSBT error: {}", e),
90+
Error::Io(ref e) => write_err!(f, "IO error"; e),
91+
Error::Psbt(ref e) => write_err!(f, "PSBT error"; e),
9292
Error::UnexpectedNetworkMagic { expected: ref e, actual: ref a } => write!(f,
9393
"unexpected network magic: expected {}, actual {}", e, a),
9494
Error::OversizedVectorAllocation { requested: ref r, max: ref m } => write!(f,
@@ -97,7 +97,7 @@ impl fmt::Display for Error {
9797
"invalid checksum: expected {}, actual {}", e.to_hex(), a.to_hex()),
9898
Error::NonMinimalVarInt => write!(f, "non-minimal varint"),
9999
Error::UnknownNetworkMagic(ref m) => write!(f, "unknown network magic: {}", m),
100-
Error::ParseFailed(ref e) => write!(f, "parse failed: {}", e),
100+
Error::ParseFailed(ref s) => write!(f, "parse failed: {}", s),
101101
Error::UnsupportedSegwitFlag(ref swflag) => write!(f,
102102
"unsupported segwit version: {}", swflag),
103103
}

src/internal_macros.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -574,3 +574,22 @@ macro_rules! user_enum {
574574
}
575575
);
576576
}
577+
578+
/// Formats error. If `std` feature is OFF appends error source (delimited by `: `). We do this
579+
/// because `e.source()` is only available in std builds, without this macro the error source is
580+
/// lost for no-std builds.
581+
macro_rules! write_err {
582+
($writer:expr, $string:literal $(, $args:expr),*; $source:expr) => {
583+
{
584+
#[cfg(feature = "std")]
585+
{
586+
let _ = &$source; // Prevents clippy warnings.
587+
write!($writer, $string $(, $args)*)
588+
}
589+
#[cfg(not(feature = "std"))]
590+
{
591+
write!($writer, concat!($string, ": {}") $(, $args)*, $source)
592+
}
593+
}
594+
}
595+
}

src/network/mod.rs

Lines changed: 9 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -54,38 +54,31 @@ pub mod stream_reader;
5454
pub enum Error {
5555
/// And I/O error
5656
Io(io::Error),
57-
/// Socket mutex was poisoned
58-
SocketMutexPoisoned,
59-
/// Not connected to peer
60-
SocketNotConnectedToPeer,
6157
}
6258

6359
impl fmt::Display for Error {
6460
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
6561
match *self {
66-
Error::Io(ref e) => fmt::Display::fmt(e, f),
67-
Error::SocketMutexPoisoned => f.write_str("socket mutex was poisoned"),
68-
Error::SocketNotConnectedToPeer => f.write_str("not connected to peer"),
62+
Error::Io(ref e) => write_err!(f, "IO error"; e),
6963
}
7064
}
7165
}
7266

73-
#[doc(hidden)]
74-
impl From<io::Error> for Error {
75-
fn from(err: io::Error) -> Self {
76-
Error::Io(err)
77-
}
78-
}
79-
8067
#[cfg(feature = "std")]
8168
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
8269
impl std::error::Error for Error {
8370
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
8471
use self::Error::*;
8572

8673
match self {
87-
Io(e) => Some(e),
88-
SocketMutexPoisoned | SocketNotConnectedToPeer => None,
74+
Io(e) => Some(e)
8975
}
9076
}
9177
}
78+
79+
#[doc(hidden)]
80+
impl From<io::Error> for Error {
81+
fn from(err: io::Error) -> Self {
82+
Error::Io(err)
83+
}
84+
}

src/util/address.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,12 +87,12 @@ pub enum Error {
8787
impl fmt::Display for Error {
8888
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
8989
match *self {
90-
Error::Base58(_) => write!(f, "base58 address encoding error"),
91-
Error::Bech32(_) => write!(f, "bech32 address encoding error"),
90+
Error::Base58(ref e) => write_err!(f, "base58 address encoding error"; e),
91+
Error::Bech32(ref e) => write_err!(f, "bech32 address encoding error"; e),
9292
Error::EmptyBech32Payload => write!(f, "the bech32 payload was empty"),
9393
Error::InvalidBech32Variant { expected, found } => write!(f, "invalid bech32 checksum variant found {:?} when {:?} was expected", found, expected),
9494
Error::InvalidWitnessVersion(v) => write!(f, "invalid witness script version: {}", v),
95-
Error::UnparsableWitnessVersion(_) => write!(f, "incorrect format of a witness version byte"),
95+
Error::UnparsableWitnessVersion(ref e) => write_err!(f, "incorrect format of a witness version byte"; e),
9696
Error::MalformedWitnessVersion => f.write_str("bitcoin script opcode does not match any known witness version, the script is malformed"),
9797
Error::InvalidWitnessProgramLength(l) => write!(f, "the witness program must be between 2 and 40 bytes in length: length={}", l),
9898
Error::InvalidSegwitV0ProgramLength(l) => write!(f, "a v0 witness program must be either of length 20 or 32 bytes: length={}", l),

src/util/base58.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ impl fmt::Display for Error {
6161
Error::InvalidExtendedKeyVersion(ref v) => write!(f, "extended key version {:#04x?} is invalid for this base58 type", v),
6262
Error::InvalidAddressVersion(ref v) => write!(f, "address version {} is invalid for this base58 type", v),
6363
Error::TooShort(_) => write!(f, "base58ck data not even long enough for a checksum"),
64-
Error::Secp256k1(ref e) => fmt::Display::fmt(&e, f),
65-
Error::Hex(ref e) => write!(f, "Hexadecimal decoding error: {}", e)
64+
Error::Secp256k1(ref e) => write_err!(f, "secp256k1 error while parsing secret key"; e),
65+
Error::Hex(ref e) => write_err!(f, "hexadecimal decoding error"; e)
6666
}
6767
}
6868
}

src/util/bip158.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ impl Display for Error {
7878
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
7979
match *self {
8080
Error::UtxoMissing(ref coin) => write!(f, "unresolved UTXO {}", coin),
81-
Error::Io(ref io) => write!(f, "{}", io)
81+
Error::Io(ref e) => write_err!(f, "IO error"; e),
8282
}
8383
}
8484
}

src/util/bip32.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -483,14 +483,14 @@ impl fmt::Display for Error {
483483
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
484484
match *self {
485485
Error::CannotDeriveFromHardenedKey => f.write_str("cannot derive hardened key from public key"),
486-
Error::Secp256k1(ref e) => fmt::Display::fmt(e, f),
486+
Error::Secp256k1(ref e) => write_err!(f, "secp256k1 error"; e),
487487
Error::InvalidChildNumber(ref n) => write!(f, "child number {} is invalid (not within [0, 2^31 - 1])", n),
488488
Error::InvalidChildNumberFormat => f.write_str("invalid child number format"),
489489
Error::InvalidDerivationPathFormat => f.write_str("invalid derivation path format"),
490490
Error::UnknownVersion(ref bytes) => write!(f, "unknown version magic bytes: {:?}", bytes),
491491
Error::WrongExtendedKeyLength(ref len) => write!(f, "encoded extended key data has wrong length {}", len),
492-
Error::Base58(ref err) => write!(f, "base58 encoding error: {}", err),
493-
Error::Hex(ref e) => write!(f, "Hexadecimal decoding error: {}", e)
492+
Error::Base58(ref e) => write_err!(f, "base58 encoding error"; e),
493+
Error::Hex(ref e) => write_err!(f, "Hexadecimal decoding error"; e),
494494
}
495495
}
496496
}

src/util/ecdsa.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -104,14 +104,14 @@ pub enum EcdsaSigError {
104104
impl fmt::Display for EcdsaSigError {
105105
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
106106
match *self {
107-
EcdsaSigError::HexEncoding(e) =>
108-
write!(f, "EcdsaSig hex encoding error: {}", e),
107+
EcdsaSigError::HexEncoding(ref e) =>
108+
write_err!(f, "EcdsaSig hex encoding error"; e),
109109
EcdsaSigError::NonStandardSighashType(hash_ty) =>
110110
write!(f, "Non standard signature hash type {}", hash_ty),
111111
EcdsaSigError::EmptySignature =>
112112
write!(f, "Empty ECDSA signature"),
113113
EcdsaSigError::Secp256k1(ref e) =>
114-
write!(f, "Invalid Ecdsa signature: {}", e),
114+
write_err!(f, "invalid ECDSA signature"; e),
115115
}
116116
}
117117
}

0 commit comments

Comments
 (0)