@lodestar/beacon-node 2.1.0-dev.a046f269a1 → 2.1.0-dev.a207065589

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 (90) hide show
  1. package/lib/api/impl/beacon/pool/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/pool/index.js +8 -0
  3. package/lib/api/impl/beacon/pool/index.js.map +1 -1
  4. package/lib/api/impl/beacon/state/index.d.ts.map +1 -1
  5. package/lib/api/impl/beacon/state/index.js +3 -2
  6. package/lib/api/impl/beacon/state/index.js.map +1 -1
  7. package/lib/api/impl/beacon/state/utils.js +1 -1
  8. package/lib/api/impl/beacon/state/utils.js.map +1 -1
  9. package/lib/api/impl/validator/index.js +1 -1
  10. package/lib/api/impl/validator/index.js.map +1 -1
  11. package/lib/chain/blocks/importBlock.d.ts.map +1 -1
  12. package/lib/chain/blocks/importBlock.js +14 -5
  13. package/lib/chain/blocks/importBlock.js.map +1 -1
  14. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  15. package/lib/chain/blocks/importExecutionPayload.js +4 -2
  16. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  17. package/lib/chain/blocks/payloadEnvelopeInput/types.d.ts +2 -1
  18. package/lib/chain/blocks/payloadEnvelopeInput/types.d.ts.map +1 -1
  19. package/lib/chain/chain.d.ts.map +1 -1
  20. package/lib/chain/chain.js +24 -5
  21. package/lib/chain/chain.js.map +1 -1
  22. package/lib/chain/forkChoice/index.d.ts +11 -2
  23. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  24. package/lib/chain/forkChoice/index.js +181 -13
  25. package/lib/chain/forkChoice/index.js.map +1 -1
  26. package/lib/chain/opPools/opPool.d.ts +9 -3
  27. package/lib/chain/opPools/opPool.d.ts.map +1 -1
  28. package/lib/chain/opPools/opPool.js +22 -16
  29. package/lib/chain/opPools/opPool.js.map +1 -1
  30. package/lib/chain/options.d.ts.map +1 -1
  31. package/lib/chain/options.js +1 -0
  32. package/lib/chain/options.js.map +1 -1
  33. package/lib/chain/seenCache/seenPayloadEnvelopeInput.d.ts +11 -2
  34. package/lib/chain/seenCache/seenPayloadEnvelopeInput.d.ts.map +1 -1
  35. package/lib/chain/seenCache/seenPayloadEnvelopeInput.js +28 -2
  36. package/lib/chain/seenCache/seenPayloadEnvelopeInput.js.map +1 -1
  37. package/lib/chain/validation/attestation.d.ts.map +1 -1
  38. package/lib/chain/validation/attestation.js +4 -2
  39. package/lib/chain/validation/attestation.js.map +1 -1
  40. package/lib/chain/validation/block.d.ts.map +1 -1
  41. package/lib/chain/validation/block.js +8 -5
  42. package/lib/chain/validation/block.js.map +1 -1
  43. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  44. package/lib/network/processor/gossipHandlers.js +15 -7
  45. package/lib/network/processor/gossipHandlers.js.map +1 -1
  46. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.d.ts.map +1 -1
  47. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +3 -1
  48. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  49. package/lib/sync/range/chain.d.ts.map +1 -1
  50. package/lib/sync/range/chain.js +1 -0
  51. package/lib/sync/range/chain.js.map +1 -1
  52. package/lib/sync/range/range.d.ts.map +1 -1
  53. package/lib/sync/range/range.js +5 -1
  54. package/lib/sync/range/range.js.map +1 -1
  55. package/lib/sync/unknownBlock.d.ts.map +1 -1
  56. package/lib/sync/unknownBlock.js +14 -1
  57. package/lib/sync/unknownBlock.js.map +1 -1
  58. package/lib/sync/utils/downloadByRange.d.ts +6 -0
  59. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  60. package/lib/sync/utils/downloadByRange.js +13 -8
  61. package/lib/sync/utils/downloadByRange.js.map +1 -1
  62. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  63. package/lib/sync/utils/downloadByRoot.js +1 -1
  64. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  65. package/lib/sync/utils/pendingBlocksTree.d.ts.map +1 -1
  66. package/lib/sync/utils/pendingBlocksTree.js +6 -1
  67. package/lib/sync/utils/pendingBlocksTree.js.map +1 -1
  68. package/package.json +17 -20
  69. package/src/api/impl/beacon/pool/index.ts +11 -0
  70. package/src/api/impl/beacon/state/index.ts +3 -7
  71. package/src/api/impl/beacon/state/utils.ts +1 -1
  72. package/src/api/impl/validator/index.ts +1 -1
  73. package/src/chain/blocks/importBlock.ts +14 -7
  74. package/src/chain/blocks/importExecutionPayload.ts +4 -2
  75. package/src/chain/blocks/payloadEnvelopeInput/types.ts +8 -1
  76. package/src/chain/chain.ts +29 -5
  77. package/src/chain/forkChoice/index.ts +235 -13
  78. package/src/chain/opPools/opPool.ts +27 -16
  79. package/src/chain/options.ts +1 -0
  80. package/src/chain/seenCache/seenPayloadEnvelopeInput.ts +28 -2
  81. package/src/chain/validation/attestation.ts +4 -2
  82. package/src/chain/validation/block.ts +8 -5
  83. package/src/network/processor/gossipHandlers.ts +28 -15
  84. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +4 -1
  85. package/src/sync/range/chain.ts +1 -0
  86. package/src/sync/range/range.ts +7 -1
  87. package/src/sync/unknownBlock.ts +20 -1
  88. package/src/sync/utils/downloadByRange.ts +27 -7
  89. package/src/sync/utils/downloadByRoot.ts +12 -9
  90. package/src/sync/utils/pendingBlocksTree.ts +6 -1
