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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
use crate::{AsyncBlockSourceResult, BlockData, BlockHeaderData, BlockSource, BlockSourceError, BlockSourceResult};
use bitcoin::hash_types::BlockHash;
use bitcoin::network::constants::Network;
use lightning::chain::BestBlock;
use std::ops::Deref;
pub trait Poll {
fn poll_chain_tip<'a>(&'a self, best_known_chain_tip: ValidatedBlockHeader) ->
AsyncBlockSourceResult<'a, ChainTip>;
fn look_up_previous_header<'a>(&'a self, header: &'a ValidatedBlockHeader) ->
AsyncBlockSourceResult<'a, ValidatedBlockHeader>;
fn fetch_block<'a>(&'a self, header: &'a ValidatedBlockHeader) ->
AsyncBlockSourceResult<'a, ValidatedBlock>;
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ChainTip {
Common,
Better(ValidatedBlockHeader),
Worse(ValidatedBlockHeader),
}
pub trait Validate: sealed::Validate {
type T: std::ops::Deref<Target = Self>;
fn validate(self, block_hash: BlockHash) -> BlockSourceResult<Self::T>;
}
impl Validate for BlockHeaderData {
type T = ValidatedBlockHeader;
fn validate(self, block_hash: BlockHash) -> BlockSourceResult<Self::T> {
let pow_valid_block_hash = self.header
.validate_pow(&self.header.target())
.or_else(|e| Err(BlockSourceError::persistent(e)))?;
if pow_valid_block_hash != block_hash {
return Err(BlockSourceError::persistent("invalid block hash"));
}
Ok(ValidatedBlockHeader { block_hash, inner: self })
}
}
impl Validate for BlockData {
type T = ValidatedBlock;
fn validate(self, block_hash: BlockHash) -> BlockSourceResult<Self::T> {
let header = match &self {
BlockData::FullBlock(block) => &block.header,
BlockData::HeaderOnly(header) => header,
};
let pow_valid_block_hash = header
.validate_pow(&header.target())
.or_else(|e| Err(BlockSourceError::persistent(e)))?;
if pow_valid_block_hash != block_hash {
return Err(BlockSourceError::persistent("invalid block hash"));
}
if let BlockData::FullBlock(block) = &self {
if !block.check_merkle_root() {
return Err(BlockSourceError::persistent("invalid merkle root"));
}
if !block.check_witness_commitment() {
return Err(BlockSourceError::persistent("invalid witness commitment"));
}
}
Ok(ValidatedBlock { block_hash, inner: self })
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ValidatedBlockHeader {
pub(crate) block_hash: BlockHash,
inner: BlockHeaderData,
}
impl std::ops::Deref for ValidatedBlockHeader {
type Target = BlockHeaderData;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl ValidatedBlockHeader {
fn check_builds_on(&self, previous_header: &ValidatedBlockHeader, network: Network) -> BlockSourceResult<()> {
if self.header.prev_blockhash != previous_header.block_hash {
return Err(BlockSourceError::persistent("invalid previous block hash"));
}
if self.height != previous_header.height + 1 {
return Err(BlockSourceError::persistent("invalid block height"));
}
let work = self.header.work();
if self.chainwork != previous_header.chainwork + work {
return Err(BlockSourceError::persistent("invalid chainwork"));
}
if let Network::Bitcoin = network {
if self.height % 2016 == 0 {
let previous_work = previous_header.header.work();
if work > (previous_work << 2) || work < (previous_work >> 2) {
return Err(BlockSourceError::persistent("invalid difficulty transition"))
}
} else if self.header.bits != previous_header.header.bits {
return Err(BlockSourceError::persistent("invalid difficulty"))
}
}
Ok(())
}
pub fn to_best_block(&self) -> BestBlock {
BestBlock::new(self.block_hash, self.inner.height)
}
}
pub struct ValidatedBlock {
pub(crate) block_hash: BlockHash,
inner: BlockData,
}
impl std::ops::Deref for ValidatedBlock {
type Target = BlockData;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
mod sealed {
pub trait Validate {}
impl Validate for crate::BlockHeaderData {}
impl Validate for crate::BlockData {}
}
pub struct ChainPoller<B: Deref<Target=T> + Sized + Send + Sync, T: BlockSource + ?Sized> {
block_source: B,
network: Network,
}
impl<B: Deref<Target=T> + Sized + Send + Sync, T: BlockSource + ?Sized> ChainPoller<B, T> {
pub fn new(block_source: B, network: Network) -> Self {
Self { block_source, network }
}
}
impl<B: Deref<Target=T> + Sized + Send + Sync, T: BlockSource + ?Sized> Poll for ChainPoller<B, T> {
fn poll_chain_tip<'a>(&'a self, best_known_chain_tip: ValidatedBlockHeader) ->
AsyncBlockSourceResult<'a, ChainTip>
{
Box::pin(async move {
let (block_hash, height) = self.block_source.get_best_block().await?;
if block_hash == best_known_chain_tip.header.block_hash() {
return Ok(ChainTip::Common);
}
let chain_tip = self.block_source
.get_header(&block_hash, height).await?
.validate(block_hash)?;
if chain_tip.chainwork > best_known_chain_tip.chainwork {
Ok(ChainTip::Better(chain_tip))
} else {
Ok(ChainTip::Worse(chain_tip))
}
})
}
fn look_up_previous_header<'a>(&'a self, header: &'a ValidatedBlockHeader) ->
AsyncBlockSourceResult<'a, ValidatedBlockHeader>
{
Box::pin(async move {
if header.height == 0 {
return Err(BlockSourceError::persistent("genesis block reached"));
}
let previous_hash = &header.header.prev_blockhash;
let height = header.height - 1;
let previous_header = self.block_source
.get_header(previous_hash, Some(height)).await?
.validate(*previous_hash)?;
header.check_builds_on(&previous_header, self.network)?;
Ok(previous_header)
})
}
fn fetch_block<'a>(&'a self, header: &'a ValidatedBlockHeader) ->
AsyncBlockSourceResult<'a, ValidatedBlock>
{
Box::pin(async move {
self.block_source
.get_block(&header.block_hash).await?
.validate(header.block_hash)
})
}
}
#[cfg(test)]
mod tests {
use crate::*;
use crate::test_utils::Blockchain;
use super::*;
use bitcoin::util::uint::Uint256;
#[tokio::test]
async fn poll_empty_chain() {
let mut chain = Blockchain::default().with_height(0);
let best_known_chain_tip = chain.tip();
chain.disconnect_tip();
let poller = ChainPoller::new(&chain, Network::Bitcoin);
match poller.poll_chain_tip(best_known_chain_tip).await {
Err(e) => {
assert_eq!(e.kind(), BlockSourceErrorKind::Transient);
assert_eq!(e.into_inner().as_ref().to_string(), "empty chain");
},
Ok(_) => panic!("Expected error"),
}
}
#[tokio::test]
async fn poll_chain_without_headers() {
let chain = Blockchain::default().with_height(1).without_headers();
let best_known_chain_tip = chain.at_height(0);
let poller = ChainPoller::new(&chain, Network::Bitcoin);
match poller.poll_chain_tip(best_known_chain_tip).await {
Err(e) => {
assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
assert_eq!(e.into_inner().as_ref().to_string(), "header not found");
},
Ok(_) => panic!("Expected error"),
}
}
#[tokio::test]
async fn poll_chain_with_invalid_pow() {
let mut chain = Blockchain::default().with_height(1);
let best_known_chain_tip = chain.at_height(0);
chain.blocks.last_mut().unwrap().header.bits =
BlockHeader::compact_target_from_u256(&Uint256::from_be_bytes([0; 32]));
let poller = ChainPoller::new(&chain, Network::Bitcoin);
match poller.poll_chain_tip(best_known_chain_tip).await {
Err(e) => {
assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
assert_eq!(e.into_inner().as_ref().to_string(), "block target correct but not attained");
},
Ok(_) => panic!("Expected error"),
}
}
#[tokio::test]
async fn poll_chain_with_malformed_headers() {
let chain = Blockchain::default().with_height(1).malformed_headers();
let best_known_chain_tip = chain.at_height(0);
let poller = ChainPoller::new(&chain, Network::Bitcoin);
match poller.poll_chain_tip(best_known_chain_tip).await {
Err(e) => {
assert_eq!(e.kind(), BlockSourceErrorKind::Persistent);
assert_eq!(e.into_inner().as_ref().to_string(), "invalid block hash");
},
Ok(_) => panic!("Expected error"),
}
}
#[tokio::test]
async fn poll_chain_with_common_tip() {
let chain = Blockchain::default().with_height(0);
let best_known_chain_tip = chain.tip();
let poller = ChainPoller::new(&chain, Network::Bitcoin);
match poller.poll_chain_tip(best_known_chain_tip).await {
Err(e) => panic!("Unexpected error: {:?}", e),
Ok(tip) => assert_eq!(tip, ChainTip::Common),
}
}
#[tokio::test]
async fn poll_chain_with_uncommon_tip_but_equal_chainwork() {
let mut chain = Blockchain::default().with_height(1);
let best_known_chain_tip = chain.tip();
chain.blocks.last_mut().unwrap().header.nonce += 1;
let worse_chain_tip = chain.tip();
assert_eq!(best_known_chain_tip.chainwork, worse_chain_tip.chainwork);
let poller = ChainPoller::new(&chain, Network::Bitcoin);
match poller.poll_chain_tip(best_known_chain_tip).await {
Err(e) => panic!("Unexpected error: {:?}", e),
Ok(tip) => assert_eq!(tip, ChainTip::Worse(worse_chain_tip)),
}
}
#[tokio::test]
async fn poll_chain_with_worse_tip() {
let mut chain = Blockchain::default().with_height(1);
let best_known_chain_tip = chain.tip();
chain.disconnect_tip();
let worse_chain_tip = chain.tip();
let poller = ChainPoller::new(&chain, Network::Bitcoin);
match poller.poll_chain_tip(best_known_chain_tip).await {
Err(e) => panic!("Unexpected error: {:?}", e),
Ok(tip) => assert_eq!(tip, ChainTip::Worse(worse_chain_tip)),
}
}
#[tokio::test]
async fn poll_chain_with_better_tip() {
let chain = Blockchain::default().with_height(1);
let best_known_chain_tip = chain.at_height(0);
let better_chain_tip = chain.tip();
let poller = ChainPoller::new(&chain, Network::Bitcoin);
match poller.poll_chain_tip(best_known_chain_tip).await {
Err(e) => panic!("Unexpected error: {:?}", e),
Ok(tip) => assert_eq!(tip, ChainTip::Better(better_chain_tip)),
}
}
}