Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
sander2 committed Aug 18, 2023
1 parent f92e8ca commit 049bf22
Show file tree
Hide file tree
Showing 6 changed files with 715 additions and 3 deletions.
4 changes: 1 addition & 3 deletions bitcoin/src/iter.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{BitcoinCoreApi, BitcoinRpcError, Error};
use crate::{BitcoinCoreApi, DynBitcoinCoreApi, BitcoinRpcError, Error};
use bitcoincore_rpc::{
bitcoin::{Block, BlockHash, Transaction},
jsonrpc::Error as JsonRpcError,
Expand All @@ -8,8 +8,6 @@ use futures::{prelude::*, stream::StreamExt};
use log::trace;
use std::{iter, sync::Arc};

type DynBitcoinCoreApi = Arc<dyn BitcoinCoreApi + Send + Sync>;

/// Stream over transactions, starting with this in the mempool and continuing with
/// transactions from previous in-chain block. The stream ends after the block at
/// `stop_height` has been returned.
Expand Down
4 changes: 4 additions & 0 deletions bitcoin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ mod addr;
mod electrs;
mod error;
mod iter;
pub mod relay;

use async_trait::async_trait;
use backoff::{backoff::Backoff, future::retry, ExponentialBackoff};
Expand Down Expand Up @@ -50,6 +51,7 @@ use bitcoincore_rpc::{
pub use electrs::{ElectrsClient, Error as ElectrsError};
pub use error::{BitcoinRpcError, ConversionError, Error};
pub use iter::{reverse_stream_transactions, stream_blocks, stream_in_chain_transactions};
pub use relay::*;
use log::{info, trace, warn};
use serde_json::error::Category as SerdeJsonCategory;
pub use sp_core::H256;
Expand Down Expand Up @@ -104,6 +106,8 @@ const RANDOMIZATION_FACTOR: f64 = 0.25;
const DERIVATION_KEY_LABEL: &str = "derivation-key";
const DEPOSIT_LABEL: &str = "deposit";

pub type DynBitcoinCoreApi = Arc<dyn BitcoinCoreApi + Send + Sync>;

fn get_exponential_backoff() -> ExponentialBackoff {
ExponentialBackoff {
current_interval: INITIAL_INTERVAL,
Expand Down
51 changes: 51 additions & 0 deletions bitcoin/src/relay/backing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
use super::Error;
use crate::DynBitcoinCoreApi;
use async_trait::async_trait;
use crate::{serialize, BitcoinCoreApi, Error as BitcoinError};

#[async_trait]
pub trait Backing {
/// Returns the height of the longest chain
async fn get_block_count(&self) -> Result<u32, Error>;

/// Returns the raw header of a block in storage
///
/// # Arguments
///
/// * `height` - The height of the block to fetch
async fn get_block_header(&self, height: u32) -> Result<Option<Vec<u8>>, Error>;

/// Returns the (little endian) hash of a block
///
/// # Arguments
///
/// * `height` - The height of the block to fetch
async fn get_block_hash(&self, height: u32) -> Result<Vec<u8>, Error>;
}

#[async_trait]
impl Backing for DynBitcoinCoreApi {
async fn get_block_count(&self) -> Result<u32, Error> {
let count = BitcoinCoreApi::get_block_count(&**self).await?;
return Ok(count as u32);
}

async fn get_block_header(&self, height: u32) -> Result<Option<Vec<u8>>, Error> {
let block_hash = match BitcoinCoreApi::get_block_hash(&**self, height).await {
Ok(h) => h,
Err(BitcoinError::InvalidBitcoinHeight) => {
return Ok(None);
}
Err(err) => return Err(err.into()),
};
let block_header = BitcoinCoreApi::get_block_header(&**self, &block_hash).await?;
Ok(Some(serialize(&block_header)))
}

async fn get_block_hash(&self, height: u32) -> Result<Vec<u8>, Error> {
let block_hash = BitcoinCoreApi::get_block_hash(&**self, height)
.await
.map(|hash| serialize(&hash))?;
Ok(block_hash)
}
}
37 changes: 37 additions & 0 deletions bitcoin/src/relay/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#![allow(clippy::enum_variant_names)]

use crate::Error as BitcoinError;
use thiserror::Error;

#[cfg(test)]
use std::mem::discriminant;

#[derive(Error, Debug)]
pub enum Error {
#[error("Client already initialized")]
AlreadyInitialized,
#[error("Client has not been initialized")]
NotInitialized,
#[error("Block already submitted")]
BlockExists,
#[error("Cannot read the best height")]
CannotFetchBestHeight,
#[error("Block hash not found for the given height")]
BlockHashNotFound,
#[error("Block header not found for the given height")]
BlockHeaderNotFound,
#[error("Failed to decode hash")]
DecodeHash,
#[error("Failed to serialize block header")]
SerializeHeader,

#[error("BitcoinError: {0}")]
BitcoinError(#[from] BitcoinError),
}

#[cfg(test)]
impl PartialEq for Error {
fn eq(&self, other: &Self) -> bool {
discriminant(self) == discriminant(other)
}
}
54 changes: 54 additions & 0 deletions bitcoin/src/relay/issuing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
use super::Error;
use async_trait::async_trait;
use crate::{sha256, Hash};
use std::sync::Arc;

#[async_trait]
pub trait Issuing {
/// Returns true if the light client is initialized
async fn is_initialized(&self) -> Result<bool, Error>;

/// Initialize the light client
///
/// # Arguments
///
/// * `header` - Raw block header
/// * `height` - Starting height
async fn initialize(&self, header: Vec<u8>, height: u32) -> Result<(), Error>;

/// Submit a block header and wait for inclusion
///
/// # Arguments
///
/// * `header` - Raw block header
async fn submit_block_header(
&self,
header: Vec<u8>,
) -> Result<(), Error>;

/// Submit a batch of block headers and wait for inclusion
///
/// # Arguments
///
/// * `headers` - Raw block headers (multiple of 80 bytes)
async fn submit_block_header_batch(&self, headers: Vec<Vec<u8>>) -> Result<(), Error>;

/// Returns the light client's chain tip
async fn get_best_height(&self) -> Result<u32, Error>;

/// Returns the block hash stored at a given height,
/// this is assumed to be in little-endian format
///
/// # Arguments
///
/// * `height` - Height of the block to fetch
async fn get_block_hash(&self, height: u32) -> Result<Vec<u8>, Error>;

/// Returns true if the block described by the hash
/// has been stored in the light client
///
/// # Arguments
///
/// * `hash_le` - Hash (little-endian) of the block
async fn is_block_stored(&self, hash_le: Vec<u8>) -> Result<bool, Error>;
}
Loading

0 comments on commit 049bf22

Please sign in to comment.