@@ -5,28 +5,33 @@ import {
5
5
  ForkChoice,
6
6
  ForkChoiceStateGetter,
7
7
  ForkChoiceStore,
8
+ IForkChoice,
8
9
  JustifiedBalancesGetter,
10
+ NativeForkChoice,
9
11
  PayloadStatus,
10
12
  ProtoArray,
11
13
  ProtoBlock,
12
14
  ForkChoiceOpts as RawForkChoiceOpts,
13
15
  } from "@lodestar/fork-choice";
14
- import {ZERO_HASH_HEX} from "@lodestar/params";
16
+ import {ForkSeq, SLOTS_PER_HISTORICAL_ROOT, ZERO_HASH_HEX, isForkPostGloas} from "@lodestar/params";
15
17
  import {
16
18
  DataAvailabilityStatus,
17
19
  IBeaconStateView,
20
+ ZERO_HASH,
18
21
  computeEpochAtSlot,
19
22
  computeStartSlotAtEpoch,
20
23
  isStatePostBellatrix,
21
24
  isStatePostGloas,
22
25
  } from "@lodestar/state-transition";
23
- import {Slot, ssz} from "@lodestar/types";
24
- import {Logger, toRootHex} from "@lodestar/utils";
26
+ import {Slot, phase0, ssz} from "@lodestar/types";
27
+ import {Logger, fromHex, toRootHex} from "@lodestar/utils";
25
28
  import {GENESIS_SLOT} from "../../constants/index.js";
26
29
  import {Metrics} from "../../metrics/index.js";
27
30
  import {ChainEvent, ChainEventEmitter} from "../emitter.js";
28
31
 
29
32
  export type ForkChoiceOpts = RawForkChoiceOpts & {
33
+ /** Use the native (Zig) fork choice store instead of the proto-array */
34
+ nativeForkChoice?: boolean;
30
35
  // for testing only
31
36
  forkchoiceConstructor?: typeof ForkChoice;
32
37
  };
@@ -58,7 +63,22 @@ export function initializeForkChoice(
58
63
  stateGetter: ForkChoiceStateGetter,
59
64
  metrics: Metrics | null,
60
65
  logger?: Logger
61
- ): ForkChoice {
66
+ ): IForkChoice {
67
+ if (opts.nativeForkChoice) {
68
+ return initializeNativeForkChoice(
69
+ config,
70
+ emitter,
71
+ currentSlot,
72
+ state,
73
+ isFinalizedState,
74
+ opts,
75
+ justifiedBalancesGetter,
76
+ stateGetter,
77
+ metrics,
78
+ logger
79
+ );
80
+ }
81
+
62
82
  return isFinalizedState
63
83
  ? initializeForkChoiceFromFinalizedState(
64
84
  config,
@@ -115,7 +135,7 @@ export function initializeForkChoiceFromFinalizedState(
115
135
  // production code use ForkChoice constructor directly
116
136
  const forkchoiceConstructor = opts.forkchoiceConstructor ?? ForkChoice;
117
137
 
118
- const isForkPostGloas = computeEpochAtSlot(state.slot) >= config.GLOAS_FORK_EPOCH;
138
+ const isPostGloasAnchor = isStatePostGloas(state) && isForkPostGloas(config.getForkName(blockHeader.slot));
119
139
 
120
140
  return new forkchoiceConstructor(
121
141
  config,
@@ -164,15 +184,20 @@ export function initializeForkChoiceFromFinalizedState(
164
184
  // TODO GLOAS: executionPayloadNumber/GasLimit are not tracked in BeaconState post-gloas
165
185
  // (EIP-7732 removed latestExecutionPayloadHeader). Using 0 as unavailable fallback —
166
186
  // see initializeForkChoiceFromUnfinalizedState for the same caveat on validation.
187
+ // A pre-Gloas anchor's gas limit is kept in the state's bid by the upgrade.
167
188
  executionPayloadNumber: isStatePostGloas(state) ? 0 : state.payloadBlockNumber,
168
- executionPayloadGasLimit: isStatePostGloas(state) ? 0 : state.latestExecutionPayloadHeader.gasLimit,
189
+ executionPayloadGasLimit: isPostGloasAnchor
190
+ ? 0
191
+ : isStatePostGloas(state)
192
+ ? Number(state.latestExecutionPayloadBid.gasLimit)
193
+ : state.latestExecutionPayloadHeader.gasLimit,
169
194
  executionStatus: blockHeader.slot === GENESIS_SLOT ? ExecutionStatus.Valid : ExecutionStatus.Syncing,
170
195
  }
171
196
  : {executionPayloadBlockHash: null, executionStatus: ExecutionStatus.PreMerge}),
172
197
 
173
198
  dataAvailabilityStatus: DataAvailabilityStatus.PreData,
174
- payloadStatus: isForkPostGloas ? PayloadStatus.PENDING : PayloadStatus.FULL,
175
- parentBlockHash: isStatePostGloas(state) ? toRootHex(state.latestBlockHash) : null,
199
+ payloadStatus: isPostGloasAnchor ? PayloadStatus.PENDING : PayloadStatus.FULL,
200
+ parentBlockHash: isPostGloasAnchor ? toRootHex(state.latestBlockHash) : null,
176
201
  },
177
202
  currentSlot
178
203
  ),
@@ -183,6 +208,200 @@ export function initializeForkChoiceFromFinalizedState(
183
208
  );
184
209
  }
185
210
 
