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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
#![warn(missing_docs)]
use std::collections::BTreeMap;
use bitcoin::blockdata::block::BlockHeader;
use bitcoin::consensus::params::Params;
use bitcoin::hash_types::BlockHash;
use thiserror::Error;
use crate::block::store;
use crate::block::time::Clock;
use crate::block::{Bits, BlockTime, Height, Target, Work};
use crate::nonempty::NonEmpty;
#[derive(Debug, Error)]
pub enum Error {
#[error("invalid block proof-of-work")]
InvalidBlockPoW,
#[error("invalid block difficulty target: {0}, expected {1}")]
InvalidBlockTarget(Target, Target),
#[error("invalid checkpoint block hash {0} at height {1}")]
InvalidBlockHash(BlockHash, Height),
#[error("block height {0} is prior to last checkpoint")]
InvalidBlockHeight(Height),
#[error("block timestamp {0} is invalid")]
InvalidBlockTime(BlockTime, std::cmp::Ordering),
#[error("duplicate block {0}")]
DuplicateBlock(BlockHash),
#[error("block missing: {0}")]
BlockMissing(BlockHash),
#[error("block import aborted at height {2}: {0} ({1} block(s) imported)")]
BlockImportAborted(Box<Self>, usize, Height),
#[error("storage error: {0}")]
Store(#[from] store::Error),
}
pub trait Header {
fn work(&self) -> Work;
}
impl Header for BlockHeader {
fn work(&self) -> Work {
self.work()
}
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ImportResult {
TipChanged(
BlockHeader,
BlockHash,
Height,
Vec<(Height, BlockHeader)>,
NonEmpty<(Height, BlockHeader)>,
),
TipUnchanged, }
#[derive(Debug, Clone)]
pub struct Branch<'a, H: Header>(pub &'a [H]);
impl<'a, H: Header> Branch<'a, H> {
pub fn work(&self) -> Work {
let mut work = Work::default();
for header in self.0.iter() {
work = work + header.work();
}
work
}
}
pub trait BlockTree: BlockReader {
fn import_blocks<I: Iterator<Item = BlockHeader>, C: Clock>(
&mut self,
chain: I,
context: &C,
) -> Result<ImportResult, Error>;
fn extend_tip<C: Clock>(
&mut self,
header: BlockHeader,
context: &C,
) -> Result<ImportResult, Error>;
}
pub trait BlockReader {
fn get_block(&self, hash: &BlockHash) -> Option<(Height, &BlockHeader)>;
fn get_block_by_height(&self, height: Height) -> Option<&BlockHeader>;
fn find_branch(&self, to: &BlockHash) -> Option<(Height, NonEmpty<BlockHeader>)>;
fn chain<'a>(&'a self) -> Box<dyn Iterator<Item = BlockHeader> + 'a> {
Box::new(self.iter().map(|(_, h)| h))
}
fn iter<'a>(&'a self) -> Box<dyn DoubleEndedIterator<Item = (Height, BlockHeader)> + 'a>;
fn range<'a>(
&'a self,
range: std::ops::Range<Height>,
) -> Box<dyn Iterator<Item = (Height, BlockHash)> + 'a> {
Box::new(
self.iter()
.map(|(height, header)| (height, header.block_hash()))
.skip(range.start as usize)
.take((range.end - range.start) as usize),
)
}
fn height(&self) -> Height;
fn tip(&self) -> (BlockHash, BlockHeader);
fn best_block(&self) -> (Height, &BlockHeader) {
let height = self.height();
(
height,
self.get_block_by_height(height)
.expect("the best block is always present"),
)
}
fn last_checkpoint(&self) -> Height;
fn checkpoints(&self) -> BTreeMap<Height, BlockHash>;
fn genesis(&self) -> &BlockHeader {
self.get_block_by_height(0)
.expect("the genesis block is always present")
}
fn is_known(&self, hash: &BlockHash) -> bool;
fn contains(&self, hash: &BlockHash) -> bool;
fn locate_headers(
&self,
locators: &[BlockHash],
stop_hash: BlockHash,
max_headers: usize,
) -> Vec<BlockHeader>;
fn locator_hashes(&self, from: Height) -> Vec<BlockHash>;
fn next_difficulty_target(
&self,
last_height: Height,
last_time: BlockTime,
last_target: Target,
params: &Params,
) -> Bits {
if (last_height + 1) % params.difficulty_adjustment_interval() != 0 {
return BlockHeader::compact_target_from_u256(&last_target);
}
let last_adjustment_height =
last_height.saturating_sub(params.difficulty_adjustment_interval() - 1);
let last_adjustment_block = self
.get_block_by_height(last_adjustment_height)
.unwrap_or_else(|| self.genesis());
let last_adjustment_time = last_adjustment_block.time;
if params.no_pow_retargeting {
return last_adjustment_block.bits;
}
let actual_timespan = last_time - last_adjustment_time;
let mut adjusted_timespan = actual_timespan;
if actual_timespan < params.pow_target_timespan as BlockTime / 4 {
adjusted_timespan = params.pow_target_timespan as BlockTime / 4;
} else if actual_timespan > params.pow_target_timespan as BlockTime * 4 {
adjusted_timespan = params.pow_target_timespan as BlockTime * 4;
}
let mut target = last_target;
target = target.mul_u32(adjusted_timespan);
target = target / Target::from_u64(params.pow_target_timespan).unwrap();
if target > params.pow_limit {
target = params.pow_limit;
}
BlockHeader::compact_target_from_u256(&target)
}
}