secret_store/
lib.rs

1// Copyright 2019 Conflux Foundation. All rights reserved.
2// Conflux is free software and distributed under GNU General Public License.
3// See http://www.gnu.org/licenses/
4
5use cfxkey as keylib;
6use keylib::KeyPair;
7use malloc_size_of_derive::MallocSizeOf as DeriveMallocSizeOf;
8use parking_lot::RwLock;
9use std::{collections::HashMap, sync::Arc};
10
11#[derive(DeriveMallocSizeOf)]
12pub struct StoreInner {
13    account_vec: Vec<KeyPair>,
14    secret_map: HashMap<String, usize>,
15}
16
17impl StoreInner {
18    pub fn new() -> Self {
19        StoreInner {
20            account_vec: Vec::new(),
21            secret_map: HashMap::new(),
22        }
23    }
24
25    pub fn insert(&mut self, kp: KeyPair) -> bool {
26        let secret_string = kp.secret().to_hex();
27        if self.secret_map.contains_key(&secret_string) {
28            return false;
29        }
30
31        let index = self.count();
32        self.secret_map.insert(secret_string, index);
33        self.account_vec.push(kp);
34        true
35    }
36
37    pub fn count(&self) -> usize { self.account_vec.len() }
38
39    pub fn get_keypair(&self, index: usize) -> KeyPair {
40        self.account_vec[index].clone()
41    }
42
43    pub fn remove_keypair(&mut self, index: usize) {
44        let secret_string = self.account_vec[index].secret().to_hex();
45        self.secret_map.remove(&secret_string);
46        self.account_vec.remove(index);
47    }
48}
49
50#[derive(DeriveMallocSizeOf)]
51pub struct SecretStore {
52    store: RwLock<StoreInner>,
53}
54
55pub type SharedSecretStore = Arc<SecretStore>;
56
57impl SecretStore {
58    pub fn new() -> Self {
59        SecretStore {
60            store: RwLock::new(StoreInner::new()),
61        }
62    }
63
64    pub fn insert(&self, kp: KeyPair) -> bool { self.store.write().insert(kp) }
65
66    pub fn count(&self) -> usize { self.store.read().count() }
67
68    pub fn get_keypair(&self, index: usize) -> KeyPair {
69        self.store.read().get_keypair(index)
70    }
71
72    pub fn remove_keypair(&self, index: usize) {
73        self.store.write().remove_keypair(index);
74    }
75}