211
+ /**
212
+ * Initialize the native fork choice. A finalized anchor is both the justified and the finalized
213
+ * checkpoint, as in the spec's `get_forkchoice_store`. An unfinalized one keeps its state's
214
+ * checkpoints, with stand-ins for the ancestors that connect it to them: nothing is reported as
215
+ * finalized that the chain has not finalized.
216
+ */
217
+ export function initializeNativeForkChoice(
218
+ config: ChainForkConfig,
219
+ emitter: ChainEventEmitter,
220
+ currentSlot: Slot,
221
+ state: IBeaconStateView,
222
+ isFinalizedState: boolean,
223
+ opts: ForkChoiceOpts,
224
+ justifiedBalancesGetter: JustifiedBalancesGetter,
225
+ stateGetter: ForkChoiceStateGetter,
226
+ metrics: Metrics | null,
227
+ logger?: Logger
228
+ ): NativeForkChoice {
229
+ const {blockHeader, checkpoint} = state.computeAnchorCheckpoint();
230
+ const anchorRoot = toRootHex(checkpoint.root);
231
+ const isPostGloas = isStatePostGloas(state);
232
+ // A state upgraded to Gloas through skipped slots still holds a pre-Gloas block, which carried its own payload
233
+ const isPostGloasAnchor = isPostGloas && config.getForkSeq(blockHeader.slot) >= ForkSeq.gloas;
234
+ const bid = isPostGloasAnchor ? state.latestExecutionPayloadBid : null;
235
+ const hasPayload = isStatePostBellatrix(state) && state.isExecutionStateType && state.isMergeTransitionComplete;
236
+ // The state caches the bid of its latest block, except at genesis: the genesis block carries no bid
237
+ const anchorBid = blockHeader.slot === GENESIS_SLOT ? null : bid;
238
+
239
+ // The store aliases no root to genesis, so a checkpoint the chain never moved off genesis is
240
+ // given the genesis block root. Only possible while that root is still in the state's history.
241
+ const withGenesisRoot = (cp: phase0.Checkpoint): phase0.Checkpoint => {
242
+ if (!ssz.Root.equals(cp.root, ZERO_HASH)) return cp;
243
+ if (state.slot > GENESIS_SLOT + SLOTS_PER_HISTORICAL_ROOT) {
244
+ throw Error(
245
+ `The native fork choice cannot start from an unfinalized state at slot ${state.slot} of a chain that never justified a checkpoint: the genesis block root has left the state's block roots. Start without --chain.nativeForkChoice`
246
+ );
247
+ }
248
+ return {epoch: cp.epoch, root: state.getBlockRootAtSlot(GENESIS_SLOT)};
249
+ };
250
+ const justifiedCheckpoint = isFinalizedState ? checkpoint : withGenesisRoot(state.currentJustifiedCheckpoint);
251
+ const finalizedCheckpoint = isFinalizedState ? checkpoint : withGenesisRoot(state.finalizedCheckpoint);
252
+ const justifiedRoot = toRootHex(justifiedCheckpoint.root);
253
+ const finalizedRoot = toRootHex(finalizedCheckpoint.root);
254
+
255
+ if (!isFinalizedState) {
256
+ logger?.warn("Initializing fork choice from unfinalized state", {
257
+ currentSlot,
258
+ stateSlot: state.slot,
259
+ headSlot: blockHeader.slot,
260
+ headRoot: anchorRoot,
261
+ finalizedEpoch: finalizedCheckpoint.epoch,
262
+ finalizedRoot,
263
+ justifiedEpoch: justifiedCheckpoint.epoch,
264
+ justifiedRoot,
265
+ });
266
+ }
267
+
268
+ const store = new ForkChoiceStore(
269
+ currentSlot,
270
+ justifiedCheckpoint,
271
+ finalizedCheckpoint,
272
+ // For an unfinalized anchor this is not the justified state, but no other state is at hand
273
+ state.getEffectiveBalanceIncrementsZeroInactive(),
274
+ justifiedBalancesGetter,
275
+ stateGetter,
276
+ {
277
+ onJustified: (cp) => emitter.emit(ChainEvent.forkChoiceJustified, cp),
278
+ onFinalized: (cp) => emitter.emit(ChainEvent.forkChoiceFinalized, cp),
279
+ onFastConfirmation: ({block, slot, currentSlot}) =>
280
+ emitter.emit(routes.events.EventType.fastConfirmation, {block, slot, currentSlot}),
281
+ onPtcQuorum: (data) => emitter.emit(ChainEvent.forkChoicePtcQuorum, data),
282
+ }
283
+ );
284
+
285
+ const checkpoints = {
286
+ justifiedEpoch: justifiedCheckpoint.epoch,
287
+ justifiedRoot,
288
+ finalizedEpoch: finalizedCheckpoint.epoch,
289
+ finalizedRoot,
290
+ unrealizedJustifiedEpoch: justifiedCheckpoint.epoch,
291
+ unrealizedJustifiedRoot: justifiedRoot,
292
+ unrealizedFinalizedEpoch: finalizedCheckpoint.epoch,
293
+ unrealizedFinalizedRoot: finalizedRoot,
294
+ };
295
+
296
+ const block: ProtoBlock = {
297
+ slot: blockHeader.slot,
298
+ parentRoot: toRootHex(blockHeader.parentRoot),
299
+ stateRoot: toRootHex(blockHeader.stateRoot),
300
+ blockRoot: anchorRoot,
301
+ targetRoot: anchorRoot,
302
+ timeliness: true,
303
+ ptcTimeliness: true,
304
+ importedTimely: true,
305
+ proposerIndex: blockHeader.proposerIndex,
306
+ ...checkpoints,
307
+
308
+ ...(hasPayload
309
+ ? {
310
+ executionPayloadBlockHash: isPostGloas
311
+ ? toRootHex(state.latestBlockHash)
312
+ : toRootHex(state.latestExecutionPayloadHeader.blockHash),
313
+ // TODO GLOAS: not tracked in BeaconState post-gloas, see initializeForkChoiceFromFinalizedState
314
+ executionPayloadNumber: isPostGloas ? 0 : state.payloadBlockNumber,
315
+ // The upgrade to Gloas keeps a pre-Gloas block's payload gas limit in the state's bid
316
+ executionPayloadGasLimit: isPostGloasAnchor
317
+ ? 0
318
+ : isPostGloas
319
+ ? Number(state.latestExecutionPayloadBid.gasLimit)
320
+ : state.latestExecutionPayloadHeader.gasLimit,
321
+ // A Gloas payload is judged when its envelope arrives, the genesis one included
322
+ executionStatus:
323
+ blockHeader.slot === GENESIS_SLOT && !isPostGloasAnchor ? ExecutionStatus.Valid : ExecutionStatus.Syncing,
324
+ }
325
+ : {executionPayloadBlockHash: null, executionStatus: ExecutionStatus.PreMerge}),
326
+
327
+ dataAvailabilityStatus: DataAvailabilityStatus.PreData,
328
+ payloadStatus: isPostGloasAnchor ? PayloadStatus.PENDING : PayloadStatus.FULL,
329
+ parentBlockHash: bid === null ? null : toRootHex(bid.parentBlockHash),
330
+ };
331
+
332
+ // Ancestors of the anchor known by root only: the finalized block, the justified block, the
333
+ // anchor's parent, and for the anchor's epoch and the one before the checkpoint block, which the
334
+ // chain can still justify and which current votes target, and the block before it, the
335
+ // dependent root of the next epoch's duties. Their slots are upper bounds and their payloads
336
+ // unknown, so they carry none.
337
+ const unfinalizedAncestors: ProtoBlock[] = [];
338
+ if (!isFinalizedState) {
339
+ const finalizedSlot = computeStartSlotAtEpoch(finalizedCheckpoint.epoch);
340
+ const candidates: [string, Slot][] = [
341
+ [finalizedRoot, finalizedSlot],
342
+ [justifiedRoot, computeStartSlotAtEpoch(justifiedCheckpoint.epoch)],
343
+ [block.parentRoot, blockHeader.slot - 1],
344
+ ];
345
+ const anchorEpoch = computeEpochAtSlot(state.slot);
346
+ for (const epoch of [anchorEpoch - 1, anchorEpoch]) {
347
+ const checkpointSlot = computeStartSlotAtEpoch(epoch);
348
+ for (const slot of [checkpointSlot - 1, checkpointSlot]) {
349
+ if (slot > finalizedSlot && slot < blockHeader.slot) {
350
+ candidates.push([toRootHex(state.getBlockRootAtSlot(slot)), slot]);
351
+ }
352
+ }
353
+ }
354
+ // Roots repeat over skipped slots: a block keeps the lowest slot it is known at
355
+ candidates.sort((a, b) => a[1] - b[1]);
356
+ for (const [blockRoot, slot] of candidates) {
357
+ const isKnown = blockRoot === anchorRoot || unfinalizedAncestors.some((b) => b.blockRoot === blockRoot);
358
+ if (isKnown || blockRoot === ZERO_HASH_HEX) continue;
359
+ const isGloas = config.getForkSeq(slot) >= ForkSeq.gloas;
360
+ const targetSlot = computeStartSlotAtEpoch(computeEpochAtSlot(slot));
361
+ unfinalizedAncestors.push({
362
+ slot,
363
+ blockRoot,
364
+ parentRoot: unfinalizedAncestors.at(-1)?.blockRoot ?? ZERO_HASH_HEX,
365
+ stateRoot: ZERO_HASH_HEX,
366
+ targetRoot: targetSlot === slot ? blockRoot : toRootHex(state.getBlockRootAtSlot(targetSlot)),
367
+ timeliness: false,
368
+ ptcTimeliness: false,
369
+ importedTimely: false,
370
+ proposerIndex: 0,
371
+ ...checkpoints,
372
+ executionPayloadBlockHash: null,
373
+ executionStatus: ExecutionStatus.PreMerge,
374
+ dataAvailabilityStatus: DataAvailabilityStatus.PreData,
375
+ payloadStatus: isGloas ? PayloadStatus.PENDING : PayloadStatus.FULL,
376
+ parentBlockHash: isGloas ? ZERO_HASH_HEX : null,
377
+ });
378
+ }
379
+ }
380
+
381
+ return new NativeForkChoice(
382
+ config,
383
+ store,
384
+ {
385
+ block,
386
+ stateSlot: state.slot,
387
+ genesisTime: state.genesisTime,
388
+ genesisValidatorsRoot: state.genesisValidatorsRoot,
389
+ justifiedCheckpoint: isFinalizedState ? state.currentJustifiedCheckpoint : justifiedCheckpoint,
390
+ finalizedCheckpoint: isFinalizedState ? state.finalizedCheckpoint : finalizedCheckpoint,
391
+ unfinalizedAncestors: isFinalizedState ? undefined : unfinalizedAncestors,
392
+ payloadBlockHash: isPostGloasAnchor
393
+ ? (anchorBid?.blockHash ?? null)
394
+ : block.executionPayloadBlockHash === null
395
+ ? null
396
+ : fromHex(block.executionPayloadBlockHash),
397
+ bidParentBlockHash: anchorBid?.parentBlockHash ?? null,
398
+ },
399
+ metrics,
400
+ opts,
401
+ logger
402
+ );
403
+ }
404
+
186
405
  /**
187
406
  * Initialize forkchoice from an unfinalized state.
188
407
  */
