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
use std::fmt::{self, Write};
use std::{io, ops};
use std::str::FromStr;
use secp256k1::{self, Secp256k1};
use consensus::encode;
use network::constants::Network;
use util::base58;
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PublicKey {
pub compressed: bool,
pub key: secp256k1::PublicKey,
}
impl PublicKey {
pub fn write_into<W: io::Write>(&self, mut writer: W) {
let write_res: io::Result<()> = if self.compressed {
writer.write_all(&self.key.serialize())
} else {
writer.write_all(&self.key.serialize_uncompressed())
};
debug_assert!(write_res.is_ok());
}
pub fn from_slice(data: &[u8]) -> Result<PublicKey, encode::Error> {
let compressed: bool = match data.len() {
33 => true,
65 => false,
len => { return Err(base58::Error::InvalidLength(len).into()); },
};
Ok(PublicKey {
compressed: compressed,
key: secp256k1::PublicKey::from_slice(data)?,
})
}
pub fn from_private_key<C: secp256k1::Signing>(secp: &Secp256k1<C>, sk: &PrivateKey) -> PublicKey {
sk.public_key(secp)
}
}
#[derive(Copy, Clone, PartialEq, Eq)]
pub struct PrivateKey {
pub compressed: bool,
pub network: Network,
pub key: secp256k1::SecretKey,
}
impl PrivateKey {
pub fn public_key<C: secp256k1::Signing>(&self, secp: &Secp256k1<C>) -> PublicKey {
PublicKey {
compressed: self.compressed,
key: secp256k1::PublicKey::from_secret_key(secp, &self.key)
}
}
pub fn fmt_wif(&self, fmt: &mut fmt::Write) -> fmt::Result {
let mut ret = [0; 34];
ret[0] = match self.network {
Network::Bitcoin => 128,
Network::Testnet | Network::Regtest => 239,
};
ret[1..33].copy_from_slice(&self.key[..]);
let privkey = if self.compressed {
ret[33] = 1;
base58::check_encode_slice(&ret[..])
} else {
base58::check_encode_slice(&ret[..33])
};
fmt.write_str(&privkey)
}
pub fn to_wif(&self) -> String {
let mut buf = String::new();
buf.write_fmt(format_args!("{}", self)).unwrap();
buf.shrink_to_fit();
buf
}
pub fn from_wif(wif: &str) -> Result<PrivateKey, encode::Error> {
let data = base58::from_check(wif)?;
let compressed = match data.len() {
33 => false,
34 => true,
_ => { return Err(encode::Error::Base58(base58::Error::InvalidLength(data.len()))); }
};
let network = match data[0] {
128 => Network::Bitcoin,
239 => Network::Testnet,
x => { return Err(encode::Error::Base58(base58::Error::InvalidVersion(vec![x]))); }
};
Ok(PrivateKey {
compressed: compressed,
network: network,
key: secp256k1::SecretKey::from_slice(&data[1..33])?,
})
}
}
impl fmt::Display for PrivateKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.fmt_wif(f)
}
}
impl fmt::Debug for PrivateKey {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "[private key data]")
}
}
impl FromStr for PrivateKey {
type Err = encode::Error;
fn from_str(s: &str) -> Result<PrivateKey, encode::Error> {
PrivateKey::from_wif(s)
}
}
impl ops::Index<ops::RangeFull> for PrivateKey {
type Output = [u8];
fn index(&self, _: ops::RangeFull) -> &[u8] {
&self.key[..]
}
}
#[cfg(test)]
mod tests {
use super::PrivateKey;
use secp256k1::Secp256k1;
use std::str::FromStr;
use network::constants::Network::Testnet;
use network::constants::Network::Bitcoin;
use util::address::Address;
#[test]
fn test_key_derivation() {
let sk = PrivateKey::from_wif("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
assert_eq!(sk.network, Testnet);
assert_eq!(sk.compressed, true);
assert_eq!(&sk.to_wif(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
let secp = Secp256k1::new();
let pk = Address::p2pkh(&sk.public_key(&secp), sk.network);
assert_eq!(&pk.to_string(), "mqwpxxvfv3QbM8PU8uBx2jaNt9btQqvQNx");
assert_eq!(&sk.to_string(), "cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy");
let sk_str =
PrivateKey::from_str("cVt4o7BGAig1UXywgGSmARhxMdzP5qvQsxKkSsc1XEkw3tDTQFpy").unwrap();
assert_eq!(&sk.to_wif(), &sk_str.to_wif());
let sk = PrivateKey::from_wif("5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3").unwrap();
assert_eq!(sk.network, Bitcoin);
assert_eq!(sk.compressed, false);
assert_eq!(&sk.to_wif(), "5JYkZjmN7PVMjJUfJWfRFwtuXTGB439XV6faajeHPAM9Z2PT2R3");
let secp = Secp256k1::new();
let pk = Address::p2pkh(&sk.public_key(&secp), sk.network);
assert_eq!(&pk.to_string(), "1GhQvF6dL8xa6wBxLnWmHcQsurx9RxiMc8");
}
}