@lodestar/fork-choice 1.51.0 → 1.52.0-dev.03eb33e6f1

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.
Files changed (45) hide show
  1. package/lib/forkChoice/errors.d.ts +12 -2
  2. package/lib/forkChoice/errors.d.ts.map +1 -1
  3. package/lib/forkChoice/errors.js +2 -0
  4. package/lib/forkChoice/errors.js.map +1 -1
  5. package/lib/forkChoice/fastConfirmation/utils.d.ts +12 -12
  6. package/lib/forkChoice/fastConfirmation/utils.d.ts.map +1 -1
  7. package/lib/forkChoice/fastConfirmation/utils.js +48 -61
  8. package/lib/forkChoice/fastConfirmation/utils.js.map +1 -1
  9. package/lib/forkChoice/forkChoice.d.ts +10 -12
  10. package/lib/forkChoice/forkChoice.d.ts.map +1 -1
  11. package/lib/forkChoice/forkChoice.js +62 -22
  12. package/lib/forkChoice/forkChoice.js.map +1 -1
  13. package/lib/forkChoice/interface.d.ts +10 -5
  14. package/lib/forkChoice/interface.d.ts.map +1 -1
  15. package/lib/forkChoice/interface.js.map +1 -1
  16. package/lib/index.d.ts +2 -2
  17. package/lib/index.d.ts.map +1 -1
  18. package/lib/index.js +1 -1
  19. package/lib/index.js.map +1 -1
  20. package/lib/metrics.d.ts +3 -0
  21. package/lib/metrics.d.ts.map +1 -1
  22. package/lib/metrics.js +5 -0
  23. package/lib/metrics.js.map +1 -1
  24. package/lib/protoArray/errors.d.ts +8 -10
  25. package/lib/protoArray/errors.d.ts.map +1 -1
  26. package/lib/protoArray/errors.js +7 -7
  27. package/lib/protoArray/errors.js.map +1 -1
  28. package/lib/protoArray/interface.d.ts +35 -2
  29. package/lib/protoArray/interface.d.ts.map +1 -1
  30. package/lib/protoArray/interface.js +22 -0
  31. package/lib/protoArray/interface.js.map +1 -1
  32. package/lib/protoArray/protoArray.d.ts +25 -11
  33. package/lib/protoArray/protoArray.d.ts.map +1 -1
  34. package/lib/protoArray/protoArray.js +159 -91
  35. package/lib/protoArray/protoArray.js.map +1 -1
  36. package/package.json +8 -8
  37. package/src/forkChoice/errors.ts +6 -2
  38. package/src/forkChoice/fastConfirmation/utils.ts +84 -94
  39. package/src/forkChoice/forkChoice.ts +67 -23
  40. package/src/forkChoice/interface.ts +10 -5
  41. package/src/index.ts +9 -1
  42. package/src/metrics.ts +5 -0
  43. package/src/protoArray/errors.ts +8 -5
  44. package/src/protoArray/interface.ts +32 -4
  45. package/src/protoArray/protoArray.ts +171 -98
package/package.json CHANGED
@@ -11,7 +11,7 @@
11
11
  "bugs": {
12
12
  "url": "https://github.com/ChainSafe/lodestar/issues"
13
13
  },
14
- "version": "1.51.0",
14
+ "version": "1.52.0-dev.03eb33e6f1",
15
15
  "type": "module",
16
16
  "exports": {
17
17
  ".": {
@@ -39,12 +39,12 @@
39
39
  "check-readme": "pnpm exec tsx ../../scripts/check_readme.ts"
40
40
  },
41
41
  "dependencies": {
42
- "@chainsafe/ssz": "^1.9.0",
43
- "@lodestar/config": "^1.51.0",
44
- "@lodestar/params": "^1.51.0",
45
- "@lodestar/state-transition": "^1.51.0",
46
- "@lodestar/types": "^1.51.0",
47
- "@lodestar/utils": "^1.51.0"
42
+ "@chainsafe/ssz": "^1.9.1",
43
+ "@lodestar/config": "^1.52.0-dev.03eb33e6f1",
44
+ "@lodestar/params": "^1.52.0-dev.03eb33e6f1",
45
+ "@lodestar/state-transition": "^1.52.0-dev.03eb33e6f1",
46
+ "@lodestar/types": "^1.52.0-dev.03eb33e6f1",
47
+ "@lodestar/utils": "^1.52.0-dev.03eb33e6f1"
48
48
  },
49
49
  "keywords": [
50
50
  "ethereum",
@@ -52,5 +52,5 @@
52
52
  "beacon",
53
53
  "blockchain"
54
54
  ],
55
- "gitHead": "7923280c2e664e2fb81344921aaf41cb751957c7"
55
+ "gitHead": "11e3b6378736b9620b5f08b4ecf87ec71d921472"
56
56
  }
