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
#![allow(missing_docs)]
pub mod errors;
use crate::errors::KeyringErrorAdapter;
use crate::errors::TerraRustWalletError;
use bitcoin::secp256k1::All;
use bitcoin::secp256k1::Secp256k1;
use serde::{Deserialize, Serialize};
use terra_rust_api::{PrivateKey, PublicKey};
#[derive(Deserialize, Serialize, Debug)]
pub struct WalletInternal {
pub keys: Vec<String>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct WalletListInternal {
pub wallets: Vec<String>,
}
pub struct Wallet<'a> {
pub name: &'a str,
}
impl<'a> Wallet<'a> {
pub fn new(wallet_name: &'a str) -> anyhow::Result<Wallet<'a>> {
log::debug!("Creating new wallet {}", wallet_name);
let wallet = Wallet::create(wallet_name);
let wallet_list_name = &wallet.full_list_name();
let keyring = keyring::Keyring::new(wallet_name, wallet_list_name);
let wallet_internal = WalletInternal { keys: vec![] };
keyring
.set_password(&serde_json::to_string(&wallet_internal)?)
.map_err(KeyringErrorAdapter::from)?;
let string_key_name: String = String::from(wallet_name);
match Wallet::get_wallets() {
Ok(old_list) => {
let mut new_list: Vec<String> = vec![];
for s in old_list {
if s.ne(wallet_name) {
new_list.push(s);
}
}
new_list.push(string_key_name);
let wallet_list = WalletListInternal { wallets: new_list };
Wallet::set_wallets(&wallet_list)?;
}
Err(_) => {
let wallet_list = WalletListInternal {
wallets: vec![string_key_name],
};
Wallet::set_wallets(&wallet_list)?;
}
}
Ok(wallet)
}
pub fn create(wallet: &'a str) -> Wallet<'a> {
Wallet { name: wallet }
}
pub fn get_private_key(
&self,
secp: &'a Secp256k1<All>,
key_name: &'a str,
seed: Option<&'a str>,
) -> anyhow::Result<PrivateKey> {
let full_key_name = self.full_key_name(key_name);
let keyring = keyring::Keyring::new(self.name, &full_key_name);
let phrase = &keyring.get_password().map_err(KeyringErrorAdapter::from)?;
match seed {
None => Ok(PrivateKey::from_words(secp, phrase)?),
Some(seed_str) => Ok(PrivateKey::from_words_seed(secp, phrase, seed_str)?),
}
}
pub fn get_public_key(
&self,
secp: &Secp256k1<All>,
key_name: &str,
seed: Option<&str>,
) -> anyhow::Result<PublicKey> {
let private_key: PrivateKey = self.get_private_key(secp, key_name, seed)?;
let pub_key = private_key.public_key(secp);
Ok(pub_key)
}
pub fn store_key(&self, key_name: &str, pk: &PrivateKey) -> anyhow::Result<bool> {
let full_key_name = self.full_key_name(key_name);
let keyring = keyring::Keyring::new(self.name, &full_key_name);
keyring
.set_password(pk.words().unwrap())
.map_err(KeyringErrorAdapter::from)?;
let old_list = self.get_keys()?;
let string_key_name: String = String::from(key_name);
let mut new_list: Vec<String> = vec![];
for s in old_list {
if s.ne(key_name) {
new_list.push(s);
}
}
new_list.push(string_key_name);
let wallet_internal = WalletInternal { keys: new_list };
self.set_keys(&wallet_internal)?;
Ok(true)
}
pub fn delete_key(&self, key_name: &str) -> anyhow::Result<bool> {
let full_key_name = self.full_key_name(key_name);
let keyring = keyring::Keyring::new(self.name, &full_key_name);
keyring
.delete_password()
.map_err(KeyringErrorAdapter::from)?;
let old_list = self.get_keys()?;
let mut new_list = vec![];
for s in old_list {
if s.ne(key_name) {
new_list.push(s);
}
}
let wallet_internal = WalletInternal { keys: new_list };
self.set_keys(&wallet_internal)?;
Ok(true)
}
pub fn list(&self) -> anyhow::Result<Vec<String>> {
self.get_keys()
}
pub fn delete(&self) -> anyhow::Result<()> {
let keys = self.get_keys()?;
for key in keys {
log::debug!("Deleting Key {} in wallet {}", key, &self.name);
self.delete_key(&key)?;
}
let wallet_list_name = self.full_list_name();
let keyring = keyring::Keyring::new(self.name, &wallet_list_name);
keyring
.delete_password()
.map_err(KeyringErrorAdapter::from)?;
let old_list = Wallet::get_wallets()?;
let mut new_list: Vec<String> = vec![];
for s in old_list {
if s.ne(self.name) {
new_list.push(s);
}
}
let wallet_list = WalletListInternal { wallets: new_list };
Wallet::set_wallets(&wallet_list)?;
Ok(())
}
fn full_key_name(&self, key_name: &'a str) -> String {
format!("TERRA-RUST-{}-{}", self.name, key_name)
}
fn full_list_name(&self) -> String {
format!("TERRA-RUST-{}_KEYS", self.name)
}
fn wallet_list_name() -> String {
"TERRA-RUST_WALLETS".to_string()
}
fn get_keys(&self) -> anyhow::Result<Vec<String>> {
let wallet_list_name = self.full_list_name();
let keyring = keyring::Keyring::new(self.name, &wallet_list_name);
let pass = keyring
.get_password()
.map_err(|source| TerraRustWalletError::KeyNotFound {
key: wallet_list_name,
source: KeyringErrorAdapter::from(source),
})?;
let wallet_internal: WalletInternal = serde_json::from_str(&pass)?;
Ok(wallet_internal.keys)
}
pub fn get_wallets() -> anyhow::Result<Vec<String>> {
let wallet_list_name = Wallet::wallet_list_name();
let keyring = keyring::Keyring::new(&wallet_list_name, "wallets");
let wallet_internal: WalletListInternal =
serde_json::from_str(&keyring.get_password().map_err(KeyringErrorAdapter::from)?)?;
Ok(wallet_internal.wallets)
}
fn set_keys(&self, int: &WalletInternal) -> anyhow::Result<()> {
let wallet_list_name = self.full_list_name();
let keyring = keyring::Keyring::new(self.name, &wallet_list_name);
keyring
.set_password(&serde_json::to_string(int)?)
.map_err(KeyringErrorAdapter::from)?;
Ok(())
}
fn set_wallets(int: &WalletListInternal) -> anyhow::Result<()> {
let wallet_list_name = Wallet::wallet_list_name();
let keyring = keyring::Keyring::new(&wallet_list_name, "wallets");
keyring
.set_password(&serde_json::to_string(int)?)
.map_err(KeyringErrorAdapter::from)?;
Ok(())
}
}
#[cfg(test)]
mod tst {
use super::*;
#[test]
pub fn test_wallet_create_delete() -> anyhow::Result<()> {
let wallet = Wallet::new("PFC-Test Wallet")?;
let key_list = wallet.get_keys()?;
assert!(key_list.is_empty());
wallet.delete()?;
Ok(())
}
#[test]
pub fn test_wallet_add_del() -> anyhow::Result<()> {
let str_1 = "notice oak worry limit wrap speak medal online prefer cluster roof addict wrist behave treat actual wasp year salad speed social layer crew genius";
let str_2 = "wonder caution square unveil april art add hover spend smile proud admit modify old copper throw crew happy nature luggage reopen exhibit ordinary napkin";
let s = Secp256k1::new();
let pk = PrivateKey::from_words(&s, str_1)?;
let pk2 = PrivateKey::from_words(&s, str_2)?;
let wallet = Wallet::new("PFC-Test Wallet")?;
wallet.store_key("PFC-Test-Key", &pk)?;
let key_list = wallet.get_keys()?;
assert_eq!(key_list.len(), 1);
wallet.store_key("PFC-Test-Key-2", &pk2)?;
let mut key_list = wallet.get_keys()?;
assert_eq!(key_list.len(), 2);
key_list.sort();
assert_eq!(key_list.join(","), "PFC-Test-Key,PFC-Test-Key-2");
let pk_get = wallet.get_private_key(&s, "PFC-Test-Key", None)?;
assert_eq!(pk_get.words().unwrap(), str_1);
wallet.delete_key("PFC-Test-Key")?;
let key_list = wallet.get_keys()?;
assert_eq!(key_list.len(), 1);
assert_eq!(key_list.join(","), "PFC-Test-Key-2");
wallet.delete()?;
Ok(())
}
}