1
1
//! A lightweight client for keeping in sync with chain activity.
2
2
//!
3
+ //! Defines an [`SpvClient`] utility for polling one or more block sources for the best chain tip.
4
+ //! It is used to notify listeners of blocks connected or disconnected since the last poll. Useful
5
+ //! for keeping a Lightning node in sync with the chain.
6
+ //!
3
7
//! Defines a [`BlockSource`] trait, which is an asynchronous interface for retrieving block headers
4
8
//! and data.
5
9
//!
9
13
//! Both features support either blocking I/O using `std::net::TcpStream` or, with feature `tokio`,
10
14
//! non-blocking I/O using `tokio::net::TcpStream` from inside a Tokio runtime.
11
15
//!
16
+ //! [`SpvClient`]: struct.SpvClient.html
12
17
//! [`BlockSource`]: trait.BlockSource.html
13
18
14
19
#[ cfg( any( feature = "rest-client" , feature = "rpc-client" ) ) ]
@@ -31,7 +36,7 @@ mod test_utils;
31
36
#[ cfg( any( feature = "rest-client" , feature = "rpc-client" ) ) ]
32
37
mod utils;
33
38
34
- use crate :: poll:: { Poll , ValidatedBlockHeader } ;
39
+ use crate :: poll:: { ChainTip , Poll , ValidatedBlockHeader } ;
35
40
36
41
use bitcoin:: blockdata:: block:: { Block , BlockHeader } ;
37
42
use bitcoin:: hash_types:: BlockHash ;
@@ -133,6 +138,25 @@ pub struct BlockHeaderData {
133
138
pub chainwork : Uint256 ,
134
139
}
135
140
141
+ /// A lightweight client for keeping a listener in sync with the chain, allowing for Simplified
142
+ /// Payment Verification (SPV).
143
+ ///
144
+ /// The client is parameterized by a chain poller which is responsible for polling one or more block
145
+ /// sources for the best chain tip. During this process it detects any chain forks, determines which
146
+ /// constitutes the best chain, and updates the listener accordingly with any blocks that were
147
+ /// connected or disconnected since the last poll.
148
+ ///
149
+ /// Block headers for the best chain are maintained in the parameterized cache, allowing for a
150
+ /// custom cache eviction policy. This offers flexibility to those sensitive to resource usage.
151
+ /// Hence, there is a trade-off between a lower memory footprint and potentially increased network
152
+ /// I/O as headers are re-fetched during fork detection.
153
+ pub struct SpvClient < P : Poll , C : Cache , L : ChainListener > {
154
+ chain_tip : ValidatedBlockHeader ,
155
+ chain_poller : P ,
156
+ chain_notifier : ChainNotifier < C > ,
157
+ chain_listener : L ,
158
+ }
159
+
136
160
/// Adaptor used for notifying when blocks have been connected or disconnected from the chain.
137
161
///
138
162
/// Used when needing to replay chain data upon startup or as new chain events occur.
@@ -186,6 +210,67 @@ impl Cache for UnboundedCache {
186
210
}
187
211
}
188
212
213
+ impl < P : Poll , C : Cache , L : ChainListener > SpvClient < P , C , L > {
214
+ /// Creates a new SPV client using `chain_tip` as the best known chain tip.
215
+ ///
216
+ /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
217
+ /// poller, which may be configured with one or more block sources to query. At least one block
218
+ /// source must provide headers back from the best chain tip to its common ancestor with
219
+ /// `chain_tip`.
220
+ /// * `header_cache` is used to look up and store headers on the best chain
221
+ /// * `chain_listener` is notified of any blocks connected or disconnected
222
+ ///
223
+ /// [`poll_best_tip`]: struct.SpvClient.html#method.poll_best_tip
224
+ pub fn new (
225
+ chain_tip : ValidatedBlockHeader ,
226
+ chain_poller : P ,
227
+ header_cache : C ,
228
+ chain_listener : L ,
229
+ ) -> Self {
230
+ let chain_notifier = ChainNotifier { header_cache } ;
231
+ Self { chain_tip, chain_poller, chain_notifier, chain_listener }
232
+ }
233
+
234
+ /// Polls for the best tip and updates the chain listener with any connected or disconnected
235
+ /// blocks accordingly.
236
+ ///
237
+ /// Returns the best polled chain tip relative to the previous best known tip and whether any
238
+ /// blocks were indeed connected or disconnected.
239
+ pub async fn poll_best_tip ( & mut self ) -> BlockSourceResult < ( ChainTip , bool ) > {
240
+ let chain_tip = self . chain_poller . poll_chain_tip ( self . chain_tip ) . await ?;
241
+ let blocks_connected = match chain_tip {
242
+ ChainTip :: Common => false ,
243
+ ChainTip :: Better ( chain_tip) => {
244
+ debug_assert_ne ! ( chain_tip. block_hash, self . chain_tip. block_hash) ;
245
+ debug_assert ! ( chain_tip. chainwork > self . chain_tip. chainwork) ;
246
+ self . update_chain_tip ( chain_tip) . await
247
+ } ,
248
+ ChainTip :: Worse ( chain_tip) => {
249
+ debug_assert_ne ! ( chain_tip. block_hash, self . chain_tip. block_hash) ;
250
+ debug_assert ! ( chain_tip. chainwork <= self . chain_tip. chainwork) ;
251
+ false
252
+ } ,
253
+ } ;
254
+ Ok ( ( chain_tip, blocks_connected) )
255
+ }
256
+
257
+ /// Updates the chain tip, syncing the chain listener with any connected or disconnected
258
+ /// blocks. Returns whether there were any such blocks.
259
+ async fn update_chain_tip ( & mut self , best_chain_tip : ValidatedBlockHeader ) -> bool {
260
+ match self . chain_notifier . sync_listener ( best_chain_tip, & self . chain_tip , & mut self . chain_poller , & mut self . chain_listener ) . await {
261
+ Ok ( _) => {
262
+ self . chain_tip = best_chain_tip;
263
+ true
264
+ } ,
265
+ Err ( ( _, Some ( chain_tip) ) ) if chain_tip. block_hash != self . chain_tip . block_hash => {
266
+ self . chain_tip = chain_tip;
267
+ true
268
+ } ,
269
+ Err ( _) => false ,
270
+ }
271
+ }
272
+ }
273
+
189
274
/// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
190
275
///
191
276
/// [listeners]: trait.ChainListener.html
@@ -301,6 +386,127 @@ impl<C: Cache> ChainNotifier<C> {
301
386
}
302
387
}
303
388
389
+ #[ cfg( test) ]
390
+ mod spv_client_tests {
391
+ use crate :: test_utils:: { Blockchain , NullChainListener } ;
392
+ use super :: * ;
393
+
394
+ use bitcoin:: network:: constants:: Network ;
395
+
396
+ #[ tokio:: test]
397
+ async fn poll_from_chain_without_headers ( ) {
398
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) . without_headers ( ) ;
399
+ let best_tip = chain. at_height ( 1 ) ;
400
+
401
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
402
+ let cache = UnboundedCache :: new ( ) ;
403
+ let mut client = SpvClient :: new ( best_tip, poller, cache, NullChainListener { } ) ;
404
+ match client. poll_best_tip ( ) . await {
405
+ Err ( e) => {
406
+ assert_eq ! ( e. kind( ) , BlockSourceErrorKind :: Persistent ) ;
407
+ assert_eq ! ( e. into_inner( ) . as_ref( ) . to_string( ) , "header not found" ) ;
408
+ } ,
409
+ Ok ( _) => panic ! ( "Expected error" ) ,
410
+ }
411
+ assert_eq ! ( client. chain_tip, best_tip) ;
412
+ }
413
+
414
+ #[ tokio:: test]
415
+ async fn poll_from_chain_with_common_tip ( ) {
416
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) ;
417
+ let common_tip = chain. tip ( ) ;
418
+
419
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
420
+ let cache = UnboundedCache :: new ( ) ;
421
+ let mut client = SpvClient :: new ( common_tip, poller, cache, NullChainListener { } ) ;
422
+ match client. poll_best_tip ( ) . await {
423
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
424
+ Ok ( ( chain_tip, blocks_connected) ) => {
425
+ assert_eq ! ( chain_tip, ChainTip :: Common ) ;
426
+ assert ! ( !blocks_connected) ;
427
+ } ,
428
+ }
429
+ assert_eq ! ( client. chain_tip, common_tip) ;
430
+ }
431
+
432
+ #[ tokio:: test]
433
+ async fn poll_from_chain_with_better_tip ( ) {
434
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) ;
435
+ let new_tip = chain. tip ( ) ;
436
+ let old_tip = chain. at_height ( 1 ) ;
437
+
438
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
439
+ let cache = UnboundedCache :: new ( ) ;
440
+ let mut client = SpvClient :: new ( old_tip, poller, cache, NullChainListener { } ) ;
441
+ match client. poll_best_tip ( ) . await {
442
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
443
+ Ok ( ( chain_tip, blocks_connected) ) => {
444
+ assert_eq ! ( chain_tip, ChainTip :: Better ( new_tip) ) ;
445
+ assert ! ( blocks_connected) ;
446
+ } ,
447
+ }
448
+ assert_eq ! ( client. chain_tip, new_tip) ;
449
+ }
450
+
451
+ #[ tokio:: test]
452
+ async fn poll_from_chain_with_better_tip_and_without_any_new_blocks ( ) {
453
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) . without_blocks ( 2 ..) ;
454
+ let new_tip = chain. tip ( ) ;
455
+ let old_tip = chain. at_height ( 1 ) ;
456
+
457
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
458
+ let cache = UnboundedCache :: new ( ) ;
459
+ let mut client = SpvClient :: new ( old_tip, poller, cache, NullChainListener { } ) ;
460
+ match client. poll_best_tip ( ) . await {
461
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
462
+ Ok ( ( chain_tip, blocks_connected) ) => {
463
+ assert_eq ! ( chain_tip, ChainTip :: Better ( new_tip) ) ;
464
+ assert ! ( !blocks_connected) ;
465
+ } ,
466
+ }
467
+ assert_eq ! ( client. chain_tip, old_tip) ;
468
+ }
469
+
470
+ #[ tokio:: test]
471
+ async fn poll_from_chain_with_better_tip_and_without_some_new_blocks ( ) {
472
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) . without_blocks ( 3 ..) ;
473
+ let new_tip = chain. tip ( ) ;
474
+ let old_tip = chain. at_height ( 1 ) ;
475
+
476
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
477
+ let cache = UnboundedCache :: new ( ) ;
478
+ let mut client = SpvClient :: new ( old_tip, poller, cache, NullChainListener { } ) ;
479
+ match client. poll_best_tip ( ) . await {
480
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
481
+ Ok ( ( chain_tip, blocks_connected) ) => {
482
+ assert_eq ! ( chain_tip, ChainTip :: Better ( new_tip) ) ;
483
+ assert ! ( blocks_connected) ;
484
+ } ,
485
+ }
486
+ assert_eq ! ( client. chain_tip, chain. at_height( 2 ) ) ;
487
+ }
488
+
489
+ #[ tokio:: test]
490
+ async fn poll_from_chain_with_worse_tip ( ) {
491
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) ;
492
+ let best_tip = chain. tip ( ) ;
493
+ chain. disconnect_tip ( ) ;
494
+ let worse_tip = chain. tip ( ) ;
495
+
496
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
497
+ let cache = UnboundedCache :: new ( ) ;
498
+ let mut client = SpvClient :: new ( best_tip, poller, cache, NullChainListener { } ) ;
499
+ match client. poll_best_tip ( ) . await {
500
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
501
+ Ok ( ( chain_tip, blocks_connected) ) => {
502
+ assert_eq ! ( chain_tip, ChainTip :: Worse ( worse_tip) ) ;
503
+ assert ! ( !blocks_connected) ;
504
+ } ,
505
+ }
506
+ assert_eq ! ( client. chain_tip, best_tip) ;
507
+ }
508
+ }
509
+
304
510
#[ cfg( test) ]
305
511
mod chain_notifier_tests {
306
512
use crate :: test_utils:: { Blockchain , MockChainListener } ;
0 commit comments