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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//! An in-memory LRU store for the light client.
use std::{
    num::NonZeroUsize,
    sync::{Mutex, MutexGuard},
};

use tendermint_light_client::{
    store::LightStore,
    types::{Height, LightBlock, Status},
};

/// In-memory LRU store.
pub struct LruStore {
    inner: Mutex<Inner>,
}

impl std::fmt::Debug for LruStore {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
        write!(f, "LruStore")
    }
}

#[derive(Clone, Debug, PartialEq)]
struct StoreEntry {
    light_block: LightBlock,
    status: Status,
}

impl StoreEntry {
    fn new(light_block: LightBlock, status: Status) -> Self {
        Self {
            light_block,
            status,
        }
    }
}

struct Inner {
    trust_root_height: Height,
    blocks: lru::LruCache<Height, StoreEntry>,
}

impl LruStore {
    /// Create a new, empty, in-memory LRU store of the given capacity and trust root height.
    pub fn new(capacity: usize, trust_root_height: Height) -> Self {
        Self {
            inner: Mutex::new(Inner {
                trust_root_height,
                blocks: lru::LruCache::new(NonZeroUsize::new(capacity).unwrap()),
            }),
        }
    }

    fn inner(&self) -> MutexGuard<'_, Inner> {
        self.inner.lock().unwrap()
    }

    fn inner_mut(&mut self) -> &mut Inner {
        self.inner.get_mut().unwrap()
    }
}

impl LightStore for LruStore {
    fn get(&self, height: Height, status: Status) -> Option<LightBlock> {
        self.inner()
            .blocks
            .get(&height)
            .filter(|e| e.status == status)
            .map(|e| e.light_block.clone())
    }

    fn insert(&mut self, light_block: LightBlock, status: Status) {
        let store = self.inner_mut();

        // Promote trust root to prevent it from being evicted.
        store.blocks.promote(&store.trust_root_height);

        store
            .blocks
            .put(light_block.height(), StoreEntry::new(light_block, status));
    }

    fn remove(&mut self, height: Height, status: Status) {
        let store = self.inner_mut();

        // Prevent removal of trust root.
        if height == store.trust_root_height {
            return;
        }

        if store
            .blocks
            .get(&height)
            .map(|e| e.status != status)
            .unwrap_or(true)
        {
            return;
        }
        store.blocks.pop(&height);
    }

    fn update(&mut self, light_block: &LightBlock, status: Status) {
        self.insert(light_block.clone(), status)
    }

    fn highest(&self, status: Status) -> Option<LightBlock> {
        self.inner()
            .blocks
            .iter()
            .filter(|(_, e)| e.status == status)
            .max_by_key(|(&height, _)| height)
            .map(|(_, e)| e.light_block.clone())
    }

    fn highest_before(&self, height: Height, status: Status) -> Option<LightBlock> {
        self.inner()
            .blocks
            .iter()
            .filter(|(_, e)| e.status == status)
            .filter(|(h, _)| h <= &&height)
            .max_by_key(|(&height, _)| height)
            .map(|(_, e)| e.light_block.clone())
    }

    fn lowest(&self, status: Status) -> Option<LightBlock> {
        self.inner()
            .blocks
            .iter()
            .filter(|(_, e)| e.status == status)
            .min_by_key(|(&height, _)| height)
            .map(|(_, e)| e.light_block.clone())
    }

    #[allow(clippy::needless_collect)]
    fn all(&self, status: Status) -> Box<dyn Iterator<Item = LightBlock>> {
        let light_blocks: Vec<_> = self
            .inner()
            .blocks
            .iter()
            .filter(|(_, e)| e.status == status)
            .map(|(_, e)| e.light_block.clone())
            .collect();

        Box::new(light_blocks.into_iter())
    }
}

#[cfg(test)]
mod test {
    use tendermint_light_client::{
        store::LightStore,
        types::{LightBlock, Status},
    };
    use tendermint_testgen::{Generator, LightChain};

    use super::LruStore;

    fn generate_blocks(count: u64) -> Vec<LightBlock> {
        LightChain::default_with_length(count)
            .light_blocks
            .into_iter()
            .map(|lb| lb.generate().unwrap())
            .map(|lb| LightBlock {
                signed_header: lb.signed_header,
                validators: lb.validators,
                next_validators: lb.next_validators,
                provider: lb.provider,
            })
            .collect()
    }

    #[test]
    fn test_trust_root_height_retained() {
        let blocks = generate_blocks(10);
        let mut store = LruStore::new(2, blocks[0].height()); // Only storing two blocks.
        store.insert(blocks[0].clone(), Status::Trusted);
        store.insert(blocks[1].clone(), Status::Trusted);
        store.insert(blocks[2].clone(), Status::Trusted);
        store.insert(blocks[3].clone(), Status::Trusted);

        let lowest = store
            .lowest(Status::Trusted)
            .expect("there should be a lowest block");
        assert_eq!(lowest, blocks[0]);
    }

    #[test]
    fn test_basic() {
        let blocks = generate_blocks(10);
        let mut store = LruStore::new(10, blocks[0].height());
        for block in &blocks {
            store.insert(block.clone(), Status::Trusted);

            // Block should be stored.
            let stored_block = store.get(block.height(), Status::Trusted);
            assert_eq!(stored_block.as_ref(), Some(block));

            // Highest and lowest blocks should be correct.
            let highest = store
                .highest(Status::Trusted)
                .expect("there should be a highest block");
            let lowest = store
                .lowest(Status::Trusted)
                .expect("there should be a lowest block");
            assert_eq!(&highest, block);
            assert_eq!(lowest, blocks[0]);

            // Highest before should work.
            let highest_before = store.highest_before(block.height(), Status::Trusted);
            assert_eq!(highest_before.as_ref(), Some(block));

            let highest_before = store.highest_before(block.height().increment(), Status::Trusted);
            assert_eq!(highest_before.as_ref(), Some(block));
        }

        // Test removal of trust root block.
        store.remove(blocks[0].height(), Status::Trusted);

        let block_zero = store.get(blocks[0].height(), Status::Trusted);
        assert_eq!(block_zero.as_ref(), Some(&blocks[0]));

        let lowest = store
            .lowest(Status::Trusted)
            .expect("there should be a lowest block");
        assert_eq!(lowest, blocks[0]);
    }
}