@lodestar/fork-choice 2.0.0 → 2.1.0-dev.02fd094efd

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2000 @@
1
+ import {ChainForkConfig} from "@lodestar/config";
2
+ import bindings from "@lodestar/native";
3
+ import {
4
+ type BalanceSource,
5
+ type BlockSummary,
6
+ type KeepHeadReason,
7
+ NODES_PER_BLOCK,
8
+ NO_BLOCK,
9
+ NO_NODE,
10
+ type AttestationData as NativeAttestationData,
11
+ ExecutionStatus as NativeExecutionStatus,
12
+ PayloadStatus as NativePayloadStatus,
13
+ ForkChoice as NativeStore,
14
+ type VerdictResult as NativeVerdictResult,
15
+ } from "@lodestar/native/fork-choice";
16
+ import {PTC_SIZE, SLOTS_PER_EPOCH, isForkPostFulu} from "@lodestar/params";
17
+ import {
18
+ DataAvailabilityStatus,
19
+ EffectiveBalanceIncrements,
20
+ IBeaconStateView,
21
+ ZERO_HASH,
22
+ computeEpochAtSlot,
23
+ computeStartSlotAtEpoch,
24
+ getAttesterSlashableIndices,
25
+ isExecutionBlockBodyType,
26
+ isStatePostBellatrix,
27
+ } from "@lodestar/state-transition";
28
+ import {
29
+ AttesterSlashing,
30
+ BeaconBlock,
31
+ IndexedAttestation,
32
+ Root,
33
+ RootHex,
34
+ Slot,
35
+ isGloasBeaconBlock,
36
+ phase0,
37
+ ssz,
38
+ } from "@lodestar/types";
39
+ import {Logger, fromHex, toRootHex, withObservedDuration} from "@lodestar/utils";
40
+ import {ForkChoiceMetrics} from "../metrics.js";
41
+ import {ProtoArrayError, ProtoArrayErrorCode} from "../protoArray/errors.js";
42
+ import {
43
+ BlockExecutionStatus,
44
+ ExecutionStatus,
45
+ HEX_ZERO_HASH,
46
+ LVHExecResponse,
47
+ LVHInvalidJudged,
48
+ LVHNotAppliedReason,
49
+ LVHVerdictResult,
50
+ PayloadExecutionStatus,
51
+ PayloadStatus,
52
+ ProtoBlock,
53
+ ProtoNode,
54
+ PtcQuorum,
55
+ getPtcVerdict,
56
+ isGloasBlock,
57
+ } from "../protoArray/interface.js";
58
+ import {DEFAULT_PRUNE_THRESHOLD} from "../protoArray/protoArray.js";
59
+ import {ForkChoiceError, ForkChoiceErrorCode, InvalidAttestationCode, InvalidBlockCode} from "./errors.js";
60
+ import {FastConfirmationSteps, type IFastConfirmationSpecStore} from "./fastConfirmation/fastConfirmationRule.js";
61
+ import {ForkChoiceOpts, UpdateAndGetHeadOpt, UpdateHeadOpt} from "./forkChoice.js";
62
+ import {
63
+ AncestorResult,
64
+ AncestorStatus,
65
+ EpochDifference,
66
+ IForkChoice,
67
+ NotReorgedReason,
68
+ ShouldOverrideForkChoiceUpdateResult,
69
+ } from "./interface.js";
70
+ import {CheckpointWithHex, IForkChoiceStore, equalCheckpointWithHex, toCheckpointWithHex} from "./store.js";
71
+
72
+ /** The anchor of a fork choice store: a block and the facts of its post-state */
73
+ export type NativeForkChoiceAnchor = {
74
+ /** The anchor block's default variant: FULL before Gloas, PENDING from Gloas on */
75
+ block: ProtoBlock;
76
+ /** Slot of the anchor state, at or after the anchor block's slot */
77
+ stateSlot: Slot;
78
+ genesisTime: number;
79
+ genesisValidatorsRoot: Root;
80
+ /** The anchor state's `current_justified_checkpoint` */
81
+ justifiedCheckpoint: phase0.Checkpoint;
82
+ /** The anchor state's `finalized_checkpoint` */
83
+ finalizedCheckpoint: phase0.Checkpoint;
84
+ /** The anchor block's own payload: the bid's `block_hash` from Gloas on. Null before the merge */
85
+ payloadBlockHash: Root | null;
86
+ /** The anchor block's Gloas bid `parent_block_hash` */
87
+ bidParentBlockHash: Root | null;
88
+ /**
89
+ * Set when the anchor is not finalized: the store then starts at `justifiedCheckpoint` and
90
+ * `finalizedCheckpoint` instead of at the anchor. Stand-ins for the anchor's ancestors, oldest
91
+ * first from the finalized block, holding both checkpoint blocks. Only `blockRoot` and `slot`
92
+ * reach the store; a stand-in is Gloas iff its slot is.
93
+ */
94
+ unfinalizedAncestors?: ProtoBlock[];
95
+ };
96
+
97
+ const PTC_VOTED = 1;
98
+ const PTC_PAYLOAD_PRESENT = 2;
99
+ const PTC_BLOB_DATA_AVAILABLE = 4;
100
+ const PTC_THRESHOLD = Math.floor(PTC_SIZE / 2);
101
+
102
+ const KEEP_HEAD_REASONS: Record<KeepHeadReason, NotReorgedReason> = {
103
+ head_timely: NotReorgedReason.HeadBlockIsTimely,
104
+ shuffling_not_stable: NotReorgedReason.NotShufflingStable,
105
+ not_ffg_competitive: NotReorgedReason.NotFFGCompetitive,
106
+ finalization_not_ok: NotReorgedReason.ChainLongUnfinality,
107
+ parent_not_previous_slot: NotReorgedReason.ParentBlockDistanceMoreThanOneSlot,
108
+ not_proposing_on_time: NotReorgedReason.NotProposingOnTime,
109
+ not_proposing_next_slot: NotReorgedReason.ReorgMoreThanOneSlot,
110
+ proposer_boost_not_worn_off: NotReorgedReason.ProposerBoostNotWornOff,
111
+ head_not_weak: NotReorgedReason.HeadBlockNotWeak,
112
+ parent_not_strong: NotReorgedReason.ParentBlockNotStrong,
113
+ };
114
+
115
+ const NOT_APPLIED_REASONS: Record<
116
+ Exclude<NativeVerdictResult, "applied">,
117
+ Exclude<LVHNotAppliedReason, LVHNotAppliedReason.Error>
118
+ > = {
119
+ unknown_lvh: LVHNotAppliedReason.UnknownLVH,
120
+ already_applied: LVHNotAppliedReason.AlreadyApplied,
121
+ contradiction: LVHNotAppliedReason.Contradiction,
122
+ unusable_lvh: LVHNotAppliedReason.UnusableLVH,
123
+ nothing_to_invalidate: LVHNotAppliedReason.NothingToInvalidate,
124
+ };
125
+
126
+ const EXECUTION_STATUS_FROM_NATIVE: Record<number, ExecutionStatus> = {
127
+ [NativeExecutionStatus.PreMerge]: ExecutionStatus.PreMerge,
128
+ [NativeExecutionStatus.Valid]: ExecutionStatus.Valid,
129
+ [NativeExecutionStatus.Syncing]: ExecutionStatus.Syncing,
130
+ [NativeExecutionStatus.Invalid]: ExecutionStatus.Invalid,
131
+ };
132
+
133
+ const EXECUTION_STATUS_TO_NATIVE = {
134
+ [ExecutionStatus.PreMerge]: NativeExecutionStatus.PreMerge,
135
+ [ExecutionStatus.Valid]: NativeExecutionStatus.Valid,
136
+ [ExecutionStatus.Syncing]: NativeExecutionStatus.Syncing,
137
+ [ExecutionStatus.Invalid]: NativeExecutionStatus.Invalid,
138
+ };
139
+
140
+ type NativeScores = {weights: BigUint64Array; attestationScores: BigUint64Array; bestChildren: Uint32Array};
141
+
142
+ /**
143
+ * `IForkChoice` on the Zig fork choice store (`src/fork_choice`).
144
+ *
145
+ * The native store owns the block tree, the votes and every decision. This class owns what the
146
+ * rest of the node reads: one `ProtoBlock` per fork choice node, indexed by the store's node ids,
147
+ * and the checkpoints mirrored into `fcStore` so its events fire. Beacon states never cross into
148
+ * the store; it asks for justified balances and committees through the provider callbacks.
149
+ *
150
+ * Behaviour that follows the spec the store is written against:
151
+ * - a finalized anchor is both the justified and the finalized checkpoint
152
+ * - `prune` drops every block that does not descend from the finalized block
153
+ * - the store always applies the proposer boost, so `proposerBoost: false` is rejected
154
+ * - an unfinalized anchor's ancestors are stand-ins known by root and slot only, with no payload:
155
+ * the safe and finalized block hashes stay zero until the store has imported those blocks
156
+ * - justified balances arrive with inactive and slashed validators zeroed, so `is_head_weak` counts such
157
+ * an equivocator at its head state balance, where the spec reads the justified state's
158
+ * - the native fast confirmation rule reports no reasons, so its `reorgs` and `restarts` metrics stay zero
159
+ */
160
+ export class NativeForkChoice implements IForkChoice {
161
+ private readonly store: NativeStore;
162
+ /** By node id. A pre-Gloas block has its single FULL variant in the PENDING slot */
163
+ private nodes: (ProtoBlock | undefined)[] = [];
164
+ /** By block index: the node id the block hangs from, undefined for the root block */
165
+ private parentNodes: (number | undefined)[] = [];
166
+ private blockIndexByRoot = new Map<RootHex, number>();
167
+ private head: ProtoBlock;
168
+ /** Slot of the last `updateHead()`, as `ForkChoice.updateHeadSlot` */
169
+ private updateHeadSlot = 0;
170
+ private pruneThreshold = DEFAULT_PRUNE_THRESHOLD;
171
+ private previousProposerBoostRoot: RootHex = HEX_ZERO_HASH;
172
+ private queuedAttestationsPreviousSlot = 0;
173
+ private voteChangesTotal = 0;
174
+ /** Post-state of the block being imported, the fallback source of justified balances */
175
+ private importingState: IBeaconStateView | null = null;
176
+ /** Balances the provider last handed to the store, for the checkpoint they belong to */
177
+ private providedBalances: {checkpoint: CheckpointWithHex; balances: EffectiveBalanceIncrements} | null = null;
178
+ private scores: NativeScores | null = null;
179
+
180
+ private readonly fastConfirmation: boolean;
181
+ private fastConfirmationPaused = false;
182
+
183
+ constructor(
184
+ private readonly config: ChainForkConfig,
185
+ private readonly fcStore: IForkChoiceStore,
186
+ anchor: NativeForkChoiceAnchor,
187
+ readonly metrics: ForkChoiceMetrics | null,
188
+ private readonly opts?: ForkChoiceOpts,
189
+ private readonly logger?: Logger
190
+ ) {
191
+ if (opts?.proposerBoost === false) {
192
+ throw Error("The native fork choice always applies proposer boost");
193
+ }
194
+
195
+ const {block} = anchor;
196
+ const anchorHasPayload = anchor.payloadBlockHash !== null && !ssz.Root.equals(anchor.payloadBlockHash, ZERO_HASH);
197
+ this.store = new NativeStore(
198
+ new bindings.BeaconConfig(config, anchor.genesisValidatorsRoot),
199
+ anchor.genesisTime,
200
+ {
201
+ root: fromHex(block.blockRoot),
202
+ parentRoot: fromHex(block.parentRoot),
203
+ slot: block.slot,
204
+ stateSlot: anchor.stateSlot,
205
+ proposerIndex: block.proposerIndex,
206
+ stateRoot: fromHex(block.stateRoot),
207
+ justifiedCheckpoint: anchor.justifiedCheckpoint,
208
+ finalizedCheckpoint: anchor.finalizedCheckpoint,
209
+ unrealizedJustifiedCheckpoint: anchor.justifiedCheckpoint,
210
+ unrealizedFinalizedCheckpoint: anchor.finalizedCheckpoint,
211
+ payloadBlockHash: anchor.payloadBlockHash ?? undefined,
212
+ bidParentBlockHash: anchor.bidParentBlockHash ?? undefined,
213
+ // A Gloas payload is only judged when its envelope arrives
214
+ executionStatus: !anchorHasPayload
215
+ ? NativeExecutionStatus.PreMerge
216
+ : isGloasBlock(block)
217
+ ? NativeExecutionStatus.Syncing
218
+ : EXECUTION_STATUS_TO_NATIVE[block.executionStatus],
219
+ validatorCount: fcStore.justified.balances.length,
220
+ },
221
+ {
222
+ justifiedBalances: (epoch, root) => this.provideJustifiedBalances(epoch, root),
223
+ slotCommitteeMembers: (root, slot) => this.provideSlotCommitteeMembers(root, slot),
224
+ stateBalanceIncrements: (root) => this.blockState(root).effectiveBalanceIncrements,
225
+ ...(opts?.fastConfirmation
226
+ ? {
227
+ checkpointBalanceSource: (epoch: number, root: Uint8Array) =>
228
+ this.provideCheckpointBalanceSource(epoch, root),
229
+ pulledUpBalanceSource: (root: Uint8Array, epoch: number) =>
230
+ this.providePulledUpBalanceSource(root, epoch),
231
+ }
232
+ : {}),
233
+ },
234
+ anchor.unfinalizedAncestors?.map((ancestor) => ({root: fromHex(ancestor.blockRoot), slot: ancestor.slot}))
235
+ );
236
+ this.fastConfirmation = opts?.fastConfirmation === true;
237
+ const ancestors = anchor.unfinalizedAncestors ?? [];
238
+ for (const [blockIndex, ancestor] of ancestors.entries()) {
239
+ this.insertBlock(blockIndex, ancestor);
240
+ }
241
+ this.insertBlock(ancestors.length, block);
242
+
243
+ // Bring the clock up to the slot the caller starts at; the anchor may be older
244
+ this.store.onTick(this.store.timeAtSlotMs(Math.max(fcStore.currentSlot, this.store.currentSlot)));
245
+ this.fcStore.currentSlot = this.store.currentSlot;
246
+ this.syncCheckpoints();
247
+ this.head = this.updateHead();
248
+
249
+ if (this.fastConfirmation) {
250
+ this.fcStore.confirmedRoot = toRootHex(this.store.confirmedRoot);
251
+ metrics?.fastConfirmation.paused.set(0);
252
+ }
253
+
254
+ metrics?.forkChoice.votes.addCollect(() => {
255
+ metrics.forkChoice.votes.set(this.store.voteCount);
256
+ metrics.forkChoice.queuedAttestations.set(this.queuedAttestationsPreviousSlot);
257
+ metrics.forkChoice.balancesLength.set(this.fcStore.justified.balances.length);
258
+ metrics.forkChoice.nodes.set(this.nodeCount());
259
+ metrics.forkChoice.indices.set(this.blockIndexByRoot.size);
260
+ });
261
+ }
262
+
263
+ // Head
264
+
265
+ getHeadRoot(): RootHex {
266
+ return this.getHead().blockRoot;
267
+ }
268
+
269
+ getHead(): ProtoBlock {
270
+ return this.head;
271
+ }
272
+
273
+ updateHead(): ProtoBlock {
274
+ this.previousProposerBoostRoot = this.getProposerBoostRoot();
275
+ const head = this.storeHead();
276
+ this.head = head;
277
+ this.updateHeadSlot = this.fcStore.currentSlot;
278
+
279
+ const computeDeltasMetrics = this.metrics?.forkChoice.computeDeltas;
280
+ if (computeDeltasMetrics) {
281
+ const voteChangesTotal = this.store.voteChangesTotal;
282
+ computeDeltasMetrics.deltasCount.set(this.nodeCount());
283
+ computeDeltasMetrics.equivocatingValidators.set(this.store.equivocatingCount);
284
+ computeDeltasMetrics.newVoteValidators.set(voteChangesTotal - this.voteChangesTotal);
285
+ this.voteChangesTotal = voteChangesTotal;
286
+ }
287
+ return head;
288
+ }
289
+
290
+ updateAndGetHead(opt: UpdateAndGetHeadOpt): {
291
+ head: ProtoBlock;
292
+ isHeadTimely?: boolean;
293
+ notReorgedReason?: NotReorgedReason;
294
+ } {
295
+ if (opt.mode === UpdateHeadOpt.GetProposerHead) {
296
+ // The tick into the proposal slot applies queued votes, which can move the head
297
+ this.updateTime(opt.slot);
298
+ }
299
+ const canonicalHeadBlock = opt.mode === UpdateHeadOpt.GetPredictedProposerHead ? this.getHead() : this.updateHead();
300
+ switch (opt.mode) {
301
+ case UpdateHeadOpt.GetPredictedProposerHead:
302
+ return {head: this.predictProposerHead(canonicalHeadBlock, opt.msFromSlot, opt.slot)};
303
+ case UpdateHeadOpt.GetProposerHead: {
304
+ const {
305
+ proposerHead: head,
306
+ isHeadTimely,
307
+ notReorgedReason,
308
+ } = this.getProposerHead(canonicalHeadBlock, opt.msFromSlot, opt.slot);
309
+ return {head, isHeadTimely, notReorgedReason};
310
+ }
311
+ default:
312
+ return {head: canonicalHeadBlock};
313
+ }
314
+ }
315
+
316
+ /**
317
+ * As `ForkChoice.shouldOverrideForkChoiceUpdate`. The spec dropped `should_override_forkchoice_update`,
318
+ * so it reads only block facts here: the head slot's votes are still queued, and the head is assumed weak.
319
+ */
320
+ shouldOverrideForkChoiceUpdate(
321
+ headBlock: ProtoBlock,
322
+ msFromSlot: number,
323
+ currentSlot: Slot
324
+ ): ShouldOverrideForkChoiceUpdateResult {
325
+ if (!this.opts?.proposerBoostReorg) {
326
+ return {shouldOverrideFcu: false, reason: NotReorgedReason.ProposerBoostReorgDisabled};
327
+ }
328
+ const parentBlock = this.getParentNode(headBlock);
329
+ if (parentBlock === undefined) {
330
+ return {shouldOverrideFcu: false, reason: NotReorgedReason.ParentBlockNotAvailable};
331
+ }
332
+
333
+ const proposalSlot = headBlock.slot + 1;
334
+ const currentTimeOk =
335
+ headBlock.slot === currentSlot ||
336
+ (proposalSlot === currentSlot &&
337
+ msFromSlot <= this.config.getProposerReorgCutoffMs(this.config.getForkName(currentSlot)));
338
+ if (currentTimeOk && this.isProposerEquivocation(headBlock)) {
339
+ return {shouldOverrideFcu: true, parentBlock};
340
+ }
341
+
342
+ const reason = this.preliminaryNotReorgedReason(headBlock, parentBlock, proposalSlot);
343
+ if (reason !== null) {
344
+ return {shouldOverrideFcu: false, reason};
345
+ }
346
+ if (!currentTimeOk) {
347
+ return {shouldOverrideFcu: false, reason: NotReorgedReason.ReorgMoreThanOneSlot};
348
+ }
349
+ return {shouldOverrideFcu: true, parentBlock};
350
+ }
351
+
352
+ /** The proposer head of the next slot, as `ForkChoice.predictProposerHead` */
353
+ predictProposerHead(headBlock: ProtoBlock, msFromSlot: number, currentSlot: Slot): ProtoBlock {
354
+ const result = this.shouldOverrideForkChoiceUpdate(headBlock, msFromSlot, currentSlot);
355
+ if (!result.shouldOverrideFcu) {
356
+ return headBlock;
357
+ }
358
+ this.logger?.verbose("Current head is weak. Predicting next block to be built on parent of head.", {
359
+ slot: currentSlot,
360
+ proposerHead: result.parentBlock.blockRoot,
361
+ weakHead: headBlock.blockRoot,
362
+ });
363
+ return result.parentBlock;
364
+ }
365
+
366
+ /** The block-only conditions of `get_proposer_head`, null when they allow a reorg */
367
+ private preliminaryNotReorgedReason(
368
+ headBlock: ProtoBlock,
369
+ parentBlock: ProtoBlock,
370
+ slot: Slot
371
+ ): NotReorgedReason | null {
372
+ if (headBlock.timeliness) {
373
+ return NotReorgedReason.HeadBlockIsTimely;
374
+ }
375
+ if (!isForkPostFulu(this.config.getForkName(slot)) && slot % SLOTS_PER_EPOCH === 0) {
376
+ return NotReorgedReason.NotShufflingStable;
377
+ }
378
+ if (
379
+ headBlock.unrealizedJustifiedEpoch !== parentBlock.unrealizedJustifiedEpoch ||
380
+ headBlock.unrealizedJustifiedRoot !== parentBlock.unrealizedJustifiedRoot
381
+ ) {
382
+ return NotReorgedReason.NotFFGCompetitive;
383
+ }
384
+ if (
385
+ computeEpochAtSlot(slot) - this.fcStore.finalizedCheckpoint.epoch >
386
+ this.config.REORG_MAX_EPOCHS_SINCE_FINALIZATION
387
+ ) {
388
+ return NotReorgedReason.ChainLongUnfinality;
389
+ }
390
+ if (parentBlock.slot + 1 !== headBlock.slot) {
391
+ return NotReorgedReason.ParentBlockDistanceMoreThanOneSlot;
392
+ }
393
+ return null;
394
+ }
395
+
396
+ private getParentNode(block: ProtoBlock): ProtoBlock | undefined {
397
+ const node = this.getNodeId(block.blockRoot, block.payloadStatus);
398
+ const parentNode = node === undefined ? undefined : this.parentNodes[Math.floor(node / NODES_PER_BLOCK)];
399
+ return parentNode === undefined || parentNode === null ? undefined : this.nodes[parentNode];
400
+ }
401
+
402
+ /**
403
+ * Spec `get_proposer_head`. `msFromSlot` is how far into `slot` the proposer is; the store takes
404
+ * it as an argument rather than a tick, so its clock and head cache stay where they are.
405
+ */
406
+ getProposerHead(
407
+ headBlock: ProtoBlock,
408
+ msFromSlot: number,
409
+ slot: Slot
410
+ ): {proposerHead: ProtoBlock; isHeadTimely: boolean; notReorgedReason?: NotReorgedReason} {
411
+ const isHeadTimely = headBlock.timeliness;
412
+ if (!this.opts?.proposerBoostReorg) {
413
+ return {proposerHead: headBlock, isHeadTimely, notReorgedReason: NotReorgedReason.ProposerBoostReorgDisabled};
414
+ }
415
+
416
+ const headNode = this.getNodeId(headBlock.blockRoot, headBlock.payloadStatus);
417
+ if (headNode === undefined) {
418
+ return {proposerHead: headBlock, isHeadTimely, notReorgedReason: NotReorgedReason.HeadBlockNotAvailable};
419
+ }
420
+ if (this.parentNodes[Math.floor(headNode / NODES_PER_BLOCK)] === undefined) {
421
+ return {proposerHead: headBlock, isHeadTimely, notReorgedReason: NotReorgedReason.ParentBlockNotAvailable};
422
+ }
423
+
424
+ this.updateTime(slot);
425
+ let decision: number | KeepHeadReason;
426
+ try {
427
+ decision = this.store.getProposerHead(headNode, slot, Math.max(0, Math.floor(msFromSlot)));
428
+ } catch (e) {
429
+ // `is_head_weak` reads the head state's committees once an equivocator is known; without it, propose on the head
430
+ if (!(e instanceof ForkChoiceError && e.type.code === ForkChoiceErrorCode.BEACON_STATE_ERROR)) throw e;
431
+ this.logger?.warn("Proposer reorg check skipped, head state not available", {slot, head: headBlock.blockRoot}, e);
432
+ return {proposerHead: headBlock, isHeadTimely, notReorgedReason: NotReorgedReason.HeadStateNotAvailable};
433
+ }
434
+ if (typeof decision === "string") {
435
+ return {proposerHead: headBlock, isHeadTimely, notReorgedReason: KEEP_HEAD_REASONS[decision]};
436
+ }
437
+
438
+ const parentBlock = this.nodes[decision];
439
+ if (parentBlock === undefined) {
440
+ return {proposerHead: headBlock, isHeadTimely, notReorgedReason: NotReorgedReason.ParentBlockNotAvailable};
441
+ }
442
+ this.logger?.verbose("Performing single-slot reorg to remove current weak head", {
443
+ slot,
444
+ proposerHead: parentBlock.blockRoot,
445
+ weakHead: headBlock.blockRoot,
446
+ });
447
+ return {proposerHead: parentBlock, isHeadTimely};
448
+ }
449
+
450
+ getHeads(): ProtoBlock[] {
451
+ const {bestChildren} = this.getScores();
452
+ const heads: ProtoBlock[] = [];
453
+ for (const id of this.nodeIds()) {
454
+ if (bestChildren[id] === NO_NODE) {
455
+ heads.push(this.nodes[id] as ProtoBlock);
456
+ }
457
+ }
458
+ return heads;
459
+ }
460
+
461
+ /** Exact Gwei weights of the leaves of the filtered block tree, for the compliance tests */
462
+ getViableHeads(): {root: RootHex; payloadStatus: PayloadStatus; weight: bigint}[] {
463
+ return this.store.viableHeads().map(({root, payloadStatus, weight}) => {
464
+ const rootHex = toRootHex(root);
465
+ const blockIndex = this.blockIndexByRoot.get(rootHex);
466
+ const node = blockIndex === undefined ? undefined : this.nodes[blockIndex * NODES_PER_BLOCK + payloadStatus];
467
+ if (node === undefined) {
468
+ throw new ForkChoiceError({code: ForkChoiceErrorCode.MISSING_PROTO_ARRAY_BLOCK, root: rootHex});
469
+ }
470
+ return {root: rootHex, payloadStatus: node.payloadStatus, weight};
471
+ });
472
+ }
473
+
474
+ getAllNodes(): ProtoNode[] {
475
+ const ids = this.nodeIds();
476
+ const positionById = new Map<number, number>();
477
+ for (const [position, id] of ids.entries()) {
478
+ positionById.set(id, position);
479
+ }
480
+ const {weights, attestationScores, bestChildren} = this.getScores();
481
+ return ids.map((id) => {
482
+ let bestDescendant = bestChildren[id];
483
+ while (bestDescendant !== NO_NODE && bestChildren[bestDescendant] !== NO_NODE) {
484
+ bestDescendant = bestChildren[bestDescendant];
485
+ }
486
+ const parent =
487
+ id % NODES_PER_BLOCK === NativePayloadStatus.Pending
488
+ ? this.parentNodes[Math.floor(id / NODES_PER_BLOCK)]
489
+ : id - (id % NODES_PER_BLOCK) + NativePayloadStatus.Pending;
490
+ return {
491
+ ...(this.nodes[id] as ProtoBlock),
492
+ parent: parent === undefined ? undefined : positionById.get(parent),
493
+ weight: weights[id],
494
+ attestationScore: attestationScores[id],
495
+ bestChild: positionById.get(bestChildren[id]),
496
+ bestDescendant: positionById.get(bestDescendant),
497
+ };
498
+ });
499
+ }
500
+
501
+ // Fast confirmation
502
+
503
+ getConfirmedRoot(): RootHex {
504
+ return this.fastConfirmation ? this.fcStore.confirmedRoot : this.fcStore.justified.checkpoint.rootHex;
505
+ }
506
+
507
+ getConfirmedBlock(): ProtoBlock | null {
508
+ return this.getBlockHexDefaultStatus(this.getConfirmedRoot());
509
+ }
510
+
511
+ getFastConfirmationStore(): IFastConfirmationSpecStore {
512
+ if (!this.fastConfirmation) {
513
+ return {
514
+ confirmedRoot: this.getConfirmedRoot(),
515
+ previousEpochObservedJustifiedCheckpoint: this.fcStore.previousEpochObservedJustifiedCheckpoint,
516
+ currentEpochObservedJustifiedCheckpoint: this.fcStore.currentEpochObservedJustifiedCheckpoint,
517
+ previousEpochGreatestUnrealizedCheckpoint: this.fcStore.previousEpochGreatestUnrealizedCheckpoint,
518
+ previousSlotHead: this.fcStore.previousSlotHead,
519
+ currentSlotHead: this.fcStore.currentSlotHead,
520
+ };
521
+ }
522
+ const fcr = this.store.fastConfirmationStore();
523
+ return {
524
+ confirmedRoot: this.getConfirmedRoot(),
525
+ previousEpochObservedJustifiedCheckpoint: toCheckpointWithHex(fcr.previousEpochObservedJustifiedCheckpoint),
526
+ currentEpochObservedJustifiedCheckpoint: toCheckpointWithHex(fcr.currentEpochObservedJustifiedCheckpoint),
527
+ previousEpochGreatestUnrealizedCheckpoint: toCheckpointWithHex(fcr.previousEpochGreatestUnrealizedCheckpoint),
528
+ previousSlotHead: toRootHex(fcr.previousSlotHead),
529
+ currentSlotHead: toRootHex(fcr.currentSlotHead),
530
+ };
531
+ }
532
+
533
+ resumeFastConfirmation(): void {
534
+ this.toggleFastConfirmation(false);
535
+ }
536
+
537
+ pauseFastConfirmation(): void {
538
+ this.toggleFastConfirmation(true);
539
+ }
540
+
541
+ private toggleFastConfirmation(paused: boolean): void {
542
+ if (!this.fastConfirmation || paused === this.fastConfirmationPaused) return;
543
+ this.fastConfirmationPaused = paused;
544
+ if (paused) {
545
+ this.fcStore.confirmedRoot = this.fcStore.finalizedCheckpoint.rootHex;
546
+ this.notifyConfirmedRoot();
547
+ }
548
+ this.metrics?.fastConfirmation.paused.set(paused ? 1 : 0);
549
+ this.logger?.info(paused ? "Paused fast confirmation" : "Resumed fast confirmation", {
550
+ slot: this.fcStore.currentSlot,
551
+ });
552
+ }
553
+
554
+ private notifyConfirmedRoot(): void {
555
+ const confirmedRoot = this.fcStore.confirmedRoot;
556
+ const confirmedBlock = this.getBlockHexDefaultStatus(confirmedRoot);
557
+ if (confirmedBlock === null) {
558
+ this.logger?.debug("Fast confirmation produced root not in fork choice", {confirmedRoot});
559
+ return;
560
+ }
561
+ this.fcStore.notifyFastConfirmation?.({
562
+ block: confirmedRoot,
563
+ slot: confirmedBlock.slot,
564
+ currentSlot: this.fcStore.currentSlot,
565
+ });
566
+ }
567
+
568
+ /** Returns whether it recomputed the head */
569
+ private runFastConfirmation(): boolean {
570
+ if (!this.fastConfirmation) return false;
571
+
572
+ if (this.fastConfirmationPaused) {
573
+ this.fcStore.confirmedRoot = this.fcStore.finalizedCheckpoint.rootHex;
574
+ this.notifyConfirmedRoot();
575
+ return false;
576
+ }
577
+
578
+ withObservedDuration(this.metrics?.fastConfirmation.totalDuration.startTimer(), () => {
579
+ try {
580
+ withObservedDuration(
581
+ this.metrics?.fastConfirmation.stepsDuration.startTimer({step: FastConfirmationSteps.updateHead}),
582
+ () => this.updateHead()
583
+ );
584
+ const previousConfirmedRoot = this.fcStore.confirmedRoot;
585
+ withObservedDuration(
586
+ this.metrics?.fastConfirmation.stepsDuration.startTimer({step: FastConfirmationSteps.runRules}),
587
+ () => this.store.onFastConfirmation()
588
+ );
589
+ this.fcStore.confirmedRoot = toRootHex(this.store.confirmedRoot);
590
+ this.updateFastConfirmationMetrics(previousConfirmedRoot);
591
+ } catch (err) {
592
+ const previousConfirmedRoot = this.fcStore.confirmedRoot;
593
+ const finalizedRoot = this.fcStore.finalizedCheckpoint.rootHex;
594
+ this.fcStore.confirmedRoot = finalizedRoot;
595
+ if (previousConfirmedRoot !== finalizedRoot) {
596
+ this.metrics?.fastConfirmation.resets.inc();
597
+ this.metrics?.fastConfirmation.fallbacks.inc();
598
+ }
599
+ const finalizedBlock = this.getBlockHexDefaultStatus(finalizedRoot);
600
+ if (finalizedBlock !== null) {
601
+ this.metrics?.fastConfirmation.confirmedEpoch.set(computeEpochAtSlot(finalizedBlock.slot));
602
+ this.metrics?.fastConfirmation.slot.set(finalizedBlock.slot);
603
+ }
604
+ this.logger?.warn(
605
+ "Fast confirmation failed, reverting to finalized",
606
+ {
607
+ slot: this.fcStore.currentSlot,
608
+ head: this.head.blockRoot,
609
+ previousConfirmedRoot,
610
+ confirmedRoot: finalizedRoot,
611
+ },
612
+ err as Error
613
+ );
614
+ }
615
+ });
616
+
617
+ this.notifyConfirmedRoot();
618
+ return true;
619
+ }
620
+
621
+ private updateFastConfirmationMetrics(previousConfirmedRoot: RootHex): void {
622
+ const metrics = this.metrics?.fastConfirmation;
623
+ if (!metrics) return;
624
+ const confirmedRoot = this.fcStore.confirmedRoot;
625
+ const confirmedBlock = this.getBlockHexDefaultStatus(confirmedRoot);
626
+ if (confirmedBlock !== null) {
627
+ metrics.confirmedEpoch.set(computeEpochAtSlot(confirmedBlock.slot));
628
+ metrics.slot.set(confirmedBlock.slot);
629
+ }
630
+ if (confirmedRoot !== previousConfirmedRoot) {
631
+ const previousBlock = this.getBlockHexDefaultStatus(previousConfirmedRoot);
632
+ if (previousBlock !== null && confirmedBlock !== null && confirmedBlock.slot < previousBlock.slot) {
633
+ metrics.resets.inc();
634
+ }
635
+ if (confirmedRoot === this.fcStore.finalizedCheckpoint.rootHex) {
636
+ metrics.fallbacks.inc();
637
+ }
638
+ }
639
+ metrics.votesTracked.set(this.store.voteCount);
640
+ }
641
+
642
+ // Checkpoints and time
643
+
644
+ getFinalizedCheckpoint(): CheckpointWithHex {
645
+ return this.fcStore.finalizedCheckpoint;
646
+ }
647
+
648
+ getJustifiedCheckpoint(): CheckpointWithHex {
649
+ return this.fcStore.justified.checkpoint;
650
+ }
651
+
652
+ getUnrealizedJustifiedCheckpoint(): CheckpointWithHex {
653
+ return this.fcStore.unrealizedJustified.checkpoint;
654
+ }
655
+
656
+ getUnrealizedFinalizedCheckpoint(): CheckpointWithHex {
657
+ return this.fcStore.unrealizedFinalizedCheckpoint;
658
+ }
659
+
660
+ getFinalizedCheckpointSlot(): Slot {
661
+ return computeStartSlotAtEpoch(this.fcStore.finalizedCheckpoint.epoch);
662
+ }
663
+
664
+ getProposerBoostRoot(): RootHex {
665
+ return toRootHex(this.store.proposerBoostRoot);
666
+ }
667
+
668
+ getPreviousProposerBoostRoot(): RootHex {
669
+ return this.previousProposerBoostRoot;
670
+ }
671
+
672
+ getTime(): Slot {
673
+ return this.fcStore.currentSlot;
674
+ }
675
+
676
+ updateTime(currentSlot: Slot): void {
677
+ while (this.fcStore.currentSlot < currentSlot) {
678
+ const slot = this.fcStore.currentSlot + 1;
679
+ this.mutated();
680
+ const queuedVoteCount = this.store.queuedVoteCount;
681
+ this.store.onTick(this.store.timeAtSlotMs(slot));
682
+ this.queuedAttestationsPreviousSlot = queuedVoteCount - this.store.queuedVoteCount;
683
+ this.fcStore.currentSlot = slot;
684
+ const didUpdateCheckpoints = this.syncCheckpoints();
685
+ if (didUpdateCheckpoints) {
686
+ // Throw before fast confirmation, which swallows head computation errors
687
+ const justified = this.fcStore.justified.checkpoint;
688
+ if (this.getBlockHexDefaultStatus(justified.rootHex)?.executionStatus === ExecutionStatus.Invalid) {
689
+ throw new ForkChoiceError({
690
+ code: ForkChoiceErrorCode.INVALID_JUSTIFIED_EXECUTION_STATUS,
691
+ epoch: justified.epoch,
692
+ root: justified.rootHex,
693
+ });
694
+ }
695
+ }
696
+ const didRecomputeHead = this.runFastConfirmation();
697
+ // A checkpoint pulled up at the epoch boundary can move the head before the next block arrives
698
+ if (didUpdateCheckpoints && !didRecomputeHead) {
699
+ this.updateHead();
700
+ }
701
+ }
702
+ }
703
+
704
+ /** Mirrors the store's checkpoints into `fcStore`, whose setters emit the chain events */
705
+ private syncCheckpoints(): boolean {
706
+ const checkpoints = this.store.checkpoints();
707
+ let updated = false;
708
+
709
+ const unrealizedJustified = toCheckpointWithHex(checkpoints.unrealizedJustified);
710
+ if (!equalCheckpointWithHex(unrealizedJustified, this.fcStore.unrealizedJustified.checkpoint)) {
711
+ // Captured while the block's state is at hand: the epoch boundary tick that realizes this
712
+ // checkpoint has no state to fall back to
713
+ this.fcStore.unrealizedJustified = {
714
+ checkpoint: unrealizedJustified,
715
+ balances: this.balancesOf(unrealizedJustified),
716
+ };
717
+ }
718
+ const unrealizedFinalized = toCheckpointWithHex(checkpoints.unrealizedFinalized);
719
+ if (!equalCheckpointWithHex(unrealizedFinalized, this.fcStore.unrealizedFinalizedCheckpoint)) {
720
+ this.fcStore.unrealizedFinalizedCheckpoint = unrealizedFinalized;
721
+ }
722
+
723
+ const justified = toCheckpointWithHex(checkpoints.justified);
724
+ if (!equalCheckpointWithHex(justified, this.fcStore.justified.checkpoint)) {
725
+ this.fcStore.justified = {checkpoint: justified, balances: this.balancesOf(justified)};
726
+ updated = true;
727
+ }
728
+ const finalized = toCheckpointWithHex(checkpoints.finalized);
729
+ if (!equalCheckpointWithHex(finalized, this.fcStore.finalizedCheckpoint)) {
730
+ this.fcStore.finalizedCheckpoint = finalized;
731
+ updated = true;
732
+ }
733
+ return updated;
734
+ }
735
+
736
+ private balancesOf(checkpoint: CheckpointWithHex): EffectiveBalanceIncrements {
737
+ for (const known of [this.providedBalances, this.fcStore.unrealizedJustified, this.fcStore.justified]) {
738
+ if (known !== null && equalCheckpointWithHex(known.checkpoint, checkpoint)) {
739
+ return known.balances;
740
+ }
741
+ }
742
+ if (this.importingState === null) {
743
+ // The anchor's balances are the ones the store was created with
744
+ if (this.blockIndexByRoot.size === 0) return this.fcStore.justified.balances;
745
+ throw Error(`No balances for justified checkpoint ${checkpoint.epoch} ${checkpoint.rootHex}`);
746
+ }
747
+ return this.fcStore.justifiedBalancesGetter(checkpoint, this.importingState);
748
+ }
749
+
750
+ private provideJustifiedBalances(epoch: number, root: Uint8Array): EffectiveBalanceIncrements {
751
+ // The store hands out a view of its own memory, valid for this call only
752
+ const checkpoint = toCheckpointWithHex({epoch, root: root.slice()});
753
+ const balances = this.balancesOf(checkpoint);
754
+ this.providedBalances = {checkpoint, balances};
755
+ return balances;
756
+ }
757
+
758
+ /** The state of block `root`, which `is_head_weak` reads; the head and the boosted block's parent are cached */
759
+ private blockState(root: Uint8Array): IBeaconStateView {
760
+ const blockRoot = toRootHex(root);
761
+ const block = this.getDefaultNode(blockRoot);
762
+ const state = block === undefined ? null : this.fcStore.stateGetter({stateRoot: block.stateRoot});
763
+ if (state === null) {
764
+ throw new ForkChoiceError({
765
+ code: ForkChoiceErrorCode.BEACON_STATE_ERROR,
766
+ error: Error(`Missing state for isHeadWeak, blockRoot=${blockRoot}`),
767
+ });
768
+ }
769
+ return state;
770
+ }
771
+
772
+ private provideSlotCommitteeMembers(root: Uint8Array, slot: Slot): Uint32Array {
773
+ const state = this.blockState(root);
774
+ const committeeCount = state.getBeaconCommitteeCountPerSlot(computeEpochAtSlot(slot));
775
+ let memberCount = 0;
776
+ for (let index = 0; index < committeeCount; index++) {
777
+ memberCount += state.getBeaconCommittee(slot, index).length;
778
+ }
779
+ const members = new Uint32Array(memberCount);
780
+ let offset = 0;
781
+ for (let index = 0; index < committeeCount; index++) {
782
+ const committee = state.getBeaconCommittee(slot, index);
783
+ members.set(committee, offset);
784
+ offset += committee.length;
785
+ }
786
+ return members;
787
+ }
788
+
789
+ private provideCheckpointBalanceSource(epoch: number, root: Uint8Array): BalanceSource {
790
+ const checkpoint = toCheckpointWithHex({epoch, root: root.slice()});
791
+ const state = this.fcStore.stateGetter({checkpoint});
792
+ if (state) return balanceSourceOf(state);
793
+ // As the TypeScript rule does, fall back to the balances captured with the checkpoint
794
+ const balances = this.balancesOf(checkpoint);
795
+ const activeIndices: number[] = [];
796
+ for (let i = 0; i < balances.length; i++) {
797
+ if (balances[i] > 0) activeIndices.push(i);
798
+ }
799
+ return {
800
+ effectiveBalanceIncrements: balances,
801
+ zeroInactiveIncrements: balances,
802
+ activeIndices: Uint32Array.from(activeIndices),
803
+ };
804
+ }
805
+
806
+ private providePulledUpBalanceSource(root: Uint8Array, epoch: number): BalanceSource {
807
+ const blockRoot = toRootHex(root);
808
+ const block = this.getDefaultNode(blockRoot);
809
+ const headState = block === undefined ? null : this.fcStore.stateGetter({stateRoot: block.stateRoot});
810
+ if (!headState) {
811
+ throw new ForkChoiceError({
812
+ code: ForkChoiceErrorCode.BEACON_STATE_ERROR,
813
+ error: Error(`Missing state for fast confirmation, blockRoot=${blockRoot}`),
814
+ });
815
+ }
816
+ const state = headState.epoch < epoch ? headState.processSlots(computeStartSlotAtEpoch(epoch)) : headState;
817
+ return balanceSourceOf(state);
818
+ }
819
+
820
+ // Handlers
821
+
822
+ onBlock(
823
+ block: BeaconBlock,
824
+ state: IBeaconStateView,
825
+ receiveDelayMs: number,
826
+ importDelayMs: number,
827
+ currentSlot: Slot,
828
+ executionStatus: BlockExecutionStatus,
829
+ dataAvailabilityStatus: DataAvailabilityStatus
830
+ ): ProtoBlock {
831
+ const {parentRoot, slot} = block;
832
+ const parentRootHex = toRootHex(parentRoot);
833
+ const bid = isGloasBeaconBlock(block) ? block.body.signedExecutionPayloadBid.message : null;
834
+ const parentHashHex = bid === null ? null : toRootHex(bid.parentBlockHash);
835
+ const parentBlock = this.getParent(parentRootHex, parentHashHex);
836
+ if (parentBlock === null) {
837
+ throw new ForkChoiceError({
838
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
839
+ err: {code: InvalidBlockCode.UNKNOWN_PARENT, root: parentRootHex, hash: parentHashHex},
840
+ });
841
+ }
842
+
843
+ const blockRoot = this.config.getForkTypes(slot).BeaconBlock.hashTreeRoot(block);
844
+ const blockRootHex = toRootHex(blockRoot);
845
+ const justifiedCheckpoint = toCheckpointWithHex(state.currentJustifiedCheckpoint);
846
+ const finalizedCheckpoint = toCheckpointWithHex(state.finalizedCheckpoint);
847
+ const blockEpoch = computeEpochAtSlot(slot);
848
+
849
+ // The parent's unrealized checkpoints carry over when the block cannot change them, see
850
+ // `ForkChoice.onBlock`
851
+ let unrealizedJustifiedCheckpoint: CheckpointWithHex;
852
+ let unrealizedFinalizedCheckpoint: CheckpointWithHex;
853
+ if (
854
+ block.body.proposerSlashings.length === 0 &&
855
+ block.body.attesterSlashings.length === 0 &&
856
+ parentBlock.unrealizedJustifiedEpoch === blockEpoch &&
857
+ parentBlock.unrealizedFinalizedEpoch + 1 >= blockEpoch
858
+ ) {
859
+ unrealizedJustifiedCheckpoint = {
860
+ epoch: parentBlock.unrealizedJustifiedEpoch,
861
+ root: fromHex(parentBlock.unrealizedJustifiedRoot),
862
+ rootHex: parentBlock.unrealizedJustifiedRoot,
863
+ };
864
+ unrealizedFinalizedCheckpoint = {
865
+ epoch: parentBlock.unrealizedFinalizedEpoch,
866
+ root: fromHex(parentBlock.unrealizedFinalizedRoot),
867
+ rootHex: parentBlock.unrealizedFinalizedRoot,
868
+ };
869
+ } else {
870
+ const unrealized = state.computeUnrealizedCheckpoints();
871
+ unrealizedJustifiedCheckpoint = toCheckpointWithHex(unrealized.justifiedCheckpoint);
872
+ unrealizedFinalizedCheckpoint = toCheckpointWithHex(unrealized.finalizedCheckpoint);
873
+ }
874
+
875
+ const hasPayload =
876
+ bid === null &&
877
+ isExecutionBlockBodyType(block.body) &&
878
+ isStatePostBellatrix(state) &&
879
+ state.isExecutionStateType &&
880
+ state.isExecutionEnabled(block);
881
+ const payload = hasPayload && isExecutionBlockBodyType(block.body) ? block.body.executionPayload : null;
882
+ if (bid === null && payload === null && executionStatus !== ExecutionStatus.PreMerge) {
883
+ throw Error(`Invalid pre-merge execution status: expected: ${ExecutionStatus.PreMerge}, got ${executionStatus}`);
884
+ }
885
+ if ((bid !== null || payload !== null) && executionStatus === ExecutionStatus.PreMerge) {
886
+ throw Error(`Invalid post-merge execution status: got ${executionStatus}`);
887
+ }
888
+
889
+ const payloadBlockHash = bid?.blockHash ?? payload?.blockHash;
890
+ const summary: BlockSummary = {
891
+ root: blockRoot,
892
+ parentRoot,
893
+ slot,
894
+ proposerIndex: block.proposerIndex,
895
+ stateRoot: block.stateRoot,
896
+ justifiedCheckpoint,
897
+ finalizedCheckpoint,
898
+ unrealizedJustifiedCheckpoint,
899
+ unrealizedFinalizedCheckpoint,
900
+ payloadBlockHash,
901
+ bidParentBlockHash: bid?.parentBlockHash,
902
+ // A zero hash is no payload, and a Gloas payload is only judged when its envelope arrives
903
+ executionStatus:
904
+ payloadBlockHash === undefined || ssz.Root.equals(payloadBlockHash, ZERO_HASH)
905
+ ? NativeExecutionStatus.PreMerge
906
+ : bid !== null
907
+ ? NativeExecutionStatus.Syncing
908
+ : EXECUTION_STATUS_TO_NATIVE[executionStatus],
909
+ arrivalMsIntoSlot: Math.max(0, Math.floor(receiveDelayMs)),
910
+ validatorCount: state.validatorCount,
911
+ };
912
+
913
+ let blockIndex: number;
914
+ this.mutated();
915
+ this.importingState = state;
916
+ try {
917
+ blockIndex = this.store.onBlock(summary);
918
+ } catch (e) {
919
+ throw this.toInvalidBlockError(e, block, blockRootHex, payloadBlockHash, parentRootHex, parentHashHex);
920
+ } finally {
921
+ // Checkpoints the store adopted during the call are mirrored while the state is at hand
922
+ this.syncCheckpoints();
923
+ this.importingState = null;
924
+ }
925
+
926
+ const [timeliness, ptcTimeliness] = this.store.blockTimeliness(blockIndex);
927
+ const targetSlot = computeStartSlotAtEpoch(blockEpoch);
928
+ const targetRoot = slot === targetSlot ? blockRoot : state.getBlockRootAtSlot(targetSlot);
929
+ const fork = this.config.getForkName(slot);
930
+ const protoBlock: ProtoBlock = {
931
+ slot,
932
+ blockRoot: blockRootHex,
933
+ parentRoot: parentRootHex,
934
+ targetRoot: toRootHex(targetRoot),
935
+ stateRoot: toRootHex(block.stateRoot),
936
+ timeliness,
937
+ ptcTimeliness,
938
+ importedTimely: currentSlot === slot && importDelayMs < this.config.getAttestationDueMs(fork),
939
+ proposerIndex: block.proposerIndex,
940
+
941
+ justifiedEpoch: justifiedCheckpoint.epoch,
942
+ justifiedRoot: justifiedCheckpoint.rootHex,
943
+ finalizedEpoch: finalizedCheckpoint.epoch,
944
+ finalizedRoot: finalizedCheckpoint.rootHex,
945
+ unrealizedJustifiedEpoch: unrealizedJustifiedCheckpoint.epoch,
946
+ unrealizedJustifiedRoot: unrealizedJustifiedCheckpoint.rootHex,
947
+ unrealizedFinalizedEpoch: unrealizedFinalizedCheckpoint.epoch,
948
+ unrealizedFinalizedRoot: unrealizedFinalizedCheckpoint.rootHex,
949
+
950
+ ...(parentHashHex !== null
951
+ ? {
952
+ // Until its payload arrives a Gloas block reports the parent payload its bid builds on
953
+ executionPayloadBlockHash: parentHashHex,
954
+ executionPayloadNumber:
955
+ parentBlock.executionPayloadBlockHash === null ? 0 : parentBlock.executionPayloadNumber,
956
+ executionPayloadGasLimit:
957
+ parentBlock.executionPayloadBlockHash === null ? 0 : parentBlock.executionPayloadGasLimit,
958
+ executionStatus: executionStatus as ExecutionStatus.Valid | ExecutionStatus.Syncing,
959
+ dataAvailabilityStatus,
960
+ }
961
+ : payload !== null
962
+ ? {
963
+ executionPayloadBlockHash: toRootHex(payload.blockHash),
964
+ executionPayloadNumber: payload.blockNumber,
965
+ executionPayloadGasLimit: payload.gasLimit,
966
+ executionStatus: executionStatus as ExecutionStatus.Valid | ExecutionStatus.Syncing,
967
+ dataAvailabilityStatus,
968
+ }
969
+ : {
970
+ executionPayloadBlockHash: null,
971
+ executionStatus: ExecutionStatus.PreMerge,
972
+ dataAvailabilityStatus: DataAvailabilityStatus.PreData,
973
+ }),
974
+
975
+ payloadStatus: parentHashHex !== null ? PayloadStatus.PENDING : PayloadStatus.FULL,
976
+ parentBlockHash: parentHashHex,
977
+ };
978
+
979
+ this.insertBlock(blockIndex, protoBlock);
980
+ this.refreshExecutionStatuses();
981
+ return {...(this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] as ProtoBlock)};
982
+ }
983
+
984
+ onAttestation(attestation: IndexedAttestation, _attDataRoot: string, forceImport?: boolean): void {
985
+ const {data, attestingIndices} = attestation;
986
+ // The spec aliases the zero hash to genesis; such votes carry no information
987
+ if (ssz.Root.equals(data.beaconBlockRoot, ZERO_HASH)) {
988
+ return;
989
+ }
990
+ if (attestingIndices.length === 0) {
991
+ throw new ForkChoiceError({
992
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
993
+ err: {code: InvalidAttestationCode.EMPTY_AGGREGATION_BITFIELD},
994
+ });
995
+ }
996
+
997
+ this.mutated();
998
+ try {
999
+ this.store.onAttestation(
1000
+ data.slot,
1001
+ data.index,
1002
+ data.beaconBlockRoot,
1003
+ data.target.epoch,
1004
+ data.target.root,
1005
+ Uint32Array.from(attestingIndices),
1006
+ forceImport === true
1007
+ );
1008
+ } catch (e) {
1009
+ throw this.toInvalidAttestationError(e, data);
1010
+ }
1011
+ }
1012
+
1013
+ onAttesterSlashing(slashing: AttesterSlashing): void {
1014
+ const {attestation1, attestation2} = slashing;
1015
+ this.mutated();
1016
+ this.store.onAttesterSlashing(
1017
+ toNativeAttestationData(attestation1.data),
1018
+ Uint32Array.from(attestation1.attestingIndices),
1019
+ toNativeAttestationData(attestation2.data),
1020
+ Uint32Array.from(attestation2.attestingIndices)
1021
+ );
1022
+ for (const validatorIndex of getAttesterSlashableIndices(slashing)) {
1023
+ this.fcStore.equivocatingIndices.add(validatorIndex);
1024
+ }
1025
+ }
1026
+
1027
+ notifyPtcMessages(
1028
+ blockRoot: RootHex,
1029
+ slot: Slot,
1030
+ ptcIndices: number[],
1031
+ payloadPresent: boolean,
1032
+ blobDataAvailable: boolean
1033
+ ): void {
1034
+ const before = this.getPtcQuorum(blockRoot);
1035
+ if (before === null) {
1036
+ return;
1037
+ }
1038
+ this.mutated();
1039
+ this.store.onPtcVotes(fromHex(blockRoot), slot, Uint16Array.from(ptcIndices), payloadPresent, blobDataAvailable);
1040
+ const after = this.getPtcQuorum(blockRoot);
1041
+ if (after === null) {
1042
+ return;
1043
+ }
1044
+ const verdict = getPtcVerdict(after);
1045
+ if (verdict === null || verdict === getPtcVerdict(before)) {
1046
+ return;
1047
+ }
1048
+
1049
+ this.metrics?.forkChoice.ptcQuorum.inc({verdict: verdict ? "true" : "false"});
1050
+ this.logger?.verbose("PTC quorum reached", {slot, blockRoot, verdict, ...after});
1051
+ this.fcStore.notifyPtcQuorum?.({blockRoot, slot, verdict, ...after});
1052
+ }
1053
+
1054
+ onExecutionPayload(
1055
+ blockRoot: RootHex,
1056
+ executionPayloadBlockHash: RootHex,
1057
+ executionPayloadNumber: number,
1058
+ executionPayloadGasLimit: number,
1059
+ executionStatus: PayloadExecutionStatus,
1060
+ dataAvailabilityStatus: DataAvailabilityStatus
1061
+ ): void {
1062
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1063
+ const pendingNode =
1064
+ blockIndex === undefined ? undefined : this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending];
1065
+ if (blockIndex === undefined || pendingNode === undefined) {
1066
+ throw new ProtoArrayError({code: ProtoArrayErrorCode.UNKNOWN_BLOCK, root: blockRoot});
1067
+ }
1068
+ if (!isGloasBlock(pendingNode)) {
1069
+ throw new ProtoArrayError({code: ProtoArrayErrorCode.PRE_GLOAS_BLOCK, root: blockRoot});
1070
+ }
1071
+ if (pendingNode.executionStatus === ExecutionStatus.Invalid) {
1072
+ throw new ForkChoiceError({
1073
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1074
+ err: {
1075
+ code: InvalidBlockCode.PARENT_EXECUTION_INVALID,
1076
+ root: pendingNode.parentRoot,
1077
+ hash: pendingNode.executionPayloadBlockHash,
1078
+ },
1079
+ });
1080
+ }
1081
+ if (this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Full] === undefined) {
1082
+ this.mutated();
1083
+ try {
1084
+ this.store.onExecutionPayload(fromHex(blockRoot), EXECUTION_STATUS_TO_NATIVE[executionStatus]);
1085
+ } catch (e) {
1086
+ throw toPayloadDeliveryError(e, blockRoot, executionPayloadBlockHash);
1087
+ }
1088
+ this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Full] = {
1089
+ ...pendingNode,
1090
+ payloadStatus: PayloadStatus.FULL,
1091
+ executionStatus,
1092
+ executionPayloadBlockHash,
1093
+ executionPayloadNumber,
1094
+ executionPayloadGasLimit,
1095
+ dataAvailabilityStatus,
1096
+ };
1097
+ this.refreshExecutionStatuses();
1098
+ }
1099
+
1100
+ // Unlike ForkChoice, a same-slot refresh also counts the votes received since the last updateHead()
1101
+ if (this.fcStore.currentSlot === this.updateHeadSlot) {
1102
+ this.head = this.storeHead();
1103
+ } else {
1104
+ this.updateHead();
1105
+ }
1106
+ }
1107
+
1108
+ validateLatestHash(execResponse: LVHExecResponse): LVHVerdictResult {
1109
+ this.mutated();
1110
+ let verdict: NativeVerdictResult;
1111
+ try {
1112
+ verdict =
1113
+ execResponse.executionStatus === ExecutionStatus.Valid
1114
+ ? this.store.onPayloadValid(fromHex(execResponse.latestValidExecHash))
1115
+ : this.store.onPayloadInvalid(
1116
+ fromHex(execResponse.invalidateFromBlockRoot),
1117
+ fromHex(execResponse.invalidateFromBlockHash),
1118
+ execResponse.latestValidExecHash === null ? undefined : fromHex(execResponse.latestValidExecHash),
1119
+ execResponse.judged === LVHInvalidJudged.FromBlock ? "from_block" : "child_payload"
1120
+ );
1121
+ } catch (e) {
1122
+ return {applied: false, reason: LVHNotAppliedReason.Error, error: e as Error};
1123
+ }
1124
+ if (verdict !== "applied") {
1125
+ return {applied: false, reason: NOT_APPLIED_REASONS[verdict]};
1126
+ }
1127
+ this.refreshExecutionStatuses();
1128
+ return {applied: true};
1129
+ }
1130
+
1131
+ /**
1132
+ * Brings every node's `executionStatus` in line with the store, which derives it per node.
1133
+ * Returns whether any status changed.
1134
+ */
1135
+ private refreshExecutionStatuses(): boolean {
1136
+ const statuses = this.store.executionStatuses();
1137
+ let changed = false;
1138
+ for (let id = 0; id < this.nodes.length; id++) {
1139
+ const node = this.nodes[id];
1140
+ if (node === undefined || node.executionPayloadBlockHash === null) continue;
1141
+ const status = EXECUTION_STATUS_FROM_NATIVE[statuses[id]];
1142
+ // A node past the merge with no payload left to judge below it stands on validated ground
1143
+ const executionStatus = status === ExecutionStatus.PreMerge ? ExecutionStatus.Valid : status;
1144
+ if (node.executionStatus !== executionStatus) changed = true;
1145
+ node.executionStatus = executionStatus;
1146
+ }
1147
+ return changed;
1148
+ }
1149
+
1150
+ prune(finalizedRoot: RootHex): ProtoBlock[] {
1151
+ const finalizedIndex = this.blockIndexByRoot.get(finalizedRoot);
1152
+ if (finalizedIndex === undefined) {
1153
+ throw new ProtoArrayError({code: ProtoArrayErrorCode.FINALIZED_NODE_UNKNOWN, root: finalizedRoot});
1154
+ }
1155
+ // A lagging archive job; the job for the current root prunes once its sweep has listed what prune drops
1156
+ if (finalizedRoot !== this.fcStore.finalizedCheckpoint.rootHex) {
1157
+ return [];
1158
+ }
1159
+ if (finalizedIndex < this.pruneThreshold) {
1160
+ return [];
1161
+ }
1162
+
1163
+ this.mutated();
1164
+ const remap = this.store.prune();
1165
+ if (remap === undefined) {
1166
+ return [];
1167
+ }
1168
+
1169
+ const removed: ProtoBlock[] = [];
1170
+ const nodes: (ProtoBlock | undefined)[] = [];
1171
+ const parentNodes: (number | undefined)[] = [];
1172
+ const blockIndexByRoot = new Map<RootHex, number>();
1173
+ for (const id of this.nodeIds()) {
1174
+ const node = this.nodes[id] as ProtoBlock;
1175
+ const blockIndex = remap[Math.floor(id / NODES_PER_BLOCK)];
1176
+ if (blockIndex === NO_BLOCK) {
1177
+ removed.push(node);
1178
+ continue;
1179
+ }
1180
+ nodes[blockIndex * NODES_PER_BLOCK + (id % NODES_PER_BLOCK)] = node;
1181
+ blockIndexByRoot.set(node.blockRoot, blockIndex);
1182
+ }
1183
+ for (const [oldIndex, blockIndex] of remap.entries()) {
1184
+ const parentNode = this.parentNodes[oldIndex];
1185
+ if (blockIndex === NO_BLOCK || parentNode === undefined) continue;
1186
+ const parentIndex = remap[Math.floor(parentNode / NODES_PER_BLOCK)];
1187
+ parentNodes[blockIndex] =
1188
+ parentIndex === NO_BLOCK ? undefined : parentIndex * NODES_PER_BLOCK + (parentNode % NODES_PER_BLOCK);
1189
+ }
1190
+ this.nodes = nodes;
1191
+ this.parentNodes = parentNodes;
1192
+ this.blockIndexByRoot = blockIndexByRoot;
1193
+ return removed;
1194
+ }
1195
+
1196
+ setPruneThreshold(threshold: number): void {
1197
+ this.pruneThreshold = threshold;
1198
+ }
1199
+
1200
+ // Payload timeliness committee
1201
+
1202
+ getPTCVotes(blockRootHex: RootHex): (boolean | null)[] | null {
1203
+ const votes = this.ptcVotesOf(blockRootHex);
1204
+ return votes === null ? null : Array.from(votes, (vote) => (vote & PTC_PAYLOAD_PRESENT) !== 0);
1205
+ }
1206
+
1207
+ getPTCVoteCounts(blockRootHex: RootHex): {
1208
+ attesterCount: number;
1209
+ payloadPresentCount: number;
1210
+ dataAvailableCount: number;
1211
+ } | null {
1212
+ const votes = this.ptcVotesOf(blockRootHex);
1213
+ if (votes === null) return null;
1214
+ let attesterCount = 0;
1215
+ let payloadPresentCount = 0;
1216
+ let dataAvailableCount = 0;
1217
+ for (const vote of votes) {
1218
+ if (vote & PTC_VOTED) attesterCount++;
1219
+ if (vote & PTC_PAYLOAD_PRESENT) payloadPresentCount++;
1220
+ if (vote & PTC_BLOB_DATA_AVAILABLE) dataAvailableCount++;
1221
+ }
1222
+ return {attesterCount, payloadPresentCount, dataAvailableCount};
1223
+ }
1224
+
1225
+ getPtcQuorum(blockRootHex: RootHex): PtcQuorum | null {
1226
+ const counts = this.getPTCVoteCounts(blockRootHex);
1227
+ if (counts === null) return null;
1228
+ const majority = (yes: number): boolean | null => {
1229
+ if (yes > PTC_THRESHOLD) return true;
1230
+ if (counts.attesterCount - yes > PTC_THRESHOLD) return false;
1231
+ return null;
1232
+ };
1233
+ return {
1234
+ payloadPresent: majority(counts.payloadPresentCount),
1235
+ blobDataAvailable: majority(counts.dataAvailableCount),
1236
+ };
1237
+ }
1238
+
1239
+ getPayloadTimelinessVotes(blockRootHex: RootHex): (boolean | null)[] | null {
1240
+ const votes = this.ptcVotesOf(blockRootHex);
1241
+ return votes === null
1242
+ ? null
1243
+ : Array.from(votes, (vote) => (vote & PTC_VOTED ? (vote & PTC_PAYLOAD_PRESENT) !== 0 : null));
1244
+ }
1245
+
1246
+ getPayloadDataAvailabilityVotes(blockRootHex: RootHex): (boolean | null)[] | null {
1247
+ const votes = this.ptcVotesOf(blockRootHex);
1248
+ return votes === null
1249
+ ? null
1250
+ : Array.from(votes, (vote) => (vote & PTC_VOTED ? (vote & PTC_BLOB_DATA_AVAILABLE) !== 0 : null));
1251
+ }
1252
+
1253
+ /** PTC votes of a Gloas block, null for an unknown or pre-Gloas root */
1254
+ private ptcVotesOf(blockRoot: RootHex): Uint8Array | null {
1255
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1256
+ const node =
1257
+ blockIndex === undefined ? undefined : this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending];
1258
+ if (blockIndex === undefined || node === undefined || !isGloasBlock(node)) {
1259
+ return null;
1260
+ }
1261
+ return this.store.ptcVotes(blockIndex);
1262
+ }
1263
+
1264
+ isProposerEquivocation(block: ProtoBlock): boolean {
1265
+ const blockIndex = this.blockIndexByRoot.get(block.blockRoot);
1266
+ return blockIndex !== undefined && this.store.isProposerEquivocation(blockIndex);
1267
+ }
1268
+
1269
+ shouldExtendPayload(blockRoot: RootHex): boolean {
1270
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1271
+ if (blockIndex === undefined || this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Full] === undefined) {
1272
+ return false;
1273
+ }
1274
+ return this.store.shouldExtendPayload(blockIndex);
1275
+ }
1276
+
1277
+ shouldBuildOnFull(head: ProtoBlock, slot: Slot): boolean {
1278
+ if (head.payloadStatus === PayloadStatus.PENDING) {
1279
+ throw new Error("shouldBuildOnFull called with PENDING head");
1280
+ }
1281
+ if (!isGloasBlock(head)) {
1282
+ return true;
1283
+ }
1284
+ const headNode = this.getNodeId(head.blockRoot, head.payloadStatus);
1285
+ if (headNode === undefined) {
1286
+ throw new ForkChoiceError({code: ForkChoiceErrorCode.MISSING_PROTO_ARRAY_BLOCK, root: head.blockRoot});
1287
+ }
1288
+ return this.store.shouldBuildOnFull(headNode, slot);
1289
+ }
1290
+
1291
+ recordPayloadInclusionListSatisfaction(blockRoot: RootHex, satisfied: boolean): boolean {
1292
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1293
+ if (blockIndex === undefined) {
1294
+ return false;
1295
+ }
1296
+ this.mutated();
1297
+ const changed = this.store.recordInclusionListSatisfaction(blockIndex, satisfied);
1298
+ if (changed && !satisfied) {
1299
+ this.metrics?.forkChoice.unsatisfiedInclusionListBlocks.inc();
1300
+ this.logger?.verbose("Payload does not satisfy the inclusion list constraints, not extending it", {blockRoot});
1301
+ }
1302
+ return changed;
1303
+ }
1304
+
1305
+ isPayloadInclusionListSatisfied(blockRoot: RootHex): boolean {
1306
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1307
+ return blockIndex !== undefined && this.store.isPayloadInclusionListSatisfied(blockIndex);
1308
+ }
1309
+
1310
+ getPayloadInclusionListSatisfaction(blockRoot: RootHex): boolean | null {
1311
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1312
+ return blockIndex === undefined ? null : (this.store.inclusionListSatisfaction(blockIndex) ?? null);
1313
+ }
1314
+
1315
+ // Block queries
1316
+
1317
+ hasBlock(blockRoot: Root): boolean {
1318
+ return this.hasBlockHex(toRootHex(blockRoot));
1319
+ }
1320
+
1321
+ hasBlockHex(blockRoot: RootHex): boolean {
1322
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1323
+ return blockIndex !== undefined && this.isFinalizedRootOrDescendant(blockIndex);
1324
+ }
1325
+
1326
+ hasBlockUnsafe(blockRoot: Root): boolean {
1327
+ return this.hasBlockHexUnsafe(toRootHex(blockRoot));
1328
+ }
1329
+
1330
+ hasBlockHexUnsafe(blockRoot: RootHex): boolean {
1331
+ return this.blockIndexByRoot.has(blockRoot);
1332
+ }
1333
+
1334
+ hasPayloadUnsafe(blockRoot: Root): boolean {
1335
+ return this.hasPayloadHexUnsafe(toRootHex(blockRoot));
1336
+ }
1337
+
1338
+ hasPayloadHexUnsafe(blockRoot: RootHex): boolean {
1339
+ return this.getNodeId(blockRoot, PayloadStatus.FULL) !== undefined;
1340
+ }
1341
+
1342
+ getBlock(blockRoot: Root, payloadStatus: PayloadStatus): ProtoBlock | null {
1343
+ return this.getBlockHex(toRootHex(blockRoot), payloadStatus);
1344
+ }
1345
+
1346
+ getBlockDefaultStatus(blockRoot: Root): ProtoBlock | null {
1347
+ return this.getBlockHexDefaultStatus(toRootHex(blockRoot));
1348
+ }
1349
+
1350
+ getBlockHex(blockRoot: RootHex, payloadStatus: PayloadStatus): ProtoBlock | null {
1351
+ const id = this.getNodeId(blockRoot, payloadStatus);
1352
+ if (id === undefined || !this.isFinalizedRootOrDescendant(Math.floor(id / NODES_PER_BLOCK))) {
1353
+ return null;
1354
+ }
1355
+ return {...(this.nodes[id] as ProtoBlock)};
1356
+ }
1357
+
1358
+ getBlockHexDefaultStatus(blockRoot: RootHex): ProtoBlock | null {
1359
+ const node = this.getDefaultNode(blockRoot);
1360
+ return node === undefined ? null : this.getBlockHex(blockRoot, node.payloadStatus);
1361
+ }
1362
+
1363
+ getBlockHexAndBlockHash(blockRoot: RootHex, blockHash: RootHex): ProtoBlock | null {
1364
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1365
+ if (blockIndex === undefined) {
1366
+ return null;
1367
+ }
1368
+ const defaultNode = this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] as ProtoBlock;
1369
+ if (!isGloasBlock(defaultNode)) {
1370
+ return defaultNode.executionPayloadBlockHash === blockHash ? defaultNode : null;
1371
+ }
1372
+ for (const status of [NativePayloadStatus.Full, NativePayloadStatus.Empty]) {
1373
+ const node = this.nodes[blockIndex * NODES_PER_BLOCK + status];
1374
+ if (node !== undefined && node.executionPayloadBlockHash === blockHash) {
1375
+ return node;
1376
+ }
1377
+ }
1378
+ return null;
1379
+ }
1380
+
1381
+ getJustifiedBlock(): ProtoBlock {
1382
+ return this.getExistingBlock(this.fcStore.justified.checkpoint.rootHex);
1383
+ }
1384
+
1385
+ getFinalizedBlock(): ProtoBlock {
1386
+ return this.getExistingBlock(this.fcStore.finalizedCheckpoint.rootHex);
1387
+ }
1388
+
1389
+ private getExistingBlock(blockRoot: RootHex): ProtoBlock {
1390
+ const block = this.getBlockHexDefaultStatus(blockRoot);
1391
+ if (block === null) {
1392
+ throw new ForkChoiceError({code: ForkChoiceErrorCode.MISSING_PROTO_ARRAY_BLOCK, root: blockRoot});
1393
+ }
1394
+ return block;
1395
+ }
1396
+
1397
+ /** Counts blocks, where `ForkChoice` counts every node and so up to three per Gloas block */
1398
+ getSlotsPresent(windowStart: number): number {
1399
+ let count = 0;
1400
+ for (const blockIndex of this.blockIndexByRoot.values()) {
1401
+ if ((this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] as ProtoBlock).slot > windowStart)
1402
+ count++;
1403
+ }
1404
+ return count;
1405
+ }
1406
+
1407
+ getCanonicalPayloadCounts(fromSlot: Slot, toSlot: Slot, head: ProtoBlock): {full: number; empty: number} {
1408
+ let full = 0;
1409
+ let empty = 0;
1410
+ let id = this.getNodeId(head.blockRoot, head.payloadStatus);
1411
+ while (id !== undefined) {
1412
+ const node = this.nodes[id] as ProtoBlock;
1413
+ if (node.slot < fromSlot) break;
1414
+ if (
1415
+ node.slot !== 0 &&
1416
+ node.slot <= toSlot &&
1417
+ isGloasBlock(node) &&
1418
+ node.payloadStatus !== PayloadStatus.PENDING
1419
+ ) {
1420
+ if (node.payloadStatus === PayloadStatus.FULL) full++;
1421
+ else empty++;
1422
+ }
1423
+ id = this.parentNodes[Math.floor(id / NODES_PER_BLOCK)];
1424
+ }
1425
+ return {full, empty};
1426
+ }
1427
+
1428
+ getAncestor(blockRoot: RootHex, ancestorSlot: Slot): ProtoNode {
1429
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1430
+ if (blockIndex === undefined) {
1431
+ throw new ForkChoiceError({code: ForkChoiceErrorCode.MISSING_PROTO_ARRAY_BLOCK, root: blockRoot});
1432
+ }
1433
+ const id = this.store.getAncestor(blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending, ancestorSlot);
1434
+ const node = id === undefined ? undefined : this.nodes[id];
1435
+ if (id === undefined || node === undefined) {
1436
+ throw new ForkChoiceError({code: ForkChoiceErrorCode.UNKNOWN_ANCESTOR, descendantRoot: blockRoot, ancestorSlot});
1437
+ }
1438
+ const {weights, attestationScores} = this.getScores();
1439
+ return {...node, weight: weights[id], attestationScore: attestationScores[id]};
1440
+ }
1441
+
1442
+ isDescendant(
1443
+ ancestorRoot: RootHex,
1444
+ ancestorPayloadStatus: PayloadStatus,
1445
+ descendantRoot: RootHex,
1446
+ descendantPayloadStatus: PayloadStatus
1447
+ ): boolean {
1448
+ const ancestorId = this.getNodeId(ancestorRoot, ancestorPayloadStatus);
1449
+ if (ancestorId === undefined) {
1450
+ return false;
1451
+ }
1452
+ const ancestorNode = this.nodes[ancestorId] as ProtoBlock;
1453
+ if (ancestorRoot === descendantRoot) {
1454
+ // The ancestor walk below starts at the parent block, so variants of the same block are compared here
1455
+ return (
1456
+ this.getNodeId(descendantRoot, descendantPayloadStatus) !== undefined &&
1457
+ (ancestorPayloadStatus === descendantPayloadStatus || ancestorPayloadStatus === PayloadStatus.PENDING)
1458
+ );
1459
+ }
1460
+ for (const node of this.iterateAncestorBlocks(descendantRoot, descendantPayloadStatus)) {
1461
+ if (node.blockRoot === ancestorNode.blockRoot) {
1462
+ return (
1463
+ node.payloadStatus === ancestorNode.payloadStatus || ancestorNode.payloadStatus === PayloadStatus.PENDING
1464
+ );
1465
+ }
1466
+ if (node.slot <= ancestorNode.slot) {
1467
+ return false;
1468
+ }
1469
+ }
1470
+ return false;
1471
+ }
1472
+
1473
+ /**
1474
+ * Consumers may await between steps (regen), and a prune in between renumbers node ids, so each
1475
+ * step resolves the last yielded block again by root. The walk ends if that block was pruned.
1476
+ */
1477
+ *iterateAncestorBlocks(blockRoot: RootHex, payloadStatus: PayloadStatus): IterableIterator<ProtoBlock> {
1478
+ const startId = this.getNodeId(blockRoot, payloadStatus);
1479
+ if (startId === undefined) return;
1480
+ let node = this.nodes[startId] as ProtoBlock;
1481
+ while (true) {
1482
+ const blockIndex = this.blockIndexByRoot.get(node.blockRoot);
1483
+ if (blockIndex === undefined) return;
1484
+ const parentId = this.parentNodes[blockIndex];
1485
+ if (parentId === undefined) return;
1486
+ node = this.nodes[parentId] as ProtoBlock;
1487
+ yield node;
1488
+ }
1489
+ }
1490
+
1491
+ getAllAncestorBlocks(blockRoot: RootHex, payloadStatus: PayloadStatus): ProtoBlock[] {
1492
+ const id = this.getNodeId(blockRoot, payloadStatus);
1493
+ if (id === undefined) {
1494
+ return [];
1495
+ }
1496
+ const start = this.nodes[id] as ProtoBlock;
1497
+ const ancestors = Array.from(this.iterateAncestorBlocks(blockRoot, payloadStatus));
1498
+ return start.payloadStatus === PayloadStatus.PENDING ? ancestors : [start, ...ancestors];
1499
+ }
1500
+
1501
+ getAllNonAncestorBlocks(blockRoot: RootHex, payloadStatus: PayloadStatus): ProtoBlock[] {
1502
+ return this.getAllAncestorAndNonAncestorBlocks(blockRoot, payloadStatus).nonAncestors;
1503
+ }
1504
+
1505
+ /**
1506
+ * `nonAncestors` are the EMPTY, FULL and pre-Gloas variants of every block that is neither on the
1507
+ * start block's chain nor descends from it, the root block aside. Unlike proto-array, this includes
1508
+ * blocks imported after the start block, since `prune` drops them. A PENDING start block's own
1509
+ * EMPTY and FULL are left out: its payload is undecided, and the archiver deletes FULL non-ancestors.
1510
+ */
1511
+ getAllAncestorAndNonAncestorBlocks(
1512
+ blockRoot: RootHex,
1513
+ payloadStatus: PayloadStatus
1514
+ ): {ancestors: ProtoBlock[]; nonAncestors: ProtoBlock[]} {
1515
+ const startId = this.getNodeId(blockRoot, payloadStatus);
1516
+ if (startId === undefined) {
1517
+ return {ancestors: [], nonAncestors: []};
1518
+ }
1519
+
1520
+ const ancestorIds = new Set<number>([startId]);
1521
+ for (
1522
+ let id = this.parentNodes[Math.floor(startId / NODES_PER_BLOCK)];
1523
+ id !== undefined;
1524
+ id = this.parentNodes[Math.floor(id / NODES_PER_BLOCK)]
1525
+ ) {
1526
+ ancestorIds.add(id);
1527
+ }
1528
+ const ancestors = Array.from(ancestorIds, (id) => this.nodes[id] as ProtoBlock);
1529
+
1530
+ const startBlock = Math.floor(startId / NODES_PER_BLOCK);
1531
+ const firstBlock = this.nodes[startId]?.payloadStatus === PayloadStatus.PENDING ? startBlock - 1 : startBlock;
1532
+ const nonAncestors: ProtoBlock[] = [];
1533
+ const pushVariants = (blockIndex: number): void => {
1534
+ for (const status of [NativePayloadStatus.Full, NativePayloadStatus.Empty, NativePayloadStatus.Pending]) {
1535
+ const id = blockIndex * NODES_PER_BLOCK + status;
1536
+ const node = this.nodes[id];
1537
+ if (node !== undefined && node.payloadStatus !== PayloadStatus.PENDING && !ancestorIds.has(id)) {
1538
+ nonAncestors.push(node);
1539
+ }
1540
+ }
1541
+ };
1542
+ for (let blockIndex = firstBlock; blockIndex > 0; blockIndex--) {
1543
+ pushVariants(blockIndex);
1544
+ }
1545
+ const descendants = new Set<number>([startBlock]);
1546
+ const blockCount = Math.ceil(this.nodes.length / NODES_PER_BLOCK);
1547
+ for (let blockIndex = startBlock + 1; blockIndex < blockCount; blockIndex++) {
1548
+ const parentId = this.parentNodes[blockIndex];
1549
+ if (parentId !== undefined && descendants.has(Math.floor(parentId / NODES_PER_BLOCK))) {
1550
+ descendants.add(blockIndex);
1551
+ } else {
1552
+ pushVariants(blockIndex);
1553
+ }
1554
+ }
1555
+ return {ancestors, nonAncestors};
1556
+ }
1557
+
1558
+ getAllAncestorAndNonAncestorBlocksDefaultStatus(blockRoot: RootHex): {
1559
+ ancestors: ProtoBlock[];
1560
+ nonAncestors: ProtoBlock[];
1561
+ } {
1562
+ const node = this.getDefaultNode(blockRoot);
1563
+ if (node === undefined) {
1564
+ throw new ForkChoiceError({code: ForkChoiceErrorCode.MISSING_PROTO_ARRAY_BLOCK, root: blockRoot});
1565
+ }
1566
+ return this.getAllAncestorAndNonAncestorBlocks(blockRoot, node.payloadStatus);
1567
+ }
1568
+
1569
+ getCanonicalBlockByRoot(blockRoot: Root): ProtoBlock | null {
1570
+ const blockRootHex = toRootHex(blockRoot);
1571
+ if (blockRootHex === this.head.blockRoot) {
1572
+ return this.head;
1573
+ }
1574
+ for (const block of this.iterateAncestorBlocks(this.head.blockRoot, this.head.payloadStatus)) {
1575
+ if (block.blockRoot === blockRootHex) {
1576
+ return block;
1577
+ }
1578
+ }
1579
+ return null;
1580
+ }
1581
+
1582
+ getCanonicalBlockAtSlot(slot: Slot): ProtoBlock | null {
1583
+ if (slot > this.head.slot) {
1584
+ return null;
1585
+ }
1586
+ if (slot === this.head.slot) {
1587
+ return this.head;
1588
+ }
1589
+ for (const block of this.iterateAncestorBlocks(this.head.blockRoot, this.head.payloadStatus)) {
1590
+ if (block.slot === slot) {
1591
+ return block;
1592
+ }
1593
+ }
1594
+ return null;
1595
+ }
1596
+
1597
+ getCanonicalBlockClosestLteSlot(slot: Slot): ProtoBlock | null {
1598
+ if (slot >= this.head.slot) {
1599
+ return this.head;
1600
+ }
1601
+ for (const block of this.iterateAncestorBlocks(this.head.blockRoot, this.head.payloadStatus)) {
1602
+ if (slot >= block.slot) {
1603
+ return block;
1604
+ }
1605
+ }
1606
+ return null;
1607
+ }
1608
+
1609
+ forwarditerateAncestorBlocks(): ProtoBlock[] {
1610
+ return this.nodeIds().map((id) => this.nodes[id] as ProtoBlock);
1611
+ }
1612
+
1613
+ *forwardIterateDescendants(blockRoot: RootHex, payloadStatus: PayloadStatus): IterableIterator<ProtoBlock> {
1614
+ const startId = this.getNodeId(blockRoot, payloadStatus);
1615
+ if (startId === undefined) {
1616
+ throw new ForkChoiceError({code: ForkChoiceErrorCode.MISSING_PROTO_ARRAY_BLOCK, root: blockRoot});
1617
+ }
1618
+ // Collected before the first yield: a prune between steps renumbers node ids
1619
+ const rootsInChain = new Set([blockRoot]);
1620
+ const descendants: ProtoBlock[] = [];
1621
+ for (const id of this.nodeIds()) {
1622
+ const node = this.nodes[id] as ProtoBlock;
1623
+ if (
1624
+ Math.floor(id / NODES_PER_BLOCK) > Math.floor(startId / NODES_PER_BLOCK) &&
1625
+ rootsInChain.has(node.parentRoot)
1626
+ ) {
1627
+ rootsInChain.add(node.blockRoot);
1628
+ descendants.push(node);
1629
+ }
1630
+ }
1631
+ yield* descendants;
1632
+ }
1633
+
1634
+ forwardIterateDescendantsDefaultStatus(blockRoot: RootHex): IterableIterator<ProtoBlock> {
1635
+ const node = this.getDefaultNode(blockRoot);
1636
+ if (node === undefined) {
1637
+ throw new ForkChoiceError({code: ForkChoiceErrorCode.MISSING_PROTO_ARRAY_BLOCK, root: blockRoot});
1638
+ }
1639
+ return this.forwardIterateDescendants(blockRoot, node.payloadStatus);
1640
+ }
1641
+
1642
+ getBlockSummariesByParentRoot(parentRoot: RootHex): ProtoBlock[] {
1643
+ return this.defaultNodes().filter((node) => node.parentRoot === parentRoot);
1644
+ }
1645
+
1646
+ getBlockSummariesAtSlot(slot: Slot): ProtoBlock[] {
1647
+ return this.defaultNodes().filter((node) => node.slot === slot);
1648
+ }
1649
+
1650
+ getCommonAncestorDepth(prevBlock: ProtoBlock, newBlock: ProtoBlock): AncestorResult {
1651
+ let prevIndex = this.blockIndexByRoot.get(prevBlock.blockRoot);
1652
+ let newIndex = this.blockIndexByRoot.get(newBlock.blockRoot);
1653
+ if (
1654
+ this.getNodeId(prevBlock.blockRoot, prevBlock.payloadStatus) === undefined ||
1655
+ this.getNodeId(newBlock.blockRoot, newBlock.payloadStatus) === undefined
1656
+ ) {
1657
+ return {code: AncestorStatus.BlockUnknown};
1658
+ }
1659
+
1660
+ // A parent's block index is always lower than its child's
1661
+ while (prevIndex !== undefined && newIndex !== undefined && prevIndex !== newIndex) {
1662
+ if (prevIndex > newIndex) prevIndex = this.parentBlockIndex(prevIndex);
1663
+ else newIndex = this.parentBlockIndex(newIndex);
1664
+ }
1665
+ if (prevIndex === undefined || newIndex === undefined) {
1666
+ return {code: AncestorStatus.NoCommonAncenstor};
1667
+ }
1668
+
1669
+ const commonAncestor = this.nodes[prevIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] as ProtoBlock;
1670
+ if (commonAncestor.blockRoot === prevBlock.blockRoot || commonAncestor.blockRoot === newBlock.blockRoot) {
1671
+ return {code: AncestorStatus.Descendant};
1672
+ }
1673
+ return {code: AncestorStatus.CommonAncestor, depth: Math.max(newBlock.slot, prevBlock.slot) - commonAncestor.slot};
1674
+ }
1675
+
1676
+ getDependentRoot(block: ProtoBlock, epochDifference: EpochDifference): RootHex {
1677
+ const beforeSlot = block.slot - (block.slot % SLOTS_PER_EPOCH) - epochDifference * SLOTS_PER_EPOCH;
1678
+
1679
+ // Close to genesis the dependent root is the genesis block root
1680
+ if (beforeSlot <= 0) {
1681
+ const genesisBlock = this.nodes[NativePayloadStatus.Pending];
1682
+ if (genesisBlock === undefined || genesisBlock.slot !== 0) {
1683
+ throw Error("Genesis block not available");
1684
+ }
1685
+ return genesisBlock.blockRoot;
1686
+ }
1687
+
1688
+ const finalizedSlot = this.getFinalizedBlock().slot;
1689
+ while (block.slot >= finalizedSlot) {
1690
+ if (block.slot < beforeSlot) {
1691
+ return block.blockRoot;
1692
+ }
1693
+ if (block.slot === beforeSlot) {
1694
+ return block.parentRoot;
1695
+ }
1696
+
1697
+ // A block at the first slot of its epoch is its own target
1698
+ const nextRoot = block.blockRoot === block.targetRoot ? block.parentRoot : block.targetRoot;
1699
+ const nextBlock = this.getDefaultNode(nextRoot);
1700
+ if (nextBlock === undefined) {
1701
+ throw Error(`No block for root ${nextRoot}`);
1702
+ }
1703
+ block = nextBlock;
1704
+ }
1705
+
1706
+ throw Error(`Not found dependent root for block slot ${block.slot}, epoch difference ${epochDifference}`);
1707
+ }
1708
+
1709
+ // Node bookkeeping
1710
+
1711
+ private nodeCount(): number {
1712
+ let count = 0;
1713
+ for (const node of this.nodes) {
1714
+ if (node !== undefined) count++;
1715
+ }
1716
+ return count;
1717
+ }
1718
+
1719
+ private storeHead(): ProtoBlock {
1720
+ const head = this.nodes[this.store.getHead()];
1721
+ if (head === undefined) {
1722
+ throw Error("Native fork choice head has no block summary");
1723
+ }
1724
+ return head;
1725
+ }
1726
+
1727
+ private mutated(): void {
1728
+ this.scores = null;
1729
+ }
1730
+
1731
+ private getScores(): NativeScores {
1732
+ this.scores ??= {
1733
+ weights: this.store.weights(),
1734
+ attestationScores: this.store.attestationScores(),
1735
+ bestChildren: this.store.bestChildren(),
1736
+ };
1737
+ return this.scores;
1738
+ }
1739
+
1740
+ private insertBlock(blockIndex: number, block: ProtoBlock): void {
1741
+ this.blockIndexByRoot.set(block.blockRoot, blockIndex);
1742
+ this.parentNodes[blockIndex] = this.store.parentNode(blockIndex);
1743
+ if (isGloasBlock(block)) {
1744
+ this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] = {
1745
+ ...block,
1746
+ payloadStatus: PayloadStatus.PENDING,
1747
+ };
1748
+ this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Empty] = {
1749
+ ...block,
1750
+ payloadStatus: PayloadStatus.EMPTY,
1751
+ };
1752
+ } else {
1753
+ this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] = {
1754
+ ...block,
1755
+ payloadStatus: PayloadStatus.FULL,
1756
+ };
1757
+ }
1758
+ }
1759
+
1760
+ /** Ids of the existing nodes, block by block in import order: PENDING or pre-Gloas, EMPTY, FULL */
1761
+ private nodeIds(): number[] {
1762
+ const ids: number[] = [];
1763
+ for (let blockIndex = 0; blockIndex * NODES_PER_BLOCK < this.nodes.length; blockIndex++) {
1764
+ for (const status of [NativePayloadStatus.Pending, NativePayloadStatus.Empty, NativePayloadStatus.Full]) {
1765
+ if (this.nodes[blockIndex * NODES_PER_BLOCK + status] !== undefined) {
1766
+ ids.push(blockIndex * NODES_PER_BLOCK + status);
1767
+ }
1768
+ }
1769
+ }
1770
+ return ids;
1771
+ }
1772
+
1773
+ /** One node per block: FULL before Gloas, PENDING from Gloas on */
1774
+ private defaultNodes(): ProtoBlock[] {
1775
+ return Array.from(
1776
+ this.blockIndexByRoot.values(),
1777
+ (blockIndex) => this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] as ProtoBlock
1778
+ );
1779
+ }
1780
+
1781
+ private getDefaultNode(blockRoot: RootHex): ProtoBlock | undefined {
1782
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1783
+ return blockIndex === undefined
1784
+ ? undefined
1785
+ : this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending];
1786
+ }
1787
+
1788
+ private getNodeId(blockRoot: RootHex, payloadStatus: PayloadStatus): number | undefined {
1789
+ const blockIndex = this.blockIndexByRoot.get(blockRoot);
1790
+ if (blockIndex === undefined) {
1791
+ return undefined;
1792
+ }
1793
+ if (!isGloasBlock(this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] as ProtoBlock)) {
1794
+ if (payloadStatus !== PayloadStatus.FULL) {
1795
+ throw new ProtoArrayError({code: ProtoArrayErrorCode.INVALID_NODE_INDEX, index: payloadStatus});
1796
+ }
1797
+ return blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending;
1798
+ }
1799
+ const status =
1800
+ payloadStatus === PayloadStatus.PENDING
1801
+ ? NativePayloadStatus.Pending
1802
+ : payloadStatus === PayloadStatus.EMPTY
1803
+ ? NativePayloadStatus.Empty
1804
+ : NativePayloadStatus.Full;
1805
+ const id = blockIndex * NODES_PER_BLOCK + status;
1806
+ return this.nodes[id] === undefined ? undefined : id;
1807
+ }
1808
+
1809
+ private parentBlockIndex(blockIndex: number): number | undefined {
1810
+ const parentNode = this.parentNodes[blockIndex];
1811
+ return parentNode === undefined ? undefined : Math.floor(parentNode / NODES_PER_BLOCK);
1812
+ }
1813
+
1814
+ /** The variant of the parent a block with this bid `parent_block_hash` builds on */
1815
+ private getParent(parentRoot: RootHex, parentBlockHash: RootHex | null): ProtoBlock | null {
1816
+ const parent = this.getDefaultNode(parentRoot);
1817
+ if (parent === undefined) {
1818
+ return null;
1819
+ }
1820
+ // A pre-Gloas parent has one variant, also for the first Gloas block
1821
+ if (parentBlockHash === null || !isGloasBlock(parent)) {
1822
+ return parent;
1823
+ }
1824
+ return this.getBlockHexAndBlockHash(parentRoot, parentBlockHash);
1825
+ }
1826
+
1827
+ private isFinalizedRootOrDescendant(blockIndex: number): boolean {
1828
+ const node = this.nodes[blockIndex * NODES_PER_BLOCK + NativePayloadStatus.Pending] as ProtoBlock;
1829
+ const {epoch, rootHex} = this.fcStore.finalizedCheckpoint;
1830
+ if (
1831
+ (node.finalizedEpoch === epoch && node.finalizedRoot === rootHex) ||
1832
+ (node.justifiedEpoch === epoch && node.justifiedRoot === rootHex) ||
1833
+ (node.unrealizedFinalizedEpoch === epoch && node.unrealizedFinalizedRoot === rootHex) ||
1834
+ (node.unrealizedJustifiedEpoch === epoch && node.unrealizedJustifiedRoot === rootHex)
1835
+ ) {
1836
+ return true;
1837
+ }
1838
+ return this.store.isFinalizedDescendant(blockIndex);
1839
+ }
1840
+
1841
+ // Errors
1842
+
1843
+ private toInvalidBlockError(
1844
+ e: unknown,
1845
+ block: BeaconBlock,
1846
+ blockRootHex: RootHex,
1847
+ payloadBlockHash: Uint8Array | undefined,
1848
+ parentRootHex: RootHex,
1849
+ parentHashHex: RootHex | null
1850
+ ): unknown {
1851
+ const finalized = this.fcStore.finalizedCheckpoint;
1852
+ switch (nativeErrorCode(e)) {
1853
+ case "UnknownParent":
1854
+ case "ParentPayloadNotVerified":
1855
+ return new ForkChoiceError({
1856
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1857
+ err: {code: InvalidBlockCode.UNKNOWN_PARENT, root: parentRootHex, hash: parentHashHex},
1858
+ });
1859
+ case "ParentPayloadInvalid":
1860
+ return new ForkChoiceError({
1861
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1862
+ err: {code: InvalidBlockCode.PARENT_EXECUTION_INVALID, root: parentRootHex, hash: parentHashHex},
1863
+ });
1864
+ case "InvalidJustifiedPayload": {
1865
+ const justified = this.fcStore.justified.checkpoint;
1866
+ return new ForkChoiceError({
1867
+ code: ForkChoiceErrorCode.INVALID_JUSTIFIED_EXECUTION_STATUS,
1868
+ epoch: justified.epoch,
1869
+ root: justified.rootHex,
1870
+ });
1871
+ }
1872
+ case "FutureBlock":
1873
+ return new ForkChoiceError({
1874
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1875
+ err: {code: InvalidBlockCode.FUTURE_SLOT, currentSlot: this.store.currentSlot, blockSlot: block.slot},
1876
+ });
1877
+ case "BlockBeforeFinalizedSlot":
1878
+ return new ForkChoiceError({
1879
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1880
+ err: {
1881
+ code: InvalidBlockCode.FINALIZED_SLOT,
1882
+ finalizedSlot: computeStartSlotAtEpoch(finalized.epoch),
1883
+ blockSlot: block.slot,
1884
+ },
1885
+ });
1886
+ case "NotFinalizedDescendant":
1887
+ return new ForkChoiceError({
1888
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1889
+ err: {code: InvalidBlockCode.NOT_FINALIZED_DESCENDANT, finalizedRoot: finalized.rootHex},
1890
+ });
1891
+ default:
1892
+ return toPayloadDeliveryError(e, blockRootHex, toRootHex(payloadBlockHash ?? ZERO_HASH));
1893
+ }
1894
+ }
1895
+
1896
+ private toInvalidAttestationError(e: unknown, data: phase0.AttestationData): unknown {
1897
+ const currentEpoch = computeEpochAtSlot(this.store.currentSlot);
1898
+ const beaconBlockRoot = toRootHex(data.beaconBlockRoot);
1899
+ const invalid = (err: ConstructorParameters<typeof ForkChoiceError>[0] & {err: unknown}): ForkChoiceError =>
1900
+ new ForkChoiceError(err);
1901
+ switch (nativeErrorCode(e)) {
1902
+ case "AttestationTargetEpochNotCurrentOrPrevious":
1903
+ return invalid({
1904
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
1905
+ err:
1906
+ data.target.epoch > currentEpoch
1907
+ ? {code: InvalidAttestationCode.FUTURE_EPOCH, attestationEpoch: data.target.epoch, currentEpoch}
1908
+ : {code: InvalidAttestationCode.PAST_EPOCH, attestationEpoch: data.target.epoch, currentEpoch},
1909
+ });
1910
+ case "AttestationTargetEpochSlotMismatch":
1911
+ return invalid({
1912
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
1913
+ err: {code: InvalidAttestationCode.BAD_TARGET_EPOCH, target: data.target.epoch, slot: data.slot},
1914
+ });
1915
+ case "UnknownAttestationTarget":
1916
+ return invalid({
1917
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
1918
+ err: {code: InvalidAttestationCode.UNKNOWN_TARGET_ROOT, root: toRootHex(data.target.root)},
1919
+ });
1920
+ case "UnknownAttestationBlock":
1921
+ return invalid({
1922
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
1923
+ err: {code: InvalidAttestationCode.UNKNOWN_HEAD_BLOCK, beaconBlockRoot},
1924
+ });
1925
+ case "AttestationForFutureBlock":
1926
+ return invalid({
1927
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
1928
+ err: {
1929
+ code: InvalidAttestationCode.ATTESTS_TO_FUTURE_BLOCK,
1930
+ block: this.getDefaultNode(beaconBlockRoot)?.slot ?? data.slot,
1931
+ attestation: data.slot,
1932
+ },
1933
+ });
1934
+ case "InvalidAttestationIndex":
1935
+ case "SameSlotFullVote":
1936
+ return invalid({
1937
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
1938
+ err: {code: InvalidAttestationCode.INVALID_DATA_INDEX, index: data.index},
1939
+ });
1940
+ case "AttestationPayloadNotVerified":
1941
+ return invalid({
1942
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
1943
+ err: {code: InvalidAttestationCode.UNKNOWN_PAYLOAD_STATUS, beaconBlockRoot},
1944
+ });
1945
+ case "AttestationTargetNotInChain":
1946
+ return invalid({
1947
+ code: ForkChoiceErrorCode.INVALID_ATTESTATION,
1948
+ err: {
1949
+ code: InvalidAttestationCode.INVALID_TARGET,
1950
+ attestation: toRootHex(data.target.root),
1951
+ local: this.getDefaultNode(beaconBlockRoot)?.targetRoot ?? HEX_ZERO_HASH,
1952
+ },
1953
+ });
1954
+ default:
1955
+ return e;
1956
+ }
1957
+ }
1958
+ }
1959
+
1960
+ function balanceSourceOf(state: IBeaconStateView): BalanceSource {
1961
+ return {
1962
+ effectiveBalanceIncrements: state.effectiveBalanceIncrements,
1963
+ zeroInactiveIncrements: state.getEffectiveBalanceIncrementsZeroInactive(),
1964
+ activeIndices: state.getCurrentShuffling().activeIndices,
1965
+ };
1966
+ }
1967
+
1968
+ /** The Zig error name of a failed native call */
1969
+ function nativeErrorCode(e: unknown): string | undefined {
1970
+ return (e as {code?: string}).code;
1971
+ }
1972
+
1973
+ /** Errors of the store rejecting a payload that a block or its envelope delivers */
1974
+ function toPayloadDeliveryError(e: unknown, root: RootHex, hash: RootHex): unknown {
1975
+ switch (nativeErrorCode(e)) {
1976
+ case "PayloadInvalidToValid":
1977
+ return new ForkChoiceError({
1978
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1979
+ err: {code: InvalidBlockCode.EXECUTION_INVALID, root, hash},
1980
+ });
1981
+ case "PayloadParentMismatch":
1982
+ return new ForkChoiceError({
1983
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1984
+ err: {code: InvalidBlockCode.PAYLOAD_PARENT_MISMATCH, root, hash},
1985
+ });
1986
+ default:
1987
+ return e;
1988
+ }
1989
+ }
1990
+
1991
+ /** Slashings may carry their attestation data with bigint slots and epochs */
1992
+ function toNativeAttestationData(data: AttesterSlashing["attestation1"]["data"]): NativeAttestationData {
1993
+ return {
1994
+ slot: Number(data.slot),
1995
+ index: Number(data.index),
1996
+ beaconBlockRoot: data.beaconBlockRoot,
1997
+ source: {epoch: Number(data.source.epoch), root: data.source.root},
1998
+ target: {epoch: Number(data.target.epoch), root: data.target.root},
1999
+ };
2000
+ }