-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathstore.rs
More file actions
3095 lines (2740 loc) · 119 KB
/
Copy pathstore.rs
File metadata and controls
3095 lines (2740 loc) · 119 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
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};
use std::num::NonZeroUsize;
use std::sync::{Arc, LazyLock, Mutex};
use lru::LruCache;
use crate::api::{StorageBackend, StorageReadView, StorageWriteBatch, Table};
use crate::error::Error;
use ethlambda_crypto::signature::ValidatorSignature;
use ethlambda_types::{
attestation::{AggregationBits, AttestationData, HashedAttestationData, bits_is_subset},
block::{
Block, BlockBody, BlockHeader, MultiMessageAggregate, SignedBlock, SingleMessageAggregate,
},
checkpoint::Checkpoint,
constants::INTERVALS_PER_SLOT,
genesis::GenesisConfig,
primitives::{H256, HashTreeRoot as _},
state::{ChainConfig, State, anchor_pair_is_consistent},
};
use libssz::{SszDecode, SszEncode};
use crate::state_diff::StateDiff;
use thiserror::Error;
use tracing::{error, info};
/// Errors returned by [`Store::get_forkchoice_store`].
#[derive(Debug, Error)]
pub enum GetForkchoiceStoreError {
#[error(
"anchor block doesn't match anchor state: \
state header = {anchor_state:?}, block = {anchor_block:?}"
)]
AnchorPairInconsistent {
anchor_state: Box<State>,
anchor_block: Box<Block>,
},
}
/// The tree hash root of an empty block body.
///
/// Used to detect genesis/anchor blocks that have no attestations,
/// allowing us to skip storing empty bodies and reconstruct them on read.
static EMPTY_BODY_ROOT: LazyLock<H256> = LazyLock::new(|| BlockBody::default().hash_tree_root());
/// Checkpoints to update in the forkchoice store.
///
/// Used with `Store::update_checkpoints` to update head and optionally
/// update justified/finalized checkpoints (only if higher slot).
pub struct ForkCheckpoints {
head: H256,
justified: Option<Checkpoint>,
finalized: Option<Checkpoint>,
}
impl ForkCheckpoints {
/// Create checkpoints update with only the head.
pub fn head_only(head: H256) -> Self {
Self {
head,
justified: None,
finalized: None,
}
}
/// Create checkpoints update with optional justified and finalized.
///
/// The head is passed through unchanged.
pub fn new(head: H256, justified: Option<Checkpoint>, finalized: Option<Checkpoint>) -> Self {
Self {
head,
justified,
finalized,
}
}
}
// ============ Metadata Keys ============
/// Key for "time" field of the Store. Its value has type [`u64`] and it's SSZ-encoded.
const KEY_TIME: &[u8] = b"time";
/// Key for "config" field of the Store. Its value has type [`ChainConfig`] and it's SSZ-encoded.
const KEY_CONFIG: &[u8] = b"config";
/// Key for "head" field of the Store. Its value has type [`H256`] and it's SSZ-encoded.
const KEY_HEAD: &[u8] = b"head";
/// Key for "safe_target" field of the Store. Its value has type [`H256`] and it's SSZ-encoded.
const KEY_SAFE_TARGET: &[u8] = b"safe_target";
/// Key for "latest_justified" field of the Store. Its value has type [`Checkpoint`] and it's SSZ-encoded.
const KEY_LATEST_JUSTIFIED: &[u8] = b"latest_justified";
/// Key for "latest_finalized" field of the Store. Its value has type [`Checkpoint`] and it's SSZ-encoded.
const KEY_LATEST_FINALIZED: &[u8] = b"latest_finalized";
/// Persist a full-state snapshot whenever a block's slot crosses a multiple of
/// this value (relative to its parent's slot).
///
/// Snapshots are the only entries written to `States` (plus the bootstrap
/// anchor); they are never pruned and bound state-reconstruction diff walks to
/// at most this many steps. ~68 minutes at 4-second slots.
const SNAPSHOT_ANCHOR_INTERVAL: u64 = 1_024;
/// Number of reconstructed/imported states memoized in memory.
///
/// States are content-addressed by block root and immutable, so the cache never
/// needs invalidation; it only bounds how many recent states stay hot for reads
/// (e.g. a block's `parent_state` right after import). A miss falls back to a
/// snapshot read or a diff-chain reconstruction.
const STATE_CACHE_CAPACITY: usize = 32;
/// Keep block proofs for at least this many slots below the tip, even once
/// finalized. Proofs older than this window are pruned only when the window
/// lies entirely within finalized history; see [`Store::prune_old_block_proofs`].
/// ~1 day at 4-second slots.
const BLOCK_PROOF_PRUNING_RANGE: u64 = 21_600;
/// ~30 minutes of resume window at 4-second slots (1800 / 4 = 450).
pub const MAX_RESUMABLE_DB_STATE_AGE: u64 = 450;
/// Hard cap for the known aggregated payload buffer (number of distinct attestation messages).
/// With 1 attestation/slot, this holds ~500 messages (~33 min at 4s/slot).
const AGGREGATED_PAYLOAD_CAP: usize = 512;
/// Hard cap for the new (pending) aggregated payload buffer.
/// Smaller than known since new payloads are drained every interval (~4s).
const NEW_PAYLOAD_CAP: usize = 64;
/// Hard cap for the gossip signature buffer (individual signatures, not distinct data_roots).
/// With 4 validators and 4-second slots, 2048 signatures covers ~512 slots (~34 min).
/// Each XMSS signature is ~3KB, so worst-case memory is ~6 MB.
const GOSSIP_SIGNATURE_CAP: usize = 2048;
/// An entry in the payload buffer: attestation data + set of proofs.
#[derive(Clone)]
struct PayloadEntry {
data: AttestationData,
proofs: Vec<SingleMessageAggregate>,
}
/// Fixed-size circular buffer for aggregated payloads.
///
/// Groups proofs by attestation data (via data_root). Each distinct
/// attestation message stores the full `AttestationData` plus all
/// `SingleMessageAggregate`s covering that message.
///
/// Entries are evicted FIFO (by insertion order of the data_root)
/// when the buffer reaches capacity.
#[derive(Clone)]
struct PayloadBuffer {
data: HashMap<H256, PayloadEntry>,
order: VecDeque<H256>,
capacity: usize,
total_proofs: usize,
}
impl PayloadBuffer {
fn new(capacity: usize) -> Self {
Self {
data: HashMap::with_capacity(capacity),
order: VecDeque::with_capacity(capacity),
capacity,
total_proofs: 0,
}
}
/// Insert a proof for an attestation, FIFO-evicting oldest data_roots
/// when total proofs reach capacity. Also ensures the buffer doesn't
/// include proofs which are a subset of other proofs for the same
/// attestation data:
///
/// - If the incoming proof's participants are a subset (incl. equal) of
/// any existing proof, the incoming proof is redundant and skipped.
/// - Otherwise, any existing proof whose participants are a strict subset
/// of the incoming proof's is removed before inserting.
fn push(&mut self, hashed: HashedAttestationData, proof: SingleMessageAggregate) {
let (data_root, att_data) = hashed.into_parts();
if let Some(entry) = self.data.get_mut(&data_root) {
let mut to_remove: Vec<usize> = Vec::new();
for (i, p) in entry.proofs.iter().enumerate() {
// Incoming is subsumed by an existing proof (incl. equal). Skip.
if bits_is_subset(&proof.participants, &p.participants) {
return;
}
// Existing is a strict subset of incoming. Mark for removal.
// (Non-strict equality was ruled out by the check above.)
if bits_is_subset(&p.participants, &proof.participants) {
to_remove.push(i);
}
}
// Remove subsumed proofs (reverse order so earlier indices stay valid).
for i in to_remove.into_iter().rev() {
entry.proofs.swap_remove(i);
self.total_proofs -= 1;
}
entry.proofs.push(proof);
self.total_proofs += 1;
} else {
self.data.insert(
data_root,
PayloadEntry {
data: att_data,
proofs: vec![proof],
},
);
self.order.push_back(data_root);
self.total_proofs += 1;
}
// Evict oldest data_roots until under capacity
while self.total_proofs > self.capacity {
if let Some(evicted) = self.order.pop_front() {
if let Some(removed) = self.data.remove(&evicted) {
self.total_proofs -= removed.proofs.len();
}
} else {
break;
}
}
}
/// Insert a batch of (hashed_attestation_data, proof) entries.
fn push_batch(&mut self, entries: Vec<(HashedAttestationData, SingleMessageAggregate)>) {
for (hashed, proof) in entries {
self.push(hashed, proof);
}
}
/// Take all entries, leaving the buffer empty.
///
/// Drains in insertion order (via `self.order`) so downstream consumers
/// like `promote_new_aggregated_payloads` re-insert into known_payloads
/// deterministically; `self.data` iteration alone would be RandomState-seeded.
/// (Fork-choice vote extraction no longer depends on this order: it resolves
/// same-slot equivocation by canonical attestation-data root, see
/// `extract_latest_attestations`.)
fn drain(&mut self) -> Vec<(HashedAttestationData, SingleMessageAggregate)> {
self.total_proofs = 0;
let mut result = Vec::with_capacity(self.data.values().map(|e| e.proofs.len()).sum());
while let Some(data_root) = self.order.pop_front() {
if let Some(entry) = self.data.remove(&data_root) {
for proof in entry.proofs {
result.push((HashedAttestationData::new(entry.data.clone()), proof));
}
}
}
result
}
/// Return the number of distinct attestation messages in the buffer.
fn len(&self) -> usize {
self.data.len()
}
/// Return the number of proofs for a given data_root without cloning.
fn proof_count_for_root(&self, data_root: &H256) -> usize {
self.data.get(data_root).map_or(0, |e| e.proofs.len())
}
/// Return cloned proofs for a given data_root, or empty vec if none.
fn proofs_for_root(&self, data_root: &H256) -> Vec<SingleMessageAggregate> {
self.data
.get(data_root)
.map_or_else(Vec::new, |e| e.proofs.clone())
}
/// Return attestation data entries keyed by data_root.
fn attestation_data_keys(&self) -> Vec<(H256, AttestationData)> {
self.data
.iter()
.map(|(&root, entry)| (root, entry.data.clone()))
.collect()
}
/// Prune payload entries whose attestation target slot is at or below `finalized_slot`.
///
/// Mirrors leanSpec's `prune_stale_attestation_data`: an entry is stale once its
/// target checkpoint is finalized — it can no longer contribute to fork choice and
/// keeping it around only pollutes `existing_proofs_for_data` lookups, occasionally
/// forcing recursive aggregation when plain XMSS aggregation would suffice.
///
/// Returns the number of data_root entries removed.
fn prune(&mut self, finalized_slot: u64) -> usize {
let before = self.data.len();
let total_proofs = &mut self.total_proofs;
self.data.retain(|_root, entry| {
if entry.data.target.slot > finalized_slot {
true
} else {
*total_proofs -= entry.proofs.len();
false
}
});
let pruned = before - self.data.len();
if pruned > 0 {
self.order.retain(|r| self.data.contains_key(r));
}
pruned
}
/// Extract per-validator latest attestations from proofs' participation bits.
///
/// An equivocator can cast two distinct votes at the same `slot`. To keep the
/// extracted head a pure function of pool contents (independent of arrival or
/// insertion order), votes are processed newest-first with an equal-slot tie
/// broken toward the larger canonical attestation-data root — the same rule the
/// block-level fork-choice tiebreak applies to block roots (leanSpec #1181). The
/// pool key is already `hash_tree_root(data)`, so the tie needs no extra hashing.
fn extract_latest_attestations(&self) -> HashMap<u64, AttestationData> {
let mut ordered: Vec<(&H256, &PayloadEntry)> = self.data.iter().collect();
// Descending by (slot, data_root): the larger tuple is the canonical winner.
ordered.sort_unstable_by(|a, b| (b.1.data.slot, b.0).cmp(&(a.1.data.slot, a.0)));
let mut result: HashMap<u64, AttestationData> = HashMap::new();
for (_data_root, entry) in ordered {
for proof in &entry.proofs {
for vid in proof.participant_indices() {
// Descending order means the first vote seen for a validator wins.
result.entry(vid).or_insert_with(|| entry.data.clone());
}
}
}
result
}
}
/// Gossip signatures grouped by attestation data.
///
/// Signatures are stored in a `BTreeMap` keyed by validator_id to guarantee
/// ascending iteration order. XMSS aggregate proofs are order-dependent:
/// verification reconstructs pubkeys from the participation bitfield (low-to-high),
/// so aggregation must produce them in the same ascending order.
struct GossipDataEntry {
data: AttestationData,
signatures: BTreeMap<u64, ValidatorSignature>,
}
/// Gossip signatures snapshot: (hashed_attestation_data, Vec<(validator_id, signature)>).
pub type GossipSignatureSnapshot = Vec<(HashedAttestationData, Vec<(u64, ValidatorSignature)>)>;
type StorageKey = Vec<u8>;
type StorageEntry = (StorageKey, Vec<u8>);
type BlockRootIndexChanges = (Vec<StorageKey>, Vec<StorageEntry>);
/// Bounded buffer for gossip signatures with FIFO eviction.
///
/// Groups signatures by attestation data (via data_root). Each distinct
/// attestation message stores the full `AttestationData` plus individual
/// validator signatures in ascending order (required for XMSS aggregation).
///
/// Entries are evicted FIFO (by insertion order of the data_root) when
/// total_signatures exceeds capacity, matching the `PayloadBuffer` pattern.
struct GossipSignatureBuffer {
data: HashMap<H256, GossipDataEntry>,
order: VecDeque<H256>,
capacity: usize,
total_signatures: usize,
}
impl GossipSignatureBuffer {
fn new(capacity: usize) -> Self {
Self {
data: HashMap::new(),
order: VecDeque::new(),
capacity,
total_signatures: 0,
}
}
/// Insert a gossip signature, FIFO-evicting oldest data_roots when over capacity.
///
/// Last-write-wins: if (validator_id, data_root) already exists, the signature is overwritten.
fn insert(
&mut self,
hashed: HashedAttestationData,
validator_id: u64,
signature: ValidatorSignature,
) {
let (data_root, att_data) = hashed.into_parts();
if let Some(entry) = self.data.get_mut(&data_root) {
let is_new = entry.signatures.insert(validator_id, signature).is_none();
if is_new {
self.total_signatures += 1;
}
} else {
let mut signatures = BTreeMap::new();
signatures.insert(validator_id, signature);
self.data.insert(
data_root,
GossipDataEntry {
data: att_data,
signatures,
},
);
self.order.push_back(data_root);
self.total_signatures += 1;
}
// Evict oldest data_roots until under capacity
while self.total_signatures > self.capacity {
if let Some(evicted) = self.order.pop_front() {
if let Some(removed) = self.data.remove(&evicted) {
self.total_signatures -= removed.signatures.len();
}
} else {
break;
}
}
}
/// Delete gossip entries for the given (validator_id, data_root) pairs.
///
/// When all signatures for a data_root are removed, the entry is cleaned up.
/// Collects emptied roots and batch-cleans the VecDeque in one pass.
fn delete(&mut self, keys: &[(u64, H256)]) {
if keys.is_empty() {
return;
}
let mut emptied_roots: HashSet<H256> = HashSet::new();
for &(vid, data_root) in keys {
if let Some(entry) = self.data.get_mut(&data_root) {
if entry.signatures.remove(&vid).is_some() {
self.total_signatures -= 1;
}
if entry.signatures.is_empty() {
self.data.remove(&data_root);
emptied_roots.insert(data_root);
}
}
}
if !emptied_roots.is_empty() {
self.order.retain(|r| !emptied_roots.contains(r));
}
}
/// Prune gossip signatures for slots <= finalized_slot.
///
/// Returns the number of data_root entries pruned.
fn prune(&mut self, finalized_slot: u64) -> usize {
let before = self.data.len();
self.data.retain(|_root, entry| {
if entry.data.slot > finalized_slot {
true
} else {
self.total_signatures -= entry.signatures.len();
false
}
});
let pruned = before - self.data.len();
if pruned > 0 {
self.order.retain(|r| self.data.contains_key(r));
}
pruned
}
/// Returns a snapshot of all gossip signatures grouped by attestation data.
fn snapshot(&self) -> GossipSignatureSnapshot {
self.data
.values()
.map(|entry| {
let sigs: Vec<_> = entry
.signatures
.iter()
.map(|(&vid, sig)| (vid, sig.clone()))
.collect();
(HashedAttestationData::new(entry.data.clone()), sigs)
})
.collect()
}
/// Largest signature count among data groups whose attestation slot is `slot`.
fn max_group_count_for_slot(&self, slot: u64) -> usize {
self.data
.values()
.filter(|entry| entry.data.slot == slot)
.map(|entry| entry.signatures.len())
.max()
.unwrap_or(0)
}
/// Extract per-validator latest attestations from the raw signature pool.
///
/// Mirrors `PayloadBuffer::extract_latest_attestations`: votes are processed
/// newest-first with an equal-slot tie broken toward the larger canonical
/// attestation-data root, so the extracted winner is independent of arrival or
/// insertion order (leanSpec #1181). This matches the leanSpec
/// `location == "signatures"` checker, which folds `attestation_signatures`
/// keeping each validator's canonical-precedence winner.
fn extract_latest_attestations(&self) -> HashMap<u64, AttestationData> {
let mut ordered: Vec<(&H256, &GossipDataEntry)> = self.data.iter().collect();
// Descending by (slot, data_root): the larger tuple is the canonical winner.
ordered.sort_unstable_by(|a, b| (b.1.data.slot, b.0).cmp(&(a.1.data.slot, a.0)));
let mut result: HashMap<u64, AttestationData> = HashMap::new();
for (_data_root, entry) in ordered {
for &vid in entry.signatures.keys() {
// Descending order means the first vote seen for a validator wins.
result.entry(vid).or_insert_with(|| entry.data.clone());
}
}
result
}
/// Returns the total number of individual signatures stored.
fn total_signatures(&self) -> usize {
self.total_signatures
}
/// Returns the number of distinct data_roots.
#[cfg(test)]
fn len(&self) -> usize {
self.data.len()
}
}
/// Encode a LiveChain key (slot, root) to bytes.
/// Layout: slot (8 bytes big-endian) || root (32 bytes)
/// Big-endian ensures lexicographic ordering matches numeric ordering.
fn encode_slot_root_key(slot: u64, root: &H256) -> Vec<u8> {
let mut result = slot.to_be_bytes().to_vec();
result.extend_from_slice(&root.0);
result
}
/// Decode a slot||root key (LiveChain / BlockProof) from bytes.
fn decode_slot_root_key(bytes: &[u8]) -> (u64, H256) {
let slot = u64::from_be_bytes(bytes[..8].try_into().expect("valid slot bytes"));
let root = H256::from_slice(&bytes[8..]);
(slot, root)
}
fn encode_block_root_key(slot: u64) -> Vec<u8> {
slot.to_be_bytes().to_vec()
}
/// Fork choice store backed by a pluggable storage backend.
///
/// The Store maintains all state required for fork choice and block processing:
///
/// - **Metadata**: time, config, head, safe_target, justified/finalized checkpoints
/// - **Blocks**: headers and bodies stored separately for efficient header-only queries
/// - **BlockRoots**: canonical block roots indexed by slot
/// - **States**: beacon states indexed by block root
/// - **Attestations**: latest known and pending ("new") attestations per validator
/// - **Signatures**: gossip signatures and aggregated proofs for signature verification
/// - **LiveChain**: slot index for efficient fork choice traversal (pruned on finalization)
///
/// # Constructors
///
/// - [`from_anchor_state`](Self::from_anchor_state): Initialize from a checkpoint state (no block body)
/// - [`get_forkchoice_store`](Self::get_forkchoice_store): Initialize from state + block (stores body)
#[derive(Clone)]
pub struct Store {
backend: Arc<dyn StorageBackend>,
/// Cached copy of the persisted [`ChainConfig`].
///
/// The config is written once at bootstrap and has no setter, so a plain copy
/// per `Store` cannot go stale: sharing it behind an `Arc` would buy nothing.
/// It stays in `Table::Metadata` under `KEY_CONFIG` because `from_db_state`
/// reads it back to reject a DB whose `genesis_time` disagrees with the config
/// file; this field only spares every caller a backend round trip and a
/// `Result` it could never act on.
config: ChainConfig,
new_payloads: Arc<Mutex<PayloadBuffer>>,
known_payloads: Arc<Mutex<PayloadBuffer>>,
/// In-memory gossip signatures, consumed at interval 2 aggregation.
gossip_signatures: Arc<Mutex<GossipSignatureBuffer>>,
/// LRU memoization of states by block root, shared across `Store` clones.
/// Avoids reconstructing recent states from diffs on every read.
state_cache: Arc<Mutex<LruCache<H256, State>>>,
}
/// Build an empty state cache sized to [`STATE_CACHE_CAPACITY`].
fn new_state_cache() -> Arc<Mutex<LruCache<H256, State>>> {
let capacity = NonZeroUsize::new(STATE_CACHE_CAPACITY).expect("cache capacity is non-zero");
Arc::new(Mutex::new(LruCache::new(capacity)))
}
impl Store {
/// Initialize a Store from an anchor state only.
///
/// Uses the state's `latest_block_header` as the anchor block header.
/// No block body is stored since it's not available.
pub fn from_anchor_state(backend: Arc<dyn StorageBackend>, anchor_state: State) -> Self {
Self::init_store(backend, anchor_state, None)
.expect("store initialization should succeed in from_anchor_state")
}
/// Initialize a Store from an anchor state and block.
///
/// The block must match the state's `latest_block_header`.
/// Named to mirror the spec's `get_forkchoice_store` function.
///
/// # Errors
///
/// Returns [`GetForkchoiceStoreError::AnchorPairInconsistent`] if the block's header
/// doesn't match the state's `latest_block_header` (comparing all fields
/// except `state_root`, which is computed internally).
pub fn get_forkchoice_store(
backend: Arc<dyn StorageBackend>,
mut anchor_state: State,
anchor_block: Block,
) -> Result<Self, GetForkchoiceStoreError> {
if !anchor_pair_is_consistent(&mut anchor_state, &anchor_block) {
return Err(GetForkchoiceStoreError::AnchorPairInconsistent {
anchor_state: Box::new(anchor_state),
anchor_block: Box::new(anchor_block),
});
}
Ok(
Self::init_store(backend, anchor_state, Some(anchor_block.body))
.expect("store initialization should succeed in get_forkchoice_store"),
)
}
/// Build a Store from the state already persisted in the storage backend.
///
/// Returns `None` when the backend holds no chain state yet, leaving the
/// caller to initialize one from genesis or a checkpoint.
///
/// # Errors
///
/// Returns [`Error::GenesisMismatch`] when the persisted chain was started
/// from a different genesis than `genesis`. This is fatal rather than a
/// fall back to "treat the DB as empty": writing a new anchor on top would
/// leave the foreign chain's rows in place, and slot-indexed reads such as
/// [`Self::get_signed_blocks_by_slot_range`] would then serve them to
/// peers.
pub fn from_db_state(
backend: Arc<dyn StorageBackend>,
genesis: &GenesisConfig,
) -> Result<Option<Self>, Error> {
let persisted_config = {
// Both keys are written by `init_store`, so a backend missing
// either has never held a chain.
let view = backend.begin_read().expect("read view");
let Some(bytes) = view.get(Table::Metadata, KEY_CONFIG).expect("get config") else {
return Ok(None);
};
if view
.get(Table::Metadata, KEY_LATEST_FINALIZED)
.expect("get latest finalized")
.is_none()
{
return Ok(None);
}
ChainConfig::from_ssz_bytes(&bytes).expect("valid config")
};
let store = Self {
backend,
config: persisted_config,
new_payloads: Arc::new(Mutex::new(PayloadBuffer::new(NEW_PAYLOAD_CAP))),
known_payloads: Arc::new(Mutex::new(PayloadBuffer::new(AGGREGATED_PAYLOAD_CAP))),
gossip_signatures: Arc::new(Mutex::new(GossipSignatureBuffer::new(
GOSSIP_SIGNATURE_CAP,
))),
state_cache: new_state_cache(),
};
// Compare against the finalized state rather than the persisted
// `ChainConfig`: the config carries only `genesis_time`, so it cannot
// catch a chain that shares our genesis time but not our validator
// set. Finalized is chosen over head because it is the state the
// anchor is rebuilt from and it never gets pruned.
let finalized = store.latest_finalized()?.root;
let state = store
.get_state(&finalized)?
.ok_or(Error::UnexpectedMissingState(finalized))?;
genesis.verify_state(&state).inspect_err(|err| {
error!(
%err,
db_genesis_time = state.config.genesis_time,
db_validators = state.validators.len(),
expected_genesis_time = genesis.genesis_time,
expected_validators = genesis.genesis_validators.len(),
"Persisted DB belongs to a different network; refusing to reuse this data directory"
)
})?;
info!("Loaded store from persisted DB state");
Ok(Some(store))
}
/// Internal helper to initialize the store with anchor data.
///
/// Header is taken from `anchor_state.latest_block_header`.
fn init_store(
backend: Arc<dyn StorageBackend>,
mut anchor_state: State,
anchor_body: Option<BlockBody>,
) -> Result<Self, Error> {
// Save original state_root for validation
let original_state_root = anchor_state.latest_block_header.state_root;
// Zero out state_root before computing (state contains header, header contains state_root)
anchor_state.latest_block_header.state_root = H256::ZERO;
// Compute state root with zeroed header
let anchor_state_root = anchor_state.hash_tree_root();
// Validate: original must be zero (genesis) or match computed (checkpoint sync)
assert!(
original_state_root == H256::ZERO || original_state_root == anchor_state_root,
"anchor header state_root mismatch: expected {anchor_state_root:?}, got {original_state_root:?}"
);
// Populate the correct state_root
anchor_state.latest_block_header.state_root = anchor_state_root;
let anchor_block_root = anchor_state.latest_block_header.hash_tree_root();
let anchor_checkpoint = Checkpoint {
root: anchor_block_root,
slot: anchor_state.latest_block_header.slot,
};
// Insert initial data
{
let mut batch = backend.begin_write().expect("write batch");
// Metadata
let metadata_entries = vec![
(KEY_TIME.to_vec(), 0u64.to_ssz()),
(KEY_CONFIG.to_vec(), anchor_state.config.to_ssz()),
(KEY_HEAD.to_vec(), anchor_block_root.to_ssz()),
(KEY_SAFE_TARGET.to_vec(), anchor_block_root.to_ssz()),
(KEY_LATEST_JUSTIFIED.to_vec(), anchor_checkpoint.to_ssz()),
(KEY_LATEST_FINALIZED.to_vec(), anchor_checkpoint.to_ssz()),
];
batch
.put_batch(Table::Metadata, metadata_entries)
.expect("put metadata");
// Block header
let header_entries = vec![(
anchor_block_root.to_ssz(),
anchor_state.latest_block_header.to_ssz(),
)];
batch
.put_batch(Table::BlockHeaders, header_entries)
.expect("put block header");
batch
.put_batch(
Table::BlockRoots,
vec![(
encode_block_root_key(anchor_state.latest_block_header.slot),
anchor_block_root.to_ssz(),
)],
)
.expect("put block root index");
// Block body (if provided)
if let Some(body) = anchor_body {
let body_entries = vec![(anchor_block_root.to_ssz(), body.to_ssz())];
batch
.put_batch(Table::BlockBodies, body_entries)
.expect("put block body");
}
// State snapshot. The anchor has no parent in the store, so it is
// the base of every diff chain: store it as a full snapshot in
// `States` (never pruned) so reconstruction always terminates here.
let state_entries = vec![(anchor_block_root.to_ssz(), anchor_state.to_ssz())];
batch
.put_batch(Table::States, state_entries)
.expect("put state");
// Live chain index
let index_entries = vec![(
encode_slot_root_key(anchor_state.latest_block_header.slot, &anchor_block_root),
anchor_state.latest_block_header.parent_root.to_ssz(),
)];
batch
.put_batch(Table::LiveChain, index_entries)
.expect("put live chain index");
batch.commit().expect("commit");
}
info!(%anchor_state_root, %anchor_block_root, "Initialized store");
Ok(Self {
backend,
config: anchor_state.config,
new_payloads: Arc::new(Mutex::new(PayloadBuffer::new(NEW_PAYLOAD_CAP))),
known_payloads: Arc::new(Mutex::new(PayloadBuffer::new(AGGREGATED_PAYLOAD_CAP))),
gossip_signatures: Arc::new(Mutex::new(GossipSignatureBuffer::new(
GOSSIP_SIGNATURE_CAP,
))),
state_cache: new_state_cache(),
})
}
// ============ Metadata Helpers ============
fn get_metadata<T: SszDecode>(&self, key: &[u8]) -> Result<T, Error> {
let view = self.backend.begin_read().expect("read view");
let bytes = view
.get(Table::Metadata, key)
.expect("get")
.expect("metadata key exists");
Ok(T::from_ssz_bytes(&bytes).expect("valid encoding"))
}
fn set_metadata<T: SszEncode>(&self, key: &[u8], value: &T) -> Result<(), Error> {
let mut batch = self.backend.begin_write().expect("write batch");
batch
.put_batch(Table::Metadata, vec![(key.to_vec(), value.to_ssz())])
.expect("put metadata");
batch.commit().expect("commit");
Ok(())
}
// ============ Time ============
/// Returns the current store time in interval counts since genesis.
///
/// Each increment represents one 800ms interval. Use [`Self::current_slot`]
/// for the slot; the interval within it is `time() % INTERVALS_PER_SLOT`.
pub fn time(&self) -> Result<u64, Error> {
self.get_metadata(KEY_TIME)
}
/// Sets the current store time.
pub fn set_time(&mut self, time: u64) -> Result<(), Error> {
self.set_metadata(KEY_TIME, &time)
}
/// The current slot, derived from the store clock.
pub fn current_slot(&self) -> u64 {
self.time().expect("store time exists") / INTERVALS_PER_SLOT
}
// ============ Config ============
/// Returns the chain configuration.
///
/// Infallible: the config is fixed at bootstrap and cached in the `Store`,
/// so this never reads the backend.
pub fn config(&self) -> &ChainConfig {
&self.config
}
// ============ Head ============
/// Returns the current head block root.
pub fn head(&self) -> Result<H256, Error> {
self.get_metadata(KEY_HEAD)
}
// ============ Safe Target ============
/// Returns the safe target block root for attestations.
pub fn safe_target(&self) -> Result<H256, Error> {
self.get_metadata(KEY_SAFE_TARGET)
}
/// Sets the safe target block root.
pub fn set_safe_target(&mut self, safe_target: H256) -> Result<(), Error> {
self.set_metadata(KEY_SAFE_TARGET, &safe_target)
}
// ============ Checkpoints ============
/// Returns the latest justified checkpoint.
pub fn latest_justified(&self) -> Result<Checkpoint, Error> {
self.get_metadata(KEY_LATEST_JUSTIFIED)
}
/// Returns the latest finalized checkpoint.
pub fn latest_finalized(&self) -> Result<Checkpoint, Error> {
self.get_metadata(KEY_LATEST_FINALIZED)
}
// ============ Checkpoint Updates ============
/// Updates head, justified, and finalized checkpoints.
///
/// - Head is always updated to the new value.
/// - Justified is updated if provided.
/// - Finalized is updated if provided.
///
/// When finalization advances, prunes the LiveChain index.
pub fn update_checkpoints(&mut self, checkpoints: ForkCheckpoints) -> Result<(), Error> {
// Read old finalized slot before updating metadata
let old_finalized_slot = self.latest_finalized()?.slot;
let old_head = self.head()?;
let (block_root_deletes, block_root_entries) =
self.block_root_index_changes(old_head, checkpoints.head)?;
let mut entries = vec![(KEY_HEAD.to_vec(), checkpoints.head.to_ssz())];
if let Some(justified) = checkpoints.justified {
entries.push((KEY_LATEST_JUSTIFIED.to_vec(), justified.to_ssz()));
}
if let Some(finalized) = checkpoints.finalized {
entries.push((KEY_LATEST_FINALIZED.to_vec(), finalized.to_ssz()));
}
let mut batch = self.backend.begin_write().expect("write batch");
batch.put_batch(Table::Metadata, entries).expect("put");
batch
.delete_batch(Table::BlockRoots, block_root_deletes)
.expect("delete old canonical block roots");
batch
.put_batch(Table::BlockRoots, block_root_entries)
.expect("put canonical block roots");
batch.commit().expect("commit");
// Lightweight pruning that should happen immediately on finalization advance:
// live chain index, signatures, and attestation data. These are cheap and
// affect fork choice correctness (live chain) or attestation processing.
// Heavy state/block pruning is deferred to prune_old_data().
if let Some(finalized) = checkpoints.finalized
&& finalized.slot > old_finalized_slot
{
let pruned_chain = self
.prune_live_chain(finalized.slot)
.expect("prune live chain");
let pruned_sigs = self.prune_gossip_signatures(finalized.slot);
let pruned_payloads = self.prune_stale_aggregated_payloads(finalized.slot);
if pruned_chain > 0 || pruned_sigs > 0 || pruned_payloads > 0 {
info!(
finalized_slot = finalized.slot,
pruned_chain, pruned_sigs, pruned_payloads, "Pruned finalized data"
);
}
}
Ok(())
}
/// Prune finalized block proofs to keep proof storage bounded.
///
/// State diffs, block headers, block bodies, and full-state snapshots are
/// all retained for the full history and are never pruned. Only proofs
/// of finalized blocks older than the pruning window are removed.
///
/// This is separated from `update_checkpoints` so callers can defer heavy
/// pruning until after a batch of blocks has been fully processed.
pub fn prune_old_data(&mut self) -> Result<(), Error> {
let finalized_slot = self
.latest_finalized()
.expect("Failed to get latest finalized checkpoint")
.slot;
let tip_slot = self
.get_block_header(&self.head().expect("Failed to get head block root"))
.map_or(finalized_slot, |header| {
header.expect("Failed to get block header").slot
});
let pruned_below_slot = self
.prune_old_block_proofs(finalized_slot, tip_slot)
.expect("prune old block proofs");
if pruned_below_slot > 0 {
info!(pruned_below_slot, "Pruned old finalized block proofs");
}
Ok(())
}
// ============ Blocks ============
/// `BlockRoots` index diff between the branch ending at `old_root` and the one
/// ending at `new_root`: slot keys to delete (canonical only on the old branch)
/// and slot -> root entries to write (canonical on the new branch).
///
/// Both branches must be walkable down to their common ancestor. A root with no
/// header, genesis' zero parent included, means they have none in common, and
/// yields [`Error::UnexpectedMissingBlockHeader`] instead of a partial diff.
fn block_root_index_changes(
&self,
mut old_root: H256,
mut new_root: H256,
) -> Result<BlockRootIndexChanges, Error> {
let mut deletes = Vec::new();
let mut entries = Vec::new();
let mut old_header = self
.get_block_header(&old_root)?
.ok_or(Error::UnexpectedMissingBlockHeader(old_root))?;
let mut new_header = self
.get_block_header(&new_root)?
.ok_or(Error::UnexpectedMissingBlockHeader(new_root))?;
// Walk both branches back toward their common ancestor, until we find the common ancestor.
while old_root != new_root {
if old_header.slot < new_header.slot {
entries.push((encode_block_root_key(new_header.slot), new_root.to_ssz()));
new_root = new_header.parent_root;
new_header = self
.get_block_header(&new_root)?
.ok_or(Error::UnexpectedMissingBlockHeader(new_root))?;
} else {
deletes.push(encode_block_root_key(old_header.slot));
old_root = old_header.parent_root;
old_header = self