1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use bitflags::bitflags;
#[link(name="bitcoinconsensus")]
extern {
fn bitcoinconsensus_verify_script(
script_pub_key: *const u8,
script_pub_key_len: u16,
tx_to: *const u8,
tx_to_len: u16,
n_in: u16,
flags: u16,
error: *mut u16
) -> u16;
fn bitcoinconsensus_verify_script_with_amount(
script_pub_key: *const u8,
script_pub_key_len: u16,
amount: i64,
tx_to: *const u8,
tx_to_len: u16,
n_in: u16,
flags: u16,
error: *mut u16
) -> u16;
fn bitcoinconsensus_version() -> u16;
}
#[derive(Debug)]
pub enum ScriptVerificationError {
TxIndexError,
TxSizeMismatch,
TxDeserializeError,
AmountRequired,
InvalidFlags,
UnknownError(u16)
}
bitflags! {
pub struct ScriptVerificationFlags: u16 {
const VERIFY_P2SH = 1;
const VERIFY_DER_SIG = (1 << 2);
const VERIFY_NULL_DUMMY = (1 << 4);
const VERIFY_CHECK_LOCK_TIME = (1 << 9);
const VERIFY_CHECK_SEQUENCE = (1 << 10);
const VERIFY_WITNESS = (1 << 11);
}
}
fn map_error(err: u16) -> ScriptVerificationError {
match err {
1 => ScriptVerificationError::TxIndexError,
2 => ScriptVerificationError::TxSizeMismatch,
3 => ScriptVerificationError::TxDeserializeError,
4 => ScriptVerificationError::AmountRequired,
5 => ScriptVerificationError::InvalidFlags,
_ => ScriptVerificationError::UnknownError(err)
}
}
pub fn verify_script(pub_key: &[u8], tx: &[u8], input: u16, flags: ScriptVerificationFlags) -> Result<(), ScriptVerificationError> {
unsafe {
let mut err: u16 = 0;
let res = bitcoinconsensus_verify_script(
pub_key.as_ptr(),
pub_key.len() as u16,
tx.as_ptr(),
tx.len() as u16,
input,
flags.bits,
&mut err as *mut u16
);
if res == 1 { Ok(()) } else { Err(map_error(err)) }
}
}
pub fn verify_script_with_amount(pub_key: &[u8], amount: i64, tx: &[u8], input: u16, flags: ScriptVerificationFlags) -> Result<(), ScriptVerificationError> {
unsafe {
let mut err: u16 = 0;
let res = bitcoinconsensus_verify_script_with_amount(
pub_key.as_ptr(),
pub_key.len() as u16,
amount,
tx.as_ptr(),
tx.len() as u16,
input,
flags.bits,
&mut err as *mut u16
);
if res == 1 { Ok(()) } else { Err(map_error(err)) }
}
}
pub fn version() -> u16 {
unsafe {
bitcoinconsensus_version()
}
}