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
extern crate alloc;
pub use crate::keys::bip44::*;
use crate::{macs::hmac::HMAC_SHA512, Error, Result};
use alloc::vec::Vec;
pub const SECRET_KEY_LENGTH: usize = 32;
pub const PUBLIC_KEY_LENGTH: usize = 65;
pub const COMPRESSED_PUBLIC_KEY_LENGTH: usize = 33;
pub const SIGNATURE_LENGTH: usize = 64;
pub struct Seed(Vec<u8>);
#[derive(Default)]
pub struct SecretKey(libsecp256k1::SecretKey);
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct PublicKey(libsecp256k1::PublicKey);
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct Signature(libsecp256k1::Signature);
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct RecoveryId(libsecp256k1::RecoveryId);
pub struct ExtendedPrivateKey {
pub secret_key: SecretKey,
pub chain_code: Vec<u8>,
}
impl ExtendedPrivateKey {
pub fn child_key(&self, segment: &Segment) -> Result<Self> {
let mut input = if segment.is_normal() {
libsecp256k1::PublicKey::from_secret_key(&self.secret_key.0)
.serialize_compressed()
.to_vec()
} else {
let mut i = Vec::new();
i.push(0);
i.extend_from_slice(&self.secret_key.0.serialize());
i
};
input.extend(segment.bs().to_vec());
let mut result = [0; 64];
HMAC_SHA512(&input, &self.chain_code, &mut result);
let (secret_key, chain_code) = result.split_at(32);
let mut secret_key = SecretKey::from_slice(&secret_key)?;
secret_key.tweak_add(&self.secret_key)?;
Ok(Self {
secret_key,
chain_code: chain_code.to_vec(),
})
}
pub fn secret_key(&self) -> &SecretKey {
&self.secret_key
}
pub fn chain_code(&self) -> &[u8] {
&self.chain_code
}
}
impl Seed {
pub fn from_bytes(bs: &[u8]) -> Self {
Self(bs.to_vec())
}
pub fn derive(&self, chain: &Chain) -> Result<ExtendedPrivateKey> {
let mut result = [0; 64];
HMAC_SHA512(&self.0, b"Bitcoin seed", &mut result);
let (secret_key, chain_code) = result.split_at(32);
let mut sk = ExtendedPrivateKey {
secret_key: SecretKey::from_slice(secret_key)?,
chain_code: chain_code.to_vec(),
};
for segment in &chain.0 {
sk = sk.child_key(segment)?;
}
Ok(sk)
}
}
impl SecretKey {
#[cfg(feature = "random")]
#[cfg_attr(docsrs, doc(cfg(feature = "random")))]
pub fn generate() -> crate::Result<Self> {
let mut bs = [0u8; SECRET_KEY_LENGTH];
crate::utils::rand::fill(&mut bs)?;
Self::from_bytes(&bs)
}
#[cfg(feature = "rand")]
pub fn generate_with<R: rand::CryptoRng + rand::RngCore>(rng: &mut R) -> crate::Result<Self> {
let mut bs = [0_u8; SECRET_KEY_LENGTH];
rng.fill_bytes(&mut bs);
Self::from_bytes(&bs)
}
pub fn inner(&self) -> &libsecp256k1::SecretKey {
&self.0
}
pub fn from_bytes(bytes: &[u8; SECRET_KEY_LENGTH]) -> Result<Self> {
Ok(Self(libsecp256k1::SecretKey::parse(bytes).map_err(|_| {
Error::InvalidArgumentError {
alg: "bytes",
expected: "a valid secret key byte array",
}
})?))
}
pub fn from_slice(bytes: &[u8]) -> Result<Self> {
Ok(Self(libsecp256k1::SecretKey::parse_slice(bytes).map_err(|_| {
Error::InvalidArgumentError {
alg: "bytes",
expected: "a valid secret key byte array",
}
})?))
}
pub fn sign(&self, msg: &[u8; 32]) -> (Signature, RecoveryId) {
let (signature, recovery_id) = libsecp256k1::sign(&libsecp256k1::Message::parse(msg), &self.0);
(Signature(signature), RecoveryId(recovery_id))
}
pub fn tweak_add(&mut self, tweak: &SecretKey) -> Result<()> {
self.0
.tweak_add_assign(&tweak.0)
.map_err(|_| Error::InvalidArgumentError {
alg: "tweak_add",
expected: "a valid tweak secret key",
})
}
pub fn tweak_mul(&mut self, tweak: &SecretKey) -> Result<()> {
self.0
.tweak_mul_assign(&tweak.0)
.map_err(|_| Error::InvalidArgumentError {
alg: "tweak_mul",
expected: "a valid tweak secret key",
})
}
pub fn to_bytes(&self) -> [u8; SECRET_KEY_LENGTH] {
self.0.serialize()
}
pub fn public_key(&self) -> PublicKey {
PublicKey(libsecp256k1::PublicKey::from_secret_key(&self.0))
}
}
impl PublicKey {
pub fn from_bytes(bytes: &[u8; PUBLIC_KEY_LENGTH]) -> Result<Self> {
Ok(Self(libsecp256k1::PublicKey::parse(bytes).map_err(|_| {
Error::InvalidArgumentError {
alg: "bytes",
expected: "a valid public key byte array",
}
})?))
}
pub fn from_compressed_bytes(bytes: &[u8; COMPRESSED_PUBLIC_KEY_LENGTH]) -> Result<Self> {
Ok(Self(libsecp256k1::PublicKey::parse_compressed(bytes).map_err(
|_| Error::InvalidArgumentError {
alg: "bytes",
expected: "a valid public key byte array",
},
)?))
}
pub fn recover(message: &[u8; 32], signature: &Signature, recovery_id: &RecoveryId) -> Result<Self> {
libsecp256k1::recover(&libsecp256k1::Message::parse(message), &signature.0, &recovery_id.0)
.map(Self)
.map_err(|_| Error::InvalidArgumentError {
alg: "recover",
expected: "a valid signature",
})
}
pub fn verify(&self, message: &[u8; 32], signature: &Signature) -> bool {
libsecp256k1::verify(&libsecp256k1::Message::parse(message), &signature.0, &self.0)
}
pub fn to_bytes(&self) -> [u8; PUBLIC_KEY_LENGTH] {
self.0.serialize()
}
pub fn to_compressed_bytes(&self) -> [u8; COMPRESSED_PUBLIC_KEY_LENGTH] {
self.0.serialize_compressed()
}
}
impl Signature {
pub fn from_bytes(bytes: &[u8; SIGNATURE_LENGTH]) -> Result<Self> {
Ok(Self(libsecp256k1::Signature::parse_standard(bytes).map_err(|_| {
Error::InvalidArgumentError {
alg: "bytes",
expected: "a valid signature byte array",
}
})?))
}
pub fn to_bytes(&self) -> [u8; SIGNATURE_LENGTH] {
self.0.serialize()
}
}
impl RecoveryId {
pub fn from_u8(b: u8) -> Result<Self> {
Ok(Self(libsecp256k1::RecoveryId::parse(b).map_err(|_| {
Error::InvalidArgumentError {
alg: "b",
expected: "a valid recovery id",
}
})?))
}
pub fn as_u8(&self) -> u8 {
self.0.serialize()
}
}