This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
lib.rs
1305 lines (1116 loc) · 35.4 KB
/
lib.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
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Polkadot.
// Polkadot 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.
// Polkadot 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 Polkadot. If not, see <http://www.gnu.org/licenses/>.
//! Implements a `AvailabilityStoreSubsystem`.
#![recursion_limit = "256"]
#![warn(missing_docs)]
use std::{
collections::{BTreeSet, HashMap, HashSet},
io,
sync::Arc,
time::{Duration, SystemTime, SystemTimeError, UNIX_EPOCH},
};
use futures::{channel::oneshot, future, select, FutureExt};
use futures_timer::Delay;
use parity_scale_codec::{Decode, Encode, Error as CodecError, Input};
use polkadot_node_subsystem_util::database::{DBTransaction, Database};
use sp_consensus::SyncOracle;
use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec};
use polkadot_node_primitives::{AvailableData, ErasureChunk};
use polkadot_node_subsystem::{
errors::{ChainApiError, RuntimeApiError},
messages::{AvailabilityStoreMessage, ChainApiMessage},
overseer, ActiveLeavesUpdate, FromOrchestra, OverseerSignal, SpawnedSubsystem, SubsystemError,
};
use polkadot_node_subsystem_util as util;
use polkadot_primitives::{
BlockNumber, CandidateEvent, CandidateHash, CandidateReceipt, Hash, Header, ValidatorIndex,
};
mod metrics;
pub use self::metrics::*;
#[cfg(test)]
mod tests;
const LOG_TARGET: &str = "parachain::availability-store";
/// The following constants are used under normal conditions:
const AVAILABLE_PREFIX: &[u8; 9] = b"available";
const CHUNK_PREFIX: &[u8; 5] = b"chunk";
const META_PREFIX: &[u8; 4] = b"meta";
const UNFINALIZED_PREFIX: &[u8; 11] = b"unfinalized";
const PRUNE_BY_TIME_PREFIX: &[u8; 13] = b"prune_by_time";
// We have some keys we want to map to empty values because existence of the key is enough. We use this because
// rocksdb doesn't support empty values.
const TOMBSTONE_VALUE: &[u8] = b" ";
/// Unavailable blocks are kept for 1 hour.
const KEEP_UNAVAILABLE_FOR: Duration = Duration::from_secs(60 * 60);
/// Finalized data is kept for 25 hours.
const KEEP_FINALIZED_FOR: Duration = Duration::from_secs(25 * 60 * 60);
/// The pruning interval.
const PRUNING_INTERVAL: Duration = Duration::from_secs(60 * 5);
/// Unix time wrapper with big-endian encoding.
#[derive(Debug, Clone, Copy, PartialEq, PartialOrd, Eq, Ord)]
struct BETimestamp(u64);
impl Encode for BETimestamp {
fn size_hint(&self) -> usize {
std::mem::size_of::<u64>()
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&self.0.to_be_bytes())
}
}
impl Decode for BETimestamp {
fn decode<I: Input>(value: &mut I) -> Result<Self, CodecError> {
<[u8; 8]>::decode(value).map(u64::from_be_bytes).map(Self)
}
}
impl From<Duration> for BETimestamp {
fn from(d: Duration) -> Self {
BETimestamp(d.as_secs())
}
}
impl Into<Duration> for BETimestamp {
fn into(self) -> Duration {
Duration::from_secs(self.0)
}
}
/// [`BlockNumber`] wrapper with big-endian encoding.
#[derive(Debug, Clone, PartialEq, PartialOrd, Eq, Ord)]
struct BEBlockNumber(BlockNumber);
impl Encode for BEBlockNumber {
fn size_hint(&self) -> usize {
std::mem::size_of::<BlockNumber>()
}
fn using_encoded<R, F: FnOnce(&[u8]) -> R>(&self, f: F) -> R {
f(&self.0.to_be_bytes())
}
}
impl Decode for BEBlockNumber {
fn decode<I: Input>(value: &mut I) -> Result<Self, CodecError> {
<[u8; std::mem::size_of::<BlockNumber>()]>::decode(value)
.map(BlockNumber::from_be_bytes)
.map(Self)
}
}
#[derive(Debug, Encode, Decode)]
enum State {
/// Candidate data was first observed at the given time but is not available in any block.
#[codec(index = 0)]
Unavailable(BETimestamp),
/// The candidate was first observed at the given time and was included in the given list of unfinalized blocks, which may be
/// empty. The timestamp here is not used for pruning. Either one of these blocks will be finalized or the state will regress to
/// `State::Unavailable`, in which case the same timestamp will be reused. Blocks are sorted ascending first by block number and
/// then hash.
#[codec(index = 1)]
Unfinalized(BETimestamp, Vec<(BEBlockNumber, Hash)>),
/// Candidate data has appeared in a finalized block and did so at the given time.
#[codec(index = 2)]
Finalized(BETimestamp),
}
// Meta information about a candidate.
#[derive(Debug, Encode, Decode)]
struct CandidateMeta {
state: State,
data_available: bool,
chunks_stored: BitVec<u8, BitOrderLsb0>,
}
fn query_inner<D: Decode>(
db: &Arc<dyn Database>,
column: u32,
key: &[u8],
) -> Result<Option<D>, Error> {
match db.get(column, key) {
Ok(Some(raw)) => {
let res = D::decode(&mut &raw[..])?;
Ok(Some(res))
},
Ok(None) => Ok(None),
Err(err) => {
gum::warn!(target: LOG_TARGET, ?err, "Error reading from the availability store");
Err(err.into())
},
}
}
fn write_available_data(
tx: &mut DBTransaction,
config: &Config,
hash: &CandidateHash,
available_data: &AvailableData,
) {
let key = (AVAILABLE_PREFIX, hash).encode();
tx.put_vec(config.col_data, &key[..], available_data.encode());
}
fn load_available_data(
db: &Arc<dyn Database>,
config: &Config,
hash: &CandidateHash,
) -> Result<Option<AvailableData>, Error> {
let key = (AVAILABLE_PREFIX, hash).encode();
query_inner(db, config.col_data, &key)
}
fn delete_available_data(tx: &mut DBTransaction, config: &Config, hash: &CandidateHash) {
let key = (AVAILABLE_PREFIX, hash).encode();
tx.delete(config.col_data, &key[..])
}
fn load_chunk(
db: &Arc<dyn Database>,
config: &Config,
candidate_hash: &CandidateHash,
chunk_index: ValidatorIndex,
) -> Result<Option<ErasureChunk>, Error> {
let key = (CHUNK_PREFIX, candidate_hash, chunk_index).encode();
query_inner(db, config.col_data, &key)
}
fn write_chunk(
tx: &mut DBTransaction,
config: &Config,
candidate_hash: &CandidateHash,
chunk_index: ValidatorIndex,
erasure_chunk: &ErasureChunk,
) {
let key = (CHUNK_PREFIX, candidate_hash, chunk_index).encode();
tx.put_vec(config.col_data, &key, erasure_chunk.encode());
}
fn delete_chunk(
tx: &mut DBTransaction,
config: &Config,
candidate_hash: &CandidateHash,
chunk_index: ValidatorIndex,
) {
let key = (CHUNK_PREFIX, candidate_hash, chunk_index).encode();
tx.delete(config.col_data, &key[..]);
}
fn load_meta(
db: &Arc<dyn Database>,
config: &Config,
hash: &CandidateHash,
) -> Result<Option<CandidateMeta>, Error> {
let key = (META_PREFIX, hash).encode();
query_inner(db, config.col_meta, &key)
}
fn write_meta(tx: &mut DBTransaction, config: &Config, hash: &CandidateHash, meta: &CandidateMeta) {
let key = (META_PREFIX, hash).encode();
tx.put_vec(config.col_meta, &key, meta.encode());
}
fn delete_meta(tx: &mut DBTransaction, config: &Config, hash: &CandidateHash) {
let key = (META_PREFIX, hash).encode();
tx.delete(config.col_meta, &key[..])
}
fn delete_unfinalized_height(tx: &mut DBTransaction, config: &Config, block_number: BlockNumber) {
let prefix = (UNFINALIZED_PREFIX, BEBlockNumber(block_number)).encode();
tx.delete_prefix(config.col_meta, &prefix);
}
fn delete_unfinalized_inclusion(
tx: &mut DBTransaction,
config: &Config,
block_number: BlockNumber,
block_hash: &Hash,
candidate_hash: &CandidateHash,
) {
let key =
(UNFINALIZED_PREFIX, BEBlockNumber(block_number), block_hash, candidate_hash).encode();
tx.delete(config.col_meta, &key[..]);
}
fn delete_pruning_key(
tx: &mut DBTransaction,
config: &Config,
t: impl Into<BETimestamp>,
h: &CandidateHash,
) {
let key = (PRUNE_BY_TIME_PREFIX, t.into(), h).encode();
tx.delete(config.col_meta, &key);
}
fn write_pruning_key(
tx: &mut DBTransaction,
config: &Config,
t: impl Into<BETimestamp>,
h: &CandidateHash,
) {
let t = t.into();
let key = (PRUNE_BY_TIME_PREFIX, t, h).encode();
tx.put(config.col_meta, &key, TOMBSTONE_VALUE);
}
fn finalized_block_range(finalized: BlockNumber) -> (Vec<u8>, Vec<u8>) {
// We use big-endian encoding to iterate in ascending order.
let start = UNFINALIZED_PREFIX.encode();
let end = (UNFINALIZED_PREFIX, BEBlockNumber(finalized + 1)).encode();
(start, end)
}
fn write_unfinalized_block_contains(
tx: &mut DBTransaction,
config: &Config,
n: BlockNumber,
h: &Hash,
ch: &CandidateHash,
) {
let key = (UNFINALIZED_PREFIX, BEBlockNumber(n), h, ch).encode();
tx.put(config.col_meta, &key, TOMBSTONE_VALUE);
}
fn pruning_range(now: impl Into<BETimestamp>) -> (Vec<u8>, Vec<u8>) {
let start = PRUNE_BY_TIME_PREFIX.encode();
let end = (PRUNE_BY_TIME_PREFIX, BETimestamp(now.into().0 + 1)).encode();
(start, end)
}
fn decode_unfinalized_key(s: &[u8]) -> Result<(BlockNumber, Hash, CandidateHash), CodecError> {
if !s.starts_with(UNFINALIZED_PREFIX) {
return Err("missing magic string".into())
}
<(BEBlockNumber, Hash, CandidateHash)>::decode(&mut &s[UNFINALIZED_PREFIX.len()..])
.map(|(b, h, ch)| (b.0, h, ch))
}
fn decode_pruning_key(s: &[u8]) -> Result<(Duration, CandidateHash), CodecError> {
if !s.starts_with(PRUNE_BY_TIME_PREFIX) {
return Err("missing magic string".into())
}
<(BETimestamp, CandidateHash)>::decode(&mut &s[PRUNE_BY_TIME_PREFIX.len()..])
.map(|(t, ch)| (t.into(), ch))
}
#[derive(Debug, thiserror::Error)]
#[allow(missing_docs)]
pub enum Error {
#[error(transparent)]
RuntimeApi(#[from] RuntimeApiError),
#[error(transparent)]
ChainApi(#[from] ChainApiError),
#[error(transparent)]
Erasure(#[from] erasure::Error),
#[error(transparent)]
Io(#[from] io::Error),
#[error(transparent)]
Oneshot(#[from] oneshot::Canceled),
#[error(transparent)]
Subsystem(#[from] SubsystemError),
#[error("Context signal channel closed")]
ContextChannelClosed,
#[error(transparent)]
Time(#[from] SystemTimeError),
#[error(transparent)]
Codec(#[from] CodecError),
#[error("Custom databases are not supported")]
CustomDatabase,
}
impl Error {
/// Determine if the error is irrecoverable
/// or notifying the user via means of logging
/// is sufficient.
fn is_fatal(&self) -> bool {
match self {
Self::Io(_) => true,
Self::Oneshot(_) => true,
Self::CustomDatabase => true,
Self::ContextChannelClosed => true,
_ => false,
}
}
}
impl Error {
fn trace(&self) {
match self {
// don't spam the log with spurious errors
Self::RuntimeApi(_) | Self::Oneshot(_) => {
gum::debug!(target: LOG_TARGET, err = ?self)
},
// it's worth reporting otherwise
_ => gum::warn!(target: LOG_TARGET, err = ?self),
}
}
}
/// Struct holding pruning timing configuration.
/// The only purpose of this structure is to use different timing
/// configurations in production and in testing.
#[derive(Clone)]
struct PruningConfig {
/// How long unavailable data should be kept.
keep_unavailable_for: Duration,
/// How long finalized data should be kept.
keep_finalized_for: Duration,
/// How often to perform data pruning.
pruning_interval: Duration,
}
impl Default for PruningConfig {
fn default() -> Self {
Self {
keep_unavailable_for: KEEP_UNAVAILABLE_FOR,
keep_finalized_for: KEEP_FINALIZED_FOR,
pruning_interval: PRUNING_INTERVAL,
}
}
}
/// Configuration for the availability store.
#[derive(Debug, Clone, Copy)]
pub struct Config {
/// The column family for availability data and chunks.
pub col_data: u32,
/// The column family for availability store meta information.
pub col_meta: u32,
}
trait Clock: Send + Sync {
// Returns time since unix epoch.
fn now(&self) -> Result<Duration, Error>;
}
struct SystemClock;
impl Clock for SystemClock {
fn now(&self) -> Result<Duration, Error> {
SystemTime::now().duration_since(UNIX_EPOCH).map_err(Into::into)
}
}
/// An implementation of the Availability Store subsystem.
pub struct AvailabilityStoreSubsystem {
pruning_config: PruningConfig,
config: Config,
db: Arc<dyn Database>,
known_blocks: KnownUnfinalizedBlocks,
finalized_number: Option<BlockNumber>,
metrics: Metrics,
clock: Box<dyn Clock>,
sync_oracle: Box<dyn SyncOracle + Send + Sync>,
}
impl AvailabilityStoreSubsystem {
/// Create a new `AvailabilityStoreSubsystem` with a given config on disk.
pub fn new(
db: Arc<dyn Database>,
config: Config,
sync_oracle: Box<dyn SyncOracle + Send + Sync>,
metrics: Metrics,
) -> Self {
Self::with_pruning_config_and_clock(
db,
config,
PruningConfig::default(),
Box::new(SystemClock),
sync_oracle,
metrics,
)
}
/// Create a new `AvailabilityStoreSubsystem` with a given config on disk.
fn with_pruning_config_and_clock(
db: Arc<dyn Database>,
config: Config,
pruning_config: PruningConfig,
clock: Box<dyn Clock>,
sync_oracle: Box<dyn SyncOracle + Send + Sync>,
metrics: Metrics,
) -> Self {
Self {
pruning_config,
config,
db,
metrics,
clock,
known_blocks: KnownUnfinalizedBlocks::default(),
sync_oracle,
finalized_number: None,
}
}
}
/// We keep the hashes and numbers of all unfinalized
/// processed blocks in memory.
#[derive(Default, Debug)]
struct KnownUnfinalizedBlocks {
by_hash: HashSet<Hash>,
by_number: BTreeSet<(BlockNumber, Hash)>,
}
impl KnownUnfinalizedBlocks {
/// Check whether the block has been already processed.
fn is_known(&self, hash: &Hash) -> bool {
self.by_hash.contains(hash)
}
/// Insert a new block into the known set.
fn insert(&mut self, hash: Hash, number: BlockNumber) {
self.by_hash.insert(hash);
self.by_number.insert((number, hash));
}
/// Prune all finalized blocks.
fn prune_finalized(&mut self, finalized: BlockNumber) {
// split_off returns everything after the given key, including the key
let split_point = finalized.saturating_add(1);
let mut finalized = self.by_number.split_off(&(split_point, Hash::zero()));
// after split_off `finalized` actually contains unfinalized blocks, we need to swap
std::mem::swap(&mut self.by_number, &mut finalized);
for (_, block) in finalized {
self.by_hash.remove(&block);
}
}
}
#[overseer::subsystem(AvailabilityStore, error=SubsystemError, prefix=self::overseer)]
impl<Context> AvailabilityStoreSubsystem {
fn start(self, ctx: Context) -> SpawnedSubsystem {
let future = run::<Context>(self, ctx).map(|_| Ok(())).boxed();
SpawnedSubsystem { name: "availability-store-subsystem", future }
}
}
#[overseer::contextbounds(AvailabilityStore, prefix = self::overseer)]
async fn run<Context>(mut subsystem: AvailabilityStoreSubsystem, mut ctx: Context) {
let mut next_pruning = Delay::new(subsystem.pruning_config.pruning_interval).fuse();
loop {
let res = run_iteration(&mut ctx, &mut subsystem, &mut next_pruning).await;
match res {
Err(e) => {
e.trace();
if e.is_fatal() {
break
}
},
Ok(true) => {
gum::info!(target: LOG_TARGET, "received `Conclude` signal, exiting");
break
},
Ok(false) => continue,
}
}
}
#[overseer::contextbounds(AvailabilityStore, prefix = self::overseer)]
async fn run_iteration<Context>(
ctx: &mut Context,
subsystem: &mut AvailabilityStoreSubsystem,
mut next_pruning: &mut future::Fuse<Delay>,
) -> Result<bool, Error> {
select! {
incoming = ctx.recv().fuse() => {
match incoming.map_err(|_| Error::ContextChannelClosed)? {
FromOrchestra::Signal(OverseerSignal::Conclude) => return Ok(true),
FromOrchestra::Signal(OverseerSignal::ActiveLeaves(
ActiveLeavesUpdate { activated, .. })
) => {
for activated in activated.into_iter() {
let _timer = subsystem.metrics.time_block_activated();
process_block_activated(ctx, subsystem, activated.hash).await?;
}
}
FromOrchestra::Signal(OverseerSignal::BlockFinalized(hash, number)) => {
let _timer = subsystem.metrics.time_process_block_finalized();
if !subsystem.known_blocks.is_known(&hash) {
// If we haven't processed this block yet,
// make sure we write the metadata about the
// candidates backed in this finalized block.
// Otherwise, we won't be able to store our chunk
// for these candidates.
if !subsystem.sync_oracle.is_major_syncing() {
// If we're major syncing, processing finalized
// blocks might take quite a very long time
// and make the subsystem unresponsive.
process_block_activated(ctx, subsystem, hash).await?;
}
}
subsystem.finalized_number = Some(number);
subsystem.known_blocks.prune_finalized(number);
process_block_finalized(
ctx,
&subsystem,
hash,
number,
).await?;
}
FromOrchestra::Communication { msg } => {
let _timer = subsystem.metrics.time_process_message();
process_message(subsystem, msg)?;
}
}
}
_ = next_pruning => {
// It's important to set the delay before calling `prune_all` because an error in `prune_all`
// could lead to the delay not being set again. Then we would never prune anything anymore.
*next_pruning = Delay::new(subsystem.pruning_config.pruning_interval).fuse();
let _timer = subsystem.metrics.time_pruning();
prune_all(&subsystem.db, &subsystem.config, &*subsystem.clock)?;
}
}
Ok(false)
}
#[overseer::contextbounds(AvailabilityStore, prefix = self::overseer)]
async fn process_block_activated<Context>(
ctx: &mut Context,
subsystem: &mut AvailabilityStoreSubsystem,
activated: Hash,
) -> Result<(), Error> {
let now = subsystem.clock.now()?;
let block_header = {
let (tx, rx) = oneshot::channel();
ctx.send_message(ChainApiMessage::BlockHeader(activated, tx)).await;
match rx.await?? {
None => return Ok(()),
Some(n) => n,
}
};
let block_number = block_header.number;
let new_blocks = util::determine_new_blocks(
ctx.sender(),
|hash| -> Result<bool, Error> { Ok(subsystem.known_blocks.is_known(hash)) },
activated,
&block_header,
subsystem.finalized_number.unwrap_or(block_number.saturating_sub(1)),
)
.await?;
// determine_new_blocks is descending in block height
for (hash, header) in new_blocks.into_iter().rev() {
// it's important to commit the db transactions for a head before the next one is processed
// alternatively, we could utilize the OverlayBackend from approval-voting
let mut tx = DBTransaction::new();
process_new_head(
ctx,
&subsystem.db,
&mut tx,
&subsystem.config,
&subsystem.pruning_config,
now,
hash,
header,
)
.await?;
subsystem.known_blocks.insert(hash, block_number);
subsystem.db.write(tx)?;
}
Ok(())
}
#[overseer::contextbounds(AvailabilityStore, prefix = self::overseer)]
async fn process_new_head<Context>(
ctx: &mut Context,
db: &Arc<dyn Database>,
db_transaction: &mut DBTransaction,
config: &Config,
pruning_config: &PruningConfig,
now: Duration,
hash: Hash,
header: Header,
) -> Result<(), Error> {
let candidate_events = util::request_candidate_events(hash, ctx.sender()).await.await??;
// We need to request the number of validators based on the parent state,
// as that is the number of validators used to create this block.
let n_validators =
util::request_validators(header.parent_hash, ctx.sender()).await.await??.len();
for event in candidate_events {
match event {
CandidateEvent::CandidateBacked(receipt, _head, _core_index, _group_index) => {
note_block_backed(
db,
db_transaction,
config,
pruning_config,
now,
n_validators,
receipt,
)?;
},
CandidateEvent::CandidateIncluded(receipt, _head, _core_index, _group_index) => {
note_block_included(
db,
db_transaction,
config,
pruning_config,
(header.number, hash),
receipt,
)?;
},
_ => {},
}
}
Ok(())
}
fn note_block_backed(
db: &Arc<dyn Database>,
db_transaction: &mut DBTransaction,
config: &Config,
pruning_config: &PruningConfig,
now: Duration,
n_validators: usize,
candidate: CandidateReceipt,
) -> Result<(), Error> {
let candidate_hash = candidate.hash();
gum::debug!(target: LOG_TARGET, ?candidate_hash, "Candidate backed");
if load_meta(db, config, &candidate_hash)?.is_none() {
let meta = CandidateMeta {
state: State::Unavailable(now.into()),
data_available: false,
chunks_stored: bitvec::bitvec![u8, BitOrderLsb0; 0; n_validators],
};
let prune_at = now + pruning_config.keep_unavailable_for;
write_pruning_key(db_transaction, config, prune_at, &candidate_hash);
write_meta(db_transaction, config, &candidate_hash, &meta);
}
Ok(())
}
fn note_block_included(
db: &Arc<dyn Database>,
db_transaction: &mut DBTransaction,
config: &Config,
pruning_config: &PruningConfig,
block: (BlockNumber, Hash),
candidate: CandidateReceipt,
) -> Result<(), Error> {
let candidate_hash = candidate.hash();
match load_meta(db, config, &candidate_hash)? {
None => {
// This is alarming. We've observed a block being included without ever seeing it backed.
// Warn and ignore.
gum::warn!(
target: LOG_TARGET,
?candidate_hash,
"Candidate included without being backed?",
);
},
Some(mut meta) => {
let be_block = (BEBlockNumber(block.0), block.1);
gum::debug!(target: LOG_TARGET, ?candidate_hash, "Candidate included");
meta.state = match meta.state {
State::Unavailable(at) => {
let at_d: Duration = at.into();
let prune_at = at_d + pruning_config.keep_unavailable_for;
delete_pruning_key(db_transaction, config, prune_at, &candidate_hash);
State::Unfinalized(at, vec![be_block])
},
State::Unfinalized(at, mut within) => {
if let Err(i) = within.binary_search(&be_block) {
within.insert(i, be_block);
State::Unfinalized(at, within)
} else {
return Ok(())
}
},
State::Finalized(_at) => {
// This should never happen as a candidate would have to be included after
// finality.
return Ok(())
},
};
write_unfinalized_block_contains(
db_transaction,
config,
block.0,
&block.1,
&candidate_hash,
);
write_meta(db_transaction, config, &candidate_hash, &meta);
},
}
Ok(())
}
macro_rules! peek_num {
($iter:ident) => {
match $iter.peek() {
Some(Ok((k, _))) => Ok(decode_unfinalized_key(&k[..]).ok().map(|(b, _, _)| b)),
Some(Err(_)) => Err($iter.next().expect("peek returned Some(Err); qed").unwrap_err()),
None => Ok(None),
}
};
}
#[overseer::contextbounds(AvailabilityStore, prefix = self::overseer)]
async fn process_block_finalized<Context>(
ctx: &mut Context,
subsystem: &AvailabilityStoreSubsystem,
finalized_hash: Hash,
finalized_number: BlockNumber,
) -> Result<(), Error> {
let now = subsystem.clock.now()?;
let mut next_possible_batch = 0;
loop {
let mut db_transaction = DBTransaction::new();
let (start_prefix, end_prefix) = finalized_block_range(finalized_number);
// We have to do some juggling here of the `iter` to make sure it doesn't cross the `.await` boundary
// as it is not `Send`. That is why we create the iterator once within this loop, drop it,
// do an asynchronous request, and then instantiate the exact same iterator again.
let batch_num = {
let mut iter = subsystem
.db
.iter_with_prefix(subsystem.config.col_meta, &start_prefix)
.take_while(|r| r.as_ref().map_or(true, |(k, _v)| &k[..] < &end_prefix[..]))
.peekable();
match peek_num!(iter)? {
None => break, // end of iterator.
Some(n) => n,
}
};
if batch_num < next_possible_batch {
continue
} // sanity.
next_possible_batch = batch_num + 1;
let batch_finalized_hash = if batch_num == finalized_number {
finalized_hash
} else {
let (tx, rx) = oneshot::channel();
ctx.send_message(ChainApiMessage::FinalizedBlockHash(batch_num, tx)).await;
match rx.await? {
Err(err) => {
gum::warn!(
target: LOG_TARGET,
batch_num,
?err,
"Failed to retrieve finalized block number.",
);
break
},
Ok(None) => {
gum::warn!(
target: LOG_TARGET,
"Availability store was informed that block #{} is finalized, \
but chain API has no finalized hash.",
batch_num,
);
break
},
Ok(Some(h)) => h,
}
};
let iter = subsystem
.db
.iter_with_prefix(subsystem.config.col_meta, &start_prefix)
.take_while(|r| r.as_ref().map_or(true, |(k, _v)| &k[..] < &end_prefix[..]))
.peekable();
let batch = load_all_at_finalized_height(iter, batch_num, batch_finalized_hash)?;
// Now that we've iterated over the entire batch at this finalized height,
// update the meta.
delete_unfinalized_height(&mut db_transaction, &subsystem.config, batch_num);
update_blocks_at_finalized_height(&subsystem, &mut db_transaction, batch, batch_num, now)?;
// We need to write at the end of the loop so the prefix iterator doesn't pick up the same values again
// in the next iteration. Another unfortunate effect of having to re-initialize the iterator.
subsystem.db.write(db_transaction)?;
}
Ok(())
}
// loads all candidates at the finalized height and maps them to `true` if finalized
// and `false` if unfinalized.
fn load_all_at_finalized_height(
mut iter: std::iter::Peekable<impl Iterator<Item = io::Result<util::database::DBKeyValue>>>,
block_number: BlockNumber,
finalized_hash: Hash,
) -> io::Result<impl IntoIterator<Item = (CandidateHash, bool)>> {
// maps candidate hashes to true if finalized, false otherwise.
let mut candidates = HashMap::new();
// Load all candidates that were included at this height.
loop {
match peek_num!(iter)? {
None => break, // end of iterator.
Some(n) if n != block_number => break, // end of batch.
_ => {},
}
let (k, _v) = iter.next().expect("`peek` used to check non-empty; qed")?;
let (_, block_hash, candidate_hash) =
decode_unfinalized_key(&k[..]).expect("`peek_num` checks validity of key; qed");
if block_hash == finalized_hash {
candidates.insert(candidate_hash, true);
} else {
candidates.entry(candidate_hash).or_insert(false);
}
}
Ok(candidates)
}
fn update_blocks_at_finalized_height(
subsystem: &AvailabilityStoreSubsystem,
db_transaction: &mut DBTransaction,
candidates: impl IntoIterator<Item = (CandidateHash, bool)>,
block_number: BlockNumber,
now: Duration,
) -> Result<(), Error> {
for (candidate_hash, is_finalized) in candidates {
let mut meta = match load_meta(&subsystem.db, &subsystem.config, &candidate_hash)? {
None => {
gum::warn!(
target: LOG_TARGET,
"Dangling candidate metadata for {}",
candidate_hash,
);
continue
},
Some(c) => c,
};
if is_finalized {
// Clear everything else related to this block. We're finalized now!
match meta.state {
State::Finalized(_) => continue, // sanity
State::Unavailable(at) => {
// This is also not going to happen; the very fact that we are
// iterating over the candidate here indicates that `State` should
// be `Unfinalized`.
delete_pruning_key(db_transaction, &subsystem.config, at, &candidate_hash);
},
State::Unfinalized(_, blocks) => {
for (block_num, block_hash) in blocks.iter().cloned() {
// this exact height is all getting cleared out anyway.
if block_num.0 != block_number {
delete_unfinalized_inclusion(
db_transaction,
&subsystem.config,
block_num.0,
&block_hash,
&candidate_hash,
);
}
}
},
}
meta.state = State::Finalized(now.into());
// Write the meta and a pruning record.
write_meta(db_transaction, &subsystem.config, &candidate_hash, &meta);
write_pruning_key(
db_transaction,
&subsystem.config,
now + subsystem.pruning_config.keep_finalized_for,