-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathall.rs
More file actions
3152 lines (2914 loc) · 129 KB
/
all.rs
File metadata and controls
3152 lines (2914 loc) · 129 KB
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
// Substrate-lite
// Copyright (C) 2019-2022 Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//! All syncing strategies (optimistic, warp sync, all forks) grouped together.
//!
//! This state machine combines GrandPa warp syncing, optimistic syncing, and all forks syncing
//! into one state machine.
//!
//! # Overview
//!
//! This state machine acts as a container of sources, blocks (verified or not), and requests.
//! In order to initialize it, you need to pass, amongst other things, a
//! [`chain_information::ChainInformation`] struct indicating the known state of the finality of
//! the chain.
//!
//! A *request* represents a query for information from a source. Once the request has finished,
//! call one of the methods of the [`AllSync`] in order to notify the state machine of the outcome.
use crate::{
chain::{blocks_tree, chain_information},
executor::host,
header,
sync::{all_forks, optimistic, warp_sync},
trie::Nibble,
verify,
};
use alloc::{borrow::Cow, vec::Vec};
use core::{
cmp, iter, marker, mem,
num::{NonZeroU32, NonZeroU64},
ops,
time::Duration,
};
pub use crate::executor::vm::ExecHint;
pub use warp_sync::{
ConfigCodeTrieNodeHint, FragmentError as WarpSyncFragmentError, WarpSyncFragment,
};
/// Configuration for the [`AllSync`].
// TODO: review these fields
#[derive(Debug)]
pub struct Config {
/// Information about the latest finalized block and its ancestors.
pub chain_information: chain_information::ValidChainInformation,
/// Number of bytes used when encoding/decoding the block number. Influences how various data
/// structures should be parsed.
pub block_number_bytes: usize,
/// If `false`, blocks containing digest items with an unknown consensus engine will fail to
/// verify.
///
/// Note that blocks must always contain digest items that are relevant to the current
/// consensus algorithm. This option controls what happens when blocks contain additional
/// digest items that aren't recognized by the implementation.
///
/// Passing `true` can lead to blocks being considered as valid when they shouldn't, as these
/// additional digest items could have some logic attached to them that restricts which blocks
/// are valid and which are not.
///
/// However, since a recognized consensus engine must always be present, both `true` and
/// `false` guarantee that the number of authorable blocks over the network is bounded.
pub allow_unknown_consensus_engines: bool,
/// Pre-allocated capacity for the number of block sources.
pub sources_capacity: usize,
/// Pre-allocated capacity for the number of blocks between the finalized block and the head
/// of the chain.
///
/// Should be set to the maximum number of block between two consecutive justifications.
pub blocks_capacity: usize,
/// Maximum number of blocks of unknown ancestry to keep in memory.
///
/// See [`all_forks::Config::max_disjoint_headers`] for more information.
pub max_disjoint_headers: usize,
/// Maximum number of simultaneous pending requests made towards the same block.
///
/// See [`all_forks::Config::max_requests_per_block`] for more information.
pub max_requests_per_block: NonZeroU32,
/// Number of blocks to download ahead of the best verified block.
///
/// Whenever the latest best block is updated, the state machine will start block
/// requests for the block `best_block_height + download_ahead_blocks` and all its
/// ancestors. Considering that requesting blocks has some latency, downloading blocks ahead
/// of time ensures that verification isn't blocked waiting for a request to be finished.
///
/// The ideal value here depends on the speed of blocks verification speed and latency of
/// block requests.
pub download_ahead_blocks: NonZeroU32,
/// If `true`, the block bodies and storage are also synchronized and the block bodies are
/// verified.
// TODO: change this now that we don't verify block bodies here
pub full_mode: bool,
/// Known valid Merkle value and storage value combination for the `:code` key.
///
/// If provided, the warp syncing algorithm will first fetch the Merkle value of `:code`, and
/// if it matches the Merkle value provided in the hint, use the storage value in the hint
/// instead of downloading it. If the hint doesn't match, an extra round-trip will be needed,
/// but if the hint matches it saves a big download.
// TODO: provide only in non-full mode?
pub code_trie_node_hint: Option<ConfigCodeTrieNodeHint>,
}
/// Identifier for a source in the [`AllSync`].
//
// Implementation note: this is an index in `AllSync::sources`.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct SourceId(usize);
/// Identifier for a request in the [`AllSync`].
//
// Implementation note: this is an index in `AllSync::requests`.
#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub struct RequestId(usize);
/// Status of the synchronization.
#[derive(Debug)]
pub enum Status<'a, TSrc> {
/// Regular syncing mode.
Sync,
/// Warp syncing algorithm is downloading Grandpa warp sync fragments containing a finality
/// proof.
WarpSyncFragments {
/// Source from which the fragments are currently being downloaded, if any.
source: Option<(SourceId, &'a TSrc)>,
/// Hash of the highest block that is proven to be finalized.
///
/// This isn't necessarily the same block as returned by
/// [`AllSync::as_chain_information`], as this function first has to download extra
/// information compared to just the finalized block.
finalized_block_hash: [u8; 32],
/// Height of the block indicated by [`Status::WarpSyncFragments::finalized_block_hash`].
finalized_block_number: u64,
},
/// Warp syncing algorithm has reached the head of the finalized chain and is downloading and
/// building the chain information.
WarpSyncChainInformation {
/// Source from which the chain information is being downloaded.
source: (SourceId, &'a TSrc),
/// Hash of the highest block that is proven to be finalized.
///
/// This isn't necessarily the same block as returned by
/// [`AllSync::as_chain_information`], as this function first has to download extra
/// information compared to just the finalized block.
finalized_block_hash: [u8; 32],
/// Height of the block indicated by
/// [`Status::WarpSyncChainInformation::finalized_block_hash`].
finalized_block_number: u64,
},
}
pub struct AllSync<TRq, TSrc, TBl> {
inner: AllSyncInner<TRq, TSrc, TBl>,
shared: Shared<TRq>,
}
impl<TRq, TSrc, TBl> AllSync<TRq, TSrc, TBl> {
/// Initializes a new state machine.
pub fn new(config: Config) -> Self {
AllSync {
inner: if config.full_mode {
AllSyncInner::Optimistic {
inner: optimistic::OptimisticSync::new(optimistic::Config {
chain_information: config.chain_information,
block_number_bytes: config.block_number_bytes,
sources_capacity: config.sources_capacity,
blocks_capacity: config.blocks_capacity,
download_ahead_blocks: config.download_ahead_blocks,
download_bodies: config.full_mode,
}),
}
} else {
match warp_sync::start_warp_sync(warp_sync::Config {
start_chain_information: config.chain_information,
block_number_bytes: config.block_number_bytes,
sources_capacity: config.sources_capacity,
requests_capacity: config.sources_capacity, // TODO: ?! add as config?
code_trie_node_hint: config.code_trie_node_hint,
}) {
Ok(inner) => AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::InProgress(inner),
},
Err((
chain_information,
warp_sync::WarpSyncInitError::NotGrandpa
| warp_sync::WarpSyncInitError::UnknownConsensus,
)) => {
// On error, `warp_sync` returns back the chain information that was
// provided in its configuration.
AllSyncInner::Optimistic {
inner: optimistic::OptimisticSync::new(optimistic::Config {
chain_information,
block_number_bytes: config.block_number_bytes,
sources_capacity: config.sources_capacity,
blocks_capacity: config.blocks_capacity,
download_ahead_blocks: config.download_ahead_blocks,
download_bodies: false,
}),
}
}
}
},
shared: Shared {
sources: slab::Slab::with_capacity(config.sources_capacity),
requests: slab::Slab::with_capacity(config.sources_capacity),
full_mode: config.full_mode,
sources_capacity: config.sources_capacity,
blocks_capacity: config.blocks_capacity,
max_disjoint_headers: config.max_disjoint_headers,
max_requests_per_block: config.max_requests_per_block,
block_number_bytes: config.block_number_bytes,
allow_unknown_consensus_engines: config.allow_unknown_consensus_engines,
},
}
}
/// Returns the value that was initially passed in [`Config::block_number_bytes`].
pub fn block_number_bytes(&self) -> usize {
self.shared.block_number_bytes
}
/// Builds a [`chain_information::ChainInformationRef`] struct corresponding to the current
/// latest finalized block. Can later be used to reconstruct a chain.
pub fn as_chain_information(&self) -> chain_information::ValidChainInformationRef {
match &self.inner {
AllSyncInner::AllForks(sync) => sync.as_chain_information(),
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::InProgress(sync),
} => sync.as_chain_information(),
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::Finished(sync),
} => (&sync.chain_information).into(),
AllSyncInner::Optimistic { inner } => inner.as_chain_information(),
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns the current status of the syncing.
pub fn status(&self) -> Status<TSrc> {
match &self.inner {
AllSyncInner::AllForks(_) => Status::Sync,
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::InProgress(sync),
} => match sync.status() {
warp_sync::Status::Fragments {
source: None,
finalized_block_hash,
finalized_block_number,
} => Status::WarpSyncFragments {
source: None,
finalized_block_hash,
finalized_block_number,
},
warp_sync::Status::Fragments {
source: Some((_, user_data)),
finalized_block_hash,
finalized_block_number,
} => Status::WarpSyncFragments {
source: Some((user_data.outer_source_id, &user_data.user_data)),
finalized_block_hash,
finalized_block_number,
},
warp_sync::Status::ChainInformation {
source: (_, user_data),
finalized_block_hash,
finalized_block_number,
} => Status::WarpSyncChainInformation {
source: (user_data.outer_source_id, &user_data.user_data),
finalized_block_hash,
finalized_block_number,
},
},
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::Finished(_),
} => Status::Sync,
AllSyncInner::Optimistic { .. } => Status::Sync, // TODO: right now we don't differentiate between AllForks and Optimistic, as they're kind of similar anyway
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns the header of the finalized block.
pub fn finalized_block_header(&self) -> header::HeaderRef {
match &self.inner {
AllSyncInner::AllForks(sync) => sync.finalized_block_header(),
AllSyncInner::Optimistic { inner } => inner.finalized_block_header(),
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::InProgress(sync),
} => sync.as_chain_information().as_ref().finalized_block_header,
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::Finished(sync),
} => sync.chain_information.as_ref().finalized_block_header,
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns the header of the best block.
///
/// > **Note**: This value is provided only for informative purposes. Keep in mind that this
/// > best block might be reverted in the future.
pub fn best_block_header(&self) -> header::HeaderRef {
match &self.inner {
AllSyncInner::AllForks(sync) => sync.best_block_header(),
AllSyncInner::Optimistic { inner } => inner.best_block_header(),
AllSyncInner::GrandpaWarpSync { .. } => self.finalized_block_header(),
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns the number of the best block.
///
/// > **Note**: This value is provided only for informative purposes. Keep in mind that this
/// > best block might be reverted in the future.
pub fn best_block_number(&self) -> u64 {
match &self.inner {
AllSyncInner::AllForks(sync) => sync.best_block_number(),
AllSyncInner::Optimistic { inner } => inner.best_block_number(),
AllSyncInner::GrandpaWarpSync { .. } => self.best_block_header().number,
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns the hash of the best block.
///
/// > **Note**: This value is provided only for informative purposes. Keep in mind that this
/// > best block might be reverted in the future.
pub fn best_block_hash(&self) -> [u8; 32] {
match &self.inner {
AllSyncInner::AllForks(sync) => sync.best_block_hash(),
AllSyncInner::Optimistic { inner } => inner.best_block_hash(),
AllSyncInner::GrandpaWarpSync { .. } => self
.best_block_header()
.hash(self.shared.block_number_bytes),
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns consensus information about the current best block of the chain.
pub fn best_block_consensus(&self) -> chain_information::ChainInformationConsensusRef {
match &self.inner {
AllSyncInner::AllForks(_) => todo!(), // TODO:
AllSyncInner::Optimistic { inner } => inner.best_block_consensus(),
AllSyncInner::GrandpaWarpSync { .. } => todo!(), // TODO: ?!
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns the header of all known non-finalized blocks in the chain without any specific
/// order.
pub fn non_finalized_blocks_unordered(&self) -> impl Iterator<Item = header::HeaderRef> {
match &self.inner {
AllSyncInner::AllForks(sync) => {
let iter = sync.non_finalized_blocks_unordered();
either::Left(iter)
}
AllSyncInner::Optimistic { inner } => {
let iter = inner.non_finalized_blocks_unordered();
either::Right(either::Left(iter))
}
AllSyncInner::GrandpaWarpSync { .. } => either::Right(either::Right(iter::empty())),
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns the header of all known non-finalized blocks in the chain.
///
/// The returned items are guaranteed to be in an order in which the parents are found before
/// their children.
pub fn non_finalized_blocks_ancestry_order(&self) -> impl Iterator<Item = header::HeaderRef> {
match &self.inner {
AllSyncInner::AllForks(sync) => {
let iter = sync.non_finalized_blocks_ancestry_order();
either::Left(iter)
}
AllSyncInner::Optimistic { inner } => {
let iter = inner.non_finalized_blocks_ancestry_order();
either::Right(either::Left(iter))
}
AllSyncInner::GrandpaWarpSync { .. } => either::Right(either::Right(iter::empty())),
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns true if it is believed that we are near the head of the chain.
///
/// The way this method is implemented is opaque and cannot be relied on. The return value
/// should only ever be shown to the user and not used for any meaningful logic.
pub fn is_near_head_of_chain_heuristic(&self) -> bool {
match &self.inner {
AllSyncInner::AllForks(_) => true,
AllSyncInner::Optimistic { .. } => false,
AllSyncInner::GrandpaWarpSync { .. } => false,
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Adds a new source to the sync state machine.
///
/// Must be passed the best block number and hash of the source, as usually reported by the
/// source itself.
///
/// Returns an identifier for this new source, plus a list of requests to start or cancel.
pub fn add_source(
&mut self,
user_data: TSrc,
best_block_number: u64,
best_block_hash: [u8; 32],
) -> SourceId {
// `inner` is temporarily replaced with `Poisoned`. A new value must be put back before
// returning.
match mem::replace(&mut self.inner, AllSyncInner::Poisoned) {
AllSyncInner::GrandpaWarpSync { mut inner } => {
let outer_source_id_entry = self.shared.sources.vacant_entry();
let outer_source_id = SourceId(outer_source_id_entry.key());
let source_extra = GrandpaWarpSyncSourceExtra {
outer_source_id,
user_data,
best_block_number,
best_block_hash,
finalized_block_height: None,
};
let inner_source_id = match &mut inner {
warp_sync::WarpSync::InProgress(sync) => sync.add_source(source_extra),
warp_sync::WarpSync::Finished(sync) => {
let new_id = sync.sources_ordered.last().map_or(
warp_sync::SourceId::min_value(),
|(id, _)| {
id.checked_add(1).unwrap_or_else(|| panic!()) // TODO: don't panic?
},
);
sync.sources_ordered.push((new_id, source_extra));
new_id
}
};
outer_source_id_entry.insert(SourceMapping::GrandpaWarpSync(inner_source_id));
self.inner = AllSyncInner::GrandpaWarpSync { inner };
outer_source_id
}
AllSyncInner::AllForks(mut all_forks) => {
let outer_source_id_entry = self.shared.sources.vacant_entry();
let outer_source_id = SourceId(outer_source_id_entry.key());
let source_user_data = AllForksSourceExtra {
user_data,
outer_source_id,
};
let source_id =
match all_forks.prepare_add_source(best_block_number, best_block_hash) {
all_forks::AddSource::BestBlockAlreadyVerified(b)
| all_forks::AddSource::BestBlockPendingVerification(b) => {
b.add_source(source_user_data)
}
all_forks::AddSource::OldBestBlock(b) => b.add_source(source_user_data),
all_forks::AddSource::UnknownBestBlock(b) => {
b.add_source_and_insert_block(source_user_data, None)
}
};
outer_source_id_entry.insert(SourceMapping::AllForks(source_id));
self.inner = AllSyncInner::AllForks(all_forks);
outer_source_id
}
AllSyncInner::Optimistic { mut inner } => {
let outer_source_id_entry = self.shared.sources.vacant_entry();
let outer_source_id = SourceId(outer_source_id_entry.key());
let source_id = inner.add_source(
OptimisticSourceExtra {
user_data,
outer_source_id,
best_block_hash,
},
best_block_number,
);
outer_source_id_entry.insert(SourceMapping::Optimistic(source_id));
self.inner = AllSyncInner::Optimistic { inner };
outer_source_id
}
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Removes a source from the state machine. Returns the user data of this source, and all
/// the requests that this source were expected to perform.
///
/// # Panic
///
/// Panics if the [`SourceId`] doesn't correspond to a valid source.
///
pub fn remove_source(
&mut self,
source_id: SourceId,
) -> (TSrc, impl Iterator<Item = (RequestId, TRq)>) {
debug_assert!(self.shared.sources.contains(source_id.0));
match (&mut self.inner, self.shared.sources.remove(source_id.0)) {
(AllSyncInner::AllForks(sync), SourceMapping::AllForks(source_id)) => {
let (user_data, requests) = sync.remove_source(source_id);
let requests = requests
.map(
|(_inner_request_id, _request_params, request_inner_user_data)| {
debug_assert!(self
.shared
.requests
.contains(request_inner_user_data.outer_request_id.0));
let _removed = self
.shared
.requests
.remove(request_inner_user_data.outer_request_id.0);
debug_assert!(matches!(
_removed,
RequestMapping::AllForks(_inner_request_id)
));
(
request_inner_user_data.outer_request_id,
request_inner_user_data.user_data.unwrap(),
)
},
)
.collect::<Vec<_>>()
.into_iter();
// TODO: also handle the "inline" requests
(user_data.user_data, requests)
}
(AllSyncInner::Optimistic { inner }, SourceMapping::Optimistic(source_id)) => {
let (user_data, requests) = inner.remove_source(source_id);
// TODO: do properly
let self_requests = &mut self.shared.requests;
let requests = requests
.map(move |(_inner_request_id, request_inner_user_data)| {
debug_assert!(
self_requests.contains(request_inner_user_data.outer_request_id.0)
);
let _removed =
self_requests.remove(request_inner_user_data.outer_request_id.0);
debug_assert!(matches!(
_removed,
RequestMapping::Optimistic(_inner_request_id)
));
(
request_inner_user_data.outer_request_id,
request_inner_user_data.user_data,
)
})
.collect::<Vec<_>>()
.into_iter();
// TODO: also handle the "inline" requests
(user_data.user_data, requests)
}
(
AllSyncInner::GrandpaWarpSync { inner },
SourceMapping::GrandpaWarpSync(source_id),
) => {
let (user_data, requests) = match inner {
warp_sync::WarpSync::InProgress(inner) => {
let (ud, requests) = inner.remove_source(source_id);
(ud, either::Left(requests))
}
warp_sync::WarpSync::Finished(inner) => {
let index = inner
.sources_ordered
.binary_search_by_key(&source_id, |(id, _)| *id)
.unwrap_or_else(|_| panic!());
let (_, user_data) = inner.sources_ordered.remove(index);
let (requests_of_source, requests_back) =
mem::take(&mut inner.in_progress_requests)
.into_iter()
.partition(|(s, ..)| *s == source_id);
inner.in_progress_requests = requests_back;
let requests_of_source = requests_of_source
.into_iter()
.map(|(_, rq_id, ud, _)| (rq_id, ud));
(user_data, either::Right(requests_of_source))
}
};
let requests = requests
.map(|(_inner_request_id, request_inner_user_data)| {
debug_assert!(self
.shared
.requests
.contains(request_inner_user_data.outer_request_id.0));
let _removed = self
.shared
.requests
.remove(request_inner_user_data.outer_request_id.0);
debug_assert!(matches!(
_removed,
RequestMapping::WarpSync(_inner_request_id)
));
(
request_inner_user_data.outer_request_id,
request_inner_user_data.user_data,
)
})
.collect::<Vec<_>>()
.into_iter();
// TODO: also handle the "inline" requests
(user_data.user_data, requests)
}
(AllSyncInner::Poisoned, _) => unreachable!(),
// Invalid combinations of syncing state machine and source id.
// This indicates a internal bug during the switch from one state machine to the
// other.
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::AllForks(_)) => unreachable!(),
(AllSyncInner::AllForks(_), SourceMapping::GrandpaWarpSync(_)) => unreachable!(),
(AllSyncInner::Optimistic { .. }, SourceMapping::AllForks(_)) => unreachable!(),
(AllSyncInner::AllForks(_), SourceMapping::Optimistic(_)) => unreachable!(),
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::Optimistic(_)) => unreachable!(),
(AllSyncInner::Optimistic { .. }, SourceMapping::GrandpaWarpSync(_)) => unreachable!(),
}
}
/// Returns the list of sources in this state machine.
pub fn sources(&'_ self) -> impl Iterator<Item = SourceId> + '_ {
match &self.inner {
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::InProgress(sync),
} => {
let iter = sync.sources().map(move |id| sync[id].outer_source_id);
either::Left(either::Left(iter))
}
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::Finished(sync),
} => {
let iter = sync
.sources_ordered
.iter()
.map(move |(_, ud)| ud.outer_source_id);
either::Left(either::Right(iter))
}
AllSyncInner::Optimistic { inner: sync } => {
let iter = sync.sources().map(move |id| sync[id].outer_source_id);
either::Right(either::Left(iter))
}
AllSyncInner::AllForks(sync) => {
let iter = sync.sources().map(move |id| sync[id].outer_source_id);
either::Right(either::Right(iter))
}
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Returns the number of ongoing requests that concern this source.
///
/// # Panic
///
/// Panics if the [`SourceId`] is invalid.
///
// TODO: this function is questionable, because in practice we send requests to sources that are outside the scope of syncing
pub fn source_num_ongoing_requests(&self, source_id: SourceId) -> usize {
debug_assert!(self.shared.sources.contains(source_id.0));
// TODO: O(n) :-/
let num_inline = self
.shared
.requests
.iter()
.filter(|(_, rq)| matches!(rq, RequestMapping::Inline(id, _, _) if *id == source_id))
.count();
let num_inner = match (&self.inner, self.shared.sources.get(source_id.0).unwrap()) {
(AllSyncInner::AllForks(sync), SourceMapping::AllForks(src)) => {
sync.source_num_ongoing_requests(*src)
}
(AllSyncInner::Optimistic { inner }, SourceMapping::Optimistic(src)) => {
inner.source_num_ongoing_requests(*src)
}
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::GrandpaWarpSync(_)) => 0,
(AllSyncInner::Poisoned, _) => unreachable!(),
// Invalid combinations of syncing state machine and source id.
// This indicates a internal bug during the switch from one state machine to the
// other.
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::AllForks(_)) => unreachable!(),
(AllSyncInner::AllForks(_), SourceMapping::GrandpaWarpSync(_)) => unreachable!(),
(AllSyncInner::Optimistic { .. }, SourceMapping::AllForks(_)) => unreachable!(),
(AllSyncInner::AllForks(_), SourceMapping::Optimistic(_)) => unreachable!(),
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::Optimistic(_)) => unreachable!(),
(AllSyncInner::Optimistic { .. }, SourceMapping::GrandpaWarpSync(_)) => unreachable!(),
};
num_inline + num_inner
}
/// Returns the current best block of the given source.
///
/// This corresponds either the latest call to [`AllSync::block_announce`] where `is_best` was
/// `true`, or to the parameter passed to [`AllSync::add_source`].
///
/// # Panic
///
/// Panics if the [`SourceId`] is invalid.
///
pub fn source_best_block(&self, source_id: SourceId) -> (u64, &[u8; 32]) {
debug_assert!(self.shared.sources.contains(source_id.0));
match (&self.inner, self.shared.sources.get(source_id.0).unwrap()) {
(AllSyncInner::AllForks(sync), SourceMapping::AllForks(src)) => {
sync.source_best_block(*src)
}
(AllSyncInner::Optimistic { inner }, SourceMapping::Optimistic(src)) => {
let height = inner.source_best_block(*src);
let hash = &inner[*src].best_block_hash;
(height, hash)
}
(
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::InProgress(sync),
},
SourceMapping::GrandpaWarpSync(src),
) => {
let ud = &sync[*src];
(ud.best_block_number, &ud.best_block_hash)
}
(
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::Finished(sync),
},
SourceMapping::GrandpaWarpSync(src),
) => {
let index = sync
.sources_ordered
.binary_search_by_key(src, |(id, _)| *id)
.unwrap_or_else(|_| panic!());
let user_data = &sync.sources_ordered[index].1;
(user_data.best_block_number, &user_data.best_block_hash)
}
(AllSyncInner::Poisoned, _) => unreachable!(),
// Invalid combinations of syncing state machine and source id.
// This indicates a internal bug during the switch from one state machine to the
// other.
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::AllForks(_)) => unreachable!(),
(AllSyncInner::AllForks(_), SourceMapping::GrandpaWarpSync(_)) => unreachable!(),
(AllSyncInner::Optimistic { .. }, SourceMapping::AllForks(_)) => unreachable!(),
(AllSyncInner::AllForks(_), SourceMapping::Optimistic(_)) => unreachable!(),
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::Optimistic(_)) => unreachable!(),
(AllSyncInner::Optimistic { .. }, SourceMapping::GrandpaWarpSync(_)) => unreachable!(),
}
}
/// Returns true if the source has earlier announced the block passed as parameter or one of
/// its descendants.
///
/// # Panic
///
/// Panics if the [`SourceId`] is out of range.
///
/// Panics if `height` is inferior or equal to the finalized block height. Finalized blocks
/// are intentionally not tracked by this data structure, and panicking when asking for a
/// potentially-finalized block prevents potentially confusing or erroneous situations.
///
pub fn source_knows_non_finalized_block(
&self,
source_id: SourceId,
height: u64,
hash: &[u8; 32],
) -> bool {
debug_assert!(self.shared.sources.contains(source_id.0));
match (&self.inner, self.shared.sources.get(source_id.0).unwrap()) {
(AllSyncInner::AllForks(sync), SourceMapping::AllForks(src)) => {
sync.source_knows_non_finalized_block(*src, height, hash)
}
(AllSyncInner::Optimistic { inner }, SourceMapping::Optimistic(src)) => {
// TODO: is this correct?
inner.source_best_block(*src) >= height
}
(
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::InProgress(sync),
},
SourceMapping::GrandpaWarpSync(src),
) => {
assert!(
height
> sync
.as_chain_information()
.as_ref()
.finalized_block_header
.number
);
let user_data = &sync[*src];
user_data.best_block_hash == *hash && user_data.best_block_number == height
}
(
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::Finished(sync),
},
SourceMapping::GrandpaWarpSync(src),
) => {
assert!(
height
> sync
.chain_information
.as_ref()
.finalized_block_header
.number
);
let index = sync
.sources_ordered
.binary_search_by_key(src, |(id, _)| *id)
.unwrap_or_else(|_| panic!());
let user_data = &sync.sources_ordered[index].1;
user_data.best_block_hash == *hash && user_data.best_block_number == height
}
(AllSyncInner::Poisoned, _) => unreachable!(),
// Invalid combinations of syncing state machine and source id.
// This indicates a internal bug during the switch from one state machine to the
// other.
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::AllForks(_)) => unreachable!(),
(AllSyncInner::AllForks(_), SourceMapping::GrandpaWarpSync(_)) => unreachable!(),
(AllSyncInner::Optimistic { .. }, SourceMapping::AllForks(_)) => unreachable!(),
(AllSyncInner::AllForks(_), SourceMapping::Optimistic(_)) => unreachable!(),
(AllSyncInner::GrandpaWarpSync { .. }, SourceMapping::Optimistic(_)) => unreachable!(),
(AllSyncInner::Optimistic { .. }, SourceMapping::GrandpaWarpSync(_)) => unreachable!(),
}
}
/// Returns the list of sources for which [`AllSync::source_knows_non_finalized_block`] would
/// return `true`.
///
/// # Panic
///
/// Panics if `height` is inferior or equal to the finalized block height. Finalized blocks
/// are intentionally not tracked by this data structure, and panicking when asking for a
/// potentially-finalized block prevents potentially confusing or erroneous situations.
///
pub fn knows_non_finalized_block(
&'_ self,
height: u64,
hash: &[u8; 32],
) -> impl Iterator<Item = SourceId> + '_ {
match &self.inner {
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::InProgress(sync),
} => {
assert!(
height
> sync
.as_chain_information()
.as_ref()
.finalized_block_header
.number
);
let hash = *hash;
let iter = sync
.sources()
.filter(move |source_id| {
let user_data = &sync[*source_id];
user_data.best_block_hash == hash && user_data.best_block_number == height
})
.map(move |id| sync[id].outer_source_id);
either::Right(either::Left(iter))
}
AllSyncInner::GrandpaWarpSync {
inner: warp_sync::WarpSync::Finished(sync),
} => {
assert!(
height
> sync
.chain_information
.as_ref()
.finalized_block_header
.number
);
let hash = *hash;
let iter = sync
.sources_ordered
.iter()
.filter(move |(_, user_data)| {
user_data.best_block_hash == hash && user_data.best_block_number == height
})
.map(move |(_, ud)| ud.outer_source_id);
either::Right(either::Right(iter))
}
AllSyncInner::AllForks(sync) => {
let iter = sync
.knows_non_finalized_block(height, hash)
.map(move |id| sync[id].outer_source_id);
either::Left(either::Left(iter))
}
AllSyncInner::Optimistic { inner } => {
// TODO: is this correct?
let iter = inner
.sources()
.filter(move |source_id| inner.source_best_block(*source_id) >= height)
.map(move |source_id| inner[source_id].outer_source_id);
either::Left(either::Right(iter))
}
AllSyncInner::Poisoned => unreachable!(),
}
}
/// Try register a new block that the source is aware of.
///
/// Some syncing strategies do not track blocks known to sources, in which case this function
/// has no effect
///
/// Has no effect if `height` is inferior or equal to the finalized block height, or if the
/// source was already known to know this block.
///
/// The block does not need to be known by the data structure.
///
/// This is automatically done for the blocks added through block announces or block requests..
///
/// # Panic
///
/// Panics if the [`SourceId`] is out of range.
///
pub fn try_add_known_block_to_source(
&mut self,
source_id: SourceId,
height: u64,
hash: [u8; 32],
) {
debug_assert!(self.shared.sources.contains(source_id.0));
if let (AllSyncInner::AllForks(sync), SourceMapping::AllForks(src)) = (
&mut self.inner,
self.shared.sources.get(source_id.0).unwrap(),
) {
sync.add_known_block_to_source(*src, height, hash)
}
}
/// Returns the details of a request to start towards a source.
///
/// This method doesn't modify the state machine in any way. [`AllSync::add_request`] must be
/// called in order for the request to actually be marked as started.
pub fn desired_requests(
&'_ self,
) -> impl Iterator<Item = (SourceId, &'_ TSrc, DesiredRequest)> + '_ {
match &self.inner {
AllSyncInner::AllForks(sync) => {
let iter = sync.desired_requests().map(
move |(inner_source_id, src_user_data, rq_params)| {
(
sync[inner_source_id].outer_source_id,
&src_user_data.user_data,
all_forks_request_convert(rq_params, self.shared.full_mode),
)
},
);
either::Left(either::Right(iter))
}
AllSyncInner::Optimistic { inner } => {
let iter = inner.desired_requests().map(move |rq_detail| {
(
inner[rq_detail.source_id].outer_source_id,
&inner[rq_detail.source_id].user_data,
optimistic_request_convert(rq_detail, self.shared.full_mode),
)
});
either::Right(either::Left(iter))
}
AllSyncInner::GrandpaWarpSync {