@lodestar/beacon-node 1.52.0-dev.29dff83619 → 1.52.0-dev.31011e1c39

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.
@@ -177,6 +177,8 @@ function compareBidCandidates(a: BidCandidate, b: BidCandidate): number {
177
177
  return a.receivedMs - b.receivedMs;
178
178
  }
179
179
 
180
+ type ParentStates = {parentState: IBeaconStateView; parentStateWithPayload: IBeaconStateView};
181
+
180
182
  type ProduceBlockContentsRes = {executionPayloadValue: Wei; consensusBlockValue: Wei} & {
181
183
  data: BlockContents<ForkPreGloas>;
182
184
  version: ForkPreGloas;
@@ -448,9 +450,11 @@ export function getValidatorApi(
448
450
  {
449
451
  commonBlockBodyPromise,
450
452
  parentBlock,
453
+ parentStatesPromise,
451
454
  }: Omit<routes.validator.ExtraProduceBlockOpts, "builderSelection"> & {
452
455
  commonBlockBodyPromise: Promise<CommonBlockBody>;
453
456
  parentBlock: ProtoBlock;
457
+ parentStatesPromise: Promise<ParentStates>;
454
458
  }
455
459
  ): Promise<ProduceBlindedBlockRes> {
456
460
  const version = config.getForkName(slot);
@@ -485,6 +489,7 @@ export function getValidatorApi(
485
489
  randaoReveal,
486
490
  graffiti,
487
491
  commonBlockBodyPromise,
492
+ ...(await parentStatesPromise),
488
493
  });
489
494
 
490
495
  metrics?.blockProductionSuccess.inc({source});
@@ -517,9 +522,11 @@ export function getValidatorApi(
517
522
  strictFeeRecipientCheck,
518
523
  commonBlockBodyPromise,
519
524
  parentBlock,
525
+ parentStatesPromise,
520
526
  }: Omit<routes.validator.ExtraProduceBlockOpts, "builderSelection"> & {
521
527
  commonBlockBodyPromise: Promise<CommonBlockBody>;
522
528
  parentBlock: ProtoBlock;
529
+ parentStatesPromise: Promise<ParentStates>;
523
530
  }
524
531
  ): Promise<ProduceBlockContentsRes & {shouldOverrideBuilder?: boolean}> {
525
532
  const version = config.getForkName(slot);
@@ -539,6 +546,7 @@ export function getValidatorApi(
539
546
  graffiti,
540
547
  feeRecipient,
541
548
  commonBlockBodyPromise,
549
+ ...(await parentStatesPromise),
542
550
  });
