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
//! Mock key manager implementation.

use std::{collections::HashMap, sync::Mutex};

pub use crate::keymanager::{
    KeyManagerError, KeyPair, KeyPairId, SignedPublicKey, StateKey, TrustedPolicySigners,
};
use crate::{core::consensus::beacon::EpochTime, keymanager::KeyManager};

#[derive(Default)]
pub struct MockKeyManagerClient {
    keys: Mutex<HashMap<KeyPairId, KeyPair>>,
    ephemeral_keys: Mutex<HashMap<KeyPairId, KeyPair>>,
}

impl Clone for MockKeyManagerClient {
    fn clone(&self) -> Self {
        let keys = self.keys.lock().unwrap();
        let ephemeral_keys = self.ephemeral_keys.lock().unwrap();
        Self {
            keys: Mutex::new(keys.clone()),
            ephemeral_keys: Mutex::new(ephemeral_keys.clone()),
        }
    }
}

impl MockKeyManagerClient {
    pub fn new() -> Self {
        Default::default()
    }
}

impl KeyManager for MockKeyManagerClient {
    fn clear_cache(&self) {
        // Nothing to do here, no cache.
    }

    fn get_or_create_keys(&self, key_pair_id: KeyPairId) -> Result<KeyPair, KeyManagerError> {
        let mut keys = self.keys.lock().unwrap();
        Ok(keys
            .entry(key_pair_id)
            .or_insert_with(|| {
                let mut kp = KeyPair::generate_mock();
                kp.state_key.0.fill(0x33);
                kp
            })
            .clone())
    }

    fn get_public_key(&self, _key_pair_id: KeyPairId) -> Result<SignedPublicKey, KeyManagerError> {
        Err(KeyManagerError::NotInitialized)
    }

    fn get_or_create_ephemeral_keys(
        &self,
        key_pair_id: KeyPairId,
        _epoch: EpochTime,
    ) -> Result<KeyPair, KeyManagerError> {
        let mut ephemeral_keys = self.ephemeral_keys.lock().unwrap();
        Ok(ephemeral_keys
            .entry(key_pair_id)
            .or_insert_with(|| {
                let mut kp = KeyPair::generate_mock();
                kp.state_key.0.fill(0x33);
                kp
            })
            .clone())
    }

    fn get_public_ephemeral_key(
        &self,
        _key_pair_id: KeyPairId,
        _epoch: EpochTime,
    ) -> Result<SignedPublicKey, KeyManagerError> {
        Err(KeyManagerError::NotInitialized)
    }

    fn box_clone(&self) -> Box<dyn KeyManager> {
        Box::new(self.clone())
    }
}