@lodestar/beacon-node 1.47.0-dev.09607ce6d4 → 1.47.0-dev.101e2c290d

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 (303) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +3 -2
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/beacon/pool/index.d.ts.map +1 -1
  5. package/lib/api/impl/beacon/pool/index.js +21 -2
  6. package/lib/api/impl/beacon/pool/index.js.map +1 -1
  7. package/lib/api/impl/beacon/state/utils.d.ts +2 -1
  8. package/lib/api/impl/beacon/state/utils.d.ts.map +1 -1
  9. package/lib/api/impl/beacon/state/utils.js.map +1 -1
  10. package/lib/api/impl/events/index.d.ts +1 -1
  11. package/lib/api/impl/events/index.d.ts.map +1 -1
  12. package/lib/api/impl/events/index.js +12 -3
  13. package/lib/api/impl/events/index.js.map +1 -1
  14. package/lib/api/impl/lodestar/index.js +1 -1
  15. package/lib/api/impl/lodestar/index.js.map +1 -1
  16. package/lib/api/rest/base.d.ts.map +1 -1
  17. package/lib/api/rest/base.js +7 -0
  18. package/lib/api/rest/base.js.map +1 -1
  19. package/lib/chain/archiveStore/archiveStore.js +1 -1
  20. package/lib/chain/archiveStore/archiveStore.js.map +1 -1
  21. package/lib/chain/blocks/importExecutionPayload.d.ts +3 -2
  22. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  23. package/lib/chain/blocks/importExecutionPayload.js +11 -9
  24. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  25. package/lib/chain/blocks/index.d.ts.map +1 -1
  26. package/lib/chain/blocks/index.js +14 -6
  27. package/lib/chain/blocks/index.js.map +1 -1
  28. package/lib/chain/blocks/payloadEnvelopeInput/payloadEnvelopeInput.d.ts +2 -1
  29. package/lib/chain/blocks/payloadEnvelopeInput/payloadEnvelopeInput.d.ts.map +1 -1
  30. package/lib/chain/blocks/payloadEnvelopeInput/payloadEnvelopeInput.js +6 -2
  31. package/lib/chain/blocks/payloadEnvelopeInput/payloadEnvelopeInput.js.map +1 -1
  32. package/lib/chain/blocks/payloadEnvelopeInput/types.d.ts +14 -5
  33. package/lib/chain/blocks/payloadEnvelopeInput/types.d.ts.map +1 -1
  34. package/lib/chain/blocks/payloadEnvelopeInput/types.js +5 -0
  35. package/lib/chain/blocks/payloadEnvelopeInput/types.js.map +1 -1
  36. package/lib/chain/blocks/verifyBlocksStateTransitionOnly.d.ts.map +1 -1
  37. package/lib/chain/blocks/verifyBlocksStateTransitionOnly.js +22 -12
  38. package/lib/chain/blocks/verifyBlocksStateTransitionOnly.js.map +1 -1
  39. package/lib/chain/blocks/verifyExecutionPayloadEnvelope.d.ts +2 -2
  40. package/lib/chain/blocks/verifyExecutionPayloadEnvelope.d.ts.map +1 -1
  41. package/lib/chain/blocks/verifyExecutionPayloadEnvelope.js +2 -2
  42. package/lib/chain/blocks/verifyExecutionPayloadEnvelope.js.map +1 -1
  43. package/lib/chain/bls/index.d.ts +1 -1
  44. package/lib/chain/bls/index.d.ts.map +1 -1
  45. package/lib/chain/bls/interface.d.ts +5 -5
  46. package/lib/chain/bls/interface.d.ts.map +1 -1
  47. package/lib/chain/bls/multithread/index.d.ts +5 -11
  48. package/lib/chain/bls/multithread/index.d.ts.map +1 -1
  49. package/lib/chain/bls/multithread/index.js +116 -101
  50. package/lib/chain/bls/multithread/index.js.map +1 -1
  51. package/lib/chain/bls/multithread/jobItem.d.ts +5 -19
  52. package/lib/chain/bls/multithread/jobItem.d.ts.map +1 -1
  53. package/lib/chain/bls/multithread/jobItem.js +10 -65
  54. package/lib/chain/bls/multithread/jobItem.js.map +1 -1
  55. package/lib/chain/bls/multithread/types.d.ts +29 -8
  56. package/lib/chain/bls/multithread/types.d.ts.map +1 -1
  57. package/lib/chain/bls/multithread/types.js +12 -0
  58. package/lib/chain/bls/multithread/types.js.map +1 -1
  59. package/lib/chain/bls/multithread/utils.d.ts +4 -0
  60. package/lib/chain/bls/multithread/utils.d.ts.map +1 -1
  61. package/lib/chain/bls/multithread/utils.js +10 -0
  62. package/lib/chain/bls/multithread/utils.js.map +1 -1
  63. package/lib/chain/bls/multithread/worker.js +49 -23
  64. package/lib/chain/bls/multithread/worker.js.map +1 -1
  65. package/lib/chain/bls/singleThread.d.ts +4 -10
  66. package/lib/chain/bls/singleThread.d.ts.map +1 -1
  67. package/lib/chain/bls/singleThread.js +8 -45
  68. package/lib/chain/bls/singleThread.js.map +1 -1
  69. package/lib/chain/bls/utils.d.ts +4 -4
  70. package/lib/chain/bls/utils.d.ts.map +1 -1
  71. package/lib/chain/bls/utils.js +18 -19
  72. package/lib/chain/bls/utils.js.map +1 -1
  73. package/lib/chain/chain.d.ts +4 -2
  74. package/lib/chain/chain.d.ts.map +1 -1
  75. package/lib/chain/chain.js +16 -6
  76. package/lib/chain/chain.js.map +1 -1
  77. package/lib/chain/errors/blockError.d.ts +1 -0
  78. package/lib/chain/errors/blockError.d.ts.map +1 -1
  79. package/lib/chain/errors/blockError.js +6 -1
  80. package/lib/chain/errors/blockError.js.map +1 -1
  81. package/lib/chain/errors/proposerPreferences.d.ts +6 -0
  82. package/lib/chain/errors/proposerPreferences.d.ts.map +1 -1
  83. package/lib/chain/errors/proposerPreferences.js +1 -0
  84. package/lib/chain/errors/proposerPreferences.js.map +1 -1
  85. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  86. package/lib/chain/forkChoice/index.js +4 -0
  87. package/lib/chain/forkChoice/index.js.map +1 -1
  88. package/lib/chain/interface.d.ts +4 -2
  89. package/lib/chain/interface.d.ts.map +1 -1
  90. package/lib/chain/interface.js.map +1 -1
  91. package/lib/chain/opPools/aggregatedAttestationPool.js +1 -1
  92. package/lib/chain/opPools/aggregatedAttestationPool.js.map +1 -1
  93. package/lib/chain/opPools/attestationPool.d.ts +1 -1
  94. package/lib/chain/opPools/attestationPool.d.ts.map +1 -1
  95. package/lib/chain/opPools/attestationPool.js +1 -1
  96. package/lib/chain/opPools/attestationPool.js.map +1 -1
  97. package/lib/chain/opPools/deferredVoluntaryExitPool.d.ts +16 -0
  98. package/lib/chain/opPools/deferredVoluntaryExitPool.d.ts.map +1 -0
  99. package/lib/chain/opPools/deferredVoluntaryExitPool.js +57 -0
  100. package/lib/chain/opPools/deferredVoluntaryExitPool.js.map +1 -0
  101. package/lib/chain/opPools/index.d.ts +1 -0
  102. package/lib/chain/opPools/index.d.ts.map +1 -1
  103. package/lib/chain/opPools/index.js +1 -0
  104. package/lib/chain/opPools/index.js.map +1 -1
  105. package/lib/chain/opPools/payloadAttestationPool.js +3 -3
  106. package/lib/chain/opPools/payloadAttestationPool.js.map +1 -1
  107. package/lib/chain/opPools/syncCommitteeMessagePool.js +1 -1
  108. package/lib/chain/opPools/syncCommitteeMessagePool.js.map +1 -1
  109. package/lib/chain/opPools/syncContributionAndProofPool.js +1 -1
  110. package/lib/chain/opPools/syncContributionAndProofPool.js.map +1 -1
  111. package/lib/chain/opPools/utils.d.ts +1 -1
  112. package/lib/chain/opPools/utils.d.ts.map +1 -1
  113. package/lib/chain/opPools/utils.js +1 -1
  114. package/lib/chain/opPools/utils.js.map +1 -1
  115. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  116. package/lib/chain/prepareNextSlot.js +23 -5
  117. package/lib/chain/prepareNextSlot.js.map +1 -1
  118. package/lib/chain/regen/interface.d.ts +4 -2
  119. package/lib/chain/regen/interface.d.ts.map +1 -1
  120. package/lib/chain/regen/interface.js +2 -0
  121. package/lib/chain/regen/interface.js.map +1 -1
  122. package/lib/chain/regen/queued.d.ts +2 -2
  123. package/lib/chain/regen/queued.d.ts.map +1 -1
  124. package/lib/chain/regen/queued.js +5 -5
  125. package/lib/chain/regen/queued.js.map +1 -1
  126. package/lib/chain/seenCache/seenAttesters.d.ts +9 -5
  127. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  128. package/lib/chain/seenCache/seenAttesters.js +25 -4
  129. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  130. package/lib/chain/seenCache/seenPayloadEnvelopeInput.d.ts +28 -1
  131. package/lib/chain/seenCache/seenPayloadEnvelopeInput.d.ts.map +1 -1
  132. package/lib/chain/seenCache/seenPayloadEnvelopeInput.js +121 -13
  133. package/lib/chain/seenCache/seenPayloadEnvelopeInput.js.map +1 -1
  134. package/lib/chain/stateCache/fifoBlockStateCache.d.ts +5 -1
  135. package/lib/chain/stateCache/fifoBlockStateCache.d.ts.map +1 -1
  136. package/lib/chain/stateCache/fifoBlockStateCache.js +6 -0
  137. package/lib/chain/stateCache/fifoBlockStateCache.js.map +1 -1
  138. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts +47 -5
  139. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts.map +1 -1
  140. package/lib/chain/stateCache/persistentCheckpointsCache.js +117 -7
  141. package/lib/chain/stateCache/persistentCheckpointsCache.js.map +1 -1
  142. package/lib/chain/stateCache/types.d.ts +3 -3
  143. package/lib/chain/stateCache/types.d.ts.map +1 -1
  144. package/lib/chain/validation/attestation.d.ts.map +1 -1
  145. package/lib/chain/validation/attestation.js +1 -4
  146. package/lib/chain/validation/attestation.js.map +1 -1
  147. package/lib/chain/validation/attesterSlashing.d.ts.map +1 -1
  148. package/lib/chain/validation/attesterSlashing.js +1 -1
  149. package/lib/chain/validation/attesterSlashing.js.map +1 -1
  150. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  151. package/lib/chain/validation/executionPayloadBid.js +1 -2
  152. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  153. package/lib/chain/validation/executionPayloadEnvelope.js +1 -1
  154. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  155. package/lib/chain/validation/payloadAttestationMessage.d.ts.map +1 -1
  156. package/lib/chain/validation/payloadAttestationMessage.js +5 -14
  157. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  158. package/lib/chain/validation/proposerPreferences.d.ts +1 -1
  159. package/lib/chain/validation/proposerPreferences.d.ts.map +1 -1
  160. package/lib/chain/validation/proposerPreferences.js +13 -4
  161. package/lib/chain/validation/proposerPreferences.js.map +1 -1
  162. package/lib/chain/validation/proposerSlashing.js +1 -1
  163. package/lib/chain/validation/proposerSlashing.js.map +1 -1
  164. package/lib/chain/validation/voluntaryExit.d.ts +9 -1
  165. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  166. package/lib/chain/validation/voluntaryExit.js +46 -1
  167. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  168. package/lib/metrics/metrics/lodestar.d.ts +62 -22
  169. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  170. package/lib/metrics/metrics/lodestar.js +114 -52
  171. package/lib/metrics/metrics/lodestar.js.map +1 -1
  172. package/lib/network/gossip/topic.d.ts +13 -0
  173. package/lib/network/gossip/topic.d.ts.map +1 -1
  174. package/lib/network/gossip/topic.js +37 -0
  175. package/lib/network/gossip/topic.js.map +1 -1
  176. package/lib/network/libp2p/index.d.ts.map +1 -1
  177. package/lib/network/libp2p/index.js +10 -2
  178. package/lib/network/libp2p/index.js.map +1 -1
  179. package/lib/network/network.d.ts.map +1 -1
  180. package/lib/network/network.js +22 -43
  181. package/lib/network/network.js.map +1 -1
  182. package/lib/network/processor/constants.d.ts +7 -0
  183. package/lib/network/processor/constants.d.ts.map +1 -0
  184. package/lib/network/processor/constants.js +7 -0
  185. package/lib/network/processor/constants.js.map +1 -0
  186. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  187. package/lib/network/processor/gossipHandlers.js +5 -1
  188. package/lib/network/processor/gossipHandlers.js.map +1 -1
  189. package/lib/network/processor/index.d.ts +3 -0
  190. package/lib/network/processor/index.d.ts.map +1 -1
  191. package/lib/network/processor/index.js +36 -15
  192. package/lib/network/processor/index.js.map +1 -1
  193. package/lib/network/reqresp/score.d.ts.map +1 -1
  194. package/lib/network/reqresp/score.js +5 -11
  195. package/lib/network/reqresp/score.js.map +1 -1
  196. package/lib/network/util.d.ts +0 -1
  197. package/lib/network/util.d.ts.map +1 -1
  198. package/lib/network/util.js +0 -4
  199. package/lib/network/util.js.map +1 -1
  200. package/lib/node/deferredVoluntaryExitPublisher.d.ts +15 -0
  201. package/lib/node/deferredVoluntaryExitPublisher.d.ts.map +1 -0
  202. package/lib/node/deferredVoluntaryExitPublisher.js +38 -0
  203. package/lib/node/deferredVoluntaryExitPublisher.js.map +1 -0
  204. package/lib/node/nodejs.d.ts +2 -1
  205. package/lib/node/nodejs.d.ts.map +1 -1
  206. package/lib/node/nodejs.js +2 -0
  207. package/lib/node/nodejs.js.map +1 -1
  208. package/lib/sync/range/batch.d.ts +23 -5
  209. package/lib/sync/range/batch.d.ts.map +1 -1
  210. package/lib/sync/range/batch.js +61 -22
  211. package/lib/sync/range/batch.js.map +1 -1
  212. package/lib/sync/range/chain.d.ts +2 -1
  213. package/lib/sync/range/chain.d.ts.map +1 -1
  214. package/lib/sync/range/chain.js +23 -10
  215. package/lib/sync/range/chain.js.map +1 -1
  216. package/lib/sync/types.d.ts +32 -0
  217. package/lib/sync/types.d.ts.map +1 -1
  218. package/lib/sync/types.js +33 -0
  219. package/lib/sync/types.js.map +1 -1
  220. package/lib/sync/unknownBlock.d.ts +13 -2
  221. package/lib/sync/unknownBlock.d.ts.map +1 -1
  222. package/lib/sync/unknownBlock.js +204 -61
  223. package/lib/sync/unknownBlock.js.map +1 -1
  224. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  225. package/lib/sync/utils/downloadByRange.js +16 -11
  226. package/lib/sync/utils/downloadByRange.js.map +1 -1
  227. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  228. package/lib/sync/utils/downloadByRoot.js +3 -1
  229. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  230. package/package.json +35 -35
  231. package/src/api/impl/beacon/blocks/index.ts +3 -2
  232. package/src/api/impl/beacon/pool/index.ts +22 -2
  233. package/src/api/impl/beacon/state/utils.ts +2 -1
  234. package/src/api/impl/events/index.ts +12 -4
  235. package/src/api/impl/lodestar/index.ts +1 -1
  236. package/src/api/rest/base.ts +7 -0
  237. package/src/chain/archiveStore/archiveStore.ts +1 -1
  238. package/src/chain/blocks/importExecutionPayload.ts +12 -11
  239. package/src/chain/blocks/index.ts +18 -6
  240. package/src/chain/blocks/payloadEnvelopeInput/payloadEnvelopeInput.ts +8 -2
  241. package/src/chain/blocks/payloadEnvelopeInput/types.ts +17 -4
  242. package/src/chain/blocks/verifyBlocksStateTransitionOnly.ts +25 -16
  243. package/src/chain/blocks/verifyExecutionPayloadEnvelope.ts +1 -9
  244. package/src/chain/bls/index.ts +1 -1
  245. package/src/chain/bls/interface.ts +7 -3
  246. package/src/chain/bls/multithread/index.ts +148 -120
  247. package/src/chain/bls/multithread/jobItem.ts +12 -82
  248. package/src/chain/bls/multithread/types.ts +33 -8
  249. package/src/chain/bls/multithread/utils.ts +11 -0
  250. package/src/chain/bls/multithread/worker.ts +85 -27
  251. package/src/chain/bls/singleThread.ts +11 -55
  252. package/src/chain/bls/utils.ts +23 -24
  253. package/src/chain/chain.ts +17 -6
  254. package/src/chain/errors/blockError.ts +8 -2
  255. package/src/chain/errors/proposerPreferences.ts +7 -0
  256. package/src/chain/forkChoice/index.ts +4 -0
  257. package/src/chain/interface.ts +4 -1
  258. package/src/chain/opPools/aggregatedAttestationPool.ts +1 -1
  259. package/src/chain/opPools/attestationPool.ts +1 -1
  260. package/src/chain/opPools/deferredVoluntaryExitPool.ts +65 -0
  261. package/src/chain/opPools/index.ts +1 -0
  262. package/src/chain/opPools/payloadAttestationPool.ts +3 -3
  263. package/src/chain/opPools/syncCommitteeMessagePool.ts +1 -1
  264. package/src/chain/opPools/syncContributionAndProofPool.ts +1 -1
  265. package/src/chain/opPools/utils.ts +1 -1
  266. package/src/chain/prepareNextSlot.ts +23 -5
  267. package/src/chain/regen/interface.ts +4 -2
  268. package/src/chain/regen/queued.ts +5 -5
  269. package/src/chain/seenCache/seenAttesters.ts +31 -5
  270. package/src/chain/seenCache/seenPayloadEnvelopeInput.ts +143 -14
  271. package/src/chain/stateCache/fifoBlockStateCache.ts +8 -1
  272. package/src/chain/stateCache/persistentCheckpointsCache.ts +133 -8
  273. package/src/chain/stateCache/types.ts +3 -3
  274. package/src/chain/validation/attestation.ts +1 -7
  275. package/src/chain/validation/attesterSlashing.ts +1 -8
  276. package/src/chain/validation/executionPayloadBid.ts +1 -2
  277. package/src/chain/validation/executionPayloadEnvelope.ts +0 -1
  278. package/src/chain/validation/payloadAttestationMessage.ts +6 -17
  279. package/src/chain/validation/proposerPreferences.ts +15 -5
  280. package/src/chain/validation/proposerSlashing.ts +1 -1
  281. package/src/chain/validation/voluntaryExit.ts +59 -2
  282. package/src/metrics/metrics/lodestar.ts +126 -57
  283. package/src/network/gossip/topic.ts +38 -0
  284. package/src/network/libp2p/index.ts +11 -2
  285. package/src/network/network.ts +27 -55
  286. package/src/network/processor/constants.ts +6 -0
  287. package/src/network/processor/gossipHandlers.ts +5 -1
  288. package/src/network/processor/index.ts +42 -19
  289. package/src/network/reqresp/score.ts +5 -11
  290. package/src/network/util.ts +0 -5
  291. package/src/node/deferredVoluntaryExitPublisher.ts +54 -0
  292. package/src/node/nodejs.ts +5 -1
  293. package/src/sync/range/batch.ts +83 -28
  294. package/src/sync/range/chain.ts +26 -11
  295. package/src/sync/types.ts +36 -1
  296. package/src/sync/unknownBlock.ts +240 -68
  297. package/src/sync/utils/downloadByRange.ts +21 -12
  298. package/src/sync/utils/downloadByRoot.ts +3 -1
  299. package/lib/chain/bls/maybeBatch.d.ts +0 -12
  300. package/lib/chain/bls/maybeBatch.d.ts.map +0 -1
  301. package/lib/chain/bls/maybeBatch.js +0 -35
  302. package/lib/chain/bls/maybeBatch.js.map +0 -1
  303. package/src/chain/bls/maybeBatch.ts +0 -45
