emerald-core 0.10.1

Ethereum Classic secure account management core libary
Documentation
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
use super::Error;
use super::serialize::RPCTransaction;

use core::{Address, Transaction};
use hdwallet::{WManager, to_prefixed_path};
use jsonrpc_core::{Params, Value};
use keystore::{self, CryptoType, KdfDepthLevel, KeyFile};
use rustc_serialize::json as rustc_json;
use serde_json;
use std::cell::RefCell;
use std::path::PathBuf;
use std::str::FromStr;
use std::sync::Mutex;
use util;

fn to_chain_id(chain: &str, chain_id: Option<usize>, default_id: u8) -> u8 {
    if chain_id.is_some() {
        return chain_id.unwrap() as u8;
    }

    util::to_chain_id(chain).unwrap_or(default_id)
}

fn check_chain_params(chain: &str, chain_id: usize) -> Result<(), Error> {
    if let Some(id) = util::to_chain_id(chain) {
        if id as usize != chain_id {
            return Err(Error::InvalidDataFormat(
                "Inconsistent chain parameters".to_string(),
            ));
        }
    };

    Ok(())
}

#[derive(Deserialize, Debug)]
#[serde(untagged)]
pub enum Either<T, U> {
    Left(T),
    Right(U),
}

impl<T, U: Default> Either<T, U> {
    pub fn into_right(self) -> U {
        match self {
            Either::Left(_) => U::default(),
            Either::Right(u) => u,
        }
    }
}

impl<T, U: Default> Either<(T,), (T, U)> {
    fn into_full(self) -> (T, U) {
        match self {
            Either::Left((t,)) => (t, U::default()),
            Either::Right((t, u)) => (t, u),
        }
    }
}

pub fn current_version(_params: ()) -> Result<&'static str, Error> {
    Ok(::version())
}

pub fn heartbeat(_params: ()) -> Result<i64, Error> {
    use time::get_time;
    let res = get_time().sec;
    debug!("Emerald heartbeat: {}", res);

    Ok(res)
}

#[derive(Serialize, Debug)]
pub struct ListAccountAccount {
    name: String,
    address: String,
    description: String,
    hardware: bool,
}

#[derive(Deserialize, Default, Debug)]
pub struct ListAccountsAdditional {
    #[serde(default)]
    chain: String,
    #[serde(default)]
    chain_id: Option<usize>,
    #[serde(default)]
    show_hidden: bool,
    #[serde(default)]
    hd_path: Option<String>,
}

pub fn list_accounts(
    params: Either<(), (ListAccountsAdditional,)>,
    keystore_path: &PathBuf,
) -> Result<Vec<ListAccountAccount>, Error> {
    let (additional,) = params.into_right();
    let res = keystore::list_accounts(keystore_path, additional.show_hidden)?
        .iter()
        .map(|&(ref name, ref address, ref desc, is_hd)| {
            ListAccountAccount {
                name: name.clone(),
                address: address.clone(),
                description: desc.clone(),
                hardware: is_hd,
            }
        })
        .collect();
    debug!(
        "Accounts listed with `show_hidden`: {}\n\t{:?}",
        additional.show_hidden,
        res
    );

    Ok(res)
}

#[derive(Deserialize, Default, Debug)]
pub struct CommonAdditional {
    #[serde(default)]
    chain: String,
    #[serde(default)]
    chain_id: Option<usize>,
}

#[derive(Deserialize)]
pub struct HideAccountAccount {
    address: String,
}

pub fn hide_account(
    params: Either<(HideAccountAccount,), (HideAccountAccount, CommonAdditional)>,
    keystore_path: &PathBuf,
) -> Result<bool, Error> {
    let (account, _) = params.into_full();
    let addr = Address::from_str(&account.address)?;
    let res = keystore::hide(&addr, keystore_path)?;
    debug!("Account hided: {}", addr);

    Ok(res)
}

#[derive(Deserialize)]
pub struct UnhideAccountAccount {
    address: String,
}

pub fn unhide_account(
    params: Either<(UnhideAccountAccount,), (UnhideAccountAccount, CommonAdditional)>,
    keystore_path: &PathBuf,
) -> Result<bool, Error> {
    let (account, _) = params.into_full();
    let addr = Address::from_str(&account.address)?;
    let res = keystore::unhide(&addr, keystore_path)?;
    debug!("Account unhided: {}", addr);

    Ok(res)
}

#[derive(Deserialize)]
pub struct ShakeAccountAccount {
    address: String,
    old_passphrase: String,
    new_passphrase: String,
}

pub fn shake_account(
    params: Either<(ShakeAccountAccount,), (ShakeAccountAccount, CommonAdditional)>,
    keystore_path: &PathBuf,
) -> Result<bool, Error> {
    use keystore::os_random;

    let (account, _) = params.into_full();
    let addr = Address::from_str(&account.address)?;

    let (kf_path, kf) = KeyFile::search_by_address(&addr, keystore_path)?;

    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,
                &mut os_random(),
                kf.name,
                kf.description,
            )?;
            let filename = (*kf_path.as_path()).file_name().unwrap();
            new_kf.flush(keystore_path, filename.to_str())?;
            debug!("Account shaked: {}", kf.address);
        }
        _ => {
            return Err(Error::InvalidDataFormat(
                "Can't shake account from HD wallet".to_string(),
            ))
        }
    };

    Ok(true)
}

