@lodestar/beacon-node 2.1.0-dev.5f507dce39 → 2.1.0-dev.6f6f023ffd

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 (98) 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/forks.d.ts +2 -2
  44. package/lib/network/forks.d.ts.map +1 -1
  45. package/lib/network/forks.js +3 -3
  46. package/lib/network/forks.js.map +1 -1
  47. package/lib/network/gossip/scoringParameters.js +19 -14
  48. package/lib/network/gossip/scoringParameters.js.map +1 -1
  49. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  50. package/lib/network/processor/gossipHandlers.js +15 -7
  51. package/lib/network/processor/gossipHandlers.js.map +1 -1
  52. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.d.ts.map +1 -1
  53. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +3 -1
  54. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  55. package/lib/sync/range/chain.d.ts.map +1 -1
  56. package/lib/sync/range/chain.js +1 -0
  57. package/lib/sync/range/chain.js.map +1 -1
  58. package/lib/sync/range/range.d.ts.map +1 -1
  59. package/lib/sync/range/range.js +5 -1
  60. package/lib/sync/range/range.js.map +1 -1
  61. package/lib/sync/unknownBlock.d.ts.map +1 -1
  62. package/lib/sync/unknownBlock.js +14 -1
  63. package/lib/sync/unknownBlock.js.map +1 -1
  64. package/lib/sync/utils/downloadByRange.d.ts +6 -0
  65. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  66. package/lib/sync/utils/downloadByRange.js +17 -8
  67. package/lib/sync/utils/downloadByRange.js.map +1 -1
  68. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  69. package/lib/sync/utils/downloadByRoot.js +1 -1
  70. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  71. package/lib/sync/utils/pendingBlocksTree.d.ts.map +1 -1
  72. package/lib/sync/utils/pendingBlocksTree.js +6 -1
  73. package/lib/sync/utils/pendingBlocksTree.js.map +1 -1
  74. package/package.json +16 -19
  75. package/src/api/impl/beacon/pool/index.ts +11 -0
  76. package/src/api/impl/beacon/state/index.ts +3 -7
  77. package/src/api/impl/beacon/state/utils.ts +1 -1
  78. package/src/api/impl/validator/index.ts +1 -1
  79. package/src/chain/blocks/importBlock.ts +14 -7
  80. package/src/chain/blocks/importExecutionPayload.ts +4 -2
  81. package/src/chain/blocks/payloadEnvelopeInput/types.ts +8 -1
  82. package/src/chain/chain.ts +29 -5
  83. package/src/chain/forkChoice/index.ts +235 -13
  84. package/src/chain/opPools/opPool.ts +27 -16
  85. package/src/chain/options.ts +1 -0
  86. package/src/chain/seenCache/seenPayloadEnvelopeInput.ts +28 -2
  87. package/src/chain/validation/attestation.ts +4 -2
  88. package/src/chain/validation/block.ts +8 -5
  89. package/src/network/forks.ts +7 -3
  90. package/src/network/gossip/scoringParameters.ts +23 -14
  91. package/src/network/processor/gossipHandlers.ts +28 -15
  92. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +4 -1
  93. package/src/sync/range/chain.ts +1 -0
  94. package/src/sync/range/range.ts +7 -1
  95. package/src/sync/unknownBlock.ts +20 -1
  96. package/src/sync/utils/downloadByRange.ts +30 -7
  97. package/src/sync/utils/downloadByRoot.ts +12 -9
  98. 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
 
@@ -29,10 +29,14 @@ import {Epoch} from "@lodestar/types";
29
29
  export const FORK_EPOCH_LOOKAHEAD = 2;
30
30
 
31
31
  /**
32
- * Return the list of `ForkBoundary`s meant to be active at `epoch`
32
+ * Return the fork boundaries active at any epoch in the inclusive range.
33
33
  * @see FORK_EPOCH_LOOKAHEAD for details on when fork boundaries are considered 'active'
34
34
  */
