@lodestar/fork-choice 1.52.0-dev.4c4ee3042c → 1.52.0-dev.536eb96eae

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.
@@ -3,29 +3,26 @@ import {
3
3
  EffectiveBalanceIncrements,
4
4
  IBeaconStateView,
5
5
  computeEpochAtSlot,
6
- computeSlotsSinceEpochStart,
7
6
  computeStartSlotAtEpoch,
8
7
  isActiveValidator,
9
8
  isStartSlotOfEpoch,
10
9
  } from "@lodestar/state-transition";
11
- import {Epoch, RootHex, Slot, ValidatorIndex} from "@lodestar/types";
10
+ import {Epoch, RootHex, Slot} from "@lodestar/types";
12
11
  import {Logger, fromHex} from "@lodestar/utils";
13
12
  import {ExecutionStatus, PayloadStatus, ProtoBlock} from "../../protoArray/interface.js";
14
13
  import {CheckpointWithHex, computeTotalBalance, equalCheckpointWithHex} from "../store.js";
15
14
  import {
15
+ ActiveBalances,
16
+ type BalanceSourceCacheKey,
16
17
  type BalanceSourceKey,
18
+ CommitteeSweep,
17
19
  FastConfirmationBalanceSource,
18
20
  FastConfirmationCache,
19
21
  FastConfirmationContext,
20
22
  FastConfirmationSnapshot,
21
23
  IFastConfirmationStore,
22
- type TotalActiveBalanceCacheKey,
23
24
  } from "./types.js";
24
25
 
25
- // Spec: adjust_committee_weight_estimate_to_ensure_safety
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 = 5n;
28
-
29
26
  const EFFECTIVE_BALANCE_INCREMENT_BIGINT = BigInt(EFFECTIVE_BALANCE_INCREMENT);
30
27
 