@@ -6,13 +6,15 @@ export enum InvalidBlockCode {
6
6
  FUTURE_SLOT = "FUTURE_SLOT",
7
7
  FINALIZED_SLOT = "FINALIZED_SLOT",
8
8
  NOT_FINALIZED_DESCENDANT = "NOT_FINALIZED_DESCENDANT",
9
+ PARENT_EXECUTION_INVALID = "PARENT_EXECUTION_INVALID",
9
10
  }
10
11
 
11
12
  export type InvalidBlock =
12
13
  | {code: InvalidBlockCode.UNKNOWN_PARENT; root: RootHex; hash: RootHex | null}
13
14
  | {code: InvalidBlockCode.FUTURE_SLOT; currentSlot: Slot; blockSlot: Slot}
14
15
  | {code: InvalidBlockCode.FINALIZED_SLOT; finalizedSlot: Slot; blockSlot: Slot}
15
- | {code: InvalidBlockCode.NOT_FINALIZED_DESCENDANT; finalizedRoot: RootHex; blockAncestor?: RootHex};
16
+ | {code: InvalidBlockCode.NOT_FINALIZED_DESCENDANT; finalizedRoot: RootHex; blockAncestor?: RootHex}
17
+ | {code: InvalidBlockCode.PARENT_EXECUTION_INVALID; root: RootHex; hash: RootHex | null};
16
18
 