@@ -1,4 +1,4 @@
1
- import {Signature} from "@chainsafe/blst";
1
+ import {Signature} from "@chainsafe/lodestar-z/blst";
2
2
  import {BLS_WITHDRAWAL_PREFIX} from "@lodestar/params";
3
3
  import {IBeaconStateView} from "@lodestar/state-transition";
4
4
  import {Slot, capella} from "@lodestar/types";
@@ -151,23 +151,38 @@ export class PrepareNextSlotScheduler {
151
151
  const proposerIndex = await getProposerIndex();
152
152
  feeRecipient = this.chain.beaconProposerCache.get(proposerIndex);
153
153
 
154
- if (feeRecipient) {
155
- // If we are proposing next slot, we need to predict if we can proposer-boost-reorg or not
154
+ // Predict the proposer head of the next slot when either:
155
+ // - we are proposing the next slot (single-slot proposer-boost-reorg), or
156
+ // - this is an epoch transition: post-Fulu the next proposer may reorg a weak
157
+ // last-block-of-epoch and build slot 0 on the strong parent (epoch-boundary reorg),
158
+ // so we should dial the strong parent through the boundary instead of the weak head.
159
+ if (feeRecipient || isEpochTransition) {
156
160
  const proposerHead = this.chain.predictProposerHead(clockSlot);
157
161
  const {slot: proposerHeadSlot, blockRoot: proposerHeadRoot} = proposerHead;
158
162
 
159
- // If we predict we can reorg, we build on the proposer head (parent) block instead
163
+ // If we predict a reorg, we build the epoch transition on the proposer head (parent) instead
160
164
  if (proposerHeadRoot !== headRoot || proposerHeadSlot !== headSlot) {
161
- this.logger.verbose("Weak head detected. May build on parent block instead", {
165
+ // feeRecipient set => WE propose the next slot and may reorg it out ourselves;
166
+ // otherwise it's a predicted reorg by another proposer (epoch-boundary reorg).
167
+ const logMessage = feeRecipient
168
+ ? "Weak head detected. We may build on parent block instead"
169
+ : "Weak head detected. Another proposer may build on parent block instead";
170
+ this.logger.verbose(logMessage, {
162
171
  proposerHeadSlot,
163
172
  proposerHeadRoot,
164
173
  headSlot,
165
174
  headRoot,
175
+ isEpochTransition,
166
176
  });
167
177
  this.metrics?.weakHeadDetected.inc();
178
+ if (isEpochTransition) {
179
+ this.metrics?.precomputeNextEpochTransition.predictedReorg.inc();
180
+ }
168
181
  updatedHead = proposerHead;
169
182
  }
183
+ }
170
184
 
185
+ if (feeRecipient) {
171
186
  if (isForkPostGloas(fork)) {
172
187
  this.chain.builderCircuitBreaker.update(clockSlot, updatedHead);
173
188
  } else {
@@ -182,6 +197,7 @@ export class PrepareNextSlotScheduler {
182
197
  }
183
198
 
184
199
  // post-fulu we'll always reach here because preparedState is undefined
200
+ // we may run epoch transition not with headBlock if it's weak
185
201
  if (preparedState === undefined || updatedHead !== headBlock) {
186
202
  preparedState = await this.chain.regen.getBlockSlotState(
187
203
  updatedHead,
@@ -280,7 +296,7 @@ export class PrepareNextSlotScheduler {
280
296
  // + if next slot is a skipped slot, it'd help getting target checkpoint state faster to validate attestations
281
297
  if (isEpochTransition) {
282
298
  this.metrics?.precomputeNextEpochTransition.count.inc({result: "success"}, 1);
283
- const previousHits = this.chain.regen.updatePreComputedCheckpoint(headRoot, nextEpoch);
299
+ const previousHits = this.chain.regen.updatePreComputedCheckpoint(updatedHead.blockRoot, nextEpoch);
284
300
  if (previousHits === 0) {
285
301
  this.metrics?.precomputeNextEpochTransition.waste.inc();
286
302
  }
@@ -289,6 +305,8 @@ export class PrepareNextSlotScheduler {
289
305
  this.logger.verbose("Completed PrepareNextSlotScheduler epoch transition", {
290
306
  nextEpoch,
291
307
  headSlot,
308
+ headRoot,
309
+ updatedHeadRoot: updatedHead.blockRoot,
292
310
  prepareSlot,
293
311
  previousHits,
294
312
  durationMs: Date.now() - start,
@@ -21,6 +21,8 @@ export enum RegenCaller {
21
21
  validateGossipAggregateAndProof = "validateGossipAggregateAndProof",
22
22
  validateGossipAttestation = "validateGossipAttestation",
23
23
  validateGossipVoluntaryExit = "validateGossipVoluntaryExit",
24
+ validateApiVoluntaryExit = "validateApiVoluntaryExit",
25
+ publishDeferredVoluntaryExits = "publishDeferredVoluntaryExits",
24
26
  validateGossipExecutionPayloadBid = "validateGossipExecutionPayloadBid",
25
27
  validateGossipPayloadAttestationMessage = "validateGossipPayloadAttestationMessage",
26
28
  validateGossipProposerPreferences = "validateGossipProposerPreferences",
@@ -39,14 +41,14 @@ export type StateRegenerationOpts = {
39
41
  };
40
42
 
41
43
  export interface IStateRegenerator extends IStateRegeneratorInternal {
42
- dropCache(): void;
44
+ dropCache(): Promise<void>;
43
45
  dumpCacheSummary(): routes.lodestar.StateCacheItem[];
44
46
  getStateSync(stateRoot: RootHex): IBeaconStateView | null;
45
47
  getPreStateSync(block: BeaconBlock): IBeaconStateView | null;
46
48
  getCheckpointStateOrBytes(cp: CheckpointHex): Promise<IBeaconStateView | Uint8Array | null>;
47
49
  getCheckpointStateSync(cp: CheckpointHex): IBeaconStateView | null;
48
50
  getClosestHeadState(head: ProtoBlock): IBeaconStateView | null;
49
- pruneOnCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch, headStateRoot: RootHex): void;
51
+ onCheckpoint(finalizedEpoch: Epoch, justifiedEpoch: Epoch, headStateRoot: RootHex): void;
50
52
  processState(blockRootHex: RootHex, postState: IBeaconStateView): void;
51
53
  addCheckpointState(cp: phase0.Checkpoint, item: IBeaconStateView): void;
52
54
  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 {
@@ -1,4 +1,5 @@
1
- import {Epoch, ValidatorIndex} from "@lodestar/types";
1
+ import {computeEpochAtSlot} from "@lodestar/state-transition";
2
+ import {Epoch, Slot, ValidatorIndex} from "@lodestar/types";
2
3
  import {MapDef} from "@lodestar/utils";
3
4
 
4
5
  // How many *non future* epochs we intend to keep for SeenAttesters.
@@ -57,7 +58,32 @@ export class SeenAttesters {
57
58
  */
58
59
  export class SeenAggregators extends SeenAttesters {}
59
60
 
60
- /**
61
- * Keeps a cache to filter payload attestations from the same attesters in the same epoch
62
- */
63
- export class SeenPayloadAttesters extends SeenAttesters {}
61
+ /** Keeps a cache to filter payload attestations from the same validator in the same slot. */
62
+ export class SeenPayloadAttesters {
63
+ private readonly validatorIndexesBySlot = new MapDef<Slot, Set<ValidatorIndex>>(() => new Set<ValidatorIndex>());
64
+ private readonly validatorIndexesByEpoch = new SeenAttesters();
65
+
66
+ isKnown(slot: Slot, validatorIndex: ValidatorIndex): boolean {
67
+ return this.validatorIndexesBySlot.get(slot)?.has(validatorIndex) === true;
68
+ }
69
+
70
+ add(slot: Slot, validatorIndex: ValidatorIndex): void {
71
+ const epoch = computeEpochAtSlot(slot);
72
+ this.validatorIndexesByEpoch.add(epoch, validatorIndex);
73
+ this.validatorIndexesBySlot.getOrDefault(slot).add(validatorIndex);
74
+ }
75
+
76
+ seenAtEpoch(epoch: Epoch, validatorIndex: ValidatorIndex): boolean {
77
+ return this.validatorIndexesByEpoch.isKnown(epoch, validatorIndex);
78
+ }
79
+
80
+ prune(currentEpoch: Epoch): void {
81
+ const lowestPermissibleEpoch = Math.max(currentEpoch - EPOCH_LOOKBACK_LIMIT, 0);
82
+ for (const slot of this.validatorIndexesBySlot.keys()) {
83
+ if (computeEpochAtSlot(slot) < lowestPermissibleEpoch) {
84
+ this.validatorIndexesBySlot.delete(slot);
85
+ }
86
+ }
87
+ this.validatorIndexesByEpoch.prune(currentEpoch);
88
+ }
89
+ }
@@ -1,18 +1,32 @@
1
1
  import {ChainForkConfig} from "@lodestar/config";
2
2
  import {CheckpointWithHex, IForkChoice, PayloadStatus, ProtoBlock} from "@lodestar/fork-choice";
3
+ import {ForkPostGloas, SLOTS_PER_EPOCH, isForkPostGloas} from "@lodestar/params";
3
4
  import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
4
- import {RootHex} from "@lodestar/types";
5
- import {Logger} from "@lodestar/utils";
5
+ import {RootHex, SignedBeaconBlock} from "@lodestar/types";
6
+ import {Logger, fromHex} from "@lodestar/utils";
7
+ import {IBeaconDb} from "../../db/index.js";
6
8
  import {Metrics} from "../../metrics/metrics.js";
9
+ import {MAX_LOOK_AHEAD_EPOCHS} from "../../sync/constants.js";
7
10
  import {IClock} from "../../util/clock.js";
11
+ import {CustodyConfig} from "../../util/dataColumns.js";
8
12
  import {SerializedCache} from "../../util/serializedCache.js";
9
13
  import {isDaOutOfRange} from "../blocks/blockInput/index.js";
10
- import {CreateFromBidProps, CreateFromBlockProps, PayloadEnvelopeInput} from "../blocks/payloadEnvelopeInput/index.js";
14
+ import {
15
+ CreateFromBidProps,
16
+ CreateFromBlockProps,
17
+ PayloadEnvelopeInput,
18
+ PayloadEnvelopeInputPruneReason,
19
+ PayloadEnvelopeInputSource,
20
+ } from "../blocks/payloadEnvelopeInput/index.js";
11
21
  import {ChainEvent, ChainEventEmitter} from "../emitter.js";
22
+ import {SeenBlockInput} from "./seenGossipBlockInput.js";
12
23
 
13
24
  export type {PayloadEnvelopeInputState} from "../blocks/payloadEnvelopeInput/index.js";
14
25
  export {PayloadEnvelopeInput} from "../blocks/payloadEnvelopeInput/index.js";
15
26
 
27
+ // Bound this cache by this max size, this is the same to SeenBlockInput
28
+ const MAX_PAYLOAD_ENVELOPE_INPUT_CACHE_SIZE = (MAX_LOOK_AHEAD_EPOCHS + 1) * SLOTS_PER_EPOCH;
29
+
16
30
  export type SeenPayloadEnvelopeInputModules = {
17
31
  config: ChainForkConfig;
18
32
  clock: IClock;
@@ -20,6 +34,9 @@ export type SeenPayloadEnvelopeInputModules = {
20
34
  chainEvents: ChainEventEmitter;
21
35
  signal: AbortSignal;
22
36
  serializedCache: SerializedCache;
37
+ db: IBeaconDb;
38
+ seenBlockInputCache: SeenBlockInput;
39
+ custodyConfig: CustodyConfig;
23
40
  metrics: Metrics | null;
24
41
  logger?: Logger;
25
42
  };
@@ -40,9 +57,14 @@ export class SeenPayloadEnvelopeInput {
40
57
  private readonly chainEvents: ChainEventEmitter;
41
58
  private readonly signal: AbortSignal;
42
59
  private readonly serializedCache: SerializedCache;
60
+ private readonly db: IBeaconDb;
61
+ private readonly seenBlockInputCache: SeenBlockInput;
62
+ private readonly custodyConfig: CustodyConfig;
43
63
  private readonly metrics: Metrics | null;
44
64
  private readonly logger?: Logger;
45
65
  private payloadInputs = new Map<RootHex, PayloadEnvelopeInput>();
66
+ // Dedup concurrent DB reloads of the same root so callers share one reconstructed object.
67
+ private readonly reloading = new Map<RootHex, Promise<PayloadEnvelopeInput | undefined>>();
46
68
 
47
69
  constructor({
48
70
  config,
@@ -51,6 +73,9 @@ export class SeenPayloadEnvelopeInput {
51
73
  chainEvents,
52
74
  signal,
53
75
  serializedCache,
76
+ db,
77
+ seenBlockInputCache,
78
+ custodyConfig,
54
79
  metrics,
55
80
  logger,
56
81
  }: SeenPayloadEnvelopeInputModules) {
@@ -60,6 +85,9 @@ export class SeenPayloadEnvelopeInput {
60
85
  this.chainEvents = chainEvents;
61
86
  this.signal = signal;
62
87
  this.serializedCache = serializedCache;
88
+ this.db = db;
89
+ this.seenBlockInputCache = seenBlockInputCache;
90
+ this.custodyConfig = custodyConfig;
63
91
  this.metrics = metrics;
64
92
  this.logger = logger;
65
93
 
@@ -86,7 +114,7 @@ export class SeenPayloadEnvelopeInput {
86
114
  let deletedCount = 0;
87
115
  for (const [, input] of this.payloadInputs) {
88
116
  if (input.slot < finalizedSlot) {
89
- this.evictPayloadInput(input);
117
+ this.evictPayloadInput(input, "finalized");
90
118
  deletedCount++;
91
119
  }
92
120
  }
@@ -110,12 +138,13 @@ export class SeenPayloadEnvelopeInput {
110
138
  const daOutOfRange = isDaOutOfRange(this.config, props.forkName, props.block.message.slot, this.clock.currentEpoch);
111
139
  const input = PayloadEnvelopeInput.createFromBlock({...props, daOutOfRange});
112
140
  this.payloadInputs.set(props.blockRootHex, input);
113
- this.metrics?.seenCache.payloadEnvelopeInput.created.inc();
141
+ this.metrics?.seenCache.payloadEnvelopeInput.created.inc({source: props.source});
114
142
  this.logger?.verbose("SeenPayloadEnvelopeInput.add created new entry", {
115
143
  slot: input.slot,
116
144
  root: props.blockRootHex,
117
145
  daOutOfRange,
118
146
  });
147
+ this.pruneToMaxSize();
119
148
  return input;
120
149
  }
121
150
 
@@ -131,12 +160,13 @@ export class SeenPayloadEnvelopeInput {
131
160
  const daOutOfRange = isDaOutOfRange(this.config, props.forkName, props.slot, this.clock.currentEpoch);
132
161
  const input = PayloadEnvelopeInput.createFromBid({...props, daOutOfRange});
133
162
  this.payloadInputs.set(props.blockRootHex, input);
134
- this.metrics?.seenCache.payloadEnvelopeInput.created.inc();
163
+ this.metrics?.seenCache.payloadEnvelopeInput.created.inc({source: props.source});
135
164
  this.logger?.verbose("SeenPayloadEnvelopeInput.addFromBid created new entry", {
136
165
  slot: input.slot,
137
166
  root: props.blockRootHex,
138
167
  daOutOfRange,
139
168
  });
169
+ this.pruneToMaxSize();
140
170
  return input;
141
171
  }
142
172
 
@@ -144,6 +174,80 @@ export class SeenPayloadEnvelopeInput {
144
174
  return this.payloadInputs.get(blockRootHex);
145
175
  }
146
176
 
177
+ /**
178
+ * Like `get()`, but on a cache miss reconstruct the shell (bid + versionedHashes) from the block
179
+ * in `seenBlockInputCache` or the hot DB.
180
+ * This api is meant for BlockInputSync when a late/weird payloads for old blocks
181
+ *
182
+ * NOTE: the reconstructed entry is always EMPTY even when the block is actually FULL (its
183
+ * payload envelope + columns persisted in the DB). The consumer should consult fork choice if it needs to.
184
+ */
185
+ async getOrReload(blockRootHex: RootHex): Promise<PayloadEnvelopeInput | undefined> {
186
+ const existing = this.payloadInputs.get(blockRootHex);
187
+ if (existing !== undefined) {
188
+ return existing;
189
+ }
190
+
191
+ // Without this dedup, two concurrent misses each db.block.get + createFromBlock a DIFFERENT shell
192
+ // for the same root; processPayloadEnvelopeJob's WeakMap (keyed by object) can't dedup the import.
193
+ const inflight = this.reloading.get(blockRootHex);
194
+ if (inflight !== undefined) {
195
+ return inflight;
196
+ }
197
+ const promise = this.reloadFromDb(blockRootHex);
198
+ this.reloading.set(blockRootHex, promise);
199
+ try {
200
+ return await promise;
201
+ } finally {
202
+ this.reloading.delete(blockRootHex);
203
+ }
204
+ }
205
+
206
+ private async reloadFromDb(blockRootHex: RootHex): Promise<PayloadEnvelopeInput | undefined> {
207
+ // Only recover unfinalized, fork-choice-known blocks. Do not read the finalized archive. The gate
208
+ // also filters out un-imported blocks that may sit in seenBlockInputCache before validation.
209
+ if (!this.forkChoice.hasBlockHex(blockRootHex)) {
210
+ return undefined;
211
+ }
212
+
213
+ // In-memory first: persistBlockInput writes db.block THEN prunes seenBlockInputCache, so a
214
+ // just-imported block whose async write (unfinalizedBlockWrites) has not flushed yet is still here;
215
+ // older blocks (already pruned from the cache) fall through to the hot db.
216
+ const cachedBlockInput = this.seenBlockInputCache.get(blockRootHex);
217
+ const block = cachedBlockInput?.hasBlock()
218
+ ? cachedBlockInput.getBlock()
219
+ : await this.db.block.get(fromHex(blockRootHex));
220
+ if (block == null) {
221
+ return undefined;
222
+ }
223
+
224
+ const forkName = this.config.getForkName(block.message.slot);
225
+ if (!isForkPostGloas(forkName)) {
226
+ return undefined;
227
+ }
228
+
229
+ const daOutOfRange = isDaOutOfRange(this.config, forkName, block.message.slot, this.clock.currentEpoch);
230
+ const input = PayloadEnvelopeInput.createFromBlock({
231
+ blockRootHex,
232
+ block: block as SignedBeaconBlock<ForkPostGloas>,
233
+ forkName,
234
+ sampledColumns: this.custodyConfig.sampledColumns,
235
+ custodyColumns: this.custodyConfig.custodyColumns,
236
+ seenTimestampSec: Date.now() / 1000,
237
+ source: PayloadEnvelopeInputSource.reload,
238
+ daOutOfRange,
239
+ });
240
+ this.payloadInputs.set(blockRootHex, input);
241
+ this.metrics?.seenCache.payloadEnvelopeInput.created.inc({source: PayloadEnvelopeInputSource.reload});
242
+ this.logger?.verbose("SeenPayloadEnvelopeInput.getOrReload reconstructed entry from db", {
243
+ slot: input.slot,
244
+ root: blockRootHex,
245
+ });
246
+ // Set above (entry is at the back of the insertion order), so the cap never evicts what we just reloaded.
247
+ this.pruneToMaxSize();
248
+ return input;
249
+ }
250
+
147
251
  hasPayload(blockRootHex: RootHex): boolean {
148
252
  return this.payloadInputs.get(blockRootHex)?.hasPayloadEnvelope() ?? false;
149
253
  }
@@ -155,8 +259,7 @@ export class SeenPayloadEnvelopeInput {
155
259
  prune(blockRootHex: RootHex): void {
156
260
  const input = this.payloadInputs.get(blockRootHex);
157
261
  if (input) {
158
- this.evictPayloadInput(input);
159
- this.logger?.verbose("SeenPayloadEnvelopeInput.prune deleted", {slot: input.slot, root: blockRootHex});
262
+ this.evictPayloadInput(input, "prune");
160
263
  }
161
264
  }
162
265
 
@@ -170,17 +273,43 @@ export class SeenPayloadEnvelopeInput {
170
273
  // ...and don't evict while columns are still being gathered: writeDataColumnsToDb awaits the
171
274
  // same hasComputedAllData() before persisting. Such entries are pruned by a later call.
172
275
  if (input?.hasComputedAllData()) {
173
- this.evictPayloadInput(input);
174
- this.logger?.verbose("SeenPayloadEnvelopeInput.pruneBelowParent deleted", {
175
- slot: block.slot,
176
- root: block.blockRoot,
177
- });
276
+ this.evictPayloadInput(input, "belowParent");
178
277
  }
179
278
  }
180
279
  }
181
280
  }
182
281
 
183
- private evictPayloadInput(payloadInput: PayloadEnvelopeInput): void {
282
+ /**
283
+ * Bound this cache to have at most MAX_PAYLOAD_ENVELOPE_INPUT_CACHE_SIZE items.
284
+ * Evicts by insertion order so a just-reloaded old-slot entry is not evicted right after.
285
+ * On unstable network, we may need to query an evicted item, UnknownBlockInput will recover
286
+ * it from db via getOrReload() api. Runs after every single insert, so it evicts ~1 per call.
287
+ */
288
+ private pruneToMaxSize(): void {
289
+ let evicted = 0;
290
+ for (const input of this.payloadInputs.values()) {
291
+ if (this.payloadInputs.size <= MAX_PAYLOAD_ENVELOPE_INPUT_CACHE_SIZE) {
292
+ break;
293
+ }
294
+ this.evictPayloadInput(input, "cap");
295
+ evicted++;
296
+ }
297
+ if (evicted > 0) {
298
+ this.logger?.debug("SeenPayloadEnvelopeInput.pruneToMaxSize evicted", {
299
+ evicted,
300
+ size: this.payloadInputs.size,
301
+ max: MAX_PAYLOAD_ENVELOPE_INPUT_CACHE_SIZE,
302
+ });
303
+ }
304
+ }
305
+
306
+ private evictPayloadInput(payloadInput: PayloadEnvelopeInput, reason: PayloadEnvelopeInputPruneReason): void {
307
+ this.metrics?.seenCache.payloadEnvelopeInput.pruned.inc({reason});
308
+ this.logger?.debug("SeenPayloadEnvelopeInput evicted", {
309
+ slot: payloadInput.slot,
310
+ root: payloadInput.blockRootHex,
311
+ reason,
312
+ });
184
313
  this.serializedCache.delete(payloadInput.getSerializedCacheKeys());
185
314
  this.payloadInputs.delete(payloadInput.blockRootHex);
186
315
  }
@@ -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 {