31
28
  const SAFETY_THRESHOLD_UNREACHABLE = Object.freeze({
@@ -182,25 +179,43 @@ export function getCheckpointState(
182
179
  return state ?? null;
183
180
  }
184
181
 
185
- export function getSlotCommittee(
182
+ /**
183
+ * Spec: get_slot_committee, for the slots `startSlot..endSlot`.
184
+ * Chain-walk queries ending at `current_slot - 1` share this sweep across many start slots.
185
+ * Extending it backwards avoids rebuilding a union of up to the full validator set per block.
186
+ */
187
+ function getCommitteeSweep(
188
+ ctx: FastConfirmationContext,
189
+ store: IFastConfirmationStore,
186
190
  cache: FastConfirmationCache,
187
- state: IBeaconStateView,
188
- slot: Slot
189
- ): Set<ValidatorIndex> {
190
- if (cache.committeeBySlot.has(slot)) {
191
- return cache.committeeBySlot.get(slot) ?? new Set();
192
- }
193
- const epoch = computeEpochAtSlot(slot);
194
- const committeesCount = state.getBeaconCommitteeCountPerSlot(epoch);
195
- const participants = new Set<ValidatorIndex>();
196
- for (let i = 0; i < committeesCount; i++) {
197
- const committee = state.getBeaconCommittee(slot, i);
198
- for (const index of committee) {
199
- participants.add(index);
191
+ startSlot: Slot,
192
+ endSlot: Slot
193
+ ): CommitteeSweep {
194
+ const headState = getHeadState(ctx, store, cache);
195
+ let sweep = cache.committeeSweepByEndSlot.get(endSlot);
196
+ if (sweep === undefined) {
197
+ sweep = {
198
+ seen: new Uint8Array(headState.validatorCount),
199
+ order: new Uint32Array(headState.validatorCount),
200
+ lengths: [],
201
+ weightsByKey: new Map(),
202
+ };
203
+ cache.committeeSweepByEndSlot.set(endSlot, sweep);
204
+ }
205
+
206
+ let length = sweep.lengths.at(-1) ?? 0;
207
+ for (let slot = endSlot - sweep.lengths.length; slot >= startSlot; slot--) {
208
+ const committeesCount = headState.getBeaconCommitteeCountPerSlot(computeEpochAtSlot(slot));
209
+ for (let i = 0; i < committeesCount; i++) {
210
+ for (const index of headState.getBeaconCommittee(slot, i)) {
211
+ if (sweep.seen[index] === 1) continue;
212
+ sweep.seen[index] = 1;
213
+ sweep.order[length++] = index;
214
+ }
200
215
  }
216
+ sweep.lengths.push(length);
201
217
  }
202
- cache.committeeBySlot.set(slot, participants);
203
- return participants;
218
+ return sweep;
204
219
  }
205
220
 
206
221
  function getSlotRangeParticipants(
@@ -209,17 +224,47 @@ function getSlotRangeParticipants(
209
224
  cache: FastConfirmationCache,
210
225
  startSlot: Slot,
211
226
  endSlot: Slot
212
- ): Set<ValidatorIndex> {
213
- const participants = new Set<ValidatorIndex>();
214
- const headState = getHeadState(ctx, store, cache);
215
-
216
- for (let slot = startSlot; slot <= endSlot; slot++) {
217
- for (const index of getSlotCommittee(cache, headState, slot)) {
218
- participants.add(index);
227
+ ): Uint32Array {
228
+ // Empty-slot discounts end at different block slots. A sweep per endpoint would allocate
229
+ // 5 bytes per registered validator for each gap, even when the gap spans just one slot.
230
+ // Cache compact participants instead, shared by support and adversarial-weight calculations.
231
+ if (endSlot !== ctx.getCurrentSlot() - 1) {
232
+ const key = `${startSlot}:${endSlot}`;
233
+ const cached = cache.participantsByRange.get(key);
234
+ if (cached !== undefined) return cached;
235
+
236
+ const state = getHeadState(ctx, store, cache);
237
+ const committees: Uint32Array[] = [];
238
+ let length = 0;
239
+ for (let slot = startSlot; slot <= endSlot; slot++) {
240
+ const count = state.getBeaconCommitteeCountPerSlot(computeEpochAtSlot(slot));
241
+ for (let i = 0; i < count; i++) {
242
+ const committee = state.getBeaconCommittee(slot, i);
243
+ committees.push(committee);
244
+ length += committee.length;
245
+ }
219
246
  }
247
+ let participants: Uint32Array;
248
+ // Within an epoch committees partition the active validator set.
249
+ if (computeEpochAtSlot(startSlot) === computeEpochAtSlot(endSlot)) {
250
+ participants = new Uint32Array(length);
251
+ let offset = 0;
252
+ for (const committee of committees) {
253
+ participants.set(committee, offset);
254
+ offset += committee.length;
255
+ }
256
+ } else {
257
+ const unique = new Set<number>();
258
+ for (const committee of committees) {
259
+ for (const index of committee) unique.add(index);
260
+ }
261
+ participants = Uint32Array.from(unique);
262
+ }
263
+ cache.participantsByRange.set(key, participants);
264
+ return participants;
220
265
  }
221
-
222
- return participants;
266
+ const sweep = getCommitteeSweep(ctx, store, cache, startSlot, endSlot);
267
+ return sweep.order.subarray(0, sweep.lengths[endSlot - startSlot]);
223
268
  }
224
269
 
225
270
  function isDescendantCached(
@@ -280,61 +325,94 @@ function getZeroInactiveBalances(balanceSource: FastConfirmationBalanceSource):
280
325
  return balanceSource.state?.getEffectiveBalanceIncrementsZeroInactive() ?? balanceSource.balances;
281
326
  }
282
327
 
283
- export function getTotalActiveBalance(
284
- balanceSource: FastConfirmationBalanceSource,
285
- cache: FastConfirmationCache
286
- ): number {
287
- // Invariant per balance source within a run, but read many times per is_one_confirmed evaluation
288
- // across the epoch-boundary chain walk; memoize so the full validator-set scan runs once per run.
289
- const key: TotalActiveBalanceCacheKey = balanceSource.state ?? balanceSource.balances;
290
- const cached = cache.totalActiveBalanceByKey.get(key);
328
+ /**
329
+ * Balances read by `get_total_active_balance` and `compute_committee_weight_between_slots`. Unlike the
330
+ * vote scans, these keep slashed validators: the maximum support and the adversarial budget they bound
331
+ * must cover slashed equivocators, whose weight `getEquivocationScore` subtracts. `unslashedTotal` serves
332
+ * `compute_proposer_score`, whose `calculate_committee_fraction` excludes slashed validators.
333
+ * Invariant per balance source within a run, but read many times per is_one_confirmed evaluation
334
+ * across the epoch-boundary chain walk; memoized so the full validator-set scan runs once per run.
335
+ */
336
+ function getActiveBalances(balanceSource: FastConfirmationBalanceSource, cache: FastConfirmationCache): ActiveBalances {
337
+ const key: BalanceSourceCacheKey = balanceSource.state ?? balanceSource.balances;
338
+ const cached = cache.activeBalancesByKey.get(key);
291
339
  if (cached !== undefined) return cached;
292
340
 
293
- const total = computeTotalBalance(getZeroInactiveBalances(balanceSource));
341
+ let active: ActiveBalances;
342
+ if (balanceSource.state) {
343
+ const {effectiveBalanceIncrements} = balanceSource.state;
344
+ const unslashedBalances = balanceSource.state.getEffectiveBalanceIncrementsZeroInactive();
345
+ const balances = new Uint16Array(balanceSource.state.validatorCount);
346
+ let total = 0;
347
+ let unslashedTotal = 0;
348
+ for (const i of balanceSource.state.getCurrentShuffling().activeIndices) {
349
+ balances[i] = effectiveBalanceIncrements[i];
350
+ total += balances[i];
351
+ unslashedTotal += unslashedBalances[i];
352
+ }
353
+ active = {balances, total, unslashedTotal};
354
+ } else {
355
+ // Fallback balances come from the justified-balance path, which also zeroes slashed validators
356
+ const total = computeTotalBalance(balanceSource.balances);
357
+ active = {balances: balanceSource.balances, total, unslashedTotal: total};
358
+ }
294
359
 
295
- cache.totalActiveBalanceByKey.set(key, total);
296
- return total;
360
+ cache.activeBalancesByKey.set(key, active);
361
+ return active;
297
362
  }
298
363
 
299
- export function estimateCommitteeWeightBetweenSlots(
364
+ export function getTotalActiveBalance(
300
365
  balanceSource: FastConfirmationBalanceSource,
366
+ cache: FastConfirmationCache
367
+ ): number {
368
+ return getActiveBalances(balanceSource, cache).total;
369
+ }
370
+
371
+ export function computeCommitteeWeightBetweenSlots(
372
+ ctx: FastConfirmationContext,
373
+ store: IFastConfirmationStore,
301
374
  cache: FastConfirmationCache,
375
+ balanceSource: FastConfirmationBalanceSource,
302
376
  startSlot: Slot,
303
377
  endSlot: Slot
304
378
  ): bigint {
305
379
  if (startSlot > endSlot) return 0n;
306
- const totalActiveBalance = BigInt(getTotalActiveBalance(balanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
307
- const startEpoch = computeEpochAtSlot(startSlot);
308
- const endEpoch = computeEpochAtSlot(endSlot);
309
380
 
310
381
  if (isFullValidatorSetCovered(startSlot, endSlot)) {
311
- return totalActiveBalance;
382
+ return BigInt(getTotalActiveBalance(balanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
312
383
  }
313
384
 
314
- const committeeWeightPerSlot = totalActiveBalance / BigInt(SLOTS_PER_EPOCH);
315
-
316
- if (startEpoch === endEpoch) {
317
- return committeeWeightPerSlot * BigInt(endSlot - startSlot + 1);
385
+ // Only the shared endpoint benefits from incremental weight prefixes across the chain walk.
386
+ // Other ranges reuse their compact participants without allocating a validator-sized sweep.
387
+ if (endSlot !== ctx.getCurrentSlot() - 1) {
388
+ const {balances} = getActiveBalances(balanceSource, cache);
389
+ let weight = 0;
390
+ for (const index of getSlotRangeParticipants(ctx, store, cache, startSlot, endSlot)) {
391
+ weight += balances[index] ?? 0;
392
+ }
393
+ return BigInt(weight) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
318
394
  }
319
395
 
320
- const numSlotsInStartEpoch = SLOTS_PER_EPOCH - computeSlotsSinceEpochStart(startSlot);
321
- const numSlotsInEndEpoch = computeSlotsSinceEpochStart(endSlot) + 1;
322
- const remainingSlotsInEndEpoch = SLOTS_PER_EPOCH - numSlotsInEndEpoch;
323
-
324
- const startEpochWeight = committeeWeightPerSlot * BigInt(numSlotsInStartEpoch);
325
- const endEpochWeight = committeeWeightPerSlot * BigInt(numSlotsInEndEpoch);
326
- // For ranges that cross exactly one epoch boundary without covering a full epoch,
327
- // the spec models overlap as:
328
- // startEpochWeightProRated = startEpochWeight * (1 - numSlotsInEndEpoch / SLOTS_PER_EPOCH)
329
- // = startEpochWeight * remainingSlotsInEndEpoch / SLOTS_PER_EPOCH
330
- // We keep the spec's "pro-rate the start epoch" form so integer rounding matches it exactly.
331
- const startEpochWeightProRated = (startEpochWeight / BigInt(SLOTS_PER_EPOCH)) * BigInt(remainingSlotsInEndEpoch);
332
-
333
- return adjustCommitteeWeightEstimateToEnsureSafety(startEpochWeightProRated + endEpochWeight);
334
- }
396
+ const sweep = getCommitteeSweep(ctx, store, cache, startSlot, endSlot);
397
+ const key: BalanceSourceCacheKey = balanceSource.state ?? balanceSource.balances;
398
+ let weights = sweep.weightsByKey.get(key);
399
+ if (weights === undefined) {
400
+ weights = [];
401
+ sweep.weightsByKey.set(key, weights);
402
+ }
335
403
 
336
- export function adjustCommitteeWeightEstimateToEnsureSafety(estimate: bigint): bigint {
337
- return ((estimate + 999n) / 1000n) * (1000n + COMMITTEE_WEIGHT_ESTIMATION_ADJUSTMENT_FACTOR);
404
+ const slotCount = endSlot - startSlot + 1;
405
+ if (weights.length < slotCount) {
406
+ const {balances} = getActiveBalances(balanceSource, cache);
407
+ let weight = weights.at(-1) ?? 0;
408
+ for (let i = weights.length; i < slotCount; i++) {
409
+ for (let j = i > 0 ? sweep.lengths[i - 1] : 0; j < sweep.lengths[i]; j++) {
410
+ weight += balances[sweep.order[j]] ?? 0;
411
+ }
412
+ weights.push(weight);
413
+ }
414
+ }
415
+ return BigInt(weights[slotCount - 1]) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
338
416
  }
339
417
 
340
418
  export function isFullValidatorSetCovered(startSlot: Slot, endSlot: Slot): boolean {
@@ -348,8 +426,9 @@ export function computeProposerScore(
348
426
  balanceSource: FastConfirmationBalanceSource,
349
427
  cache: FastConfirmationCache
350
428
  ): bigint {
351
- const totalActiveBalance = BigInt(getTotalActiveBalance(balanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
352
- const committeeWeight = totalActiveBalance / BigInt(SLOTS_PER_EPOCH);
429
+ const unslashedTotal =
430
+ BigInt(getActiveBalances(balanceSource, cache).unslashedTotal) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
431
+ const committeeWeight = unslashedTotal / BigInt(SLOTS_PER_EPOCH);
353
432
  return (committeeWeight * BigInt(ctx.config.PROPOSER_SCORE_BOOST)) / 100n;
354
433
  }
355
434
 
@@ -417,7 +496,7 @@ export function getNodeSupportBetweenSlots(
417
496
  if (startSlot > endSlot) return 0;
418
497
  const balances = getZeroInactiveBalances(balanceSource);
419
498
  const participants = getSlotRangeParticipants(ctx, store, cache, startSlot, endSlot);
420
- if (participants.size === 0) return 0;
499
+ if (participants.length === 0) return 0;
421
500
 
422
501
  const equivocating = ctx.getEquivocatingIndices();
423
502
  let score = 0;
@@ -454,7 +533,7 @@ export function getEquivocationScore(
454
533
  const state = balanceSource.state;
455
534
  const stateEpoch = state ? computeEpochAtSlot(state.slot) : null;
456
535
  const participants = getSlotRangeParticipants(ctx, store, cache, startSlot, endSlot);
457
- if (participants.size === 0) return 0;
536
+ if (participants.length === 0) return 0;
458
537
 
459
538
  let score = 0;
460
539
  for (const i of participants) {
@@ -477,7 +556,7 @@ export function computeAdversarialWeight(
477
556
  startSlot: Slot,
478
557
  endSlot: Slot
479
558
  ): bigint {
480
- const maximumWeight = estimateCommitteeWeightBetweenSlots(balanceSource, cache, startSlot, endSlot);
559
+ const maximumWeight = computeCommitteeWeightBetweenSlots(ctx, store, cache, balanceSource, startSlot, endSlot);
481
560
  const maxAdversarialWeight = (maximumWeight / 100n) * BigInt(ctx.config.CONFIRMATION_BYZANTINE_THRESHOLD);
482
561
  const equivocationScore =
483
562
  BigInt(getEquivocationScore(ctx, store, cache, balanceSource, startSlot, endSlot)) *
@@ -581,21 +660,23 @@ export function computeSafetyThreshold(
581
660
  // Build the threshold from the same terms used in the paper/spec:
582
661
  // max possible committee support, proposer boost, empty-slot discount, and adversarial budget.
583
662
  const proposerScore = computeProposerScore(ctx, balanceSource, cache);
584
- const maximumSupport = estimateCommitteeWeightBetweenSlots(
585
- balanceSource,
663
+ const maximumSupport = computeCommitteeWeightBetweenSlots(
664
+ ctx,
665
+ store,
586
666
  cache,
667
+ balanceSource,
587
668
  (parentBlock.slot + 1) as Slot,
588
669
  (currentSlot - 1) as Slot
589
670
  );
590
671
  const supportDiscount = computeEmptySlotSupportDiscount(ctx, store, cache, balanceSource, blockRoot);
591
672
  const adversarialWeight = getAdversarialWeight(ctx, store, cache, balanceSource, blockRoot);
592
673
 
593
- // Spec underflow guard:
594
- // if the discount alone already exceeds the threshold budget, the safety threshold is zero.
595
- const threshold =
596
- supportDiscount > maximumSupport + proposerScore + 2n * adversarialWeight
597
- ? 0n
598
- : (maximumSupport + proposerScore + 2n * adversarialWeight - supportDiscount) / 2n;
674
+ // The discounted votes come from committees within the maximum support range and are weighed with
675
+ // the same balances, so exceeding it means the computation is wrong rather than an underflow to guard.
676
+ if (supportDiscount > maximumSupport) {
677
+ throw new Error(`Fast confirmation support discount ${supportDiscount} exceeds maximum support ${maximumSupport}`);
678
+ }
679
+ const threshold = (maximumSupport + proposerScore + 2n * adversarialWeight - supportDiscount) / 2n;
599
680
 
600
681
  return {threshold, proposerScore, maximumSupport, supportDiscount, adversarialWeight};
601
682
  }
@@ -729,9 +810,11 @@ export function computeHonestFfgSupportForCurrentTarget(
729
810
  const totalActiveBalance =
730
811
  BigInt(getTotalActiveBalance(targetBalanceSource, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
731
812
  const ffgSupport = BigInt(getCurrentTargetScore(ctx, store, cache)) * EFFECTIVE_BALANCE_INCREMENT_BIGINT;
732
- const tillNowFFGWeight = estimateCommitteeWeightBetweenSlots(
733
- targetBalanceSource,
813
+ const tillNowFFGWeight = computeCommitteeWeightBetweenSlots(
814
+ ctx,
815
+ store,
734
816
  cache,
817
+ targetBalanceSource,
735
818
  computeStartSlotAtEpoch(currentEpoch),
736
819
  (currentSlot - 1) as Slot
737
820
  );
@@ -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,
@@ -1129,7 +1129,7 @@ export class ProtoArray {
1129
1129
  if (judged === LVHInvalidJudged.ChildPayload) {
1130
1130
  return {applied: false, reason: LVHNotAppliedReason.UnusableLVH};
1131
1131
  }
1132
- latestValidHashIndex = this.getUnknownLVHIndex(invalidateFromIndex);
1132
+ latestValidHashIndex = this.getParentPayloadIndex(invalidateFromIndex);
1133
1133
  }
1134
1134
 
1135
1135
  // Never invalidate the justified block, the EMPTY variant sharing its chain, or anything at or below it in
@@ -1144,8 +1144,8 @@ export class ProtoArray {
1144
1144
  (node.blockRoot === this.justifiedRoot && node.payloadStatus === PayloadStatus.EMPTY);
1145
1145
  if (conflict || justified) {
1146
1146
  if (judged === LVHInvalidJudged.FromBlock) {
1147
- // The LVH is unusable: fall back to the unknown LVH bound, but never cross this node
1148
- 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));
1149
1149
  } else if (conflict) {
1150
1150
  return {applied: false, reason: LVHNotAppliedReason.Contradiction};
1151
1151
  } else {
@@ -1166,11 +1166,11 @@ export class ProtoArray {
1166
1166
  }
1167
1167
 
1168
1168
  /**
1169
- * Upper bound (exclusive) for invalidating from `fromIndex` when the engine gave no usable LVH: the parent of the
1170
- * last ancestor that still inherits the queried payload. Pre-gloas this is the parent of `fromIndex`. For a gloas
1171
- * 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.
1172
1172
  */
1173
- private getUnknownLVHIndex(fromIndex: number): number {
1173
+ private getParentPayloadIndex(fromIndex: number): number {
1174
1174
  const payloadBlockHash = this.nodes[fromIndex].executionPayloadBlockHash;
1175
1175
  let nodeIndex = fromIndex;
1176
1176
  let parentIndex = this.nodes[nodeIndex].parent;
@@ -1204,19 +1204,23 @@ export class ProtoArray {
1204
1204
  }
1205
1205
 
1206
1206
  /**
1207
- * Gloas PENDING and EMPTY variants have no payload of their own, they inherit the execution status of
1208
- * the payload they build on, which is their `executionPayloadBlockHash`. Once that payload is VALID, all
1209
- * of them are, not only the ones on the chain the validation walked up (e.g. siblings, or blocks
1210
- * 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.
1211
1212
  */
1212
1213
  private validatePayloadDependents(payloadHashes: Set<RootHex>): void {
1213
1214
  for (let nodeIndex = 0; nodeIndex < this.nodes.length; nodeIndex++) {
1214
1215
  const node = this.nodes[nodeIndex];
1216
+ const parentStatus = node.parent !== undefined ? this.nodes[node.parent].executionStatus : undefined;
1215
1217
  if (
1216
- node.payloadStatus === PayloadStatus.PENDING &&
1217
1218
  node.executionStatus === ExecutionStatus.Syncing &&
1218
1219
  node.executionPayloadBlockHash !== null &&
1219
- payloadHashes.has(node.executionPayloadBlockHash)
1220
+ payloadHashes.has(node.executionPayloadBlockHash) &&
1221
+ (parentStatus === undefined ||
1222
+ parentStatus === ExecutionStatus.Valid ||
1223
+ parentStatus === ExecutionStatus.PreMerge)
1220
1224
  ) {
1221
1225
  // Also flips the sibling EMPTY variant
1222
1226
  this.validateNodeByIndex(nodeIndex);
@@ -1295,11 +1299,11 @@ export class ProtoArray {
1295
1299
  invalidNode.executionStatus === ExecutionStatus.PreMerge
1296
1300
  ) {
1297
1301
  throw new ProtoArrayError({
1298
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1299
- lvhCode:
1302
+ code: ProtoArrayErrorCode.INVALID_EXECUTION_STATUS_TRANSITION,
1303
+ transition:
1300
1304
  invalidNode.executionStatus === ExecutionStatus.Valid
1301
- ? LVHExecErrorCode.ValidToInvalid
1302
- : LVHExecErrorCode.PreMergeToInvalid,
1305
+ ? ExecutionStatusTransition.ValidToInvalid
1306
+ : ExecutionStatusTransition.PreMergeToInvalid,
1303
1307
  blockRoot: invalidNode.blockRoot,
1304
1308
  execHash: invalidNode.executionPayloadBlockHash ?? ZERO_HASH_HEX,
1305
1309
  });
@@ -1323,8 +1327,8 @@ export class ProtoArray {
1323
1327
  const validNode = this.getNodeFromIndex(nodeIndex);
1324
1328
  if (validNode.executionStatus === ExecutionStatus.Invalid) {
1325
1329
  throw new ProtoArrayError({
1326
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1327
- lvhCode: LVHExecErrorCode.InvalidToValid,
1330
+ code: ProtoArrayErrorCode.INVALID_EXECUTION_STATUS_TRANSITION,
1331
+ transition: ExecutionStatusTransition.InvalidToValid,
1328
1332
  blockRoot: validNode.blockRoot,
1329
1333
  execHash: validNode.executionPayloadBlockHash,
1330
1334
  });