@lodestar/beacon-node 1.52.0-dev.5745da1108 → 1.52.0-dev.643dd3c5bf

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 (130) hide show
  1. package/lib/api/impl/validator/index.d.ts.map +1 -1
  2. package/lib/api/impl/validator/index.js +2 -4
  3. package/lib/api/impl/validator/index.js.map +1 -1
  4. package/lib/chain/archiveStore/utils/archiveBlocks.js +1 -1
  5. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  6. package/lib/chain/chain.d.ts.map +1 -1
  7. package/lib/chain/chain.js +9 -5
  8. package/lib/chain/chain.js.map +1 -1
  9. package/lib/chain/errors/executionPayloadBid.d.ts +6 -1
  10. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  11. package/lib/chain/errors/executionPayloadBid.js +1 -0
  12. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  13. package/lib/chain/errors/executionPayloadEnvelope.d.ts +7 -0
  14. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  15. package/lib/chain/errors/executionPayloadEnvelope.js +1 -0
  16. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  17. package/lib/chain/prepareNextSlot.d.ts +45 -0
  18. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  19. package/lib/chain/prepareNextSlot.js +265 -69
  20. package/lib/chain/prepareNextSlot.js.map +1 -1
  21. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  22. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  23. package/lib/chain/produceBlock/produceBlockBody.js +23 -15
  24. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  25. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  26. package/lib/chain/validation/executionPayloadBid.js +17 -2
  27. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  28. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  29. package/lib/chain/validation/executionPayloadEnvelope.js +21 -5
  30. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  31. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  32. package/lib/chain/validation/voluntaryExit.js +39 -6
  33. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  34. package/lib/execution/engine/blockHash.d.ts +12 -0
  35. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  36. package/lib/execution/engine/blockHash.js +17 -0
  37. package/lib/execution/engine/blockHash.js.map +1 -0
  38. package/lib/execution/engine/mock.d.ts.map +1 -1
  39. package/lib/execution/engine/mock.js +6 -6
  40. package/lib/execution/engine/mock.js.map +1 -1
  41. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  42. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  43. package/lib/execution/engine/payloadIdCache.js +7 -2
  44. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  45. package/lib/metrics/metrics/beacon.d.ts +5 -0
  46. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  47. package/lib/metrics/metrics/beacon.js +5 -0
  48. package/lib/metrics/metrics/beacon.js.map +1 -1
  49. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  50. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  51. package/lib/metrics/metrics/lodestar.js +5 -0
  52. package/lib/metrics/metrics/lodestar.js.map +1 -1
  53. package/lib/network/core/events.d.ts +6 -2
  54. package/lib/network/core/events.d.ts.map +1 -1
  55. package/lib/network/core/events.js +9 -0
  56. package/lib/network/core/events.js.map +1 -1
  57. package/lib/network/core/networkCoreWorkerHandler.d.ts.map +1 -1
  58. package/lib/network/core/networkCoreWorkerHandler.js +3 -2
  59. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  60. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  61. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  62. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  63. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  64. package/lib/sync/range/batch.d.ts +4 -0
  65. package/lib/sync/range/batch.d.ts.map +1 -1
  66. package/lib/sync/range/batch.js +12 -0
  67. package/lib/sync/range/batch.js.map +1 -1
  68. package/lib/sync/range/chain.d.ts +17 -2
  69. package/lib/sync/range/chain.d.ts.map +1 -1
  70. package/lib/sync/range/chain.js +52 -19
  71. package/lib/sync/range/chain.js.map +1 -1
  72. package/lib/sync/range/range.d.ts.map +1 -1
  73. package/lib/sync/range/range.js +1 -0
  74. package/lib/sync/range/range.js.map +1 -1
  75. package/lib/sync/range/utils/batches.d.ts +20 -4
  76. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  77. package/lib/sync/range/utils/batches.js +31 -13
  78. package/lib/sync/range/utils/batches.js.map +1 -1
  79. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  80. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  81. package/lib/sync/range/utils/peerBalancer.js +5 -2
  82. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  83. package/lib/sync/types.d.ts +2 -0
  84. package/lib/sync/types.d.ts.map +1 -1
  85. package/lib/sync/types.js.map +1 -1
  86. package/lib/sync/unknownBlock.d.ts.map +1 -1
  87. package/lib/sync/unknownBlock.js +60 -19
  88. package/lib/sync/unknownBlock.js.map +1 -1
  89. package/lib/sync/utils/downloadByRange.d.ts +8 -0
  90. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  91. package/lib/sync/utils/downloadByRange.js +43 -23
  92. package/lib/sync/utils/downloadByRange.js.map +1 -1
  93. package/lib/util/asyncIterableToEvents.d.ts +20 -3
  94. package/lib/util/asyncIterableToEvents.d.ts.map +1 -1
  95. package/lib/util/asyncIterableToEvents.js +76 -20
  96. package/lib/util/asyncIterableToEvents.js.map +1 -1
  97. package/lib/util/dataColumns.d.ts +1 -1
  98. package/lib/util/dataColumns.d.ts.map +1 -1
  99. package/lib/util/dataColumns.js +4 -1
  100. package/lib/util/dataColumns.js.map +1 -1
  101. package/package.json +17 -17
  102. package/src/api/impl/validator/index.ts +2 -4
  103. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  104. package/src/chain/chain.ts +9 -5
  105. package/src/chain/errors/executionPayloadBid.ts +6 -0
  106. package/src/chain/errors/executionPayloadEnvelope.ts +8 -0
  107. package/src/chain/prepareNextSlot.ts +347 -89
  108. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  109. package/src/chain/validation/executionPayloadBid.ts +20 -2
  110. package/src/chain/validation/executionPayloadEnvelope.ts +28 -5
  111. package/src/chain/validation/voluntaryExit.ts +44 -6
  112. package/src/execution/engine/blockHash.ts +27 -0
  113. package/src/execution/engine/mock.ts +13 -8
  114. package/src/execution/engine/payloadIdCache.ts +12 -4
  115. package/src/metrics/metrics/beacon.ts +9 -0
  116. package/src/metrics/metrics/lodestar.ts +5 -0
  117. package/src/network/core/events.ts +12 -0
  118. package/src/network/core/networkCoreWorkerHandler.ts +6 -2
  119. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  120. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  121. package/src/sync/range/batch.ts +13 -0
  122. package/src/sync/range/chain.ts +64 -17
  123. package/src/sync/range/range.ts +1 -0
  124. package/src/sync/range/utils/batches.ts +38 -13
  125. package/src/sync/range/utils/peerBalancer.ts +4 -1
  126. package/src/sync/types.ts +2 -0
  127. package/src/sync/unknownBlock.ts +65 -21
  128. package/src/sync/utils/downloadByRange.ts +60 -26
  129. package/src/util/asyncIterableToEvents.ts +100 -21
  130. package/src/util/dataColumns.ts +4 -1
