-
Notifications
You must be signed in to change notification settings - Fork 250
/
blockchain_dag.nim
2894 lines (2436 loc) · 109 KB
/
blockchain_dag.nim
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
# beacon_chain
# Copyright (c) 2018-2024 Status Research & Development GmbH
# Licensed and distributed under either of
# * MIT license (license terms in the root directory or at https://opensource.org/licenses/MIT).
# * Apache v2 license (license terms in the root directory or at https://www.apache.org/licenses/LICENSE-2.0).
# at your option. This file may not be copied, modified, or distributed except according to those terms.
{.push raises: [].}
import
std/[algorithm, sequtils, tables, sets],
stew/[arrayops, assign2, byteutils],
chronos, metrics, results, snappy, chronicles,
../spec/[beaconstate, eth2_merkleization, eth2_ssz_serialization, helpers,
state_transition, validator],
../spec/forks,
".."/[beacon_chain_db, beacon_clock, era_db],
"."/[block_pools_types, block_quarantine]
export
eth2_merkleization, eth2_ssz_serialization,
block_pools_types, results, beacon_chain_db
logScope: topics = "chaindag"
# https://github.com/ethereum/beacon-metrics/blob/master/metrics.md#interop-metrics
declareGauge beacon_head_root, "Root of the head block of the beacon chain"
declareGauge beacon_head_slot, "Slot of the head block of the beacon chain"
# https://github.com/ethereum/beacon-metrics/blob/master/metrics.md#interop-metrics
declareGauge beacon_finalized_epoch, "Current finalized epoch" # On epoch transition
declareGauge beacon_finalized_root, "Current finalized root" # On epoch transition
declareGauge beacon_current_justified_epoch, "Current justified epoch" # On epoch transition
declareGauge beacon_current_justified_root, "Current justified root" # On epoch transition
declareGauge beacon_previous_justified_epoch, "Current previously justified epoch" # On epoch transition
declareGauge beacon_previous_justified_root, "Current previously justified root" # On epoch transition
declareGauge beacon_reorgs_total_total, "Total occurrences of reorganizations of the chain" # On fork choice; backwards-compat name (used to be a counter)
declareGauge beacon_reorgs_total, "Total occurrences of reorganizations of the chain" # Interop copy
declareCounter beacon_state_data_cache_hits, "EpochRef hits"
declareCounter beacon_state_data_cache_misses, "EpochRef misses"
declareCounter beacon_state_rewinds, "State database rewinds"
declareGauge beacon_active_validators, "Number of validators in the active validator set"
declareGauge beacon_current_active_validators, "Number of validators in the active validator set" # Interop copy
declareGauge beacon_pending_deposits, "Number of pending deposits (state.eth1_data.deposit_count - state.eth1_deposit_index)" # On block
declareGauge beacon_processed_deposits_total, "Number of total deposits included on chain" # On block
declareCounter beacon_dag_state_replay_seconds, "Time spent replaying states"
const
EPOCHS_PER_STATE_SNAPSHOT* = 32
## When finality happens, we prune historical states from the database except
## for a snapshot every 32 epochs from which replays can happen - there's a
## balance here between making long replays and saving on disk space
MAX_SLOTS_PER_PRUNE* = SLOTS_PER_EPOCH
## We prune the database incrementally so as not to introduce long
## processing breaks - this number is the maximum number of blocks we allow
## to be pruned every time the prune call is made (once per slot typically)
## unless head is moving faster (ie during sync)
proc putBlock*(
dag: ChainDAGRef, signedBlock: ForkyTrustedSignedBeaconBlock) =
dag.db.putBlock(signedBlock)
proc updateState*(
dag: ChainDAGRef, state: var ForkedHashedBeaconState, bsi: BlockSlotId,
save: bool, cache: var StateCache,
updateFlags: UpdateFlags): bool {.gcsafe.}
template withUpdatedState*(
dag: ChainDAGRef, stateParam: var ForkedHashedBeaconState,
bsiParam: BlockSlotId, okBody: untyped, failureBody: untyped): untyped =
## Helper template that updates stateData to a particular BlockSlot - usage of
## stateData is unsafe outside of block, or across `await` boundaries
block:
let bsi {.inject.} = bsiParam
var cache {.inject.} = StateCache()
if updateState(dag, stateParam, bsi, false, cache, dag.updateFlags):
template bid(): BlockId {.inject, used.} = bsi.bid
template updatedState(): ForkedHashedBeaconState {.inject, used.} = stateParam
okBody
else:
failureBody
func get_effective_balances(
validators: openArray[Validator], epoch: Epoch): seq[Gwei] =
## Get the balances from a state as counted for fork choice
result.newSeq(validators.len) # zero-init
for i in 0 ..< result.len:
# All non-active validators have a 0 balance
let validator = unsafeAddr validators[i]
if validator[].is_active_validator(epoch) and not validator[].slashed:
result[i] = validator[].effective_balance
proc updateValidatorKeys*(dag: ChainDAGRef, validators: openArray[Validator]) =
# Update validator key cache - must be called every time a valid block is
# applied to the state - this is important to ensure that when we sync blocks
# without storing a state (non-epoch blocks essentially), the deposits from
# those blocks are persisted to the in-database cache of immutable validator
# data (but no earlier than that the whole block as been validated)
dag.db.updateImmutableValidators(validators)
proc updateFinalizedBlocks*(db: BeaconChainDB, newFinalized: openArray[BlockId]) =
if db.db.readOnly: return # TODO abstraction leak - where to put this?
db.withManyWrites:
for bid in newFinalized:
db.finalizedBlocks.insert(bid.slot, bid.root)
proc updateFrontfillBlocks*(dag: ChainDAGRef) =
# When backfilling is done and manages to reach the frontfill point, we can
# write the frontfill index knowing that the block information in the
# era files match the chain
if dag.db.db.readOnly: return # TODO abstraction leak - where to put this?
if dag.frontfillBlocks.len == 0 or dag.backfill.slot > GENESIS_SLOT:
return
info "Writing frontfill index", slots = dag.frontfillBlocks.len
dag.db.withManyWrites:
let low = dag.db.finalizedBlocks.low.expect(
"wrote at least tailRef during init")
let blocks = min(low.int, dag.frontfillBlocks.len - 1)
var parent: Eth2Digest
for i in 0..blocks:
let root = dag.frontfillBlocks[i]
if not isZero(root):
dag.db.finalizedBlocks.insert(Slot(i), root)
dag.db.putBeaconBlockSummary(
root, BeaconBlockSummary(slot: Slot(i), parent_root: parent))
parent = root
reset(dag.frontfillBlocks)
func validatorKey*(
dag: ChainDAGRef, index: ValidatorIndex or uint64): Opt[CookedPubKey] =
## Returns the validator pubkey for the index, assuming it's been observed
## at any point in time - this function may return pubkeys for indicies that
## are not (yet) part of the head state (if the key has been observed on a
## non-head branch)!
dag.db.immutableValidators.load(index)
template is_merge_transition_complete*(
stateParam: ForkedHashedBeaconState): bool =
withState(stateParam):
when consensusFork >= ConsensusFork.Bellatrix:
is_merge_transition_complete(forkyState.data)
else:
false
func effective_balances*(epochRef: EpochRef): seq[Gwei] =
try:
SSZ.decode(snappy.decode(epochRef.effective_balances_bytes, uint32.high),
List[Gwei, Limit VALIDATOR_REGISTRY_LIMIT]).toSeq()
except CatchableError as exc:
raiseAssert exc.msg
func getBlockRef*(dag: ChainDAGRef, root: Eth2Digest): Opt[BlockRef] =
## Retrieve a resolved block reference, if available - this function does
## not return historical finalized blocks, see `getBlockIdAtSlot` for a
## function that covers the entire known history
let key = KeyedBlockRef.asLookupKey(root)
# HashSet lacks the api to do check-and-get in one lookup - `[]` will return
# the copy of the instance in the set which has more fields than `root` set!
if key in dag.forkBlocks:
try: ok(dag.forkBlocks[key].blockRef())
except KeyError: raiseAssert "contains"
else:
err()
func getBlockIdAtSlot*(
state: ForkyHashedBeaconState, slot: Slot): Opt[BlockSlotId] =
## Use given state to attempt to find a historical `BlockSlotId`.
if slot > state.data.slot:
return Opt.none(BlockSlotId) # State does not know about requested slot
if state.data.slot > slot + SLOTS_PER_HISTORICAL_ROOT:
return Opt.none(BlockSlotId) # Cache has expired
var idx = slot mod SLOTS_PER_HISTORICAL_ROOT
let root =
if slot == state.data.slot:
state.latest_block_root
else:
state.data.block_roots[idx]
var bid = BlockId(slot: slot, root: root)
let availableSlots =
min(slot.uint64, slot + SLOTS_PER_HISTORICAL_ROOT - state.data.slot)
for i in 0 ..< availableSlots:
if idx == 0:
idx = SLOTS_PER_HISTORICAL_ROOT
dec idx
if state.data.block_roots[idx] != root:
return Opt.some BlockSlotId.init(bid, slot)
dec bid.slot
if bid.slot == GENESIS_SLOT:
return Opt.some BlockSlotId.init(bid, slot)
Opt.none(BlockSlotId) # Unknown if there are more empty slots before
func getBlockIdAtSlot*(dag: ChainDAGRef, slot: Slot): Opt[BlockSlotId] =
## Retrieve the canonical block at the given slot, or the last block that
## comes before - similar to atSlot, but without the linear scan - may hit
## the database to look up early indices.
if slot > dag.finalizedHead.slot:
return dag.head.atSlot(slot).toBlockSlotId() # iterate to the given slot
if dag.finalizedHead.blck == nil:
# Not initialized yet (in init)
return Opt.none(BlockSlotId)
if slot >= dag.finalizedHead.blck.slot:
# finalized head is still in memory
return dag.finalizedHead.blck.atSlot(slot).toBlockSlotId()
# Load from memory, if the block ID is sufficiently recent.
# For checkpoint sync, this is the only available of historical block IDs
# until sufficient blocks have been backfilled.
template tryWithState(state: ForkedHashedBeaconState) =
block:
withState(state):
# State must be a descendent of the finalized chain to be viable
let finBsi = forkyState.getBlockIdAtSlot(dag.finalizedHead.slot)
if finBsi.isSome and # DAG finalized bid slot wrong if CP not @ epoch
finBsi.unsafeGet.bid.root == dag.finalizedHead.blck.bid.root:
let bsi = forkyState.getBlockIdAtSlot(slot)
if bsi.isSome:
return bsi
tryWithState dag.headState
tryWithState dag.epochRefState
tryWithState dag.clearanceState
# Fallback to database, this only works for backfilled blocks
let finlow = dag.db.finalizedBlocks.low.expect("at least tailRef written")
if slot >= finlow:
var pos = slot
while true:
let root = dag.db.finalizedBlocks.get(pos)
if root.isSome():
return ok BlockSlotId.init(
BlockId(root: root.get(), slot: pos), slot)
doAssert pos > finlow, "We should have returned the finlow"
pos = pos - 1
if slot == GENESIS_SLOT and dag.genesis.isSome():
return ok dag.genesis.get().atSlot()
err() # not backfilled yet
proc containsBlock(
cfg: RuntimeConfig, db: BeaconChainDB, slot: Slot, root: Eth2Digest): bool =
db.containsBlock(root, cfg.consensusForkAtEpoch(slot.epoch))
proc containsBlock*(dag: ChainDAGRef, bid: BlockId): bool =
dag.cfg.containsBlock(dag.db, bid.slot, bid.root)
proc getForkedBlock*(db: BeaconChainDB, root: Eth2Digest):
Opt[ForkedTrustedSignedBeaconBlock] =
# When we only have a digest, we don't know which fork it's from so we try
# them one by one - this should be used sparingly
static: doAssert high(ConsensusFork) == ConsensusFork.Fulu
if (let blck = db.getBlock(root, fulu.TrustedSignedBeaconBlock);
blck.isSome()):
ok(ForkedTrustedSignedBeaconBlock.init(blck.get()))
elif (let blck = db.getBlock(root, electra.TrustedSignedBeaconBlock);
blck.isSome()):
ok(ForkedTrustedSignedBeaconBlock.init(blck.get()))
elif (let blck = db.getBlock(root, deneb.TrustedSignedBeaconBlock);
blck.isSome()):
ok(ForkedTrustedSignedBeaconBlock.init(blck.get()))
elif (let blck = db.getBlock(root, capella.TrustedSignedBeaconBlock);
blck.isSome()):
ok(ForkedTrustedSignedBeaconBlock.init(blck.get()))
elif (let blck = db.getBlock(root, bellatrix.TrustedSignedBeaconBlock);
blck.isSome()):
ok(ForkedTrustedSignedBeaconBlock.init(blck.get()))
elif (let blck = db.getBlock(root, altair.TrustedSignedBeaconBlock);
blck.isSome()):
ok(ForkedTrustedSignedBeaconBlock.init(blck.get()))
elif (let blck = db.getBlock(root, phase0.TrustedSignedBeaconBlock);
blck.isSome()):
ok(ForkedTrustedSignedBeaconBlock.init(blck.get()))
else:
err()
proc getBlock*(
dag: ChainDAGRef, bid: BlockId,
T: type ForkyTrustedSignedBeaconBlock): Opt[T] =
dag.db.getBlock(bid.root, T) or
getBlock(
dag.era, getStateField(dag.headState, historical_roots).asSeq,
dag.headState.historical_summaries().asSeq,
bid.slot, Opt[Eth2Digest].ok(bid.root), T)
proc getBlockSSZ*(dag: ChainDAGRef, bid: BlockId, bytes: var seq[byte]): bool =
# Load the SSZ-encoded data of a block into `bytes`, overwriting the existing
# content
let fork = dag.cfg.consensusForkAtEpoch(bid.slot.epoch)
dag.db.getBlockSSZ(bid.root, bytes, fork) or
(bid.slot <= dag.finalizedHead.slot and
getBlockSSZ(
dag.era, getStateField(dag.headState, historical_roots).asSeq,
dag.headState.historical_summaries().asSeq,
bid.slot, bytes).isOk() and bytes.len > 0)
proc getBlockSZ*(dag: ChainDAGRef, bid: BlockId, bytes: var seq[byte]): bool =
# Load the snappy-frame-compressed ("SZ") SSZ-encoded data of a block into
# `bytes`, overwriting the existing content
# careful: there are two snappy encodings in use, with and without framing!
# Returns true if the block is found, false if not
let fork = dag.cfg.consensusForkAtEpoch(bid.slot.epoch)
dag.db.getBlockSZ(bid.root, bytes, fork) or
(bid.slot <= dag.finalizedHead.slot and
getBlockSZ(
dag.era, getStateField(dag.headState, historical_roots).asSeq,
dag.headState.historical_summaries().asSeq,
bid.slot, bytes).isOk and bytes.len > 0)
proc getForkedBlock*(
dag: ChainDAGRef, bid: BlockId): Opt[ForkedTrustedSignedBeaconBlock] =
let fork = dag.cfg.consensusForkAtEpoch(bid.slot.epoch)
result.ok(ForkedTrustedSignedBeaconBlock(kind: fork))
withBlck(result.get()):
type T = type(forkyBlck)
forkyBlck = getBlock(dag, bid, T).valueOr:
getBlock(
dag.era, getStateField(dag.headState, historical_roots).asSeq,
dag.headState.historical_summaries().asSeq,
bid.slot, Opt[Eth2Digest].ok(bid.root), T).valueOr:
result.err()
return
proc getBlockId*(db: BeaconChainDB, root: Eth2Digest): Opt[BlockId] =
block: # We might have a summary in the database
let summary = db.getBeaconBlockSummary(root)
if summary.isOk():
return ok(BlockId(root: root, slot: summary.get().slot))
block:
# We might have a block without having written a summary - this can happen
# if there was a crash between writing the block and writing the summary,
# specially in databases written by older nimbus versions
let forked = db.getForkedBlock(root)
if forked.isSome():
# Shouldn't happen too often but..
let
blck = forked.get()
summary = withBlck(blck): forkyBlck.message.toBeaconBlockSummary()
debug "Writing summary", blck = shortLog(blck)
db.putBeaconBlockSummary(root, summary)
return ok(BlockId(root: root, slot: summary.slot))
err()
proc getBlockId*(dag: ChainDAGRef, root: Eth2Digest): Opt[BlockId] =
## Look up block id by root in history - useful for turning a root into a
## slot - may hit the database, may return blocks that have since become
## unviable - use `getBlockIdAtSlot` to check that the block is still viable
## if used in a sensitive context
block: # If we have a BlockRef, this is the fastest way to get a block id
let blck = dag.getBlockRef(root)
if blck.isOk():
return ok(blck.get().bid)
dag.db.getBlockId(root)
proc getForkedBlock*(
dag: ChainDAGRef, root: Eth2Digest): Opt[ForkedTrustedSignedBeaconBlock] =
let bid = dag.getBlockId(root)
if bid.isSome():
dag.getForkedBlock(bid.get())
else:
# In case we didn't have a summary - should be rare, but ..
dag.db.getForkedBlock(root)
func isCanonical*(dag: ChainDAGRef, bid: BlockId): bool =
## Returns `true` if the given `bid` is part of the history selected by
## `dag.head`.
let current = dag.getBlockIdAtSlot(bid.slot).valueOr:
return false # We don't know, so ..
return current.bid == bid
func isFinalized*(dag: ChainDAGRef, bid: BlockId): bool =
## Returns `true` if the given `bid` is part of the finalized history
## selected by `dag.finalizedHead`.
dag.isCanonical(bid) and (bid.slot <= dag.finalizedHead.slot)
func parent*(dag: ChainDAGRef, bid: BlockId): Opt[BlockId] =
if bid.slot == 0:
return err()
if bid.slot > dag.finalizedHead.slot:
# Make sure we follow the correct history as there may be forks
let blck = ? dag.getBlockRef(bid.root)
doAssert not isNil(blck.parent), "should reach finalized head"
return ok blck.parent.bid
let bids = ? dag.getBlockIdAtSlot(bid.slot - 1)
ok(bids.bid)
func parentOrSlot*(dag: ChainDAGRef, bsi: BlockSlotId): Opt[BlockSlotId] =
if bsi.slot == 0:
return err()
if bsi.isProposed:
let parent = ? dag.parent(bsi.bid)
ok BlockSlotId.init(parent, bsi.slot)
else:
ok BlockSlotId.init(bsi.bid, bsi.slot - 1)
func atSlot*(dag: ChainDAGRef, bid: BlockId, slot: Slot): Opt[BlockSlotId] =
if bid.slot > dag.finalizedHead.slot:
let blck = ? dag.getBlockRef(bid.root)
if slot > dag.finalizedHead.slot:
return blck.atSlot(slot).toBlockSlotId()
else:
# Check if the given `bid` is still part of history - it might hail from an
# orphaned fork
let existing = ? dag.getBlockIdAtSlot(bid.slot)
if existing.bid != bid:
return err() # Not part of known / relevant history
if existing.slot == slot: # and bid.slot == slot
return ok existing
if bid.slot <= slot:
ok BlockSlotId.init(bid, slot)
else:
dag.getBlockIdAtSlot(slot)
func nextTimestamp[I, T](cache: var LRUCache[I, T]): uint32 =
if cache.timestamp == uint32.high:
for i in 0 ..< I:
template e: untyped = cache.entries[i]
if e.lastUsed != 0:
e.lastUsed = 1
cache.timestamp = 1
inc cache.timestamp
cache.timestamp
template peekIt[I, T](cache: var LRUCache[I, T], predicate: untyped): Opt[T] =
block:
var res: Opt[T]
for i in 0 ..< I:
template e: untyped = cache.entries[i]
template it: untyped {.inject, used.} = e.value
if e.lastUsed != 0 and predicate:
res.ok it
break
res
template findIt[I, T](cache: var LRUCache[I, T], predicate: untyped): Opt[T] =
block:
var res: Opt[T]
for i in 0 ..< I:
template e: untyped = cache.entries[i]
template it: untyped {.inject, used.} = e.value
if e.lastUsed != 0 and predicate:
e.lastUsed = cache.nextTimestamp
res.ok it
break
res
template delIt[I, T](cache: var LRUCache[I, T], predicate: untyped) =
block:
for i in 0 ..< I:
template e: untyped = cache.entries[i]
template it: untyped {.inject, used.} = e.value
if e.lastUsed != 0 and predicate:
e.reset()
func put[I, T](cache: var LRUCache[I, T], value: T) =
var lru = 0
block:
var min = uint32.high
for i in 0 ..< I:
template e: untyped = cache.entries[i]
if e.lastUsed < min:
min = e.lastUsed
lru = i
if min == 0:
break
template e: untyped = cache.entries[lru]
e.value = value
e.lastUsed = cache.nextTimestamp
func epochAncestor(dag: ChainDAGRef, bid: BlockId, epoch: Epoch):
Opt[BlockSlotId] =
## The epoch ancestor is the last block that has an effect on the epoch-
## related state data, as updated in `process_epoch` - this block determines
## effective balances, validator addtions and removals etc and serves as a
## base for `EpochRef` construction.
if epoch < dag.tail.slot.epoch or bid.slot < dag.tail.slot:
# Not enough information in database to meaningfully process pre-tail epochs
return Opt.none BlockSlotId
let
dependentSlot =
if epoch == dag.tail.slot.epoch:
# Use the tail as "dependent block" - this may be the genesis block, or,
# in the case of checkpoint sync, the checkpoint block
dag.tail.slot
else:
epoch.start_slot() - 1
bsi = ? dag.atSlot(bid, dependentSlot)
epochSlot =
if epoch == dag.tail.slot.epoch:
dag.tail.slot
else:
epoch.start_slot()
ok BlockSlotId(bid: bsi.bid, slot: epochSlot)
func epochKey(dag: ChainDAGRef, bid: BlockId, epoch: Epoch): Opt[EpochKey] =
## The state transition works by storing information from blocks in a
## "working" area until the epoch transition, then batching work collected
## during the epoch. Thus, last block in the ancestor epochs is the block
## that has an impact on epoch currently considered.
##
## This function returns an epoch key pointing to that epoch boundary, i.e. the
## boundary where the last block has been applied to the state and epoch
## processing has been done.
let bsi = dag.epochAncestor(bid, epoch).valueOr:
return Opt.none(EpochKey)
Opt.some(EpochKey(bid: bsi.bid, epoch: epoch))
func putShufflingRef*(dag: ChainDAGRef, shufflingRef: ShufflingRef) =
## Store shuffling in the cache
if shufflingRef.epoch < dag.finalizedHead.slot.epoch():
# Only cache epoch information for unfinalized blocks - earlier states
# are seldomly used (ie RPC), so no need to cache
return
dag.shufflingRefs.put shufflingRef
func findShufflingRef*(
dag: ChainDAGRef, bid: BlockId, epoch: Epoch): Opt[ShufflingRef] =
## Lookup a shuffling in the cache, returning `none` if it's not present - see
## `getShufflingRef` for a version that creates a new instance if it's missing
let
dependent_slot = epoch.attester_dependent_slot()
dependent_bsi = ? dag.atSlot(bid, dependent_slot)
# Check `ShufflingRef` cache
let shufflingRef = dag.shufflingRefs.findIt(
it.epoch == epoch and it.attester_dependent_root == dependent_bsi.bid.root)
if shufflingRef.isOk:
return shufflingRef
# Check `EpochRef` cache
let epochRef = dag.epochRefs.peekIt(
it.shufflingRef.epoch == epoch and
it.shufflingRef.attester_dependent_root == dependent_bsi.bid.root)
if epochRef.isOk:
dag.putShufflingRef(epochRef.get.shufflingRef)
return ok epochRef.get.shufflingRef
err()
func findEpochRef*(
dag: ChainDAGRef, bid: BlockId, epoch: Epoch): Opt[EpochRef] =
## Lookup an EpochRef in the cache, returning `none` if it's not present - see
## `getEpochRef` for a version that creates a new instance if it's missing
let key = ? dag.epochKey(bid, epoch)
dag.epochRefs.findIt(it.key == key)
func putEpochRef(dag: ChainDAGRef, epochRef: EpochRef) =
if epochRef.epoch < dag.finalizedHead.slot.epoch():
# Only cache epoch information for unfinalized blocks - earlier states
# are seldomly used (ie RPC), so no need to cache
return
dag.epochRefs.put epochRef
func init*(
T: type ShufflingRef, state: ForkedHashedBeaconState,
cache: var StateCache, epoch: Epoch): T =
let attester_dependent_root =
withState(state): forkyState.dependent_root(epoch.get_previous_epoch)
ShufflingRef(
epoch: epoch,
attester_dependent_root: attester_dependent_root,
shuffled_active_validator_indices:
cache.get_shuffled_active_validator_indices(state, epoch),
)
func init*(
T: type EpochRef, dag: ChainDAGRef, state: ForkedHashedBeaconState,
cache: var StateCache): T =
let
epoch = state.get_current_epoch()
proposer_dependent_root = withState(state):
forkyState.proposer_dependent_root
shufflingRef = dag.findShufflingRef(state.latest_block_id, epoch).valueOr:
let tmp = ShufflingRef.init(state, cache, epoch)
dag.putShufflingRef(tmp)
tmp
total_active_balance = withState(state):
get_total_active_balance(forkyState.data, cache)
epochRef = EpochRef(
key: dag.epochKey(state.latest_block_id, epoch).expect(
"Valid epoch ancestor when processing state"),
eth1_data:
getStateField(state, eth1_data),
eth1_deposit_index:
getStateField(state, eth1_deposit_index),
checkpoints:
FinalityCheckpoints(
justified: getStateField(state, current_justified_checkpoint),
finalized: getStateField(state, finalized_checkpoint)),
# beacon_proposers: Separately filled below
proposer_dependent_root: proposer_dependent_root,
shufflingRef: shufflingRef,
total_active_balance: total_active_balance
)
epochStart = epoch.start_slot()
for i in 0'u64..<SLOTS_PER_EPOCH:
epochRef.beacon_proposers[i] =
get_beacon_proposer_index(state, cache, epochStart + i)
# When fork choice runs, it will need the effective balance of the justified
# checkpoint - we pre-load the balances here to avoid rewinding the justified
# state later and compress them because not all checkpoints end up being used
# for fork choice - specially during long periods of non-finalization
func snappyEncode(inp: openArray[byte]): seq[byte] =
try:
snappy.encode(inp)
except CatchableError as err:
raiseAssert err.msg
epochRef.effective_balances_bytes =
snappyEncode(SSZ.encode(
List[Gwei, Limit VALIDATOR_REGISTRY_LIMIT](
get_effective_balances(getStateField(state, validators).asSeq, epoch))))
epochRef
func loadStateCache(
dag: ChainDAGRef, cache: var StateCache, bid: BlockId, epoch: Epoch) =
# When creating a state cache, we want the current and the previous epoch
# information to be preloaded as both of these are used in state transition
# functions
template load(e: Epoch) =
block:
let epoch = e
if epoch notin cache.shuffled_active_validator_indices:
let shufflingRef = dag.findShufflingRef(bid, epoch)
if shufflingRef.isSome():
cache.shuffled_active_validator_indices[epoch] =
shufflingRef[][].shuffled_active_validator_indices
let epochRef = dag.findEpochRef(bid, epoch)
if epochRef.isSome():
let start_slot = epoch.start_slot()
for i, idx in epochRef[][].beacon_proposers:
cache.beacon_proposer_indices[start_slot + i] = idx
cache.total_active_balance[epoch] = epochRef[][].total_active_balance
load(epoch)
if epoch > 0:
load(epoch - 1)
if dag.head != nil: # nil during init.. sigh
let period = dag.head.slot.sync_committee_period
if period == epoch.sync_committee_period and
period notin cache.sync_committees and
period > dag.cfg.ALTAIR_FORK_EPOCH.sync_committee_period():
# If the block we're aiming for shares ancestry with head, we can reuse
# the cached head committee - this accounts for most "live" cases like
# syncing and checking blocks since the committees rarely change
let periodBsi = dag.atSlot(bid, period.start_slot)
if periodBsi.isSome and periodBsi ==
dag.atSlot(dag.head.bid, period.start_slot):
# We often end up sharing sync committees with head during sync / gossip
# validation / head updates
cache.sync_committees[period] = dag.headSyncCommittees
func containsForkBlock*(dag: ChainDAGRef, root: Eth2Digest): bool =
## Checks for blocks at the finalized checkpoint or newer
KeyedBlockRef.asLookupKey(root) in dag.forkBlocks
func isFinalizedStateSnapshot(slot: Slot): bool =
slot.is_epoch and slot.epoch mod EPOCHS_PER_STATE_SNAPSHOT == 0
func isStateCheckpoint(dag: ChainDAGRef, bsi: BlockSlotId): bool =
## State checkpoints are the points in time for which we store full state
## snapshots, which later serve as rewind starting points when replaying state
## transitions from database, for example during reorgs.
##
# As a policy, we only store epoch boundary states without the epoch block
# (if it exists) applied - the rest can be reconstructed by loading an epoch
# boundary state and applying the missing blocks.
# We also avoid states that were produced with empty slots only - as such,
# there is only a checkpoint for the first epoch after a block.
# The tail block also counts as a state checkpoint!
(bsi.isProposed and bsi.bid == dag.tail) or
(bsi.slot.is_epoch and bsi.slot.epoch == (bsi.bid.slot.epoch + 1))
proc getState(
db: BeaconChainDB, cfg: RuntimeConfig, block_root: Eth2Digest, slot: Slot,
state: var ForkedHashedBeaconState, rollback: RollbackProc): bool =
let state_root = db.getStateRoot(block_root, slot).valueOr:
return false
db.getState(cfg.consensusForkAtEpoch(slot.epoch), state_root, state, rollback)
proc containsState*(
db: BeaconChainDB, cfg: RuntimeConfig, block_root: Eth2Digest,
slots: Slice[Slot], legacy = true): bool =
var slot = slots.b
while slot >= slots.a:
let state_root = db.getStateRoot(block_root, slot)
if state_root.isSome() and
db.containsState(
cfg.consensusForkAtEpoch(slot.epoch), state_root.get(), legacy):
return true
if slot == slots.a: # avoid underflow at genesis
break
slot -= 1
false
proc getState*(
db: BeaconChainDB, cfg: RuntimeConfig, block_root: Eth2Digest,
slots: Slice[Slot], state: var ForkedHashedBeaconState,
rollback: RollbackProc): bool =
var slot = slots.b
while slot >= slots.a:
let state_root = db.getStateRoot(block_root, slot)
if state_root.isSome() and
db.getState(
cfg.consensusForkAtEpoch(slot.epoch), state_root.get(), state,
rollback):
return true
if slot == slots.a: # avoid underflow at genesis
break
slot -= 1
false
proc getState(
dag: ChainDAGRef, bsi: BlockSlotId, state: var ForkedHashedBeaconState): bool =
## Load a state from the database given a block and a slot - this will first
## lookup the state root in the state root table then load the corresponding
## state, if it exists
if not dag.isStateCheckpoint(bsi):
return false
let rollbackAddr =
# Any restore point will do as long as it's not the object being updated
if unsafeAddr(state) == unsafeAddr(dag.headState):
unsafeAddr dag.clearanceState
else:
unsafeAddr dag.headState
let v = addr state
func rollback() =
assign(v[], rollbackAddr[])
dag.db.getState(dag.cfg, bsi.bid.root, bsi.slot, state, rollback)
proc getStateByParent(
dag: ChainDAGRef, bid: BlockId, state: var ForkedHashedBeaconState): bool =
## Try to load the state referenced by the parent of the given `bid` - this
## state can be used to advance to the `bid` state itself.
let slot = bid.slot
let
summary = dag.db.getBeaconBlockSummary(bid.root).valueOr:
return false
parentMinSlot =
dag.db.getBeaconBlockSummary(summary.parent_root).
map(proc(x: auto): auto = x.slot).valueOr:
# in the cases that we don't have slot information, we'll search for the
# state for a few back from the `bid` slot - if there are gaps of empty
# slots larger than this, we will not be able to load the state using this
# trick
if slot.uint64 >= (EPOCHS_PER_STATE_SNAPSHOT * 2) * SLOTS_PER_EPOCH:
slot - (EPOCHS_PER_STATE_SNAPSHOT * 2) * SLOTS_PER_EPOCH
else:
Slot(0)
let rollbackAddr =
# Any restore point will do as long as it's not the object being updated
if unsafeAddr(state) == unsafeAddr(dag.headState):
unsafeAddr dag.clearanceState
else:
unsafeAddr dag.headState
let v = addr state
func rollback() =
assign(v[], rollbackAddr[])
dag.db.getState(
dag.cfg, summary.parent_root, parentMinSlot..slot, state, rollback)
proc getNearbyState(
dag: ChainDAGRef, state: var ForkedHashedBeaconState, bid: BlockId,
lowSlot: Slot): Opt[void] =
## Load state from DB that is close to `bid` and has at least slot `lowSlot`.
var
e = bid.slot.epoch
b = bid
while true:
let stateSlot = e.start_slot
if stateSlot < lowSlot:
return err()
b = (? dag.atSlot(b, max(stateSlot, 1.Slot) - 1)).bid
let bsi = BlockSlotId.init(b, stateSlot)
if not dag.getState(bsi, state):
if e == GENESIS_EPOCH:
return err()
dec e
continue
return ok()
proc currentSyncCommitteeForPeriod*(
dag: ChainDAGRef,
tmpState: var ForkedHashedBeaconState,
period: SyncCommitteePeriod): Opt[SyncCommittee] =
## Fetch a `SyncCommittee` for a given sync committee period.
## For non-finalized periods, follow the chain as selected by fork choice.
let lowSlot = max(dag.tail.slot, dag.cfg.ALTAIR_FORK_EPOCH.start_slot)
if period < lowSlot.sync_committee_period:
return err()
let
periodStartSlot = period.start_slot
syncCommitteeSlot = max(periodStartSlot, lowSlot)
bsi = ? dag.getBlockIdAtSlot(syncCommitteeSlot)
dag.withUpdatedState(tmpState, bsi) do:
withState(updatedState):
when consensusFork >= ConsensusFork.Altair:
ok forkyState.data.current_sync_committee
else: err()
do: err()
proc getBlockIdAtSlot*(
dag: ChainDAGRef, state: ForkyHashedBeaconState, slot: Slot): Opt[BlockId] =
if slot >= state.data.slot:
Opt.some state.latest_block_id
elif state.data.slot <= slot + SLOTS_PER_HISTORICAL_ROOT:
dag.getBlockId(state.data.get_block_root_at_slot(slot))
else:
Opt.none(BlockId)
proc updateBeaconMetrics(
state: ForkedHashedBeaconState, bid: BlockId, cache: var StateCache) =
# https://github.com/ethereum/beacon-metrics/blob/master/metrics.md#additional-metrics
# both non-negative, so difference can't overflow or underflow int64
beacon_head_root.set(bid.root.toGaugeValue)
beacon_head_slot.set(bid.slot.toGaugeValue)
withState(state):
beacon_pending_deposits.set(
(forkyState.data.eth1_data.deposit_count -
forkyState.data.eth1_deposit_index).toGaugeValue)
beacon_processed_deposits_total.set(
forkyState.data.eth1_deposit_index.toGaugeValue)
beacon_current_justified_epoch.set(
forkyState.data.current_justified_checkpoint.epoch.toGaugeValue)
beacon_current_justified_root.set(
forkyState.data.current_justified_checkpoint.root.toGaugeValue)
beacon_previous_justified_epoch.set(
forkyState.data.previous_justified_checkpoint.epoch.toGaugeValue)
beacon_previous_justified_root.set(
forkyState.data.previous_justified_checkpoint.root.toGaugeValue)
beacon_finalized_epoch.set(
forkyState.data.finalized_checkpoint.epoch.toGaugeValue)
beacon_finalized_root.set(
forkyState.data.finalized_checkpoint.root.toGaugeValue)
let active_validators = count_active_validators(
forkyState.data, forkyState.data.slot.epoch, cache).toGaugeValue
beacon_active_validators.set(active_validators)
beacon_current_active_validators.set(active_validators)
import blockchain_dag_light_client
export
blockchain_dag_light_client.getLightClientBootstrap,
blockchain_dag_light_client.getLightClientUpdateForPeriod,
blockchain_dag_light_client.getLightClientFinalityUpdate,
blockchain_dag_light_client.getLightClientOptimisticUpdate
proc putState(dag: ChainDAGRef, state: ForkedHashedBeaconState, bid: BlockId) =
# Store a state and its root
let slot = getStateField(state, slot)
logScope:
blck = shortLog(bid)
stateSlot = shortLog(slot)
stateRoot = shortLog(getStateRoot(state))
if not dag.isStateCheckpoint(BlockSlotId.init(bid, slot)):
return
# Don't consider legacy tables here, they are slow to read so we'll want to
# rewrite things in the new table anyway.
if dag.db.containsState(
dag.cfg.consensusForkAtEpoch(slot.epoch), getStateRoot(state),
legacy = false):
return
let startTick = Moment.now()
# Ideally we would save the state and the root lookup cache in a single
# transaction to prevent database inconsistencies, but the state loading code
# is resilient against one or the other going missing
withState(state):
dag.db.putState(forkyState)
debug "Stored state", putStateDur = Moment.now() - startTick
proc advanceSlots*(
dag: ChainDAGRef, state: var ForkedHashedBeaconState, slot: Slot, save: bool,
cache: var StateCache, info: var ForkedEpochInfo,
updateFlags: UpdateFlags) =
# Given a state, advance it zero or more slots by applying empty slot
# processing - the state must be positioned at or before `slot`
doAssert getStateField(state, slot) <= slot
let stateBid = state.latest_block_id
while getStateField(state, slot) < slot:
let
preEpoch = getStateField(state, slot).epoch
loadStateCache(dag, cache, stateBid, getStateField(state, slot).epoch)
process_slots(
dag.cfg, state, getStateField(state, slot) + 1, cache, info,
updateFlags).expect("process_slots shouldn't fail when state slot is correct")
if save:
dag.putState(state, stateBid)
# The reward information in the state transition is computed for epoch
# transitions - when transitioning into epoch N, the activities in epoch
# N-2 are translated into balance updates, and this is what we capture
# in the monitor. This may be inaccurate during a deep reorg (>1 epoch)
# which is an acceptable tradeoff for monitoring.
withState(state):
let postEpoch = forkyState.data.slot.epoch
if preEpoch != postEpoch and postEpoch >= 2:
var proposers: array[SLOTS_PER_EPOCH, Opt[ValidatorIndex]]
let epochRef = dag.findEpochRef(stateBid, postEpoch - 2)
if epochRef.isSome():
proposers = epochRef[][].beacon_proposers
dag.validatorMonitor[].registerEpochInfo(
forkyState.data, proposers, info)
proc applyBlock(
dag: ChainDAGRef, state: var ForkedHashedBeaconState, bid: BlockId,
cache: var StateCache, info: var ForkedEpochInfo,
updateFlags: UpdateFlags): Result[void, cstring] =
loadStateCache(dag, cache, bid, getStateField(state, slot).epoch)
discard case dag.cfg.consensusForkAtEpoch(bid.slot.epoch)
of ConsensusFork.Phase0:
let data = getBlock(dag, bid, phase0.TrustedSignedBeaconBlock).valueOr:
return err("Block load failed")
? state_transition(
dag.cfg, state, data, cache, info,
updateFlags + {slotProcessed}, noRollback)
of ConsensusFork.Altair:
let data = getBlock(dag, bid, altair.TrustedSignedBeaconBlock).valueOr:
return err("Block load failed")
? state_transition(
dag.cfg, state, data, cache, info,
updateFlags + {slotProcessed}, noRollback)
of ConsensusFork.Bellatrix:
let data = getBlock(dag, bid, bellatrix.TrustedSignedBeaconBlock).valueOr:
return err("Block load failed")
? state_transition(
dag.cfg, state, data, cache, info,
updateFlags + {slotProcessed}, noRollback)
of ConsensusFork.Capella:
let data = getBlock(dag, bid, capella.TrustedSignedBeaconBlock).valueOr:
return err("Block load failed")