Skip to content

Commit 435486f

Browse files
committed
Merge #45: Implement std::error::Error for Error
814cd71 Implement std::error::Error for Error (Tobin C. Harding) Pull request description: So that the usage of `bitcoinconsensus::Error` is more ergonomic for downstream users implement `std::error::Error`. ACKs for top commit: apoelstra: utACK 814cd71 Tree-SHA512: 931e384eda3a0841ba7dfc9241f33fda2f02e11d85146cc8b8d2e79838419ccb852f3d98e8d35a5afd91179b0b490c258dec88c10d5a27e780918cb099cb98e2
2 parents 9fc4dac + 814cd71 commit 435486f

File tree

2 files changed

+42
-0
lines changed

2 files changed

+42
-0
lines changed

Cargo.toml

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ name = "bitcoinconsensus"
1818
path = "src/lib.rs"
1919

2020
[features]
21+
default = ["std"]
22+
std = []
2123
external-secp = []
2224

2325
[dependencies]

src/lib.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,19 +20,59 @@
2020
extern crate libc;
2121

2222
use libc::{c_int,c_uchar, c_uint};
23+
use core::fmt;
2324

25+
/// Errors returned by `libbitcoinconsensus` (see github.com/bitcoin/bitcoin/doc/shared-libraries.md).
2426
#[allow(non_camel_case_types)]
2527
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
2628
#[repr(C)]
2729
pub enum Error {
30+
/// Default value, passed to `libbitcoinconsensus` as a return parameter.
2831
ERR_SCRIPT = 0,
32+
/// An invalid index for `txTo`.
2933
ERR_TX_INDEX,
34+
/// `txToLen` did not match with the size of `txTo`.
3035
ERR_TX_SIZE_MISMATCH,
36+
/// An error deserializing `txTo`.
3137
ERR_TX_DESERIALIZE,
38+
/// Input amount is required if WITNESS is used.
3239
ERR_AMOUNT_REQUIRED,
40+
/// Script verification `flags` are invalid (i.e. not part of the libconsensus interface).
3341
ERR_INVALID_FLAGS
3442
}
3543

44+
impl fmt::Display for Error {
45+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
46+
use self::Error::*;
47+
48+
let s = match *self {
49+
ERR_SCRIPT => "error value was not set (value still 0)",
50+
ERR_TX_INDEX => "an invalid index for txTo",
51+
ERR_TX_SIZE_MISMATCH => "txToLen did not match with the size of txTo",
52+
ERR_TX_DESERIALIZE => "an error deserializing txTo",
53+
ERR_AMOUNT_REQUIRED => "input amount is required if WITNESS is used",
54+
ERR_INVALID_FLAGS => "script verification flags are invalid",
55+
};
56+
f.write_str(s)
57+
}
58+
}
59+
60+
#[cfg(feature = "std")]
61+
impl std::error::Error for Error {
62+
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
63+
use self::Error::*;
64+
65+
match *self {
66+
ERR_SCRIPT
67+
| ERR_TX_INDEX
68+
| ERR_TX_SIZE_MISMATCH
69+
| ERR_TX_DESERIALIZE
70+
| ERR_AMOUNT_REQUIRED
71+
| ERR_INVALID_FLAGS => None,
72+
}
73+
}
74+
}
75+
3676
/// Do not enable any verification.
3777
pub const VERIFY_NONE : c_uint = 0;
3878
/// Evaluate P2SH (BIP16) subscripts.

0 commit comments

Comments
 (0)