@lodestar/fork-choice 1.52.0-dev.77088eb712 → 1.52.0-dev.7dadcecdca

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.
@@ -1,4 +1,4 @@
1
- import {SLOTS_PER_EPOCH} from "@lodestar/params";
1
+ import {EFFECTIVE_BALANCE_INCREMENT, SLOTS_PER_EPOCH} from "@lodestar/params";
2
2
  import {
3
3
  EffectiveBalanceIncrements,
4
4
  IBeaconStateView,
@@ -24,14 +24,16 @@ import {
24
24
 
25
25
  // Spec: adjust_committee_weight_estimate_to_ensure_safety
26
26
  // https://github.com/ethereum/consensus-specs/blob/master/specs/phase0/fast-confirmation.md#adjust_committee_weight_estimate_to_ensure_safety
27
- const COMMITTEE_WEIGHT_ESTIMATION_ADJUSTMENT_FACTOR = 5;
27
+ const COMMITTEE_WEIGHT_ESTIMATION_ADJUSTMENT_FACTOR = 5n;
28
+
29
+ const EFFECTIVE_BALANCE_INCREMENT_BIGINT = BigInt(EFFECTIVE_BALANCE_INCREMENT);
28
30
 
29
31
  const SAFETY_THRESHOLD_UNREACHABLE = Object.freeze({
30
- threshold: Number.POSITIVE_INFINITY,
31
- proposerScore: 0,
32
- maximumSupport: 0,
33
- supportDiscount: 0,
34
- adversarialWeight: 0,
32
+ threshold: 2n ** 64n,
33
+ proposerScore: 0n,
34
+ maximumSupport: 0n,
35
+ supportDiscount: 0n,
36
+ adversarialWeight: 0n,
35
37
  });
36
38
 
37
39
  export function getBlock(ctx: FastConfirmationContext, cache: FastConfirmationCache, root: RootHex): ProtoBlock | null {
@@ -299,9 +301,9 @@ export function estimateCommitteeWeightBetweenSlots(
299
301
  cache: FastConfirmationCache,
300
302
  startSlot: Slot,
301
303
  endSlot: Slot
302
- ): number {
303
- if (startSlot > endSlot) return 0;
304
- const totalActiveBalance = getTotalActiveBalance(balanceSource, cache);
304
+ ): bigint {
305
+ if (startSlot > endSlot) return 0n;
306
+ const totalActiveBalance = BigInt(getTotalActiveBalance(balanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
305
307
  const startEpoch = computeEpochAtSlot(startSlot);
306
308
  const endEpoch = computeEpochAtSlot(endSlot);
307
309
 
@@ -309,41 +311,30 @@ export function estimateCommitteeWeightBetweenSlots(
309
311
  return totalActiveBalance;
310
312
  }
311
313
 
312
- const committeeWeightPerSlot = Math.floor(totalActiveBalance / SLOTS_PER_EPOCH);
314
+ const committeeWeightPerSlot = totalActiveBalance / BigInt(SLOTS_PER_EPOCH);
313
315
 
314
316
  if (startEpoch === endEpoch) {
315
- return committeeWeightPerSlot * (endSlot - startSlot + 1);
317
+ return committeeWeightPerSlot * BigInt(endSlot - startSlot + 1);
316
318
  }
317
319
 
318
320
  const numSlotsInStartEpoch = SLOTS_PER_EPOCH - computeSlotsSinceEpochStart(startSlot);
319
321
  const numSlotsInEndEpoch = computeSlotsSinceEpochStart(endSlot) + 1;
320
322
  const remainingSlotsInEndEpoch = SLOTS_PER_EPOCH - numSlotsInEndEpoch;
321
323
 
322
- const startEpochWeight = committeeWeightPerSlot * numSlotsInStartEpoch;
323
- const endEpochWeight = committeeWeightPerSlot * numSlotsInEndEpoch;
324
+ const startEpochWeight = committeeWeightPerSlot * BigInt(numSlotsInStartEpoch);
325
+ const endEpochWeight = committeeWeightPerSlot * BigInt(numSlotsInEndEpoch);
324
326
  // For ranges that cross exactly one epoch boundary without covering a full epoch,
325
327
  // the spec models overlap as:
326
328
  // startEpochWeightProRated = startEpochWeight * (1 - numSlotsInEndEpoch / SLOTS_PER_EPOCH)
327
329
  // = startEpochWeight * remainingSlotsInEndEpoch / SLOTS_PER_EPOCH
328
330
  // We keep the spec's "pro-rate the start epoch" form so integer rounding matches it exactly.
329
- const startEpochWeightProRated = Math.floor(startEpochWeight / SLOTS_PER_EPOCH) * remainingSlotsInEndEpoch;
331
+ const startEpochWeightProRated = (startEpochWeight / BigInt(SLOTS_PER_EPOCH)) * BigInt(remainingSlotsInEndEpoch);
330
332
 
331
333
  return adjustCommitteeWeightEstimateToEnsureSafety(startEpochWeightProRated + endEpochWeight);
332
334
  }
333
335
 
334
- export function adjustCommitteeWeightEstimateToEnsureSafety(estimate: number): number {
335
- // The spec applies this adjustment in raw Gwei:
336
- // ceil(estimate_gwei / 1000) * (1000 + factor)
337
- //
338
- // Lodestar carries effective balance increments instead, where:
339
- // 1 increment = EFFECTIVE_BALANCE_INCREMENT = 1e9 Gwei
340
- //
341
- // Since each increment is already far larger than 1000 Gwei, the spec's
342
- // `ceil(... / 1000)` becomes a no-op at our unit scale. The equivalent
343
- // conservative adjustment in increments is therefore:
344
- // ceil(estimate_increments * (1000 + factor) / 1000)
345
- // The `+ 999` is integer ceiling division by 1000.
346
- return Math.floor((estimate * (1000 + COMMITTEE_WEIGHT_ESTIMATION_ADJUSTMENT_FACTOR) + 999) / 1000);
336
+ export function adjustCommitteeWeightEstimateToEnsureSafety(estimate: bigint): bigint {
337
+ return ((estimate + 999n) / 1000n) * (1000n + COMMITTEE_WEIGHT_ESTIMATION_ADJUSTMENT_FACTOR);
347
338
  }
348
339
 
349
340
  export function isFullValidatorSetCovered(startSlot: Slot, endSlot: Slot): boolean {
@@ -356,10 +347,10 @@ export function computeProposerScore(
356
347
  ctx: FastConfirmationContext,
357
348
  balanceSource: FastConfirmationBalanceSource,
358
349
  cache: FastConfirmationCache
359
- ): number {
360
- const totalActiveBalance = getTotalActiveBalance(balanceSource, cache);
361
- const committeeWeight = Math.floor(totalActiveBalance / SLOTS_PER_EPOCH);
362
- return Math.floor((committeeWeight * ctx.config.PROPOSER_SCORE_BOOST) / 100);
350
+ ): bigint {
351
+ const totalActiveBalance = BigInt(getTotalActiveBalance(balanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
352
+ const committeeWeight = totalActiveBalance / BigInt(SLOTS_PER_EPOCH);
353
+ return (committeeWeight * BigInt(ctx.config.PROPOSER_SCORE_BOOST)) / 100n;
363
354
  }
364
355
 
365
356
  /**
@@ -485,14 +476,13 @@ export function computeAdversarialWeight(
485
476
  balanceSource: FastConfirmationBalanceSource,
486
477
  startSlot: Slot,
487
478
  endSlot: Slot
488
- ): number {
479
+ ): bigint {
489
480
  const maximumWeight = estimateCommitteeWeightBetweenSlots(balanceSource, cache, startSlot, endSlot);
490
- // The spec uses raw Gwei and computes `maximum_weight // 100 * threshold`.
491
- // Lodestar carries effective-balance increments instead, so divide after multiplying to avoid
492
- // dropping the adversarial budget to zero for small validator sets/minimal presets.
493
- const maxAdversarialWeight = Math.floor((maximumWeight * ctx.config.CONFIRMATION_BYZANTINE_THRESHOLD) / 100);
494
- const equivocationScore = getEquivocationScore(ctx, store, cache, balanceSource, startSlot, endSlot);
495
- return maxAdversarialWeight > equivocationScore ? maxAdversarialWeight - equivocationScore : 0;
481
+ const maxAdversarialWeight = (maximumWeight / 100n) * BigInt(ctx.config.CONFIRMATION_BYZANTINE_THRESHOLD);
482
+ const equivocationScore =
483
+ BigInt(getEquivocationScore(ctx, store, cache, balanceSource, startSlot, endSlot)) *
484
+ EFFECTIVE_BALANCE_INCREMENT_BIGINT;
485
+ return maxAdversarialWeight > equivocationScore ? maxAdversarialWeight - equivocationScore : 0n;
496
486
  }
497
487
 
498
488
  export function getAdversarialWeight(
@@ -501,13 +491,13 @@ export function getAdversarialWeight(
501
491
  cache: FastConfirmationCache,
502
492
  balanceSource: FastConfirmationBalanceSource,
503
493
  blockRoot: RootHex
504
- ): number {
494
+ ): bigint {
505
495
  const currentSlot = ctx.getCurrentSlot();
506
- if (currentSlot === 0) return 0;
496
+ if (currentSlot === 0) return 0n;
507
497
  const block = getBlock(ctx, cache, blockRoot);
508
- if (!block) return 0;
498
+ if (!block) return 0n;
509
499
  const parentBlock = getBlock(ctx, cache, block.parentRoot);
510
- if (!parentBlock) return 0;
500
+ if (!parentBlock) return 0n;
511
501
  const blockEpoch = computeEpochAtSlot(block.slot);
512
502
  const parentEpoch = computeEpochAtSlot(parentBlock.slot);
513
503
 
@@ -524,31 +514,34 @@ export function computeEmptySlotSupportDiscount(
524
514
  cache: FastConfirmationCache,
525
515
  balanceSource: FastConfirmationBalanceSource,
526
516
  blockRoot: RootHex
527
- ): number {
517
+ ): bigint {
528
518
  const block = getBlock(ctx, cache, blockRoot);
529
- if (!block) return 0;
519
+ if (!block) return 0n;
530
520
  const parentBlock = getBlock(ctx, cache, block.parentRoot);
531
- if (!parentBlock) return 0;
521
+ if (!parentBlock) return 0n;
532
522
 
533
523
  if (parentBlock.slot + 1 === block.slot) {
534
- return 0;
524
+ return 0n;
535
525
  }
536
526
 
537
527
  // Post-Gloas the parent block has PENDING, EMPTY and FULL nodes. Only the support of the node this
538
528
  // block actually extends is discounted; votes for the other parent nodes are not support for it.
539
529
  const parentNodePayloadStatus = ctx.getParentNodePayloadStatus(blockRoot);
540
- if (parentNodePayloadStatus === null) return 0;
541
-
542
- const parentSupportInEmptySlots = getNodeSupportBetweenSlots(
543
- ctx,
544
- store,
545
- cache,
546
- balanceSource,
547
- block.parentRoot,
548
- parentNodePayloadStatus,
549
- (parentBlock.slot + 1) as Slot,
550
- (block.slot - 1) as Slot
551
- );
530
+ if (parentNodePayloadStatus === null) return 0n;
531
+
532
+ const parentSupportInEmptySlots =
533
+ BigInt(
534
+ getNodeSupportBetweenSlots(
535
+ ctx,
536
+ store,
537
+ cache,
538
+ balanceSource,
539
+ block.parentRoot,
540
+ parentNodePayloadStatus,
541
+ (parentBlock.slot + 1) as Slot,
542
+ (block.slot - 1) as Slot
543
+ )
544
+ ) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
552
545
  const adversarialWeight = computeAdversarialWeight(
553
546
  ctx,
554
547
  store,
@@ -558,7 +551,7 @@ export function computeEmptySlotSupportDiscount(
558
551
  (block.slot - 1) as Slot
559
552
  );
560
553
 
561
- return parentSupportInEmptySlots > adversarialWeight ? parentSupportInEmptySlots - adversarialWeight : 0;
554
+ return parentSupportInEmptySlots > adversarialWeight ? parentSupportInEmptySlots - adversarialWeight : 0n;
562
555
  }
563
556
 
564
557
  export function computeSafetyThreshold(
@@ -568,11 +561,11 @@ export function computeSafetyThreshold(
568
561
  balanceSource: FastConfirmationBalanceSource,
569
562
  blockRoot: RootHex
570
563
  ): {
571
- threshold: number;
572
- proposerScore: number;
573
- maximumSupport: number;
574
- supportDiscount: number;
575
- adversarialWeight: number;
564
+ threshold: bigint;
565
+ proposerScore: bigint;
566
+ maximumSupport: bigint;
567
+ supportDiscount: bigint;
568
+ adversarialWeight: bigint;
576
569
  } {
577
570
  const currentSlot = ctx.getCurrentSlot();
578
571
  const block = getBlock(ctx, cache, blockRoot);
@@ -600,9 +593,9 @@ export function computeSafetyThreshold(
600
593
  // Spec underflow guard:
601
594
  // if the discount alone already exceeds the threshold budget, the safety threshold is zero.
602
595
  const threshold =
603
- supportDiscount > maximumSupport + proposerScore + 2 * adversarialWeight
604
- ? 0
605
- : Math.floor((maximumSupport + proposerScore + 2 * adversarialWeight - supportDiscount) / 2);
596
+ supportDiscount > maximumSupport + proposerScore + 2n * adversarialWeight
597
+ ? 0n
598
+ : (maximumSupport + proposerScore + 2n * adversarialWeight - supportDiscount) / 2n;
606
599
 
607
600
  return {threshold, proposerScore, maximumSupport, supportDiscount, adversarialWeight};
608
601
  }
@@ -626,7 +619,8 @@ export function isOneConfirmed(
626
619
 
627
620
  // Spec: is_one_confirmed(store, balance_source, block_root)
628
621
  // Compare actual support for this block against the computed LMD-GHOST safety threshold.
629
- const support = getAttestationScore(ctx, cache, balanceSource, blockRoot, sourceKey);
622
+ const support =
623
+ BigInt(getAttestationScore(ctx, cache, balanceSource, blockRoot, sourceKey)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
630
624
  const {threshold, proposerScore, maximumSupport, supportDiscount, adversarialWeight} = computeSafetyThreshold(
631
625
  ctx,
632
626
  store,
@@ -709,18 +703,15 @@ export function getCurrentTargetScore(
709
703
  }
710
704
 
711
705
  function computeHonestFfgSupport(
712
- totalActiveBalance: number,
713
- ffgSupport: number,
714
- ffgWeightTillNow: number,
715
- adversarialWeight: number,
706
+ totalActiveBalance: bigint,
707
+ ffgSupport: bigint,
708
+ ffgWeightTillNow: bigint,
709
+ adversarialWeight: bigint,
716
710
  byzantineThreshold: number
717
- ): number {
711
+ ): bigint {
718
712
  const remainingFfgWeight = totalActiveBalance - ffgWeightTillNow;
719
- // The spec rounds in raw Gwei as `remaining_ffg_weight // 100 * honest_percent`.
720
- // In Lodestar this value is in effective-balance increments, so multiply before dividing by 100
721
- // to preserve the same percentage semantics at our coarser unit scale.
722
- const remainingHonestFfgWeight = Math.floor((remainingFfgWeight * (100 - byzantineThreshold)) / 100);
723
- const minHonestFfgSupport = ffgSupport - Math.min(adversarialWeight, ffgSupport);
713
+ const remainingHonestFfgWeight = (remainingFfgWeight / 100n) * BigInt(100 - byzantineThreshold);
714
+ const minHonestFfgSupport = ffgSupport > adversarialWeight ? ffgSupport - adversarialWeight : 0n;
724
715
  return minHonestFfgSupport + remainingHonestFfgWeight;
725
716
  }
726
717
 
@@ -728,15 +719,16 @@ export function computeHonestFfgSupportForCurrentTarget(
728
719
  ctx: FastConfirmationContext,
729
720
  store: IFastConfirmationStore,
730
721
  cache: FastConfirmationCache
731
- ): number {
722
+ ): bigint {
732
723
  const currentSlot = ctx.getCurrentSlot();
733
- if (currentSlot === 0) return 0;
724
+ if (currentSlot === 0) return 0n;
734
725
  const currentEpoch = computeEpochAtSlot(currentSlot);
735
726
  const targetState = getCurrentEpochState(ctx, store, cache);
736
- if (!targetState) return 0;
727
+ if (!targetState) return 0n;
737
728
  const targetBalanceSource = {state: targetState, balances: targetState.effectiveBalanceIncrements};
738
- const totalActiveBalance = getTotalActiveBalance(targetBalanceSource, cache);
739
- const ffgSupport = getCurrentTargetScore(ctx, store, cache);
729
+ const totalActiveBalance =
730
+ BigInt(getTotalActiveBalance(targetBalanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
731
+ const ffgSupport = BigInt(getCurrentTargetScore(ctx, store, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
740
732
  const tillNowFFGWeight = estimateCommitteeWeightBetweenSlots(
741
733
  targetBalanceSource,
742
734
  cache,
@@ -772,12 +764,11 @@ export function willNoConflictingCheckpointBeJustified(
772
764
  }
773
765
  const targetState = getCurrentEpochState(ctx, store, cache);
774
766
  if (!targetState) return false;
775
- const totalActiveBalance = getTotalActiveBalance(
776
- {state: targetState, balances: targetState.effectiveBalanceIncrements},
777
- cache
778
- );
767
+ const totalActiveBalance =
768
+ BigInt(getTotalActiveBalance({state: targetState, balances: targetState.effectiveBalanceIncrements}, cache)) *
769
+ EFFECTIVE_BALANCE_INCREMENT_BIGINT;
779
770
  const honestSupport = computeHonestFfgSupportForCurrentTarget(ctx, store, cache);
780
- return 3 * honestSupport > 1 * totalActiveBalance;
771
+ return 3n * honestSupport > 1n * totalActiveBalance;
781
772
  }
782
773
 
783
774
  export function willCurrentTargetBeJustified(
@@ -787,12 +778,11 @@ export function willCurrentTargetBeJustified(
787
778
  ): boolean {
788
779
  const targetState = getCurrentEpochState(ctx, store, cache);
789
780
  if (!targetState) return false;
790
- const totalActiveBalance = getTotalActiveBalance(
791
- {state: targetState, balances: targetState.effectiveBalanceIncrements},
792
- cache
793
- );
781
+ const totalActiveBalance =
782
+ BigInt(getTotalActiveBalance({state: targetState, balances: targetState.effectiveBalanceIncrements}, cache)) *
783
+ EFFECTIVE_BALANCE_INCREMENT_BIGINT;
794
784
  const honestSupport = computeHonestFfgSupportForCurrentTarget(ctx, store, cache);
795
- return 3 * honestSupport >= 2 * totalActiveBalance;
785
+ return 3n * honestSupport >= 2n * totalActiveBalance;
796
786
  }
797
787
 
798
788
  export function isConfirmedChainSafe(
@@ -34,7 +34,6 @@ import {
34
34
  import {Logger, MapDef, fromHex, toRootHex, withObservedDuration} from "@lodestar/utils";
35
35
  import {ForkChoiceMetrics} from "../metrics.js";
36
36
  import {computeDeltas} from "../protoArray/computeDeltas.js";
37
- import {ProtoArrayError, ProtoArrayErrorCode} from "../protoArray/errors.js";
38
37
  import {
39
38
  BlockExecutionStatus,
40
39
  ExecutionStatus,
@@ -112,7 +111,6 @@ const INIT_VOTE_SLOT: Slot = 0;
112
111
  * - Time is not updated automatically, updateTime MUST be called every slot
113
112
  */
114
113
  export class ForkChoice implements IForkChoice {
115
- irrecoverableError?: Error;
116
114
  /**
117
115
  * Votes currently tracked in the protoArray. Instead of tracking a VoteTracker of currentIndex, nextIndex and epoch,
118
116
  * we decompose the struct and track them in separate arrays for performance reason.
@@ -152,6 +150,8 @@ export class ForkChoice implements IForkChoice {
152
150
 
153
151
  /** Cached head */
154
152
  private head: ProtoBlock;
153
+ /** Slot of the last `updateHead()`, scores and best child links reflect votes, boost and viability at that slot */
154
+ private updateHeadSlot = 0;
155
155
  /**
156
156
  * Only cache attestation data root hex if it's tree backed since it's available.
157
157
  **/
@@ -695,18 +695,8 @@ export class ForkChoice implements IForkChoice {
695
695
  }
696
696
 
697
697
  // findHead returns the ProtoNode representing the head
698
- let head: ProtoNode;
699
- try {
700
- head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
701
- } catch (e) {
702
- // A poisoned tree never recovers, shut the node down instead of failing every head computation
703
- if (e instanceof ProtoArrayError && e.type.code === ProtoArrayErrorCode.INVALID_JUSTIFIED_EXECUTION_STATUS) {
704
- this.irrecoverableError = e;
705
- }
706
- throw e;
707
- }
708
-
709
- this.head = head;
698
+ this.head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
699
+ this.updateHeadSlot = currentSlot;
710
700
  return this.head;
711
701
  }
712
702
 
@@ -1161,7 +1151,7 @@ export class ForkChoice implements IForkChoice {
1161
1151
 
1162
1152
  /**
1163
1153
  * Notify fork choice that an execution payload has arrived (Gloas fork)
1164
- * Creates the FULL variant of a Gloas block when the payload becomes available
1154
+ * Creates the FULL variant of a Gloas block when the payload becomes available and refreshes the cached head
1165
1155
  * Spec: gloas/fork-choice.md#new-on_execution_payload
1166
1156
  */
1167
1157
  onExecutionPayload(
@@ -1185,9 +1175,10 @@ export class ForkChoice implements IForkChoice {
1185
1175
  });
1186
1176
  }
1187
1177
 
1178
+ const currentSlot = this.fcStore.currentSlot;
1188
1179
  this.protoArray.onExecutionPayload(
1189
1180
  blockRoot,
1190
- this.fcStore.currentSlot,
1181
+ currentSlot,
1191
1182
  executionPayloadBlockHash,
1192
1183
  executionPayloadNumber,
1193
1184
  executionPayloadGasLimit,
@@ -1195,6 +1186,11 @@ export class ForkChoice implements IForkChoice {
1195
1186
  executionStatus,
1196
1187
  dataAvailabilityStatus
1197
1188
  );
1189
+ if (currentSlot === this.updateHeadSlot) {
1190
+ this.head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
1191
+ } else {
1192
+ this.updateHead();
1193
+ }
1198
1194
  }
1199
1195
 
1200
1196
  /**
@@ -1211,6 +1207,18 @@ export class ForkChoice implements IForkChoice {
1211
1207
  const previousSlot = this.fcStore.currentSlot;
1212
1208
  // Note: we are relying upon `onTick` to update `fcStore.time` to ensure we don't get stuck in a loop.
1213
1209
  const didUpdateCheckpoints = this.onTick(previousSlot + 1);
1210
+ if (didUpdateCheckpoints) {
1211
+ // The pull-up realizes the unrealized justified checkpoint regardless of its execution status. Throw before
1212
+ // fast confirmation, which swallows head computation errors
1213
+ const justified = this.fcStore.justified.checkpoint;
1214
+ if (this.getBlockHexDefaultStatus(justified.rootHex)?.executionStatus === ExecutionStatus.Invalid) {
1215
+ throw new ForkChoiceError({
1216
+ code: ForkChoiceErrorCode.INVALID_JUSTIFIED_EXECUTION_STATUS,
1217
+ epoch: justified.epoch,
1218
+ root: justified.rootHex,
1219
+ });
1220
+ }
1221
+ }
1214
1222
  this.queuedAttestationsPreviousSlot = 0;
1215
1223
  // Process any attestations that might now be eligible before running FCR for this slot.
1216
1224
  this.processAttestationQueue();
@@ -78,8 +78,6 @@ export type ShouldOverrideForkChoiceUpdateResult =
78
78
  | {shouldOverrideFcu: false; reason: NotReorgedReason};
79
79
 
80
80
  export interface IForkChoice {
81
- irrecoverableError?: Error;
82
-
83
81
  /**
84
82
  * Returns the ancestor node of `block_root` at the given `slot`. (Note: `slot` refers
85
83
  * to the block that is *returned*, not the one that is supplied.)
@@ -213,7 +211,7 @@ export interface IForkChoice {
213
211
  ): void;
214
212
  /**
215
213
  * Notify fork choice that an execution payload has arrived (Gloas fork)
216
- * Creates the FULL variant of a Gloas block when the payload becomes available
214
+ * Creates the FULL variant of a Gloas block when the payload becomes available and refreshes the cached head
217
215
  *
218
216
  * ## Specification
219
217
  *
@@ -1,14 +1,12 @@
1
1
  import {Epoch, RootHex} from "@lodestar/types";
2
2
  import {LodestarError} from "@lodestar/utils";
3
3
 
4
- export enum LVHExecErrorCode {
4
+ export enum ExecutionStatusTransition {
5
5
  PreMergeToInvalid = "PreMergeToInvalid",
6
6
  ValidToInvalid = "ValidToInvalid",
7
7
  InvalidToValid = "InvalidToValid",
8
8
  }
9
9
 
10
- export type LVHExecError = {lvhCode: LVHExecErrorCode; blockRoot: RootHex; execHash: RootHex};
11
-
12
10
  export enum ProtoArrayErrorCode {
13
11
  FINALIZED_NODE_UNKNOWN = "PROTO_ARRAY_ERROR_FINALIZED_NODE_UNKNOWN",
14
12
  JUSTIFIED_NODE_UNKNOWN = "PROTO_ARRAY_ERROR_JUSTIFIED_NODE_UNKNOWN",
@@ -28,7 +26,7 @@ export enum ProtoArrayErrorCode {
28
26
  INVALID_BEST_NODE = "PROTO_ARRAY_ERROR_INVALID_BEST_NODE",
29
27
  INVALID_BLOCK_EXECUTION_STATUS = "PROTO_ARRAY_INVALID_BLOCK_EXECUTION_STATUS",
30
28
  INVALID_JUSTIFIED_EXECUTION_STATUS = "PROTO_ARRAY_INVALID_JUSTIFIED_EXECUTION_STATUS",
31
- INVALID_LVH_EXECUTION_RESPONSE = "PROTO_ARRAY_INVALID_LVH_EXECUTION_RESPONSE",
29
+ INVALID_EXECUTION_STATUS_TRANSITION = "PROTO_ARRAY_ERROR_INVALID_EXECUTION_STATUS_TRANSITION",
32
30
  PRE_GLOAS_BLOCK = "PROTO_ARRAY_ERROR_PRE_GLOAS_BLOCK",
33
31
  }
34
32
 
@@ -59,7 +57,12 @@ export type ProtoArrayErrorType =
59
57
  }
60
58
  | {code: ProtoArrayErrorCode.INVALID_BLOCK_EXECUTION_STATUS; root: RootHex}
61
59
  | {code: ProtoArrayErrorCode.INVALID_JUSTIFIED_EXECUTION_STATUS; root: RootHex}
62
- | ({code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE} & LVHExecError)
60
+ | {
61
+ code: ProtoArrayErrorCode.INVALID_EXECUTION_STATUS_TRANSITION;
62
+ transition: ExecutionStatusTransition;
63
+ blockRoot: RootHex;
64
+ execHash: RootHex;
65
+ }
63
66
  | {code: ProtoArrayErrorCode.PRE_GLOAS_BLOCK; root: RootHex};
64
67
 
65
68
  export class ProtoArrayError extends LodestarError<ProtoArrayErrorType> {}
@@ -4,7 +4,7 @@ import {DataAvailabilityStatus, computeEpochAtSlot, computeStartSlotAtEpoch} fro
4
4
  import {Epoch, RootHex, Slot, ValidatorIndex} from "@lodestar/types";
5
5
  import {bitCount, toRootHex} from "@lodestar/utils";
6
6
  import {ForkChoiceError, ForkChoiceErrorCode} from "../forkChoice/errors.js";
7
- import {LVHExecErrorCode, ProtoArrayError, ProtoArrayErrorCode} from "./errors.js";
7
+ import {ExecutionStatusTransition, ProtoArrayError, ProtoArrayErrorCode} from "./errors.js";
8
8
  import {
9
9
  ExecutionStatus,
10
10
  HEX_ZERO_HASH,
@@ -711,8 +711,14 @@ export class ProtoArray {
711
711
  this.propagateValidExecutionStatusByIndex(pendingIndex);
712
712
  }
713
713
 
714
- // Update bestChild for PENDING node (may now prefer FULL over EMPTY)
715
- this.maybeUpdateBestChildAndDescendant(pendingIndex, fullIndex, currentSlot, proposerBoostRoot);
714
+ // A zero-weight leaf only changes best child and descendant links on its path to the root
715
+ let childIndex = fullIndex;
716
+ let parentIndex: number | undefined = pendingIndex;
717
+ while (parentIndex !== undefined) {
718
+ this.maybeUpdateBestChildAndDescendant(parentIndex, childIndex, currentSlot, proposerBoostRoot);
719
+ childIndex = parentIndex;
720
+ parentIndex = this.nodes[childIndex].parent;
721
+ }
716
722
  }
717
723
 
718
724
  /** Count blocks selected as FULL or EMPTY by the supplied head chain in the inclusive slot range. */
@@ -1123,7 +1129,7 @@ export class ProtoArray {
1123
1129
  if (judged === LVHInvalidJudged.ChildPayload) {
1124
1130
  return {applied: false, reason: LVHNotAppliedReason.UnusableLVH};
1125
1131
  }
1126
- latestValidHashIndex = this.getUnknownLVHIndex(invalidateFromIndex);
1132
+ latestValidHashIndex = this.getParentPayloadIndex(invalidateFromIndex);
1127
1133
  }
1128
1134
 
1129
1135
  // Never invalidate the justified block, the EMPTY variant sharing its chain, or anything at or below it in
@@ -1138,8 +1144,8 @@ export class ProtoArray {
1138
1144
  (node.blockRoot === this.justifiedRoot && node.payloadStatus === PayloadStatus.EMPTY);
1139
1145
  if (conflict || justified) {
1140
1146
  if (judged === LVHInvalidJudged.FromBlock) {
1141
- // The LVH is unusable: fall back to the unknown LVH bound, but never cross this node
1142
- latestValidHashIndex = Math.max(nodeIndex, this.getUnknownLVHIndex(invalidateFromIndex));
1147
+ // The LVH is unusable: invalidate only the judged payload, but never cross this node
1148
+ latestValidHashIndex = Math.max(nodeIndex, this.getParentPayloadIndex(invalidateFromIndex));
1143
1149
  } else if (conflict) {
1144
1150
  return {applied: false, reason: LVHNotAppliedReason.Contradiction};
1145
1151
  } else {
@@ -1160,11 +1166,11 @@ export class ProtoArray {
1160
1166
  }
1161
1167
 
1162
1168
  /**
1163
- * Upper bound (exclusive) for invalidating from `fromIndex` when the engine gave no usable LVH: the parent of the
1164
- * last ancestor that still inherits the queried payload. Pre-gloas this is the parent of `fromIndex`. For a gloas
1165
- * EMPTY or PENDING node it reaches up to the FULL node that owns the payload. -1 when the chain reaches the root.
1169
+ * Index of the nearest ancestor carrying a different payload than `fromIndex`, i.e. the node holding its parent
1170
+ * payload. Pre-gloas this is the parent of `fromIndex`. For a gloas EMPTY or PENDING node it skips past the FULL
1171
+ * node that owns the payload. -1 when the chain reaches the root.
1166
1172
  */
1167
- private getUnknownLVHIndex(fromIndex: number): number {
1173
+ private getParentPayloadIndex(fromIndex: number): number {
1168
1174
  const payloadBlockHash = this.nodes[fromIndex].executionPayloadBlockHash;
1169
1175
  let nodeIndex = fromIndex;
1170
1176
  let parentIndex = this.nodes[nodeIndex].parent;
@@ -1198,19 +1204,23 @@ export class ProtoArray {
1198
1204
  }
1199
1205
 
1200
1206
  /**
1201
- * Gloas PENDING and EMPTY variants have no payload of their own, they inherit the execution status of
1202
- * the payload they build on, which is their `executionPayloadBlockHash`. Once that payload is VALID, all
1203
- * of them are, not only the ones on the chain the validation walked up (e.g. siblings, or blocks
1204
- * building on a sibling's EMPTY variant).
1207
+ * A node's execution status is that of the payload in its `executionPayloadBlockHash`: its own for FULL, the
1208
+ * inherited parent payload for gloas PENDING and EMPTY. Once that payload is VALID every node carrying it is, not
1209
+ * only the chain the validation walked up (e.g. siblings, blocks on a sibling's EMPTY variant, or an equivocating
1210
+ * block with the same payload). A node is only flipped below a Valid parent, otherwise a later INVALID for the
1211
+ * parent would reach it. A parent has a lower index than its children, so the scan updates it first.
1205
1212
  */
1206
1213
  private validatePayloadDependents(payloadHashes: Set<RootHex>): void {
1207
1214
  for (let nodeIndex = 0; nodeIndex < this.nodes.length; nodeIndex++) {
1208
1215
  const node = this.nodes[nodeIndex];
1216
+ const parentStatus = node.parent !== undefined ? this.nodes[node.parent].executionStatus : undefined;
1209
1217
  if (
1210
- node.payloadStatus === PayloadStatus.PENDING &&
1211
1218
  node.executionStatus === ExecutionStatus.Syncing &&
1212
1219
  node.executionPayloadBlockHash !== null &&
1213
- payloadHashes.has(node.executionPayloadBlockHash)
1220
+ payloadHashes.has(node.executionPayloadBlockHash) &&
1221
+ (parentStatus === undefined ||
1222
+ parentStatus === ExecutionStatus.Valid ||
1223
+ parentStatus === ExecutionStatus.PreMerge)
1214
1224
  ) {
1215
1225
  // Also flips the sibling EMPTY variant
1216
1226
  this.validateNodeByIndex(nodeIndex);
@@ -1289,11 +1299,11 @@ export class ProtoArray {
1289
1299
  invalidNode.executionStatus === ExecutionStatus.PreMerge
1290
1300
  ) {
1291
1301
  throw new ProtoArrayError({
1292
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1293
- lvhCode:
1302
+ code: ProtoArrayErrorCode.INVALID_EXECUTION_STATUS_TRANSITION,
1303
+ transition:
1294
1304
  invalidNode.executionStatus === ExecutionStatus.Valid
1295
- ? LVHExecErrorCode.ValidToInvalid
1296
- : LVHExecErrorCode.PreMergeToInvalid,
1305
+ ? ExecutionStatusTransition.ValidToInvalid
1306
+ : ExecutionStatusTransition.PreMergeToInvalid,
1297
1307
  blockRoot: invalidNode.blockRoot,
1298
1308
  execHash: invalidNode.executionPayloadBlockHash ?? ZERO_HASH_HEX,
1299
1309
  });
@@ -1317,8 +1327,8 @@ export class ProtoArray {
1317
1327
  const validNode = this.getNodeFromIndex(nodeIndex);
1318
1328
  if (validNode.executionStatus === ExecutionStatus.Invalid) {
1319
1329
  throw new ProtoArrayError({
1320
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1321
- lvhCode: LVHExecErrorCode.InvalidToValid,
1330
+ code: ProtoArrayErrorCode.INVALID_EXECUTION_STATUS_TRANSITION,
1331
+ transition: ExecutionStatusTransition.InvalidToValid,
1322
1332
  blockRoot: validNode.blockRoot,
1323
1333
  execHash: validNode.executionPayloadBlockHash,
1324
1334
  });