@lodestar/fork-choice 1.52.0-dev.0ac7778d70 → 1.52.0-dev.0e16c08e28

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 (40) hide show
  1. package/lib/forkChoice/errors.d.ts +6 -1
  2. package/lib/forkChoice/errors.d.ts.map +1 -1
  3. package/lib/forkChoice/errors.js +1 -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 +5 -6
  10. package/lib/forkChoice/forkChoice.d.ts.map +1 -1
  11. package/lib/forkChoice/forkChoice.js +29 -25
  12. package/lib/forkChoice/forkChoice.js.map +1 -1
  13. package/lib/forkChoice/interface.d.ts +4 -7
  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/protoArray/errors.d.ts +8 -10
  21. package/lib/protoArray/errors.d.ts.map +1 -1
  22. package/lib/protoArray/errors.js +7 -7
  23. package/lib/protoArray/errors.js.map +1 -1
  24. package/lib/protoArray/interface.d.ts +33 -2
  25. package/lib/protoArray/interface.d.ts.map +1 -1
  26. package/lib/protoArray/interface.js +22 -0
  27. package/lib/protoArray/interface.js.map +1 -1
  28. package/lib/protoArray/protoArray.d.ts +20 -22
  29. package/lib/protoArray/protoArray.d.ts.map +1 -1
  30. package/lib/protoArray/protoArray.js +104 -100
  31. package/lib/protoArray/protoArray.js.map +1 -1
  32. package/package.json +8 -8
  33. package/src/forkChoice/errors.ts +3 -1
  34. package/src/forkChoice/fastConfirmation/utils.ts +84 -94
  35. package/src/forkChoice/forkChoice.ts +29 -26
  36. package/src/forkChoice/interface.ts +4 -5
  37. package/src/index.ts +9 -1
  38. package/src/protoArray/errors.ts +8 -5
  39. package/src/protoArray/interface.ts +30 -4
  40. package/src/protoArray/protoArray.ts +106 -110
@@ -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,22 +695,8 @@ export class ForkChoice implements IForkChoice {
693
695
  }
694
696
 
695
697
  // findHead returns the ProtoNode representing the head
696
- let head: ProtoNode;
697
- try {
698
- head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
699
- } catch (e) {
700
- // A poisoned tree never recovers, shut the node down instead of failing every head computation
701
- if (
702
- e instanceof ProtoArrayError &&
703
- (e.type.code === ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE ||
704
- e.type.code === ProtoArrayErrorCode.INVALID_JUSTIFIED_EXECUTION_STATUS)
705
- ) {
706
- this.irrecoverableError = e;
707
- }
708
- throw e;
709
- }
710
-
711
- this.head = head;
698
+ this.head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
699
+ this.updateHeadSlot = currentSlot;
712
700
  return this.head;
713
701
  }
714
702
 
@@ -1163,7 +1151,7 @@ export class ForkChoice implements IForkChoice {
1163
1151
 
1164
1152
  /**
1165
1153
  * Notify fork choice that an execution payload has arrived (Gloas fork)
1166
- * 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
1167
1155
  * Spec: gloas/fork-choice.md#new-on_execution_payload
1168
1156
  */
1169
1157
  onExecutionPayload(
@@ -1187,9 +1175,10 @@ export class ForkChoice implements IForkChoice {
1187
1175
  });
1188
1176
  }
1189
1177
 
1178
+ const currentSlot = this.fcStore.currentSlot;
1190
1179
  this.protoArray.onExecutionPayload(
1191
1180
  blockRoot,
1192
- this.fcStore.currentSlot,
1181
+ currentSlot,
1193
1182
  executionPayloadBlockHash,
1194
1183
  executionPayloadNumber,
1195
1184
  executionPayloadGasLimit,
@@ -1197,6 +1186,11 @@ export class ForkChoice implements IForkChoice {
1197
1186
  executionStatus,
1198
1187
  dataAvailabilityStatus
1199
1188
  );
1189
+ if (currentSlot === this.updateHeadSlot) {
1190
+ this.head = this.protoArray.findHead(this.fcStore.justified.checkpoint.rootHex, currentSlot);
1191
+ } else {
1192
+ this.updateHead();
1193
+ }
1200
1194
  }
1201
1195
 
