|
| 1 | +use super::Error; |
| 2 | +use crate::DynBitcoinCoreApi; |
| 3 | +use async_trait::async_trait; |
| 4 | +use crate::{serialize, BitcoinCoreApi, Error as BitcoinError}; |
| 5 | + |
| 6 | +#[async_trait] |
| 7 | +pub trait Backing { |
| 8 | + /// Returns the height of the longest chain |
| 9 | + async fn get_block_count(&self) -> Result<u32, Error>; |
| 10 | + |
| 11 | + /// Returns the raw header of a block in storage |
| 12 | + /// |
| 13 | + /// # Arguments |
| 14 | + /// |
| 15 | + /// * `height` - The height of the block to fetch |
| 16 | + async fn get_block_header(&self, height: u32) -> Result<Option<Vec<u8>>, Error>; |
| 17 | + |
| 18 | + /// Returns the (little endian) hash of a block |
| 19 | + /// |
| 20 | + /// # Arguments |
| 21 | + /// |
| 22 | + /// * `height` - The height of the block to fetch |
| 23 | + async fn get_block_hash(&self, height: u32) -> Result<Vec<u8>, Error>; |
| 24 | +} |
| 25 | + |
| 26 | +#[async_trait] |
| 27 | +impl Backing for DynBitcoinCoreApi { |
| 28 | + async fn get_block_count(&self) -> Result<u32, Error> { |
| 29 | + let count = BitcoinCoreApi::get_block_count(&**self).await?; |
| 30 | + return Ok(count as u32); |
| 31 | + } |
| 32 | + |
| 33 | + async fn get_block_header(&self, height: u32) -> Result<Option<Vec<u8>>, Error> { |
| 34 | + let block_hash = match BitcoinCoreApi::get_block_hash(&**self, height).await { |
| 35 | + Ok(h) => h, |
| 36 | + Err(BitcoinError::InvalidBitcoinHeight) => { |
| 37 | + return Ok(None); |
| 38 | + } |
| 39 | + Err(err) => return Err(err.into()), |
| 40 | + }; |
| 41 | + let block_header = BitcoinCoreApi::get_block_header(&**self, &block_hash).await?; |
| 42 | + Ok(Some(serialize(&block_header))) |
| 43 | + } |
| 44 | + |
| 45 | + async fn get_block_hash(&self, height: u32) -> Result<Vec<u8>, Error> { |
| 46 | + let block_hash = BitcoinCoreApi::get_block_hash(&**self, height) |
| 47 | + .await |
| 48 | + .map(|hash| serialize(&hash))?; |
| 49 | + Ok(block_hash) |
| 50 | + } |
| 51 | +} |
0 commit comments