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 Default for StoreInner {
18    fn default() -> Self { Self::new() }
19}
20
21impl StoreInner {
22    pub fn new() -> Self {
23        StoreInner {
24            account_vec: Vec::new(),
25            secret_map: HashMap::new(),
26        }
27    }
28
29    pub fn insert(&mut self, kp: KeyPair) -> bool {
30        let secret_string = kp.secret().to_hex();
31        if self.secret_map.contains_key(&secret_string) {
32            return false;
33        }
34
35        let index = self.count();
36        self.secret_map.insert(secret_string, index);
37        self.account_vec.push(kp);
38        true
39    }
40
41    pub fn count(&self) -> usize { self.account_vec.len() }
42
43    pub fn get_keypair(&self, index: usize) -> KeyPair {
44        self.account_vec[index].clone()
45    }
46
47    pub fn remove_keypair(&mut self, index: usize) {
48        let secret_string = self.account_vec[index].secret().to_hex();
49        self.secret_map.remove(&secret_string);
50        self.account_vec.remove(index);
51    }
52}
53
54#[derive(DeriveMallocSizeOf)]
55pub struct SecretStore {
56    store: RwLock<StoreInner>,
57}
58
59pub type SharedSecretStore = Arc<SecretStore>;
60
61impl Default for SecretStore {
62    fn default() -> Self { Self::new() }
63}
64
65impl SecretStore {
66    pub fn new() -> Self {
67        SecretStore {
68            store: RwLock::new(StoreInner::new()),
69        }
70    }
71
72    pub fn insert(&self, kp: KeyPair) -> bool { self.store.write().insert(kp) }
73
74    pub fn count(&self) -> usize { self.store.read().count() }
75
76    pub fn get_keypair(&self, index: usize) -> KeyPair {
77        self.store.read().get_keypair(index)
78    }
79
80    pub fn remove_keypair(&self, index: usize) {
81        self.store.write().remove_keypair(index);
82    }
83}