@lodestar/beacon-node 1.47.0-dev.9572bcc698 → 1.47.0-dev.9ba9a5ce85

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 (148) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +41 -10
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/lodestar/index.js +1 -1
  5. package/lib/api/impl/lodestar/index.js.map +1 -1
  6. package/lib/api/impl/validator/index.d.ts.map +1 -1
  7. package/lib/api/impl/validator/index.js +237 -49
  8. package/lib/api/impl/validator/index.js.map +1 -1
  9. package/lib/api/impl/validator/utils.js +1 -1
  10. package/lib/api/impl/validator/utils.js.map +1 -1
  11. package/lib/chain/archiveStore/archiveStore.js +1 -1
  12. package/lib/chain/archiveStore/archiveStore.js.map +1 -1
  13. package/lib/chain/blocks/index.js +7 -7
  14. package/lib/chain/blocks/index.js.map +1 -1
  15. package/lib/chain/blocks/verifyBlock.d.ts.map +1 -1
  16. package/lib/chain/blocks/verifyBlock.js +5 -2
  17. package/lib/chain/blocks/verifyBlock.js.map +1 -1
  18. package/lib/chain/chain.d.ts +5 -2
  19. package/lib/chain/chain.d.ts.map +1 -1
  20. package/lib/chain/chain.js +6 -2
  21. package/lib/chain/chain.js.map +1 -1
  22. package/lib/chain/errors/executionPayloadBid.d.ts +5 -0
  23. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  24. package/lib/chain/errors/executionPayloadBid.js +1 -0
  25. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  26. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  27. package/lib/chain/forkChoice/index.js +4 -0
  28. package/lib/chain/forkChoice/index.js.map +1 -1
  29. package/lib/chain/interface.d.ts +4 -2
  30. package/lib/chain/interface.d.ts.map +1 -1
  31. package/lib/chain/interface.js.map +1 -1
  32. package/lib/chain/opPools/executionPayloadBidPool.d.ts +7 -2
  33. package/lib/chain/opPools/executionPayloadBidPool.d.ts.map +1 -1
  34. package/lib/chain/opPools/executionPayloadBidPool.js +4 -4
  35. package/lib/chain/opPools/executionPayloadBidPool.js.map +1 -1
  36. package/lib/chain/opPools/index.d.ts +1 -1
  37. package/lib/chain/opPools/index.d.ts.map +1 -1
  38. package/lib/chain/opPools/index.js.map +1 -1
  39. package/lib/chain/prepareNextSlot.d.ts +5 -0
  40. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  41. package/lib/chain/prepareNextSlot.js +47 -6
  42. package/lib/chain/prepareNextSlot.js.map +1 -1
  43. package/lib/chain/produceBlock/computeNewStateRoot.d.ts.map +1 -1
  44. package/lib/chain/produceBlock/computeNewStateRoot.js +3 -25
  45. package/lib/chain/produceBlock/computeNewStateRoot.js.map +1 -1
  46. package/lib/chain/produceBlock/produceBlockBody.js +1 -1
  47. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  48. package/lib/chain/regen/interface.d.ts +3 -2
  49. package/lib/chain/regen/interface.d.ts.map +1 -1
  50. package/lib/chain/regen/interface.js +1 -0
  51. package/lib/chain/regen/interface.js.map +1 -1
  52. package/lib/chain/regen/queued.d.ts +2 -2
  53. package/lib/chain/regen/queued.d.ts.map +1 -1
  54. package/lib/chain/regen/queued.js +5 -5
  55. package/lib/chain/regen/queued.js.map +1 -1
  56. package/lib/chain/stateCache/fifoBlockStateCache.d.ts +5 -1
  57. package/lib/chain/stateCache/fifoBlockStateCache.d.ts.map +1 -1
  58. package/lib/chain/stateCache/fifoBlockStateCache.js +6 -0
  59. package/lib/chain/stateCache/fifoBlockStateCache.js.map +1 -1
  60. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts +47 -5
  61. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts.map +1 -1
  62. package/lib/chain/stateCache/persistentCheckpointsCache.js +117 -7
  63. package/lib/chain/stateCache/persistentCheckpointsCache.js.map +1 -1
  64. package/lib/chain/stateCache/types.d.ts +3 -3
  65. package/lib/chain/stateCache/types.d.ts.map +1 -1
  66. package/lib/chain/validation/block.d.ts.map +1 -1
  67. package/lib/chain/validation/block.js +40 -10
  68. package/lib/chain/validation/block.js.map +1 -1
  69. package/lib/chain/validation/executionPayloadBid.d.ts +15 -3
  70. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  71. package/lib/chain/validation/executionPayloadBid.js +165 -10
  72. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  73. package/lib/execution/builder/apiClient.d.ts +70 -0
  74. package/lib/execution/builder/apiClient.d.ts.map +1 -0
  75. package/lib/execution/builder/apiClient.js +202 -0
  76. package/lib/execution/builder/apiClient.js.map +1 -0
  77. package/lib/execution/builder/validateBid.d.ts +23 -0
  78. package/lib/execution/builder/validateBid.d.ts.map +1 -0
  79. package/lib/execution/builder/validateBid.js +119 -0
  80. package/lib/execution/builder/validateBid.js.map +1 -0
  81. package/lib/metrics/metrics/lodestar.d.ts +29 -1
  82. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  83. package/lib/metrics/metrics/lodestar.js +61 -3
  84. package/lib/metrics/metrics/lodestar.js.map +1 -1
  85. package/lib/network/network.d.ts.map +1 -1
  86. package/lib/network/network.js +5 -4
  87. package/lib/network/network.js.map +1 -1
  88. package/lib/network/processor/constants.d.ts +7 -0
  89. package/lib/network/processor/constants.d.ts.map +1 -0
  90. package/lib/network/processor/constants.js +7 -0
  91. package/lib/network/processor/constants.js.map +1 -0
  92. package/lib/network/processor/gossipHandlers.js +1 -1
  93. package/lib/network/processor/gossipHandlers.js.map +1 -1
  94. package/lib/network/processor/gossipQueues/indexed.d.ts.map +1 -1
  95. package/lib/network/processor/gossipQueues/indexed.js +0 -1
  96. package/lib/network/processor/gossipQueues/indexed.js.map +1 -1
  97. package/lib/network/processor/index.d.ts +3 -0
  98. package/lib/network/processor/index.d.ts.map +1 -1
  99. package/lib/network/processor/index.js +52 -23
  100. package/lib/network/processor/index.js.map +1 -1
  101. package/lib/node/nodejs.d.ts.map +1 -1
  102. package/lib/node/nodejs.js +5 -0
  103. package/lib/node/nodejs.js.map +1 -1
  104. package/lib/sync/range/chain.d.ts.map +1 -1
  105. package/lib/sync/range/chain.js +9 -2
  106. package/lib/sync/range/chain.js.map +1 -1
  107. package/lib/sync/range/range.js +1 -1
  108. package/lib/sync/range/range.js.map +1 -1
  109. package/lib/sync/unknownBlock.d.ts +6 -2
  110. package/lib/sync/unknownBlock.d.ts.map +1 -1
  111. package/lib/sync/unknownBlock.js +48 -17
  112. package/lib/sync/unknownBlock.js.map +1 -1
  113. package/package.json +15 -15
  114. package/src/api/impl/beacon/blocks/index.ts +48 -13
  115. package/src/api/impl/lodestar/index.ts +1 -1
  116. package/src/api/impl/validator/index.ts +290 -49
  117. package/src/api/impl/validator/utils.ts +1 -1
  118. package/src/chain/archiveStore/archiveStore.ts +1 -1
  119. package/src/chain/blocks/index.ts +7 -7
  120. package/src/chain/blocks/verifyBlock.ts +5 -2
  121. package/src/chain/chain.ts +8 -1
  122. package/src/chain/errors/executionPayloadBid.ts +6 -0
  123. package/src/chain/forkChoice/index.ts +4 -0
  124. package/src/chain/interface.ts +4 -2
  125. package/src/chain/opPools/executionPayloadBidPool.ts +13 -7
  126. package/src/chain/opPools/index.ts +1 -1
  127. package/src/chain/prepareNextSlot.ts +49 -6
  128. package/src/chain/produceBlock/computeNewStateRoot.ts +3 -38
  129. package/src/chain/produceBlock/produceBlockBody.ts +1 -1
  130. package/src/chain/regen/interface.ts +3 -2
  131. package/src/chain/regen/queued.ts +5 -5
  132. package/src/chain/stateCache/fifoBlockStateCache.ts +8 -1
  133. package/src/chain/stateCache/persistentCheckpointsCache.ts +133 -8
  134. package/src/chain/stateCache/types.ts +3 -3
  135. package/src/chain/validation/block.ts +43 -10
  136. package/src/chain/validation/executionPayloadBid.ts +192 -12
  137. package/src/execution/builder/apiClient.ts +264 -0
  138. package/src/execution/builder/validateBid.ts +181 -0
  139. package/src/metrics/metrics/lodestar.ts +64 -4
  140. package/src/network/network.ts +7 -4
  141. package/src/network/processor/constants.ts +6 -0
  142. package/src/network/processor/gossipHandlers.ts +1 -1
  143. package/src/network/processor/gossipQueues/indexed.ts +0 -1
  144. package/src/network/processor/index.ts +67 -30
  145. package/src/node/nodejs.ts +5 -0
  146. package/src/sync/range/chain.ts +9 -2
  147. package/src/sync/range/range.ts +1 -1
  148. package/src/sync/unknownBlock.ts +62 -18
