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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use std::error;
use std::fmt;
use crate::types::PublicKey;
use crate::deps_common::bitcoin::blockdata::opcodes::All as btc_opcodes;
use crate::deps_common::bitcoin::blockdata::script::{Builder, Instruction, Script};
use crate::util::hash::Hash160;
use sha2::Digest;
use sha2::Sha256;
use std::convert::TryFrom;
pub mod b58;
pub mod c32;
#[cfg(test)]
pub mod c32_old;
pub const C32_ADDRESS_VERSION_MAINNET_SINGLESIG: u8 = 22; pub const C32_ADDRESS_VERSION_MAINNET_MULTISIG: u8 = 20; pub const C32_ADDRESS_VERSION_TESTNET_SINGLESIG: u8 = 26; pub const C32_ADDRESS_VERSION_TESTNET_MULTISIG: u8 = 21; #[derive(Debug)]
pub enum Error {
InvalidCrockford32,
InvalidVersion(u8),
EmptyData,
BadByte(u8),
BadChecksum(u32, u32),
InvalidLength(usize),
TooShort(usize),
Other(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Error::InvalidCrockford32 => write!(f, "Invalid crockford 32 string"),
Error::InvalidVersion(ref v) => write!(f, "Invalid version {}", v),
Error::EmptyData => f.write_str("Empty data"),
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::TooShort(_) => write!(f, "base58ck data not even long enough for a checksum"),
Error::Other(ref s) => f.write_str(s),
}
}
}
impl error::Error for Error {
fn cause(&self) -> Option<&dyn error::Error> {
None
}
fn description(&self) -> &'static str {
match *self {
Error::InvalidCrockford32 => "Invalid crockford 32 string",
Error::InvalidVersion(_) => "Invalid version",
Error::EmptyData => "Empty data",
Error::BadByte(_) => "invalid b58 character",
Error::BadChecksum(_, _) => "invalid b58ck checksum",
Error::InvalidLength(_) => "invalid length for b58 type",
Error::TooShort(_) => "b58ck data less than 4 bytes",
Error::Other(_) => "unknown b58 error",
}
}
}
#[repr(u8)]
#[derive(Debug, Clone, PartialEq, PartialOrd, Ord, Hash, Eq, Copy, Serialize, Deserialize)]
pub enum AddressHashMode {
SerializeP2PKH = 0x00, SerializeP2SH = 0x01, SerializeP2WPKH = 0x02, SerializeP2WSH = 0x03, }
impl AddressHashMode {
pub fn to_version_mainnet(&self) -> u8 {
match *self {
AddressHashMode::SerializeP2PKH => C32_ADDRESS_VERSION_MAINNET_SINGLESIG,
_ => C32_ADDRESS_VERSION_MAINNET_MULTISIG,
}
}
pub fn to_version_testnet(&self) -> u8 {
match *self {
AddressHashMode::SerializeP2PKH => C32_ADDRESS_VERSION_TESTNET_SINGLESIG,
_ => C32_ADDRESS_VERSION_TESTNET_MULTISIG,
}
}
pub fn from_version(version: u8) -> AddressHashMode {
match version {
C32_ADDRESS_VERSION_TESTNET_SINGLESIG | C32_ADDRESS_VERSION_MAINNET_SINGLESIG => {
AddressHashMode::SerializeP2PKH
}
_ => AddressHashMode::SerializeP2SH,
}
}
}
impl TryFrom<u8> for AddressHashMode {
type Error = Error;
fn try_from(value: u8) -> Result<AddressHashMode, Self::Error> {
match value {
x if x == AddressHashMode::SerializeP2PKH as u8 => Ok(AddressHashMode::SerializeP2PKH),
x if x == AddressHashMode::SerializeP2SH as u8 => Ok(AddressHashMode::SerializeP2SH),
x if x == AddressHashMode::SerializeP2WPKH as u8 => {
Ok(AddressHashMode::SerializeP2WPKH)
}
x if x == AddressHashMode::SerializeP2WSH as u8 => Ok(AddressHashMode::SerializeP2WSH),
_ => Err(Error::InvalidVersion(value)),
}
}
}
fn to_bits_p2pkh<K: PublicKey>(pubk: &K) -> Hash160 {
let key_hash = Hash160::from_data(&pubk.to_bytes());
key_hash
}
fn to_bits_p2sh<K: PublicKey>(num_sigs: usize, pubkeys: &Vec<K>) -> Hash160 {
let mut bldr = Builder::new();
bldr = bldr.push_int(num_sigs as i64);
for pubk in pubkeys {
bldr = bldr.push_slice(&pubk.to_bytes());
}
bldr = bldr.push_int(pubkeys.len() as i64);
bldr = bldr.push_opcode(btc_opcodes::OP_CHECKMULTISIG);
let script = bldr.into_script();
let script_hash = Hash160::from_data(&script.as_bytes());
script_hash
}
fn to_bits_p2sh_p2wpkh<K: PublicKey>(pubk: &K) -> Hash160 {
let key_hash = Hash160::from_data(&pubk.to_bytes());
let bldr = Builder::new().push_int(0).push_slice(key_hash.as_bytes());
let script = bldr.into_script();
let script_hash = Hash160::from_data(&script.as_bytes());
script_hash
}
fn to_bits_p2sh_p2wsh<K: PublicKey>(num_sigs: usize, pubkeys: &Vec<K>) -> Hash160 {
let mut bldr = Builder::new();
bldr = bldr.push_int(num_sigs as i64);
for pubk in pubkeys {
bldr = bldr.push_slice(&pubk.to_bytes());
}
bldr = bldr.push_int(pubkeys.len() as i64);
bldr = bldr.push_opcode(btc_opcodes::OP_CHECKMULTISIG);
let mut digest = Sha256::new();
let mut d = [0u8; 32];
digest.update(bldr.into_script().as_bytes());
d.copy_from_slice(digest.finalize().as_slice());
let ws = Builder::new().push_int(0).push_slice(&d).into_script();
let ws_hash = Hash160::from_data(&ws.as_bytes());
ws_hash
}
pub fn public_keys_to_address_hash<K: PublicKey>(
hash_flag: &AddressHashMode,
num_sigs: usize,
pubkeys: &Vec<K>,
) -> Hash160 {
match *hash_flag {
AddressHashMode::SerializeP2PKH => to_bits_p2pkh(&pubkeys[0]),
AddressHashMode::SerializeP2SH => to_bits_p2sh(num_sigs, pubkeys),
AddressHashMode::SerializeP2WPKH => to_bits_p2sh_p2wpkh(&pubkeys[0]),
AddressHashMode::SerializeP2WSH => to_bits_p2sh_p2wsh(num_sigs, pubkeys),
}
}
#[cfg(test)]
mod test {
use super::*;
use crate::util::hash::*;
use crate::util::secp256k1::Secp256k1PublicKey as PubKey;
struct PubkeyFixture {
keys: Vec<PubKey>,
num_required: usize,
segwit: bool,
result: Vec<u8>,
}
#[test]
fn test_public_keys_to_address_hash() {
let pubkey_fixtures = vec![
PubkeyFixture {
keys: vec![
PubKey::from_hex("040fadbbcea0ff3b05f03195b41cd991d7a0af8bd38559943aec99cbdaf0b22cc806b9a4f07579934774cc0c155e781d45c989f94336765e88a66d91cfb9f060b0").unwrap(),
],
num_required: 1,
segwit: false,
result: hex_bytes("395f3643cea07ec4eec73b4d9a973dcce56b9bf1").unwrap().to_vec()
},
PubkeyFixture {
keys: vec![
PubKey::from_hex("040fadbbcea0ff3b05f03195b41cd991d7a0af8bd38559943aec99cbdaf0b22cc806b9a4f07579934774cc0c155e781d45c989f94336765e88a66d91cfb9f060b0").unwrap(),
PubKey::from_hex("04c77f262dda02580d65c9069a8a34c56bd77325bba4110b693b90216f5a3edc0bebc8ce28d61aa86b414aa91ecb29823b11aeed06098fcd97fee4bc73d54b1e96").unwrap(),
],
num_required: 2,
segwit: false,
result: hex_bytes("fd3a5e9f5ba311ce6122765f0af8da7488e25d3a").unwrap().to_vec(),
},
PubkeyFixture {
keys: vec![
PubKey::from_hex("020fadbbcea0ff3b05f03195b41cd991d7a0af8bd38559943aec99cbdaf0b22cc8").unwrap(),
],
num_required: 1,
segwit: true,
result: hex_bytes("0ac7ad046fe22c794dd923b3be14b2e668e50c42").unwrap().to_vec(),
},
PubkeyFixture {
keys: vec![
PubKey::from_hex("020fadbbcea0ff3b05f03195b41cd991d7a0af8bd38559943aec99cbdaf0b22cc8").unwrap(),
PubKey::from_hex("02c77f262dda02580d65c9069a8a34c56bd77325bba4110b693b90216f5a3edc0b").unwrap(),
],
num_required: 2,
segwit: true,
result: hex_bytes("3e02fa83ac2fae11fd6703b91e7c94ad393052e2").unwrap().to_vec(),
},
];
for pubkey_fixture in pubkey_fixtures {
let hash_mode = if !pubkey_fixture.segwit {
if pubkey_fixture.num_required == 1 {
AddressHashMode::SerializeP2PKH
} else {
AddressHashMode::SerializeP2SH
}
} else {
if pubkey_fixture.num_required == 1 {
AddressHashMode::SerializeP2WPKH
} else {
AddressHashMode::SerializeP2WSH
}
};
let result_hash = public_keys_to_address_hash(
&hash_mode,
pubkey_fixture.num_required,
&pubkey_fixture.keys,
);
let result = result_hash.as_bytes().to_vec();
assert_eq!(result, pubkey_fixture.result);
}
}
}