-
-
Notifications
You must be signed in to change notification settings - Fork 454
Expand file tree
/
Copy pathforkChoice.ts
More file actions
1887 lines (1700 loc) · 72.6 KB
/
forkChoice.ts
File metadata and controls
1887 lines (1700 loc) · 72.6 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
import {ChainForkConfig} from "@lodestar/config";
import {ForkSeq, SLOTS_PER_EPOCH, SLOTS_PER_HISTORICAL_ROOT} from "@lodestar/params";
import {
DataAvailabilityStatus,
EffectiveBalanceIncrements,
IBeaconStateView,
ZERO_HASH,
computeEpochAtSlot,
computeSlotsSinceEpochStart,
computeStartSlotAtEpoch,
getAttesterSlashableIndices,
isExecutionBlockBodyType,
} from "@lodestar/state-transition";
import {
AttesterSlashing,
BeaconBlock,
Epoch,
IndexedAttestation,
Root,
RootHex,
Slot,
ValidatorIndex,
isGloasBeaconBlock,
phase0,
ssz,
} from "@lodestar/types";
import {Logger, MapDef, fromHex, toRootHex} from "@lodestar/utils";
import {ForkChoiceMetrics} from "../metrics.js";
import {computeDeltas} from "../protoArray/computeDeltas.js";
import {ProtoArrayError, ProtoArrayErrorCode} from "../protoArray/errors.js";
import {
ExecutionStatus,
HEX_ZERO_HASH,
LVHExecResponse,
MaybeValidExecutionStatus,
NULL_VOTE_INDEX,
PayloadStatus,
ProtoBlock,
ProtoNode,
VoteIndex,
isGloasBlock,
} from "../protoArray/interface.js";
import {ProtoArray} from "../protoArray/protoArray.js";
import {ForkChoiceError, ForkChoiceErrorCode, InvalidAttestationCode, InvalidBlockCode} from "./errors.js";
import {
AncestorResult,
AncestorStatus,
EpochDifference,
IForkChoice,
NotReorgedReason,
ShouldOverrideForkChoiceUpdateResult,
} from "./interface.js";
import {CheckpointWithPayloadStatus, IForkChoiceStore, JustifiedBalances, toCheckpointWithPayload} from "./store.js";
export type ForkChoiceOpts = {
proposerBoost?: boolean;
proposerBoostReorg?: boolean;
computeUnrealized?: boolean;
};
export enum UpdateHeadOpt {
GetCanonicalHead = "getCanonicalHead", // Skip getProposerHead
GetProposerHead = "getProposerHead", // With getProposerHead
GetPredictedProposerHead = "getPredictedProposerHead", // With predictProposerHead
}
export type UpdateAndGetHeadOpt =
// When slot is provided, it overrides fcStore.currentSlot for Gloas FULL vs EMPTY tie-breaker logic
| {mode: UpdateHeadOpt.GetCanonicalHead; slot?: Slot}
| {mode: UpdateHeadOpt.GetProposerHead; secFromSlot: number; slot: Slot}
| {mode: UpdateHeadOpt.GetPredictedProposerHead; secFromSlot: number; slot: Slot};
// the initial vote epoch for all validators
const INIT_VOTE_SLOT: Slot = 0;
/**
* Provides an implementation of "Ethereum Consensus -- Beacon Chain Fork Choice":
*
* https://github.com/ethereum/consensus-specs/blob/v1.1.10/specs/phase0/fork-choice.md#fork-choice
*
* ## Detail
*
* This class wraps `ProtoArray` and provides:
*
* - Management of validators latest messages and balances
* - Management of the justified/finalized checkpoints as seen by fork choice
* - Queuing of attestations from the current slot
*
* This class MUST be used with the following considerations:
*
* - Time is not updated automatically, updateTime MUST be called every slot
*/
export class ForkChoice implements IForkChoice {
irrecoverableError?: Error;
/**
* Votes currently tracked in the protoArray. Instead of tracking a VoteTracker of currentIndex, nextIndex and epoch,
* we decompose the struct and track them in separate arrays for performance reason.
*
* For Gloas (ePBS), LatestMessage tracks slot instead of epoch and includes payload_present flag.
* Spec: gloas/fork-choice.md#modified-latestmessage
*
* IMPORTANT: voteCurrentIndices and voteNextIndices point to the EXACT variant node index.
* The payload status is encoded in the node index itself (different variants have different indices).
* For example, if a validator votes for the EMPTY variant, voteNextIndices[i] points to that specific EMPTY node.
*/
private readonly voteCurrentIndices: VoteIndex[];
private readonly voteNextIndices: VoteIndex[];
private readonly voteNextSlots: Slot[];
/**
* Attestations that arrived at the current slot and must be queued for later processing.
* NOT currently tracked in the protoArray
*
* Modified for Gloas to track PayloadStatus per validator.
* Maps: Slot -> BlockRoot -> ValidatorIndex -> PayloadStatus
*/
private readonly queuedAttestations: MapDef<Slot, MapDef<RootHex, Map<ValidatorIndex, PayloadStatus>>> = new MapDef(
() => new MapDef(() => new Map())
);
/**
* It's inconsistent to count number of queued attestations at different intervals of slot.
* Instead of that, we count number of queued attestations at the previous slot.
*/
private queuedAttestationsPreviousSlot = 0;
// Note: as of Jun 2022 Lodestar metrics show that 100% of the times updateHead() is called, synced = false.
// Because we are processing attestations from gossip, recomputing scores is always necessary
// /** Avoid having to compute deltas all the times. */
// private synced = false;
/** Cached head */
private head: ProtoBlock;
/**
* Only cache attestation data root hex if it's tree backed since it's available.
**/
private validatedAttestationDatas = new Set<string>();
/** Boost the entire branch with this proposer root as the leaf */
private proposerBoostRoot: RootHex | null = null;
/** Score to use in proposer boost, evaluated lazily from justified balances */
private justifiedProposerBoostScore: number | null = null;
/** The current effective balances */
private balances: EffectiveBalanceIncrements;
/**
* Instantiates a Fork Choice from some existing components
*
* This is useful if the existing components have been loaded from disk after a process restart.
*/
constructor(
private readonly config: ChainForkConfig,
private readonly fcStore: IForkChoiceStore,
/** The underlying representation of the block DAG. */
private readonly protoArray: ProtoArray,
validatorCount: number,
readonly metrics: ForkChoiceMetrics | null,
private readonly opts?: ForkChoiceOpts,
private readonly logger?: Logger
) {
// initialize votes, they will grow in addLatestMessage() function below
this.voteCurrentIndices = new Array(validatorCount).fill(NULL_VOTE_INDEX);
this.voteNextIndices = new Array(validatorCount).fill(NULL_VOTE_INDEX);
// when compute deltas, we ignore epoch if voteNextIndex is NULL_VOTE_INDEX anyway
this.voteNextSlots = new Array(validatorCount).fill(0);
this.head = this.updateHead();
this.balances = this.fcStore.justified.balances;
metrics?.forkChoice.votes.addCollect(() => {
metrics.forkChoice.votes.set(this.voteNextSlots.length);
metrics.forkChoice.queuedAttestations.set(this.queuedAttestationsPreviousSlot);
metrics.forkChoice.validatedAttestationDatas.set(this.validatedAttestationDatas.size);
metrics.forkChoice.balancesLength.set(this.balances.length);
metrics.forkChoice.nodes.set(this.protoArray.nodes.length);
metrics.forkChoice.indices.set(this.protoArray.indices.size);
});
}
/**
* Returns the block root of an ancestor of `blockRoot` at the given `slot`.
* (Note: `slot` refers to the block that is *returned*, not the one that is supplied.)
*
* NOTE: May be expensive: potentially walks through the entire fork of head to finalized block
*
* ### Specification
*
* Equivalent to:
*
* https://github.com/ethereum/consensus-specs/blob/v1.1.10/specs/phase0/fork-choice.md#get_ancestor
*/
getAncestor(blockRoot: RootHex, ancestorSlot: Slot): ProtoNode {
return this.protoArray.getAncestor(blockRoot, ancestorSlot);
}
/**
* Get the cached head root
*/
getHeadRoot(): RootHex {
return this.getHead().blockRoot;
}
/**
* Get the cached head
*/
getHead(): ProtoBlock {
return this.head;
}
/**
*
* A multiplexer to wrap around the traditional `updateHead()` according to the scenario
* Scenarios as follow:
* Prepare to propose in the next slot: getHead() -> predictProposerHead()
* Proposing in the current slot: updateHead() -> getProposerHead()
* Others eg. initializing forkchoice, importBlock: updateHead()
*
* Only `GetProposerHead` returns additional field `isHeadTimely` and `notReorgedReason` for metrics purpose
*/
updateAndGetHead(opt: UpdateAndGetHeadOpt): {
head: ProtoBlock;
isHeadTimely?: boolean;
notReorgedReason?: NotReorgedReason;
} {
const {mode} = opt;
const canonicalHeadBlock =
mode === UpdateHeadOpt.GetPredictedProposerHead ? this.getHead() : this.updateHead(opt.slot);
switch (mode) {
case UpdateHeadOpt.GetPredictedProposerHead:
return {head: this.predictProposerHead(canonicalHeadBlock, opt.secFromSlot, opt.slot)};
case UpdateHeadOpt.GetProposerHead: {
const {
proposerHead: head,
isHeadTimely,
notReorgedReason,
} = this.getProposerHead(canonicalHeadBlock, opt.secFromSlot, opt.slot);
return {head, isHeadTimely, notReorgedReason};
}
case UpdateHeadOpt.GetCanonicalHead:
return {head: canonicalHeadBlock};
default:
return {head: canonicalHeadBlock};
}
}
// Called by `predictProposerHead` and `importBlock`. If the result is not same as blockRoot's block, return true else false
// See https://github.com/ethereum/consensus-specs/blob/v1.5.0/specs/bellatrix/fork-choice.md#should_override_forkchoice_update
// Return true if the given block passes all criteria to be re-orged out
// Return false otherwise.
// Note when proposer boost reorg is disabled, it always returns false
shouldOverrideForkChoiceUpdate(
headBlock: ProtoBlock,
secFromSlot: number,
currentSlot: Slot
): ShouldOverrideForkChoiceUpdateResult {
if (headBlock === null) {
// should not happen because this block just got imported. Fall back to no-reorg.
return {shouldOverrideFcu: false, reason: NotReorgedReason.HeadBlockNotAvailable};
}
const {proposerBoost, proposerBoostReorg} = this.opts ?? {};
// Skip re-org attempt if proposer boost (reorg) are disabled
if (!proposerBoost || !proposerBoostReorg) {
this.logger?.verbose("Skip shouldOverrideForkChoiceUpdate check since the related flags are disabled", {
slot: currentSlot,
proposerBoost,
proposerBoostReorg,
});
return {shouldOverrideFcu: false, reason: NotReorgedReason.ProposerBoostReorgDisabled};
}
const parentBlock = this.protoArray.getBlock(
headBlock.parentRoot,
this.protoArray.getParentPayloadStatus(headBlock)
);
const proposalSlot = headBlock.slot + 1;
// No reorg if parentBlock isn't available
if (parentBlock === undefined) {
return {shouldOverrideFcu: false, reason: NotReorgedReason.ParentBlockNotAvailable};
}
const {prelimProposerHead, prelimNotReorgedReason} = this.getPreliminaryProposerHead(
headBlock,
parentBlock,
proposalSlot
);
if (prelimProposerHead === headBlock) {
return {shouldOverrideFcu: false, reason: prelimNotReorgedReason ?? NotReorgedReason.Unknown};
}
const currentTimeOk =
headBlock.slot === currentSlot ||
(proposalSlot === currentSlot && this.isProposingOnTime(secFromSlot, currentSlot));
if (!currentTimeOk) {
return {shouldOverrideFcu: false, reason: NotReorgedReason.ReorgMoreThanOneSlot};
}
this.logger?.verbose("Block is weak. Should override forkchoice update", {
blockRoot: headBlock.blockRoot,
slot: currentSlot,
});
return {shouldOverrideFcu: true, parentBlock};
}
/**
* Get the proposer boost root
*/
getProposerBoostRoot(): RootHex {
return this.proposerBoostRoot ?? HEX_ZERO_HASH;
}
/**
* To predict the proposer head of the next slot. That is, to predict if proposer-boost-reorg could happen.
* Reason why we can't be certain is because information of the head block is not fully available yet
* since the current slot hasn't ended especially the attesters' votes.
*
* There is a chance we mispredict.
*
* By calling this function, we assume we are the proposer of next slot
*
*/
predictProposerHead(headBlock: ProtoBlock, secFromSlot: number, currentSlot: Slot): ProtoBlock {
const {proposerBoost, proposerBoostReorg} = this.opts ?? {};
// Skip re-org attempt if proposer boost (reorg) are disabled
if (!proposerBoost || !proposerBoostReorg) {
this.logger?.verbose("No proposer boost reorg prediction since the related flags are disabled", {
slot: currentSlot,
proposerBoost,
proposerBoostReorg,
});
return headBlock;
}
const blockRoot = headBlock.blockRoot;
const result = this.shouldOverrideForkChoiceUpdate(headBlock, secFromSlot, currentSlot);
if (result.shouldOverrideFcu) {
this.logger?.verbose("Current head is weak. Predicting next block to be built on parent of head.", {
slot: currentSlot,
proposerHead: result.parentBlock.blockRoot,
weakHead: blockRoot,
});
return result.parentBlock;
}
this.logger?.verbose("Current head is strong. Predicting next block to be built on head", {
slot: currentSlot,
head: headBlock.blockRoot,
reason: result.reason,
});
return headBlock;
}
/**
*
* This function takes in the canonical head block and determine the proposer head (canonical head block or its parent)
* https://github.com/ethereum/consensus-specs/pull/3034 for info about proposer boost reorg
* This function should only be called during block proposal and only be called after `updateHead()` in `updateAndGetHead()`
*
* Same as https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.4/specs/phase0/fork-choice.md#get_proposer_head
*/
getProposerHead(
headBlock: ProtoBlock,
secFromSlot: number,
slot: Slot
): {proposerHead: ProtoBlock; isHeadTimely: boolean; notReorgedReason?: NotReorgedReason} {
const isHeadTimely = headBlock.timeliness;
let proposerHead = headBlock;
// Skip re-org attempt if proposer boost (reorg) are disabled
const {proposerBoost, proposerBoostReorg} = this.opts ?? {};
if (!proposerBoost || !proposerBoostReorg) {
this.logger?.verbose("No proposer boost reorg attempt since the related flags are disabled", {
slot,
proposerBoost,
proposerBoostReorg,
});
return {proposerHead, isHeadTimely, notReorgedReason: NotReorgedReason.ProposerBoostReorgDisabled};
}
const parentBlock = this.protoArray.getBlock(
headBlock.parentRoot,
this.protoArray.getParentPayloadStatus(headBlock)
);
// No reorg if parentBlock isn't available
if (parentBlock === undefined) {
return {proposerHead, isHeadTimely, notReorgedReason: NotReorgedReason.ParentBlockNotAvailable};
}
const {prelimProposerHead, prelimNotReorgedReason} = this.getPreliminaryProposerHead(headBlock, parentBlock, slot);
if (prelimProposerHead === headBlock && prelimNotReorgedReason !== undefined) {
return {proposerHead, isHeadTimely, notReorgedReason: prelimNotReorgedReason};
}
// Only re-org if we are proposing on-time
if (!this.isProposingOnTime(secFromSlot, slot)) {
return {proposerHead, isHeadTimely, notReorgedReason: NotReorgedReason.NotProposingOnTime};
}
// No reorg if attempted reorg is more than a single slot
// Half of single_slot_reorg check in the spec is done in getPreliminaryProposerHead()
const currentTimeOk = headBlock.slot + 1 === slot;
if (!currentTimeOk) {
return {proposerHead, isHeadTimely, notReorgedReason: NotReorgedReason.ReorgMoreThanOneSlot};
}
// No reorg if proposer boost is still in effect
const isProposerBoostWornOff = this.proposerBoostRoot !== headBlock.blockRoot;
if (!isProposerBoostWornOff) {
return {proposerHead, isHeadTimely, notReorgedReason: NotReorgedReason.ProposerBoostNotWornOff};
}
// No reorg if headBlock is "not weak" ie. headBlock's weight exceeds (REORG_HEAD_WEIGHT_THRESHOLD = 20)% of total attester weight
// https://github.com/ethereum/consensus-specs/blob/v1.4.0-beta.4/specs/phase0/fork-choice.md#is_head_weak
const reorgThreshold = getCommitteeFraction(this.fcStore.justified.totalBalance, {
slotsPerEpoch: SLOTS_PER_EPOCH,
committeePercent: this.config.REORG_HEAD_WEIGHT_THRESHOLD,
});
const headNode = this.protoArray.getNode(headBlock.blockRoot, headBlock.payloadStatus);
// If headNode is unavailable, give up reorg
if (headNode === undefined || headNode.weight >= reorgThreshold) {
return {proposerHead, isHeadTimely, notReorgedReason: NotReorgedReason.HeadBlockNotWeak};
}
// No reorg if parentBlock is "not strong" ie. parentBlock's weight is less than or equal to (REORG_PARENT_WEIGHT_THRESHOLD = 160)% of total attester weight
// https://github.com/ethereum/consensus-specs/blob/v1.6.1/specs/phase0/fork-choice.md#is_parent_strong
const parentThreshold = getCommitteeFraction(this.fcStore.justified.totalBalance, {
slotsPerEpoch: SLOTS_PER_EPOCH,
committeePercent: this.config.REORG_PARENT_WEIGHT_THRESHOLD,
});
const parentNode = this.protoArray.getNode(parentBlock.blockRoot, parentBlock.payloadStatus);
// If parentNode is unavailable, give up reorg
if (parentNode === undefined || parentNode.weight <= parentThreshold) {
return {proposerHead, isHeadTimely, notReorgedReason: NotReorgedReason.ParentBlockNotStrong};
}
// Reorg if all above checks fail
this.logger?.verbose("Performing single-slot reorg to remove current weak head", {
slot,
proposerHead: parentBlock.blockRoot,
weakHead: headBlock.blockRoot,
});
proposerHead = parentBlock;
return {proposerHead, isHeadTimely};
}
/**
* Run the fork choice rule to determine the head.
* Update the head cache.
*
* Very expensive function (400ms / run as of Aug 2021). Call when the head really needs to be re-calculated.
*
* ## Specification
*
* Is equivalent to:
*
* https://github.com/ethereum/consensus-specs/blob/v1.1.10/specs/phase0/fork-choice.md#get_head
*
* @param slot - If provided, overrides fcStore.currentSlot for Gloas FULL vs EMPTY tie-breaker logic
*/
updateHead(slot?: Slot): ProtoBlock {
// balances is not changed but votes are changed
// NOTE: In current Lodestar metrics, 100% of forkChoiceRequests this.synced = false.
// No need to cache computeDeltas()
//
// TODO: In current Lodestar metrics, 100% of forkChoiceRequests result in a changed head.
// No need to cache the head anymore
// Check if scores need to be calculated/updated
const oldBalances = this.balances;
const newBalances = this.fcStore.justified.balances;
const computeDeltasMetrics = this.metrics?.forkChoice.computeDeltas;
const timer = computeDeltasMetrics?.duration.startTimer();
const {
deltas,
equivocatingValidators,
oldInactiveValidators,
newInactiveValidators,
unchangedVoteValidators,
newVoteValidators,
} = computeDeltas(
this.protoArray.nodes.length,
this.voteCurrentIndices,
this.voteNextIndices,
oldBalances,
newBalances,
this.fcStore.equivocatingIndices
);
timer?.();
computeDeltasMetrics?.deltasCount.set(deltas.length);
computeDeltasMetrics?.zeroDeltasCount.set(deltas.filter((d) => d === 0).length);
computeDeltasMetrics?.equivocatingValidators.set(equivocatingValidators);
computeDeltasMetrics?.oldInactiveValidators.set(oldInactiveValidators);
computeDeltasMetrics?.newInactiveValidators.set(newInactiveValidators);
computeDeltasMetrics?.unchangedVoteValidators.set(unchangedVoteValidators);
computeDeltasMetrics?.newVoteValidators.set(newVoteValidators);
this.balances = newBalances;
/**
* The structure in line with deltas to propagate boost up the branch
* starting from the proposerIndex
*/
let proposerBoost: {root: RootHex; score: number} | null = null;
if (this.opts?.proposerBoost && this.proposerBoostRoot) {
const proposerBoostScore =
this.justifiedProposerBoostScore ??
getCommitteeFraction(this.fcStore.justified.totalBalance, {
slotsPerEpoch: SLOTS_PER_EPOCH,
committeePercent: this.config.PROPOSER_SCORE_BOOST,
});
proposerBoost = {root: this.proposerBoostRoot, score: proposerBoostScore};
this.justifiedProposerBoostScore = proposerBoostScore;
}
// When preparing for the next slot, pass slot as currentSlot + 1 to choose FULL vs EMPTY
// This is important for Gloas tie-breaker logic
const currentSlot = slot ?? this.fcStore.currentSlot;
this.protoArray.applyScoreChanges({
deltas,
proposerBoost,
justifiedEpoch: this.fcStore.justified.checkpoint.epoch,
justifiedRoot: this.fcStore.justified.checkpoint.rootHex,
finalizedEpoch: this.fcStore.finalizedCheckpoint.epoch,
finalizedRoot: this.fcStore.finalizedCheckpoint.rootHex,
currentSlot,
});
// findHead returns the ProtoNode representing the head
const head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
this.head = head;
return this.head;
}
/**
* An iteration over protoArray to get present slots, to be called preemptively
* from prepareNextSlot to prevent delay on produceBlindedBlock
* @param windowStart is the slot after which (excluding) to provide present slots
*/
getSlotsPresent(windowStart: number): number {
return this.protoArray.nodes.filter((node) => node.slot > windowStart).length;
}
/** Very expensive function, iterates the entire ProtoArray. Called only in debug API */
getHeads(): ProtoBlock[] {
return this.protoArray.nodes.filter((node) => node.bestChild === undefined);
}
/** This is for the debug API only */
getAllNodes(): ProtoNode[] {
return this.protoArray.nodes;
}
getFinalizedCheckpoint(): CheckpointWithPayloadStatus {
return this.fcStore.finalizedCheckpoint;
}
getJustifiedCheckpoint(): CheckpointWithPayloadStatus {
return this.fcStore.justified.checkpoint;
}
/**
* Add `block` to the fork choice DAG.
*
* ## Specification
*
* Approximates:
*
* https://github.com/ethereum/consensus-specs/blob/v1.1.10/specs/phase0/fork-choice.md#on_block
*
* It only approximates the specification since it does not run the `state_transition` check.
* That should have already been called upstream and it's too expensive to call again.
*
* ## Notes:
*
* The supplied block **must** pass the `state_transition` function as it will not be run here.
*
* `justifiedBalances` balances of justified state which is updated synchronously.
* This ensures that the forkchoice is never out of sync.
*/
onBlock(
block: BeaconBlock,
state: IBeaconStateView,
blockDelaySec: number,
currentSlot: Slot,
executionStatus: MaybeValidExecutionStatus,
dataAvailabilityStatus: DataAvailabilityStatus
): ProtoBlock {
const {parentRoot, slot} = block;
const parentRootHex = toRootHex(parentRoot);
// Parent block must be known because state_transition would have failed otherwise.
const parentHashHex = isGloasBeaconBlock(block)
? toRootHex(block.body.signedExecutionPayloadBid.message.parentBlockHash)
: null;
const parentBlock = this.protoArray.getParent(parentRootHex, parentHashHex);
if (!parentBlock) {
throw new ForkChoiceError({
code: ForkChoiceErrorCode.INVALID_BLOCK,
err: {
code: InvalidBlockCode.UNKNOWN_PARENT,
root: parentRootHex,
hash: parentHashHex,
},
});
}
// Blocks cannot be in the future. If they are, their consideration must be delayed until
// the are in the past.
//
// Note: presently, we do not delay consideration. We just drop the block.
if (slot > this.fcStore.currentSlot) {
throw new ForkChoiceError({
code: ForkChoiceErrorCode.INVALID_BLOCK,
err: {
code: InvalidBlockCode.FUTURE_SLOT,
currentSlot: this.fcStore.currentSlot,
blockSlot: slot,
},
});
}
// Check that block is later than the finalized epoch slot (optimization to reduce calls to
// get_ancestor).
const finalizedSlot = computeStartSlotAtEpoch(this.fcStore.finalizedCheckpoint.epoch);
if (slot <= finalizedSlot) {
throw new ForkChoiceError({
code: ForkChoiceErrorCode.INVALID_BLOCK,
err: {
code: InvalidBlockCode.FINALIZED_SLOT,
finalizedSlot,
blockSlot: slot,
},
});
}
// Check block is a descendant of the finalized block at the checkpoint finalized slot.
const blockAncestorNode = this.getAncestor(parentRootHex, finalizedSlot);
const fcStoreFinalized = this.fcStore.finalizedCheckpoint;
if (
blockAncestorNode.blockRoot !== fcStoreFinalized.rootHex ||
blockAncestorNode.payloadStatus !== fcStoreFinalized.payloadStatus
) {
throw new ForkChoiceError({
code: ForkChoiceErrorCode.INVALID_BLOCK,
err: {
code: InvalidBlockCode.NOT_FINALIZED_DESCENDANT,
finalizedRoot: fcStoreFinalized.rootHex,
blockAncestor: blockAncestorNode.blockRoot,
},
});
}
const blockRoot = this.config.getForkTypes(slot).BeaconBlock.hashTreeRoot(block);
const blockRootHex = toRootHex(blockRoot);
// Assign proposer score boost if the block is timely
// before attesting interval = before 1st interval
const isTimely = this.isBlockTimely(block, blockDelaySec);
if (
this.opts?.proposerBoost &&
isTimely &&
// only boost the first block we see
this.proposerBoostRoot === null
) {
this.proposerBoostRoot = blockRootHex;
}
// Get justified checkpoint with payload status for Gloas
const justifiedPayloadStatus = getCheckpointPayloadStatus(
this.config,
state,
state.currentJustifiedCheckpoint.epoch
);
const justifiedCheckpoint = toCheckpointWithPayload(state.currentJustifiedCheckpoint, justifiedPayloadStatus);
const stateJustifiedEpoch = justifiedCheckpoint.epoch;
// Get finalized checkpoint with payload status for Gloas
const finalizedPayloadStatus = getCheckpointPayloadStatus(this.config, state, state.finalizedCheckpoint.epoch);
const finalizedCheckpoint = toCheckpointWithPayload(state.finalizedCheckpoint, finalizedPayloadStatus);
// Justified balances for `justifiedCheckpoint` are new to the fork-choice. Compute them on demand only if
// the justified checkpoint changes
this.updateCheckpoints(justifiedCheckpoint, finalizedCheckpoint, () =>
this.fcStore.justifiedBalancesGetter(justifiedCheckpoint, state)
);
const blockEpoch = computeEpochAtSlot(slot);
// same logic to compute_pulled_up_tip in the spec, making it inline because of reusing variables
// If the parent checkpoints are already at the same epoch as the block being imported,
// it's impossible for the unrealized checkpoints to differ from the parent's. This
// holds true because:
//
// 1. A child block cannot have lower FFG checkpoints than its parent.
// 2. A block in epoch `N` cannot contain attestations which would justify an epoch higher than `N`.
// 3. A block in epoch `N` cannot contain attestations which would finalize an epoch higher than `N - 1`.
//
// This is an optimization. It should reduce the amount of times we run
// `process_justification_and_finalization` by approximately 1/3rd when the chain is
// performing optimally.
let unrealizedJustifiedCheckpoint: CheckpointWithPayloadStatus;
let unrealizedFinalizedCheckpoint: CheckpointWithPayloadStatus;
if (this.opts?.computeUnrealized) {
if (
parentBlock.unrealizedJustifiedEpoch === blockEpoch &&
parentBlock.unrealizedFinalizedEpoch + 1 >= blockEpoch
) {
// reuse from parent, happens at 1/3 last blocks of epoch as monitored in mainnet
// Get payload status for unrealized justified checkpoint
const unrealizedJustifiedPayloadStatus = getCheckpointPayloadStatus(
this.config,
state,
parentBlock.unrealizedJustifiedEpoch
);
unrealizedJustifiedCheckpoint = {
epoch: parentBlock.unrealizedJustifiedEpoch,
root: fromHex(parentBlock.unrealizedJustifiedRoot),
rootHex: parentBlock.unrealizedJustifiedRoot,
payloadStatus: unrealizedJustifiedPayloadStatus,
};
// Get payload status for unrealized finalized checkpoint
const unrealizedFinalizedPayloadStatus = getCheckpointPayloadStatus(
this.config,
state,
parentBlock.unrealizedFinalizedEpoch
);
unrealizedFinalizedCheckpoint = {
epoch: parentBlock.unrealizedFinalizedEpoch,
root: fromHex(parentBlock.unrealizedFinalizedRoot),
rootHex: parentBlock.unrealizedFinalizedRoot,
payloadStatus: unrealizedFinalizedPayloadStatus,
};
} else {
// compute new, happens 2/3 first blocks of epoch as monitored in mainnet
const unrealized = state.computeUnrealizedCheckpoints();
// Get payload status for unrealized justified checkpoint
const unrealizedJustifiedPayloadStatus = getCheckpointPayloadStatus(
this.config,
state,
unrealized.justifiedCheckpoint.epoch
);
unrealizedJustifiedCheckpoint = toCheckpointWithPayload(
unrealized.justifiedCheckpoint,
unrealizedJustifiedPayloadStatus
);
// Get payload status for unrealized finalized checkpoint
const unrealizedFinalizedPayloadStatus = getCheckpointPayloadStatus(
this.config,
state,
unrealized.finalizedCheckpoint.epoch
);
unrealizedFinalizedCheckpoint = toCheckpointWithPayload(
unrealized.finalizedCheckpoint,
unrealizedFinalizedPayloadStatus
);
}
} else {
unrealizedJustifiedCheckpoint = justifiedCheckpoint;
unrealizedFinalizedCheckpoint = finalizedCheckpoint;
}
// Un-realized checkpoints
// Update best known unrealized justified & finalized checkpoints
this.updateUnrealizedCheckpoints(unrealizedJustifiedCheckpoint, unrealizedFinalizedCheckpoint, () =>
this.fcStore.justifiedBalancesGetter(unrealizedJustifiedCheckpoint, state)
);
// If block is from past epochs, try to update store's justified & finalized checkpoints right away
if (blockEpoch < computeEpochAtSlot(currentSlot)) {
this.updateCheckpoints(unrealizedJustifiedCheckpoint, unrealizedFinalizedCheckpoint, () =>
this.fcStore.justifiedBalancesGetter(unrealizedJustifiedCheckpoint, state)
);
}
const targetSlot = computeStartSlotAtEpoch(blockEpoch);
const targetRoot = slot === targetSlot ? blockRoot : state.getBlockRootAtSlot(targetSlot);
// This does not apply a vote to the block, it just makes fork choice aware of the block so
// it can still be identified as the head even if it doesn't have any votes.
const protoBlock: ProtoBlock = {
slot: slot,
blockRoot: blockRootHex,
parentRoot: parentRootHex,
targetRoot: toRootHex(targetRoot),
stateRoot: toRootHex(block.stateRoot),
timeliness: isTimely,
justifiedEpoch: stateJustifiedEpoch,
justifiedRoot: toRootHex(state.currentJustifiedCheckpoint.root),
finalizedEpoch: finalizedCheckpoint.epoch,
finalizedRoot: toRootHex(state.finalizedCheckpoint.root),
unrealizedJustifiedEpoch: unrealizedJustifiedCheckpoint.epoch,
unrealizedJustifiedRoot: unrealizedJustifiedCheckpoint.rootHex,
unrealizedFinalizedEpoch: unrealizedFinalizedCheckpoint.epoch,
unrealizedFinalizedRoot: unrealizedFinalizedCheckpoint.rootHex,
...(isGloasBeaconBlock(block)
? {
executionPayloadBlockHash: toRootHex(block.body.signedExecutionPayloadBid.message.parentBlockHash), // post-gloas, we don't know payload hash until we import execution payload. Set to parent payload hash for now
executionPayloadNumber: (() => {
// Determine parent's execution payload number based on which variant the block extends
const parentBlockHashFromBid = toRootHex(block.body.signedExecutionPayloadBid.message.parentBlockHash);
// If parent is pre-merge, return 0
if (parentBlock.executionPayloadBlockHash === null) {
return 0;
}
// If parent is pre-Gloas, it only has FULL variant
if (parentBlock.parentBlockHash === null) {
return parentBlock.executionPayloadNumber;
}
// Parent is Gloas: get the variant that matches the parentBlockHash from bid
const parentVariant = this.getBlockHexAndBlockHash(parentRootHex, parentBlockHashFromBid);
if (parentVariant && parentVariant.executionPayloadBlockHash !== null) {
return parentVariant.executionPayloadNumber;
}
// Fallback to parent block's number (we know it's post-merge from check above)
return parentBlock.executionPayloadNumber;
})(),
executionStatus: this.getPostGloasExecStatus(executionStatus),
dataAvailabilityStatus,
}
: isExecutionBlockBodyType(block.body) && state.isExecutionStateType && state.isExecutionEnabled(block)
? {
executionPayloadBlockHash: toRootHex(block.body.executionPayload.blockHash),
executionPayloadNumber: block.body.executionPayload.blockNumber,
executionStatus: this.getPreGloasExecStatus(executionStatus),
dataAvailabilityStatus,
}
: {
executionPayloadBlockHash: null,
executionStatus: this.getPreMergeExecStatus(executionStatus),
dataAvailabilityStatus: this.getPreMergeDataStatus(dataAvailabilityStatus),
}),
payloadStatus: isGloasBeaconBlock(block) ? PayloadStatus.PENDING : PayloadStatus.FULL,
parentBlockHash: parentHashHex,
};
this.protoArray.onBlock(protoBlock, currentSlot, this.proposerBoostRoot);
return protoBlock;
}
/**
* Register `attestation` with the fork choice DAG so that it may influence future calls to `getHead`.
*
* ## Specification
*
* Approximates:
*
* https://github.com/ethereum/consensus-specs/blob/v1.1.10/specs/phase0/fork-choice.md#on_attestation
*
* It only approximates the specification since it does not perform
* `is_valid_indexed_attestation` since that should already have been called upstream and it's
* too expensive to call again.
*
* ## Notes:
*
* The supplied `attestation` **must** pass the `in_valid_indexed_attestation` function as it
* will not be run here.
*/
onAttestation(attestation: IndexedAttestation, attDataRoot: string, forceImport?: boolean): void {
// Ignore any attestations to the zero hash.
//
// This is an edge case that results from the spec aliasing the zero hash to the genesis
// block. Attesters may attest to the zero hash if they have never seen a block.
//
// We have two options here:
//
// 1. Apply all zero-hash attestations to the genesis block.
// 2. Ignore all attestations to the zero hash.
//
// (1) becomes weird once we hit finality and fork choice drops the genesis block. (2) is
// fine because votes to the genesis block are not useful; all validators implicitly attest
// to genesis just by being present in the chain.
const attestationData = attestation.data;
const {slot, beaconBlockRoot} = attestationData;
const blockRootHex = toRootHex(beaconBlockRoot);
const targetEpoch = attestationData.target.epoch;
if (ssz.Root.equals(beaconBlockRoot, ZERO_HASH)) {
return;
}
this.validateOnAttestation(attestation, slot, blockRootHex, targetEpoch, attDataRoot, forceImport);
// Pre-gloas: payload is always present
// Post-gloas:
// - always add weight to PENDING
// - if message.slot > block.slot, it also add weights to FULL or EMPTY
let payloadStatus: PayloadStatus;
// We need to retrieve block to check if it's Gloas and to compare slot
// https://github.com/ethereum/consensus-specs/blob/v1.7.0-alpha.1/specs/gloas/fork-choice.md#new-is_supporting_vote
const block = this.getBlockHexDefaultStatus(blockRootHex);
if (block && isGloasBlock(block)) {
// Post-Gloas block: determine FULL/EMPTY/PENDING based on slot and committee index
// If slot > block.slot, we can determine FULL or EMPTY. Else always PENDING
if (slot > block.slot) {
if (attestationData.index === 1) {
payloadStatus = PayloadStatus.FULL;
} else if (attestationData.index === 0) {
payloadStatus = PayloadStatus.EMPTY;
} else {
throw new ForkChoiceError({
code: ForkChoiceErrorCode.INVALID_ATTESTATION,
err: {
code: InvalidAttestationCode.INVALID_DATA_INDEX,
index: attestationData.index,
},
});
}
} else {
payloadStatus = PayloadStatus.PENDING;
}
} else {
// Pre-Gloas block or block not found: always FULL
payloadStatus = PayloadStatus.FULL;
}
if (slot < this.fcStore.currentSlot) {
for (const validatorIndex of attestation.attestingIndices) {
if (!this.fcStore.equivocatingIndices.has(validatorIndex)) {
this.addLatestMessage(validatorIndex, slot, blockRootHex, payloadStatus);
}
}
} else {
// The spec declares:
//
// ```
// Attestations can only affect the fork choice of subsequent slots.
// Delay consideration in the fork choice until their slot is in the past.
// ```
const byRoot = this.queuedAttestations.getOrDefault(slot);
const validatorVotes = byRoot.getOrDefault(blockRootHex);
for (const validatorIndex of attestation.attestingIndices) {
if (!this.fcStore.equivocatingIndices.has(validatorIndex)) {
validatorVotes.set(validatorIndex, payloadStatus);
}
}
}
}
/**
* Small different from the spec:
* We already call is_slashable_attestation_data() and is_valid_indexed_attestation
* in state transition so no need to do it again
*/
onAttesterSlashing(attesterSlashing: AttesterSlashing): void {
// TODO: we already call in in state-transition, find a way not to recompute it again
const intersectingIndices = getAttesterSlashableIndices(attesterSlashing);
for (const validatorIndex of intersectingIndices) {
this.fcStore.equivocatingIndices.add(validatorIndex);
}
}
/**
* Process a PTC (Payload Timeliness Committee) message
* Updates the PTC votes for multiple validators attesting to a block
* Spec: gloas/fork-choice.md#new-on_payload_attestation_message
*/
notifyPtcMessages(blockRoot: RootHex, ptcIndices: number[], payloadPresent: boolean): void {
this.protoArray.notifyPtcMessages(blockRoot, ptcIndices, payloadPresent);
}
/**
* Notify fork choice that an execution payload has arrived (Gloas fork)
* Creates the FULL variant of a Gloas block when the payload becomes available
* Spec: gloas/fork-choice.md#new-on_execution_payload
*/
onExecutionPayload(
blockRoot: RootHex,
executionPayloadBlockHash: RootHex,
executionPayloadNumber: number,
executionPayloadStateRoot: RootHex
): void {
this.protoArray.onExecutionPayload(
blockRoot,
this.fcStore.currentSlot,
executionPayloadBlockHash,
executionPayloadNumber,
executionPayloadStateRoot,
this.proposerBoostRoot
);
}
/**
* Call `onTick` for all slots between `fcStore.getCurrentSlot()` and the provided `currentSlot`.
* This should only be called once per slot because: