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
use themelio_structs::NetID;

use crate::{TrustStore, TrustedHeight};
use std::{collections::HashMap, sync::Arc, sync::RwLock};

/// In-memory trust store.
#[derive(Clone)]
pub struct InMemoryTrustStore {
    inner: Arc<RwLock<HashMap<NetID, TrustedHeight>>>,
}

impl Default for InMemoryTrustStore {
    fn default() -> Self {
        Self::new()
    }
}

impl InMemoryTrustStore {
    /// Creates a new in-memory trust store.
    pub fn new() -> Self {
        Self {
            inner: Default::default(),
        }
    }
}

impl TrustStore for InMemoryTrustStore {
    fn set(&self, netid: NetID, trusted: TrustedHeight) {
        let mut inner = self.inner.write().unwrap();
        if let Some(old) = inner.get(&netid) {
            if old.height >= trusted.height {
                return;
            }
        }
        inner.insert(netid, trusted);
    }

    fn get(&self, netid: NetID) -> Option<TrustedHeight> {
        self.inner.read().unwrap().get(&netid).cloned()
    }
}