17
19
  export enum InvalidAttestationCode {
18
20
  /**
@@ -90,6 +92,7 @@ export enum ForkChoiceErrorCode {
90
92
  UNABLE_TO_SET_JUSTIFIED_CHECKPOINT = "FORKCHOICE_ERROR_UNABLE_TO_SET_JUSTIFIED_CHECKPOINT",
91
93
  AFTER_BLOCK_FAILED = "FORKCHOICE_ERROR_AFTER_BLOCK_FAILED",
92
94
  MISSING_EXECUTION_PAYLOAD_BLOCK_HASH = "FORKCHOICE_ERROR_MISSING_EXECUTION_PAYLOAD_BLOCK_HASH",
95
+ INVALID_JUSTIFIED_EXECUTION_STATUS = "FORKCHOICE_ERROR_INVALID_JUSTIFIED_EXECUTION_STATUS",
93
96
  }
94
97
 
95
98
  export type ForkChoiceErrorType =
@@ -105,6 +108,7 @@ export type ForkChoiceErrorType =
105
108
  | {code: ForkChoiceErrorCode.FORK_CHOICE_STORE_ERROR; error: Error}
106
109
  | {code: ForkChoiceErrorCode.UNABLE_TO_SET_JUSTIFIED_CHECKPOINT; error: Error}
107
110
  | {code: ForkChoiceErrorCode.AFTER_BLOCK_FAILED; error: Error}
108
- | {code: ForkChoiceErrorCode.MISSING_EXECUTION_PAYLOAD_BLOCK_HASH; root: RootHex; slot: Slot};
111
+ | {code: ForkChoiceErrorCode.MISSING_EXECUTION_PAYLOAD_BLOCK_HASH; root: RootHex; slot: Slot}
112
+ | {code: ForkChoiceErrorCode.INVALID_JUSTIFIED_EXECUTION_STATUS; epoch: Epoch; root: RootHex};
109
113
 
110
114
  export class ForkChoiceError extends LodestarError<ForkChoiceErrorType> {}
@@ -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,12 +34,13 @@ 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,
41
40
  HEX_ZERO_HASH,
42
41
  LVHExecResponse,
42
+ LVHNotAppliedReason,
43
+ LVHVerdictResult,
43
44
  NULL_VOTE_INDEX,
44
45
  PayloadExecutionStatus,
45
46
  PayloadStatus,
@@ -110,7 +111,6 @@ const INIT_VOTE_SLOT: Slot = 0;
110
111
  * - Time is not updated automatically, updateTime MUST be called every slot
111
112
  */
112
113
  export class ForkChoice implements IForkChoice {
113
- irrecoverableError?: Error;
114
114
  /**
115
115
  * Votes currently tracked in the protoArray. Instead of tracking a VoteTracker of currentIndex, nextIndex and epoch,
116
116
  * we decompose the struct and track them in separate arrays for performance reason.
@@ -150,6 +150,8 @@ export class ForkChoice implements IForkChoice {
150
150
 
151
151
  /** Cached head */
152
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;
153
155
  /**
154
156
  * Only cache attestation data root hex if it's tree backed since it's available.
155
157
  **/
@@ -693,9 +695,8 @@ export class ForkChoice implements IForkChoice {
693
695
  }
694
696
 
695
697
  // findHead returns the ProtoNode representing the head
696
- const head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
697
-
698
- this.head = head;
698
+ this.head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
699
+ this.updateHeadSlot = currentSlot;
699
700
  return this.head;
700
701
  }
701
702
 
@@ -753,6 +754,9 @@ export class ForkChoice implements IForkChoice {
753
754
  *
754
755
  * `justifiedBalances` balances of justified state which is updated synchronously.
755
756
  * This ensures that the forkchoice is never out of sync.
757
+ *
758
+ * A block whose parent payload chain was invalidated is rejected. `executionStatus` is ignored for a gloas
759
+ * block: it has no payload of its own and inherits the status of the parent variant it builds on.
756
760
  */
757
761
  onBlock(
758
762
  block: BeaconBlock,
@@ -781,6 +785,19 @@ export class ForkChoice implements IForkChoice {
781
785
  });
782
786
  }
783
787
 
788
+ // An execution engine verdict can invalidate the parent while this block is being verified. Inserting the
789
+ // block would put a viable node below an invalidated one, or poison the tree if this block is VALID
790
+ if (parentBlock.executionStatus === ExecutionStatus.Invalid) {
791
+ throw new ForkChoiceError({
792
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
793
+ err: {
794
+ code: InvalidBlockCode.PARENT_EXECUTION_INVALID,
795
+ root: parentRootHex,
796
+ hash: parentHashHex,
797
+ },
798
+ });
799
+ }
800
+
784
801
  // Blocks cannot be in the future. If they are, their consideration must be delayed until
785
802
  // the are in the past.
786
803
  //
@@ -942,7 +959,9 @@ export class ForkChoice implements IForkChoice {
942
959
  executionPayloadBlockHash: parentBlockHashFromBid,
943
960
  executionPayloadNumber: parentMeta.number,
944
961
  executionPayloadGasLimit: parentMeta.gasLimit,
945
- executionStatus: this.getPostMergeExecStatus(executionStatus),
962
+ // The parent's default (PENDING) variant does not reflect a SYNCING parent payload, inheriting
963
+ // from the variant matching the bid's parent block hash keeps that payload from being marked VALID
964
+ executionStatus: this.getPostMergeExecStatus(parentBlock.executionStatus),
946
965
  dataAvailabilityStatus,
947
966
  };
948
967
  })()
