@lodestar/fork-choice 1.51.0 → 1.52.0-dev.47827ac6f8

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.
@@ -40,6 +40,8 @@ import {
40
40
  ExecutionStatus,
41
41
  HEX_ZERO_HASH,
42
42
  LVHExecResponse,
43
+ LVHNotAppliedReason,
44
+ LVHVerdictResult,
43
45
  NULL_VOTE_INDEX,
44
46
  PayloadExecutionStatus,
45
47
  PayloadStatus,
@@ -693,7 +695,16 @@ 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);
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
+ }
697
708
 
698
709
  this.head = head;
699
710
  return this.head;
@@ -753,6 +764,9 @@ export class ForkChoice implements IForkChoice {
753
764
  *
754
765
  * `justifiedBalances` balances of justified state which is updated synchronously.
755
766
  * This ensures that the forkchoice is never out of sync.
767
+ *
768
+ * A block whose parent payload chain was invalidated is rejected. `executionStatus` is ignored for a gloas
769
+ * block: it has no payload of its own and inherits the status of the parent variant it builds on.
756
770
  */
757
771
  onBlock(
758
772
  block: BeaconBlock,
@@ -781,6 +795,19 @@ export class ForkChoice implements IForkChoice {
781
795
  });
782
796
  }
783
797
 
798
+ // An execution engine verdict can invalidate the parent while this block is being verified. Inserting the
799
+ // block would put a viable node below an invalidated one, or poison the tree if this block is VALID
800
+ if (parentBlock.executionStatus === ExecutionStatus.Invalid) {
801
+ throw new ForkChoiceError({
802
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
803
+ err: {
804
+ code: InvalidBlockCode.PARENT_EXECUTION_INVALID,
805
+ root: parentRootHex,
806
+ hash: parentHashHex,
807
+ },
808
+ });
809
+ }
810
+
784
811
  // Blocks cannot be in the future. If they are, their consideration must be delayed until
785
812
  // the are in the past.
786
813
  //
@@ -942,7 +969,9 @@ export class ForkChoice implements IForkChoice {
942
969
  executionPayloadBlockHash: parentBlockHashFromBid,
943
970
  executionPayloadNumber: parentMeta.number,
944
971
  executionPayloadGasLimit: parentMeta.gasLimit,
945
- executionStatus: this.getPostMergeExecStatus(executionStatus),
972
+ // The parent's default (PENDING) variant does not reflect a SYNCING parent payload, inheriting
973
+ // from the variant matching the bid's parent block hash keeps that payload from being marked VALID
974
+ executionStatus: this.getPostMergeExecStatus(parentBlock.executionStatus),
946
975
  dataAvailabilityStatus,
947
976
  };
948
977
  })()
