@lodestar/beacon-node 1.39.0 → 1.40.0-dev.3715a82f3f

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 (171) hide show
  1. package/lib/api/impl/beacon/state/utils.d.ts +2 -7
  2. package/lib/api/impl/beacon/state/utils.d.ts.map +1 -1
  3. package/lib/api/impl/beacon/state/utils.js +0 -12
  4. package/lib/api/impl/beacon/state/utils.js.map +1 -1
  5. package/lib/api/impl/config/constants.d.ts +3 -0
  6. package/lib/api/impl/config/constants.d.ts.map +1 -1
  7. package/lib/api/impl/config/constants.js +5 -1
  8. package/lib/api/impl/config/constants.js.map +1 -1
  9. package/lib/api/impl/lodestar/index.js +1 -1
  10. package/lib/api/impl/lodestar/index.js.map +1 -1
  11. package/lib/api/impl/proof/index.d.ts.map +1 -1
  12. package/lib/api/impl/proof/index.js +1 -2
  13. package/lib/api/impl/proof/index.js.map +1 -1
  14. package/lib/api/impl/validator/index.d.ts.map +1 -1
  15. package/lib/api/impl/validator/index.js +1 -3
  16. package/lib/api/impl/validator/index.js.map +1 -1
  17. package/lib/chain/archiveStore/historicalState/getHistoricalState.d.ts.map +1 -1
  18. package/lib/chain/archiveStore/historicalState/getHistoricalState.js +5 -3
  19. package/lib/chain/archiveStore/historicalState/getHistoricalState.js.map +1 -1
  20. package/lib/chain/archiveStore/utils/archiveBlocks.d.ts.map +1 -1
  21. package/lib/chain/archiveStore/utils/archiveBlocks.js +19 -14
  22. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  23. package/lib/chain/blocks/importBlock.d.ts.map +1 -1
  24. package/lib/chain/blocks/importBlock.js +12 -3
  25. package/lib/chain/blocks/importBlock.js.map +1 -1
  26. package/lib/chain/blocks/verifyBlock.d.ts.map +1 -1
  27. package/lib/chain/blocks/verifyBlock.js +8 -1
  28. package/lib/chain/blocks/verifyBlock.js.map +1 -1
  29. package/lib/chain/blocks/verifyBlocksStateTransitionOnly.d.ts.map +1 -1
  30. package/lib/chain/blocks/verifyBlocksStateTransitionOnly.js +1 -0
  31. package/lib/chain/blocks/verifyBlocksStateTransitionOnly.js.map +1 -1
  32. package/lib/chain/chain.d.ts +3 -2
  33. package/lib/chain/chain.d.ts.map +1 -1
  34. package/lib/chain/chain.js +16 -6
  35. package/lib/chain/chain.js.map +1 -1
  36. package/lib/chain/initState.d.ts +1 -1
  37. package/lib/chain/initState.d.ts.map +1 -1
  38. package/lib/chain/initState.js +5 -3
  39. package/lib/chain/initState.js.map +1 -1
  40. package/lib/chain/interface.d.ts +2 -2
  41. package/lib/chain/interface.d.ts.map +1 -1
  42. package/lib/chain/lightClient/proofs.d.ts.map +1 -1
  43. package/lib/chain/lightClient/proofs.js +0 -2
  44. package/lib/chain/lightClient/proofs.js.map +1 -1
  45. package/lib/chain/opPools/aggregatedAttestationPool.d.ts +5 -9
  46. package/lib/chain/opPools/aggregatedAttestationPool.d.ts.map +1 -1
  47. package/lib/chain/opPools/aggregatedAttestationPool.js +12 -141
  48. package/lib/chain/opPools/aggregatedAttestationPool.js.map +1 -1
  49. package/lib/chain/opPools/opPool.js +5 -8
  50. package/lib/chain/opPools/opPool.js.map +1 -1
  51. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  52. package/lib/chain/prepareNextSlot.js +4 -7
  53. package/lib/chain/prepareNextSlot.js.map +1 -1
  54. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  55. package/lib/chain/produceBlock/produceBlockBody.js +1 -1
  56. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  57. package/lib/chain/regen/interface.d.ts +1 -5
  58. package/lib/chain/regen/interface.d.ts.map +1 -1
  59. package/lib/chain/regen/queued.d.ts +4 -7
  60. package/lib/chain/regen/queued.d.ts.map +1 -1
  61. package/lib/chain/regen/queued.js +15 -25
  62. package/lib/chain/regen/queued.js.map +1 -1
  63. package/lib/chain/regen/regen.d.ts +1 -1
  64. package/lib/chain/regen/regen.d.ts.map +1 -1
  65. package/lib/chain/regen/regen.js +13 -17
  66. package/lib/chain/regen/regen.js.map +1 -1
  67. package/lib/chain/shufflingCache.d.ts +16 -11
  68. package/lib/chain/shufflingCache.d.ts.map +1 -1
  69. package/lib/chain/shufflingCache.js +47 -41
  70. package/lib/chain/shufflingCache.js.map +1 -1
  71. package/lib/chain/stateCache/blockStateCacheImpl.d.ts +1 -2
  72. package/lib/chain/stateCache/blockStateCacheImpl.d.ts.map +1 -1
  73. package/lib/chain/stateCache/blockStateCacheImpl.js +2 -2
  74. package/lib/chain/stateCache/blockStateCacheImpl.js.map +1 -1
  75. package/lib/chain/stateCache/fifoBlockStateCache.d.ts +1 -2
  76. package/lib/chain/stateCache/fifoBlockStateCache.d.ts.map +1 -1
  77. package/lib/chain/stateCache/fifoBlockStateCache.js +4 -4
  78. package/lib/chain/stateCache/fifoBlockStateCache.js.map +1 -1
  79. package/lib/chain/stateCache/inMemoryCheckpointsCache.d.ts +4 -5
  80. package/lib/chain/stateCache/inMemoryCheckpointsCache.d.ts.map +1 -1
  81. package/lib/chain/stateCache/inMemoryCheckpointsCache.js +9 -10
  82. package/lib/chain/stateCache/inMemoryCheckpointsCache.js.map +1 -1
  83. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts +5 -6
  84. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts.map +1 -1
  85. package/lib/chain/stateCache/persistentCheckpointsCache.js +17 -17
  86. package/lib/chain/stateCache/persistentCheckpointsCache.js.map +1 -1
  87. package/lib/chain/stateCache/types.d.ts +5 -6
  88. package/lib/chain/stateCache/types.d.ts.map +1 -1
  89. package/lib/chain/stateCache/types.js.map +1 -1
  90. package/lib/chain/validation/attestation.d.ts.map +1 -1
  91. package/lib/chain/validation/attestation.js +2 -2
  92. package/lib/chain/validation/attestation.js.map +1 -1
  93. package/lib/chain/validation/attesterSlashing.d.ts.map +1 -1
  94. package/lib/chain/validation/attesterSlashing.js +1 -1
  95. package/lib/chain/validation/attesterSlashing.js.map +1 -1
  96. package/lib/chain/validation/block.d.ts.map +1 -1
  97. package/lib/chain/validation/block.js +2 -0
  98. package/lib/chain/validation/block.js.map +1 -1
  99. package/lib/chain/validation/blsToExecutionChange.d.ts.map +1 -1
  100. package/lib/chain/validation/blsToExecutionChange.js +9 -2
  101. package/lib/chain/validation/blsToExecutionChange.js.map +1 -1
  102. package/lib/chain/validation/proposerSlashing.js +2 -1
  103. package/lib/chain/validation/proposerSlashing.js.map +1 -1
  104. package/lib/db/repositories/checkpointState.d.ts +2 -6
  105. package/lib/db/repositories/checkpointState.d.ts.map +1 -1
  106. package/lib/db/repositories/checkpointState.js +3 -15
  107. package/lib/db/repositories/checkpointState.js.map +1 -1
  108. package/lib/db/repositories/stateArchive.d.ts +9 -9
  109. package/lib/db/repositories/stateArchive.d.ts.map +1 -1
  110. package/lib/db/repositories/stateArchive.js +6 -21
  111. package/lib/db/repositories/stateArchive.js.map +1 -1
  112. package/lib/execution/engine/mock.d.ts +9 -6
  113. package/lib/execution/engine/mock.d.ts.map +1 -1
  114. package/lib/execution/engine/mock.js +34 -7
  115. package/lib/execution/engine/mock.js.map +1 -1
  116. package/lib/index.d.ts +1 -1
  117. package/lib/index.d.ts.map +1 -1
  118. package/lib/index.js +1 -1
  119. package/lib/index.js.map +1 -1
  120. package/lib/metrics/metrics/lodestar.d.ts +1 -6
  121. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  122. package/lib/metrics/metrics/lodestar.js +3 -17
  123. package/lib/metrics/metrics/lodestar.js.map +1 -1
  124. package/lib/network/reqresp/utils/dataColumnResponseValidation.js +1 -1
  125. package/lib/network/reqresp/utils/dataColumnResponseValidation.js.map +1 -1
  126. package/lib/node/nodejs.d.ts.map +1 -1
  127. package/lib/node/nodejs.js +17 -2
  128. package/lib/node/nodejs.js.map +1 -1
  129. package/lib/util/sszBytes.js +1 -1
  130. package/lib/util/sszBytes.js.map +1 -1
  131. package/package.json +15 -15
  132. package/src/api/impl/beacon/state/utils.ts +2 -22
  133. package/src/api/impl/config/constants.ts +8 -0
  134. package/src/api/impl/lodestar/index.ts +1 -1
  135. package/src/api/impl/proof/index.ts +1 -2
  136. package/src/api/impl/validator/index.ts +1 -3
  137. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +5 -3
  138. package/src/chain/archiveStore/utils/archiveBlocks.ts +21 -14
  139. package/src/chain/blocks/importBlock.ts +13 -3
  140. package/src/chain/blocks/verifyBlock.ts +9 -3
  141. package/src/chain/blocks/verifyBlocksStateTransitionOnly.ts +1 -0
  142. package/src/chain/chain.ts +20 -9
  143. package/src/chain/initState.ts +5 -3
  144. package/src/chain/interface.ts +2 -2
  145. package/src/chain/lightClient/proofs.ts +0 -2
  146. package/src/chain/opPools/aggregatedAttestationPool.ts +19 -191
  147. package/src/chain/opPools/opPool.ts +5 -7
  148. package/src/chain/prepareNextSlot.ts +2 -6
  149. package/src/chain/produceBlock/produceBlockBody.ts +6 -1
  150. package/src/chain/regen/interface.ts +1 -5
  151. package/src/chain/regen/queued.ts +15 -34
  152. package/src/chain/regen/regen.ts +12 -18
  153. package/src/chain/shufflingCache.ts +67 -50
  154. package/src/chain/stateCache/blockStateCacheImpl.ts +2 -3
  155. package/src/chain/stateCache/fifoBlockStateCache.ts +4 -5
  156. package/src/chain/stateCache/inMemoryCheckpointsCache.ts +9 -15
  157. package/src/chain/stateCache/persistentCheckpointsCache.ts +17 -25
  158. package/src/chain/stateCache/types.ts +5 -10
  159. package/src/chain/validation/attestation.ts +3 -3
  160. package/src/chain/validation/attesterSlashing.ts +8 -1
  161. package/src/chain/validation/block.ts +3 -0
  162. package/src/chain/validation/blsToExecutionChange.ts +9 -7
  163. package/src/chain/validation/proposerSlashing.ts +2 -1
  164. package/src/db/repositories/checkpointState.ts +3 -19
  165. package/src/db/repositories/stateArchive.ts +13 -27
  166. package/src/execution/engine/mock.ts +40 -13
  167. package/src/index.ts +1 -1
  168. package/src/metrics/metrics/lodestar.ts +3 -17
  169. package/src/network/reqresp/utils/dataColumnResponseValidation.ts +1 -1
  170. package/src/node/nodejs.ts +18 -3
  171. package/src/util/sszBytes.ts +1 -1