1202
1196
  /**
@@ -1213,6 +1207,18 @@ export class ForkChoice implements IForkChoice {
1213
1207
  const previousSlot = this.fcStore.currentSlot;
1214
1208
  // Note: we are relying upon `onTick` to update `fcStore.time` to ensure we don't get stuck in a loop.
1215
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
+ }
1216
1222
  this.queuedAttestationsPreviousSlot = 0;
1217
1223
  // Process any attestations that might now be eligible before running FCR for this slot.
1218
1224
  this.processAttestationQueue();
@@ -1633,14 +1639,11 @@ export class ForkChoice implements IForkChoice {
1633
1639
  * justified's status as well as validate the terminal conditions if terminal block
1634
1640
  * becomes valid
1635
1641
  */
1636
- validateLatestHash(execResponse: LVHExecResponse, opts?: {strict?: boolean}): boolean {
1642
+ validateLatestHash(execResponse: LVHExecResponse): LVHVerdictResult {
1637
1643
  try {
1638
- return this.protoArray.validateLatestHash(execResponse, this.fcStore.currentSlot, opts);
1644
+ return this.protoArray.validateLatestHash(execResponse, this.fcStore.currentSlot);
1639
1645
  } catch (e) {
1640
- if (e instanceof ProtoArrayError && e.type.code === ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE) {
1641
- this.irrecoverableError = e;
1642
- }
1643
- return false;
1646
+ return {applied: false, reason: LVHNotAppliedReason.Error, error: e as Error};
1644
1647
  }
1645
1648
  }
1646
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.)
@@ -212,7 +211,7 @@ export interface IForkChoice {
212
211
  ): void;
213
212
  /**
214
213
  * Notify fork choice that an execution payload has arrived (Gloas fork)
215
- * 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
216
215
  *
217
216
  * ## Specification
218
217
  *
@@ -361,9 +360,9 @@ export interface IForkChoice {
361
360
  getCommonAncestorDepth(prevBlock: ProtoBlock, newBlock: ProtoBlock): AncestorResult;
362
361
  /**
363
362
  * Apply an execution engine verdict with a latest valid hash, see `ProtoArray.validateLatestHash`.
364
- * Returns whether any execution status changed. A consensus failure is recorded in `irrecoverableError`.
363
+ * Returns whether any execution status changed, and if not, why.
365
364
  */
366
- validateLatestHash(execResponse: LVHExecResponse, opts?: {strict?: boolean}): boolean;
365
+ validateLatestHash(execResponse: LVHExecResponse): LVHVerdictResult;
367
366
 
368
367
  /**
369
368
  * 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";
@@ -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> {}
@@ -58,16 +58,42 @@ export type LVHValidResponse = {
58
58
  /** Resolves the exact node to validate when several nodes carry the same payload hash (gloas variants) */
59
59
  blockRoot?: RootHex;
60
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
+ }
61
68
  export type LVHInvalidResponse = {
62
69
  executionStatus: ExecutionStatus.Invalid;
63
70
  latestValidExecHash: RootHex | null;
64
- invalidateFromParentBlockRoot: RootHex;
65
- // EL block hash from invalid block's bid (gloas) or payload's parentHash (pre-gloas).
66
- // Disambiguates which variant of the parent (FULL vs EMPTY) to invalidate from.
67
- 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;
68
76
  };
69
77
  export type LVHExecResponse = LVHValidResponse | LVHInvalidResponse;
70
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
+
71
97
  /**
72
98
  * Any execution status that is not definitively invalid.
73
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 {ExecutionStatusTransition, 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 */
@@ -709,8 +711,14 @@ export class ProtoArray {
709
711
  this.propagateValidExecutionStatusByIndex(pendingIndex);
710
712
  }
711
713
 
712
- // Update bestChild for PENDING node (may now prefer FULL over EMPTY)
713
- 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
+ }
714
722
  }
715
723
 
716
724
  /** Count blocks selected as FULL or EMPTY by the supplied head chain in the inclusive slot range. */
