@lodestar/beacon-node 1.36.0-dev.c7f3e8d129 → 1.36.0-dev.d4044b6621

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 (177) 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 -22
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/lodestar/index.d.ts +5 -0
  5. package/lib/api/impl/lodestar/index.d.ts.map +1 -1
  6. package/lib/api/impl/lodestar/index.js +35 -10
  7. package/lib/api/impl/lodestar/index.js.map +1 -1
  8. package/lib/api/impl/node/utils.js +1 -1
  9. package/lib/api/impl/node/utils.js.map +1 -1
  10. package/lib/chain/archiveStore/archiveStore.d.ts +9 -0
  11. package/lib/chain/archiveStore/archiveStore.d.ts.map +1 -1
  12. package/lib/chain/archiveStore/archiveStore.js +24 -0
  13. package/lib/chain/archiveStore/archiveStore.js.map +1 -1
  14. package/lib/chain/archiveStore/strategies/frequencyStateArchiveStrategy.d.ts +7 -0
  15. package/lib/chain/archiveStore/strategies/frequencyStateArchiveStrategy.d.ts.map +1 -1
  16. package/lib/chain/archiveStore/strategies/frequencyStateArchiveStrategy.js +31 -5
  17. package/lib/chain/archiveStore/strategies/frequencyStateArchiveStrategy.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 +32 -16
  21. package/lib/chain/chain.js.map +1 -1
  22. package/lib/chain/errors/dataColumnSidecarError.d.ts +23 -13
  23. package/lib/chain/errors/dataColumnSidecarError.d.ts.map +1 -1
  24. package/lib/chain/errors/dataColumnSidecarError.js +5 -0
  25. package/lib/chain/errors/dataColumnSidecarError.js.map +1 -1
  26. package/lib/chain/forkChoice/index.d.ts +9 -1
  27. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  28. package/lib/chain/forkChoice/index.js +109 -4
  29. package/lib/chain/forkChoice/index.js.map +1 -1
  30. package/lib/chain/interface.d.ts +2 -0
  31. package/lib/chain/interface.d.ts.map +1 -1
  32. package/lib/chain/options.d.ts +0 -2
  33. package/lib/chain/options.d.ts.map +1 -1
  34. package/lib/chain/options.js +2 -2
  35. package/lib/chain/options.js.map +1 -1
  36. package/lib/chain/stateCache/datastore/db.d.ts +12 -0
  37. package/lib/chain/stateCache/datastore/db.d.ts.map +1 -1
  38. package/lib/chain/stateCache/datastore/db.js +70 -0
  39. package/lib/chain/stateCache/datastore/db.js.map +1 -1
  40. package/lib/chain/stateCache/datastore/file.d.ts +1 -0
  41. package/lib/chain/stateCache/datastore/file.d.ts.map +1 -1
  42. package/lib/chain/stateCache/datastore/file.js +7 -0
  43. package/lib/chain/stateCache/datastore/file.js.map +1 -1
  44. package/lib/chain/stateCache/datastore/types.d.ts +1 -0
  45. package/lib/chain/stateCache/datastore/types.d.ts.map +1 -1
  46. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts +16 -1
  47. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts.map +1 -1
  48. package/lib/chain/stateCache/persistentCheckpointsCache.js +31 -1
  49. package/lib/chain/stateCache/persistentCheckpointsCache.js.map +1 -1
  50. package/lib/chain/validation/dataColumnSidecar.d.ts.map +1 -1
  51. package/lib/chain/validation/dataColumnSidecar.js +45 -17
  52. package/lib/chain/validation/dataColumnSidecar.js.map +1 -1
  53. package/lib/index.d.ts +2 -0
  54. package/lib/index.d.ts.map +1 -1
  55. package/lib/index.js +2 -0
  56. package/lib/index.js.map +1 -1
  57. package/lib/metrics/metrics/lodestar.d.ts +10 -0
  58. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  59. package/lib/metrics/metrics/lodestar.js +15 -1
  60. package/lib/metrics/metrics/lodestar.js.map +1 -1
  61. package/lib/network/core/networkCore.d.ts.map +1 -1
  62. package/lib/network/core/networkCore.js +5 -1
  63. package/lib/network/core/networkCore.js.map +1 -1
  64. package/lib/network/core/networkCoreWorker.js +8 -8
  65. package/lib/network/core/networkCoreWorker.js.map +1 -1
  66. package/lib/network/core/networkCoreWorkerHandler.js +1 -1
  67. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  68. package/lib/network/discv5/worker.js +2 -7
  69. package/lib/network/discv5/worker.js.map +1 -1
  70. package/lib/network/events.d.ts +1 -0
  71. package/lib/network/events.d.ts.map +1 -1
  72. package/lib/network/gossip/encoding.js +1 -1
  73. package/lib/network/gossip/encoding.js.map +1 -1
  74. package/lib/network/gossip/snappy_bun.d.ts +3 -0
  75. package/lib/network/gossip/snappy_bun.d.ts.map +1 -0
  76. package/lib/network/gossip/snappy_bun.js +3 -0
  77. package/lib/network/gossip/snappy_bun.js.map +1 -0
  78. package/lib/network/metadata.d.ts +1 -1
  79. package/lib/network/metadata.d.ts.map +1 -1
  80. package/lib/network/metadata.js +1 -0
  81. package/lib/network/metadata.js.map +1 -1
  82. package/lib/network/options.d.ts +0 -1
  83. package/lib/network/options.d.ts.map +1 -1
  84. package/lib/network/options.js.map +1 -1
  85. package/lib/network/peers/discover.js +2 -2
  86. package/lib/network/peers/discover.js.map +1 -1
  87. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  88. package/lib/network/processor/gossipHandlers.js +14 -8
  89. package/lib/network/processor/gossipHandlers.js.map +1 -1
  90. package/lib/network/reqresp/ReqRespBeaconNode.d.ts.map +1 -1
  91. package/lib/network/reqresp/ReqRespBeaconNode.js +3 -1
  92. package/lib/network/reqresp/ReqRespBeaconNode.js.map +1 -1
  93. package/lib/network/reqresp/handlers/beaconBlocksByRange.d.ts +2 -1
  94. package/lib/network/reqresp/handlers/beaconBlocksByRange.d.ts.map +1 -1
  95. package/lib/network/reqresp/handlers/beaconBlocksByRange.js +14 -3
  96. package/lib/network/reqresp/handlers/beaconBlocksByRange.js.map +1 -1
  97. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.d.ts +2 -1
  98. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.d.ts.map +1 -1
  99. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +9 -1
  100. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  101. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.d.ts +2 -1
  102. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.d.ts.map +1 -1
  103. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +9 -1
  104. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  105. package/lib/network/reqresp/handlers/index.js +6 -6
  106. package/lib/network/reqresp/handlers/index.js.map +1 -1
  107. package/lib/network/reqresp/types.d.ts +1 -0
  108. package/lib/network/reqresp/types.d.ts.map +1 -1
  109. package/lib/node/nodejs.d.ts +2 -1
  110. package/lib/node/nodejs.d.ts.map +1 -1
  111. package/lib/node/nodejs.js +2 -1
  112. package/lib/node/nodejs.js.map +1 -1
  113. package/lib/sync/range/range.d.ts.map +1 -1
  114. package/lib/sync/range/range.js +2 -1
  115. package/lib/sync/range/range.js.map +1 -1
  116. package/lib/sync/utils/downloadByRange.d.ts +58 -13
  117. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  118. package/lib/sync/utils/downloadByRange.js +201 -82
  119. package/lib/sync/utils/downloadByRange.js.map +1 -1
  120. package/lib/sync/utils/remoteSyncType.d.ts +2 -1
  121. package/lib/sync/utils/remoteSyncType.d.ts.map +1 -1
  122. package/lib/sync/utils/remoteSyncType.js +19 -4
  123. package/lib/sync/utils/remoteSyncType.js.map +1 -1
  124. package/lib/util/blobs.d.ts +1 -1
  125. package/lib/util/blobs.d.ts.map +1 -1
  126. package/lib/util/blobs.js +53 -20
  127. package/lib/util/blobs.js.map +1 -1
  128. package/lib/util/profile.d.ts +6 -4
  129. package/lib/util/profile.d.ts.map +1 -1
  130. package/lib/util/profile.js +40 -3
  131. package/lib/util/profile.js.map +1 -1
  132. package/lib/util/sszBytes.d.ts +2 -0
  133. package/lib/util/sszBytes.d.ts.map +1 -1
  134. package/lib/util/sszBytes.js +25 -0
  135. package/lib/util/sszBytes.js.map +1 -1
  136. package/package.json +31 -24
  137. package/src/api/impl/beacon/blocks/index.ts +47 -25
  138. package/src/api/impl/lodestar/index.ts +42 -10
  139. package/src/api/impl/node/utils.ts +1 -1
  140. package/src/chain/archiveStore/archiveStore.ts +27 -0
  141. package/src/chain/archiveStore/strategies/frequencyStateArchiveStrategy.ts +32 -5
  142. package/src/chain/chain.ts +48 -23
  143. package/src/chain/errors/dataColumnSidecarError.ts +27 -13
  144. package/src/chain/forkChoice/index.ts +178 -2
  145. package/src/chain/interface.ts +2 -0
  146. package/src/chain/options.ts +2 -3
  147. package/src/chain/stateCache/datastore/db.ts +89 -1
  148. package/src/chain/stateCache/datastore/file.ts +8 -0
  149. package/src/chain/stateCache/datastore/types.ts +1 -0
  150. package/src/chain/stateCache/persistentCheckpointsCache.ts +45 -2
  151. package/src/chain/validation/dataColumnSidecar.ts +54 -19
  152. package/src/index.ts +2 -0
  153. package/src/metrics/metrics/lodestar.ts +18 -1
  154. package/src/network/core/networkCore.ts +5 -1
  155. package/src/network/core/networkCoreWorker.ts +9 -9
  156. package/src/network/core/networkCoreWorkerHandler.ts +1 -1
  157. package/src/network/discv5/worker.ts +2 -7
  158. package/src/network/events.ts +1 -1
  159. package/src/network/gossip/encoding.ts +1 -1
  160. package/src/network/gossip/snappy_bun.ts +2 -0
  161. package/src/network/metadata.ts +3 -1
  162. package/src/network/options.ts +0 -1
  163. package/src/network/peers/discover.ts +2 -2
  164. package/src/network/processor/gossipHandlers.ts +16 -7
  165. package/src/network/reqresp/ReqRespBeaconNode.ts +3 -1
  166. package/src/network/reqresp/handlers/beaconBlocksByRange.ts +18 -3
  167. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +13 -1
  168. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +13 -1
  169. package/src/network/reqresp/handlers/index.ts +6 -6
  170. package/src/network/reqresp/types.ts +1 -0
  171. package/src/node/nodejs.ts +3 -0
  172. package/src/sync/range/range.ts +2 -1
  173. package/src/sync/utils/downloadByRange.ts +259 -103
  174. package/src/sync/utils/remoteSyncType.ts +23 -4
  175. package/src/util/blobs.ts +64 -20
  176. package/src/util/profile.ts +45 -3
  177. package/src/util/sszBytes.ts +30 -0
