-
Notifications
You must be signed in to change notification settings - Fork 3
/
serves.rs
executable file
·547 lines (478 loc) · 20.1 KB
/
serves.rs
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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
use super::common::{
extract_chain_params, CommonAdditional, Either, FunctionParams, ListAccountAccount,
ListAccountsAdditional, NewAccountAccount, NewMnemonicAccount, SelectedAccount,
ShakeAccountAccount, SignData, SignTxAdditional, SignTxTransaction, UpdateAccountAccount,
};
use super::Error;
use super::StorageController;
use contract::Contract;
use core::{Address, Transaction};
use hdwallet::bip32::to_prefixed_path;
use hdwallet::WManager;
use jsonrpc_core::{Params, Value};
use keystore::{os_random, CryptoType, Kdf, KdfDepthLevel, KeyFile, PBKDF2_KDF_NAME};
use mnemonic::{self, gen_entropy, HDPath, Language, Mnemonic, ENTROPY_BYTE_LENGTH};
use serde_json;
use std::cell::RefCell;
use std::str::FromStr;
use std::sync::{Arc, Mutex};
use util;
pub fn current_version() -> Result<&'static str, Error> {
Ok(::version())
}
pub fn heartbeat() -> Result<i64, Error> {
use time::get_time;
let res = get_time().sec;
debug!("Emerald heartbeat: {}", res);
Ok(res)
}
pub fn list_accounts(
params: Either<(), (ListAccountsAdditional,)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<Vec<ListAccountAccount>, Error> {
let storage_ctrl = storage.lock().unwrap();
let (additional,) = params.into_right();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let res = storage
.list_accounts(additional.show_hidden)?
.iter()
.map(|info| ListAccountAccount {
name: info.name.clone(),
address: info.address.clone(),
description: info.description.clone(),
hardware: info.is_hardware,
is_hidden: info.is_hidden,
})
.collect();
debug!(
"Accounts listed with `show_hidden`: {}\n\t{:?}",
additional.show_hidden, res
);
Ok(res)
}
pub fn hide_account(
params: Either<(SelectedAccount,), (SelectedAccount, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<bool, Error> {
let storage_ctrl = storage.lock().unwrap();
let (account, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let addr = Address::from_str(&account.address)?;
let res = storage.hide(&addr)?;
debug!("Account hided: {}", addr);
Ok(res)
}
pub fn unhide_account(
params: Either<(SelectedAccount,), (SelectedAccount, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<bool, Error> {
let storage_ctrl = storage.lock().unwrap();
let (account, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let addr = Address::from_str(&account.address)?;
let res = storage.unhide(&addr)?;
debug!("Account unhided: {}", addr);
Ok(res)
}
pub fn shake_account(
params: Either<(ShakeAccountAccount,), (ShakeAccountAccount, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<bool, Error> {
use keystore::os_random;
let storage_ctrl = storage.lock().unwrap();
let (account, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let addr = Address::from_str(&account.address)?;
let (_, kf) = storage.search_by_address(&addr)?;
match kf.crypto {
CryptoType::Core(ref core) => {
let pk = kf.decrypt_key(&account.old_passphrase)?;
let new_kf = KeyFile::new_custom(
pk,
&account.new_passphrase,
core.kdf_params.kdf,
&mut os_random(),
kf.name,
kf.description,
)?;
storage.put(&new_kf)?;
debug!("Account shaked: {}", kf.address);
}
_ => {
return Err(Error::InvalidDataFormat(
"Can't shake account from HD wallet".to_string(),
));
}
};
Ok(true)
}
pub fn update_account(
params: Either<(UpdateAccountAccount,), (UpdateAccountAccount, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<bool, Error> {
let storage_ctrl = storage.lock().unwrap();
let (account, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let addr = Address::from_str(&account.address)?;
let (_, mut kf) = storage.search_by_address(&addr)?;
if !account.name.is_empty() {
kf.name = Some(account.name);
}
if !account.description.is_empty() {
kf.description = Some(account.description);
}
storage.put(&kf)?;
debug!(
"Account {} updated with name: {}, description: {}",
kf.address,
kf.name.unwrap_or_else(|| "".to_string()),
kf.description.unwrap_or_else(|| "".to_string())
);
Ok(true)
}
pub fn import_account(
params: Either<(Value,), (Value, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<String, Error> {
let storage_ctrl = storage.lock().unwrap();
let (raw, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let raw = serde_json::to_string(&raw)?;
let kf = KeyFile::decode(&raw)?;
storage.put(&kf)?;
debug!("Account imported: {}", kf.address);
Ok(format!("{}", kf.address))
}
pub fn export_account(
params: Either<(SelectedAccount,), (SelectedAccount, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<Value, Error> {
let storage_ctrl = storage.lock().unwrap();
let (account, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let addr = Address::from_str(&account.address)?;
let (_, kf) = storage.search_by_address(&addr)?;
let value = serde_json::to_value(&kf)?;
debug!("Account exported: {}", kf.address);
Ok(value)
}
pub fn new_account(
params: Either<(NewAccountAccount,), (NewAccountAccount, CommonAdditional)>,
sec: &KdfDepthLevel,
storage: &Arc<Mutex<StorageController>>,
) -> Result<String, Error> {
let storage_ctrl = storage.lock().unwrap();
let (account, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
if account.passphrase.is_empty() {
return Err(Error::InvalidDataFormat("Empty passphase".to_string()));
}
let kf = KeyFile::new(
&account.passphrase,
sec,
Some(account.name),
Some(account.description),
)?;
let addr = kf.address.to_string();
storage.put(&kf)?;
debug!("New account generated: {}", kf.address);
Ok(addr)
}
pub fn sign_transaction(
params: Either<(SignTxTransaction,), (SignTxTransaction, SignTxAdditional)>,
storage: &Arc<Mutex<StorageController>>,
wallet_manager: &Arc<Mutex<RefCell<WManager>>>,
) -> Result<Params, Error> {
let storage_ctrl = storage.lock().unwrap();
let (transaction, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let addr = Address::from_str(&transaction.from)?;
let (_chain, chain_id) = extract_chain_params(&additional)?;
let passphrase = transaction.passphrase.clone();
match storage.search_by_address(&addr) {
Ok((_, kf)) => {
match transaction.try_into() {
Ok(tr) => {
match kf.crypto {
CryptoType::Core(_) => {
if passphrase.is_none() {
return Err(Error::InvalidDataFormat(
"Missing passphrase".to_string(),
));
}
let pass = passphrase.unwrap();
if let Ok(pk) = kf.decrypt_key(&pass) {
let raw = tr
.to_signed_raw(pk, chain_id)
.expect("Expect to sign a transaction");
let signed = Transaction::to_raw_params(&raw);
debug!("Signed transaction to: {:?}\n\t raw: {:?}", &tr.to, signed);
Ok(signed)
} else {
Err(Error::InvalidDataFormat("Invalid passphrase".to_string()))
}
}
CryptoType::HdWallet(hw) => {
let guard = wallet_manager.lock().unwrap();
let mut wm = guard.borrow_mut();
let hd_path = match to_prefixed_path(&hw.hd_path) {
Ok(hd) => hd,
Err(e) => return Err(Error::InvalidDataFormat(e.to_string())),
};
if let Err(e) = wm.update(Some(hd_path.clone())) {
return Err(Error::InvalidDataFormat(format!(
"Can't update HD wallets list : {}",
e.to_string()
)));
}
let mut err = String::new();
let rlp = tr.to_rlp(Some(chain_id));
for (addr, fd) in wm.devices() {
debug!("Selected device: {:?} {:?}", &addr, &fd);
// MUST verify address before making a signature, or a malicious
// person can replace HD path with another one and convince user to
// make signature from this address
match wm.get_address(&fd, Some(hd_path.clone())) {
Ok(actual_addr) => {
if actual_addr != addr {
return Err(Error::InvalidDataFormat(
"Address for stored HD path is incorrect"
.to_string(),
));
}
}
Err(e) => {
return Err(Error::InvalidDataFormat(format!(
"Can't get Address for HD Path: {}",
e.to_string()
)));
}
}
match wm.sign_transaction(&fd, &rlp, Some(hd_path.clone())) {
Ok(s) => {
let raw = tr.raw_from_sig(chain_id, &s);
let signed = Transaction::to_raw_params(&raw);
debug!(
"HD wallet addr:{:?} path: {:?} signed transaction \
to: {:?}\n\t raw: {:?}",
addr, fd, &tr.to, signed
);
return Ok(signed);
}
Err(e) => {
err = format!(
"{}\nWallet addr:{} on path:{}, can't sign \
transaction: {}",
err,
addr,
fd,
e.to_string()
);
continue;
}
}
}
Err(Error::InvalidDataFormat(err))
}
}
}
Err(err) => Err(Error::InvalidDataFormat(err.to_string())),
}
}
Err(_) => Err(Error::InvalidDataFormat("Can't find account".to_string())),
}
}
pub fn sign(
params: Either<(SignData,), (SignData, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
wallet_manager: &Arc<Mutex<RefCell<WManager>>>,
) -> Result<Params, Error> {
let storage_ctrl = storage.lock().unwrap();
let (input, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
let addr = Address::from_str(&input.address)?;
let hash = util::keccak256(
format!(
"\x19Ethereum Signed Message:\n{}{}",
input.data.len(),
input.data
)
.as_bytes(),
);
match storage.search_by_address(&addr) {
Ok((_, kf)) => {
match kf.crypto {
CryptoType::Core(_) => {
if input.passphrase.is_none() {
return Err(Error::InvalidDataFormat("Missing passphrase".to_string()));
}
let pass = input.passphrase.unwrap();
if let Ok(pk) = kf.decrypt_key(&pass) {
let signed = pk.sign_hash(hash)?;
Ok(Params::Array(vec![Value::String(signed.into())]))
} else {
Err(Error::InvalidDataFormat("Invalid passphrase".to_string()))
}
}
CryptoType::HdWallet(hw) => {
let guard = wallet_manager.lock().unwrap();
let mut wm = guard.borrow_mut();
let hd_path = match to_prefixed_path(&hw.hd_path) {
Ok(hd) => hd,
Err(e) => return Err(Error::InvalidDataFormat(e.to_string())),
};
if let Err(e) = wm.update(Some(hd_path.clone())) {
return Err(Error::InvalidDataFormat(format!(
"Can't update HD wallets list : {}",
e.to_string()
)));
}
let mut err = String::new();
for (addr, fd) in wm.devices() {
debug!("Selected device: {:?} {:?}", &addr, &fd);
// MUST verify address before making a signature, or a malicious
// person can replace HD path with another one and convince user to
// make signature from this address
match wm.get_address(&fd, Some(hd_path.clone())) {
Ok(actual_addr) => {
if actual_addr != addr {
return Err(Error::InvalidDataFormat(
"Address for stored HD path is incorrect".to_string(),
));
}
}
Err(e) => {
return Err(Error::InvalidDataFormat(format!(
"Can't get Address for HD Path: {}",
e.to_string()
)));
}
}
match wm.sign(&fd, &hash, &Some(hd_path.clone())) {
Ok(s) => {
debug!(
"HD wallet addr:{:?} path: {:?} signed data to: {:?}\n\t raw: \
{:?}",
addr, fd, input.data, s
);
return Ok(Params::Array(vec![Value::String(s.into())]));
}
Err(e) => {
err = format!(
"{}\nWallet addr:{} on path:{}, can't sign data: {}",
err,
addr,
fd,
e.to_string()
);
continue;
}
}
}
Err(Error::InvalidDataFormat(err))
}
}
}
Err(_) => Err(Error::InvalidDataFormat("Can't find account".to_string())),
}
}
pub fn encode_function_call(
params: Either<(Value,), (Value, FunctionParams)>,
) -> Result<String, Error> {
let (_, inputs) = params.into_full();
Contract::serialize_params(&inputs.types, inputs.values).map_err(From::from)
}
pub fn list_contracts(
params: Either<(), (CommonAdditional,)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<Vec<serde_json::Value>, Error> {
let storage_ctrl = storage.lock().unwrap();
let (additional,) = params.into_right();
let storage = storage_ctrl.get_contracts(&additional.chain)?;
Ok(storage.list())
}
pub fn import_contract(
params: Either<(Value,), (Value, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<(), Error> {
let storage_ctrl = storage.lock().unwrap();
let (raw, additional) = params.into_full();
let storage = storage_ctrl.get_contracts(&additional.chain)?;
storage.add(&raw)?;
Ok(())
}
pub fn list_addresses(
params: Either<(), (CommonAdditional,)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<Vec<serde_json::Value>, Error> {
let storage_ctrl = storage.lock().unwrap();
let (additional,) = params.into_right();
let storage = storage_ctrl.get_addressbook(&additional.chain)?;
Ok(storage.list())
}
pub fn import_address(
params: Either<(Value,), (Value, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<String, Error> {
let storage_ctrl = storage.lock().unwrap();
let (raw, additional) = params.into_full();
let storage = storage_ctrl.get_addressbook(&additional.chain)?;
storage.add(&raw)?;
Ok(raw.get("address").unwrap().to_string())
}
pub fn delete_address(
params: Either<(Value,), (Value, CommonAdditional)>,
storage: &Arc<Mutex<StorageController>>,
) -> Result<(), Error> {
let storage_ctrl = storage.lock().unwrap();
let (addr, additional) = params.into_full();
let storage = storage_ctrl.get_addressbook(&additional.chain)?;
storage.delete(&addr)?;
Ok(())
}
//pub fn export_contract(
// params: Either<(Value,), (Value, FunctionParams)>,
// storage: &Arc<Mutex<StorageController>>,
//) -> Result<Value, Error> {
// let storage_ctrl = storage.lock().unwrap();
// let (_, inputs) = params.into_full();
// let storage = storage_ctrl.get_contracts(&additional.chain)?;
//}
pub fn generate_mnemonic() -> Result<String, Error> {
let entropy = gen_entropy(ENTROPY_BYTE_LENGTH)?;
let mnemonic = Mnemonic::new(Language::English, &entropy)?;
Ok(mnemonic.sentence())
}
pub fn import_mnemonic(
params: Either<(NewMnemonicAccount,), (NewMnemonicAccount, CommonAdditional)>,
sec: &KdfDepthLevel,
storage: &Arc<Mutex<StorageController>>,
) -> Result<String, Error> {
let storage_ctrl = storage.lock().unwrap();
let (account, additional) = params.into_full();
let storage = storage_ctrl.get_keystore(&additional.chain)?;
if account.password.is_empty() {
return Err(Error::InvalidDataFormat("Empty password".to_string()));
}
let mnemonic = Mnemonic::try_from(Language::English, &account.mnemonic)?;
let hd_path = HDPath::try_from(&account.hd_path)?;
let pk = mnemonic::generate_key(&hd_path, &mnemonic.seed(""))?;
let kdf = if cfg!(target_os = "windows") {
Kdf::from_str(PBKDF2_KDF_NAME)?
} else {
Kdf::from(*sec)
};
let mut rng = os_random();
let kf = KeyFile::new_custom(
pk,
&account.password,
kdf,
&mut rng,
Some(account.name),
Some(account.description),
)?;
let addr = kf.address.to_string();
storage.put(&kf)?;
debug!("New mnemonic account generated: {}", kf.address);
Ok(addr)
}