#[derive(Deserialize)]
pub struct UpdateAccountAccount {
    #[serde(default)]
    address: String,
    #[serde(default)]
    name: String,
    description: String,
}

pub fn update_account(
    params: Either<(UpdateAccountAccount,), (UpdateAccountAccount, CommonAdditional)>,
    keystore_path: &PathBuf,
) -> Result<bool, Error> {
    let (account, _) = params.into_full();
    let addr = Address::from_str(&account.address)?;

    let (kf_path, mut kf) = KeyFile::search_by_address(&addr, keystore_path)?;
    if !account.name.is_empty() {
        kf.name = Some(account.name);
    }
    if !account.description.is_empty() {
        kf.description = Some(account.description);
    }

    let filename = (*kf_path.as_path()).file_name().unwrap();
    kf.flush(keystore_path, filename.to_str())?;
    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)>,
    keystore_path: &PathBuf,
) -> Result<String, Error> {
    let (raw, _) = params.into_full();
    let raw = serde_json::to_string(&raw)?;

    let kf = KeyFile::decode(raw.to_lowercase())?;
    kf.flush(keystore_path, None)?;

    debug!("Account imported: {}", kf.address);

    Ok(format!("{}", kf.address))
}

#[derive(Deserialize)]
pub struct ExportAccountAccount {
    address: String,
}

pub fn export_account(
    params: Either<(ExportAccountAccount,), (ExportAccountAccount, CommonAdditional)>,
    keystore_path: &PathBuf,
) -> Result<Value, Error> {
    let (account, _) = params.into_full();
    let addr = Address::from_str(&account.address)?;

    let (_, kf) = KeyFile::search_by_address(&addr, keystore_path)?;
    let raw = rustc_json::encode(&kf)?;
    let value = serde_json::to_value(&raw)?;
    debug!("Account exported: {}", kf.address);

    Ok(value)
}

#[derive(Deserialize, Debug)]
pub struct NewAccountAccount {
    #[serde(default)]
    name: String,
    #[serde(default)]
    description: String,
    passphrase: String,
}

pub fn new_account(
    params: Either<(NewAccountAccount,), (NewAccountAccount, CommonAdditional)>,
    sec: &KdfDepthLevel,
    keystore_path: &PathBuf,
) -> Result<String, Error> {
    let (account, _) = params.into_full();
    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();
    kf.flush(keystore_path, None)?;
    debug!("New account generated: {}", kf.address);

    Ok(addr)
}

#[derive(Deserialize)]
pub struct SignTransactionTransaction {
    pub from: String,
    pub to: String,
    pub gas: String,
    #[serde(rename = "gasPrice")]
    pub gas_price: String,
    #[serde(default)]
    pub value: String,
    #[serde(default)]
    pub data: String,
    pub nonce: String,
    pub passphrase: String,
}

#[derive(Deserialize, Default, Debug)]
pub struct SignTransactionAdditional {
    #[serde(default)]
    chain: String,
    #[serde(default)]
    chain_id: Option<usize>,
    #[serde(default)]
    hd_path: Option<String>,
}

pub fn sign_transaction(
    params: Either<
        (SignTransactionTransaction,),
        (SignTransactionTransaction, SignTransactionAdditional),
    >,
    keystore_path: &PathBuf,
    default_chain_id: u8,
    wallet_manager: &Mutex<RefCell<WManager>>,
) -> Result<Params, Error> {
    let (transaction, additional) = params.into_full();
    let addr = Address::from_str(&transaction.from)?;

    if additional.chain_id.is_some() {
        check_chain_params(&additional.chain, additional.chain_id.unwrap())?;
    }

    match KeyFile::search_by_address(&addr, keystore_path) {
        Ok((_, kf)) => {
            let rpc_transaction = RPCTransaction {
                from: transaction.from,
                to: transaction.to,
                gas: transaction.gas,
                gas_price: transaction.gas_price,
                value: transaction.value,
                data: transaction.data,
                nonce: transaction.nonce,
            };
            let chain_id = to_chain_id(&additional.chain, additional.chain_id, default_chain_id);
            match rpc_transaction.try_into() {
                Ok(tr) => {
                    match kf.crypto {
                        CryptoType::Core(_) => {
                            if let Ok(pk) = kf.decrypt_key(&transaction.passphrase) {
                                let raw = tr.to_signed_raw(pk, chain_id).expect(
                                    "Expect to sign a \
                                     transaction",
                                );
                                let signed = Transaction::to_raw_params(raw);
                                debug!(
                                    "Signed by emerald transaction to: {:?}\n\t raw: {:?}",
                                    &tr.to,
                                    signed
                                );

                                Ok(signed)
                            } else {
                                Err(Error::InvalidDataFormat("Invalid passphrase".to_string()))
                            }
                        }

                        CryptoType::HdWallet(hw) => {
                            let quard = wallet_manager.lock().unwrap();
                            let mut wm = quard.borrow_mut();

                            let hd_path = match to_prefixed_path(&hw.hd_path) {
                                Ok(hd) => hd,
                                Err(e) => {
                                    return Err(Error::InvalidDataFormat(
                                        format!("Invalid hd path format: {}", 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(format!(
                                                "Address for stored HD path is incorrect"
                                            )));
                                        }
                                    }
                                    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())),
    }
}