-
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathcbfmgr.rs
2208 lines (1928 loc) · 72 KB
/
cbfmgr.rs
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
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Compact Block Filter Manager.
//!
//! Manages BIP 157/8 compact block filter sync.
//!
mod rescan;
use std::ops::{Bound, RangeInclusive};
use thiserror::Error;
use nakamoto_common::bitcoin::network::constants::ServiceFlags;
use nakamoto_common::bitcoin::network::message_filter::{CFHeaders, CFilter, GetCFHeaders};
use nakamoto_common::bitcoin::{Script, Transaction, Txid};
use nakamoto_common::block::filter::{self, BlockFilter, Filters};
use nakamoto_common::block::time::{Clock, LocalDuration, LocalTime};
use nakamoto_common::block::tree::BlockReader;
use nakamoto_common::block::{BlockHash, Height};
use nakamoto_common::collections::{AddressBook, HashMap};
use nakamoto_common::source;
use super::filter_cache::FilterCache;
use super::output::{Disconnect, Wakeup};
use super::{DisconnectReason, Link, PeerId, Socket};
use rescan::Rescan;
/// Idle timeout.
pub const IDLE_TIMEOUT: LocalDuration = LocalDuration::BLOCK_INTERVAL;
/// Services required from peers for BIP 158 functionality.
pub const REQUIRED_SERVICES: ServiceFlags = ServiceFlags::COMPACT_FILTERS;
/// Maximum filter headers to be expected in a message.
pub const MAX_MESSAGE_CFHEADERS: usize = 2000;
/// Maximum filters to be expected in a message.
pub const MAX_MESSAGE_CFILTERS: usize = 1000;
/// Filter cache capacity in bytes.
pub const DEFAULT_FILTER_CACHE_SIZE: usize = 1024 * 1024; // 1 MB.
/// How long to wait to receive a reply from a peer.
pub const DEFAULT_REQUEST_TIMEOUT: LocalDuration = LocalDuration::from_secs(6);
/// An error originating in the CBF manager.
#[derive(Error, Debug)]
pub enum Error {
/// The request was ignored. This happens if we're not able to fulfill the request.
#[error("ignoring `{msg}` message from {from}")]
Ignored {
/// Message that was ignored.
msg: &'static str,
/// Message sender.
from: PeerId,
},
/// Error due to an invalid peer message.
#[error("invalid message received from {from}: {reason}")]
InvalidMessage {
/// Message sender.
from: PeerId,
/// Reason why the message is invalid.
reason: &'static str,
},
/// Error with the underlying filters datastore.
#[error("filters error: {0}")]
Filters(#[from] filter::Error),
}
/// An event originating in the CBF manager.
#[derive(Debug, Clone)]
pub enum Event {
/// Filter was received and validated.
FilterReceived {
/// Peer we received from.
from: PeerId,
/// The received filter.
filter: BlockFilter,
/// Filter height.
height: Height,
/// Hash of corresponding block.
block_hash: BlockHash,
},
/// Filter was processed.
FilterProcessed {
/// The corresponding block hash.
block: BlockHash,
/// The filter height.
height: Height,
/// Whether or not this filter matched something in the watchlist.
matched: bool,
/// Whether or not this filter was valid.
valid: bool,
/// Filter was cached.
cached: bool,
},
/// Filter headers were imported successfully.
FilterHeadersImported {
/// Number of filter headers imported.
count: usize,
/// New filter header chain height.
height: Height,
/// Block hash corresponding to the tip of the filter header chain.
block_hash: BlockHash,
},
/// Started syncing filter headers with a peer.
Syncing {
/// The remote peer.
peer: PeerId,
/// The start height from which we're syncing.
start_height: Height,
/// The stop hash.
stop_hash: BlockHash,
},
/// Request canceled.
RequestCanceled {
/// Reason for cancellation.
reason: &'static str,
},
/// A rescan has started.
RescanStarted {
/// Start height.
start: Height,
/// End height.
end: Option<Height>,
},
/// An active rescan has completed.
RescanCompleted {
/// Last height processed by rescan.
height: Height,
},
/// Finished syncing filter headers up to the specified height.
Synced(Height),
/// A peer has timed out responding to a filter request.
/// TODO: Use event or remove.
TimedOut(PeerId),
/// Block header chain rollback detected.
/// TODO: Use event or remove.
RollbackDetected(Height),
}
impl std::fmt::Display for Event {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Event::TimedOut(addr) => write!(fmt, "Peer {} timed out", addr),
Event::FilterReceived {
from,
height,
block_hash,
..
} => {
write!(
fmt,
"Filter {} received for block {} from {}",
height, block_hash, from
)
}
Event::FilterProcessed {
height,
matched,
valid,
..
} => {
write!(
fmt,
"Filter processed at height {} (match = {}, valid = {})",
height, matched, valid
)
}
Event::FilterHeadersImported { count, height, .. } => {
write!(
fmt,
"Imported {} filter header(s) up to height = {}",
count, height
)
}
Event::Synced(height) => {
write!(fmt, "Filter headers synced up to height = {}", height)
}
Event::Syncing {
peer,
start_height,
stop_hash,
} => write!(
fmt,
"Syncing filter headers with {}, start = {}, stop = {}",
peer, start_height, stop_hash
),
Event::RescanStarted {
start,
end: Some(end),
} => {
write!(fmt, "Rescan started from height {} to {}", start, end)
}
Event::RescanStarted { start, end: None } => {
write!(fmt, "Rescan started from height {}", start)
}
Event::RescanCompleted { height } => {
write!(fmt, "Rescan completed at height {}", height)
}
Event::RequestCanceled { reason } => {
write!(fmt, "Request canceled: {}", reason)
}
Event::RollbackDetected(height) => {
write!(
fmt,
"Rollback detected: discarding filters from height {}..",
height
)
}
}
}
}
/// Compact filter synchronization.
pub trait SyncFilters {
/// Get compact filter headers from peer, starting at the start height, and ending at the
/// stop hash.
fn get_cfheaders(
&mut self,
addr: PeerId,
start_height: Height,
stop_hash: BlockHash,
timeout: LocalDuration,
);
/// Get compact filters from a peer.
fn get_cfilters(
&mut self,
addr: PeerId,
start_height: Height,
stop_hash: BlockHash,
timeout: LocalDuration,
);
/// Send compact filter headers to a peer.
fn send_cfheaders(&mut self, addr: PeerId, headers: CFHeaders);
/// Send a compact filter to a peer.
fn send_cfilter(&mut self, addr: PeerId, filter: CFilter);
}
/// The ability to emit CBF related events.
pub trait Events {
/// Emit an CBF-related event.
fn event(&self, event: Event);
}
/// An error from attempting to get compact filters.
#[derive(Error, Debug)]
pub enum GetFiltersError {
/// The specified range is invalid, eg. it is out of bounds.
#[error("the specified range is invalid")]
InvalidRange,
/// Not connected to any compact filter peer.
#[error("not connected to any peer with compact filters support")]
NotConnected,
}
/// CBF manager configuration.
#[derive(Debug)]
pub struct Config {
/// How long to wait for a response from a peer.
pub request_timeout: LocalDuration,
/// Filter cache size, in bytes.
pub filter_cache_size: usize,
}
impl Default for Config {
fn default() -> Self {
Self {
request_timeout: DEFAULT_REQUEST_TIMEOUT,
filter_cache_size: DEFAULT_FILTER_CACHE_SIZE,
}
}
}
/// A CBF peer.
#[derive(Debug)]
struct Peer {
#[allow(dead_code)]
height: Height,
#[allow(dead_code)]
last_active: LocalTime,
#[allow(dead_code)]
socket: Socket,
}
/// A compact block filter manager.
#[derive(Debug)]
pub struct FilterManager<F, U, C> {
/// Rescan state.
pub rescan: Rescan,
/// Filter header chain.
pub filters: F,
config: Config,
peers: AddressBook<PeerId, Peer>,
upstream: U,
clock: C,
/// Last time we idled.
last_idle: Option<LocalTime>,
/// Last time a filter was processed.
/// We use this to figure out when to re-issue filter requests.
last_processed: Option<LocalTime>,
/// Inflight requests.
inflight: HashMap<BlockHash, (Height, PeerId, LocalTime)>,
}
impl<F: Filters, U: SyncFilters + Events + Wakeup + Disconnect, C: Clock> FilterManager<F, U, C> {
/// Create a new filter manager.
pub fn new(config: Config, rng: fastrand::Rng, filters: F, upstream: U, clock: C) -> Self {
let peers = AddressBook::new(rng.clone());
let rescan = Rescan::new(config.filter_cache_size);
Self {
config,
peers,
rescan,
upstream,
clock,
filters,
inflight: HashMap::with_hasher(rng.into()),
last_idle: None,
last_processed: None,
}
}
/// Initialize the manager. Should only be called once.
pub fn initialize<T: BlockReader>(&mut self, tree: &T) {
self.idle(tree);
}
/// A tick was received.
pub fn received_wake<T: BlockReader>(&mut self, tree: &T) {
self.idle(tree);
let timeout = self.config.request_timeout;
let now = self.clock.local_time();
// Check if any header request expired. If so, retry with a different peer and disconnect
// the unresponsive peer.
for (stop_hash, (start_height, addr, expiry)) in &mut self.inflight {
if now >= *expiry {
let (start_height, stop_hash) = (*start_height, *stop_hash);
if let Some((peer, _)) = self.peers.sample_with(|p, _| p != addr) {
let peer = *peer;
self.peers.remove(addr);
self.upstream
.disconnect(*addr, DisconnectReason::PeerTimeout("getcfheaders"));
self.upstream
.get_cfheaders(peer, start_height, stop_hash, timeout);
*addr = peer;
*expiry = now + timeout;
}
}
}
// If we've waited too long since the last processed filter, re-issue requests
// for missing filters.
if now - self.last_processed.unwrap_or_default() >= DEFAULT_REQUEST_TIMEOUT {
if self.rescan.active {
self.rescan.reset(); // Clear pending request queue.
self.get_cfilters(self.rescan.current..=self.filters.height(), tree)
.ok();
}
}
}
/// Rollback filters to the given height.
pub fn rollback(&mut self, height: Height) -> Result<(), filter::Error> {
// It's possible that a rollback doesn't affect the filter chain, if the filter headers
// haven't caught up to the block headers when the re-org happens.
if height >= self.filters.height() {
return Ok(());
}
// Purge stale block filters.
self.rescan.rollback(height);
// Rollback filter header chain.
self.filters.rollback(height)?;
// Nb. Inflight filter header requests for heights that were rolled back will be ignored
// when received.
//
// TODO: Inflight filter requests need to be re-issued.
if self.rescan.active {
// Reset "current" scanning height.
//
// We start re-scanning from either the start, or the current height, whichever
// is greater, while ensuring that we only reset backwards, ie. we never skip
// heights.
//
// For example, given we are currently at 7, if we rolled back to height 4, and our
// start is at 5, we restart from 5.
//
// If we rolled back to height 4 and our start is at 3, we restart at 4, because
// we don't need to scan blocks before our start height.
//
// If we rolled back to height 9 from height 11, we wouldn't want to re-scan any
// blocks, since we haven't yet gotten to that height.
//
let start = self.rescan.start;
let current = self.rescan.current;
if current > height + 1 {
self.rescan.current = Height::max(height + 1, start);
}
log::debug!(
"Rollback from {} to {}, start = {}, height = {}",
current,
self.rescan.current,
start,
height
);
}
Ok(())
}
/// Add scripts to the list of scripts to watch.
pub fn watch(&mut self, scripts: Vec<Script>) {
self.rescan.watch.extend(scripts);
}
/// Add transaction outputs to list of transactions to watch.
pub fn watch_transaction(&mut self, tx: &Transaction) {
self.rescan.transactions.insert(
tx.txid(),
tx.output.iter().map(|o| o.script_pubkey.clone()).collect(),
);
}
/// Remove transaction from list of transactions being watch.
pub fn unwatch_transaction(&mut self, txid: &Txid) -> bool {
self.rescan.transactions.remove(txid).is_some()
}
/// Rescan compact block filters.
pub fn rescan<T: BlockReader>(
&mut self,
start: Bound<Height>,
end: Bound<Height>,
watch: Vec<Script>,
tree: &T,
) -> Vec<(Height, BlockHash)> {
self.rescan.restart(
match start {
Bound::Unbounded => tree.height() + 1,
Bound::Included(h) => h,
Bound::Excluded(h) => h + 1,
},
match end {
Bound::Unbounded => None,
Bound::Included(h) => Some(h),
Bound::Excluded(h) => Some(h - 1),
},
watch,
);
self.upstream.event(Event::RescanStarted {
start: self.rescan.start,
end: self.rescan.end,
});
if self.rescan.watch.is_empty() {
return vec![];
}
let height = self.filters.height();
let start = self.rescan.start;
let stop = self
.rescan
.end
// Don't request further than the filter chain height.
.map(|h| Height::min(h, height))
.unwrap_or(height);
let range = start..=stop;
if range.is_empty() {
return vec![];
}
// Start fetching the filters we can.
match self.get_cfilters(range, tree) {
Ok(()) => {}
Err(GetFiltersError::NotConnected) => {}
Err(err) => panic!("{}: Error fetching filters: {}", source!(), err),
}
// When we reset the rescan range, there is the possibility of getting immediate cache
// hits from `get_cfilters`. Hence, process the filter queue.
let (matches, events, _) = self.rescan.process();
for event in events {
self.upstream.event(event);
}
matches
}
/// Send one or more `getcfilters` messages to random peers.
///
/// If the range is greater than [`MAX_MESSAGE_CFILTERS`], request filters from multiple
/// peers.
pub fn get_cfilters<T: BlockReader>(
&mut self,
range: RangeInclusive<Height>,
tree: &T,
) -> Result<(), GetFiltersError> {
if self.peers.is_empty() {
return Err(GetFiltersError::NotConnected);
}
if range.is_empty() {
return Err(GetFiltersError::InvalidRange);
}
assert!(*range.end() <= self.filters.height());
// TODO: Only ask peers synced to a certain height.
// Choose a different peer for each requested range.
for (range, peer) in self
.rescan
.requests(range, tree)
.into_iter()
.zip(self.peers.cycle())
{
let stop_hash = tree
.get_block_by_height(*range.end())
.ok_or(GetFiltersError::InvalidRange)?
.block_hash();
let timeout = self.config.request_timeout;
self.upstream
.get_cfilters(*peer, *range.start(), stop_hash, timeout);
}
Ok(())
}
/// Handle a `cfheaders` message from a peer.
///
/// Returns the new filter header height, or an error.
pub fn received_cfheaders<T: BlockReader>(
&mut self,
from: &PeerId,
msg: CFHeaders,
tree: &T,
) -> Result<Height, Error> {
let from = *from;
let stop_hash = msg.stop_hash;
if self.inflight.remove(&stop_hash).is_none() {
return Err(Error::Ignored {
from,
msg: "cfheaders: unsolicited message",
});
}
if msg.filter_type != 0x0 {
return Err(Error::InvalidMessage {
from,
reason: "cfheaders: invalid filter type",
});
}
let prev_header = msg.previous_filter_header;
let (_, tip) = self.filters.tip();
// If the previous header doesn't match our tip, this could be a stale
// message arriving too late. Ignore it.
if tip != &prev_header {
return Ok(self.filters.height());
}
let start_height = self.filters.height();
let stop_height = if let Some((height, _)) = tree.get_block(&stop_hash) {
height
} else {
return Err(Error::InvalidMessage {
from,
reason: "cfheaders: unknown stop hash",
});
};
let hashes = msg.filter_hashes;
let count = hashes.len();
if start_height > stop_height {
return Err(Error::InvalidMessage {
from,
reason: "cfheaders: start height is greater than stop height",
});
}
if count > MAX_MESSAGE_CFHEADERS {
return Err(Error::InvalidMessage {
from,
reason: "cfheaders: header count exceeds maximum",
});
}
if count == 0 {
return Err(Error::InvalidMessage {
from,
reason: "cfheaders: empty header list",
});
}
if (stop_height - start_height) as usize != count {
return Err(Error::InvalidMessage {
from,
reason: "cfheaders: header count does not match height range",
});
}
// Ok, looks like everything's valid..
let mut last_header = prev_header;
let mut headers = Vec::with_capacity(count);
// Create headers out of the hashes.
for filter_hash in hashes {
last_header = filter_hash.filter_header(&last_header);
headers.push((filter_hash, last_header));
}
self.filters
.import_headers(headers)
.map(|height| {
self.upstream.event(Event::FilterHeadersImported {
count,
height,
block_hash: stop_hash,
});
self.headers_imported(start_height, height, tree).unwrap(); // TODO
assert!(height <= tree.height());
if height == tree.height() {
self.upstream.event(Event::Synced(height));
} else {
self.sync(tree);
}
height
})
.map_err(Error::from)
}
/// Handle a `getcfheaders` message from a peer.
pub fn received_getcfheaders<T: BlockReader>(
&mut self,
from: &PeerId,
msg: GetCFHeaders,
tree: &T,
) -> Result<(), Error> {
let from = *from;
if msg.filter_type != 0x0 {
return Err(Error::InvalidMessage {
from,
reason: "getcfheaders: invalid filter type",
});
}
let start_height = msg.start_height as Height;
let stop_height = if let Some((height, _)) = tree.get_block(&msg.stop_hash) {
height
} else {
// Can't handle this message, we don't have the stop block.
return Err(Error::Ignored {
msg: "getcfheaders",
from,
});
};
let headers = self.filters.get_headers(start_height..=stop_height);
if !headers.is_empty() {
let hashes = headers.iter().map(|(hash, _)| *hash);
let prev_header = self.filters.get_prev_header(start_height).expect(
"FilterManager::received_getcfheaders: all headers up to the tip must exist",
);
self.upstream.send_cfheaders(
from,
CFHeaders {
filter_type: msg.filter_type,
stop_hash: msg.stop_hash,
previous_filter_header: prev_header,
filter_hashes: hashes.collect(),
},
);
return Ok(());
}
// We must be syncing, since we have the block headers requested but
// not the associated filter headers. Simply ignore the request.
Err(Error::Ignored {
msg: "getcfheaders",
from,
})
}
/// Handle a `cfilter` message.
///
/// Returns a list of blocks that need to be fetched from the network.
pub fn received_cfilter<T: BlockReader>(
&mut self,
from: &PeerId,
msg: CFilter,
tree: &T,
) -> Result<Vec<(Height, BlockHash)>, Error> {
let from = *from;
if msg.filter_type != 0x0 {
return Err(Error::Ignored {
msg: "cfilter",
from,
});
}
let height = if let Some((height, _)) = tree.get_block(&msg.block_hash) {
height
} else {
// Can't handle this message, we don't have the block.
return Err(Error::Ignored {
msg: "cfilter",
from,
});
};
// The expected hash for this block filter.
let header = if let Some((_, header)) = self.filters.get_header(height) {
header
} else {
// Can't handle this message, we don't have the header.
return Err(Error::Ignored {
msg: "cfilter",
from,
});
};
// Note that in case this fails, we have a bug in our implementation, since filter
// headers are supposed to be downloaded in-order.
let prev_header = self
.filters
.get_prev_header(height)
.expect("FilterManager::received_cfilter: all headers up to the tip must exist");
let filter = BlockFilter::new(&msg.filter);
let block_hash = msg.block_hash;
if filter.filter_header(&prev_header) != header {
return Err(Error::InvalidMessage {
from,
reason: "cfilter: filter hash doesn't match header",
});
}
self.upstream.event(Event::FilterReceived {
from,
block_hash,
height,
filter: filter.clone(),
});
if self.rescan.received(height, filter, block_hash) {
let (matches, events, processed) = self.rescan.process();
for event in events {
self.upstream.event(event);
}
// If we processed some filters, update the time to further delay requesting new
// filters.
if processed > 0 {
self.last_processed = Some(self.clock.local_time());
}
return Ok(matches);
} else {
// Unsolicited filter.
}
Ok(Vec::default())
}
/// Called when a peer disconnected.
pub fn peer_disconnected(&mut self, id: &PeerId) {
self.peers.remove(id);
}
/// Called when a new peer was negotiated.
pub fn peer_negotiated<T: BlockReader>(
&mut self,
socket: Socket,
height: Height,
services: ServiceFlags,
link: Link,
tree: &T,
) {
if !link.is_outbound() {
return;
}
if !services.has(REQUIRED_SERVICES) {
return;
}
let time = self.clock.local_time();
self.peers.insert(
socket.addr,
Peer {
last_active: time,
height,
socket,
},
);
self.sync(tree);
}
/// Attempt to sync the filter header chain.
pub fn sync<T: BlockReader>(&mut self, tree: &T) {
let filter_height = self.filters.height();
let block_height = tree.height();
assert!(filter_height <= block_height);
// Don't start syncing filter headers until block headers are synced passed the last
// checkpoint. BIP 157 states that we should sync the full block header chain before
// syncing any filter headers, but this seems impractical. We choose a middle-ground.
if let Some(checkpoint) = tree.checkpoints().keys().next_back() {
if &block_height < checkpoint {
return;
}
}
if filter_height < block_height {
// We need to sync the filter header chain.
let start_height = self.filters.height() + 1;
let stop_height = tree.height();
if let Some((peer, start_height, stop_hash)) =
self.send_getcfheaders(start_height..=stop_height, tree)
{
self.upstream.event(Event::Syncing {
peer,
start_height,
stop_hash,
});
}
}
if self.rescan.active {
self.get_cfilters(self.rescan.current..=self.filters.height(), tree)
.ok();
}
}
// PRIVATE METHODS /////////////////////////////////////////////////////////
/// Called periodically. Triggers syncing if necessary.
fn idle<T: BlockReader>(&mut self, tree: &T) {
let now = self.clock.local_time();
if now - self.last_idle.unwrap_or_default() >= IDLE_TIMEOUT {
self.sync(tree);
self.last_idle = Some(now);
self.upstream.wakeup(IDLE_TIMEOUT);
}
}
/// Send a `getcfheaders` message to a random peer.
///
/// # Panics
///
/// Panics if the range is not within the bounds of the active chain.
///
fn send_getcfheaders<T: BlockReader>(
&mut self,
range: RangeInclusive<Height>,
tree: &T,
) -> Option<(PeerId, Height, BlockHash)> {
let (start, end) = (*range.start(), *range.end());
debug_assert!(start <= end);
debug_assert!(!range.is_empty());
if range.is_empty() {
return None;
}
// Cap requested header count.
let count = usize::min(MAX_MESSAGE_CFHEADERS, (end - start + 1) as usize);
let start_height = start;
let stop_hash = {
let stop_height = start + count as Height - 1;
let stop_block = tree
.get_block_by_height(stop_height)
.unwrap_or_else(|| panic!("{}: Stop height is out of bounds", source!()));
stop_block.block_hash()
};
if self.inflight.contains_key(&stop_hash) {
// Don't request the same thing twice.
return None;
}
// TODO: We should select peers that are caught up to the requested height.
if let Some((peer, _)) = self.peers.sample() {
let time = self.clock.local_time();
let timeout = self.config.request_timeout;
self.upstream
.get_cfheaders(*peer, start_height, stop_hash, timeout);
self.inflight
.insert(stop_hash, (start_height, *peer, time + timeout));
return Some((*peer, start_height, stop_hash));
} else {
// TODO: Emit 'NotConnected' instead, and make sure we retry later, or when a
// peer connects.
self.upstream.event(Event::RequestCanceled {
reason: "no peers with required services",
});
}
None
}
/// Called when filter headers were successfully imported.
///
/// The height is the new filter header chain height, and the hash is the
/// hash of the block corresponding to the last filter header.
///
/// When new headers are imported, we want to download the corresponding compact filters
/// to check them for matches.
fn headers_imported<T: BlockReader>(
&mut self,
start: Height,
stop: Height,
tree: &T,
) -> Result<(), GetFiltersError> {
if !self.rescan.active {
return Ok(());
}
let start = Height::max(start, self.rescan.current);
let stop = Height::min(stop, self.rescan.end.unwrap_or(stop));
let range = start..=stop; // If the range is empty, it means we are not caught up yet.
if !range.is_empty() {
self.get_cfilters(range, tree)?;
}
Ok(())
}
}
/// Iterator over height ranges.
struct HeightIterator {
start: Height,
stop: Height,
step: Height,
}
impl Iterator for HeightIterator {
type Item = RangeInclusive<Height>;
fn next(&mut self) -> Option<Self::Item> {
if self.start <= self.stop {
let start = self.start;
let stop = self.stop.min(start + self.step - 1);
self.start = stop + 1;
Some(start..=stop)
} else {
None
}
}
}
#[cfg(test)]
mod tests {
use std::iter;
use std::ops::RangeBounds;
use nakamoto_common::bitcoin;
use nakamoto_common::bitcoin_hashes;
use bitcoin::consensus::Params;
use bitcoin::network::message::NetworkMessage;
use bitcoin::network::message_filter::GetCFilters;
use bitcoin::BlockHeader;
use bitcoin_hashes::hex::FromHex;
use nakamoto_chain::store::Genesis;
use quickcheck::TestResult;
use quickcheck_macros::quickcheck;
use nakamoto_chain::block::{cache::BlockCache, store};
use nakamoto_chain::filter::cache::{FilterCache, StoredHeader};
use nakamoto_common::block::filter::{FilterHash, FilterHeader};
use nakamoto_common::block::time::RefClock;
use nakamoto_common::block::tree::BlockReader as _;
use nakamoto_common::block::tree::BlockTree;
use nakamoto_common::block::tree::ImportResult;
use nakamoto_common::network::Network;
use nakamoto_common::nonempty::NonEmpty;
use nakamoto_test::assert_matches;