ckb_traits/
header_provider.rsuse ckb_types::{
core::{BlockNumber, EpochNumberWithFraction, HeaderView},
packed::Byte32,
};
pub trait HeaderProvider {
fn get_header(&self, hash: &Byte32) -> Option<HeaderView>;
}
pub struct HeaderFields {
pub hash: Byte32,
pub number: BlockNumber,
pub epoch: EpochNumberWithFraction,
pub timestamp: u64,
pub parent_hash: Byte32,
}
pub trait HeaderFieldsProvider {
fn get_header_fields(&self, hash: &Byte32) -> Option<HeaderFields>;
fn block_median_time(&self, block_hash: &Byte32, median_block_count: usize) -> u64 {
let mut timestamps: Vec<u64> = Vec::with_capacity(median_block_count);
let mut block_hash = block_hash.clone();
for _ in 0..median_block_count {
let header_fields = self
.get_header_fields(&block_hash)
.expect("parent header exist");
timestamps.push(header_fields.timestamp);
block_hash = header_fields.parent_hash;
if header_fields.number == 0 {
break;
}
}
timestamps.sort_unstable();
timestamps[timestamps.len() >> 1]
}
}