@@ -11,14 +11,20 @@ const SLOTS_RETAINED = 2;
11
11
  type BlockRootHex = string;
12
12
  type BlockHashHex = string;
13
13
 
14
+ export type PooledExecutionPayloadBid = {
15
+ signedBid: gloas.SignedExecutionPayloadBid;
16
+ /** Time in milliseconds from the slot start when the bid was received */
17
+ receivedMs: number;
18
+ };
19
+
14
20
  /**
15
21
  * Store the best signed execution payload bid per slot / (parent block root, parent block hash).
16
22
  */
17
23
  export class ExecutionPayloadBidPool {
18
24
  private readonly bidByParentHashByParentRootBySlot = new MapDef<
19
25
  Slot,
20
- MapDef<BlockRootHex, Map<BlockHashHex, gloas.SignedExecutionPayloadBid>>
21
- >(() => new MapDef<BlockRootHex, Map<BlockHashHex, gloas.SignedExecutionPayloadBid>>(() => new Map()));
26
+ MapDef<BlockRootHex, Map<BlockHashHex, PooledExecutionPayloadBid>>
27
+ >(() => new MapDef<BlockRootHex, Map<BlockHashHex, PooledExecutionPayloadBid>>(() => new Map()));
22
28
  private lowestPermissibleSlot = 0;
23
29
 
24
30
  get size(): number {
@@ -31,7 +37,7 @@ export class ExecutionPayloadBidPool {
31
37
  return count;
32
38
  }
33
39
 
34
- add(bid: gloas.SignedExecutionPayloadBid): InsertOutcome {
40
+ add(bid: gloas.SignedExecutionPayloadBid, receivedMs: number): InsertOutcome {
35
41
  const {slot, parentBlockRoot, parentBlockHash, value} = bid.message;
36
42
  const lowestPermissibleSlot = this.lowestPermissibleSlot;
37
43
 
@@ -45,16 +51,16 @@ export class ExecutionPayloadBidPool {
45
51
  const existing = bidByParentHash.get(parentHashHex);
46
52
 
47
53
  if (existing) {
48
- const existingValue = existing.message.value;
54
+ const existingValue = existing.signedBid.message.value;
49
55
  const newValue = value;
50
56
  if (newValue > existingValue) {
51
- bidByParentHash.set(parentHashHex, bid);
57
+ bidByParentHash.set(parentHashHex, {signedBid: bid, receivedMs});
52
58
  return InsertOutcome.NewData;
53
59
  }
54
60
  return newValue === existingValue ? InsertOutcome.AlreadyKnown : InsertOutcome.NotBetterThan;
55
61
  }
56
62
 
57
- bidByParentHash.set(parentHashHex, bid);
63
+ bidByParentHash.set(parentHashHex, {signedBid: bid, receivedMs});
58
64
  return InsertOutcome.NewData;
59
65
  }
60
66
 
@@ -66,7 +72,7 @@ export class ExecutionPayloadBidPool {
66
72
  slot: Slot,
67
73
  parentBlockHash: BlockHashHex | null,
68
74
  parentBlockRoot: BlockRootHex
69
- ): gloas.SignedExecutionPayloadBid | null {
75
+ ): PooledExecutionPayloadBid | null {
70
76
  if (parentBlockHash === null) return null;
71
77
  const bidByParentHash = this.bidByParentHashByParentRootBySlot.get(slot)?.get(parentBlockRoot);
72
78
  return bidByParentHash?.get(parentBlockHash) ?? null;
@@ -1,7 +1,7 @@
1
1
  export {AggregatedAttestationPool} from "./aggregatedAttestationPool.js";
2
2
  export {AttestationPool} from "./attestationPool.js";
3
3
  export {DeferredVoluntaryExitPool} from "./deferredVoluntaryExitPool.js";
4
- export {ExecutionPayloadBidPool} from "./executionPayloadBidPool.js";
4
+ export {ExecutionPayloadBidPool, type PooledExecutionPayloadBid} from "./executionPayloadBidPool.js";
5
5
  export {OpPool} from "./opPool.js";
6
6
  export {PayloadAttestationPool} from "./payloadAttestationPool.js";
7
7
  export {ProposerPreferencesPool} from "./proposerPreferencesPool.js";
@@ -45,6 +45,14 @@ const PREPARE_EPOCH_LIMIT = 1;
45
45
  * Expressed in bps so it scales with slot duration (mainnet vs minimal/devnet). */
46
46
  const BUILDER_PREVERIFY_LIMIT_BPS = 2000;
47
47
 
48
+ /**
49
+ * How far before the next slot builder connections are pre-established, see `checkBuilderStatusBeforeSlot`.
50
+ *
51
+ * 1667 = 16.67% of slot (2s on mainnet). Must stay under the few seconds an idle connection survives,
52
+ * while leaving room for a round trip to a distant builder to complete before the slot begins.
53
+ */
54
+ const BUILDER_STATUS_CHECK_BEFORE_SLOT_BPS = 1667;
55
+
48
56
  /**
49
57
  * At Bellatrix, if we are responsible for proposing in next slot, we want to prepare payload
50
58
  * 4s before the start of next slot at PREPARE_NEXT_SLOT_BPS of the current slot.
@@ -151,25 +159,41 @@ export class PrepareNextSlotScheduler {
151
159
  const proposerIndex = await getProposerIndex();
152
160
  feeRecipient = this.chain.beaconProposerCache.get(proposerIndex);
153
161
 
154
- if (feeRecipient) {
155
- // If we are proposing next slot, we need to predict if we can proposer-boost-reorg or not
156
- const proposerHead = this.chain.predictProposerHead(clockSlot);
162
+ // Predict the proposer head of the next slot when either:
163
+ // - we are proposing the next slot (single-slot proposer-boost-reorg), or
164
+ // - this is an epoch transition: post-Fulu the next proposer may reorg a weak
165
+ // last-block-of-epoch and build slot 0 on the strong parent (epoch-boundary reorg),
166
+ // so we should dial the strong parent through the boundary instead of the weak head.
167
+ if (feeRecipient || isEpochTransition) {
168
+ const proposerHead = this.chain.predictProposerHead();
157
169
  const {slot: proposerHeadSlot, blockRoot: proposerHeadRoot} = proposerHead;
158
170
 
159
- // If we predict we can reorg, we build on the proposer head (parent) block instead
171
+ // If we predict a reorg, we build the epoch transition on the proposer head (parent) instead
160
172
  if (proposerHeadRoot !== headRoot || proposerHeadSlot !== headSlot) {
161
- this.logger.verbose("Weak head detected. May build on parent block instead", {
173
+ // feeRecipient set => WE propose the next slot and may reorg it out ourselves;
174
+ // otherwise it's a predicted reorg by another proposer (epoch-boundary reorg).
175
+ const logMessage = feeRecipient
176
+ ? "Weak head detected. We may build on parent block instead"
177
+ : "Weak head detected. Another proposer may build on parent block instead";
178
+ this.logger.verbose(logMessage, {
162
179
  proposerHeadSlot,
163
180
  proposerHeadRoot,
164
181
  headSlot,
165
182
  headRoot,
183
+ isEpochTransition,
166
184
  });
167
185
  this.metrics?.weakHeadDetected.inc();
186
+ if (isEpochTransition) {
187
+ this.metrics?.precomputeNextEpochTransition.predictedReorg.inc();
188
+ }
168
189
  updatedHead = proposerHead;
169
190
  }
191
+ }
170
192
 
193
+ if (feeRecipient) {
171
194
  if (isForkPostGloas(fork)) {
172
195
  this.chain.builderCircuitBreaker.update(clockSlot, updatedHead);
196
+ this.checkBuilderStatusBeforeSlot(prepareSlot);
173
197
  } else {
174
198
  // Update the builder status, if enabled shoot an api call to check status
175
199
  this.chain.updateBuilderStatus(clockSlot);
@@ -182,6 +206,7 @@ export class PrepareNextSlotScheduler {
182
206
  }
183
207
 
184
208
  // post-fulu we'll always reach here because preparedState is undefined
209
+ // we may run epoch transition not with headBlock if it's weak
185
210
  if (preparedState === undefined || updatedHead !== headBlock) {
186
211
  preparedState = await this.chain.regen.getBlockSlotState(
187
212
  updatedHead,
@@ -280,7 +305,7 @@ export class PrepareNextSlotScheduler {
280
305
  // + if next slot is a skipped slot, it'd help getting target checkpoint state faster to validate attestations
281
306
  if (isEpochTransition) {
282
307
  this.metrics?.precomputeNextEpochTransition.count.inc({result: "success"}, 1);
283
- const previousHits = this.chain.regen.updatePreComputedCheckpoint(headRoot, nextEpoch);
308
+ const previousHits = this.chain.regen.updatePreComputedCheckpoint(updatedHead.blockRoot, nextEpoch);
284
309
  if (previousHits === 0) {
285
310
  this.metrics?.precomputeNextEpochTransition.waste.inc();
286
311
  }
@@ -289,6 +314,8 @@ export class PrepareNextSlotScheduler {
289
314
  this.logger.verbose("Completed PrepareNextSlotScheduler epoch transition", {
290
315
  nextEpoch,
291
316
  headSlot,
317
+ headRoot,
318
+ updatedHeadRoot: updatedHead.blockRoot,
292
319
  prepareSlot,
293
320
  previousHits,
294
321
  durationMs: Date.now() - start,
@@ -372,6 +399,22 @@ export class PrepareNextSlotScheduler {
372
399
  }
373
400
  };
374
401
 
402
+ /**
403
+ * Pre-establish the builder connections so the handshake lands outside the bid deadline. Scheduled
404
+ * later in the slot, connecting at PREPARE_NEXT_SLOT_BPS would go cold before bids are requested.
405
+ */
406
+ private checkBuilderStatusBeforeSlot(prepareSlot: Slot): void {
407
+ const msBeforeSlot = this.config.getSlotComponentDurationMs(BUILDER_STATUS_CHECK_BEFORE_SLOT_BPS);
408
+ const msUntilCheck = -this.chain.clock.msFromSlot(prepareSlot) - msBeforeSlot;
409
+ sleep(Math.max(0, msUntilCheck), this.signal)
410
+ .then(() => this.chain.builderApiClient.checkStatus())
411
+ .catch((e) => {
412
+ if (!isErrorAborted(e)) {
413
+ this.logger.debug("Failed to check builder status", {prepareSlot}, e as Error);
414
+ }
415
+ });
416
+ }
417
+
375
418
  computeStateHashTreeRoot(state: IBeaconStateView, isEpochTransition: boolean): void {
376
419
  // cache HashObjects for faster hashTreeRoot() later, especially for computeNewStateRoot() if we need to produce a block at slot 0 of epoch
377
420
  // see https://github.com/ChainSafe/lodestar/issues/6194
@@ -1,11 +1,5 @@
1
- import {
2
- DataAvailabilityStatus,
3
- ExecutionPayloadStatus,
4
- IBeaconStateView,
5
- StateHashTreeRootSource,
6
- } from "@lodestar/state-transition";
1
+ import {EMPTY_SIGNATURE, IBeaconStateView} from "@lodestar/state-transition";
7
2
  import {BeaconBlock, BlindedBeaconBlock, Gwei, Root} from "@lodestar/types";
8
- import {ZERO_HASH} from "../../constants/index.js";
9
3
  import {Metrics} from "../../metrics/index.js";
10
4
 
11
5
  /**
@@ -19,35 +13,6 @@ export function computeNewStateRoot(
19
13
  block: BeaconBlock | BlindedBeaconBlock
20
14
  ): {newStateRoot: Root; proposerReward: Gwei; postState: IBeaconStateView} {
21
15
  // Set signature to zero to re-use stateTransition() function which requires the SignedBeaconBlock type
22
- const blockEmptySig = {message: block, signature: ZERO_HASH};
23
-
24
- const postState = state.stateTransition(
25
- blockEmptySig,
26
- {
27
- // ExecutionPayloadStatus.valid: Assume payload valid, it has been produced by a trusted EL
28
- executionPayloadStatus: ExecutionPayloadStatus.valid,
29
- // DataAvailabilityStatus.available: Assume the blobs to be available, have just been produced by trusted EL
30
- dataAvailabilityStatus: DataAvailabilityStatus.Available,
31
- // verifyStateRoot: false | the root in the block is zero-ed, it's being computed here
32
- verifyStateRoot: false,
33
- // verifyProposer: false | as the block signature is zero-ed
34
- verifyProposer: false,
35
- // verifySignatures: false | since the data to assemble the block is trusted
36
- verifySignatures: false,
37
- // Preserve cache in source state, since the resulting state is not added to the state cache
38
- dontTransferCache: true,
39
- },
40
- {metrics}
41
- );
42
-
43
- const {attestations, syncAggregate, slashing} = postState.proposerRewards;
44
- const proposerReward = BigInt(attestations + syncAggregate + slashing);
45
-
46
- const hashTreeRootTimer = metrics?.stateHashTreeRootTime.startTimer({
47
- source: StateHashTreeRootSource.computeNewStateRoot,
48
- });
49
- const newStateRoot = postState.hashTreeRoot();
50
- hashTreeRootTimer?.();
51
-
52
- return {newStateRoot, proposerReward, postState};
16
+ const signedBlock = {message: block, signature: EMPTY_SIGNATURE};
17
+ return state.computeNewStateRoot({block: signedBlock}, {metrics});
53
18
  }
@@ -241,7 +241,7 @@ export async function produceBlockBody<T extends BlockType>(
241
241
  const parentExecutionRequests = isExtendingPayload
242
242
  ? await this.getParentExecutionRequests(parentBlock.slot, parentBlock.blockRoot)
243
243
  : ssz.gloas.ExecutionRequests.defaultValue();
244
- executionPayloadValue = BigInt(builderBid.message.value) * GWEI_TO_WEI;
244
+ executionPayloadValue = (BigInt(builderBid.message.value) + builderBid.message.executionPayment) * GWEI_TO_WEI;
245
245
 
246
246
  const commonBlockBody = await commonBlockBodyPromise;
247
247
  const gloasBody = Object.assign({}, commonBlockBody) as gloas.BeaconBlockBody;
@@ -24,6 +24,7 @@ export enum RegenCaller {
24
24
  validateApiVoluntaryExit = "validateApiVoluntaryExit",
25
25
  publishDeferredVoluntaryExits = "publishDeferredVoluntaryExits",
26
26
  validateGossipExecutionPayloadBid = "validateGossipExecutionPayloadBid",
27
+ validateApiExecutionPayloadBid = "validateApiExecutionPayloadBid",
27
28
  validateGossipPayloadAttestationMessage = "validateGossipPayloadAttestationMessage",
28
29
  validateGossipProposerPreferences = "validateGossipProposerPreferences",
29
30
  onForkChoiceFinalized = "onForkChoiceFinalized",
@@ -41,14 +42,14 @@ export type StateRegenerationOpts = {
41
42
  };
42
43
 
43
44
  export interface IStateRegenerator extends IStateRegeneratorInternal {
44
- dropCache(): void;
45
+ dropCache(): Promise<void>;
45
46
  dumpCacheSummary(): routes.lodestar.StateCacheItem[];
46
47
  getStateSync(stateRoot: RootHex): IBeaconStateView | null;
47
48
  getPreStateSync(block: BeaconBlock): IBeaconStateView | null;
48
49
  getCheckpointStateOrBytes(cp: CheckpointHex): Promise<IBeaconStateView | Uint8Array | null>;
49
50
  getCheckpointStateSync(cp: CheckpointHex): IBeaconStateView | null;
50
51
  getClosestHeadState(head: ProtoBlock): IBeaconStateView | null;
51
- pruneOnCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch, headStateRoot: RootHex): void;
52
+ onCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch, headStateRoot: RootHex): void;
52
53
  processState(blockRootHex: RootHex, postState: IBeaconStateView): void;
53
54
  addCheckpointState(cp: phase0.Checkpoint, item: IBeaconStateView): void;
54
55
  updateHeadState(newHead: ProtoBlock, maybeHeadState: IBeaconStateView): void;
@@ -67,9 +67,9 @@ export class QueuedStateRegenerator implements IStateRegenerator {
67
67
  return this.jobQueue.jobLen < REGEN_CAN_ACCEPT_WORK_THRESHOLD;
68
68
  }
69
69
 
70
- dropCache(): void {
70
+ async dropCache(): Promise<void> {
71
71
  this.blockStateCache.clear();
72
- this.checkpointStateCache.clear();
72
+ await this.checkpointStateCache.clear();
73
73
  }
74
74
 
75
75
  dumpCacheSummary(): routes.lodestar.StateCacheItem[] {
@@ -138,9 +138,9 @@ export class QueuedStateRegenerator implements IStateRegenerator {
138
138
  return this.checkpointStateCache.getLatest(head.blockRoot, Infinity) || this.blockStateCache.get(head.stateRoot);
139
139
  }
140
140
 
141
- pruneOnCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch, headStateRoot: RootHex): void {
142
- this.checkpointStateCache.prune(finalizedEpoch, justifiedEpoch);
143
- this.blockStateCache.prune(headStateRoot);
141
+ onCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch, headStateRoot: RootHex): void {
142
+ this.checkpointStateCache.onCheckpoint(finalizedEpoch, justifiedEpoch);
143
+ this.blockStateCache.onCheckpoint(headStateRoot);
144
144
  }
145
145
 
146
146
  processState(blockRootHex: RootHex, postState: IBeaconStateView): void {
@@ -144,13 +144,20 @@ export class FIFOBlockStateCache implements BlockStateCache {
144
144
  return this.cache.size;
145
145
  }
146
146
 
147
+ /**
148
+ * On a checkpoint event, prune the cache while keeping the head state.
149
+ */
150
+ onCheckpoint(headStateRootHex: string): void {
151
+ this.prune(headStateRootHex);
152
+ }
153
+
147
154
  /**
148
155
  * Prune the cache from tail to keep the most recent n states consistently.
149
156
  * The tail of the list is the oldest state, in case regen adds back the same state,
150
157
  * it should stay next to head so that it won't be pruned right away.
151
158
  * The FIFO cache helps with this.
152
159
  */
153
- prune(lastAddedKey: string): void {
160
+ private prune(lastAddedKey: string): void {
154
161
  while (this.keyOrder.length > this.maxStates) {
155
162
  const key = this.keyOrder.last();
156
163
  // it does not make sense to prune the last added state
@@ -14,7 +14,11 @@ import {BlockStateCache, CacheItemType, CheckpointHex, CheckpointStateCache} fro
14
14
  export type PersistentCheckpointStateCacheOpts = {
15
15
  /** Keep max n state epochs in memory, persist the rest to disk */
16
16
  maxCPStateEpochsInMemory?: number;
17
- /** Keep max n state epochs on disk */
17
+ /**
18
+ * On-disk retention of persisted checkpoint states. Selects one of two modes:
19
+ * - `Infinity` (default) -> tiered retention mode
20
+ * - any finite `n` (>= 0) -> legacy flat retention (keep the last n dense epochs)
21
+ */
18
22
  maxCPStateEpochsOnDisk?: number;
19
23
  };
20
24
 
@@ -64,6 +68,18 @@ export const DEFAULT_MAX_CP_STATE_EPOCHS_IN_MEMORY = 3;
64
68
  */
65
69
  export const DEFAULT_MAX_CP_STATE_ON_DISK = Infinity;
66
70
 
71
+ // CP_STATE_TIER_BASE = spacing multiplier per tier AND per-tier capacity. Deciding capacity == base
72
+ // so that a full tier[n] always holds exactly ONE epoch aligned to tier[n+1]
73
+ // given tier[n] has span = 16 ^ n and tier[n+1] has span = 16 ^ (n+1)
74
+ // why 16?
75
+ // - tier 0 is the dense hot-regen window; it must exceed regen's MAX_EPOCH_TO_PROCESS (=5).
76
+ // - with a full 4 tiers = 64 epochs, we can cover ~ a year of continuous non-finality, and it'll grow very slowly after that
77
+ // - tier0 spans 16 epochs ≈ 1.7h, this is more than enough to handle reorg
78
+ // - tier1 spans 256 epochs ≈ 1.1d, ie we store 16 epochs of the previous day
79
+ // - tier2 spans 4096 epochs ≈ 18d, ie we store 16 epochs of the last ~2.5 weeks
80
+ // - tier3 spans 65536ep ≈ 291d, ie we store 16 epochs of the last 0.8 year
81
+ export const CP_STATE_TIER_BASE = 16;
82
+
67
83
  // TODO GLOAS: re-evaluate this timing
68
84
  const PROCESS_CHECKPOINT_STATES_BPS = 6667;
69
85
 
@@ -112,6 +128,19 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
112
128
  private preComputedCheckpointHits: number | null = null;
113
129
  private readonly maxEpochsInMemory: number;
114
130
  private readonly maxEpochsOnDisk: number;
131
+ /**
132
+ * Persist checkpoint states (epoch + root) by tiers
133
+ *
134
+ * ╔═════════ tier 2 ══════════╦═══════ tier 1 ═══════╦═══ tier 0 (dense) ══╗
135
+ * finalizedEpoch -> ║ keep 1 epoch per 256 ║ keep 1 epoch per 16 ║ keep every epoch ║ -> head
136
+ * ║ x·······x·······x······ ║ x···x···x···x··· ║ xxxxxxxxxxxxxxxxx ║
137
+ * ╚═══════════════════════════╩══════════════════════╩═════════════════════╝
138
+ *
139
+ * starting from tier 1, all epochs must be aligned to the finalized epoch
140
+ */
141
+ private persistentTiers: Map<Epoch, Set<RootHex>>[] = [new Map()];
142
+ private finalizedEpoch: Epoch = 0;
143
+ private justifiedEpoch: Epoch = 0;
115
144
  private readonly datastore: CPStateDatastore;
116
145
  private readonly blockStateCache: BlockStateCache;
117
146
  private readonly bufferPool?: BufferPool;
@@ -152,6 +181,13 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
152
181
  metrics.cpStateCache.size.set({type: CacheItemType.inMemory}, inMemoryCount);
153
182
  metrics.cpStateCache.epochSize.set({type: CacheItemType.persisted}, persistentEpochs.size);
154
183
  metrics.cpStateCache.epochSize.set({type: CacheItemType.inMemory}, memoryEpochs.size);
184
+
185
+ for (let tier = 0; tier < this.persistentTiers.length; tier++) {
186
+ let states = 0;
187
+ for (const roots of this.persistentTiers[tier].values()) states += roots.size;
188
+ metrics.cpStateCache.persistentTierEpochs.set({tier}, this.persistentTiers[tier].size);
189
+ metrics.cpStateCache.persistentTierStates.set({tier}, states);
190
+ }
155
191
  });
156
192
  }
157
193
  this.logger = logger;
@@ -407,10 +443,77 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
407
443
  }
408
444
 
409
445
  /**
410
- * This is just to conform to the old implementation
446
+ * This is called on every checkpoint event to refresh the pinned finalized/justified epochs.
411
447
  */
412
- prune(): void {
413
- // do nothing
448
+ onCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch): void {
449
+ this.finalizedEpoch = finalizedEpoch;
450
+ this.justifiedEpoch = justifiedEpoch;
451
+ }
452
+
453
+ /**
454
+ * This is called right after we persist a checkpoint state.
455
+ */
456
+ private async onPersist(epoch: Epoch, rootHex: RootHex): Promise<void> {
457
+ let roots = this.persistentTiers[0].get(epoch);
458
+ if (roots === undefined) {
459
+ roots = new Set<RootHex>();
460
+ this.persistentTiers[0].set(epoch, roots);
461
+ }
462
+ roots.add(rootHex);
463
+ await this.prunePersistentTier(0);
464
+ }
465
+
466
+ /**
467
+ * When tier `n` overflows (> CP_STATE_TIER_BASE epochs), evict its oldest epoch and either promote it to tier `n + 1` (if aligned there) or delete it.
468
+ *
469
+ * before: persistentTiers[n] = { ..., e_old }
470
+ * persistentTiers[n+1] = { ... }
471
+ *
472
+ * after, if e_old aligns to n+1: | after, if e_old does NOT align to n+1:
473
+ * persistentTiers[n] = { ... } | persistentTiers[n] = { ... }
474
+ * persistentTiers[n+1] = { ..., e_old } | e_old and all its roots deleted from disk
475
+ *
476
+ * Since pruning a tier[n] may push an item at tier[n+1], we must call the function recursively.
477
+ */
478
+ private async prunePersistentTier(tier: number): Promise<void> {
479
+ const tierMap = this.persistentTiers[tier];
480
+ while (tierMap.size > CP_STATE_TIER_BASE) {
481
+ // Evict the oldest epoch, but never the pinned justified epoch
482
+ const oldestEpoch = Math.min(...Array.from(tierMap.keys()).filter((epoch) => epoch !== this.justifiedEpoch));
483
+ const roots = tierMap.get(oldestEpoch) as Set<RootHex>;
484
+ tierMap.delete(oldestEpoch);
485
+
486
+ const rootHexes = Array.from(roots).join(",");
487
+ // `>= finalizedEpoch` guards the transient window where an epoch below the (fork-choice)
488
+ // finalized epoch has not yet been removed by pruneFinalized: its offset would be negative
489
+ // and JS `%` could spuriously report it as aligned. Such epochs are stale -> delete.
490
+ if (oldestEpoch >= this.finalizedEpoch && this.alignedForTier(oldestEpoch, tier + 1)) {
491
+ if (this.persistentTiers[tier + 1] === undefined) {
492
+ this.persistentTiers[tier + 1] = new Map<Epoch, Set<RootHex>>();
493
+ }
494
+ this.persistentTiers[tier + 1].set(oldestEpoch, roots);
495
+ this.logger.verbose("Migrated persistent checkpoint states to lower tier", {
496
+ epoch: oldestEpoch,
497
+ fromTier: tier,
498
+ toTier: tier + 1,
499
+ rootHexes,
500
+ });
501
+ await this.prunePersistentTier(tier + 1);
502
+ } else {
503
+ // the oldest epoch is not aligned to the next tier
504
+ await this.deleteAllEpochItems(oldestEpoch)
505
+ .then(() => this.logger.verbose("Pruned checkpoint states from disk", {epoch: oldestEpoch, tier, rootHexes}))
506
+ .catch((e) => this.logger.debug("Error delete all epoch items", {epoch: oldestEpoch, tier}, e as Error));
507
+ }
508
+ }
509
+ }
510
+
511
+ /**
512
+ * Starting from tier[1], it must be aligned to the finalized epoch
513
+ * ie given finalized epoch F, tier[n] only epochs of F + n*16, n = 1,2,3...
514
+ */
515
+ private alignedForTier(epoch: Epoch, tier: number): boolean {
516
+ return (epoch - this.finalizedEpoch) % CP_STATE_TIER_BASE ** tier === 0;
414
517
  }
415
518
 
416
519
  /**
@@ -598,9 +701,16 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
598
701
  return seedBlockState;
599
702
  }
600
703
 
601
- clear(): void {
602
- this.cache.clear();
603
- this.epochIndex.clear();
704
+ async clear(): Promise<void> {
705
+ // deleteAllEpochItems removes every root of an epoch from disk and clears the cache
706
+ await Promise.all(
707
+ Array.from(this.epochIndex.keys()).map((epoch) =>
708
+ this.deleteAllEpochItems(epoch).catch((e) =>
709
+ this.logger.debug("Error delete all epoch items on clear", {epoch}, e as Error)
710
+ )
711
+ )
712
+ );
713
+ this.persistentTiers = [new Map()];
604
714
  }
605
715
 
606
716
  /** ONLY FOR DEBUGGING PURPOSES. For lodestar debug API */
@@ -743,12 +853,18 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
743
853
  }
744
854
  // overwrite cpKey, this means the state is deleted from memory
745
855
  this.cache.set(cpKey, {type: CacheItemType.persisted, value: persistedKey});
856
+ if (this.isTieredMode) {
857
+ await this.onPersist(epoch, rootHex);
858
+ }
746
859
  } else {
747
860
  if (persistedKey) {
748
861
  // persisted file will be eventually deleted by the archive task
749
862
  // this also means the state is deleted from memory
750
863
  this.cache.set(cpKey, {type: CacheItemType.persisted, value: persistedKey});
751
864
  // do not update epochIndex
865
+ if (this.isTieredMode) {
866
+ await this.onPersist(epoch, rootHex);
867
+ }
752
868
  } else {
753
869
  // delete the state from memory
754
870
  this.cache.delete(cpKey);
@@ -790,6 +906,10 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
790
906
  this.cache.delete(key);
791
907
  }
792
908
  this.epochIndex.delete(epoch);
909
+ // keep the on-disk retention tiers in sync so they never drift from epochIndex
910
+ for (const tierMap of this.persistentTiers) {
911
+ tierMap.delete(epoch);
912
+ }
793
913
  this.logger.verbose("Pruned checkpoint states for epoch", {
794
914
  epoch,
795
915
  persistCount,
@@ -798,7 +918,7 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
798
918
  }
799
919
 
800
920
  /**
801
- * Prune persisted checkpoint states from disk.
921
+ * Legacy flat-window on-disk pruning, used only when a `maxEpochsOnDisk` is configured.
802
922
  * Note that this should handle all possible errors and not throw.
803
923
  */
804
924
  private prunePersistedStates(): void {
@@ -842,6 +962,11 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
842
962
 
843
963
  return null;
844
964
  }
965
+
966
+ /** Tiered pruning is active with the default `Infinity` on-disk cap; a finite cap uses the flat path */
967
+ private get isTieredMode(): boolean {
968
+ return this.maxEpochsOnDisk === Infinity;
969
+ }
845
970
  }
846
971
 
847
972
  export function toCheckpointHex(checkpoint: phase0.Checkpoint): CheckpointHex {
@@ -29,7 +29,7 @@ export interface BlockStateCache {
29
29
  getSeedState(): IBeaconStateView;
30
30
  clear(): void;
31
31
  size: number;
32
- prune(headStateRootHex: RootHex): void;
32
+ onCheckpoint(headStateRootHex: RootHex): void;
33
33
  dumpSummary(): routes.lodestar.StateCacheItem[];
34
34
  /** Expose beacon states stored in cache. Use with caution */
35
35
  getStates(): IterableIterator<IBeaconStateView>;
@@ -65,9 +65,9 @@ export interface CheckpointStateCache {
65
65
  getLatest(rootHex: RootHex, maxEpoch: Epoch): IBeaconStateView | null;
66
66
  getOrReloadLatest(rootHex: RootHex, maxEpoch: Epoch): Promise<IBeaconStateView | null>;
67
67
  updatePreComputedCheckpoint(rootHex: RootHex, epoch: Epoch): number | null;
68
- prune(finalizedEpoch: Epoch, justifiedEpoch: Epoch): void;
68
+ onCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch): void;
69
69
  processState(blockRootHex: RootHex, state: IBeaconStateView): Promise<number>;
70
- clear(): void;
70
+ clear(): Promise<void>;
71
71
  dumpSummary(): routes.lodestar.StateCacheItem[];
72
72
  /** Expose beacon states stored in cache. Use with caution */
73
73
  getStates(): IterableIterator<IBeaconStateView>;
@@ -12,6 +12,7 @@ import {
12
12
  MAX_PROPOSER_SLASHINGS,
13
13
  MAX_VOLUNTARY_EXITS,
14
14
  MAX_WITHDRAWAL_REQUESTS_PER_PAYLOAD,
15
+ MIN_SEED_LOOKAHEAD,
15
16
  isForkPostBellatrix,
16
17
  isForkPostDeneb,
17
18
  isForkPostGloas,
@@ -249,26 +250,58 @@ export async function validateGossipBlock(
249
250
  // This requires execution engine integration to verify the parent block hash
250
251
  }
251
252
 
252
- // use getPreState to reload state if needed. It also checks for whether the current finalized checkpoint is an ancestor of the block.
253
- // As a result, we throw an IGNORE (whereas the spec says we should REJECT for this scenario).
253
+ // For gossip forwarding we only need the state to check the block's proposer index.
254
+ // If the state cannot be regenerated we throw an IGNORE (whereas the spec says we should REJECT for the
255
+ // finalized-ancestor scenario, which is already guarded by the parentBlock lookup above).
254
256
  // this is something we should change this in the future to make the code airtight to the spec.
255
257
  // [IGNORE] The block's parent (defined by block.parent_root) has been seen (via both gossip and non-gossip sources) (a client MAY queue blocks for processing once the parent block is retrieved).
256
258
  // [REJECT] The block's parent (defined by block.parent_root) passes validation.
257
- const blockState = await chain.regen
258
- .getPreState(block, {dontTransferCache: true}, RegenCaller.validateGossipBlock)
259
- .catch(() => {
260
- throw new BlockGossipError(GossipAction.IGNORE, {code: BlockErrorCode.PARENT_BLOCK_UNKNOWN, parentRoot});
259
+ const canUseParentState = blockEpoch - computeEpochAtSlot(parentBlock.slot) <= MIN_SEED_LOOKAHEAD;
260
+
261
+ const getValidationState = async () => {
262
+ const getPreState = () =>
263
+ chain.regen.getPreState(block, {dontTransferCache: true}, RegenCaller.validateGossipBlock);
264
+ if (canUseParentState) {
265
+ try {
266
+ const parentState = await chain.regen.getState(parentBlock.stateRoot, RegenCaller.validateGossipBlock);
267
+ chain.metrics?.gossipBlock.preStateSource.inc({source: "parentState"});
268
+ return parentState;
269
+ } catch {
270
+ // if parent state is not in memory, we fall back to disk reload / dial-forward
271
+ chain.metrics?.gossipBlock.preStateSource.inc({source: "fallbackPreState"});
272
+ chain.logger.debug("Parent state not in memory, falling back to getPreState for gossip block validation", {
273
+ slot: blockSlot,
274
+ root: blockRoot,
275
+ parentSlot: parentBlock.slot,
276
+ parentRoot,
277
+ });
278
+ return getPreState();
279
+ }
280
+ }
281
+ // parent is >1 epoch behind (deep skip) → beyond proposer-lookahead range, must dial forward
282
+ chain.metrics?.gossipBlock.preStateSource.inc({source: "preState"});
283
+ chain.logger.debug("Cannot use parent state for gossip block validation, dialing forward via getPreState", {
284
+ slot: blockSlot,
285
+ root: blockRoot,
286
+ parentSlot: parentBlock.slot,
287
+ parentRoot,
261
288
  });
289
+ return getPreState();
290
+ };
291
+
292
+ const state = await getValidationState().catch(() => {
293
+ throw new BlockGossipError(GossipAction.IGNORE, {code: BlockErrorCode.PARENT_BLOCK_UNKNOWN, parentRoot});
294
+ });
262
295
 
263
296
  // in forky condition, make sure to populate ShufflingCache with regened state
264
- chain.shufflingCache.processState(blockState);
297
+ chain.shufflingCache.processState(state);
265
298
 
266
299
  // [REJECT] The block's execution payload timestamp is correct with respect to the slot
267
300
  // -- i.e. execution_payload.timestamp == compute_timestamp_at_slot(state, block.slot).
268
301
  if (isForkPostBellatrix(fork) && !isForkPostGloas(fork)) {
269
302
  if (!isExecutionBlockBodyType(block.body)) throw Error("Not execution block body type");
270
303
  const executionPayload = block.body.executionPayload;
271
- if (isStatePostBellatrix(blockState) && blockState.isExecutionStateType && blockState.isExecutionEnabled(block)) {
304
+ if (isStatePostBellatrix(state) && state.isExecutionStateType && state.isExecutionEnabled(block)) {
272
305
  const expectedTimestamp = computeTimeAtSlot(config, blockSlot, chain.genesisTime);
273
306
  if (executionPayload.timestamp !== computeTimeAtSlot(config, blockSlot, chain.genesisTime)) {
274
307
  throw new BlockGossipError(GossipAction.REJECT, {
@@ -281,7 +314,7 @@ export async function validateGossipBlock(
281
314
  }
282
315
 
283
316
  // [REJECT] The proposer index is a valid validator index
284
- if (proposerIndex >= blockState.validatorCount) {
317
+ if (proposerIndex >= state.validatorCount) {
285
318
  throw new BlockGossipError(GossipAction.REJECT, {code: BlockErrorCode.UNKNOWN_PROPOSER, proposerIndex});
286
319
  }
287
320
 
@@ -293,7 +326,7 @@ export async function validateGossipBlock(
293
326
  // shuffling (defined by parent_root/slot). If the proposer_index cannot immediately be verified against the expected
294
327
  // shuffling, the block MAY be queued for later processing while proposers for the block's branch are calculated --
295
328
  // in such a case do not REJECT, instead IGNORE this message.
296
- if (blockState.getBeaconProposer(blockSlot) !== proposerIndex) {
329
+ if (state.getBeaconProposer(blockSlot) !== proposerIndex) {
297
330
  throw new BlockGossipError(GossipAction.REJECT, {code: BlockErrorCode.INCORRECT_PROPOSER, proposerIndex});
298
331
  }
299
332