tendermint_light_client/
instance.rs

1//! Supervisor and Handle implementation.
2
3use tendermint::block::Height;
4
5use crate::{
6    errors::Error,
7    light_client::LightClient,
8    state::State,
9    verifier::types::{LightBlock, Status},
10};
11
12/// A light client `Instance` packages a `LightClient` together with its `State`.
13#[derive(Debug)]
14pub struct Instance {
15    /// The light client for this instance
16    pub light_client: LightClient,
17
18    /// The state of the light client for this instance
19    pub state: State,
20}
21
22impl Instance {
23    /// Constructs a new instance from the given light client and its state.
24    pub fn new(light_client: LightClient, state: State) -> Self {
25        Self {
26            light_client,
27            state,
28        }
29    }
30
31    /// Return the peer id of this instance.
32    pub fn peer_id(&self) -> &tendermint::node::Id {
33        &self.light_client.peer
34    }
35
36    /// Get the latest trusted block.
37    pub fn latest_trusted(&self) -> Option<LightBlock> {
38        self.state.light_store.highest(Status::Trusted)
39    }
40
41    /// Trust the given block.
42    pub fn trust_block(&mut self, lb: &LightBlock) {
43        self.state.light_store.update(lb, Status::Trusted);
44    }
45
46    /// Get or fetch the block at the given height
47    pub fn get_or_fetch_block(&mut self, height: Height) -> Result<LightBlock, Error> {
48        let (block, _) = self
49            .light_client
50            .get_or_fetch_block(height, &mut self.state)
51            .map_err(|e| {
52                // FIXME: Move this to the light client method
53                if e.to_string()
54                    .contains("must be less than or equal to the current blockchain height")
55                {
56                    // FIXME: Fetch latest height from error message
57                    Error::height_too_high(height, Height::default())
58                } else {
59                    e
60                }
61            })?;
62
63        Ok(block)
64    }
65}