use codec::{Decode, Encode};
use parking_lot::RwLock;
use sp_runtime::{
generic::BlockId,
traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero},
Justifications,
};
use std::collections::{btree_set::BTreeSet, HashMap, VecDeque};
use tracing::{debug, warn};
use crate::{
error::{Error, Result},
header_metadata::HeaderMetadata,
tree_route, CachedHeaderMetadata,
};
pub trait HeaderBackend<Block: BlockT>: Send + Sync {
fn header(&self, hash: Block::Hash) -> Result<Option<Block::Header>>;
fn info(&self) -> Info<Block>;
fn status(&self, hash: Block::Hash) -> Result<BlockStatus>;
fn number(
&self,
hash: Block::Hash,
) -> Result<Option<<<Block as BlockT>::Header as HeaderT>::Number>>;
fn hash(&self, number: NumberFor<Block>) -> Result<Option<Block::Hash>>;
fn block_hash_from_id(&self, id: &BlockId<Block>) -> Result<Option<Block::Hash>> {
match *id {
BlockId::Hash(h) => Ok(Some(h)),
BlockId::Number(n) => self.hash(n),
}
}
fn block_number_from_id(&self, id: &BlockId<Block>) -> Result<Option<NumberFor<Block>>> {
match *id {
BlockId::Hash(h) => self.number(h),
BlockId::Number(n) => Ok(Some(n)),
}
}
fn expect_header(&self, hash: Block::Hash) -> Result<Block::Header> {
self.header(hash)?
.ok_or_else(|| Error::UnknownBlock(format!("Expect header: {}", hash)))
}
fn expect_block_number_from_id(&self, id: &BlockId<Block>) -> Result<NumberFor<Block>> {
self.block_number_from_id(id).and_then(|n| {
n.ok_or_else(|| Error::UnknownBlock(format!("Expect block number from id: {}", id)))
})
}
fn expect_block_hash_from_id(&self, id: &BlockId<Block>) -> Result<Block::Hash> {
self.block_hash_from_id(id).and_then(|h| {
h.ok_or_else(|| Error::UnknownBlock(format!("Expect block hash from id: {}", id)))
})
}
}
pub trait ForkBackend<Block: BlockT>:
HeaderMetadata<Block> + HeaderBackend<Block> + Send + Sync
{
fn expand_forks(
&self,
fork_heads: &[Block::Hash],
) -> std::result::Result<BTreeSet<Block::Hash>, Error> {
let mut expanded_forks = BTreeSet::new();
for fork_head in fork_heads {
match tree_route(self, *fork_head, self.info().finalized_hash) {
Ok(tree_route) => {
for block in tree_route.retracted() {
expanded_forks.insert(block.hash);
}
continue;
},
Err(_) => {
},
}
}
Ok(expanded_forks)
}
}
impl<Block, T> ForkBackend<Block> for T
where
Block: BlockT,
T: HeaderMetadata<Block> + HeaderBackend<Block> + Send + Sync,
{
}
struct MinimalBlockMetadata<Block: BlockT> {
number: NumberFor<Block>,
hash: Block::Hash,
parent: Block::Hash,
}
impl<Block> Clone for MinimalBlockMetadata<Block>
where
Block: BlockT,
{
fn clone(&self) -> Self {
Self { number: self.number, hash: self.hash, parent: self.parent }
}
}
impl<Block> Copy for MinimalBlockMetadata<Block> where Block: BlockT {}
impl<Block> From<&CachedHeaderMetadata<Block>> for MinimalBlockMetadata<Block>
where
Block: BlockT,
{
fn from(value: &CachedHeaderMetadata<Block>) -> Self {
Self { number: value.number, hash: value.hash, parent: value.parent }
}
}
pub trait Backend<Block: BlockT>:
HeaderBackend<Block> + HeaderMetadata<Block, Error = Error>
{
fn body(&self, hash: Block::Hash) -> Result<Option<Vec<<Block as BlockT>::Extrinsic>>>;
fn justifications(&self, hash: Block::Hash) -> Result<Option<Justifications>>;
fn last_finalized(&self) -> Result<Block::Hash>;
fn leaves(&self) -> Result<Vec<Block::Hash>>;
fn children(&self, parent_hash: Block::Hash) -> Result<Vec<Block::Hash>>;
fn longest_containing(
&self,
base_hash: Block::Hash,
import_lock: &RwLock<()>,
) -> Result<Option<Block::Hash>> {
let Some(base_header) = self.header(base_hash)? else { return Ok(None) };
let leaves = {
let _import_guard = import_lock.read();
let info = self.info();
if info.finalized_number > *base_header.number() {
return Ok(None);
}
self.leaves()?
};
for leaf_hash in leaves {
let mut current_hash = leaf_hash;
loop {
if current_hash == base_hash {
return Ok(Some(leaf_hash));
}
let current_header = self
.header(current_hash)?
.ok_or_else(|| Error::MissingHeader(current_hash.to_string()))?;
if current_header.number() < base_header.number() {
break;
}
current_hash = *current_header.parent_hash();
}
}
warn!(
target: crate::LOG_TARGET,
"Block {:?} exists in chain but not found when following all leaves backwards",
base_hash,
);
Ok(None)
}
fn indexed_transaction(&self, hash: Block::Hash) -> Result<Option<Vec<u8>>>;
fn has_indexed_transaction(&self, hash: Block::Hash) -> Result<bool> {
Ok(self.indexed_transaction(hash)?.is_some())
}
fn block_indexed_body(&self, hash: Block::Hash) -> Result<Option<Vec<Vec<u8>>>>;
fn displaced_leaves_after_finalizing(
&self,
finalized_block_hash: Block::Hash,
finalized_block_number: NumberFor<Block>,
) -> std::result::Result<DisplacedLeavesAfterFinalization<Block>, Error> {
let leaves = self.leaves()?;
let now = std::time::Instant::now();
debug!(
target: crate::LOG_TARGET,
?leaves,
?finalized_block_hash,
?finalized_block_number,
"Checking for displaced leaves after finalization."
);
if finalized_block_number == Zero::zero() || leaves.len() == 1 {
return Ok(DisplacedLeavesAfterFinalization::default());
}
let mut finalized_chain = VecDeque::new();
let current_finalized = match self.header_metadata(finalized_block_hash) {
Ok(metadata) => metadata,
Err(Error::UnknownBlock(_)) => {
debug!(
target: crate::LOG_TARGET,
hash = ?finalized_block_hash,
elapsed = ?now.elapsed(),
"Tried to fetch unknown block, block ancestry has gaps.",
);
return Ok(DisplacedLeavesAfterFinalization::default());
},
Err(e) => {
debug!(
target: crate::LOG_TARGET,
hash = ?finalized_block_hash,
err = ?e,
elapsed = ?now.elapsed(),
"Failed to fetch block.",
);
return Err(e);
},
};
finalized_chain.push_front(MinimalBlockMetadata::from(¤t_finalized));
let mut local_cache = HashMap::<Block::Hash, MinimalBlockMetadata<Block>>::new();
let mut result = DisplacedLeavesAfterFinalization {
displaced_leaves: Vec::with_capacity(leaves.len()),
displaced_blocks: Vec::with_capacity(leaves.len()),
};
let mut displaced_blocks_candidates = Vec::new();
let genesis_hash = self.info().genesis_hash;
for leaf_hash in leaves {
let mut current_header_metadata =
MinimalBlockMetadata::from(&self.header_metadata(leaf_hash).map_err(|err| {
debug!(
target: crate::LOG_TARGET,
?leaf_hash,
?err,
elapsed = ?now.elapsed(),
"Failed to fetch leaf header.",
);
err
})?);
let leaf_number = current_header_metadata.number;
if leaf_hash == genesis_hash {
result.displaced_leaves.push((leaf_number, leaf_hash));
debug!(
target: crate::LOG_TARGET,
?leaf_hash,
elapsed = ?now.elapsed(),
"Added genesis leaf to displaced leaves."
);
continue;
}
debug!(
target: crate::LOG_TARGET,
?leaf_number,
?leaf_hash,
elapsed = ?now.elapsed(),
"Handle displaced leaf.",
);
displaced_blocks_candidates.clear();
while current_header_metadata.number > finalized_block_number {
displaced_blocks_candidates.push(current_header_metadata.hash);
let parent_hash = current_header_metadata.parent;
match local_cache.get(&parent_hash) {
Some(metadata_header) => {
current_header_metadata = *metadata_header;
},
None => {
current_header_metadata = MinimalBlockMetadata::from(
&self.header_metadata(parent_hash).map_err(|err| {
debug!(
target: crate::LOG_TARGET,
?err,
?parent_hash,
?leaf_hash,
elapsed = ?now.elapsed(),
"Failed to fetch parent header during leaf tracking.",
);
err
})?,
);
local_cache.insert(parent_hash, current_header_metadata);
},
}
}
if current_header_metadata.hash == finalized_block_hash {
debug!(
target: crate::LOG_TARGET,
?leaf_hash,
elapsed = ?now.elapsed(),
"Leaf points to the finalized header, skipping for now.",
);
continue;
}
displaced_blocks_candidates.push(current_header_metadata.hash);
debug!(
target: crate::LOG_TARGET,
current_hash = ?current_header_metadata.hash,
current_num = ?current_header_metadata.number,
?finalized_block_number,
elapsed = ?now.elapsed(),
"Looking for path from finalized block number to current leaf number"
);
for distance_from_finalized in 1_u32.. {
let (finalized_chain_block_number, finalized_chain_block_hash) =
match finalized_chain.iter().rev().nth(distance_from_finalized as usize) {
Some(header) => (header.number, header.hash),
None => {
let to_fetch = finalized_chain.front().expect("Not empty; qed");
let metadata = match self.header_metadata(to_fetch.parent) {
Ok(metadata) => metadata,
Err(Error::UnknownBlock(_)) => {
debug!(
target: crate::LOG_TARGET,
distance_from_finalized,
hash = ?to_fetch.parent,
number = ?to_fetch.number,
elapsed = ?now.elapsed(),
"Tried to fetch unknown block, block ancestry has gaps."
);
break;
},
Err(err) => {
debug!(
target: crate::LOG_TARGET,
hash = ?to_fetch.parent,
number = ?to_fetch.number,
?err,
elapsed = ?now.elapsed(),
"Failed to fetch header for parent hash.",
);
return Err(err);
},
};
let metadata = MinimalBlockMetadata::from(&metadata);
let result = (metadata.number, metadata.hash);
finalized_chain.push_front(metadata);
result
},
};
if current_header_metadata.hash == finalized_chain_block_hash {
result.displaced_leaves.push((leaf_number, leaf_hash));
debug!(
target: crate::LOG_TARGET,
?leaf_hash,
elapsed = ?now.elapsed(),
"Leaf is ancestor of finalized block."
);
break;
}
if current_header_metadata.number <= finalized_chain_block_number {
continue;
}
let parent_hash = current_header_metadata.parent;
if finalized_chain_block_hash == parent_hash {
result.displaced_blocks.extend(displaced_blocks_candidates.drain(..));
result.displaced_leaves.push((leaf_number, leaf_hash));
debug!(
target: crate::LOG_TARGET,
?leaf_hash,
elapsed = ?now.elapsed(),
"Found displaced leaf."
);
break;
}
debug!(
target: crate::LOG_TARGET,
?parent_hash,
elapsed = ?now.elapsed(),
"Found displaced block. Looking further.",
);
displaced_blocks_candidates.push(parent_hash);
current_header_metadata = MinimalBlockMetadata::from(
&self.header_metadata(parent_hash).map_err(|err| {
debug!(
target: crate::LOG_TARGET,
?err,
?parent_hash,
elapsed = ?now.elapsed(),
"Failed to fetch header for parent during displaced block collection",
);
err
})?,
);
}
}
result.displaced_blocks.sort_unstable();
result.displaced_blocks.dedup();
debug!(
target: crate::LOG_TARGET,
%finalized_block_hash,
?finalized_block_number,
?result,
elapsed = ?now.elapsed(),
"Finished checking for displaced leaves after finalization.",
);
return Ok(result);
}
}
#[derive(Clone, Debug)]
pub struct DisplacedLeavesAfterFinalization<Block: BlockT> {
pub displaced_leaves: Vec<(NumberFor<Block>, Block::Hash)>,
pub displaced_blocks: Vec<Block::Hash>,
}
impl<Block: BlockT> Default for DisplacedLeavesAfterFinalization<Block> {
fn default() -> Self {
Self { displaced_leaves: Vec::new(), displaced_blocks: Vec::new() }
}
}
impl<Block: BlockT> DisplacedLeavesAfterFinalization<Block> {
pub fn hashes(&self) -> impl Iterator<Item = Block::Hash> + '_ {
self.displaced_leaves.iter().map(|(_, hash)| *hash)
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Encode, Decode)]
pub enum BlockGapType {
MissingHeaderAndBody,
MissingBody,
}
#[derive(Debug, Clone, Copy, Eq, PartialEq, Encode, Decode)]
pub struct BlockGap<N> {
pub start: N,
pub end: N,
pub gap_type: BlockGapType,
}
#[derive(Debug, Eq, PartialEq, Clone)]
pub struct Info<Block: BlockT> {
pub best_hash: Block::Hash,
pub best_number: <<Block as BlockT>::Header as HeaderT>::Number,
pub genesis_hash: Block::Hash,
pub finalized_hash: Block::Hash,
pub finalized_number: <<Block as BlockT>::Header as HeaderT>::Number,
pub finalized_state: Option<(Block::Hash, <<Block as BlockT>::Header as HeaderT>::Number)>,
pub number_leaves: usize,
pub block_gap: Option<BlockGap<NumberFor<Block>>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BlockStatus {
InChain,
Unknown,
}