@@ -5,17 +5,22 @@ import {
5
5
  ForkChoiceStore,
6
6
  JustifiedBalancesGetter,
7
7
  ProtoArray,
8
+ ProtoBlock,
8
9
  ForkChoiceOpts as RawForkChoiceOpts,
9
10
  } from "@lodestar/fork-choice";
11
+ import {ZERO_HASH_HEX} from "@lodestar/params";
10
12
  import {
11
13
  CachedBeaconStateAllForks,
12
14
  DataAvailabilityStatus,
13
15
  computeAnchorCheckpoint,
16
+ computeEpochAtSlot,
17
+ computeStartSlotAtEpoch,
18
+ getBlockRootAtSlot,
14
19
  getEffectiveBalanceIncrementsZeroInactive,
15
20
  isExecutionStateType,
16
21
  isMergeTransitionComplete,
17
22
  } from "@lodestar/state-transition";
18
- import {Slot} from "@lodestar/types";
23
+ import {Slot, ssz} from "@lodestar/types";
19
24
  import {Logger, toRootHex} from "@lodestar/utils";
20
25
  import {GENESIS_SLOT} from "../../constants/index.js";
21
26
  import {Metrics} from "../../metrics/index.js";
@@ -35,6 +40,43 @@ export enum ForkchoiceCaller {
35
40
  * Fork Choice extended with a ChainEventEmitter
36
41
  */
37
42
  export function initializeForkChoice(
43
+ config: ChainForkConfig,
44
+ emitter: ChainEventEmitter,
45
+ currentSlot: Slot,
46
+ state: CachedBeaconStateAllForks,
47
+ isFinalizedState: boolean,
48
+ opts: ForkChoiceOpts,
49
+ justifiedBalancesGetter: JustifiedBalancesGetter,
50
+ metrics: Metrics | null,
51
+ logger?: Logger
52
+ ): ForkChoice {
53
+ return isFinalizedState
54
+ ? initializeForkChoiceFromFinalizedState(
55
+ config,
56
+ emitter,
57
+ currentSlot,
58
+ state,
59
+ opts,
60
+ justifiedBalancesGetter,
61
+ metrics,
62
+ logger
63
+ )
64
+ : initializeForkChoiceFromUnfinalizedState(
65
+ config,
66
+ emitter,
67
+ currentSlot,
68
+ state,
69
+ opts,
70
+ justifiedBalancesGetter,
71
+ metrics,
72
+ logger
73
+ );
74
+ }
75
+
76
+ /**
77
+ * Initialize forkchoice from a finalized state.
78
+ */
79
+ export function initializeForkChoiceFromFinalizedState(
38
80
  config: ChainForkConfig,
39
81
  emitter: ChainEventEmitter,
40
82
  currentSlot: Slot,
@@ -82,7 +124,7 @@ export function initializeForkChoice(
82
124
  parentRoot: toRootHex(blockHeader.parentRoot),
83
125
  stateRoot: toRootHex(blockHeader.stateRoot),
84
126
  blockRoot: toRootHex(checkpoint.root),
85
- timeliness: true, // Optimisitcally assume is timely
127
+ timeliness: true, // Optimistically assume is timely
86
128
 
87
129
  justifiedEpoch: justifiedCheckpoint.epoch,
88
130
  justifiedRoot: toRootHex(justifiedCheckpoint.root),
@@ -105,6 +147,140 @@ export function initializeForkChoice(
105
147
  },
106
148
  currentSlot
107
149
  ),
150
+ state.validators.length,
151
+ metrics,
152
+ opts,
153
+ logger
154
+ );
155
+ }
156
+
157
+ /**
158
+ * Initialize forkchoice from an unfinalized state.
159
+ */
160
+ export function initializeForkChoiceFromUnfinalizedState(
161
+ config: ChainForkConfig,
162
+ emitter: ChainEventEmitter,
163
+ currentSlot: Slot,
164
+ unfinalizedState: CachedBeaconStateAllForks,
165
+ opts: ForkChoiceOpts,
166
+ justifiedBalancesGetter: JustifiedBalancesGetter,
167
+ metrics: Metrics | null,
168
+ logger?: Logger
169
+ ): ForkChoice {
170
+ const {blockHeader} = computeAnchorCheckpoint(config, unfinalizedState);
171
+ const finalizedCheckpoint = unfinalizedState.finalizedCheckpoint.toValue();
172
+ const justifiedCheckpoint = unfinalizedState.currentJustifiedCheckpoint.toValue();
173
+ const headRoot = toRootHex(ssz.phase0.BeaconBlockHeader.hashTreeRoot(blockHeader));
174
+
175
+ const logCtx = {
176
+ currentSlot: currentSlot,
177
+ stateSlot: unfinalizedState.slot,
178
+ headSlot: blockHeader.slot,
179
+ headRoot: headRoot,
180
+ finalizedEpoch: finalizedCheckpoint.epoch,
181
+ finalizedRoot: toRootHex(finalizedCheckpoint.root),
182
+ justifiedEpoch: justifiedCheckpoint.epoch,
183
+ justifiedRoot: toRootHex(justifiedCheckpoint.root),
184
+ };
185
+ logger?.warn("Initializing fork choice from unfinalized state", logCtx);
186
+
187
+ // this is not the justified state, but there is no other ways to get justified balances
188
+ const justifiedBalances = getEffectiveBalanceIncrementsZeroInactive(unfinalizedState);
189
+ const store = new ForkChoiceStore(
190
+ currentSlot,
191
+ justifiedCheckpoint,
192
+ finalizedCheckpoint,
193
+ justifiedBalances,
194
+ justifiedBalancesGetter,
195
+ {
196
+ onJustified: (cp) => emitter.emit(ChainEvent.forkChoiceJustified, cp),
197
+ onFinalized: (cp) => emitter.emit(ChainEvent.forkChoiceFinalized, cp),
198
+ }
199
+ );
200
+
201
+ // this is the same to the finalized state
202
+ const headBlock: ProtoBlock = {
203
+ slot: blockHeader.slot,
204
+ parentRoot: toRootHex(blockHeader.parentRoot),
205
+ stateRoot: toRootHex(blockHeader.stateRoot),
206
+ blockRoot: headRoot,
207
+ targetRoot: headRoot,
208
+ timeliness: true, // Optimistically assume is timely
209
+
210
+ justifiedEpoch: justifiedCheckpoint.epoch,
211
+ justifiedRoot: toRootHex(justifiedCheckpoint.root),
212
+ finalizedEpoch: finalizedCheckpoint.epoch,
213
+ finalizedRoot: toRootHex(finalizedCheckpoint.root),
214
+ unrealizedJustifiedEpoch: justifiedCheckpoint.epoch,
215
+ unrealizedJustifiedRoot: toRootHex(justifiedCheckpoint.root),
216
+ unrealizedFinalizedEpoch: finalizedCheckpoint.epoch,
217
+ unrealizedFinalizedRoot: toRootHex(finalizedCheckpoint.root),
218
+
219
+ ...(isExecutionStateType(unfinalizedState) && isMergeTransitionComplete(unfinalizedState)
220
+ ? {
221
+ executionPayloadBlockHash: toRootHex(unfinalizedState.latestExecutionPayloadHeader.blockHash),
222
+ executionPayloadNumber: unfinalizedState.latestExecutionPayloadHeader.blockNumber,
223
+ executionStatus: blockHeader.slot === GENESIS_SLOT ? ExecutionStatus.Valid : ExecutionStatus.Syncing,
224
+ }
225
+ : {executionPayloadBlockHash: null, executionStatus: ExecutionStatus.PreMerge}),
226
+
227
+ dataAvailabilityStatus: DataAvailabilityStatus.PreData,
228
+ };
229
+
230
+ const parentSlot = blockHeader.slot - 1;
231
+ const parentEpoch = computeEpochAtSlot(parentSlot);
232
+ // parent of head block
233
+ const parentBlock: ProtoBlock = {
234
+ ...headBlock,
235
+ slot: parentSlot,
236
+ // link this to the dummy justified block
237
+ parentRoot: toRootHex(justifiedCheckpoint.root),
238
+ // dummy data, we're not able to regen state before headBlock
239
+ stateRoot: ZERO_HASH_HEX,
240
+ blockRoot: headBlock.parentRoot,
241
+ targetRoot: toRootHex(getBlockRootAtSlot(unfinalizedState, computeStartSlotAtEpoch(parentEpoch))),
242
+ };
243
+
244
+ const justifiedBlock: ProtoBlock = {
245
+ ...headBlock,
246
+ slot: computeStartSlotAtEpoch(justifiedCheckpoint.epoch),
247
+ // link this to the finalized root so that getAncestors can find the finalized block
248
+ parentRoot: toRootHex(finalizedCheckpoint.root),
249
+ // dummy data, we're not able to regen state before headBlock
250
+ stateRoot: ZERO_HASH_HEX,
251
+ blockRoot: toRootHex(justifiedCheckpoint.root),
252
+ // same to blockRoot
253
+ targetRoot: toRootHex(justifiedCheckpoint.root),
254
+ };
255
+
256
+ const finalizedBlock: ProtoBlock = {
257
+ ...headBlock,
258
+ slot: computeStartSlotAtEpoch(finalizedCheckpoint.epoch),
259
+ // we don't care parent of finalized block
260
+ parentRoot: ZERO_HASH_HEX,
261
+ // dummy data, we're not able to regen state before headBlock
262
+ stateRoot: ZERO_HASH_HEX,
263
+ blockRoot: toRootHex(finalizedCheckpoint.root),
264
+ // same to blockRoot
265
+ targetRoot: toRootHex(finalizedCheckpoint.root),
266
+ };
267
+
268
+ const protoArray = ProtoArray.initialize(finalizedBlock, currentSlot);
269
+ protoArray.onBlock(justifiedBlock, currentSlot);
270
+ protoArray.onBlock(parentBlock, currentSlot);
271
+ protoArray.onBlock(headBlock, currentSlot);
272
+
273
+ logger?.verbose("Initialized protoArray successfully", {...logCtx, length: protoArray.length()});
274
+
275
+ // forkchoiceConstructor is only used for some test cases
276
+ // production code use ForkChoice constructor directly
277
+ const forkchoiceConstructor = opts.forkchoiceConstructor ?? ForkChoice;
278
+
279
+ return new forkchoiceConstructor(
280
+ config,
281
+ store,
282
+ protoArray,
283
+ unfinalizedState.validators.length,
108
284
  metrics,
109
285
  opts,
110
286
  logger
@@ -178,6 +178,8 @@ export interface IBeaconChain {
178
178
  stateRoot: RootHex,
179
179
  opts?: StateGetOpts
180
180
  ): Promise<{state: BeaconStateAllForks; executionOptimistic: boolean; finalized: boolean} | null>;
181
+ /** Return serialized bytes of a persisted checkpoint state */
182
+ getPersistedCheckpointState(checkpoint?: phase0.Checkpoint): Promise<Uint8Array | null>;
181
183
  /** Returns a cached state by checkpoint */
182
184
  getStateByCheckpoint(
183
185
  checkpoint: CheckpointWithHex
@@ -8,6 +8,7 @@ import {ShufflingCacheOpts} from "./shufflingCache.js";
8
8
  import {DEFAULT_MAX_BLOCK_STATES, FIFOBlockStateCacheOpts} from "./stateCache/fifoBlockStateCache.js";
9
9
  import {
10
10
  DEFAULT_MAX_CP_STATE_EPOCHS_IN_MEMORY,
11
+ DEFAULT_MAX_CP_STATE_ON_DISK,
11
12
  PersistentCheckpointStateCacheOpts,
12
13
  } from "./stateCache/persistentCheckpointsCache.js";
13
14
  import {ValidatorMonitorOpts} from "./validatorMonitor.js";
@@ -41,8 +42,6 @@ export type IChainOptions = BlockProcessOpts &
41
42
  maxCachedBlobSidecars?: number;
42
43
  /** Max number of produced block roots (blinded or full) cached for broadcast validations */
43
44
  maxCachedProducedRoots?: number;
44
- /** Subscribe to and custody all data column sidecar subnets */
45
- supernode?: boolean;
46
45
  initialCustodyGroupCount?: number;
47
46
  broadcastValidationStrictness?: string;
48
47
  minSameMessageSignatureSetsToBatch: number;
@@ -118,7 +117,6 @@ export const defaultChainOptions: IChainOptions = {
118
117
  archiveMode: DEFAULT_ARCHIVE_MODE,
119
118
  pruneHistory: false,
120
119
  emitPayloadAttributes: false,
121
- supernode: false,
122
120
  // for gossip block validation, it's unlikely we see a reorg with 32 slots
123
121
  // for attestation validation, having this value ensures we don't have to regen states most of the time
124
122
  maxSkipSlots: 32,
@@ -135,4 +133,5 @@ export const defaultChainOptions: IChainOptions = {
135
133
  nHistoricalStatesFileDataStore: true,
136
134
  maxBlockStates: DEFAULT_MAX_BLOCK_STATES,
137
135
  maxCPStateEpochsInMemory: DEFAULT_MAX_CP_STATE_EPOCHS_IN_MEMORY,
136
+ maxCPStateEpochsOnDisk: DEFAULT_MAX_CP_STATE_ON_DISK,
138
137
  };
@@ -1,5 +1,11 @@
1
- import {phase0, ssz} from "@lodestar/types";
1
+ import {SLOTS_PER_EPOCH} from "@lodestar/params";
2
+ import {Epoch, phase0, ssz} from "@lodestar/types";
3
+ import {MapDef} from "@lodestar/utils";
2
4
  import {IBeaconDb} from "../../../db/interface.js";
5
+ import {
6
+ getLastProcessedSlotFromBeaconStateSerialized,
7
+ getSlotFromBeaconStateSerialized,
8
+ } from "../../../util/sszBytes.js";
3
9
  import {CPStateDatastore, DatastoreKey} from "./types.js";
4
10
 
5
11
  /**
@@ -22,6 +28,13 @@ export class DbCPStateDatastore implements CPStateDatastore {
22
28
  return this.db.checkpointState.getBinary(serializedCheckpoint);
23
29
  }
24
30
 
31
+ async readLatestSafe(): Promise<Uint8Array | null> {
32
+ const allKeys = await this.readKeys();
33
+ if (allKeys.length === 0) return null;
34
+
35
+ return getLatestSafeDatastoreKey(allKeys, this.read.bind(this));
36
+ }
37
+
25
38
  async readKeys(): Promise<DatastoreKey[]> {
26
39
  return this.db.checkpointState.keys();
27
40
  }
@@ -34,3 +47,78 @@ export function datastoreKeyToCheckpoint(key: DatastoreKey): phase0.Checkpoint {
34
47
  export function checkpointToDatastoreKey(cp: phase0.Checkpoint): DatastoreKey {
35
48
  return ssz.phase0.Checkpoint.serialize(cp);
36
49
  }
50
+
51
+ /**
52
+ * Get the latest safe checkpoint state the node can use to boot from
53
+ * - it should be the checkpoint state that's unique in its epoch
54
+ * - its last processed block slot should be at epoch boundary or last slot of previous epoch
55
+ * - state slot should be at epoch boundary
56
+ * - state slot should be equal to epoch * SLOTS_PER_EPOCH
57
+ *
58
+ * return the serialized data of Current Root Checkpoint State (CRCS) or Previous Root Checkpoint State (PRCS)
59
+ *
60
+ */
61
+ export async function getLatestSafeDatastoreKey(
62
+ allKeys: DatastoreKey[],
63
+ readFn: (key: DatastoreKey) => Promise<Uint8Array | null>
64
+ ): Promise<Uint8Array | null> {
65
+ const checkpointsByEpoch = new MapDef<Epoch, DatastoreKey[]>(() => []);
66
+ for (const key of allKeys) {
67
+ const cp = datastoreKeyToCheckpoint(key);
68
+ checkpointsByEpoch.getOrDefault(cp.epoch).push(key);
69
+ }
70
+
71
+ const dataStoreKeyByEpoch: Map<Epoch, DatastoreKey> = new Map();
72
+ for (const [epoch, keys] of checkpointsByEpoch.entries()) {
73
+ // only consider epochs with a single checkpoint to avoid ambiguity from forks
74
+ if (keys.length === 1) {
75
+ dataStoreKeyByEpoch.set(epoch, keys[0]);
76
+ }
77
+ }
78
+
79
+ const epochsDesc = Array.from(dataStoreKeyByEpoch.keys()).sort((a, b) => b - a);
80
+ for (const epoch of epochsDesc) {
81
+ const datastoreKey = dataStoreKeyByEpoch.get(epoch);
82
+ if (datastoreKey == null) {
83
+ // should not happen
84
+ continue;
85
+ }
86
+
87
+ const stateBytes = await readFn(datastoreKey);
88
+ if (stateBytes == null) {
89
+ // should not happen
90
+ continue;
91
+ }
92
+
93
+ const lastProcessedSlot = getLastProcessedSlotFromBeaconStateSerialized(stateBytes);
94
+ if (lastProcessedSlot == null) {
95
+ // cannot extract last processed slot from serialized state, skip
96
+ continue;
97
+ }
98
+
99
+ const stateSlot = getSlotFromBeaconStateSerialized(stateBytes);
100
+ if (stateSlot == null) {
101
+ // cannot extract slot from serialized state, skip
102
+ continue;
103
+ }
104
+
105
+ if (lastProcessedSlot !== stateSlot && lastProcessedSlot !== stateSlot - 1) {
106
+ // not CRCS or PRCS, skip
107
+ continue;
108
+ }
109
+
110
+ if (stateSlot % SLOTS_PER_EPOCH !== 0) {
111
+ // not at epoch boundary, skip
112
+ continue;
113
+ }
114
+
115
+ if (stateSlot !== SLOTS_PER_EPOCH * epoch) {
116
+ // should not happen after above checks, but just to be safe
117
+ continue;
118
+ }
119
+
120
+ return stateBytes;
121
+ }
122
+
123
+ return null;
124
+ }
@@ -2,6 +2,7 @@ import path from "node:path";
2
2
  import {phase0, ssz} from "@lodestar/types";
3
3
  import {fromHex, toHex} from "@lodestar/utils";
4
4
  import {ensureDir, readFile, readFileNames, removeFile, writeIfNotExist} from "../../../util/file.js";
5
+ import {getLatestSafeDatastoreKey} from "./db.js";
5
6
  import {CPStateDatastore, DatastoreKey} from "./types.js";
6
7
 
7
8
  const CHECKPOINT_STATES_FOLDER = "checkpoint_states";
@@ -44,6 +45,13 @@ export class FileCPStateDatastore implements CPStateDatastore {
44
45
  return readFile(filePath);
45
46
  }
46
47
 
48
+ async readLatestSafe(): Promise<Uint8Array | null> {
49
+ const allKeys = await this.readKeys();
50
+ if (allKeys.length === 0) return null;
51
+
52
+ return getLatestSafeDatastoreKey(allKeys, this.read.bind(this));
53
+ }
54
+
47
55
  async readKeys(): Promise<DatastoreKey[]> {
48
56
  const fileNames = await readFileNames(this.folderPath);
49
57
  return fileNames
@@ -8,6 +8,7 @@ export interface CPStateDatastore {
8
8
  write: (cpKey: phase0.Checkpoint, stateBytes: Uint8Array) => Promise<DatastoreKey>;
9
9
  remove: (key: DatastoreKey) => Promise<void>;
10
10
  read: (key: DatastoreKey) => Promise<Uint8Array | null>;
11
+ readLatestSafe: () => Promise<Uint8Array | null>;
11
12
  readKeys: () => Promise<DatastoreKey[]>;
12
13
  init?: () => Promise<void>;
13
14
  }
@@ -17,8 +17,10 @@ import {MapTracker} from "./mapMetrics.js";
17
17
  import {BlockStateCache, CacheItemType, CheckpointHex, CheckpointStateCache} from "./types.js";
18
18
 
19
19
  export type PersistentCheckpointStateCacheOpts = {
20
- /** Keep max n states in memory, persist the rest to disk */
20
+ /** Keep max n state epochs in memory, persist the rest to disk */
21
21
  maxCPStateEpochsInMemory?: number;
22
+ /** Keep max n state epochs on disk */
23
+ maxCPStateEpochsOnDisk?: number;
22
24
  };
23
25
 
24
26
  type PersistentCheckpointStateCacheModules = {
@@ -58,6 +60,14 @@ type LoadedStateBytesData = {persistedKey: DatastoreKey; stateBytes: Uint8Array}
58
60
  */
59
61
  export const DEFAULT_MAX_CP_STATE_EPOCHS_IN_MEMORY = 3;
60
62
 
63
+ /**
64
+ * By default we don't prune any persistent checkpoint states as it's not safe to delete them during
65
+ * long non-finality as we don't know the state of the chain and there could be a deep (hundreds of epochs) reorg
66
+ * if there two competing chains with similar weight but we wouldn't have a close enough state to pivot to this chain
67
+ * and instead require a resync from last finalized checkpoint state which could be very far in the past.
68
+ */
69
+ export const DEFAULT_MAX_CP_STATE_ON_DISK = Infinity;
70
+
61
71
  // TODO GLOAS: re-evaluate this timing
62
72
  const PROCESS_CHECKPOINT_STATES_BPS = 6667;
63
73
 
@@ -104,6 +114,7 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
104
114
  private preComputedCheckpoint: string | null = null;
105
115
  private preComputedCheckpointHits: number | null = null;
106
116
  private readonly maxEpochsInMemory: number;
117
+ private readonly maxEpochsOnDisk: number;
107
118
  private readonly datastore: CPStateDatastore;
108
119
  private readonly blockStateCache: BlockStateCache;
109
120
  private readonly bufferPool?: BufferPool | null;
@@ -139,10 +150,16 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
139
150
  this.logger = logger;
140
151
  this.clock = clock;
141
152
  this.signal = signal;
153
+
142
154
  if (opts.maxCPStateEpochsInMemory !== undefined && opts.maxCPStateEpochsInMemory < 0) {
143
155
  throw new Error("maxEpochsInMemory must be >= 0");
144
156
  }
157
+ if (opts.maxCPStateEpochsOnDisk !== undefined && opts.maxCPStateEpochsOnDisk < 0) {
158
+ throw new Error("maxCPStateEpochsOnDisk must be >= 0");
159
+ }
160
+
145
161
  this.maxEpochsInMemory = opts.maxCPStateEpochsInMemory ?? DEFAULT_MAX_CP_STATE_EPOCHS_IN_MEMORY;
162
+ this.maxEpochsOnDisk = opts.maxCPStateEpochsOnDisk ?? DEFAULT_MAX_CP_STATE_ON_DISK;
146
163
  // Specify different datastore for testing
147
164
  this.datastore = datastore;
148
165
  this.blockStateCache = blockStateCache;
@@ -324,6 +341,7 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
324
341
  this.logger.verbose("Added checkpoint state to memory", {epoch: cp.epoch, rootHex: cpHex.rootHex});
325
342
  }
326
343
  this.epochIndex.getOrDefault(cp.epoch).add(cpHex.rootHex);
344
+ this.prunePersistedStates();
327
345
  }
328
346
 
329
347
  /**
@@ -766,13 +784,38 @@ export class PersistentCheckpointStateCache implements CheckpointStateCache {
766
784
  this.cache.delete(key);
767
785
  }
768
786
  this.epochIndex.delete(epoch);
769
- this.logger.verbose("Pruned finalized checkpoints states for epoch", {
787
+ this.logger.verbose("Pruned checkpoint states for epoch", {
770
788
  epoch,
771
789
  persistCount,
772
790
  rootHexes: Array.from(rootHexes).join(","),
773
791
  });
774
792
  }
775
793
 
794
+ /**
795
+ * Prune persisted checkpoint states from disk.
796
+ * Note that this should handle all possible errors and not throw.
797
+ */
798
+ private prunePersistedStates(): void {
799
+ // epochsOnDisk epochsInMemory
800
+ // |----------------------------------------------------------|----------------------|
801
+ const maxTrackedEpochs = this.maxEpochsOnDisk + this.maxEpochsInMemory;
802
+ if (this.epochIndex.size <= maxTrackedEpochs) {
803
+ return;
804
+ }
805
+
806
+ const sortedEpochs = Array.from(this.epochIndex.keys()).sort((a, b) => a - b);
807
+ const pruneEpochs = sortedEpochs.slice(0, sortedEpochs.length - maxTrackedEpochs);
808
+ for (const epoch of pruneEpochs) {
809
+ this.deleteAllEpochItems(epoch).catch((e) =>
810
+ this.logger.debug(
811
+ "Error delete all epoch items",
812
+ {epoch, maxEpochsOnDisk: this.maxEpochsOnDisk, maxEpochsInMemory: this.maxEpochsInMemory},
813
+ e as Error
814
+ )
815
+ );
816
+ }
817
+ }
818
+
776
819
  /**
777
820
  * Serialize validators to bytes leveraging the buffer pool to save memory allocation.
778
821
  * - As monitored on holesky as of Jan 2024, it helps save ~500ms state reload time (4.3s vs 3.8s)
@@ -1,10 +1,14 @@
1
- import {ChainConfig} from "@lodestar/config";
1
+ import {ChainConfig, ChainForkConfig} from "@lodestar/config";
2
2
  import {
3
3
  KZG_COMMITMENTS_INCLUSION_PROOF_DEPTH,
4
4
  KZG_COMMITMENTS_SUBTREE_INDEX,
5
5
  NUMBER_OF_COLUMNS,
6
6
  } from "@lodestar/params";
7
- import {computeStartSlotAtEpoch, getBlockHeaderProposerSignatureSet} from "@lodestar/state-transition";
7
+ import {
8
+ computeEpochAtSlot,
9
+ computeStartSlotAtEpoch,
10
+ getBlockHeaderProposerSignatureSet,
11
+ } from "@lodestar/state-transition";
8
12
  import {Root, Slot, SubnetID, fulu, ssz} from "@lodestar/types";
9
13
  import {toRootHex, verifyMerkleBranch} from "@lodestar/utils";
10
14
  import {Metrics} from "../../metrics/metrics.js";
@@ -29,13 +33,13 @@ export async function validateGossipDataColumnSidecar(
29
33
  const blockHeader = dataColumnSidecar.signedBlockHeader.message;
30
34
 
31
35
  // 1) [REJECT] The sidecar is valid as verified by verify_data_column_sidecar
32
- verifyDataColumnSidecar(dataColumnSidecar);
36
+ verifyDataColumnSidecar(chain.config, dataColumnSidecar);
33
37
 
34
38
  // 2) [REJECT] The sidecar is for the correct subnet -- i.e. compute_subnet_for_data_column_sidecar(sidecar.index) == subnet_id
35
39
  if (computeSubnetForDataColumnSidecar(chain.config, dataColumnSidecar) !== gossipSubnet) {
36
40
  throw new DataColumnSidecarGossipError(GossipAction.REJECT, {
37
41
  code: DataColumnSidecarErrorCode.INVALID_SUBNET,
38
- columnIdx: dataColumnSidecar.index,
42
+ columnIndex: dataColumnSidecar.index,
39
43
  gossipSubnet: gossipSubnet,
40
44
  });
41
45
  }
@@ -152,7 +156,7 @@ export async function validateGossipDataColumnSidecar(
152
156
  throw new DataColumnSidecarGossipError(GossipAction.REJECT, {
153
157
  code: DataColumnSidecarErrorCode.INCLUSION_PROOF_INVALID,
154
158
  slot: dataColumnSidecar.signedBlockHeader.message.slot,
155
- columnIdx: dataColumnSidecar.index,
159
+ columnIndex: dataColumnSidecar.index,
156
160
  });
157
161
  }
158
162
 
@@ -169,7 +173,7 @@ export async function validateGossipDataColumnSidecar(
169
173
  throw new DataColumnSidecarGossipError(GossipAction.REJECT, {
170
174
  code: DataColumnSidecarErrorCode.INVALID_KZG_PROOF,
171
175
  slot: blockHeader.slot,
172
- columnIdx: dataColumnSidecar.index,
176
+ columnIndex: dataColumnSidecar.index,
173
177
  });
174
178
  } finally {
175
179
  kzgProofTimer?.();
@@ -184,12 +188,12 @@ export async function validateGossipDataColumnSidecar(
184
188
  * SPEC FUNCTION
185
189
  * https://github.com/ethereum/consensus-specs/blob/v1.6.0-alpha.4/specs/fulu/p2p-interface.md#verify_data_column_sidecar
186
190
  */
187
- function verifyDataColumnSidecar(dataColumnSidecar: fulu.DataColumnSidecar): void {
191
+ function verifyDataColumnSidecar(config: ChainForkConfig, dataColumnSidecar: fulu.DataColumnSidecar): void {
188
192
  if (dataColumnSidecar.index >= NUMBER_OF_COLUMNS) {
189
193
  throw new DataColumnSidecarGossipError(GossipAction.REJECT, {
190
194
  code: DataColumnSidecarErrorCode.INVALID_INDEX,
191
195
  slot: dataColumnSidecar.signedBlockHeader.message.slot,
192
- columnIdx: dataColumnSidecar.index,
196
+ columnIndex: dataColumnSidecar.index,
193
197
  });
194
198
  }
195
199
 
@@ -197,7 +201,20 @@ function verifyDataColumnSidecar(dataColumnSidecar: fulu.DataColumnSidecar): voi
197
201
  throw new DataColumnSidecarGossipError(GossipAction.REJECT, {
198
202
  code: DataColumnSidecarErrorCode.NO_COMMITMENTS,
199
203
  slot: dataColumnSidecar.signedBlockHeader.message.slot,
200
- columnIdx: dataColumnSidecar.index,
204
+ columnIndex: dataColumnSidecar.index,
205
+ });
206
+ }
207
+
208
+ const epoch = computeEpochAtSlot(dataColumnSidecar.signedBlockHeader.message.slot);
209
+ const maxBlobsPerBlock = config.getMaxBlobsPerBlock(epoch);
210
+
211
+ if (dataColumnSidecar.kzgCommitments.length > maxBlobsPerBlock) {
212
+ throw new DataColumnSidecarGossipError(GossipAction.REJECT, {
213
+ code: DataColumnSidecarErrorCode.TOO_MANY_KZG_COMMITMENTS,
214
+ slot: dataColumnSidecar.signedBlockHeader.message.slot,
215
+ columnIndex: dataColumnSidecar.index,
216
+ count: dataColumnSidecar.kzgCommitments.length,
217
+ limit: maxBlobsPerBlock,
201
218
  });
202
219
  }
203
220
 
@@ -276,7 +293,6 @@ export async function validateBlockDataColumnSidecars(
276
293
  "Block has no blob commitments but data column sidecars were provided"
277
294
  );
278
295
  }
279
-
280
296
  // Hash the first sidecar block header and compare the rest via (cheaper) equality
281
297
  const firstSidecarBlockHeader = dataColumnSidecars[0].signedBlockHeader.message;
282
298
  const firstBlockRoot = ssz.phase0.BeaconBlockHeader.hashTreeRoot(firstSidecarBlockHeader);
@@ -285,7 +301,7 @@ export async function validateBlockDataColumnSidecars(
285
301
  {
286
302
  code: DataColumnSidecarErrorCode.INCORRECT_BLOCK,
287
303
  slot: blockSlot,
288
- columnIdx: 0,
304
+ columnIndex: 0,
289
305
  expected: toRootHex(blockRoot),
290
306
  actual: toRootHex(firstBlockRoot),
291
307
  },
@@ -300,33 +316,52 @@ export async function validateBlockDataColumnSidecars(
300
316
  for (let i = 0; i < dataColumnSidecars.length; i++) {
301
317
  const columnSidecar = dataColumnSidecars[i];
302
318
 
319
+ if (!ssz.phase0.BeaconBlockHeader.equals(firstSidecarBlockHeader, columnSidecar.signedBlockHeader.message)) {
320
+ throw new DataColumnSidecarValidationError({
321
+ code: DataColumnSidecarErrorCode.INCORRECT_HEADER_ROOT,
322
+ slot: blockSlot,
323
+ expected: toRootHex(blockRoot),
324
+ actual: toRootHex(ssz.phase0.BeaconBlockHeader.hashTreeRoot(columnSidecar.signedBlockHeader.message)),
325
+ });
326
+ }
327
+
303
328
  if (columnSidecar.index >= NUMBER_OF_COLUMNS) {
304
329
  throw new DataColumnSidecarValidationError(
305
330
  {
306
331
  code: DataColumnSidecarErrorCode.INVALID_INDEX,
307
332
  slot: blockSlot,
308
- columnIdx: columnSidecar.index,
333
+ columnIndex: columnSidecar.index,
309
334
  },
310
335
  "DataColumnSidecar has invalid index"
311
336
  );
312
337
  }
313
338
 
314
- if (columnSidecar.kzgCommitments.length !== blockBlobCount) {
339
+ if (columnSidecar.column.length !== blockBlobCount) {
315
340
  throw new DataColumnSidecarValidationError({
316
- code: DataColumnSidecarErrorCode.INCORRECT_KZG_COMMITMENTS_COUNT,
341
+ code: DataColumnSidecarErrorCode.INCORRECT_CELL_COUNT,
317
342
  slot: blockSlot,
318
- columnIdx: columnSidecar.index,
343
+ columnIndex: columnSidecar.index,
319
344
  expected: blockBlobCount,
345
+ actual: columnSidecar.column.length,
346
+ });
347
+ }
348
+
349
+ if (columnSidecar.column.length !== columnSidecar.kzgCommitments.length) {
350
+ throw new DataColumnSidecarValidationError({
351
+ code: DataColumnSidecarErrorCode.INCORRECT_KZG_COMMITMENTS_COUNT,
352
+ slot: blockSlot,
353
+ columnIndex: columnSidecar.index,
354
+ expected: columnSidecar.column.length,
320
355
  actual: columnSidecar.kzgCommitments.length,
321
356
  });
322
357
  }
323
358
 
324
- if (columnSidecar.kzgProofs.length !== columnSidecar.kzgCommitments.length) {
359
+ if (columnSidecar.column.length !== columnSidecar.kzgProofs.length) {
325
360
  throw new DataColumnSidecarValidationError({
326
361
  code: DataColumnSidecarErrorCode.INCORRECT_KZG_PROOF_COUNT,
327
362
  slot: blockSlot,
328
- columnIdx: columnSidecar.index,
329
- expected: columnSidecar.kzgCommitments.length,
363
+ columnIndex: columnSidecar.index,
364
+ expected: columnSidecar.column.length,
330
365
  actual: columnSidecar.kzgProofs.length,
331
366
  });
332
367
  }
@@ -336,7 +371,7 @@ export async function validateBlockDataColumnSidecars(
336
371
  {
337
372
  code: DataColumnSidecarErrorCode.INCLUSION_PROOF_INVALID,
338
373
  slot: blockSlot,
339
- columnIdx: columnSidecar.index,
374
+ columnIndex: columnSidecar.index,
340
375
  },
341
376
  "DataColumnSidecar has invalid inclusion proof"
342
377
  );
package/src/index.ts CHANGED
@@ -3,6 +3,8 @@
3
3
  export type {RestApiServerMetrics, RestApiServerModules, RestApiServerOpts} from "./api/rest/base.js";
4
4
  export {RestApiServer} from "./api/rest/base.js";
5
5
  export {checkAndPersistAnchorState, initStateFromDb, initStateFromEth1} from "./chain/index.js";
6
+ export {DbCPStateDatastore} from "./chain/stateCache/datastore/db.js";
7
+ export {FileCPStateDatastore} from "./chain/stateCache/datastore/file.js";
6
8
  export {BeaconDb, type IBeaconDb} from "./db/index.js";
7
9
  export {Eth1Provider, type IEth1Provider} from "./eth1/index.js";
8
10
  // Export metrics utilities to de-duplicate validator metrics