1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
use ckb_types::{
core::{BlockNumber, HeaderView},
packed::Byte32,
};
pub trait HeaderProvider {
fn get_header(&self, hash: &Byte32) -> Option<HeaderView>;
fn timestamp_and_parent(&self, block_hash: &Byte32) -> (u64, BlockNumber, Byte32) {
let header = self.get_header(block_hash).expect("parent header exist");
(
header.timestamp(),
header.number(),
header.data().raw().parent_hash(),
)
}
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 (timestamp, block_number, parent_hash) = self.timestamp_and_parent(&block_hash);
timestamps.push(timestamp);
block_hash = parent_hash;
if block_number == 0 {
break;
}
}
timestamps.sort_unstable();
timestamps[timestamps.len() >> 1]
}
}
impl HeaderProvider for Box<dyn Fn(Byte32) -> Option<HeaderView>> {
fn get_header(&self, hash: &Byte32) -> Option<HeaderView> {
(self)(hash.to_owned())
}
}