@@ -1,5 +1,5 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
- import {Id, Repository} from "@lodestar/db";
2
+ import {DbBatch, Id, Repository} from "@lodestar/db";
3
3
  import {
4
4
  BLS_WITHDRAWAL_PREFIX,
5
5
  ForkName,
@@ -440,23 +440,21 @@ async function persistDiff<K extends Id, V>(
440
440
  serializeKey: (key: K) => number | string
441
441
  ): Promise<void> {
442
442
  const persistedKeys = await dbRepo.keys();
443
- const itemsToPut: {key: K; value: V}[] = [];
444
- const keysToDelete: K[] = [];
443
+ const batch: DbBatch<K, V> = [];
445
444
 
446
445
  const persistedKeysSerialized = new Set(persistedKeys.map(serializeKey));
447
446
  for (const item of items) {
448
447
  if (!persistedKeysSerialized.has(serializeKey(item.key))) {
449
- itemsToPut.push(item);
448
+ batch.push({type: "put", key: item.key, value: item.value});
450
449
  }
451
450
  }
452
451
 
453
452
  const targetKeysSerialized = new Set(items.map((item) => serializeKey(item.key)));
454
453
  for (const persistedKey of persistedKeys) {
455
454
  if (!targetKeysSerialized.has(serializeKey(persistedKey))) {
456
- keysToDelete.push(persistedKey);
455
+ batch.push({type: "del", key: persistedKey});
457
456
  }
458
457
  }
459
458
 
460
- if (itemsToPut.length > 0) await dbRepo.batchPut(itemsToPut);
461
- if (keysToDelete.length > 0) await dbRepo.batchDelete(keysToDelete);
459
+ if (batch.length > 0) await dbRepo.batch(batch);
462
460
  }
@@ -117,12 +117,7 @@ export class PrepareNextSlotScheduler {
117
117
  // the slot 0 of next epoch will likely use this Previous Root Checkpoint state for state transition so we transfer cache here
118
118
  // the resulting state with cache will be cached in Checkpoint State Cache which is used for the upcoming block processing
119
119
  // for other slots dontTransferCached=true because we don't run state transition on this state
120
- //
121
- // Shuffling calculation will be done asynchronously when passing asyncShufflingCalculation=true. Shuffling will be queued in
122
- // beforeProcessEpoch and should theoretically be ready immediately after the synchronous epoch transition finished and the
123
- // event loop is free. In long periods of non-finality too many forks will cause the shufflingCache to throw an error for
124
- // too many queued shufflings so only run async during normal epoch transition. See issue ChainSafe/lodestar#7244
125
- {dontTransferCache: !isEpochTransition, asyncShufflingCalculation: true},
120
+ {dontTransferCache: !isEpochTransition},
126
121
  RegenCaller.precomputeEpoch
127
122
  );
128
123
 
@@ -148,6 +143,7 @@ export class PrepareNextSlotScheduler {
148
143
  updatedPrepareState = (await this.chain.regen.getBlockSlotState(
149
144
  proposerHeadRoot,
150
145
  prepareSlot,
146
+ // only transfer cache if epoch transition because that's the state we will use to stateTransition() the 1st block of epoch
151
147
  {dontTransferCache: !isEpochTransition},
152
148
  RegenCaller.predictProposerHead
153
149
  )) as CachedBeaconStateExecutions;
@@ -661,7 +661,12 @@ export async function produceCommonBlockBody<T extends BlockType>(
661
661
  this.opPool.getSlashingsAndExits(currentState, blockType, this.metrics);
662
662
 
663
663
  const endAttestations = stepsMetrics?.startTimer();
664
- const attestations = this.aggregatedAttestationPool.getAttestationsForBlock(fork, this.forkChoice, currentState);
664
+ const attestations = this.aggregatedAttestationPool.getAttestationsForBlock(
665
+ fork,
666
+ this.forkChoice,
667
+ this.shufflingCache,
668
+ currentState
669
+ );
665
670
  endAttestations?.({
666
671
  step: BlockProductionStep.attestations,
667
672
  });
@@ -31,10 +31,6 @@ export enum RegenFnName {
31
31
 
32
32
  export type StateRegenerationOpts = {
33
33
  dontTransferCache: boolean;
34
- /**
35
- * Do not queue shuffling calculation async. Forces sync JIT calculation in afterProcessEpoch if not passed as `true`
36
- */
37
- asyncShufflingCalculation?: boolean;
38
34
  };
39
35
 
40
36
  export interface IStateRegenerator extends IStateRegeneratorInternal {
@@ -90,5 +86,5 @@ export interface IStateRegeneratorInternal {
90
86
  /**
91
87
  * Return the exact state with `stateRoot`
92
88
  */
93
- getState(stateRoot: RootHex, rCaller: RegenCaller, opts?: StateRegenerationOpts): Promise<CachedBeaconStateAllForks>;
89
+ getState(stateRoot: RootHex, rCaller: RegenCaller): Promise<CachedBeaconStateAllForks>;
94
90
  }
@@ -79,21 +79,15 @@ export class QueuedStateRegenerator implements IStateRegenerator {
79
79
 
80
80
  /**
81
81
  * Get a state from block state cache.
82
- * This is not for block processing so don't transfer cache
83
82
  */
84
83
  getStateSync(stateRoot: RootHex): CachedBeaconStateAllForks | null {
85
- return this.blockStateCache.get(stateRoot, {dontTransferCache: true});
84
+ return this.blockStateCache.get(stateRoot);
86
85
  }
87
86
 
88
87
  /**
89
88
  * Get state for block processing.
90
- * By default, do not transfer cache except for the block at clock slot
91
- * which is usually the gossip block.
92
89
  */
93
- getPreStateSync(
94
- block: BeaconBlock,
95
- opts: StateRegenerationOpts = {dontTransferCache: true}
96
- ): CachedBeaconStateAllForks | null {
90
+ getPreStateSync(block: BeaconBlock): CachedBeaconStateAllForks | null {
97
91
  const parentRoot = toRootHex(block.parentRoot);
98
92
  const parentBlock = this.forkChoice.getBlockHex(parentRoot);
99
93
  if (!parentBlock) {
@@ -108,7 +102,7 @@ export class QueuedStateRegenerator implements IStateRegenerator {
108
102
 
109
103
  // Check the checkpoint cache (if the pre-state is a checkpoint state)
110
104
  if (parentEpoch < blockEpoch) {
111
- const checkpointState = this.checkpointStateCache.getLatest(parentRoot, blockEpoch, opts);
105
+ const checkpointState = this.checkpointStateCache.getLatest(parentRoot, blockEpoch);
112
106
  if (checkpointState && computeEpochAtSlot(checkpointState.slot) === blockEpoch) {
113
107
  return checkpointState;
114
108
  }
@@ -118,7 +112,7 @@ export class QueuedStateRegenerator implements IStateRegenerator {
118
112
  // Otherwise the state transition may not be cached and wasted. Queue for regen since the
119
113
  // work required will still be significant.
120
114
  if (parentEpoch === blockEpoch) {
121
- const state = this.blockStateCache.get(parentBlock.stateRoot, opts);
115
+ const state = this.blockStateCache.get(parentBlock.stateRoot);
122
116
  if (state) {
123
117
  return state;
124
118
  }
@@ -132,21 +126,17 @@ export class QueuedStateRegenerator implements IStateRegenerator {
132
126
  }
133
127
 
134
128
  /**
135
- * Get checkpoint state from cache, this function is not for block processing so don't transfer cache
129
+ * Get checkpoint state from cache
136
130
  */
137
131
  getCheckpointStateSync(cp: CheckpointHex): CachedBeaconStateAllForks | null {
138
- return this.checkpointStateCache.get(cp, {dontTransferCache: true});
132
+ return this.checkpointStateCache.get(cp);
139
133
  }
140
134
 
141
135
  /**
142
- * Get state closest to head, this function is not for block processing so don't transfer cache
136
+ * Get state closest to head
143
137
  */
144
138
  getClosestHeadState(head: ProtoBlock): CachedBeaconStateAllForks | null {
145
- const opts = {dontTransferCache: true};
146
- return (
147
- this.checkpointStateCache.getLatest(head.blockRoot, Infinity, opts) ||
148
- this.blockStateCache.get(head.stateRoot, opts)
149
- );
139
+ return this.checkpointStateCache.getLatest(head.blockRoot, Infinity) || this.blockStateCache.get(head.stateRoot);
150
140
  }
151
141
 
152
142
  pruneOnCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch, headStateRoot: RootHex): void {
@@ -181,10 +171,7 @@ export class QueuedStateRegenerator implements IStateRegenerator {
181
171
  maybeHeadStateRoot,
182
172
  };
183
173
  const headState =
184
- newHeadStateRoot === maybeHeadStateRoot
185
- ? maybeHeadState
186
- : // maybeHeadState was already in block state cache so we don't transfer the cache
187
- this.blockStateCache.get(newHeadStateRoot, {dontTransferCache: true});
174
+ newHeadStateRoot === maybeHeadStateRoot ? maybeHeadState : this.blockStateCache.get(newHeadStateRoot);
188
175
 
189
176
  if (headState) {
190
177
  this.blockStateCache.setHeadState(headState);
@@ -199,9 +186,7 @@ export class QueuedStateRegenerator implements IStateRegenerator {
199
186
 
200
187
  // for the new FIFOBlockStateCache, it's important to reload state to regen head state here if needed
201
188
  const allowDiskReload = true;
202
- // transfer cache here because we want to regen state asap
203
- const cloneOpts = {dontTransferCache: false};
204
- this.regen.getState(newHeadStateRoot, RegenCaller.processBlock, cloneOpts, allowDiskReload).then(
189
+ this.regen.getState(newHeadStateRoot, RegenCaller.processBlock, allowDiskReload).then(
205
190
  (headStateRegen) => this.blockStateCache.setHeadState(headStateRegen),
206
191
  (e) => this.logger.error("Error on head state regen", logCtx, e)
207
192
  );
@@ -224,7 +209,7 @@ export class QueuedStateRegenerator implements IStateRegenerator {
224
209
  this.metrics?.regenFnCallTotal.inc({caller: rCaller, entrypoint: RegenFnName.getPreState});
225
210
 
226
211
  // First attempt to fetch the state from caches before queueing
227
- const cachedState = this.getPreStateSync(block, opts);
212
+ const cachedState = this.getPreStateSync(block);
228
213
 
229
214
  if (cachedState !== null) {
230
215
  return cachedState;
@@ -243,7 +228,7 @@ export class QueuedStateRegenerator implements IStateRegenerator {
243
228
  this.metrics?.regenFnCallTotal.inc({caller: rCaller, entrypoint: RegenFnName.getCheckpointState});
244
229
 
245
230
  // First attempt to fetch the state from cache before queueing
246
- const checkpointState = this.checkpointStateCache.get(toCheckpointHex(cp), opts);
231
+ const checkpointState = this.checkpointStateCache.get(toCheckpointHex(cp));
247
232
  if (checkpointState) {
248
233
  return checkpointState;
249
234
  }
@@ -271,22 +256,18 @@ export class QueuedStateRegenerator implements IStateRegenerator {
271
256
  return this.jobQueue.push({key: "getBlockSlotState", args: [blockRoot, slot, opts, rCaller]});
272
257
  }
273
258
 
274
- async getState(
275
- stateRoot: RootHex,
276
- rCaller: RegenCaller,
277
- opts: StateRegenerationOpts = {dontTransferCache: true}
278
- ): Promise<CachedBeaconStateAllForks> {
259
+ async getState(stateRoot: RootHex, rCaller: RegenCaller): Promise<CachedBeaconStateAllForks> {
279
260
  this.metrics?.regenFnCallTotal.inc({caller: rCaller, entrypoint: RegenFnName.getState});
280
261
 
281
262
  // First attempt to fetch the state from cache before queueing
282
- const state = this.blockStateCache.get(stateRoot, opts);
263
+ const state = this.blockStateCache.get(stateRoot);
283
264
  if (state) {
284
265
  return state;
285
266
  }
286
267
 
287
268
  // The state is not immediately available in the cache, enqueue the job
288
269
  this.metrics?.regenFnQueuedTotal.inc({caller: rCaller, entrypoint: RegenFnName.getState});
289
- return this.jobQueue.push({key: "getState", args: [stateRoot, rCaller, opts]});
270
+ return this.jobQueue.push({key: "getState", args: [stateRoot, rCaller]});
290
271
  }
291
272
 
292
273
  private jobQueueProcessor = async (regenRequest: RegenRequest): Promise<CachedBeaconStateAllForks> => {
@@ -78,7 +78,7 @@ export class StateRegenerator implements IStateRegeneratorInternal {
78
78
  }
79
79
 
80
80
  // Otherwise, get the state normally.
81
- return this.getState(parentBlock.stateRoot, regenCaller, opts, allowDiskReload);
81
+ return this.getState(parentBlock.stateRoot, regenCaller, allowDiskReload);
82
82
  }
83
83
 
84
84
  /**
@@ -124,8 +124,8 @@ export class StateRegenerator implements IStateRegeneratorInternal {
124
124
  const {checkpointStateCache} = this.modules;
125
125
  const epoch = computeEpochAtSlot(slot);
126
126
  const latestCheckpointStateCtx = allowDiskReload
127
- ? await checkpointStateCache.getOrReloadLatest(blockRoot, epoch, opts)
128
- : checkpointStateCache.getLatest(blockRoot, epoch, opts);
127
+ ? await checkpointStateCache.getOrReloadLatest(blockRoot, epoch)
128
+ : checkpointStateCache.getLatest(blockRoot, epoch);
129
129
 
130
130
  // If a checkpoint state exists with the given checkpoint root, it either is in requested epoch
131
131
  // or needs to have empty slots processed until the requested epoch
@@ -136,7 +136,7 @@ export class StateRegenerator implements IStateRegeneratorInternal {
136
136
  // Otherwise, use the fork choice to get the stateRoot from block at the checkpoint root
137
137
  // regenerate that state,
138
138
  // then process empty slots until the requested epoch
139
- const blockStateCtx = await this.getState(block.stateRoot, regenCaller, opts, allowDiskReload);
139
+ const blockStateCtx = await this.getState(block.stateRoot, regenCaller, allowDiskReload);
140
140
  return processSlotsByCheckpoint(this.modules, blockStateCtx, slot, regenCaller, opts);
141
141
  }
142
142
 
@@ -148,23 +148,15 @@ export class StateRegenerator implements IStateRegeneratorInternal {
148
148
  async getState(
149
149
  stateRoot: RootHex,
150
150
  caller: RegenCaller,
151
- opts?: StateRegenerationOpts,
152
151
  // internal option, don't want to expose to external caller
153
152
  allowDiskReload = false
154
153
  ): Promise<CachedBeaconStateAllForks> {
155
154
  // Trivial case, state at stateRoot is already cached
156
- const cachedStateCtx = this.modules.blockStateCache.get(stateRoot, opts);
155
+ const cachedStateCtx = this.modules.blockStateCache.get(stateRoot);
157
156
  if (cachedStateCtx) {
158
157
  return cachedStateCtx;
159
158
  }
160
159
 
161
- // in block gossip validation (getPreState() call), dontTransferCache is specified as true because we only want to transfer cache in verifyBlocksStateTransitionOnly()
162
- // but here we want to process blocks as fast as possible so force to transfer cache in this case
163
- if (opts && allowDiskReload) {
164
- // if there is no `opts` specified, it already means "false"
165
- opts.dontTransferCache = false;
166
- }
167
-
168
160
  // Otherwise we have to use the fork choice to traverse backwards, block by block,
169
161
  // searching the state caches
170
162
  // then replay blocks forward to the desired stateRoot
@@ -179,7 +171,7 @@ export class StateRegenerator implements IStateRegeneratorInternal {
179
171
  const getSeedStateTimer = this.modules.metrics?.regenGetState.getSeedState.startTimer({caller});
180
172
  // iterateAncestorBlocks only returns ancestor blocks, not the block itself
181
173
  for (const b of this.modules.forkChoice.iterateAncestorBlocks(block.blockRoot)) {
182
- state = this.modules.blockStateCache.get(b.stateRoot, opts);
174
+ state = this.modules.blockStateCache.get(b.stateRoot);
183
175
  if (state) {
184
176
  break;
185
177
  }
@@ -187,8 +179,8 @@ export class StateRegenerator implements IStateRegeneratorInternal {
187
179
  if (!lastBlockToReplay) continue;
188
180
  const epoch = computeEpochAtSlot(lastBlockToReplay.slot - 1);
189
181
  state = allowDiskReload
190
- ? await checkpointStateCache.getOrReloadLatest(b.blockRoot, epoch, opts)
191
- : checkpointStateCache.getLatest(b.blockRoot, epoch, opts);
182
+ ? await checkpointStateCache.getOrReloadLatest(b.blockRoot, epoch)
183
+ : checkpointStateCache.getLatest(b.blockRoot, epoch);
192
184
  if (state) {
193
185
  break;
194
186
  }
@@ -255,6 +247,7 @@ export class StateRegenerator implements IStateRegeneratorInternal {
255
247
  try {
256
248
  // Only advances state trusting block's signture and hashes.
257
249
  // We are only running the state transition to get a specific state's data.
250
+ // stateTransition() does the clone() inside, transfer cache to make the regen faster
258
251
  state = stateTransition(
259
252
  state,
260
253
  block,
@@ -265,6 +258,7 @@ export class StateRegenerator implements IStateRegeneratorInternal {
265
258
  verifyStateRoot: false,
266
259
  verifyProposer: false,
267
260
  verifySignatures: false,
261
+ dontTransferCache: false,
268
262
  },
269
263
  this.modules
270
264
  );
@@ -390,8 +384,8 @@ export async function processSlotsToNearestCheckpoint(
390
384
  const checkpointState = postState;
391
385
  const cp = getCheckpointFromState(checkpointState);
392
386
  checkpointStateCache.add(cp, checkpointState);
393
- // consumers should not mutate or get the transfered cache
394
- emitter?.emit(ChainEvent.checkpoint, cp, checkpointState.clone(true));
387
+ // consumers should not mutate state ever
388
+ emitter?.emit(ChainEvent.checkpoint, cp, checkpointState);
395
389
 
396
390
  if (count >= 1) {
397
391
  // in normal condition, we only process 1 epoch so never reach this
@@ -1,12 +1,12 @@
1
+ import {ForkSeq} from "@lodestar/params";
1
2
  import {
2
- BeaconStateAllForks,
3
+ CachedBeaconStateAllForks,
3
4
  EpochShuffling,
4
- IShufflingCache,
5
- ShufflingBuildProps,
6
- computeEpochShuffling,
7
- computeEpochShufflingAsync,
5
+ getAttestingIndices,
6
+ getBeaconCommittees,
7
+ getIndexedAttestation,
8
8
  } from "@lodestar/state-transition";
9
- import {Epoch, RootHex} from "@lodestar/types";
9
+ import {Attestation, CommitteeIndex, Epoch, IndexedAttestation, RootHex, Slot} from "@lodestar/types";
10
10
  import {LodestarError, Logger, MapDef, pruneSetToMax} from "@lodestar/utils";
11
11
  import {Metrics} from "../metrics/metrics.js";
12
12
 
@@ -53,7 +53,7 @@ export type ShufflingCacheOpts = {
53
53
  * - if a shuffling is not available (which does not happen with default chain option of maxSkipSlots = 32), track a promise to make sure we don't compute the same shuffling twice
54
54
  * - skip computing shuffling when loading state bytes from disk
55
55
  */
56
- export class ShufflingCache implements IShufflingCache {
56
+ export class ShufflingCache {
57
57
  /** LRU cache implemented as a map, pruned every time we add an item */
58
58
  private readonly itemsByDecisionRootByEpoch: MapDef<Epoch, Map<RootHex, CacheItem>> = new MapDef(
59
59
  () => new Map<RootHex, CacheItem>()
@@ -136,60 +136,76 @@ export class ShufflingCache implements IShufflingCache {
136
136
  }
137
137
 
138
138
  /**
139
- * Gets a cached shuffling via the epoch and decision root. If the shuffling is not
140
- * available it will build it synchronously and return the shuffling.
141
- *
142
- * NOTE: If a shuffling is already queued and not calculated it will build and resolve
143
- * the promise but the already queued build will happen at some later time
139
+ * Get a shuffling synchronously, return null if not present.
140
+ * The only time we have a promise cache item is when we regen shuffling for attestation, which never happens
141
+ * with default chain option.
144
142
  */
145
- getSync<T extends ShufflingBuildProps | undefined>(
146
- epoch: Epoch,
147
- decisionRoot: RootHex,
148
- buildProps?: T
149
- ): T extends ShufflingBuildProps ? EpochShuffling : EpochShuffling | null {
143
+ getSync(epoch: Epoch, decisionRoot: RootHex): EpochShuffling | null {
150
144
  const cacheItem = this.itemsByDecisionRootByEpoch.getOrDefault(epoch).get(decisionRoot);
151
- if (!cacheItem) {
145
+ if (cacheItem === undefined) {
152
146
  this.metrics?.shufflingCache.miss.inc();
153
- } else if (isShufflingCacheItem(cacheItem)) {
147
+ return null;
148
+ }
149
+
150
+ if (isShufflingCacheItem(cacheItem)) {
154
151
  this.metrics?.shufflingCache.hit.inc();
155
152
  return cacheItem.shuffling;
156
- } else if (buildProps) {
157
- // TODO: (@matthewkeil) This should possible log a warning??
158
- this.metrics?.shufflingCache.shufflingPromiseNotResolvedAndThrownAway.inc();
159
- } else {
160
- this.metrics?.shufflingCache.shufflingPromiseNotResolved.inc();
161
153
  }
162
154
 
163
- let shuffling: EpochShuffling | null = null;
164
- if (buildProps) {
165
- const timer = this.metrics?.shufflingCache.shufflingCalculationTime.startTimer({source: "getSync"});
166
- shuffling = computeEpochShuffling(buildProps.state, buildProps.activeIndices, epoch);
167
- timer?.();
168
- this.set(shuffling, decisionRoot);
169
- }
170
- return shuffling as T extends ShufflingBuildProps ? EpochShuffling : EpochShuffling | null;
155
+ return null;
171
156
  }
172
157
 
173
158
  /**
174
- * Queue asynchronous build for an EpochShuffling, triggered from state-transition
159
+ * Process a state to extract and cache all shufflings (previous, current, next).
160
+ * Uses the stored decision roots from epochCtx.
175
161
  */
176
- build(epoch: number, decisionRoot: string, state: BeaconStateAllForks, activeIndices: Uint32Array): void {
177
- this.insertPromise(epoch, decisionRoot);
178
- /**
179
- * TODO: (@matthewkeil) This will get replaced by a proper build queue and a worker to do calculations
180
- * on a NICE thread
181
- */
182
- const timer = this.metrics?.shufflingCache.shufflingCalculationTime.startTimer({source: "build"});
183
- computeEpochShufflingAsync(state, activeIndices, epoch)
184
- .then((shuffling) => {
185
- this.set(shuffling, decisionRoot);
186
- })
187
- .catch((err) =>
188
- this.logger?.error(`error building shuffling for epoch ${epoch} at decisionRoot ${decisionRoot}`, {}, err)
189
- )
190
- .finally(() => {
191
- timer?.();
162
+ processState(state: CachedBeaconStateAllForks): void {
163
+ const {epochCtx} = state;
164
+
165
+ // Cache previous shuffling
166
+ this.set(epochCtx.previousShuffling, epochCtx.previousDecisionRoot);
167
+
168
+ // Cache current shuffling
169
+ this.set(epochCtx.currentShuffling, epochCtx.currentDecisionRoot);
170
+
171
+ // Cache next shuffling
172
+ this.set(epochCtx.nextShuffling, epochCtx.nextDecisionRoot);
173
+ }
174
+
175
+ getIndexedAttestation(
176
+ epoch: number,
177
+ decisionRoot: string,
178
+ fork: ForkSeq,
179
+ attestation: Attestation
180
+ ): IndexedAttestation {
181
+ const shuffling = this.getShufflingOrThrow(epoch, decisionRoot);
182
+ return getIndexedAttestation(shuffling, fork, attestation);
183
+ }
184
+
185
+ getAttestingIndices(epoch: number, decisionRoot: string, fork: ForkSeq, attestation: Attestation): number[] {
186
+ const shuffling = this.getShufflingOrThrow(epoch, decisionRoot);
187
+ return getAttestingIndices(shuffling, fork, attestation);
188
+ }
189
+
190
+ getBeaconCommittee(epoch: number, decisionRoot: string, slot: Slot, index: CommitteeIndex): Uint32Array {
191
+ return this.getBeaconCommittees(epoch, decisionRoot, slot, [index])[0];
192
+ }
193
+
194
+ getBeaconCommittees(epoch: number, decisionRoot: string, slot: Slot, indices: CommitteeIndex[]): Uint32Array[] {
195
+ const shuffling = this.getShufflingOrThrow(epoch, decisionRoot);
196
+ return getBeaconCommittees(shuffling, slot, indices);
197
+ }
198
+
199
+ private getShufflingOrThrow(epoch: number, decisionRoot: string): EpochShuffling {
200
+ const shuffling = this.getSync(epoch, decisionRoot);
201
+ if (shuffling === null) {
202
+ throw new ShufflingCacheError({
203
+ code: ShufflingCacheErrorCode.NO_SHUFFLING_FOUND,
204
+ epoch,
205
+ decisionRoot,
192
206
  });
207
+ }
208
+ return shuffling;
193
209
  }
194
210
 
195
211
  /**
@@ -207,7 +223,8 @@ export class ShufflingCache implements IShufflingCache {
207
223
  (Date.now() - cacheItem.timeInsertedMs) / 1000
208
224
  );
209
225
  } else {
210
- this.metrics?.shufflingCache.shufflingBuiltMultipleTimes.inc();
226
+ this.metrics?.shufflingCache.shufflingSetMultipleTimes.inc();
227
+ return;
211
228
  }
212
229
  }
213
230
  // set the shuffling
@@ -3,7 +3,6 @@ import {CachedBeaconStateAllForks} from "@lodestar/state-transition";
3
3
  import {Epoch, RootHex} from "@lodestar/types";
4
4
  import {toRootHex} from "@lodestar/utils";
5
5
  import {Metrics} from "../../metrics/index.js";
6
- import {StateRegenerationOpts} from "../regen/interface.js";
7
6
  import {MapTracker} from "./mapMetrics.js";
8
7
  import {BlockStateCache} from "./types.js";
9
8
 
@@ -39,7 +38,7 @@ export class BlockStateCacheImpl implements BlockStateCache {
39
38
  }
40
39
  }
41
40
 
42
- get(rootHex: RootHex, opts?: StateRegenerationOpts): CachedBeaconStateAllForks | null {
41
+ get(rootHex: RootHex): CachedBeaconStateAllForks | null {
43
42
  this.metrics?.lookups.inc();
44
43
  const item = this.head?.stateRoot === rootHex ? this.head.state : this.cache.get(rootHex);
45
44
  if (!item) {
@@ -49,7 +48,7 @@ export class BlockStateCacheImpl implements BlockStateCache {
49
48
  this.metrics?.hits.inc();
50
49
  this.metrics?.stateClonedCount.observe(item.clonedCount);
51
50
 
52
- return item.clone(opts?.dontTransferCache);
51
+ return item;
53
52
  }
54
53
 
55
54
  add(item: CachedBeaconStateAllForks): void {
@@ -4,7 +4,6 @@ import {RootHex} from "@lodestar/types";
4
4
  import {toRootHex} from "@lodestar/utils";
5
5
  import {Metrics} from "../../metrics/index.js";
6
6
  import {LinkedList} from "../../util/array.js";
7
- import {StateRegenerationOpts} from "../regen/interface.js";
8
7
  import {MapTracker} from "./mapMetrics.js";
9
8
  import {BlockStateCache} from "./types.js";
10
9
 
@@ -86,14 +85,14 @@ export class FIFOBlockStateCache implements BlockStateCache {
86
85
  }
87
86
 
88
87
  const firstState = firstValue.value;
89
- // don't transfer cache because consumer only use this cache to reload another state from disc
90
- return firstState.clone(true);
88
+ // consumers should not mutate the returned state
89
+ return firstState;
91
90
  }
92
91
 
93
92
  /**
94
93
  * Get a state from this cache given a state root hex.
95
94
  */
96
- get(rootHex: RootHex, opts?: StateRegenerationOpts): CachedBeaconStateAllForks | null {
95
+ get(rootHex: RootHex): CachedBeaconStateAllForks | null {
97
96
  this.metrics?.lookups.inc();
98
97
  const item = this.cache.get(rootHex);
99
98
  if (!item) {
@@ -103,7 +102,7 @@ export class FIFOBlockStateCache implements BlockStateCache {
103
102
  this.metrics?.hits.inc();
104
103
  this.metrics?.stateClonedCount.observe(item.clonedCount);
105
104
 
106
- return item.clone(opts?.dontTransferCache);
105
+ return item;
107
106
  }
108
107
 
109
108
  /**
@@ -3,7 +3,6 @@ import {CachedBeaconStateAllForks} from "@lodestar/state-transition";
3
3
  import {Epoch, RootHex, phase0} from "@lodestar/types";
4
4
  import {MapDef, toRootHex} from "@lodestar/utils";
5
5
  import {Metrics} from "../../metrics/index.js";
6
- import {StateRegenerationOpts} from "../regen/interface.js";
7
6
  import {MapTracker} from "./mapMetrics.js";
8
7
  import {CacheItemType, CheckpointStateCache} from "./types.js";
9
8
 
@@ -42,21 +41,16 @@ export class InMemoryCheckpointStateCache implements CheckpointStateCache {
42
41
  this.maxEpochs = maxEpochs;
43
42
  }
44
43
 
45
- async getOrReload(cp: CheckpointHex, opts?: StateRegenerationOpts): Promise<CachedBeaconStateAllForks | null> {
46
- return this.get(cp, opts);
44
+ async getOrReload(cp: CheckpointHex): Promise<CachedBeaconStateAllForks | null> {
45
+ return this.get(cp);
47
46
  }
48
47
 
49
48
  async getStateOrBytes(cp: CheckpointHex): Promise<Uint8Array | CachedBeaconStateAllForks | null> {
50
- // no need to transfer cache for this api
51
- return this.get(cp, {dontTransferCache: true});
49
+ return this.get(cp);
52
50
  }
53
51
 
54
- async getOrReloadLatest(
55
- rootHex: string,
56
- maxEpoch: number,
57
- opts?: StateRegenerationOpts
58
- ): Promise<CachedBeaconStateAllForks | null> {
59
- return this.getLatest(rootHex, maxEpoch, opts);
52
+ async getOrReloadLatest(rootHex: string, maxEpoch: number): Promise<CachedBeaconStateAllForks | null> {
53
+ return this.getLatest(rootHex, maxEpoch);
60
54
  }
61
55
 
62
56
  async processState(): Promise<number> {
@@ -64,7 +58,7 @@ export class InMemoryCheckpointStateCache implements CheckpointStateCache {
64
58
  return 0;
65
59
  }
66
60
 
67
- get(cp: CheckpointHex, opts?: StateRegenerationOpts): CachedBeaconStateAllForks | null {
61
+ get(cp: CheckpointHex): CachedBeaconStateAllForks | null {
68
62
  this.metrics?.lookups.inc();
69
63
  const cpKey = toCheckpointKey(cp);
70
64
  const item = this.cache.get(cpKey);
@@ -81,7 +75,7 @@ export class InMemoryCheckpointStateCache implements CheckpointStateCache {
81
75
 
82
76
  this.metrics?.stateClonedCount.observe(item.clonedCount);
83
77
 
84
- return item.clone(opts?.dontTransferCache);
78
+ return item;
85
79
  }
86
80
 
87
81
  add(cp: phase0.Checkpoint, item: CachedBeaconStateAllForks): void {
@@ -98,14 +92,14 @@ export class InMemoryCheckpointStateCache implements CheckpointStateCache {
98
92
  /**
99
93
  * Searches for the latest cached state with a `root`, starting with `epoch` and descending
100
94
  */
101
- getLatest(rootHex: RootHex, maxEpoch: Epoch, opts?: StateRegenerationOpts): CachedBeaconStateAllForks | null {
95
+ getLatest(rootHex: RootHex, maxEpoch: Epoch): CachedBeaconStateAllForks | null {
102
96
  // sort epochs in descending order, only consider epochs lte `epoch`
103
97
  const epochs = Array.from(this.epochIndex.keys())
104
98
  .sort((a, b) => b - a)
105
99
  .filter((e) => e <= maxEpoch);
106
100
  for (const epoch of epochs) {
107
101
  if (this.epochIndex.get(epoch)?.has(rootHex)) {
108
- return this.get({rootHex, epoch}, opts);
102
+ return this.get({rootHex, epoch});
109
103
  }
110
104
  }
111
105
  return null;