@@ -132,8 +132,6 @@ const BLOCK_PRODUCTION_RACE_CUTOFF_BPS = 1667;
132
132
  * TODO GLOAS: revisit, the block propagates faster as it only commits to a bid and the attestation deadline changed
133
133
  */
134
134
  export const BLOCK_PRODUCTION_RACE_CUTOFF_GLOAS_BPS = 1667;
135
- /** Rejection message of the bid block branch when there is no viable bid to commit to */
136
- const NO_BID_AVAILABLE = "No builder bid available";
137
135
 
138
136
  type BidCandidate = {
139
137
  signedBid: gloas.SignedExecutionPayloadBid;
@@ -1156,7 +1154,7 @@ export function getValidatorApi(
1156
1154
  });
1157
1155
  const bidBlockPromise: ReturnType<typeof chain.produceBlock> = bestBidPromise.then((candidate) => {
1158
1156
  if (candidate === null) {
1159
- throw new Error(NO_BID_AVAILABLE);
1157
+ throw new NoBidReceived();
1160
1158
  }
1161
1159
  metrics?.blockProductionRequests.inc({source: ProducedBlockSource.builder});
1162
1160
  return timed(ProducedBlockSource.builder, () =>
@@ -1270,7 +1268,7 @@ export function getValidatorApi(
1270
1268
  source = ProducedBlockSource.engine;
1271
1269
  bestResult = engineResult;
1272
1270
  const reason =
1273
- bidBlockResult.status === "rejected" && (bidBlockResult.reason as Error).message === NO_BID_AVAILABLE
1271
+ bidBlockResult.status === "rejected" && bidBlockResult.reason instanceof NoBidReceived
1274
1272
  ? EngineBlockSelectionReason.BuilderNoBid
1275
1273
  : bidBlockResult.status === "pending"
1276
1274
  ? EngineBlockSelectionReason.BuilderPending
@@ -284,7 +284,7 @@ export async function archiveBlocks(
284
284
  }
285
285
 
286
286
  // Delete expired data column sidecars
287
- // Keep only `[min(compute_blob_data_retention_start_epoch(current_epoch), current_epoch - archiveDataEpochs)]`
287
+ // Keep only `[current_epoch - max(MIN_EPOCHS_FOR_DATA_COLUMN_SIDECARS_REQUESTS, archiveDataEpochs)]`
288
288
  if (finalizedPostFulu) {
289
289
  if (archiveDataEpochs !== Infinity) {
290
290
  const dataColumnSidecarsMinEpoch = getDataColumnSidecarsMinEpoch(config, currentEpoch, archiveDataEpochs);
@@ -896,16 +896,18 @@ export class BeaconChain implements IBeaconChain {
896
896
  ): Promise<{block: SignedBeaconBlock; executionOptimistic: boolean; finalized: boolean} | null> {
897
897
  const block = this.forkChoice.getBlockHexDefaultStatus(root);
898
898
  if (block) {
899
+ // The finalized block stays in fork-choice and the hot db until the archiver has migrated it
900
+ const finalized = block.slot <= this.forkChoice.getFinalizedBlock().slot;
899
901
  // Block found in fork-choice.
900
902
  // It may be in the block input cache, awaiting full DA reconstruction, check there first
901
903
  // Otherwise (most likely), check the hot db
902
904
  const blockInput = this.seenBlockInputCache.get(block.blockRoot);
903
905
  if (blockInput?.hasBlock()) {
904
- return {block: blockInput.getBlock(), executionOptimistic: isOptimisticBlock(block), finalized: false};
906
+ return {block: blockInput.getBlock(), executionOptimistic: isOptimisticBlock(block), finalized};
905
907
  }
906
908
  const data = await this.db.block.get(fromHex(root));
907
909
  if (data) {
908
- return {block: data, executionOptimistic: isOptimisticBlock(block), finalized: false};
910
+ return {block: data, executionOptimistic: isOptimisticBlock(block), finalized};
909
911
  }
910
912
  // If block is not found in hot db, try cold db since there could be an archive cycle happening
911
913
  // TODO: Add a lock to the archiver to have deterministic behavior on where are blocks
@@ -920,6 +922,8 @@ export class BeaconChain implements IBeaconChain {
920
922
  ): Promise<{block: Uint8Array; executionOptimistic: boolean; finalized: boolean; slot: Slot} | null> {
921
923
  const block = this.forkChoice.getBlockHexDefaultStatus(root);
922
924
  if (block) {
925
+ // The finalized block stays in fork-choice and the hot db until the archiver has migrated it
926
+ const finalized = block.slot <= this.forkChoice.getFinalizedBlock().slot;
923
927
  // Block found in fork-choice.
924
928
  // It may be in the block input cache, awaiting full DA reconstruction, check there first
925
929
  // Otherwise (most likely), check the hot db
@@ -931,14 +935,14 @@ export class BeaconChain implements IBeaconChain {
931
935
  return {
932
936
  block: serialized,
933
937
  executionOptimistic: isOptimisticBlock(block),
934
- finalized: false,
938
+ finalized,
935
939
  slot: blockInput.slot,
936
940
  };
937
941
  }
938
942
  return {
939
943
  block: sszTypesFor(blockInput.forkName).SignedBeaconBlock.serialize(signedBlock),
940
944
  executionOptimistic: isOptimisticBlock(block),
941
- finalized: false,
945
+ finalized,
942
946
  slot: blockInput.slot,
943
947
  };
944
948
  }
@@ -946,7 +950,7 @@ export class BeaconChain implements IBeaconChain {
946
950
  if (data) {
947
951
  const slot = getSlotFromSignedBeaconBlockSerialized(data);
948
952
  if (slot === null) throw new Error(`Invalid block data stored in DB for root: ${root}`);
949
- return {block: data, executionOptimistic: isOptimisticBlock(block), finalized: false, slot};
953
+ return {block: data, executionOptimistic: isOptimisticBlock(block), finalized, slot};
950
954
  }
951
955
  // If block is not found in hot db, try cold db since there could be an archive cycle happening
952
956
  // TODO: Add a lock to the archiver to have deterministic behavior on where are blocks
@@ -23,6 +23,7 @@ export enum ExecutionPayloadBidErrorCode {
23
23
  PROPOSER_PREFERENCES_GAS_LIMIT_MISMATCH = "EXECUTION_PAYLOAD_BID_ERROR_PROPOSER_PREFERENCES_GAS_LIMIT_MISMATCH",
24
24
  INCLUSION_LIST_BITS_NOT_INCLUSIVE = "EXECUTION_PAYLOAD_BID_ERROR_INCLUSION_LIST_BITS_NOT_INCLUSIVE",
25
25
  BEFORE_INCLUSION_LIST_DEADLINE = "EXECUTION_PAYLOAD_BID_ERROR_BEFORE_INCLUSION_LIST_DEADLINE",
26
+ BEFORE_PAYLOAD_ATTESTATION_DEADLINE = "EXECUTION_PAYLOAD_BID_ERROR_BEFORE_PAYLOAD_ATTESTATION_DEADLINE",
26
27
  }
27
28
 
28
29
  export type ExecutionPayloadBidErrorType =
@@ -99,6 +100,11 @@ export type ExecutionPayloadBidErrorType =
99
100
  builderIndex: BuilderIndex;
100
101
  slot: Slot;
101
102
  }
103
+ | {
104
+ code: ExecutionPayloadBidErrorCode.BEFORE_PAYLOAD_ATTESTATION_DEADLINE;
105
+ builderIndex: BuilderIndex;
106
+ slot: Slot;
107
+ }
102
108
  | {
103
109
  code: ExecutionPayloadBidErrorCode.PROPOSER_PREFERENCES_GAS_LIMIT_MISMATCH;
104
110
  builderIndex: BuilderIndex;
@@ -20,6 +20,7 @@ export enum ExecutionPayloadEnvelopeErrorCode {
20
20
  INCORRECT_TIMESTAMP = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_INCORRECT_TIMESTAMP",
21
21
  EMPTY_TRANSACTION = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_EMPTY_TRANSACTION",
22
22
  WITHDRAWALS_MISMATCH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_WITHDRAWALS_MISMATCH",
23
+ INVALID_BLOCK_HASH = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_INVALID_BLOCK_HASH",
23
24
  INVALID_SIGNATURE = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_INVALID_SIGNATURE",
24
25
  PAYLOAD_ENVELOPE_INPUT_MISSING = "EXECUTION_PAYLOAD_ENVELOPE_ERROR_PAYLOAD_ENVELOPE_INPUT_MISSING",
25
26
  }
@@ -112,6 +113,13 @@ export type ExecutionPayloadEnvelopeErrorType =
112
113
  envelopeWithdrawalsRoot: RootHex;
113
114
  expectedWithdrawalsRoot: RootHex;
114
115
  }
116
+ | {
117
+ code: ExecutionPayloadEnvelopeErrorCode.INVALID_BLOCK_HASH;
118
+ slot: Slot;
119
+ root: RootHex;
120
+ blockHash: RootHex;
121
+ computedBlockHash: RootHex;
122
+ }
115
123
  | {code: ExecutionPayloadEnvelopeErrorCode.INVALID_SIGNATURE; slot: Slot; root: RootHex}
116
124
  | {code: ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING; blockRoot: RootHex};
117
125
 
@@ -1,7 +1,14 @@
1
1
  import {routes} from "@lodestar/api";
2
2
  import {ChainForkConfig} from "@lodestar/config";
3
- import {getFinalizedExecutionBlockHash, getSafeExecutionBlockHash} from "@lodestar/fork-choice";
4
3
  import {
4
+ ProtoBlock,
5
+ PtcQuorumEvent,
6
+ getFinalizedExecutionBlockHash,
7
+ getPtcVerdict,
8
+ getSafeExecutionBlockHash,
9
+ } from "@lodestar/fork-choice";
10
+ import {
11
+ ForkName,
5
12
  ForkPostBellatrix,
6
13
  ForkSeq,
7
14
  SLOTS_PER_EPOCH,
@@ -21,7 +28,7 @@ import {
21
28
  isStatePostFulu,
22
29
  isStatePostGloas,
23
30
  } from "@lodestar/state-transition";
24
- import {Bytes32, Slot, ValidatorIndex} from "@lodestar/types";
31
+ import {Bytes32, RootHex, Slot, ValidatorIndex} from "@lodestar/types";
25
32
  import {Logger, fromHex, isErrorAborted, sleep, toHex} from "@lodestar/utils";
26
33
  import {GENESIS_SLOT} from "../constants/constants.js";
27
34
  import {BuilderStatus} from "../execution/builder/http.js";
@@ -29,6 +36,7 @@ import {PayloadAttributes} from "../execution/index.js";
29
36
  import {Metrics} from "../metrics/index.js";
30
37
  import {ClockEvent} from "../util/clock.js";
31
38
  import {isQueueErrorAborted} from "../util/queue/index.js";
39
+ import {ChainEvent} from "./emitter.js";
32
40
  import {ForkchoiceCaller} from "./forkChoice/index.js";
33
41
  import {IBeaconChain} from "./interface.js";
34
42
  import {
@@ -38,8 +46,13 @@ import {
38
46
  } from "./produceBlock/produceBlockBody.js";
39
47
  import {RegenCaller} from "./regen/index.js";
40
48
 
41
- // TODO GLOAS: re-evaluate this timing
42
- /* With 12s slot times, this scheduler will run 4s before the start of each slot (`12 - 0.6667 * 12 = 4`). */
49
+ /**
50
+ * With 12s slot times, this scheduler will run 4s before the start of each slot (`12 - 0.6667 * 12 = 4`).
51
+ *
52
+ * Post-Gloas this is after the payload deadline (50% of the slot), so the parent's payload has normally been
53
+ * imported, and before the PTC deadline (75%). The parent choice is revisited when the PTC verdict or a timely
54
+ * payload comes in after the scheduled run, see `reprepare`.
55
+ */
43
56
  export const PREPARE_NEXT_SLOT_BPS = 6667;
44
57
 
45
58
  /* We don't want to do more epoch transition than this */
@@ -58,6 +71,28 @@ const BUILDER_PREVERIFY_LIMIT_BPS = 2000;
58
71
  */
59
72
  const BUILDER_STATUS_CHECK_BEFORE_SLOT_BPS = 1667;
60
73
 
74
+ export enum PreparePayloadReason {
75
+ /** The scheduled run at PREPARE_NEXT_SLOT_BPS of the slot */
76
+ scheduled = "scheduled",
77
+ /** The PTC reached a verdict on the payload of the current slot's block */
78
+ ptcQuorum = "ptc_quorum",
79
+ /** A timely payload of the current slot's block was imported after the scheduled run */
80
+ payloadImported = "payload_imported",
81
+ }
82
+
83
+ /** Inputs the payload for `prepareSlot` was last prepared with, a re-prepare with the same inputs is skipped */
84
+ type PreparedPayload = {
85
+ prepareSlot: Slot;
86
+ proposerIndex: ValidatorIndex;
87
+ headRoot: RootHex;
88
+ /** Whether the payload builds on the parent's full payload or its empty variant, `null` pre-Gloas */
89
+ buildOnFull: boolean | null;
90
+ /** `undefined` if the proposer is not ours, only the payload attributes event was emitted */
91
+ feeRecipient: string | undefined;
92
+ /** The forkchoiceUpdated failed, so a re-prepare retries it even with unchanged inputs */
93
+ failed: boolean;
94
+ };
95
+
61
96
  /**
62
97
  * At Bellatrix, if we are responsible for proposing in next slot, we want to prepare payload
63
98
  * 4s before the start of next slot at PREPARE_NEXT_SLOT_BPS of the current slot.
@@ -70,6 +105,11 @@ const BUILDER_STATUS_CHECK_BEFORE_SLOT_BPS = 1667;
70
105
  *
71
106
  */
72
107
  export class PrepareNextSlotScheduler {
108
+ private lastPrepared: PreparedPayload | null = null;
109
+ /** Slot a payload preparation is in flight for, a re-prepare requested meanwhile runs after it */
110
+ private preparingSlot: Slot | null = null;
111
+ private queuedReason: PreparePayloadReason | null = null;
112
+
73
113
  constructor(
74
114
  private readonly chain: IBeaconChain,
75
115
  private readonly config: ChainForkConfig,
@@ -78,10 +118,14 @@ export class PrepareNextSlotScheduler {
78
118
  private readonly signal: AbortSignal
79
119
  ) {
80
120
  this.chain.clock.on(ClockEvent.slot, this.prepareForNextSlot);
121
+ this.chain.emitter.on(ChainEvent.forkChoicePtcQuorum, this.onPtcQuorum);
122
+ this.chain.emitter.on(routes.events.EventType.executionPayload, this.onExecutionPayloadImported);
81
123
  this.signal.addEventListener(
82
124
  "abort",
83
125
  () => {
84
126
  this.chain.clock.off(ClockEvent.slot, this.prepareForNextSlot);
127
+ this.chain.emitter.off(ChainEvent.forkChoicePtcQuorum, this.onPtcQuorum);
128
+ this.chain.emitter.off(routes.events.EventType.executionPayload, this.onExecutionPayloadImported);
85
129
  },
86
130
  {once: true}
87
131
  );
@@ -109,6 +153,10 @@ export class PrepareNextSlotScheduler {
109
153
  // or precompute epoch transition
110
154
  await sleep(this.config.getSlotComponentDurationMs(currentFork, PREPARE_NEXT_SLOT_BPS), this.signal);
111
155
 
156
+ // Re-prepare requests from here on are queued until this run is done. Earlier ones are
157
+ // dropped, the head computed below already reflects them.
158
+ this.preparingSlot = prepareSlot;
159
+
112
160
  // calling updateHead() here before we produce a block to reduce reorg possibility
113
161
  const headBlock = this.chain.recomputeForkChoiceHead(ForkchoiceCaller.prepareNextSlot);
114
162
  const {slot: headSlot, blockRoot: headRoot} = headBlock;
@@ -163,15 +211,7 @@ export class PrepareNextSlotScheduler {
163
211
  };
164
212
 
165
213
  const proposerIndex = await getProposerIndex();
166
- if (this.chain.beaconProposerCache.has(proposerIndex)) {
167
- const pooledPreferences = isForkPostGloas(fork)
168
- ? getPooledProposerPreferences(this.chain, prepareSlot, headRoot)
169
- : null;
170
- feeRecipient =
171
- pooledPreferences !== null
172
- ? toHex(pooledPreferences.feeRecipient)
173
- : this.chain.beaconProposerCache.getOrDefault(proposerIndex);
174
- }
214
+ feeRecipient = this.getFeeRecipient(fork, prepareSlot, headRoot, proposerIndex);
175
215
 
176
216
  // Predict the proposer head of the next slot when either:
177
217
  // - we are proposing the next slot (single-slot proposer-boost-reorg), or
@@ -231,82 +271,15 @@ export class PrepareNextSlotScheduler {
231
271
  );
232
272
  }
233
273
 
234
- if (!isStatePostBellatrix(preparedState)) {
235
- throw new Error("Expected Bellatrix state for payload attributes");
236
- }
237
-
238
- let parentBlockHash: Bytes32;
239
- // Apply parent payload once here as it's reused by EL prep and SSE emit below
240
- let stateAfterParentPayload: IBeaconStateViewBellatrix = preparedState;
241
- if (isStatePostGloas(preparedState)) {
242
- // Spec: should_build_on_full(store, head, slot) - see produceBlockBody.ts for context.
243
- if (this.chain.forkChoice.shouldBuildOnFull(updatedHead, prepareSlot)) {
244
- parentBlockHash = preparedState.latestExecutionPayloadBid.blockHash;
245
- // Skip applying parent payload unless we're proposing the next slot or have to emit payload_attributes events
246
- if (feeRecipient !== undefined || this.chain.opts.emitPayloadAttributes === true) {
247
- const parentExecutionRequests = await this.chain.getParentExecutionRequests(
248
- updatedHead.slot,
249
- updatedHead.blockRoot
250
- );
251
- stateAfterParentPayload = preparedState.withParentPayloadApplied(parentExecutionRequests);
252
- }
253
- } else {
254
- parentBlockHash = preparedState.latestExecutionPayloadBid.parentBlockHash;
255
- }
256
- } else {
257
- parentBlockHash = preparedState.latestExecutionPayloadHeader.blockHash;
258
- }
259
-
260
- // The payload_attributes event must carry the same hashes we send to the EL
261
- const safeBlockHash = getSafeExecutionBlockHash(this.chain.forkChoice, this.logger);
262
- const finalizedBlockHash = getFinalizedExecutionBlockHash(this.chain.forkChoice);
263
-
264
- let payloadAttributes: PayloadAttributes | undefined;
265
- // If emitPayloadAttributes is true emit a SSE payloadAttributes event for
266
- // every slot. Without the flag, only emit the event if we are proposing in the next slot.
267
- if (
268
- (feeRecipient || this.chain.opts.emitPayloadAttributes === true) &&
269
- this.chain.emitter.listenerCount(routes.events.EventType.payloadAttributes)
270
- ) {
271
- const data = getPayloadAttributesForSSE(fork as ForkPostBellatrix, this.chain, {
272
- prepareState: stateAfterParentPayload,
273
- prepareSlot,
274
- parentBlockRoot: fromHex(updatedHead.blockRoot),
275
- parentBlockHash,
276
- safeBlockHash,
277
- finalizedBlockHash,
278
- feeRecipient: feeRecipient ?? "0x0000000000000000000000000000000000000000",
279
- });
280
- this.chain.emitter.emit(routes.events.EventType.payloadAttributes, {data, version: fork});
281
- payloadAttributes = data.payloadAttributes;
282
- }
283
-
284
- if (feeRecipient) {
285
- const preparationTime =
286
- computeTimeAtSlot(this.config, prepareSlot, this.chain.genesisTime) - Date.now() / 1000;
287
- this.metrics?.blockPayload.payloadAdvancePrepTime.observe(preparationTime);
288
-
289
- // awaiting here instead of throwing an async call because there is no other task
290
- // left for scheduler and this gives nice semantics to catch and log errors in the
291
- // try/catch wrapper here.
292
- await prepareExecutionPayload(
293
- this.chain,
294
- this.logger,
295
- fork as ForkPostBellatrix, // State is of execution type
296
- fromHex(updatedHead.blockRoot),
297
- parentBlockHash,
298
- safeBlockHash,
299
- finalizedBlockHash,
300
- stateAfterParentPayload,
301
- feeRecipient,
302
- payloadAttributes
303
- );
304
- this.logger.verbose("PrepareNextSlotScheduler prepared new payload", {
305
- prepareSlot,
306
- proposerIndex,
307
- feeRecipient,
308
- });
309
- }
274
+ await this.preparePayload({
275
+ reason: PreparePayloadReason.scheduled,
276
+ fork: fork as ForkPostBellatrix,
277
+ prepareSlot,
278
+ proposerIndex,
279
+ feeRecipient,
280
+ head: updatedHead,
281
+ state: preparedState,
282
+ });
310
283
 
311
284
  this.computeStateHashTreeRoot(preparedState, isEpochTransition);
312
285
  } else {
@@ -416,9 +389,294 @@ export class PrepareNextSlotScheduler {
416
389
  this.metrics?.precomputeNextEpochTransition.count.inc({result: "error"}, 1);
417
390
  this.logger.error("Failed to run prepareForNextSlot", {nextEpoch, isEpochTransition, prepareSlot}, e as Error);
418
391
  }
392
+ } finally {
393
+ this.finishRun(prepareSlot);
419
394
  }
420
395
  };
421
396
 
397
+ /**
398
+ * Choose the parent the payload for `prepareSlot` builds on, emit the payload attributes and ask the engine
399
+ * to build the payload. Records the inputs so a later `reprepare` can skip an unchanged result.
400
+ */
401
+ private async preparePayload({
402
+ reason,
403
+ fork,
404
+ prepareSlot,
405
+ proposerIndex,
406
+ feeRecipient,
407
+ head,
408
+ state,
409
+ }: {
410
+ reason: PreparePayloadReason;
411
+ fork: ForkPostBellatrix;
412
+ prepareSlot: Slot;
413
+ proposerIndex: ValidatorIndex;
414
+ feeRecipient: string | undefined;
415
+ head: ProtoBlock;
416
+ state: IBeaconStateView;
417
+ }): Promise<void> {
418
+ if (!isStatePostBellatrix(state)) {
419
+ throw new Error("Expected Bellatrix state for payload attributes");
420
+ }
421
+
422
+ let parentBlockHash: Bytes32;
423
+ let buildOnFull: boolean | null = null;
424
+ // Apply parent payload once here as it's reused by EL prep and SSE emit below
425
+ let stateAfterParentPayload: IBeaconStateViewBellatrix = state;
426
+ if (isStatePostGloas(state)) {
427
+ // Spec: should_build_on_full(store, head, slot) - see produceBlockBody.ts for context.
428
+ buildOnFull = this.chain.forkChoice.shouldBuildOnFull(head, prepareSlot);
429
+ if (buildOnFull) {
430
+ parentBlockHash = state.latestExecutionPayloadBid.blockHash;
431
+ // Skip applying parent payload unless we're proposing the next slot or have to emit payload_attributes events
432
+ if (feeRecipient !== undefined || this.chain.opts.emitPayloadAttributes === true) {
433
+ const parentExecutionRequests = await this.chain.getParentExecutionRequests(head.slot, head.blockRoot);
434
+ stateAfterParentPayload = state.withParentPayloadApplied(parentExecutionRequests);
435
+ }
436
+ } else {
437
+ parentBlockHash = state.latestExecutionPayloadBid.parentBlockHash;
438
+ }
439
+ } else {
440
+ parentBlockHash = state.latestExecutionPayloadHeader.blockHash;
441
+ }
442
+
443
+ // Block production owns the engine head once the proposal slot started, a late fcU could move it back
444
+ if (reason !== PreparePayloadReason.scheduled && this.chain.clock.currentSlot >= prepareSlot) {
445
+ this.metrics?.blockPayload.payloadReprepare.inc({reason, result: "dropped"});
446
+ this.logger.debug("Proposal slot started, not re-preparing", {prepareSlot, reason, headRoot: head.blockRoot});
447
+ return;
448
+ }
449
+
450
+ // The payload_attributes event must carry the same hashes we send to the EL
451
+ const safeBlockHash = getSafeExecutionBlockHash(this.chain.forkChoice, this.logger);
452
+ const finalizedBlockHash = getFinalizedExecutionBlockHash(this.chain.forkChoice);
453
+
454
+ let payloadAttributes: PayloadAttributes | undefined;
455
+ // If emitPayloadAttributes is true emit a SSE payloadAttributes event for
456
+ // every slot. Without the flag, only emit the event if we are proposing in the next slot.
457
+ if (
458
+ (feeRecipient || this.chain.opts.emitPayloadAttributes === true) &&
459
+ this.chain.emitter.listenerCount(routes.events.EventType.payloadAttributes)
460
+ ) {
461
+ const data = getPayloadAttributesForSSE(fork, this.chain, {
462
+ prepareState: stateAfterParentPayload,
463
+ prepareSlot,
464
+ parentBlockRoot: fromHex(head.blockRoot),
465
+ parentBlockHash,
466
+ safeBlockHash,
467
+ finalizedBlockHash,
468
+ feeRecipient: feeRecipient ?? "0x0000000000000000000000000000000000000000",
469
+ });
470
+ this.chain.emitter.emit(routes.events.EventType.payloadAttributes, {data, version: fork});
471
+ payloadAttributes = data.payloadAttributes;
472
+ }
473
+
474
+ // Builders take the parent from the payload attributes event, so re-prepare whenever it was emitted. Recorded
475
+ // before the engine call, a failed forkchoiceUpdated must not drop the later re-prepares for this slot
476
+ const prepared = feeRecipient !== undefined || payloadAttributes !== undefined;
477
+ const record: PreparedPayload = {
478
+ prepareSlot,
479
+ proposerIndex,
480
+ headRoot: head.blockRoot,
481
+ buildOnFull,
482
+ feeRecipient,
483
+ failed: false,
484
+ };
485
+ if (prepared) {
486
+ this.lastPrepared = record;
487
+ }
488
+
489
+ if (feeRecipient) {
490
+ // Only for the scheduled run, a re-prepare later in the slot would add a second, shorter sample
491
+ if (reason === PreparePayloadReason.scheduled) {
492
+ const preparationTime = computeTimeAtSlot(this.config, prepareSlot, this.chain.genesisTime) - Date.now() / 1000;
493
+ this.metrics?.blockPayload.payloadAdvancePrepTime.observe(preparationTime);
494
+ }
495
+
496
+ // awaiting here instead of throwing an async call because there is no other task
497
+ // left for scheduler and this gives nice semantics to catch and log errors in the
498
+ // try/catch wrapper here.
499
+ try {
500
+ await prepareExecutionPayload(
501
+ this.chain,
502
+ this.logger,
503
+ fork, // State is of execution type
504
+ fromHex(head.blockRoot),
505
+ parentBlockHash,
506
+ safeBlockHash,
507
+ finalizedBlockHash,
508
+ stateAfterParentPayload,
509
+ feeRecipient,
510
+ payloadAttributes
511
+ );
512
+ } catch (e) {
513
+ record.failed = true;
514
+ throw e;
515
+ }
516
+ this.logger.verbose("PrepareNextSlotScheduler prepared new payload", {
517
+ prepareSlot,
518
+ proposerIndex,
519
+ feeRecipient,
520
+ reason,
521
+ headRoot: head.blockRoot,
522
+ buildOnFull,
523
+ });
524
+ }
525
+
526
+ if (prepared && reason !== PreparePayloadReason.scheduled) {
527
+ this.metrics?.blockPayload.payloadReprepare.inc({reason, result: "changed"});
528
+ }
529
+ }
530
+
531
+ /** Fee recipient of our validator proposing `prepareSlot`, `undefined` if the proposer is not ours */
532
+ private getFeeRecipient(
533
+ fork: ForkName,
534
+ prepareSlot: Slot,
535
+ headRoot: RootHex,
536
+ proposerIndex: ValidatorIndex
537
+ ): string | undefined {
538
+ if (!this.chain.beaconProposerCache.has(proposerIndex)) {
539
+ return undefined;
540
+ }
541
+ const pooledPreferences = isForkPostGloas(fork)
542
+ ? getPooledProposerPreferences(this.chain, prepareSlot, headRoot)
543
+ : null;
544
+ return pooledPreferences !== null
545
+ ? toHex(pooledPreferences.feeRecipient)
546
+ : this.chain.beaconProposerCache.getOrDefault(proposerIndex);
547
+ }
548
+
549
+ /**
550
+ * The PTC verdict on the current slot's block decides whether the next proposal extends its payload.
551
+ * Spec: the proposer SHOULD call `prepare_execution_payload` again once the parent's payload attestations are in.
552
+ */
553
+ private onPtcQuorum = (data: PtcQuorumEvent): void => {
554
+ if (data.slot === this.chain.clock.currentSlot) {
555
+ this.requestReprepare(PreparePayloadReason.ptcQuorum);
556
+ }
557
+ };
558
+
559
+ /**
560
+ * A payload of the current slot's block imported after the scheduled run moves the head to its full variant.
561
+ * Only react to a payload the PTC votes present: seen before the payload deadline, or already voted present. The
562
+ * event is only emitted once the payload's data is available. A late one without that verdict will likely be voted
563
+ * absent and the re-prepare undone.
564
+ */
565
+ private onExecutionPayloadImported = ({slot, blockRoot}: {slot: Slot; blockRoot: RootHex}): void => {
566
+ if (slot !== this.chain.clock.currentSlot) {
567
+ return;
568
+ }
569
+ const payloadInput = this.chain.seenPayloadEnvelopeInputCache.get(blockRoot);
570
+ if (payloadInput === undefined || !payloadInput.hasPayloadEnvelope()) {
571
+ return;
572
+ }
573
+ const seenSec = this.chain.clock.secFromSlot(slot, payloadInput.getPayloadEnvelopeSource().seenTimestampSec);
574
+ const quorum = this.chain.forkChoice.getPtcQuorum(blockRoot);
575
+ if (
576
+ seenSec >= this.config.getPayloadDueMs(this.config.getForkName(slot)) / 1000 &&
577
+ (quorum === null || getPtcVerdict(quorum) !== true)
578
+ ) {
579
+ return;
580
+ }
581
+ this.requestReprepare(PreparePayloadReason.payloadImported);
582
+ };
583
+
584
+ /**
585
+ * Re-run the payload preparation for the next slot after its inputs may have changed. Waits for an in-flight
586
+ * preparation, drops the request if neither a payload nor payload attributes were prepared for the next slot.
587
+ */
588
+ private requestReprepare(reason: PreparePayloadReason): void {
589
+ const prepareSlot = this.chain.clock.currentSlot + 1;
590
+ if (this.preparingSlot !== null) {
591
+ if (this.preparingSlot === prepareSlot) {
592
+ this.queuedReason = reason;
593
+ }
594
+ return;
595
+ }
596
+ if (this.lastPrepared?.prepareSlot !== prepareSlot) {
597
+ return;
598
+ }
599
+
600
+ this.preparingSlot = prepareSlot;
601
+ this.reprepare(prepareSlot, reason)
602
+ .catch((e) => {
603
+ if (!isErrorAborted(e) && !isQueueErrorAborted(e)) {
604
+ this.metrics?.blockPayload.payloadReprepare.inc({reason, result: "error"});
605
+ this.logger.error("Failed to re-prepare payload for next slot", {prepareSlot, reason}, e as Error);
606
+ }
607
+ })
608
+ .finally(() => this.finishRun(prepareSlot));
609
+ }
610
+
611
+ private finishRun(prepareSlot: Slot): void {
612
+ if (this.preparingSlot !== prepareSlot) {
613
+ return;
614
+ }
615
+ this.preparingSlot = null;
616
+ const queued = this.queuedReason;
617
+ this.queuedReason = null;
618
+ if (queued !== null) {
619
+ this.requestReprepare(queued);
620
+ }
621
+ }
622
+
623
+ private async reprepare(prepareSlot: Slot, reason: PreparePayloadReason): Promise<void> {
624
+ const prepared = this.lastPrepared;
625
+ const fork = this.config.getForkName(prepareSlot);
626
+ if (prepared === null || prepared.prepareSlot !== prepareSlot || !isForkPostBellatrix(fork)) {
627
+ return;
628
+ }
629
+
630
+ // Same head resolution as the scheduled run, the head may have changed since
631
+ const headBlock = this.chain.recomputeForkChoiceHead(ForkchoiceCaller.prepareNextSlot);
632
+ const feeRecipient = this.getFeeRecipient(fork, prepareSlot, headBlock.blockRoot, prepared.proposerIndex);
633
+ // Without a local proposer a re-prepare only re-emits the payload attributes, skip it if nobody listens
634
+ if (
635
+ feeRecipient === undefined &&
636
+ (this.chain.opts.emitPayloadAttributes !== true ||
637
+ this.chain.emitter.listenerCount(routes.events.EventType.payloadAttributes) === 0)
638
+ ) {
639
+ return;
640
+ }
641
+ const isEpochTransition = computeEpochAtSlot(prepareSlot) > computeEpochAtSlot(prepareSlot - 1);
642
+ const proposerHead = feeRecipient !== undefined || isEpochTransition ? this.chain.predictProposerHead() : headBlock;
643
+ const head = proposerHead.blockRoot !== headBlock.blockRoot ? proposerHead : headBlock;
644
+
645
+ const buildOnFull = isForkPostGloas(fork) ? this.chain.forkChoice.shouldBuildOnFull(head, prepareSlot) : null;
646
+ const logCtx = {prepareSlot, reason, headRoot: head.blockRoot, buildOnFull};
647
+ if (
648
+ !prepared.failed &&
649
+ head.blockRoot === prepared.headRoot &&
650
+ buildOnFull === prepared.buildOnFull &&
651
+ feeRecipient === prepared.feeRecipient
652
+ ) {
653
+ this.metrics?.blockPayload.payloadReprepare.inc({reason, result: "unchanged"});
654
+ this.logger.debug("Payload for next slot unchanged, not re-preparing", logCtx);
655
+ return;
656
+ }
657
+ this.logger.verbose("Re-preparing payload for next slot", {
658
+ ...logCtx,
659
+ prevHeadRoot: prepared.headRoot,
660
+ prevBuildOnFull: prepared.buildOnFull,
661
+ });
662
+
663
+ const state = await this.chain.regen.getBlockSlotState(
664
+ head,
665
+ prepareSlot,
666
+ {dontTransferCache: !isEpochTransition},
667
+ head === headBlock ? RegenCaller.precomputeEpoch : RegenCaller.predictProposerHead
668
+ );
669
+ await this.preparePayload({
670
+ reason,
671
+ fork,
672
+ prepareSlot,
673
+ proposerIndex: prepared.proposerIndex,
674
+ feeRecipient,
675
+ head,
676
+ state,
677
+ });
678
+ }
679
+
422
680
  /**
423
681
  * Pre-establish the builder connections so the handshake lands outside the bid deadline. Scheduled
424
682
  * later in the slot, connecting at PREPARE_NEXT_SLOT_BPS would go cold before bids are requested.