@@ -1020,22 +1028,19 @@ export class ProtoArray {
1020
1028
 
1021
1029
  /**
1022
1030
  * Apply an execution engine verdict with a latest valid hash (LVH) to the tree. VALID flips Syncing nodes up to the
1023
- * LVH node. INVALID invalidates the node identified by `invalidateFromParentBlockRoot/Hash` and its ancestors up to
1024
- * the LVH node (exclusive), then every descendant. Returns whether any status changed.
1031
+ * LVH node. INVALID invalidates the node identified by `invalidateFromBlockRoot/Hash` and its ancestors up to
1032
+ * the LVH node (exclusive), then every descendant. Returns whether any status changed, and if not, why.
1025
1033
  *
1026
- * A null or unknown LVH means the engine only vouches for the queried payload being invalid: the queried node and
1027
- * the nodes that inherit that payload (gloas PENDING and EMPTY variants) are invalidated, nothing above them.
1034
+ * A verdict never contradicts what fork choice already holds: a node the engine already resolved is never flipped
1035
+ * and an INVALID never crosses the justified node. The LVH is unusable when it is null, not an ancestor of the from
1036
+ * node, or the walk to it meets such a node.
1028
1037
  *
1029
- * `strict` keeps the consensus failure semantics for verdicts about a payload the engine just processed: a VALID
1030
- * or PreMerge node on the invalidated chain poisons the tree. Verdicts from forkchoiceUpdated or about an ancestor
1031
- * chain are applied with `strict: false`: a node the engine already validated is never invalidated and the justified
1032
- * node is never crossed. If the walk to the LVH meets either, the LVH is treated as unknown.
1038
+ * An unusable LVH leaves only the claim about the judged payload. With `LVHInvalidJudged.FromBlock` that is the from
1039
+ * node: it and the nodes that inherit its payload (gloas PENDING and EMPTY variants) are invalidated, nothing above
1040
+ * them. With `LVHInvalidJudged.ChildPayload` the judged payload is not in the tree and the from node is its parent,
1041
+ * so the verdict is dropped.
1033
1042
  */
1034
- validateLatestHash(
1035
- execResponse: LVHExecResponse,
1036
- currentSlot: Slot,
1037
- {strict = true}: {strict?: boolean} = {}
1038
- ): boolean {
1043
+ validateLatestHash(execResponse: LVHExecResponse, currentSlot: Slot): LVHVerdictResult {
1039
1044
  // Look reverse because its highly likely node with latestValidExecHash is towards the
1040
1045
  // the leaves of the forkchoice
1041
1046
  //
@@ -1065,28 +1070,26 @@ export class ProtoArray {
1065
1070
  // We are trying to be as forgiving as possible here because ideally latestValidHashIndex
1066
1071
  // should be found in the forkchoice
1067
1072
  if (latestValidHashIndex < 0) {
1068
- return false;
1073
+ return {applied: false, reason: LVHNotAppliedReason.UnknownLVH};
1069
1074
  }
1070
1075
  const {executionStatus} = this.nodes[latestValidHashIndex];
1071
1076
  if (executionStatus === ExecutionStatus.Valid || executionStatus === ExecutionStatus.PreMerge) {
1072
- return false;
1077
+ return {applied: false, reason: LVHNotAppliedReason.AlreadyApplied};
1073
1078
  }
1074
- if (!strict) {
1075
- // The walk up flips every Syncing ancestor, a lenient verdict must not contradict an invalidated one
1076
- let nodeIndex: number | undefined = latestValidHashIndex;
1077
- while (nodeIndex !== undefined) {
1078
- const node: ProtoNode = this.nodes[nodeIndex];
1079
- if (node.executionStatus === ExecutionStatus.Valid || node.executionStatus === ExecutionStatus.PreMerge) {
1080
- break;
1081
- }
1082
- if (node.executionStatus === ExecutionStatus.Invalid) {
1083
- return false;
1084
- }
1085
- nodeIndex = node.parent;
1079
+ // The walk up flips every Syncing ancestor, it must not contradict an invalidated one
1080
+ let nodeIndex: number | undefined = latestValidHashIndex;
1081
+ while (nodeIndex !== undefined) {
1082
+ const node: ProtoNode = this.nodes[nodeIndex];
1083
+ if (node.executionStatus === ExecutionStatus.Valid || node.executionStatus === ExecutionStatus.PreMerge) {
1084
+ break;
1086
1085
  }
1086
+ if (node.executionStatus === ExecutionStatus.Invalid) {
1087
+ return {applied: false, reason: LVHNotAppliedReason.Contradiction};
1088
+ }
1089
+ nodeIndex = node.parent;
1087
1090
  }
1088
1091
  this.propagateValidExecutionStatusByIndex(latestValidHashIndex);
1089
- return true;
1092
+ return {applied: true};
1090
1093
  }
1091
1094
 
1092
1095
  // In case of invalidation, ideally:
@@ -1102,64 +1105,72 @@ export class ProtoArray {
1102
1105
  // Mark chain ii) as Invalid if LVH is found and non null, else only invalidate invalid_payload
1103
1106
  // if its in fcU.
1104
1107
  //
1105
- const {invalidateFromParentBlockRoot, invalidateFromParentBlockHash, latestValidExecHash} = execResponse;
1106
- const invalidateFromParentIndex = this.getNodeIndexByRootAndBlockHash(
1107
- invalidateFromParentBlockRoot,
1108
- invalidateFromParentBlockHash
1109
- );
1110
- if (invalidateFromParentIndex === undefined) {
1108
+ const {invalidateFromBlockRoot, invalidateFromBlockHash, latestValidExecHash, judged} = execResponse;
1109
+ const invalidateFromIndex = this.getNodeIndexByRootAndBlockHash(invalidateFromBlockRoot, invalidateFromBlockHash);
1110
+ if (invalidateFromIndex === undefined) {
1111
1111
  throw Error(
1112
- `Unable to find invalidateFromParentBlockRoot=${invalidateFromParentBlockRoot} invalidateFromParentBlockHash=${invalidateFromParentBlockHash} in forkChoice`
1112
+ `Unable to find invalidateFromBlockRoot=${invalidateFromBlockRoot} invalidateFromBlockHash=${invalidateFromBlockHash} in forkChoice`
1113
1113
  );
1114
1114
  }
1115
- if (!strict && this.nodes[invalidateFromParentIndex].executionStatus !== ExecutionStatus.Syncing) {
1116
- return false;
1115
+ const fromStatus = this.nodes[invalidateFromIndex].executionStatus;
1116
+ if (fromStatus !== ExecutionStatus.Syncing) {
1117
+ return {
1118
+ applied: false,
1119
+ reason:
1120
+ fromStatus === ExecutionStatus.Invalid
1121
+ ? LVHNotAppliedReason.AlreadyApplied
1122
+ : LVHNotAppliedReason.Contradiction,
1123
+ };
1117
1124
  }
1118
1125
 
1119
1126
  let latestValidHashIndex =
1120
- latestValidExecHash !== null ? this.getNodeIndexFromLVH(latestValidExecHash, invalidateFromParentIndex) : null;
1127
+ latestValidExecHash !== null ? this.getNodeIndexFromLVH(latestValidExecHash, invalidateFromIndex) : null;
1121
1128
  if (latestValidHashIndex === null) {
1122
- if (strict) {
1123
- // The strict from node is the parent of the rejected payload and may be valid, never guess here
1124
- throw Error(`Unable to find latestValidExecHash=${latestValidExecHash} in the forkchoice`);
1129
+ if (judged === LVHInvalidJudged.ChildPayload) {
1130
+ return {applied: false, reason: LVHNotAppliedReason.UnusableLVH};
1125
1131
  }
1126
- latestValidHashIndex = this.getUnknownLVHIndex(invalidateFromParentIndex);
1127
- }
1128
-
1129
- if (!strict) {
1130
- // Never invalidate the justified block, the EMPTY variant sharing its chain, or anything at or below it in
1131
- // the tree. The justified block's own payload (FULL variant) is not part of the checkpoint
1132
- const justifiedIndex = this.getDefaultNodeIndex(this.justifiedRoot) ?? -1;
1133
- let nodeIndex: number | undefined = invalidateFromParentIndex;
1134
- while (nodeIndex !== undefined && nodeIndex > latestValidHashIndex) {
1135
- const node: ProtoNode = this.nodes[nodeIndex];
1136
- if (
1137
- node.executionStatus !== ExecutionStatus.Syncing ||
1138
- nodeIndex <= justifiedIndex ||
1139
- (node.blockRoot === this.justifiedRoot && node.payloadStatus === PayloadStatus.EMPTY)
1140
- ) {
1141
- // Conflicting LVH: fall back to the unknown LVH bound, but never cross this node
1142
- latestValidHashIndex = Math.max(nodeIndex, this.getUnknownLVHIndex(invalidateFromParentIndex));
1143
- break;
1132
+ latestValidHashIndex = this.getParentPayloadIndex(invalidateFromIndex);
1133
+ }
1134
+
1135
+ // Never invalidate the justified block, the EMPTY variant sharing its chain, or anything at or below it in
1136
+ // the tree. The justified block's own payload (FULL variant) is not part of the checkpoint
1137
+ const justifiedIndex = this.getDefaultNodeIndex(this.justifiedRoot) ?? -1;
1138
+ let nodeIndex: number | undefined = invalidateFromIndex;
1139
+ while (nodeIndex !== undefined && nodeIndex > latestValidHashIndex) {
1140
+ const node: ProtoNode = this.nodes[nodeIndex];
1141
+ const conflict = node.executionStatus !== ExecutionStatus.Syncing;
1142
+ const justified =
1143
+ nodeIndex <= justifiedIndex ||
1144
+ (node.blockRoot === this.justifiedRoot && node.payloadStatus === PayloadStatus.EMPTY);
1145
+ if (conflict || justified) {
1146
+ if (judged === LVHInvalidJudged.FromBlock) {
1147
+ // The LVH is unusable: invalidate only the judged payload, but never cross this node
1148
+ latestValidHashIndex = Math.max(nodeIndex, this.getParentPayloadIndex(invalidateFromIndex));
1149
+ } else if (conflict) {
1150
+ return {applied: false, reason: LVHNotAppliedReason.Contradiction};
1151
+ } else {
1152
+ // The LVH is below the justified node, it still covers everything above it
1153
+ latestValidHashIndex = nodeIndex;
1144
1154
  }
1145
- nodeIndex = node.parent;
1155
+ break;
1146
1156
  }
1157
+ nodeIndex = node.parent;
1147
1158
  }
1148
1159
 
1149
- if (invalidateFromParentIndex <= latestValidHashIndex) {
1150
- return false;
1160
+ if (invalidateFromIndex <= latestValidHashIndex) {
1161
+ return {applied: false, reason: LVHNotAppliedReason.NothingToInvalidate};
1151
1162
  }
1152
1163
 
1153
- this.propagateInValidExecutionStatusByIndex(invalidateFromParentIndex, latestValidHashIndex, currentSlot);
1154
- return true;
1164
+ this.propagateInValidExecutionStatusByIndex(invalidateFromIndex, latestValidHashIndex, currentSlot);
1165
+ return {applied: true};
1155
1166
  }
1156
1167
 
1157
1168
  /**
1158
- * Upper bound (exclusive) for invalidating from `fromIndex` when the engine gave no usable LVH: the parent of the
1159
- * last ancestor that still inherits the queried payload. Pre-gloas this is the parent of `fromIndex`. For a gloas
1160
- * 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.
1161
1172
  */
1162
- private getUnknownLVHIndex(fromIndex: number): number {
1173
+ private getParentPayloadIndex(fromIndex: number): number {
1163
1174
  const payloadBlockHash = this.nodes[fromIndex].executionPayloadBlockHash;
1164
1175
  let nodeIndex = fromIndex;
1165
1176
  let parentIndex = this.nodes[nodeIndex].parent;
@@ -1193,19 +1204,23 @@ export class ProtoArray {
1193
1204
  }
1194
1205
 
1195
1206
  /**
1196
- * Gloas PENDING and EMPTY variants have no payload of their own, they inherit the execution status of
1197
- * the payload they build on, which is their `executionPayloadBlockHash`. Once that payload is VALID, all
1198
- * of them are, not only the ones on the chain the validation walked up (e.g. siblings, or blocks
1199
- * 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.
1200
1212
  */
1201
1213
  private validatePayloadDependents(payloadHashes: Set<RootHex>): void {
1202
1214
  for (let nodeIndex = 0; nodeIndex < this.nodes.length; nodeIndex++) {
1203
1215
  const node = this.nodes[nodeIndex];
1216
+ const parentStatus = node.parent !== undefined ? this.nodes[node.parent].executionStatus : undefined;
1204
1217
  if (
1205
- node.payloadStatus === PayloadStatus.PENDING &&
1206
1218
  node.executionStatus === ExecutionStatus.Syncing &&
1207
1219
  node.executionPayloadBlockHash !== null &&
1208
- payloadHashes.has(node.executionPayloadBlockHash)
1220
+ payloadHashes.has(node.executionPayloadBlockHash) &&
1221
+ (parentStatus === undefined ||
1222
+ parentStatus === ExecutionStatus.Valid ||
1223
+ parentStatus === ExecutionStatus.PreMerge)
1209
1224
  ) {
1210
1225
  // Also flips the sibling EMPTY variant
1211
1226
  this.validateNodeByIndex(nodeIndex);
@@ -1224,12 +1239,12 @@ export class ProtoArray {
1224
1239
  */
1225
1240
 
1226
1241
  private propagateInValidExecutionStatusByIndex(
1227
- invalidateFromParentIndex: number,
1242
+ invalidateFromIndex: number,
1228
1243
  latestValidHashIndex: number,
1229
1244
  currentSlot: Slot
1230
1245
  ): void {
1231
- // Pass 1: mark invalidateFromParentIndex and its parents invalid
1232
- let invalidateIndex: number | undefined = invalidateFromParentIndex;
1246
+ // Pass 1: mark invalidateFromIndex and its parents invalid
1247
+ let invalidateIndex: number | undefined = invalidateFromIndex;
1233
1248
  while (invalidateIndex !== undefined && invalidateIndex > latestValidHashIndex) {
1234
1249
  const invalidNode = this.invalidateNodeByIndex(invalidateIndex);
1235
1250
  invalidateIndex = invalidNode.parent;
@@ -1278,28 +1293,19 @@ export class ProtoArray {
1278
1293
  private invalidateNodeByIndex(nodeIndex: number): ProtoNode {
1279
1294
  const invalidNode = this.getNodeFromIndex(nodeIndex);
1280
1295
 
1281
- // If node to be invalidated is pre-merge or valid,it is a catastrophe,
1282
- // and indicates consensus failure and a non recoverable damage.
1283
- //
1284
- // There is no further processing that can be done.
1285
- // Just assign error for marking proto-array perma damaged and throw!
1296
+ // validateLatestHash never starts an invalidation that reaches a pre-merge or valid node
1286
1297
  if (
1287
1298
  invalidNode.executionStatus === ExecutionStatus.Valid ||
1288
1299
  invalidNode.executionStatus === ExecutionStatus.PreMerge
1289
1300
  ) {
1290
- const lvhCode =
1291
- invalidNode.executionStatus === ExecutionStatus.Valid
1292
- ? LVHExecErrorCode.ValidToInvalid
1293
- : LVHExecErrorCode.PreMergeToInvalid;
1294
-
1295
- this.lvhError = {
1296
- lvhCode,
1301
+ throw new ProtoArrayError({
1302
+ code: ProtoArrayErrorCode.INVALID_EXECUTION_STATUS_TRANSITION,
1303
+ transition:
1304
+ invalidNode.executionStatus === ExecutionStatus.Valid
1305
+ ? ExecutionStatusTransition.ValidToInvalid
1306
+ : ExecutionStatusTransition.PreMergeToInvalid,
1297
1307
  blockRoot: invalidNode.blockRoot,
1298
1308
  execHash: invalidNode.executionPayloadBlockHash ?? ZERO_HASH_HEX,
1299
- };
1300
- throw new ProtoArrayError({
1301
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1302
- ...this.lvhError,
1303
1309
  });
1304
1310
  }
1305
1311
 
@@ -1320,14 +1326,11 @@ export class ProtoArray {
1320
1326
  private validateNodeByIndex(nodeIndex: number): ProtoNode {
1321
1327
  const validNode = this.getNodeFromIndex(nodeIndex);
1322
1328
  if (validNode.executionStatus === ExecutionStatus.Invalid) {
1323
- this.lvhError = {
1324
- lvhCode: LVHExecErrorCode.InvalidToValid,
1329
+ throw new ProtoArrayError({
1330
+ code: ProtoArrayErrorCode.INVALID_EXECUTION_STATUS_TRANSITION,
1331
+ transition: ExecutionStatusTransition.InvalidToValid,
1325
1332
  blockRoot: validNode.blockRoot,
1326
1333
  execHash: validNode.executionPayloadBlockHash,
1327
- };
1328
- throw new ProtoArrayError({
1329
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1330
- ...this.lvhError,
1331
1334
  });
1332
1335
  }
1333
1336
 
@@ -1393,13 +1396,6 @@ export class ProtoArray {
1393
1396
  * For Gloas, may return PENDING/EMPTY/FULL variants.
1394
1397
  */
1395
1398
  findHead(justifiedRoot: RootHex, currentSlot: Slot): ProtoNode {
1396
- if (this.lvhError) {
1397
- throw new ProtoArrayError({
1398
- code: ProtoArrayErrorCode.INVALID_LVH_EXECUTION_RESPONSE,
1399
- ...this.lvhError,
1400
- });
1401
- }
1402
-
1403
1399
  // Get canonical node: FULL for pre-Gloas, PENDING for Gloas
1404
1400
  const justifiedIndex = this.getDefaultNodeIndex(justifiedRoot);
1405
1401
  if (justifiedIndex === undefined) {