@@ -217,7 +436,7 @@ export function initializeForkChoiceFromUnfinalizedState(
217
436
  // this is not the justified state, but there is no other ways to get justified balances
218
437
  const justifiedBalances = unfinalizedState.getEffectiveBalanceIncrementsZeroInactive();
219
438
 
220
- const isForkPostGloas = computeEpochAtSlot(unfinalizedState.slot) >= config.GLOAS_FORK_EPOCH;
439
+ const isPostGloasAnchor = isStatePostGloas(unfinalizedState) && isForkPostGloas(config.getForkName(blockHeader.slot));
221
440
 
222
441
  const store = new ForkChoiceStore(
223
442
  currentSlot,
@@ -270,17 +489,20 @@ export function initializeForkChoiceFromUnfinalizedState(
270
489
  // PENDING/EMPTY convention), so gossip bids that reference the head's *own* payload
271
490
  // hash won't match this variant anyway and will IGNORE until `onExecutionPayload`
272
491
  // upgrades the head to FULL with real values.
492
+ // A pre-Gloas anchor's gas limit is kept in the state's bid by the upgrade.
273
493
  executionPayloadNumber: isStatePostGloas(unfinalizedState) ? 0 : unfinalizedState.payloadBlockNumber,
274
- executionPayloadGasLimit: isStatePostGloas(unfinalizedState)
494
+ executionPayloadGasLimit: isPostGloasAnchor
275
495
  ? 0
276
- : unfinalizedState.latestExecutionPayloadHeader.gasLimit,
496
+ : isStatePostGloas(unfinalizedState)
497
+ ? Number(unfinalizedState.latestExecutionPayloadBid.gasLimit)
498
+ : unfinalizedState.latestExecutionPayloadHeader.gasLimit,
277
499
  executionStatus: blockHeader.slot === GENESIS_SLOT ? ExecutionStatus.Valid : ExecutionStatus.Syncing,
278
500
  }
279
501
  : {executionPayloadBlockHash: null, executionStatus: ExecutionStatus.PreMerge}),
280
502
 
281
503
  dataAvailabilityStatus: DataAvailabilityStatus.PreData,
282
- payloadStatus: isForkPostGloas ? PayloadStatus.PENDING : PayloadStatus.FULL,
283
- parentBlockHash: isStatePostGloas(unfinalizedState) ? toRootHex(unfinalizedState.latestBlockHash) : null,
504
+ payloadStatus: isPostGloasAnchor ? PayloadStatus.PENDING : PayloadStatus.FULL,
505
+ parentBlockHash: isPostGloasAnchor ? toRootHex(unfinalizedState.latestBlockHash) : null,
284
506
  };
