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
use super::{Chain, Guard, Id};
use crate::{
error::{Error, ErrorKind::*},
keyring,
};
use lazy_static::lazy_static;
use std::{collections::BTreeMap, sync::RwLock};
lazy_static! {
pub static ref REGISTRY: GlobalRegistry = GlobalRegistry::default();
}
#[derive(Default)]
pub struct Registry(BTreeMap<Id, Chain>);
impl Registry {
pub fn add_to_keyring(
&mut self,
chain_id: &Id,
signer: keyring::ed25519::Signer,
) -> Result<(), Error> {
let chain = self.0.get_mut(chain_id).ok_or_else(|| {
err!(
InvalidKey,
"can't add signer {} to unregistered chain: {}",
signer.provider(),
chain_id
)
})?;
chain.keyring.add(signer)
}
pub fn register_chain(&mut self, chain: Chain) -> Result<(), Error> {
let chain_id = chain.id;
if self.0.insert(chain_id, chain).is_none() {
Ok(())
} else {
fail!(ConfigError, "chain ID already registered: {}", chain_id);
}
}
pub fn get_chain(&self, chain_id: &Id) -> Option<&Chain> {
self.0.get(chain_id)
}
}
#[derive(Default)]
pub struct GlobalRegistry(pub(super) RwLock<Registry>);
impl GlobalRegistry {
pub fn get(&self) -> Guard {
self.0.read().unwrap().into()
}
pub fn register(&self, chain: Chain) -> Result<(), Error> {
let mut registry = self.0.write().unwrap();
registry.register_chain(chain)
}
}