@lodestar/fork-choice 2.1.0-dev.c63474c8f3 → 2.1.0-dev.d00daf7fb4

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