35
- export function getActiveForkBoundaries(config: ChainForkConfig, epoch: Epoch): ForkBoundary[] {
35
+ export function getActiveForkBoundaries(
36
+ config: ChainForkConfig,
37
+ fromEpoch: Epoch,
38
+ toEpoch = fromEpoch
39
+ ): ForkBoundary[] {
36
40
  const activeBoundaries: ForkBoundary[] = [];
37
41
  const {forkBoundariesAscendingEpochOrder} = config;
38
42
 
@@ -48,7 +52,7 @@ export function getActiveForkBoundaries(config: ChainForkConfig, epoch: Epoch):
48
52
  continue;
49
53
  }
50
54
 
51
- if (epoch >= currentEpoch - FORK_EPOCH_LOOKAHEAD && epoch <= nextEpoch + FORK_EPOCH_LOOKAHEAD) {
55
+ if (toEpoch >= currentEpoch - FORK_EPOCH_LOOKAHEAD && fromEpoch <= nextEpoch + FORK_EPOCH_LOOKAHEAD) {
52
56
  activeBoundaries.push(currentForkBoundary);
53
57
  }
54
58
  }
@@ -6,8 +6,8 @@ import {
6
6
  } from "@libp2p/gossipsub/score";
7
7
  import {BeaconConfig} from "@lodestar/config";
8
8
  import {ATTESTATION_SUBNET_COUNT, PTC_SIZE, SLOTS_PER_EPOCH, TARGET_AGGREGATORS_PER_COMMITTEE} from "@lodestar/params";
9
- import {computeCommitteeCount} from "@lodestar/state-transition";
10
- import {getActiveForkBoundaries} from "../forks.js";
9
+ import {computeCommitteeCount, computeStartSlotAtEpoch} from "@lodestar/state-transition";
10
+ import {FORK_EPOCH_LOOKAHEAD, getActiveForkBoundaries} from "../forks.js";
11
11
  import {Eth2Context} from "./gossipsub.js";
12
12
  import {GossipType} from "./interface.js";
13
13
  import {stringifyGossipTopic} from "./topic.js";
@@ -132,11 +132,20 @@ function getAllTopicsScoreParams(
132
132
  precomputedParams: PreComputedParams
133
133
  ): Record<string, TopicScoreParams> {
134
134
  const {epochDurationMs, slotDurationMs} = precomputedParams;
135
- const epoch = eth2Context.currentEpoch;
136
135
  const topicsParams: Record<string, TopicScoreParams> = {};
137
- const boundaries = getActiveForkBoundaries(config, epoch);
136
+ // Gossipsub copies the score parameters at construction, including those for future subscriptions.
137
+ const boundaries = getActiveForkBoundaries(config, eth2Context.currentEpoch, Infinity);
138
138
  const beaconAttestationSubnetWeight = 1 / ATTESTATION_SUBNET_COUNT;
139
139
  for (const boundary of boundaries) {
140
+ const currentSlot = Math.max(
141
+ eth2Context.currentSlot,
142
+ computeStartSlotAtEpoch(boundary.epoch - FORK_EPOCH_LOOKAHEAD)
143
+ );
144
+ // The node subscribes to a boundary's topics FORK_EPOCH_LOOKAHEAD epochs early, but peers only publish on
145
+ // them from the boundary epoch. Hold back the mesh delivery penalty until then, otherwise every mesh peer
146
+ // is penalized for an empty topic.
147
+ const subscribeEpoch = Math.max(eth2Context.currentEpoch, boundary.epoch - FORK_EPOCH_LOOKAHEAD);
148
+ const activationDelayMs = Math.max(0, boundary.epoch - subscribeEpoch) * epochDurationMs;
140
149
  //first all fixed topics
141
150
  topicsParams[
142
151
  stringifyGossipTopic(config, {
@@ -225,8 +234,8 @@ function getAllTopicsScoreParams(
225
234
  meshMessageInfo: {
226
235
  decaySlots: SLOTS_PER_EPOCH * 5,
227
236
  capFactor: 3,
228
- activationWindow: epochDurationMs,
229
- currentSlot: eth2Context.currentSlot,
237
+ activationWindow: activationDelayMs + epochDurationMs,
238
+ currentSlot,
230
239
  },
231
240
  });
232
241
  topicsParams[
@@ -241,8 +250,8 @@ function getAllTopicsScoreParams(
241
250
  meshMessageInfo: {
242
251
  decaySlots: SLOTS_PER_EPOCH * 5,
243
252
  capFactor: 3,
244
- activationWindow: epochDurationMs,
245
- currentSlot: eth2Context.currentSlot,
253
+ activationWindow: activationDelayMs + epochDurationMs,
254
+ currentSlot,
246
255
  },
247
256
  });
248
257
 
@@ -268,8 +277,8 @@ function getAllTopicsScoreParams(
268
277
  meshMessageInfo: {
269
278
  decaySlots: SLOTS_PER_EPOCH * 2,
270
279
  capFactor: 4,
271
- activationWindow: epochDurationMs,
272
- currentSlot: eth2Context.currentSlot,
280
+ activationWindow: activationDelayMs + epochDurationMs,
281
+ currentSlot,
273
282
  },
274
283
  });
275
284
 
@@ -280,10 +289,10 @@ function getAllTopicsScoreParams(
280
289
  meshMessageInfo: {
281
290
  decaySlots: multipleBurstsPerSubnetPerEpoch ? SLOTS_PER_EPOCH * 4 : SLOTS_PER_EPOCH * 16,
282
291
  capFactor: 16,
283
- activationWindow: multipleBurstsPerSubnetPerEpoch
284
- ? slotDurationMs * (SLOTS_PER_EPOCH / 2 + 1)
285
- : epochDurationMs,
286
- currentSlot: eth2Context.currentSlot,
292
+ activationWindow:
293
+ activationDelayMs +
294
+ (multipleBurstsPerSubnetPerEpoch ? slotDurationMs * (SLOTS_PER_EPOCH / 2 + 1) : epochDurationMs),
295
+ currentSlot,
287
296
  },
288
297
  });
289
298
  for (let subnet = 0; subnet < ATTESTATION_SUBNET_COUNT; subnet++) {