|
| 1 | +use core::{convert::Infallible, marker::PhantomData}; |
| 2 | + |
| 3 | +use alloc::collections::BTreeMap; |
| 4 | +use bitcoin::BlockHash; |
| 5 | + |
| 6 | +use crate::BlockId; |
| 7 | + |
| 8 | +/// Represents a service that tracks the best chain history. |
| 9 | +/// TODO: How do we ensure the chain oracle is consistent across a single call? |
| 10 | +/// * We need to somehow lock the data! What if the ChainOracle is remote? |
| 11 | +/// * Get tip method! And check the tip still exists at the end! And every internal call |
| 12 | +/// does not go beyond the initial tip. |
| 13 | +pub trait ChainOracle { |
| 14 | + /// Error type. |
| 15 | + type Error: core::fmt::Debug; |
| 16 | + |
| 17 | + /// Get the height and hash of the tip in the best chain. |
| 18 | + fn get_tip_in_best_chain(&self) -> Result<Option<BlockId>, Self::Error>; |
| 19 | + |
| 20 | + /// Returns the block hash (if any) of the given `height`. |
| 21 | + fn get_block_in_best_chain(&self, height: u32) -> Result<Option<BlockHash>, Self::Error>; |
| 22 | + |
| 23 | + /// Determines whether the block of [`BlockId`] exists in the best chain. |
| 24 | + fn is_block_in_best_chain(&self, block_id: BlockId) -> Result<bool, Self::Error> { |
| 25 | + Ok(matches!(self.get_block_in_best_chain(block_id.height)?, Some(h) if h == block_id.hash)) |
| 26 | + } |
| 27 | +} |
| 28 | + |
| 29 | +// [TODO] We need stuff for smart pointers. Maybe? How does rust lib do this? |
| 30 | +// Box<dyn ChainOracle>, Arc<dyn ChainOracle> ????? I will figure it out |
| 31 | +impl<C: ChainOracle> ChainOracle for &C { |
| 32 | + type Error = C::Error; |
| 33 | + |
| 34 | + fn get_tip_in_best_chain(&self) -> Result<Option<BlockId>, Self::Error> { |
| 35 | + <C as ChainOracle>::get_tip_in_best_chain(self) |
| 36 | + } |
| 37 | + |
| 38 | + fn get_block_in_best_chain(&self, height: u32) -> Result<Option<BlockHash>, Self::Error> { |
| 39 | + <C as ChainOracle>::get_block_in_best_chain(self, height) |
| 40 | + } |
| 41 | + |
| 42 | + fn is_block_in_best_chain(&self, block_id: BlockId) -> Result<bool, Self::Error> { |
| 43 | + <C as ChainOracle>::is_block_in_best_chain(self, block_id) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +/// This structure increases the performance of getting chain data. |
| 48 | +#[derive(Debug)] |
| 49 | +pub struct Cache<C> { |
| 50 | + assume_final_depth: u32, |
| 51 | + tip_height: u32, |
| 52 | + cache: BTreeMap<u32, BlockHash>, |
| 53 | + marker: PhantomData<C>, |
| 54 | +} |
| 55 | + |
| 56 | +impl<C> Cache<C> { |
| 57 | + /// Creates a new [`Cache`]. |
| 58 | + /// |
| 59 | + /// `assume_final_depth` represents the minimum number of blocks above the block in question |
| 60 | + /// when we can assume the block is final (reorgs cannot happen). I.e. a value of 0 means the |
| 61 | + /// tip is assumed to be final. The cache only caches blocks that are assumed to be final. |
| 62 | + pub fn new(assume_final_depth: u32) -> Self { |
| 63 | + Self { |
| 64 | + assume_final_depth, |
| 65 | + tip_height: 0, |
| 66 | + cache: Default::default(), |
| 67 | + marker: Default::default(), |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +impl<C: ChainOracle> Cache<C> { |
| 73 | + /// This is the topmost (highest) block height that we assume as final (no reorgs possible). |
| 74 | + /// |
| 75 | + /// Blocks higher than this height are not cached. |
| 76 | + pub fn assume_final_height(&self) -> u32 { |
| 77 | + self.tip_height.saturating_sub(self.assume_final_depth) |
| 78 | + } |
| 79 | + |
| 80 | + /// Update the `tip_height` with the [`ChainOracle`]'s tip. |
| 81 | + /// |
| 82 | + /// `tip_height` is used with `assume_final_depth` to determine whether we should cache a |
| 83 | + /// certain block height (`tip_height` - `assume_final_depth`). |
| 84 | + pub fn try_update_tip_height(&mut self, chain: C) -> Result<(), C::Error> { |
| 85 | + let tip = chain.get_tip_in_best_chain()?; |
| 86 | + if let Some(BlockId { height, .. }) = tip { |
| 87 | + self.tip_height = height; |
| 88 | + } |
| 89 | + Ok(()) |
| 90 | + } |
| 91 | + |
| 92 | + /// Get a block from the cache with the [`ChainOracle`] as fallback. |
| 93 | + /// |
| 94 | + /// If the block does not exist in cache, the logic fallbacks to fetching from the internal |
| 95 | + /// [`ChainOracle`]. If the block is at or below the "assume final height", we will also store |
| 96 | + /// the missing block in the cache. |
| 97 | + pub fn try_get_block(&mut self, chain: C, height: u32) -> Result<Option<BlockHash>, C::Error> { |
| 98 | + if let Some(&hash) = self.cache.get(&height) { |
| 99 | + return Ok(Some(hash)); |
| 100 | + } |
| 101 | + |
| 102 | + let hash = chain.get_block_in_best_chain(height)?; |
| 103 | + |
| 104 | + if hash.is_some() && height > self.tip_height { |
| 105 | + self.tip_height = height; |
| 106 | + } |
| 107 | + |
| 108 | + // only cache block if at least as deep as `assume_final_depth` |
| 109 | + let assume_final_height = self.tip_height.saturating_sub(self.assume_final_depth); |
| 110 | + if height <= assume_final_height { |
| 111 | + if let Some(hash) = hash { |
| 112 | + self.cache.insert(height, hash); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + Ok(hash) |
| 117 | + } |
| 118 | + |
| 119 | + /// Determines whether the block of `block_id` is in the chain using the cache. |
| 120 | + /// |
| 121 | + /// This uses [`try_get_block`] internally. |
| 122 | + /// |
| 123 | + /// [`try_get_block`]: Self::try_get_block |
| 124 | + pub fn try_is_block_in_chain(&mut self, chain: C, block_id: BlockId) -> Result<bool, C::Error> { |
| 125 | + match self.try_get_block(chain, block_id.height)? { |
| 126 | + Some(hash) if hash == block_id.hash => Ok(true), |
| 127 | + _ => Ok(false), |
| 128 | + } |
| 129 | + } |
| 130 | +} |
| 131 | + |
| 132 | +impl<C: ChainOracle<Error = Infallible>> Cache<C> { |
| 133 | + /// Updates the `tip_height` with the [`ChainOracle`]'s tip. |
| 134 | + /// |
| 135 | + /// This is the no-error version of [`try_update_tip_height`]. |
| 136 | + /// |
| 137 | + /// [`try_update_tip_height`]: Self::try_update_tip_height |
| 138 | + pub fn update_tip_height(&mut self, chain: C) { |
| 139 | + self.try_update_tip_height(chain) |
| 140 | + .expect("chain oracle error is infallible") |
| 141 | + } |
| 142 | + |
| 143 | + /// Get a block from the cache with the [`ChainOracle`] as fallback. |
| 144 | + /// |
| 145 | + /// This is the no-error version of [`try_get_block`]. |
| 146 | + /// |
| 147 | + /// [`try_get_block`]: Self::try_get_block |
| 148 | + pub fn get_block(&mut self, chain: C, height: u32) -> Option<BlockHash> { |
| 149 | + self.try_get_block(chain, height) |
| 150 | + .expect("chain oracle error is infallible") |
| 151 | + } |
| 152 | + |
| 153 | + /// Determines whether the block at `block_id` is in the chain using the cache. |
| 154 | + /// |
| 155 | + /// This is the no-error version of [`try_is_block_in_chain`]. |
| 156 | + /// |
| 157 | + /// [`try_is_block_in_chain`]: Self::try_is_block_in_chain |
| 158 | + pub fn is_block_in_best_chain(&mut self, chain: C, block_id: BlockId) -> bool { |
| 159 | + self.try_is_block_in_chain(chain, block_id) |
| 160 | + .expect("chain oracle error is infallible") |
| 161 | + } |
| 162 | +} |
0 commit comments