285
507
 
286
508
  const parentSlot = blockHeader.slot - 1;
@@ -1,6 +1,7 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {
3
3
  BLS_WITHDRAWAL_PREFIX,
4
+ FAR_FUTURE_EPOCH,
4
5
  ForkName,
5
6
  ForkSeq,
6
7
  MAX_ATTESTER_SLASHINGS,
@@ -17,6 +18,7 @@ import {
17
18
  getAttesterSlashableIndices,
18
19
  getAttesterSlashingSignatureSets,
19
20
  getProposerSlashingSignatureSets,
21
+ getValidatorFromStateBytes,
20
22
  } from "@lodestar/state-transition";
21
23
  import {
22
24
  AttesterSlashing,
@@ -389,12 +391,19 @@ export class OpPool {
389
391
  }
390
392
 
391
393
  /**
392
- * Prune all types of transactions given the latest head state
394
+ * Prune all types of transactions given the latest head state and the finalized checkpoint state.
395
+ * `finalizedState` is only needed to prune voluntary exits, and may be null when there are none.
393
396
  */
394
- pruneAll(headBlock: SignedBeaconBlock, headState: IBeaconStateView): void {
397
+ pruneAll(
398
+ headBlock: SignedBeaconBlock,
399
+ headState: IBeaconStateView,
400
+ finalizedState: IBeaconStateView | Uint8Array | null
401
+ ): void {
395
402
  this.pruneAttesterSlashings(headState);
396
403
  this.pruneProposerSlashings(headState);
397
- this.pruneVoluntaryExits(headState);
404
+ if (finalizedState !== null) {
405
+ this.pruneVoluntaryExits(finalizedState);
406
+ }
398
407
  this.pruneBlsToExecutionChanges(headBlock, headState);
399
408
  }
400
409
 
@@ -438,21 +447,23 @@ export class OpPool {
438
447
 
439
448
  /**
440
449
  * Call after finalizing
441
- * Prune if validator has already exited at or before the finalized checkpoint of the head.
450
+ * Prune if validator has already exited in the finalized state, so an exit included only in a block that is later
451
+ * orphaned stays in the pool. The finalized state may be serialized bytes if it is not in memory.
452
+ *
453
+ * Exits are not pruned by fork: from Deneb the signature domain is fixed to Capella (EIP-7044), so a fork transition
454
+ * cannot invalidate an exit verified at a Deneb+ state. Exits verified with a pre-Capella domain before crossing into
455
+ * Deneb are not handled, as only chains that cross the Deneb fork are affected.
442
456
  */
443
- private pruneVoluntaryExits(headState: IBeaconStateView): void {
444
- const headStateFork = this.config.getForkSeq(headState.slot);
445
- const finalizedEpoch = headState.finalizedCheckpoint.epoch;
446
-
457
+ private pruneVoluntaryExits(finalizedState: IBeaconStateView | Uint8Array): void {
447
458
  for (const [key, voluntaryExit] of this.voluntaryExits.entries()) {
448
- // VoluntaryExit messages signed in the previous fork become invalid and can never be included in any future
449
- // block, so just drop as the head state advances into the next fork.
450
- if (this.config.getForkSeq(computeStartSlotAtEpoch(voluntaryExit.message.epoch)) < headStateFork) {
451
- this.voluntaryExits.delete(key);
452
- }
453
-
454
- // TODO: Improve this simplistic condition
455
- if (voluntaryExit.message.epoch <= finalizedEpoch) {
459
+ const {validatorIndex} = voluntaryExit.message;
460
+ const finalizedValidator =
461
+ finalizedState instanceof Uint8Array
462
+ ? getValidatorFromStateBytes(this.config, finalizedState, validatorIndex)
463
+ : validatorIndex < finalizedState.validatorCount
464
+ ? finalizedState.getValidator(validatorIndex)
465
+ : null;
466
+ if (finalizedValidator !== null && finalizedValidator.exitEpoch !== FAR_FUTURE_EPOCH) {
456
467
  this.voluntaryExits.delete(key);
457
468
  }
458
469
  }
@@ -132,6 +132,7 @@ export const defaultChainOptions: IChainOptions = {
132
132
  // - it helps debug easier when network is unfinalized
133
133
  nHistoricalStatesFileDataStore: true,
134
134
  nativeStateTransition: true,
135
+ nativeForkChoice: false,
135
136
  maxBlockStates: DEFAULT_MAX_BLOCK_STATES,
136
137
  maxCPStateEpochsInMemory: DEFAULT_MAX_CP_STATE_EPOCHS_IN_MEMORY,
137
138
  maxCPStateEpochsOnDisk: DEFAULT_MAX_CP_STATE_ON_DISK,
@@ -64,6 +64,7 @@ export class SeenPayloadEnvelopeInput {
64
64
  private readonly metrics: Metrics | null;
65
65
  private readonly logger?: Logger;
66
66
  private payloadInputs = new Map<RootHex, PayloadEnvelopeInput>();
67
+ private readonly unvalidatedRoots = new Set<RootHex>();
67
68
  // Dedup concurrent DB reloads of the same root so callers share one reconstructed object.
68
69
  private readonly reloading = new Map<RootHex, Promise<PayloadEnvelopeInput | undefined>>();
69
70
 
@@ -127,9 +128,17 @@ export class SeenPayloadEnvelopeInput {
127
128
  });
128
129
  };
129
130
 
130
- add(props: Omit<CreateFromBlockProps, "daOutOfRange">): PayloadEnvelopeInput {
131
+ /**
132
+ * Set `unvalidated` for a block of which only the proposer signature is verified, e.g. one retained for unknown
133
+ * parent sync. Such entries are evicted first when the cache is over its max size, until the block passes gossip
134
+ * validation or is imported. Adding an existing entry without `unvalidated` promotes it without replacing it.
135
+ */
136
+ add(props: Omit<CreateFromBlockProps, "daOutOfRange">, opts?: {unvalidated?: boolean}): PayloadEnvelopeInput {
131
137
  const existing = this.payloadInputs.get(props.blockRootHex);
132
138
  if (existing !== undefined) {
139
+ if (!opts?.unvalidated) {
140
+ this.unvalidatedRoots.delete(props.blockRootHex);
141
+ }
133
142
  this.logger?.verbose("SeenPayloadEnvelopeInput.add reused existing entry", {
134
143
  slot: existing.slot,
135
144
  root: props.blockRootHex,
@@ -139,6 +148,9 @@ export class SeenPayloadEnvelopeInput {
139
148
  const daOutOfRange = isDaOutOfRange(this.config, props.forkName, props.block.message.slot, this.clock.currentEpoch);
140
149
  const input = PayloadEnvelopeInput.createFromBlock({...props, daOutOfRange});
141
150
  this.payloadInputs.set(props.blockRootHex, input);
151
+ if (opts?.unvalidated) {
152
+ this.unvalidatedRoots.add(props.blockRootHex);
153
+ }
142
154
  this.metrics?.seenCache.payloadEnvelopeInput.created.inc({source: props.source});
143
155
  this.logger?.verbose("SeenPayloadEnvelopeInput.add created new entry", {
144
156
  slot: input.slot,
@@ -300,12 +312,25 @@ export class SeenPayloadEnvelopeInput {
300
312
 
301
313
  /**
302
314
  * Bound this cache to have at most MAX_PAYLOAD_ENVELOPE_INPUT_CACHE_SIZE items.
303
- * Evicts by insertion order so a just-reloaded old-slot entry is not evicted right after.
315
+ * Evicts entries of unvalidated blocks that are not imported yet first, then the rest by insertion order so a
316
+ * just-reloaded old-slot entry is not evicted right after.
304
317
  * On unstable network, we may need to query an evicted item, UnknownBlockInput will recover
305
318
  * it from db via getOrReload() api. Runs after every single insert, so it evicts ~1 per call.
306
319
  */
307
320
  private pruneToMaxSize(): void {
308
321
  let evicted = 0;
322
+ for (const blockRootHex of this.unvalidatedRoots) {
323
+ if (this.payloadInputs.size <= MAX_PAYLOAD_ENVELOPE_INPUT_CACHE_SIZE) {
324
+ break;
325
+ }
326
+ const input = this.payloadInputs.get(blockRootHex);
327
+ if (input === undefined || this.forkChoice.hasBlockHex(blockRootHex)) {
328
+ this.unvalidatedRoots.delete(blockRootHex);
329
+ continue;
330
+ }
331
+ this.evictPayloadInput(input, "capUnvalidated");
332
+ evicted++;
333
+ }
309
334
  for (const input of this.payloadInputs.values()) {
310
335
  if (this.payloadInputs.size <= MAX_PAYLOAD_ENVELOPE_INPUT_CACHE_SIZE) {
311
336
  break;
@@ -331,5 +356,6 @@ export class SeenPayloadEnvelopeInput {
331
356
  });
332
357
  this.serializedCache.delete(payloadInput.getSerializedCacheKeys());
333
358
  this.payloadInputs.delete(payloadInput.blockRootHex);
359
+ this.unvalidatedRoots.delete(payloadInput.blockRootHex);
334
360
  }
335
361
  }
@@ -261,10 +261,12 @@ async function validateAttestationNoSignatureCheck(
261
261
  const attSlot = attestationOrBytes.attSlot;
262
262
  attDataKey = getSeenAttDataKeyFromGossipAttestation(attestationOrBytes);
263
263
  const committeeIndexForLookup = isForkPostElectra(fork)
264
- ? (getCommitteeIndexFromAttestationOrBytes(fork, attestationOrBytes) ?? 0)
264
+ ? getCommitteeIndexFromAttestationOrBytes(fork, attestationOrBytes)
265
265
  : PRE_ELECTRA_SINGLE_ATTESTATION_COMMITTEE_INDEX;
266
266
  const cachedAttData =
267
- attDataKey !== null ? chain.seenAttestationDatas.get(attSlot, committeeIndexForLookup, attDataKey) : null;
267
+ attDataKey !== null && committeeIndexForLookup !== null
268
+ ? chain.seenAttestationDatas.get(attSlot, committeeIndexForLookup, attDataKey)
269
+ : null;
268
270
  if (cachedAttData === null) {
269
271
  const attestation = sszDeserializeSingleAttestation(fork, attestationOrBytes.serializedData);
270
272
  // only deserialize on the first AttestationData that's not cached
@@ -98,13 +98,16 @@ export async function validateGossipBlock(
98
98
  // If fork choice does *not* consider the parent to be a descendant of the finalized block,
99
99
  // then there are two more cases:
100
100
  //
101
- // 1. We have the parent stored in our database. Because fork-choice has confirmed the
102
- // parent is *not* in our post-finalization DAG, all other blocks must be either
103
- // pre-finalization or conflicting with finalization.
101
+ // 1. Fork choice still holds the parent. Because it is *not* in our post-finalization DAG,
102
+ // the parent is either pre-finalization or conflicting with finalization, so the
103
+ // finalized checkpoint is not an ancestor of the block: REJECT.
104
104
  // 2. The parent is unknown to us, we probably want to download it since it might actually
105
105
  // descend from the finalized root.
106
- // (Non-Lighthouse): Since we prune all blocks non-descendant from finalized checking the `db.block` database won't be useful to guard
107
- // against known bad fork blocks, so we throw PARENT_BLOCK_UNKNOWN for cases (1) and (2)
106
+ // Blocks that fork choice has already pruned fall into case (2), as the `db.block` database
107
+ // does not keep non-descendants of the finalized block either.
108
+ if (chain.forkChoice.hasBlockHexUnsafe(parentRoot)) {
109
+ throw new BlockGossipError(GossipAction.REJECT, {code: BlockErrorCode.NOT_FINALIZED_DESCENDANT, parentRoot});
110
+ }
108
111
  throw new BlockGossipError(GossipAction.IGNORE, {code: BlockErrorCode.PARENT_BLOCK_UNKNOWN, parentRoot});
109
112
  }
110
113
 
@@ -183,7 +183,8 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
183
183
  blockRootHex: RootHex,
184
184
  fork: ForkName,
185
185
  peerIdStr: string,
186
- seenTimestampSec: number
186
+ seenTimestampSec: number,
187
+ opts?: {unvalidated?: boolean}
187
188
  ): BlockInput {
188
189
  const blockInput = chain.seenBlockInputCache.getByBlock({
189
190
  block: signedBlock,
@@ -196,15 +197,18 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
196
197
  // Also seed the payload-envelope cache, so we have PayloadEnvelopeInput even through "PARENT_BLOCK_UNKNOWN" error
197
198
  // see https://github.com/ChainSafe/lodestar/issues/9475
198
199
  if (isForkPostGloas(fork)) {
199
- chain.seenPayloadEnvelopeInputCache.add({
200
- blockRootHex,
201
- block: signedBlock as SignedBeaconBlock<ForkPostGloas>,
202
- forkName: fork,
203
- sampledColumns: chain.custodyConfig.sampledColumns,
204
- custodyColumns: chain.custodyConfig.custodyColumns,
205
- seenTimestampSec,
206
- source: PayloadEnvelopeInputSource.gossip,
207
- });
200
+ chain.seenPayloadEnvelopeInputCache.add(
201
+ {
202
+ blockRootHex,
203
+ block: signedBlock as SignedBeaconBlock<ForkPostGloas>,
204
+ forkName: fork,
205
+ sampledColumns: chain.custodyConfig.sampledColumns,
206
+ custodyColumns: chain.custodyConfig.custodyColumns,
207
+ seenTimestampSec,
208
+ source: PayloadEnvelopeInputSource.gossip,
209
+ },
210
+ opts
211
+ );
208
212
  }
209
213
 
210
214
  return blockInput;
@@ -300,7 +304,9 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
300
304
  }
301
305
  chain.seenBlockProposers.add(slot, proposerIndex, blockRootHex);
302
306
 
303
- const blockInput = cacheSignatureVerifiedBlock(signedBlock, blockRootHex, fork, peerIdStr, seenTimestampSec);
307
+ const blockInput = cacheSignatureVerifiedBlock(signedBlock, blockRootHex, fork, peerIdStr, seenTimestampSec, {
308
+ unvalidated: true,
309
+ });
304
310
  chain.emitter.emit(ChainEvent.blockUnknownParent, {
305
311
  blockInput,
306
312
  peer: peerIdStr,
@@ -575,7 +581,8 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
575
581
  const delaySec = seenTimestampSec - computeTimeAtSlot(config, slot, chain.genesisTime);
576
582
  metrics?.gossipBlock.elapsedTimeTillReceived.observe({source: OpSource.gossip}, delaySec);
577
583
  chain.validatorMonitor?.registerBeaconBlock(OpSource.gossip, delaySec, signedBlock.message);
578
- if (!blockInput.hasBlockAndAllData()) {
584
+ const missingData = !blockInput.hasBlockAndAllData();
585
+ if (missingData) {
579
586
  chain.logger.debug("Received gossip block, attempting fetch of unavailable data", blockInput.getLogMeta());
580
587
  // The data is not yet fully available, immediately trigger an aggressive pull via unknown block sync
581
588
  chain.emitter.emit(ChainEvent.incompleteBlockInput, {
@@ -668,8 +675,13 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
668
675
  }
669
676
  metrics?.gossipBlock.processBlockErrors.inc({error: e instanceof BlockError ? e.type.code : "NOT_BLOCK_ERROR"});
670
677
  logger[logLevel]("Error processing block", {slot, root: blockInput.blockRootHex, peer: peerIdStr}, e as Error);
671
- // TODO(fulu): Revisit when we prune block inputs
672
- chain.seenBlockInputCache.prune(blockInput.blockRootHex);
678
+ // BlockInputSync retries the import of a block with missing data from this same BlockInput, pruning it here
679
+ // would put later gossip columns into a new BlockInput that is never imported. The entry is released once the
680
+ // block is persisted, BlockInputSync removes it, on finalization or by the cache size limit
681
+ if (!missingData) {
682
+ // TODO(fulu): Revisit when we prune block inputs
683
+ chain.seenBlockInputCache.prune(blockInput.blockRootHex);
684
+ }
673
685
  });
674
686
  }
675
687
 
@@ -721,7 +733,8 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
721
733
  e.type.root,
722
734
  topic.boundary.fork,
723
735
  peerIdStr,
724
- seenTimestampSec
736
+ seenTimestampSec,
737
+ {unvalidated: false}
725
738
  );
726
739
  // We're returning IGNORE (thrown below), so this block is not forwarded to peers. Unlike the
727
740
  // happy path there is no rush to forward, so we don't need to wrap in callInNextEventLoop.
@@ -226,5 +226,8 @@ export function validateDataColumnSidecarsByRangeRequest(
226
226
  count = config.MAX_REQUEST_BLOCKS_DENEB;
227
227
  }
228
228
 
229
- return {startSlot, count, columns};
229
+ // Spec: sidecars MUST be sent in (slot, column_index) order, so serve each requested column once, ascending
230
+ const sortedColumns = Array.from(new Set(columns)).sort((a, b) => a - b);
231
+
232
+ return {startSlot, count, columns: sortedColumns};
230
233
  }
@@ -627,6 +627,7 @@ export class SyncChain {
627
627
  case DownloadByRangeErrorCode.INVALID_ENVELOPE_BLOCK_HASH:
628
628
  case DownloadByRangeErrorCode.INVALID_ENVELOPE_SLOT:
629
629
  case DownloadByRangeErrorCode.INVALID_CHAIN_SEGMENT:
630
+ case DownloadByRangeErrorCode.TOO_MANY_KZG_COMMITMENTS:
630
631
  case DataColumnSidecarErrorCode.INCORRECT_KZG_COMMITMENTS_COUNT:
631
632
  case DataColumnSidecarErrorCode.INCORRECT_KZG_PROOF_COUNT:
632
633
  case DataColumnSidecarErrorCode.INVALID_KZG_PROOF_BATCH:
@@ -1,6 +1,7 @@
1
1
  import {EventEmitter} from "node:events";
2
2
  import {StrictEventEmitter} from "strict-event-emitter-types";
3
3
  import {BeaconConfig} from "@lodestar/config";
4
+ import {isForkPostGloas} from "@lodestar/params";
4
5
  import {IBeaconStateViewGloas, computeStartSlotAtEpoch, isStatePostGloas} from "@lodestar/state-transition";
5
6
  import {Epoch, Status, fulu, ssz} from "@lodestar/types";
6
7
  import {Logger, byteArrayEquals, prettyPrintIndices, toHex, toRootHex} from "@lodestar/utils";
@@ -434,7 +435,12 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
434
435
  // the batch then downloads the head's payload as dangling parent and validates it against the bid
435
436
  const headState = this.chain.getHeadState();
436
437
  let parentPayload: ParentPayload | undefined;
437
- if (isStatePostGloas(headState) && headState.latestBlockHeader.slot > 0) {
438
+ // A pre-Gloas head block in a state upgraded to Gloas carried its own payload, no envelope follows it
439
+ if (
440
+ isStatePostGloas(headState) &&
441
+ headState.latestBlockHeader.slot > 0 &&
442
+ isForkPostGloas(this.config.getForkName(headState.latestBlockHeader.slot))
443
+ ) {
438
444
  const header = ssz.phase0.BeaconBlockHeader.clone(headState.latestBlockHeader);
439
445
  if (byteArrayEquals(header.stateRoot, ssz.Root.defaultValue())) {
440
446
  header.stateRoot = headState.hashTreeRoot();