@@ -1003,14 +1032,8 @@ export class ForkChoice implements IForkChoice {
1003
1032
  *
1004
1033
  * https://github.com/ethereum/consensus-specs/blob/v1.1.10/specs/phase0/fork-choice.md#on_attestation
1005
1034
  *
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.
1035
+ * Does not run `is_valid_indexed_attestation`. The caller must ensure all of its
1036
+ * validity requirements except index ordering: `attestingIndices` may be unsorted.
1014
1037
  */
1015
1038
  onAttestation(attestation: IndexedAttestation, attDataRoot: string, forceImport?: boolean): void {
1016
1039
  // Ignore any attestations to the zero hash.
@@ -1149,6 +1172,19 @@ export class ForkChoice implements IForkChoice {
1149
1172
  executionStatus: PayloadExecutionStatus,
1150
1173
  dataAvailabilityStatus: DataAvailabilityStatus
1151
1174
  ): void {
1175
+ // Same guard as onBlock: the PENDING variant carries the status of the payload chain this block builds on
1176
+ const pendingBlock = this.getBlockHexDefaultStatus(blockRoot);
1177
+ if (pendingBlock?.executionStatus === ExecutionStatus.Invalid) {
1178
+ throw new ForkChoiceError({
1179
+ code: ForkChoiceErrorCode.INVALID_BLOCK,
1180
+ err: {
1181
+ code: InvalidBlockCode.PARENT_EXECUTION_INVALID,
1182
+ root: pendingBlock.parentRoot,
1183
+ hash: pendingBlock.executionPayloadBlockHash,
1184
+ },
1185
+ });
1186
+ }
1187
+
1152
1188
  this.protoArray.onExecutionPayload(
1153
1189
  blockRoot,
1154
1190
  this.fcStore.currentSlot,
@@ -1547,7 +1583,9 @@ export class ForkChoice implements IForkChoice {
1547
1583
 
1548
1584
  /** Very expensive function, iterates the entire ProtoArray. TODO: Is this function even necessary? */
1549
1585
  getBlockSummariesByParentRoot(parentRoot: RootHex): ProtoBlock[] {
1550
- return this.protoArray.nodes.filter((node) => node.parentRoot === parentRoot);
1586
+ return this.protoArray.nodes.filter(
1587
+ (node) => node.parentRoot === parentRoot && (!isGloasBlock(node) || node.payloadStatus === PayloadStatus.PENDING)
1588
+ );
1551
1589
  }
1552
1590
 
1553
1591
  /** Very expensive function, iterates the entire ProtoArray. TODO: Is this function even necessary? */
@@ -1556,7 +1594,7 @@ export class ForkChoice implements IForkChoice {
1556
1594
  const blocksAtSlot: ProtoBlock[] = [];
1557
1595
  for (let i = 0, len = nodes.length; i < len; i++) {
1558
1596
  const node = nodes[i];
1559
- if (node.slot === slot) {
1597
+ if (node.slot === slot && (!isGloasBlock(node) || node.payloadStatus === PayloadStatus.PENDING)) {
1560
1598
  blocksAtSlot.push(node);
1561
1599
  }
1562
1600
  }
@@ -1593,13 +1631,11 @@ export class ForkChoice implements IForkChoice {
1593
1631
  * justified's status as well as validate the terminal conditions if terminal block
1594
1632
  * becomes valid
1595
1633
  */
1596
- validateLatestHash(execResponse: LVHExecResponse): void {
1634
+ validateLatestHash(execResponse: LVHExecResponse): LVHVerdictResult {
1597
1635
  try {
1598
- this.protoArray.validateLatestHash(execResponse, this.fcStore.currentSlot);
1636
+ return this.protoArray.validateLatestHash(execResponse, this.fcStore.currentSlot);
1599
1637
  } catch (e) {
1600
- if (e instanceof ProtoArrayError && e.type.code === ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE) {
1601
- this.irrecoverableError = e;
1602
- }
1638
+ return {applied: false, reason: LVHNotAppliedReason.Error, error: e as Error};
1603
1639
  }
1604
1640
  }
1605
1641
 
@@ -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,
@@ -155,6 +156,9 @@ export interface IForkChoice {
155
156
  * ## Notes:
156
157
  *
157
158
  * The supplied block **must** pass the `state_transition` function as it will not be run here.
159
+ *
160
+ * Throws `InvalidBlockCode.PARENT_EXECUTION_INVALID` if the parent payload chain was invalidated.
161
+ * `executionStatus` is ignored for a gloas block, it inherits the status of the parent variant it builds on.
158
162
  */
159
163
  onBlock(
160
164
  block: BeaconBlock,
@@ -350,14 +354,17 @@ export interface IForkChoice {
350
354
  * `CheckpointWithHex` / finalized root without a specific payload-status variant in mind.
351
355
  */
352
356
  forwardIterateDescendantsDefaultStatus(blockRoot: RootHex): IterableIterator<ProtoBlock>;
357
+ /** One summary per block, its default variant (FULL pre-Gloas, PENDING for Gloas) */
353
358
  getBlockSummariesByParentRoot(parentRoot: RootHex): ProtoBlock[];
359
+ /** One summary per block, its default variant (FULL pre-Gloas, PENDING for Gloas) */
354
360
  getBlockSummariesAtSlot(slot: Slot): ProtoBlock[];
355
361
  /** Returns the distance of common ancestor of nodes to the max of the newNode and the prevNode. */
356
362
  getCommonAncestorDepth(prevBlock: ProtoBlock, newBlock: ProtoBlock): AncestorResult;
357
363
  /**
358
- * Optimistic sync validate till validated latest hash, invalidate any decendant branch if invalidated branch decendant provided
364
+ * Apply an execution engine verdict with a latest valid hash, see `ProtoArray.validateLatestHash`.
365
+ * Returns whether any execution status changed, and if not, why.
359
366
  */
360
- validateLatestHash(execResponse: LVHExecResponse): void;
367
+ validateLatestHash(execResponse: LVHExecResponse): LVHVerdictResult;
361
368
 
362
369
  /**
363
370
  * A dependent root is the block root of the last block before the state transition that decided a specific shuffling
package/src/index.ts CHANGED
@@ -41,10 +41,18 @@ export type {
41
41
  BlockExtraMeta,
42
42
  LVHInvalidResponse,
43
43
  LVHValidResponse,
44
+ LVHVerdictResult,
44
45
  PayloadExecutionStatus,
45
46
  ProtoBlock,
46
47
  ProtoNode,
47
48
  PtcQuorum,
48
49
  } from "./protoArray/interface.js";
49
- export {ExecutionStatus, PayloadStatus, getPtcVerdict, isGloasBlock} from "./protoArray/interface.js";
50
+ export {
51
+ ExecutionStatus,
52
+ LVHInvalidJudged,
53
+ LVHNotAppliedReason,
54
+ PayloadStatus,
55
+ getPtcVerdict,
56
+ isGloasBlock,
57
+ } from "./protoArray/interface.js";
50
58
  export {ProtoArray} from "./protoArray/protoArray.js";
package/src/metrics.ts CHANGED
@@ -32,6 +32,11 @@ export function getForkChoiceMetrics(register: MetricsRegisterExtra) {
32
32
  name: "beacon_fork_choice_changed_head_total",
33
33
  help: "Count of occasions fork choice has found a new head",
34
34
  }),
35
+ executionInvalidations: register.gauge<{source: string}>({
36
+ name: "beacon_fork_choice_execution_invalidations_total",
37
+ help: "Count of execution engine INVALID verdicts applied to fork choice, by verdict source",
38
+ labelNames: ["source"],
39
+ }),
35
40
  reorg: register.gauge({
36
41
  name: "beacon_fork_choice_reorg_total",
37
42
  help: "Count of occasions fork choice has switched to a different chain",
@@ -55,17 +55,45 @@ export function isGloasBlock(block: ProtoBlock): block is ProtoBlock & {parentBl
55
55
  export type LVHValidResponse = {
56
56
  executionStatus: ExecutionStatus.Valid;
57
57
  latestValidExecHash: RootHex;
58
+ /** Resolves the exact node to validate when several nodes carry the same payload hash (gloas variants) */
59
+ blockRoot?: RootHex;
58
60
  };
61
+ /** Which payload the execution engine judged INVALID, relative to the node the invalidation starts from */
62
+ export enum LVHInvalidJudged {
63
+ /** The from node's own payload, e.g. the head sent in forkchoiceUpdated */
64
+ FromBlock = "from_block",
65
+ /** A payload built on the from node that is not in fork choice, e.g. a payload rejected by newPayload */
66
+ ChildPayload = "child_payload",
67
+ }
59
68
  export type LVHInvalidResponse = {
60
69
  executionStatus: ExecutionStatus.Invalid;
61
70
  latestValidExecHash: RootHex | null;
62
- invalidateFromParentBlockRoot: RootHex;
63
- // EL block hash from invalid block's bid (gloas) or payload's parentHash (pre-gloas).
64
- // Disambiguates which variant of the parent (FULL vs EMPTY) to invalidate from.
65
- invalidateFromParentBlockHash: RootHex;
71
+ invalidateFromBlockRoot: RootHex;
72
+ // EL block hash of the from node's payload chain, disambiguates which variant (FULL vs EMPTY) to invalidate from.
73
+ // For `ChildPayload` it is the judged payload's parent hash.
74
+ invalidateFromBlockHash: RootHex;
75
+ judged: LVHInvalidJudged;
66
76
  };
67
77
  export type LVHExecResponse = LVHValidResponse | LVHInvalidResponse;
68
78
 
79
+ export enum LVHNotAppliedReason {
80
+ /** VALID verdict whose latest valid hash is not in fork choice */
81
+ UnknownLVH = "unknown_lvh",
82
+ /** Fork choice already holds the verdict */
83
+ AlreadyApplied = "already_applied",
84
+ /** The verdict contradicts a status the engine already resolved */
85
+ Contradiction = "contradiction",
86
+ /** INVALID verdict on a payload that is not in fork choice, with a latest valid hash that is null or unknown */
87
+ UnusableLVH = "unusable_lvh",
88
+ /** INVALID verdict that covers no node above the latest valid hash or the justified block */
89
+ NothingToInvalidate = "nothing_to_invalidate",
90
+ Error = "error",
91
+ }
92
+ export type LVHVerdictResult =
93
+ | {applied: true}
94
+ | {applied: false; reason: Exclude<LVHNotAppliedReason, LVHNotAppliedReason.Error>}
95
+ | {applied: false; reason: LVHNotAppliedReason.Error; error: Error};
96
+
69
97
  /**
70
98
  * Any execution status that is not definitively invalid.
71
99
  * Valid | Syncing | PreMerge
@@ -4,11 +4,14 @@ 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 {LVHExecError, LVHExecErrorCode, ProtoArrayError, ProtoArrayErrorCode} from "./errors.js";
7
+ import {LVHExecErrorCode, ProtoArrayError, ProtoArrayErrorCode} from "./errors.js";
8
8
  import {
9
9
  ExecutionStatus,
10
10
  HEX_ZERO_HASH,
11
11
  LVHExecResponse,
12
+ LVHInvalidJudged,
13
+ LVHNotAppliedReason,
14
+ LVHVerdictResult,
12
15
  PayloadExecutionStatus,
13
16
  PayloadStatus,
14
17
  ProtoBlock,
@@ -94,7 +97,6 @@ export class ProtoArray {
94
97
  * Note: undefined array elements indicate that variant doesn't exist for this block
95
98
  */
96
99
  indices = new Map<RootHex, VariantIndices>();
97
- lvhError?: LVHExecError;
98
100
 
99
101
  private previousProposerBoost: ProposerBoost | null = null;
100
102
  /** Root read by shouldExtendPayload(), set even while the boost weight is withheld */
@@ -1019,12 +1021,20 @@ export class ProtoArray {
1019
1021
  }
1020
1022
 
1021
1023
  /**
1022
- * Optimistic sync validate till validated latest hash, invalidate any descendant branch
1023
- * if invalidate till hash provided. If consensus fails, this will invalidate entire
1024
- * forkChoice which will throw on any call to findHead
1024
+ * Apply an execution engine verdict with a latest valid hash (LVH) to the tree. VALID flips Syncing nodes up to the
1025
+ * LVH node. INVALID invalidates the node identified by `invalidateFromBlockRoot/Hash` and its ancestors up to
1026
+ * the LVH node (exclusive), then every descendant. Returns whether any status changed, and if not, why.
1027
+ *
1028
+ * A verdict never contradicts what fork choice already holds: a node the engine already resolved is never flipped
1029
+ * and an INVALID never crosses the justified node. The LVH is unusable when it is null, not an ancestor of the from
1030
+ * node, or the walk to it meets such a node.
1031
+ *
1032
+ * An unusable LVH leaves only the claim about the judged payload. With `LVHInvalidJudged.FromBlock` that is the from
1033
+ * node: it and the nodes that inherit its payload (gloas PENDING and EMPTY variants) are invalidated, nothing above
1034
+ * them. With `LVHInvalidJudged.ChildPayload` the judged payload is not in the tree and the from node is its parent,
1035
+ * so the verdict is dropped.
1025
1036
  */
1026
- // TODO GLOAS: Review usage of this post-gloas
1027
- validateLatestHash(execResponse: LVHExecResponse, currentSlot: Slot): void {
1037
+ validateLatestHash(execResponse: LVHExecResponse, currentSlot: Slot): LVHVerdictResult {
1028
1038
  // Look reverse because its highly likely node with latestValidExecHash is towards the
1029
1039
  // the leaves of the forkchoice
1030
1040
  //
@@ -1035,71 +1045,134 @@ export class ProtoArray {
1035
1045
  // https://github.com/ChainSafe/lodestar/pull/4182#discussion_r914770167
1036
1046
 
1037
1047
  if (execResponse.executionStatus === ExecutionStatus.Valid) {
1038
- const {latestValidExecHash} = execResponse;
1048
+ const {latestValidExecHash, blockRoot} = execResponse;
1039
1049
  // We use -1 for denoting not found
1040
1050
  let latestValidHashIndex = -1;
1041
1051
 
1042
- for (let nodeIndex = this.nodes.length - 1; nodeIndex >= 0; nodeIndex--) {
1043
- if (this.nodes[nodeIndex].executionPayloadBlockHash === latestValidExecHash) {
1044
- latestValidHashIndex = nodeIndex;
1045
- // We found the block corresponding to latestValidHashIndex, exit the loop
1046
- break;
1052
+ if (blockRoot !== undefined) {
1053
+ latestValidHashIndex = this.getNodeIndexByRootAndBlockHash(blockRoot, latestValidExecHash) ?? -1;
1054
+ } else {
1055
+ for (let nodeIndex = this.nodes.length - 1; nodeIndex >= 0; nodeIndex--) {
1056
+ if (this.nodes[nodeIndex].executionPayloadBlockHash === latestValidExecHash) {
1057
+ latestValidHashIndex = nodeIndex;
1058
+ // We found the block corresponding to latestValidHashIndex, exit the loop
1059
+ break;
1060
+ }
1047
1061
  }
1048
1062
  }
1049
1063
 
1050
1064
  // We are trying to be as forgiving as possible here because ideally latestValidHashIndex
1051
1065
  // should be found in the forkchoice
1052
- if (latestValidHashIndex >= 0) {
1053
- this.propagateValidExecutionStatusByIndex(latestValidHashIndex);
1066
+ if (latestValidHashIndex < 0) {
1067
+ return {applied: false, reason: LVHNotAppliedReason.UnknownLVH};
1054
1068
  }
1055
- } else {
1056
- // In case of invalidation, ideally:
1057
- // i) Find the invalid payload
1058
- // ii) Obtain a chain [LVH.child, LVH.child.child, ....., invalid_payload]
1059
- // iii) Obtain a chain [Last_known_valid_node, ...., LVH]
1060
- //
1061
- // Mark chain iii) as Valid if LVH is non null but right now LVH can be non null without
1062
- // gurranteing chain iii) to be valid: for e.g. in following scenario LVH can be returned
1063
- // as any of SYNCING: SYNCING, SYNCING, SYNCING, INVALID (due to simple check)/
1064
- // So we currently ignore this chain and hope eventually it gets resolved
1065
- //
1066
- // Mark chain ii) as Invalid if LVH is found and non null, else only invalidate invalid_payload
1067
- // if its in fcU.
1068
- //
1069
- const {invalidateFromParentBlockRoot, invalidateFromParentBlockHash, latestValidExecHash} = execResponse;
1070
- const invalidateFromParentIndex = this.getNodeIndexByRootAndBlockHash(
1071
- invalidateFromParentBlockRoot,
1072
- invalidateFromParentBlockHash
1069
+ const {executionStatus} = this.nodes[latestValidHashIndex];
1070
+ if (executionStatus === ExecutionStatus.Valid || executionStatus === ExecutionStatus.PreMerge) {
1071
+ return {applied: false, reason: LVHNotAppliedReason.AlreadyApplied};
1072
+ }
1073
+ // The walk up flips every Syncing ancestor, it must not contradict an invalidated one
1074
+ let nodeIndex: number | undefined = latestValidHashIndex;
1075
+ while (nodeIndex !== undefined) {
1076
+ const node: ProtoNode = this.nodes[nodeIndex];
1077
+ if (node.executionStatus === ExecutionStatus.Valid || node.executionStatus === ExecutionStatus.PreMerge) {
1078
+ break;
1079
+ }
1080
+ if (node.executionStatus === ExecutionStatus.Invalid) {
1081
+ return {applied: false, reason: LVHNotAppliedReason.Contradiction};
1082
+ }
1083
+ nodeIndex = node.parent;
1084
+ }
1085
+ this.propagateValidExecutionStatusByIndex(latestValidHashIndex);
1086
+ return {applied: true};
1087
+ }
1088
+
1089
+ // In case of invalidation, ideally:
1090
+ // i) Find the invalid payload
1091
+ // ii) Obtain a chain [LVH.child, LVH.child.child, ....., invalid_payload]
1092
+ // iii) Obtain a chain [Last_known_valid_node, ...., LVH]
1093
+ //
1094
+ // Mark chain iii) as Valid if LVH is non null but right now LVH can be non null without
1095
+ // gurranteing chain iii) to be valid: for e.g. in following scenario LVH can be returned
1096
+ // as any of SYNCING: SYNCING, SYNCING, SYNCING, INVALID (due to simple check)/
1097
+ // So we currently ignore this chain and hope eventually it gets resolved
1098
+ //
1099
+ // Mark chain ii) as Invalid if LVH is found and non null, else only invalidate invalid_payload
1100
+ // if its in fcU.
1101
+ //
1102
+ const {invalidateFromBlockRoot, invalidateFromBlockHash, latestValidExecHash, judged} = execResponse;
1103
+ const invalidateFromIndex = this.getNodeIndexByRootAndBlockHash(invalidateFromBlockRoot, invalidateFromBlockHash);
1104
+ if (invalidateFromIndex === undefined) {
1105
+ throw Error(
1106
+ `Unable to find invalidateFromBlockRoot=${invalidateFromBlockRoot} invalidateFromBlockHash=${invalidateFromBlockHash} in forkChoice`
1073
1107
  );
1074
- if (invalidateFromParentIndex === undefined) {
1075
- throw Error(
1076
- `Unable to find invalidateFromParentBlockRoot=${invalidateFromParentBlockRoot} invalidateFromParentBlockHash=${invalidateFromParentBlockHash} in forkChoice`
1077
- );
1108
+ }
1109
+ const fromStatus = this.nodes[invalidateFromIndex].executionStatus;
1110
+ if (fromStatus !== ExecutionStatus.Syncing) {
1111
+ return {
1112
+ applied: false,
1113
+ reason:
1114
+ fromStatus === ExecutionStatus.Invalid
1115
+ ? LVHNotAppliedReason.AlreadyApplied
1116
+ : LVHNotAppliedReason.Contradiction,
1117
+ };
1118
+ }
1119
+
1120
+ let latestValidHashIndex =
1121
+ latestValidExecHash !== null ? this.getNodeIndexFromLVH(latestValidExecHash, invalidateFromIndex) : null;
1122
+ if (latestValidHashIndex === null) {
1123
+ if (judged === LVHInvalidJudged.ChildPayload) {
1124
+ return {applied: false, reason: LVHNotAppliedReason.UnusableLVH};
1078
1125
  }
1079
- const latestValidHashIndex =
1080
- latestValidExecHash !== null ? this.getNodeIndexFromLVH(latestValidExecHash, invalidateFromParentIndex) : null;
1081
- if (latestValidHashIndex === null) {
1082
- /**
1083
- * The LVH (latest valid hash) is null or not found.
1084
- *
1085
- * The spec gives an allowance for the EL being able to return a nullish LVH if it could not
1086
- * "determine" one. There are two interpretations:
1087
- *
1088
- * - "the LVH is unknown" - simply throw and move on. We can't determine which chain to invalidate
1089
- * since we don't know which ancestor is valid.
1090
- *
1091
- * - "the LVH doesn't exist" - this means that the entire ancestor chain is invalid, and should
1092
- * be marked as such.
1093
- *
1094
- * The more robust approach is to treat nullish LVH as "the LVH is unknown" rather than
1095
- * "the LVH doesn't exist". The alternative means that we will poison a valid chain when the
1096
- * EL is lazy (or buggy) with its LVH response.
1097
- */
1098
- throw Error(`Unable to find latestValidExecHash=${latestValidExecHash} in the forkchoice`);
1126
+ latestValidHashIndex = this.getUnknownLVHIndex(invalidateFromIndex);
1127
+ }
1128
+
1129
+ // Never invalidate the justified block, the EMPTY variant sharing its chain, or anything at or below it in
1130
+ // the tree. The justified block's own payload (FULL variant) is not part of the checkpoint
1131
+ const justifiedIndex = this.getDefaultNodeIndex(this.justifiedRoot) ?? -1;
1132
+ let nodeIndex: number | undefined = invalidateFromIndex;
1133
+ while (nodeIndex !== undefined && nodeIndex > latestValidHashIndex) {
1134
+ const node: ProtoNode = this.nodes[nodeIndex];
1135
+ const conflict = node.executionStatus !== ExecutionStatus.Syncing;
1136
+ const justified =
1137
+ nodeIndex <= justifiedIndex ||
1138
+ (node.blockRoot === this.justifiedRoot && node.payloadStatus === PayloadStatus.EMPTY);
1139
+ if (conflict || justified) {
1140
+ 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));
1143
+ } else if (conflict) {
1144
+ return {applied: false, reason: LVHNotAppliedReason.Contradiction};
1145
+ } else {
1146
+ // The LVH is below the justified node, it still covers everything above it
1147
+ latestValidHashIndex = nodeIndex;
1148
+ }
1149
+ break;
1099
1150
  }
1151
+ nodeIndex = node.parent;
1152
+ }
1100
1153
 
1101
- this.propagateInValidExecutionStatusByIndex(invalidateFromParentIndex, latestValidHashIndex, currentSlot);
1154
+ if (invalidateFromIndex <= latestValidHashIndex) {
1155
+ return {applied: false, reason: LVHNotAppliedReason.NothingToInvalidate};
1102
1156
  }
1157
+
1158
+ this.propagateInValidExecutionStatusByIndex(invalidateFromIndex, latestValidHashIndex, currentSlot);
1159
+ return {applied: true};
1160
+ }
1161
+
1162
+ /**
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.
1166
+ */
1167
+ private getUnknownLVHIndex(fromIndex: number): number {
1168
+ const payloadBlockHash = this.nodes[fromIndex].executionPayloadBlockHash;
1169
+ let nodeIndex = fromIndex;
1170
+ let parentIndex = this.nodes[nodeIndex].parent;
1171
+ while (parentIndex !== undefined && this.nodes[parentIndex].executionPayloadBlockHash === payloadBlockHash) {
1172
+ nodeIndex = parentIndex;
1173
+ parentIndex = this.nodes[nodeIndex].parent;
1174
+ }
1175
+ return parentIndex ?? -1;
1103
1176
  }
1104
1177
 
1105
1178
  private propagateValidExecutionStatusByIndex(validNodeIndex: number): void {
@@ -1156,12 +1229,12 @@ export class ProtoArray {
1156
1229
  */
1157
1230
 
1158
1231
  private propagateInValidExecutionStatusByIndex(
1159
- invalidateFromParentIndex: number,
1232
+ invalidateFromIndex: number,
1160
1233
  latestValidHashIndex: number,
1161
1234
  currentSlot: Slot
1162
1235
  ): void {
1163
- // Pass 1: mark invalidateFromParentIndex and its parents invalid
1164
- let invalidateIndex: number | undefined = invalidateFromParentIndex;
1236
+ // Pass 1: mark invalidateFromIndex and its parents invalid
1237
+ let invalidateIndex: number | undefined = invalidateFromIndex;
1165
1238
  while (invalidateIndex !== undefined && invalidateIndex > latestValidHashIndex) {
1166
1239
  const invalidNode = this.invalidateNodeByIndex(invalidateIndex);
1167
1240
  invalidateIndex = invalidNode.parent;
@@ -1210,28 +1283,19 @@ export class ProtoArray {
1210
1283
  private invalidateNodeByIndex(nodeIndex: number): ProtoNode {
1211
1284
  const invalidNode = this.getNodeFromIndex(nodeIndex);
1212
1285
 
1213
- // If node to be invalidated is pre-merge or valid,it is a catastrophe,
1214
- // and indicates consensus failure and a non recoverable damage.
1215
- //
1216
- // There is no further processing that can be done.
1217
- // Just assign error for marking proto-array perma damaged and throw!
1286
+ // validateLatestHash never starts an invalidation that reaches a pre-merge or valid node
1218
1287
  if (
1219
1288
  invalidNode.executionStatus === ExecutionStatus.Valid ||
1220
1289
  invalidNode.executionStatus === ExecutionStatus.PreMerge
1221
1290
  ) {
1222
- const lvhCode =
1223
- invalidNode.executionStatus === ExecutionStatus.Valid
1224
- ? LVHExecErrorCode.ValidToInvalid
1225
- : LVHExecErrorCode.PreMergeToInvalid;
1226
-
1227
- this.lvhError = {
1228
- lvhCode,
1229
- blockRoot: invalidNode.blockRoot,
1230
- execHash: invalidNode.executionPayloadBlockHash ?? ZERO_HASH_HEX,
1231
- };
1232
1291
  throw new ProtoArrayError({
1233
1292
  code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1234
- ...this.lvhError,
1293
+ lvhCode:
1294
+ invalidNode.executionStatus === ExecutionStatus.Valid
1295
+ ? LVHExecErrorCode.ValidToInvalid
1296
+ : LVHExecErrorCode.PreMergeToInvalid,
1297
+ blockRoot: invalidNode.blockRoot,
1298
+ execHash: invalidNode.executionPayloadBlockHash ?? ZERO_HASH_HEX,
1235
1299
  });
1236
1300
  }
1237
1301
 
@@ -1252,14 +1316,11 @@ export class ProtoArray {
1252
1316
  private validateNodeByIndex(nodeIndex: number): ProtoNode {
1253
1317
  const validNode = this.getNodeFromIndex(nodeIndex);
1254
1318
  if (validNode.executionStatus === ExecutionStatus.Invalid) {
1255
- this.lvhError = {
1319
+ throw new ProtoArrayError({
1320
+ code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1256
1321
  lvhCode: LVHExecErrorCode.InvalidToValid,
1257
1322
  blockRoot: validNode.blockRoot,
1258
1323
  execHash: validNode.executionPayloadBlockHash,
1259
- };
1260
- throw new ProtoArrayError({
1261
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1262
- ...this.lvhError,
1263
1324
  });
1264
1325
  }
1265
1326
 
@@ -1295,6 +1356,15 @@ export class ProtoArray {
1295
1356
 
1296
1357
  // For Gloas: check if from previous slot
1297
1358
  if (node.slot + 1 !== currentSlot) {
1359
+ // During the block's own slot a payload known to not satisfy the inclusion list
1360
+ // constraints ranks below its EMPTY variant, as it will from the next slot on
1361
+ if (
1362
+ node.slot === currentSlot &&
1363
+ node.payloadStatus === PayloadStatus.FULL &&
1364
+ this.payloadInclusionListSatisfaction.get(node.blockRoot) === false
1365
+ ) {
1366
+ return PayloadStatus.PENDING;
1367
+ }
1298
1368
  return node.payloadStatus;
1299
1369
  }
1300
1370
 
@@ -1316,13 +1386,6 @@ export class ProtoArray {
1316
1386
  * For Gloas, may return PENDING/EMPTY/FULL variants.
1317
1387
  */
1318
1388
  findHead(justifiedRoot: RootHex, currentSlot: Slot): ProtoNode {
1319
- if (this.lvhError) {
1320
- throw new ProtoArrayError({
1321
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1322
- ...this.lvhError,
1323
- });
1324
- }
1325
-
1326
1389
  // Get canonical node: FULL for pre-Gloas, PENDING for Gloas
1327
1390
  const justifiedIndex = this.getDefaultNodeIndex(justifiedRoot);
1328
1391
  if (justifiedIndex === undefined) {