543
551
  if (strictFeeRecipientCheck && feeRecipient && isForkPostBellatrix(version)) {
544
552
  const blockFeeRecipient = toHex((block as bellatrix.BeaconBlock).body.executionPayload.feeRecipient);
@@ -634,6 +642,13 @@ export function getValidatorApi(
634
642
  notOnOutOfRangeData(parentBlockRoot);
635
643
  metrics?.blockProductionSlotDelta.set(slot - parentSlot);
636
644
 
645
+ // Fetch the production state once and thread it to all downstream production calls, not awaited so each
646
+ // block source includes it in its production time. Only reached for pre-gloas slots (produceBlockV3 rejects
647
+ // post-gloas forks), the execution payload is part of the parent block so its state already includes it
648
+ const parentStatesPromise: Promise<ParentStates> = chain.regen
649
+ .getBlockSlotState(parentBlock, slot, {dontTransferCache: true}, RegenCaller.produceBlock)
650
+ .then((parentState) => ({parentState, parentStateWithPayload: parentState}));
651
+
637
652
  const fork = config.getForkName(slot);
638
653
 
639
654
  const isBuilderEnabled =
@@ -676,6 +691,7 @@ export function getValidatorApi(
676
691
  strictFeeRecipientCheck: false,
677
692
  commonBlockBodyPromise,
678
693
  parentBlock,
694
+ parentStatesPromise,
679
695
  })
680
696
  : Promise.reject(new Error("Builder disabled"));
681
697
 
@@ -684,6 +700,7 @@ export function getValidatorApi(
684
700
  strictFeeRecipientCheck,
685
701
  commonBlockBodyPromise,
686
702
  parentBlock,
703
+ parentStatesPromise,
687
704
  }).then((engineBlock) => {
688
705
  // Once the engine returns a block, in the event of either:
689
706
  // - suspected builder censorship
@@ -719,28 +736,28 @@ export function getValidatorApi(
719
736
  });
720
737
 
721
738
  // Ensure builder and engine HTTP requests are sent before starting common block body production
722
- // by deferring the call to next event loop iteration, allowing pending I/O operations like
723
- // HTTP requests to be processed first and sent out early in slot.
724
- callInNextEventLoop(() => {
725
- logger.verbose("Producing common block body", loggerContext);
726
- const commonBlockBodyStartedAt = Date.now();
727
-
728
- chain
729
- .produceCommonBlockBody({
730
- slot,
731
- parentBlock,
732
- randaoReveal,
733
- graffiti: graffitiBytes,
734
- })
735
- .then((commonBlockBody) => {
736
- deferredCommonBlockBody.resolve(commonBlockBody);
737
- logger.verbose("Produced common block body", {
738
- ...loggerContext,
739
- durationMs: Date.now() - commonBlockBodyStartedAt,
740
- });
741
- })
742
- .catch(deferredCommonBlockBody.reject);
743
- });
739
+ // by deferring the call to next event loop iteration once the state is available, allowing pending
740
+ // I/O operations like HTTP requests to be processed first and sent out early in slot.
741
+ parentStatesPromise.then(
742
+ (parentStates) =>
743
+ callInNextEventLoop(() => {
744
+ logger.verbose("Producing common block body", loggerContext);
745
+ const commonBlockBodyStartedAt = Date.now();
746
+
747
+ chain
748
+ .produceCommonBlockBody({slot, parentBlock, randaoReveal, graffiti: graffitiBytes, ...parentStates})
749
+ .then((commonBlockBody) => {
750
+ deferredCommonBlockBody.resolve(commonBlockBody);
751
+ logger.verbose("Produced common block body", {
752
+ ...loggerContext,
753
+ durationMs: Date.now() - commonBlockBodyStartedAt,
754
+ });
755
+ })
756
+ .catch(deferredCommonBlockBody.reject);
757
+ }),
758
+ // Both block sources fail on the state themselves and do not await the common block body
759
+ () => {}
760
+ );
744
761
 
745
762
  const [builder, engine] = await blockProductionRacePromise;
746
763
 
@@ -1008,19 +1025,23 @@ export function getValidatorApi(
1008
1025
  (!circuitBreakerActive &&
1009
1026
  chain.executionPayloadBidPool.getBestBid(slot, bidParentBlockHash, parentBlockRootHex) !== null);
1010
1027
 
1011
- // Calculate cutoff time based on start of the slot, ensures a slow local payload build does
1012
- // not delay the proposal when a builder bid block is available (and vice versa)
1013
- const cutoffMs = Math.max(
1014
- 0,
1015
- config.getSlotComponentDurationMs(fork, BLOCK_PRODUCTION_RACE_CUTOFF_GLOAS_BPS) - chain.clock.msFromSlot(slot)
1016
- );
1028
+ // Cutoff time into the slot, ensures a slow local payload build does not delay the proposal when a
1029
+ // builder bid block is available (and vice versa). Each timer waits for the time left until the cutoff
1030
+ const cutoffMs = config.getSlotComponentDurationMs(fork, BLOCK_PRODUCTION_RACE_CUTOFF_GLOAS_BPS);
1031
+ const msToCutoff = (): number => Math.max(0, cutoffMs - chain.clock.msFromSlot(slot));
1017
1032
 
1018
1033
  // Give p2p bids the same time to bid up as granted to builder API bid requests via the advertised
1019
1034
  // deadline, the pool is read once the deadline passed and the bid requests settled. A late request
1020
1035
  // does not wait past the race cutoff, a pooled bid is still the fastest fallback if the local block fails
1021
1036
  const bidDeadlinePromise = circuitBreakerActive
1022
1037
  ? Promise.resolve()
1023
- : sleep(Math.min(chain.builderApiClient.bidDeadline, cutoffMs));
1038
+ : sleep(Math.min(chain.builderApiClient.bidDeadline, msToCutoff()));
1039
+
1040
+ let parentExecutionRequestsPromise: Promise<gloas.ExecutionRequests> | null = null;
1041
+ const getParentExecutionRequests = (): Promise<gloas.ExecutionRequests> => {
1042
+ parentExecutionRequestsPromise ??= chain.getParentExecutionRequests(parentSlot, parentBlockRootHex);
1043
+ return parentExecutionRequestsPromise;
1044
+ };
1024
1045
 
1025
1046
  // Candidates are ranked by their boosted counted total payment, the p2p bid is governed
1026
1047
  // by the top-level factors and each builder API bid by its own entry. Ties prefer the
@@ -1030,10 +1051,9 @@ export function getValidatorApi(
1030
1051
  // Past the race cutoff a pooled p2p bid is used right away rather than waiting for pending
1031
1052
  // builder API requests, the local block is selected at the cutoff anyway if it is ready
1032
1053
  let [builderApiBids] = await Promise.all([
1033
- Promise.race([builderApiBidsPromise, sleep(cutoffMs).then(() => null)]),
1054
+ Promise.race([builderApiBidsPromise, sleep(msToCutoff()).then(() => null)]),
1034
1055
  bidDeadlinePromise,
1035
1056
  ]);
1036
- let parentExecutionRequestsPromise: Promise<gloas.ExecutionRequests> | null = null;
1037
1057
 
1038
1058
  let p2pBid: PooledExecutionPayloadBid | null = circuitBreakerActive
1039
1059
  ? null
@@ -1062,10 +1082,7 @@ export function getValidatorApi(
1062
1082
  parentBlockHash: bidParentBlockHash,
1063
1083
  parentBlockRoot: parentBlockRootHex,
1064
1084
  entry,
1065
- getParentExecutionRequests: () => {
1066
- parentExecutionRequestsPromise ??= chain.getParentExecutionRequests(parentSlot, parentBlockRootHex);
1067
- return parentExecutionRequestsPromise;
1068
- },
1085
+ getParentExecutionRequests,
1069
1086
  });
1070
1087
  return {
1071
1088
  signedBid,
@@ -1114,23 +1131,6 @@ export function getValidatorApi(
1114
1131
  return rankedCandidates[0];
1115
1132
  })();
1116
1133
 
1117
- const commonBlockBodyPromise = chain.produceCommonBlockBody({
1118
- slot,
1119
- parentBlock,
1120
- randaoReveal,
1121
- graffiti: graffitiBytes,
1122
- });
1123
-
1124
- const baseAttrs = {
1125
- slot,
1126
- parentBlock,
1127
- randaoReveal,
1128
- graffiti: graffitiBytes,
1129
- feeRecipient,
1130
- strictFeeRecipientCheck,
1131
- commonBlockBodyPromise,
1132
- };
1133
-
1134
1134
  metrics?.blockProductionRequests.inc({source: ProducedBlockSource.engine});
1135
1135
 
1136
1136
  const timed = <T>(source: ProducedBlockSource, fn: () => Promise<T>): Promise<T> => {
@@ -1138,11 +1138,59 @@ export function getValidatorApi(
1138
1138
  return fn().finally(() => t?.({source}));
1139
1139
  };
1140
1140
 
1141
+ // Fetch the production state once and apply the parent execution payload once here, so all
1142
+ // downstream consumers share a single state: the un-applied `parentState` (for `computeNewStateRoot`)
1143
+ // and the applied `parentStateWithPayload` (for attestation scoring and execution-payload prep).
1144
+ // Not awaited, the race below covers it and both blocks are produced from it
1145
+ const baseAttrsPromise = (async () => {
1146
+ const parentState = await chain.regen.getBlockSlotState(
1147
+ parentBlock,
1148
+ slot,
1149
+ {dontTransferCache: true},
1150
+ RegenCaller.produceBlock
1151
+ );
1152
+ // Fetch the parent's execution requests once here and thread them via blockAttributes: they are
1153
+ // used both to apply the parent payload below and as the block's `parentExecutionRequests` field
1154
+ // (so both are guaranteed consistent). Only needed when building on FULL; empty parent has none.
1155
+ const parentExecutionRequests =
1156
+ isBuildingOnFull && isStatePostGloas(parentState)
1157
+ ? await getParentExecutionRequests()
1158
+ : ssz.gloas.ExecutionRequests.defaultValue();
1159
+ // When building on EMPTY there is nothing to apply, so it stays the same view as parentState
1160
+ // (the availability bit for parentSlot stays false, which is correct).
1161
+ const parentStateWithPayload =
1162
+ isBuildingOnFull && isStatePostGloas(parentState)
1163
+ ? parentState.withParentPayloadApplied(parentExecutionRequests)
1164
+ : parentState;
1165
+
1166
+ const commonBlockBodyPromise = chain.produceCommonBlockBody({
1167
+ slot,
1168
+ parentBlock,
1169
+ randaoReveal,
1170
+ graffiti: graffitiBytes,
1171
+ parentState,
1172
+ parentStateWithPayload,
1173
+ });
1174
+
1175
+ return {
1176
+ slot,
1177
+ parentBlock,
1178
+ randaoReveal,
1179
+ graffiti: graffitiBytes,
1180
+ feeRecipient,
1181
+ strictFeeRecipientCheck,
1182
+ commonBlockBodyPromise,
1183
+ parentState,
1184
+ parentStateWithPayload,
1185
+ parentExecutionRequests,
1186
+ };
1187
+ })();
1188
+
1141
1189
  // use abort controller to stop waiting for the bid block if the engine block will be selected
1142
1190
  const controller = new AbortController();
1143
1191
 
1144
- const enginePromise: ReturnType<typeof chain.produceBlock> = timed(ProducedBlockSource.engine, () =>
1145
- chain.produceBlock(baseAttrs)
1192
+ const enginePromise: ReturnType<typeof chain.produceBlock> = timed(ProducedBlockSource.engine, async () =>
1193
+ chain.produceBlock(await baseAttrsPromise)
1146
1194
  ).then((engineBlock) => {
1147
1195
  // No need to wait for the bid block if the engine block will always be selected, either
1148
1196
  // due to suspected builder censorship, or because no builders are configured and the
@@ -1157,13 +1205,13 @@ export function getValidatorApi(
1157
1205
  throw new NoBidReceived();
1158
1206
  }
1159
1207
  metrics?.blockProductionRequests.inc({source: ProducedBlockSource.builder});
1160
- return timed(ProducedBlockSource.builder, () =>
1161
- chain.produceBlock({...baseAttrs, builderBid: candidate.signedBid})
1208
+ return timed(ProducedBlockSource.builder, async () =>
1209
+ chain.produceBlock({...(await baseAttrsPromise), builderBid: candidate.signedBid})
1162
1210
  );
1163
1211
  });
1164
1212
 
1165
1213
  const [engineResult, bidBlockResult] = await resolveOrRacePromises([enginePromise, bidBlockPromise], {
1166
- resolveTimeoutMs: cutoffMs,
1214
+ resolveTimeoutMs: msToCutoff(),
1167
1215
  raceTimeoutMs: config.getSlotDurationMs(fork),
1168
1216
  signal: controller.signal,
1169
1217
  });
@@ -1215,18 +1215,10 @@ export class BeaconChain implements IBeaconChain {
1215
1215
  }
1216
1216
 
1217
1217
  async produceCommonBlockBody(blockAttributes: BlockAttributes): Promise<CommonBlockBody> {
1218
- const {slot, parentBlock} = blockAttributes;
1219
- const state = await this.regen.getBlockSlotState(
1220
- parentBlock,
1221
- slot,
1222
- {dontTransferCache: true},
1223
- RegenCaller.produceBlock
1224
- );
1225
-
1226
1218
  // TODO: To avoid breaking changes for metric define this attribute
1227
1219
  const blockType = BlockType.Full;
1228
1220
 
1229
- return produceCommonBlockBody.call(this, blockType, state, blockAttributes);
1221
+ return produceCommonBlockBody.call(this, blockType, blockAttributes);
1230
1222
  }
1231
1223
 
1232
1224
  produceBlock(blockAttributes: BlockAttributes & {commonBlockBodyPromise: Promise<CommonBlockBody>}): Promise<{
@@ -1248,46 +1240,24 @@ export class BeaconChain implements IBeaconChain {
1248
1240
 
1249
1241
  async produceBlockWrapper<T extends BlockType>(
1250
1242
  blockType: T,
1251
- {
1252
- randaoReveal,
1253
- graffiti,
1254
- slot,
1255
- feeRecipient,
1256
- strictFeeRecipientCheck,
1257
- commonBlockBodyPromise,
1258
- parentBlock,
1259
- builderBid,
1260
- }: BlockAttributes & {commonBlockBodyPromise: Promise<CommonBlockBody>}
1243
+ blockAttributes: BlockAttributes & {commonBlockBodyPromise: Promise<CommonBlockBody>}
1261
1244
  ): Promise<{
1262
1245
  block: AssembledBlockType<T>;
1263
1246
  executionPayloadValue: Wei;
1264
1247
  consensusBlockValue: Wei;
1265
1248
  shouldOverrideBuilder?: boolean;
1266
1249
  }> {
1267
- const state = await this.regen.getBlockSlotState(
1268
- parentBlock,
1269
- slot,
1270
- {dontTransferCache: true},
1271
- RegenCaller.produceBlock
1272
- );
1273
- const proposerIndex = state.getBeaconProposer(slot);
1250
+ const {slot, parentBlock, parentState} = blockAttributes;
1251
+ const proposerIndex = parentState.getBeaconProposer(slot);
1274
1252
  const proposerPubKey = this.pubkeyCache.getPubkeyBytesOrThrow(proposerIndex);
1275
1253
 
1276
1254
  const {body, produceResult, executionPayloadValue, shouldOverrideBuilder} = await produceBlockBody.call(
1277
1255
  this,
1278
1256
  blockType,
1279
- state,
1280
1257
  {
1281
- randaoReveal,
1282
- graffiti,
1283
- slot,
1284
- feeRecipient,
1285
- strictFeeRecipientCheck,
1286
- parentBlock,
1258
+ ...blockAttributes,
1287
1259
  proposerIndex,
1288
1260
  proposerPubKey,
1289
- commonBlockBodyPromise,
1290
- builderBid,
1291
1261
  }
1292
1262
  );
1293
1263
 
@@ -1312,7 +1282,9 @@ export class BeaconChain implements IBeaconChain {
1312
1282
  body,
1313
1283
  } as AssembledBlockType<T>;
1314
1284
 
1315
- const {newStateRoot, proposerReward} = computeNewStateRoot(this.metrics, state, block);
1285
+ // `parentState` is the un-applied production state; `computeNewStateRoot` re-applies the parent
1286
+ // payload during state transition, so it must not receive the already-applied state
1287
+ const {newStateRoot, proposerReward} = computeNewStateRoot(this.metrics, parentState, block);
1316
1288
  block.stateRoot = newStateRoot;
1317
1289
  const blockRoot =
1318
1290
  produceResult.type === BlockType.Full
@@ -24,6 +24,7 @@ import {
24
24
  G2_POINT_AT_INFINITY,
25
25
  IBeaconStateView,
26
26
  type IBeaconStateViewBellatrix,
27
+ type IBeaconStateViewGloas,
27
28
  computeEpochAtSlot,
28
29
  computeTimeAtSlot,
29
30
  getExpectedGasLimit,
@@ -111,6 +112,12 @@ export type BlockAttributes = {
111
112
  graffiti: Bytes32;
112
113
  slot: Slot;
113
114
  parentBlock: ProtoBlock;
115
+ // the state of parentBlock processed to slot
116
+ parentState: IBeaconStateView;
117
+ // parentStateWithPayload is the same as parentState for pre-gloas or if building on EMPTY
118
+ parentStateWithPayload: IBeaconStateView;
119
+ // Parent's execution requests, undefined pre-gloas.
120
+ parentExecutionRequests?: gloas.ExecutionRequests;
114
121
  feeRecipient?: string;
115
122
  /** Verify that a locally produced execution payload uses `feeRecipient`. */
116
123
  strictFeeRecipientCheck?: boolean;
@@ -175,32 +182,9 @@ export type ProduceResult =
175
182
  | ProduceFullPhase0
176
183
  | ProduceBlinded;
177
184
 
178
- /**
179
- * Drop voluntary exits that `parent_execution_requests` have invalidated (e.g. a withdrawal
180
- * request initiating an exit on the same validator). Op pool selected against the unapplied
181
- * state, so re-validate against the post-apply state to avoid producing an invalid block.
182
- *
183
- * `getStateAfterParentPayload` is a thunk so the post-apply state is only materialized when
184
- * actually needed (i.e. when extending the parent payload and there are exits to filter).
185
- */
186
- function maybeFilterInvalidatedVoluntaryExits(
187
- commonBlockBody: CommonBlockBody,
188
- isExtendingPayload: boolean,
189
- getStateAfterParentPayload: () => IBeaconStateViewBellatrix
190
- ): CommonBlockBody["voluntaryExits"] {
191
- if (!isExtendingPayload || commonBlockBody.voluntaryExits.length === 0) {
192
- return commonBlockBody.voluntaryExits;
193
- }
194
- const state = getStateAfterParentPayload();
195
- return commonBlockBody.voluntaryExits.filter((signedVoluntaryExit) =>
196
- state.isValidVoluntaryExit(signedVoluntaryExit, false)
197
- );
198
- }
199
-
200
185
  export async function produceBlockBody<T extends BlockType>(
201
186
  this: BeaconChain,
202
187
  blockType: T,
203
- currentState: IBeaconStateView,
204
188
  blockAttr: BlockAttributes & {
205
189
  proposerIndex: ValidatorIndex;
206
190
  proposerPubKey: BLSPubkey;
@@ -221,6 +205,9 @@ export async function produceBlockBody<T extends BlockType>(
221
205
  proposerPubKey,
222
206
  commonBlockBodyPromise,
223
207
  builderBid,
208
+ parentState,
209
+ parentStateWithPayload,
210
+ parentExecutionRequests,
224
211
  } = blockAttr;
225
212
  let executionPayloadValue: Wei;
226
213
  let blockBody: AssembledBodyType<T>;
@@ -242,17 +229,17 @@ export async function produceBlockBody<T extends BlockType>(
242
229
  this.logger.verbose("Producing beacon block body", logMeta);
243
230
 
244
231
  if (builderBid !== undefined) {
245
- if (!isStatePostGloas(currentState)) {
246
- throw new Error("Expected Gloas state for builder bid block production");
232
+ if (!isStatePostGloas(parentState)) {
233
+ throw new Error(`Expected Gloas state for builder bid block production slot=${blockSlot}`);
234
+ }
235
+ if (parentExecutionRequests === undefined) {
236
+ throw new Error(`Expected parentExecutionRequests for gloas block production slot=${blockSlot}`);
247
237
  }
248
238
 
249
239
  const isExtendingPayload = byteArrayEquals(
250
240
  builderBid.message.parentBlockHash,
251
- currentState.latestExecutionPayloadBid.blockHash
241
+ parentState.latestExecutionPayloadBid.blockHash
252
242
  );
253
- const parentExecutionRequests = isExtendingPayload
254
- ? await this.getParentExecutionRequests(parentBlock.slot, parentBlock.blockRoot)
255
- : ssz.gloas.ExecutionRequests.defaultValue();
256
243
  executionPayloadValue = (BigInt(builderBid.message.value) + builderBid.message.executionPayment) * GWEI_TO_WEI;
257
244
 
258
245
  const commonBlockBody = await commonBlockBodyPromise;
@@ -262,10 +249,9 @@ export async function produceBlockBody<T extends BlockType>(
262
249
  parentBlock.blockRoot,
263
250
  blockSlot - 1
264
251
  );
252
+ // parentExecutionRequests fetched once by the entrypoint (isExtendingPayload aligns with the
253
+ // build-on-full decision used to select this bid; default value when building on an empty parent)
265
254
  gloasBody.parentExecutionRequests = parentExecutionRequests;
266
- gloasBody.voluntaryExits = maybeFilterInvalidatedVoluntaryExits(commonBlockBody, isExtendingPayload, () =>
267
- currentState.withParentPayloadApplied(parentExecutionRequests)
268
- );
269
255
  blockBody = gloasBody as AssembledBodyType<T>;
270
256
 
271
257
  this.logger.verbose("Produced block with builder bid", {
@@ -278,8 +264,11 @@ export async function produceBlockBody<T extends BlockType>(
278
264
  isExtendingPayload,
279
265
  });
280
266
  } else if (isForkPostGloas(fork)) {
281
- if (!isStatePostGloas(currentState)) {
282
- throw new Error("Expected Gloas state for Gloas block production");
267
+ if (!isStatePostGloas(parentState)) {
268
+ throw new Error(`Expected Gloas state for Gloas block production slot=${blockSlot}`);
269
+ }
270
+ if (parentExecutionRequests === undefined) {
271
+ throw new Error(`Expected parentExecutionRequests for gloas block production slot=${blockSlot}`);
283
272
  }
284
273
 
285
274
  // TODO GLOAS: support non self-building here, the block type differentiation between
@@ -299,20 +288,16 @@ export async function produceBlockBody<T extends BlockType>(
299
288
 
300
289
  // Get execution payload from EL
301
290
  let parentBlockHash: Bytes32;
302
- let parentExecutionRequests: gloas.ExecutionRequests;
303
- // Apply parent payload once here as it's reused by EL prep and voluntary exit filtering below
304
- let stateAfterParentPayload: IBeaconStateViewBellatrix = currentState;
305
- // Spec: should_build_on_full(store, head, slot). `parentBlock` is the proposer's head
306
- // (set by chain.getProposerHead(slot)). Returns false when the PTC majority signalled
307
- // the blob data is not available or the payload was not timely, forcing a build on EMPTY (reorg).
308
- const isBuildingOnFull = this.forkChoice.shouldBuildOnFull(parentBlock, blockSlot);
291
+ const stateAfterParentPayload = parentStateWithPayload as IBeaconStateViewGloas;
292
+ // Spec: should_build_on_full(store, head, slot), decided by the caller when applying the parent payload
293
+ const isBuildingOnFull = byteArrayEquals(
294
+ stateAfterParentPayload.latestBlockHash,
295
+ parentState.latestExecutionPayloadBid.blockHash
296
+ );
309
297
  if (isBuildingOnFull) {
310
- parentBlockHash = currentState.latestExecutionPayloadBid.blockHash;
311
- parentExecutionRequests = await this.getParentExecutionRequests(parentBlock.slot, parentBlock.blockRoot);
312
- stateAfterParentPayload = currentState.withParentPayloadApplied(parentExecutionRequests);
298
+ parentBlockHash = parentState.latestExecutionPayloadBid.blockHash;
313
299
  } else {
314
- parentBlockHash = currentState.latestExecutionPayloadBid.parentBlockHash;
315
- parentExecutionRequests = ssz.gloas.ExecutionRequests.defaultValue();
300
+ parentBlockHash = parentState.latestExecutionPayloadBid.parentBlockHash;
316
301
  }
317
302
  const prepareRes = await prepareExecutionPayload(
318
303
  this,
@@ -377,7 +362,7 @@ export async function produceBlockBody<T extends BlockType>(
377
362
  parentBlockHash,
378
363
  parentBlockRoot,
379
364
  blockHash: executionPayload.blockHash,
380
- prevRandao: currentState.getRandaoMix(currentState.epoch),
365
+ prevRandao: parentState.getRandaoMix(parentState.epoch),
381
366
  feeRecipient: executionPayload.feeRecipient,
382
367
  gasLimit: BigInt(executionPayload.gasLimit),
383
368
  builderIndex: BUILDER_INDEX_SELF_BUILD,
@@ -414,12 +399,8 @@ export async function produceBlockBody<T extends BlockType>(
414
399
  parentBlock.blockRoot,
415
400
  blockSlot - 1
416
401
  );
402
+ // parentExecutionRequests fetched once by the entrypoint (default value when building on an empty parent)
417
403
  gloasBody.parentExecutionRequests = parentExecutionRequests;
418
- gloasBody.voluntaryExits = maybeFilterInvalidatedVoluntaryExits(
419
- commonBlockBody,
420
- isBuildingOnFull,
421
- () => stateAfterParentPayload
422
- );
423
404
  blockBody = gloasBody as AssembledBodyType<T>;
424
405
 
425
406
  // Store execution payload data required to construct execution payload envelope later
@@ -449,7 +430,7 @@ export async function produceBlockBody<T extends BlockType>(
449
430
  shouldOverrideBuilder,
450
431
  });
451
432
  } else if (isForkPostBellatrix(fork)) {
452
- if (!isStatePostBellatrix(currentState)) {
433
+ if (!isStatePostBellatrix(parentState)) {
453
434
  throw new Error("Expected Bellatrix state for execution block production");
454
435
  }
455
436
 
@@ -478,10 +459,10 @@ export async function produceBlockBody<T extends BlockType>(
478
459
  this.logger,
479
460
  fork,
480
461
  parentBlockRoot,
481
- currentState.latestExecutionPayloadHeader.blockHash,
462
+ parentState.latestExecutionPayloadHeader.blockHash,
482
463
  safeBlockHash,
483
464
  finalizedBlockHash ?? ZERO_HASH_HEX,
484
- currentState,
465
+ parentState,
485
466
  executionBuilder.issueLocalFcUWithFeeRecipient
486
467
  );
487
468
  }
@@ -493,7 +474,7 @@ export async function produceBlockBody<T extends BlockType>(
493
474
  slot: blockSlot,
494
475
  proposerPubKey: toHex(proposerPubKey),
495
476
  });
496
- const headerRes = await prepareExecutionPayloadHeader(this, fork, currentState, proposerPubKey);
477
+ const headerRes = await prepareExecutionPayloadHeader(this, fork, parentState, proposerPubKey);
497
478
 
498
479
  endExecutionPayloadHeader?.({
499
480
  step: BlockProductionStep.executionPayload,
@@ -528,7 +509,7 @@ export async function produceBlockBody<T extends BlockType>(
528
509
  });
529
510
  } else {
530
511
  const headerGasLimit = builderRes.header.gasLimit;
531
- const parentGasLimit = currentState.latestExecutionPayloadHeader.gasLimit;
512
+ const parentGasLimit = parentState.latestExecutionPayloadHeader.gasLimit;
532
513
  const expectedGasLimit = getExpectedGasLimit(parentGasLimit, targetGasLimit);
533
514
 
534
515
  const lowerBound = Math.min(parentGasLimit, expectedGasLimit);
@@ -582,10 +563,10 @@ export async function produceBlockBody<T extends BlockType>(
582
563
  this.logger,
583
564
  fork,
584
565
  parentBlockRoot,
585
- currentState.latestExecutionPayloadHeader.blockHash,
566
+ parentState.latestExecutionPayloadHeader.blockHash,
586
567
  safeBlockHash,
587
568
  finalizedBlockHash ?? ZERO_HASH_HEX,
588
- currentState,
569
+ parentState,
589
570
  feeRecipient
590
571
  );
591
572
 
@@ -1111,8 +1092,7 @@ export function getPooledProposerPreferences(
1111
1092
  export async function produceCommonBlockBody<T extends BlockType>(
1112
1093
  this: BeaconChain,
1113
1094
  blockType: T,
1114
- currentState: IBeaconStateView,
1115
- {randaoReveal, graffiti, slot, parentBlock}: BlockAttributes
1095
+ {randaoReveal, graffiti, slot, parentBlock, parentStateWithPayload}: BlockAttributes
1116
1096
  ): Promise<CommonBlockBody> {
1117
1097
  const stepsMetrics =
1118
1098
  blockType === BlockType.Full
@@ -1133,7 +1113,7 @@ export async function produceCommonBlockBody<T extends BlockType>(
1133
1113
  // }
1134
1114
  // }
1135
1115
  const [attesterSlashings, proposerSlashings, voluntaryExits, blsToExecutionChanges] =
1136
- this.opPool.getSlashingsAndExits(currentState, blockType, this.metrics);
1116
+ this.opPool.getSlashingsAndExits(parentStateWithPayload, blockType, this.metrics);
1137
1117
 
1138
1118
  const endAttestations = stepsMetrics?.startTimer();
1139
1119
  // TODO: extract to a separate BeaconChain method to coordinate the 2 op-pools
@@ -1141,7 +1121,7 @@ export async function produceCommonBlockBody<T extends BlockType>(
1141
1121
  fork,
1142
1122
  this.forkChoice,
1143
1123
  this.shufflingCache,
1144
- currentState,
1124
+ parentStateWithPayload,
1145
1125
  this.singleAttestationPool
1146
1126
  );
1147
1127
  endAttestations?.({
@@ -1172,7 +1152,7 @@ export async function produceCommonBlockBody<T extends BlockType>(
1172
1152
  };
1173
1153
 
1174
1154
  if (!isForkPostHeze(fork)) {
1175
- commonBlockBody.eth1Data = currentState.eth1Data;
1155
+ commonBlockBody.eth1Data = parentStateWithPayload.eth1Data;
1176
1156
  commonBlockBody.deposits = [];
1177
1157
  }
1178
1158