@@ -1003,14 +1022,8 @@ export class ForkChoice implements IForkChoice {
1003
1022
  *
1004
1023
  * https://github.com/ethereum/consensus-specs/blob/v1.1.10/specs/phase0/fork-choice.md#on_attestation
1005
1024
  *
1006
- * It only approximates the specification since it does not perform
1007
- * `is_valid_indexed_attestation` since that should already have been called upstream and it's
1008
- * too expensive to call again.
1009
- *
1010
- * ## Notes:
1011
- *
1012
- * The supplied `attestation` **must** pass the `in_valid_indexed_attestation` function as it
1013
- * will not be run here.
1025
+ * Does not run `is_valid_indexed_attestation`. The caller must ensure all of its
1026
+ * validity requirements except index ordering: `attestingIndices` may be unsorted.
1014
1027
  */
1015
1028
  onAttestation(attestation: IndexedAttestation, attDataRoot: string, forceImport?: boolean): void {
1016
1029
  // Ignore any attestations to the zero hash.
@@ -1138,7 +1151,7 @@ export class ForkChoice implements IForkChoice {
1138
1151
 
1139
1152
  /**
1140
1153
  * Notify fork choice that an execution payload has arrived (Gloas fork)
1141
- * 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
1142
1155
  * Spec: gloas/fork-choice.md#new-on_execution_payload
1143
1156
  */
1144
1157
  onExecutionPayload(
@@ -1149,9 +1162,23 @@ export class ForkChoice implements IForkChoice {
1149
1162
  executionStatus: PayloadExecutionStatus,
1150
1163
  dataAvailabilityStatus: DataAvailabilityStatus
1151
1164
  ): void {
1165
+ // Same guard as onBlock: the PENDING variant carries the status of the payload chain this block builds on
1166
+ const pendingBlock = this.getBlockHexDefaultStatus(blockRoot);
1167
+ if (pendingBlock?.executionStatus === ExecutionStatus.Invalid) {
1168
+ throw new ForkChoiceError({
1169
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1170
+ err: {
1171
+ code: InvalidBlockCode.PARENT_EXECUTION_INVALID,
1172
+ root: pendingBlock.parentRoot,
1173
+ hash: pendingBlock.executionPayloadBlockHash,
1174
+ },
1175
+ });
1176
+ }
1177
+
1178
+ const currentSlot = this.fcStore.currentSlot;
1152
1179
  this.protoArray.onExecutionPayload(
1153
1180
  blockRoot,
1154
- this.fcStore.currentSlot,
1181
+ currentSlot,
1155
1182
  executionPayloadBlockHash,
1156
1183
  executionPayloadNumber,
1157
1184
  executionPayloadGasLimit,
@@ -1159,6 +1186,11 @@ export class ForkChoice implements IForkChoice {
1159
1186
  executionStatus,
1160
1187
  dataAvailabilityStatus
1161
1188
  );
1189
+ if (currentSlot === this.updateHeadSlot) {
1190
+ this.head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
1191
+ } else {
1192
+ this.updateHead();
1193
+ }
1162
1194
  }
1163
1195
 
1164
1196
  /**
@@ -1175,6 +1207,18 @@ export class ForkChoice implements IForkChoice {
1175
1207
  const previousSlot = this.fcStore.currentSlot;
1176
1208
  // Note: we are relying upon `onTick` to update `fcStore.time` to ensure we don't get stuck in a loop.
1177
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
+ }
1178
1222
  this.queuedAttestationsPreviousSlot = 0;
1179
1223
  // Process any attestations that might now be eligible before running FCR for this slot.
1180
1224
  this.processAttestationQueue();
@@ -1547,7 +1591,9 @@ export class ForkChoice implements IForkChoice {
1547
1591
 
1548
1592
  /** Very expensive function, iterates the entire ProtoArray. TODO: Is this function even necessary? */
1549
1593
  getBlockSummariesByParentRoot(parentRoot: RootHex): ProtoBlock[] {
1550
- return this.protoArray.nodes.filter((node) => node.parentRoot === parentRoot);
1594
+ return this.protoArray.nodes.filter(
1595
+ (node) => node.parentRoot === parentRoot && (!isGloasBlock(node) || node.payloadStatus === PayloadStatus.PENDING)
1596
+ );
1551
1597
  }
1552
1598
 
1553
1599
  /** Very expensive function, iterates the entire ProtoArray. TODO: Is this function even necessary? */
@@ -1556,7 +1602,7 @@ export class ForkChoice implements IForkChoice {
1556
1602
  const blocksAtSlot: ProtoBlock[] = [];
1557
1603
  for (let i = 0, len = nodes.length; i < len; i++) {
1558
1604
  const node = nodes[i];
1559
- if (node.slot === slot) {
1605
+ if (node.slot === slot && (!isGloasBlock(node) || node.payloadStatus === PayloadStatus.PENDING)) {
1560
1606
  blocksAtSlot.push(node);
1561
1607
  }
1562
1608
  }
@@ -1593,13 +1639,11 @@ export class ForkChoice implements IForkChoice {
1593
1639
  * justified's status as well as validate the terminal conditions if terminal block
1594
1640
  * becomes valid
1595
1641
  */
1596
- validateLatestHash(execResponse: LVHExecResponse): void {
1642
+ validateLatestHash(execResponse: LVHExecResponse): LVHVerdictResult {
1597
1643
  try {
1598
- this.protoArray.validateLatestHash(execResponse, this.fcStore.currentSlot);
1644
+ return this.protoArray.validateLatestHash(execResponse, this.fcStore.currentSlot);
1599
1645
  } catch (e) {
1600
- if (e instanceof ProtoArrayError && e.type.code === ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE) {
1601
- this.irrecoverableError = e;
1602
- }
1646
+ return {applied: false, reason: LVHNotAppliedReason.Error, error: e as Error};
1603
1647
  }
1604
1648
  }
1605
1649
 
@@ -3,6 +3,7 @@ import {AttesterSlashing, BeaconBlock, Epoch, IndexedAttestation, Root, RootHex,
3
3
  import {
4
4
  BlockExecutionStatus,
5
5
  LVHExecResponse,
6
+ LVHVerdictResult,
6
7
  PayloadExecutionStatus,
7
8
  PayloadStatus,
8
9
  ProtoBlock,
@@ -77,8 +78,6 @@ export type ShouldOverrideForkChoiceUpdateResult =
77
78
  | {shouldOverrideFcu: false; reason: NotReorgedReason};
78
79
 
79
80
  export interface IForkChoice {
80
- irrecoverableError?: Error;
81
-
82
81
  /**
83
82
  * Returns the ancestor node of `block_root` at the given `slot`. (Note: `slot` refers
84
83
  * to the block that is *returned*, not the one that is supplied.)
@@ -155,6 +154,9 @@ export interface IForkChoice {
155
154
  * ## Notes:
156
155
  *
157
156
  * The supplied block **must** pass the `state_transition` function as it will not be run here.
157
+ *
158
+ * Throws `InvalidBlockCode.PARENT_EXECUTION_INVALID` if the parent payload chain was invalidated.
159
+ * `executionStatus` is ignored for a gloas block, it inherits the status of the parent variant it builds on.
158
160
  */
159
161
  onBlock(
160
162
  block: BeaconBlock,
@@ -209,7 +211,7 @@ export interface IForkChoice {
209
211
  ): void;
210
212
  /**
211
213
  * Notify fork choice that an execution payload has arrived (Gloas fork)
212
- * 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
213
215
  *
214
216
  * ## Specification
215
217
  *
@@ -350,14 +352,17 @@ export interface IForkChoice {
350
352
  * `CheckpointWithHex` / finalized root without a specific payload-status variant in mind.
351
353
  */
352
354
  forwardIterateDescendantsDefaultStatus(blockRoot: RootHex): IterableIterator<ProtoBlock>;
355
+ /** One summary per block, its default variant (FULL pre-Gloas, PENDING for Gloas) */
353
356
  getBlockSummariesByParentRoot(parentRoot: RootHex): ProtoBlock[];
357
+ /** One summary per block, its default variant (FULL pre-Gloas, PENDING for Gloas) */
354
358
  getBlockSummariesAtSlot(slot: Slot): ProtoBlock[];
355
359
  /** Returns the distance of common ancestor of nodes to the max of the newNode and the prevNode. */
356
360
  getCommonAncestorDepth(prevBlock: ProtoBlock, newBlock: ProtoBlock): AncestorResult;
357
361
  /**
358
- * Optimistic sync validate till validated latest hash, invalidate any decendant branch if invalidated branch decendant provided
362
+ * Apply an execution engine verdict with a latest valid hash, see `ProtoArray.validateLatestHash`.
363
+ * Returns whether any execution status changed, and if not, why.
359
364
  */
360
- validateLatestHash(execResponse: LVHExecResponse): void;
365
+ validateLatestHash(execResponse: LVHExecResponse): LVHVerdictResult;
361
366
 
362
367
  /**
363
368
  * A dependent root is the block root of the last block before the state transition that decided a specific shuffling