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
use super::Wallet;
use eth_keystore::KeystoreError;
use ethers_core::{
k256::{
ecdsa::SigningKey, elliptic_curve::error::Error as K256Error, EncodedPoint as K256PublicKey,
},
rand::{CryptoRng, Rng},
types::Address,
utils::keccak256,
};
use std::{path::Path, str::FromStr};
use thiserror::Error;
#[derive(Error, Debug)]
pub enum WalletError {
#[error(transparent)]
EthKeystoreError(#[from] KeystoreError),
}
impl Clone for Wallet<SigningKey> {
fn clone(&self) -> Self {
Self {
signer: SigningKey::from_bytes(&*self.signer.to_bytes()).unwrap(),
address: self.address,
chain_id: self.chain_id,
}
}
}
impl Wallet<SigningKey> {
pub fn new_keystore<P, R, S>(dir: P, rng: &mut R, password: S) -> Result<Self, WalletError>
where
P: AsRef<Path>,
R: Rng + CryptoRng,
S: AsRef<[u8]>,
{
let (secret, _) = eth_keystore::new(dir, rng, password)?;
let signer = SigningKey::from_bytes(secret.as_slice())
.expect("private key should always be convertible to signing key");
let address = key_to_address(&signer);
Ok(Self {
signer,
address,
chain_id: None,
})
}
pub fn decrypt_keystore<P, S>(keypath: P, password: S) -> Result<Self, WalletError>
where
P: AsRef<Path>,
S: AsRef<[u8]>,
{
let secret = eth_keystore::decrypt_key(keypath, password)?;
let signer = SigningKey::from_bytes(secret.as_slice())
.expect("private key should always be convertible to signing key");
let address = key_to_address(&signer);
Ok(Self {
signer,
address,
chain_id: None,
})
}
pub fn new<R: Rng + CryptoRng>(rng: &mut R) -> Self {
let signer = SigningKey::random(rng);
let address = key_to_address(&signer);
Self {
signer,
address,
chain_id: None,
}
}
}
fn key_to_address(secret_key: &SigningKey) -> Address {
let uncompressed_pub_key = K256PublicKey::from(&secret_key.verify_key()).decompress();
let public_key = uncompressed_pub_key.unwrap().to_bytes();
debug_assert_eq!(public_key[0], 0x04);
let hash = keccak256(&public_key[1..]);
Address::from_slice(&hash[12..])
}
impl PartialEq for Wallet<SigningKey> {
fn eq(&self, other: &Self) -> bool {
self.signer.to_bytes().eq(&other.signer.to_bytes())
&& self.address == other.address
&& self.chain_id == other.chain_id
}
}
impl From<SigningKey> for Wallet<SigningKey> {
fn from(signer: SigningKey) -> Self {
let address = key_to_address(&signer);
Self {
signer,
address,
chain_id: None,
}
}
}
use ethers_core::k256::SecretKey as K256SecretKey;
impl From<K256SecretKey> for Wallet<SigningKey> {
fn from(key: K256SecretKey) -> Self {
let signer = SigningKey::from_bytes(&*key.to_bytes())
.expect("private key should always be convertible to signing key");
let address = key_to_address(&signer);
Self {
signer,
address,
chain_id: None,
}
}
}
impl FromStr for Wallet<SigningKey> {
type Err = K256Error;
fn from_str(src: &str) -> Result<Self, Self::Err> {
let src = hex::decode(src).expect("invalid hex when reading PrivateKey");
let sk = SigningKey::from_bytes(&src).unwrap();
Ok(sk.into())
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Signer;
use std::fs;
use tempfile::tempdir;
#[tokio::test]
async fn encrypted_json_keystore() {
let dir = tempdir().unwrap();
let mut rng = rand::thread_rng();
let key = Wallet::<SigningKey>::new_keystore(&dir, &mut rng, "randpsswd").unwrap();
let message = "Some data";
let signature = key.sign_message(message).await.unwrap();
let paths = fs::read_dir(dir).unwrap();
for path in paths {
let path = path.unwrap().path();
let key2 = Wallet::<SigningKey>::decrypt_keystore(&path.clone(), "randpsswd").unwrap();
let signature2 = key2.sign_message(message).await.unwrap();
assert_eq!(signature, signature2);
assert!(std::fs::remove_file(&path).is_ok());
}
}
#[tokio::test]
async fn signs_msg() {
let message = "Some data";
let hash = ethers_core::utils::hash_message(message);
let key = Wallet::<SigningKey>::new(&mut rand::thread_rng());
let address = key.address;
let signature = key.sign_message(message).await.unwrap();
let recovered = signature.recover(message).unwrap();
let recovered2 = signature.recover(hash).unwrap();
signature.verify(message, address).unwrap();
assert_eq!(recovered, address);
assert_eq!(recovered2, address);
}
#[tokio::test]
#[cfg(not(feature = "celo"))]
async fn signs_tx() {
use ethers_core::types::TransactionRequest;
let tx = TransactionRequest {
from: None,
to: Some(
"F0109fC8DF283027b6285cc889F5aA624EaC1F55"
.parse::<Address>()
.unwrap()
.into(),
),
value: Some(1_000_000_000.into()),
gas: Some(2_000_000.into()),
nonce: Some(0.into()),
gas_price: Some(21_000_000_000u128.into()),
data: None,
};
let chain_id = 1u64;
let wallet: Wallet<SigningKey> =
"4c0883a69102937d6231471b5dbb6204fe5129617082792ae468d01a3f362318"
.parse()
.unwrap();
let wallet = wallet.set_chain_id(chain_id);
let sig = wallet.sign_transaction(&tx).await.unwrap();
let sighash = tx.sighash(Some(chain_id));
assert!(sig.verify(sighash, wallet.address).is_ok());
}
#[test]
fn key_to_address() {
let wallet: Wallet<SigningKey> =
"0000000000000000000000000000000000000000000000000000000000000001"
.parse()
.unwrap();
assert_eq!(
wallet.address,
Address::from_str("7E5F4552091A69125d5DfCb7b8C2659029395Bdf").expect("Decoding failed")
);
let wallet: Wallet<SigningKey> =
"0000000000000000000000000000000000000000000000000000000000000002"
.parse()
.unwrap();
assert_eq!(
wallet.address,
Address::from_str("2B5AD5c4795c026514f8317c7a215E218DcCD6cF").expect("Decoding failed")
);
let wallet: Wallet<SigningKey> =
"0000000000000000000000000000000000000000000000000000000000000003"
.parse()
.unwrap();
assert_eq!(
wallet.address,
Address::from_str("6813Eb9362372EEF6200f3b1dbC3f819671cBA69").expect("Decoding failed")
);
}
}