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.
@@ -190,6 +214,67 @@ impl Cache for UnboundedCache {
190
214
}
191
215
}
192
216
217
+ impl < P : Poll , C : Cache , L : ChainListener > SpvClient < P , C , L > {
218
+ /// Creates a new SPV client using `chain_tip` as the best known chain tip.
219
+ ///
220
+ /// Subsequent calls to [`poll_best_tip`] will poll for the best chain tip using the given chain
221
+ /// poller, which may be configured with one or more block sources to query. At least one block
222
+ /// source must provide headers back from the best chain tip to its common ancestor with
223
+ /// `chain_tip`.
224
+ /// * `header_cache` is used to look up and store headers on the best chain
225
+ /// * `chain_listener` is notified of any blocks connected or disconnected
226
+ ///
227
+ /// [`poll_best_tip`]: struct.SpvClient.html#method.poll_best_tip
228
+ pub fn new (
229
+ chain_tip : ValidatedBlockHeader ,
230
+ chain_poller : P ,
231
+ header_cache : C ,
232
+ chain_listener : L ,
233
+ ) -> Self {
234
+ let chain_notifier = ChainNotifier { header_cache } ;
235
+ Self { chain_tip, chain_poller, chain_notifier, chain_listener }
236
+ }
237
+
238
+ /// Polls for the best tip and updates the chain listener with any connected or disconnected
239
+ /// blocks accordingly.
240
+ ///
241
+ /// Returns the best polled chain tip relative to the previous best known tip and whether any
242
+ /// blocks were indeed connected or disconnected.
243
+ pub async fn poll_best_tip ( & mut self ) -> BlockSourceResult < ( ChainTip , bool ) > {
244
+ let chain_tip = self . chain_poller . poll_chain_tip ( self . chain_tip ) . await ?;
245
+ let blocks_connected = match chain_tip {
246
+ ChainTip :: Common => false ,
247
+ ChainTip :: Better ( chain_tip) => {
248
+ debug_assert_ne ! ( chain_tip. block_hash, self . chain_tip. block_hash) ;
249
+ debug_assert ! ( chain_tip. chainwork > self . chain_tip. chainwork) ;
250
+ self . update_chain_tip ( chain_tip) . await
251
+ } ,
252
+ ChainTip :: Worse ( chain_tip) => {
253
+ debug_assert_ne ! ( chain_tip. block_hash, self . chain_tip. block_hash) ;
254
+ debug_assert ! ( chain_tip. chainwork <= self . chain_tip. chainwork) ;
255
+ false
256
+ } ,
257
+ } ;
258
+ Ok ( ( chain_tip, blocks_connected) )
259
+ }
260
+
261
+ /// Updates the chain tip, syncing the chain listener with any connected or disconnected
262
+ /// blocks. Returns whether there were any such blocks.
263
+ async fn update_chain_tip ( & mut self , best_chain_tip : ValidatedBlockHeader ) -> bool {
264
+ match self . chain_notifier . sync_listener ( best_chain_tip, & self . chain_tip , & mut self . chain_poller , & mut self . chain_listener ) . await {
265
+ Ok ( _) => {
266
+ self . chain_tip = best_chain_tip;
267
+ true
268
+ } ,
269
+ Err ( ( _, Some ( chain_tip) ) ) if chain_tip. block_hash != self . chain_tip . block_hash => {
270
+ self . chain_tip = chain_tip;
271
+ true
272
+ } ,
273
+ Err ( _) => false ,
274
+ }
275
+ }
276
+ }
277
+
193
278
/// Notifies [listeners] of blocks that have been connected or disconnected from the chain.
194
279
///
195
280
/// [listeners]: trait.ChainListener.html
@@ -330,6 +415,127 @@ impl<C: Cache> ChainNotifier<C> {
330
415
}
331
416
}
332
417
418
+ #[ cfg( test) ]
419
+ mod spv_client_tests {
420
+ use crate :: test_utils:: { Blockchain , NullChainListener } ;
421
+ use super :: * ;
422
+
423
+ use bitcoin:: network:: constants:: Network ;
424
+
425
+ #[ tokio:: test]
426
+ async fn poll_from_chain_without_headers ( ) {
427
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) . without_headers ( ) ;
428
+ let best_tip = chain. at_height ( 1 ) ;
429
+
430
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
431
+ let cache = UnboundedCache :: new ( ) ;
432
+ let mut client = SpvClient :: new ( best_tip, poller, cache, NullChainListener { } ) ;
433
+ match client. poll_best_tip ( ) . await {
434
+ Err ( e) => {
435
+ assert_eq ! ( e. kind( ) , BlockSourceErrorKind :: Persistent ) ;
436
+ assert_eq ! ( e. into_inner( ) . as_ref( ) . to_string( ) , "header not found" ) ;
437
+ } ,
438
+ Ok ( _) => panic ! ( "Expected error" ) ,
439
+ }
440
+ assert_eq ! ( client. chain_tip, best_tip) ;
441
+ }
442
+
443
+ #[ tokio:: test]
444
+ async fn poll_from_chain_with_common_tip ( ) {
445
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) ;
446
+ let common_tip = chain. tip ( ) ;
447
+
448
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
449
+ let cache = UnboundedCache :: new ( ) ;
450
+ let mut client = SpvClient :: new ( common_tip, poller, cache, NullChainListener { } ) ;
451
+ match client. poll_best_tip ( ) . await {
452
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
453
+ Ok ( ( chain_tip, blocks_connected) ) => {
454
+ assert_eq ! ( chain_tip, ChainTip :: Common ) ;
455
+ assert ! ( !blocks_connected) ;
456
+ } ,
457
+ }
458
+ assert_eq ! ( client. chain_tip, common_tip) ;
459
+ }
460
+
461
+ #[ tokio:: test]
462
+ async fn poll_from_chain_with_better_tip ( ) {
463
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) ;
464
+ let new_tip = chain. tip ( ) ;
465
+ let old_tip = chain. at_height ( 1 ) ;
466
+
467
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
468
+ let cache = UnboundedCache :: new ( ) ;
469
+ let mut client = SpvClient :: new ( old_tip, poller, cache, NullChainListener { } ) ;
470
+ match client. poll_best_tip ( ) . await {
471
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
472
+ Ok ( ( chain_tip, blocks_connected) ) => {
473
+ assert_eq ! ( chain_tip, ChainTip :: Better ( new_tip) ) ;
474
+ assert ! ( blocks_connected) ;
475
+ } ,
476
+ }
477
+ assert_eq ! ( client. chain_tip, new_tip) ;
478
+ }
479
+
480
+ #[ tokio:: test]
481
+ async fn poll_from_chain_with_better_tip_and_without_any_new_blocks ( ) {
482
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) . without_blocks ( 2 ..) ;
483
+ let new_tip = chain. tip ( ) ;
484
+ let old_tip = chain. at_height ( 1 ) ;
485
+
486
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
487
+ let cache = UnboundedCache :: new ( ) ;
488
+ let mut client = SpvClient :: new ( old_tip, poller, cache, NullChainListener { } ) ;
489
+ match client. poll_best_tip ( ) . await {
490
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
491
+ Ok ( ( chain_tip, blocks_connected) ) => {
492
+ assert_eq ! ( chain_tip, ChainTip :: Better ( new_tip) ) ;
493
+ assert ! ( !blocks_connected) ;
494
+ } ,
495
+ }
496
+ assert_eq ! ( client. chain_tip, old_tip) ;
497
+ }
498
+
499
+ #[ tokio:: test]
500
+ async fn poll_from_chain_with_better_tip_and_without_some_new_blocks ( ) {
501
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) . without_blocks ( 3 ..) ;
502
+ let new_tip = chain. tip ( ) ;
503
+ let old_tip = chain. at_height ( 1 ) ;
504
+
505
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
506
+ let cache = UnboundedCache :: new ( ) ;
507
+ let mut client = SpvClient :: new ( old_tip, poller, cache, NullChainListener { } ) ;
508
+ match client. poll_best_tip ( ) . await {
509
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
510
+ Ok ( ( chain_tip, blocks_connected) ) => {
511
+ assert_eq ! ( chain_tip, ChainTip :: Better ( new_tip) ) ;
512
+ assert ! ( blocks_connected) ;
513
+ } ,
514
+ }
515
+ assert_eq ! ( client. chain_tip, chain. at_height( 2 ) ) ;
516
+ }
517
+
518
+ #[ tokio:: test]
519
+ async fn poll_from_chain_with_worse_tip ( ) {
520
+ let mut chain = Blockchain :: default ( ) . with_height ( 3 ) ;
521
+ let best_tip = chain. tip ( ) ;
522
+ chain. disconnect_tip ( ) ;
523
+ let worse_tip = chain. tip ( ) ;
524
+
525
+ let poller = poll:: ChainPoller :: new ( & mut chain as & mut dyn BlockSource , Network :: Testnet ) ;
526
+ let cache = UnboundedCache :: new ( ) ;
527
+ let mut client = SpvClient :: new ( best_tip, poller, cache, NullChainListener { } ) ;
528
+ match client. poll_best_tip ( ) . await {
529
+ Err ( e) => panic ! ( "Unexpected error: {:?}" , e) ,
530
+ Ok ( ( chain_tip, blocks_connected) ) => {
531
+ assert_eq ! ( chain_tip, ChainTip :: Worse ( worse_tip) ) ;
532
+ assert ! ( !blocks_connected) ;
533
+ } ,
534
+ }
535
+ assert_eq ! ( client. chain_tip, best_tip) ;
536
+ }
537
+ }
538
+
333
539
#[ cfg( test) ]
334
540
mod chain_notifier_tests {
335
541
use crate :: test_utils:: { Blockchain , MockChainListener } ;
0 commit comments