@lodestar/beacon-node 1.49.0-dev.fbb58f7280 → 1.49.0-rc.0

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 (212) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +13 -4
  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 +4 -2
  6. package/lib/api/impl/beacon/pool/index.js.map +1 -1
  7. package/lib/chain/archiveStore/archiveStore.d.ts +1 -2
  8. package/lib/chain/archiveStore/archiveStore.d.ts.map +1 -1
  9. package/lib/chain/archiveStore/archiveStore.js +5 -8
  10. package/lib/chain/archiveStore/archiveStore.js.map +1 -1
  11. package/lib/chain/archiveStore/historicalState/metrics.d.ts.map +1 -1
  12. package/lib/chain/archiveStore/historicalState/metrics.js +5 -6
  13. package/lib/chain/archiveStore/historicalState/metrics.js.map +1 -1
  14. package/lib/chain/archiveStore/utils/archiveBlocks.d.ts +11 -2
  15. package/lib/chain/archiveStore/utils/archiveBlocks.d.ts.map +1 -1
  16. package/lib/chain/archiveStore/utils/archiveBlocks.js +46 -28
  17. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  18. package/lib/chain/archiveStore/utils/pruneHistory.d.ts +2 -2
  19. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  20. package/lib/chain/archiveStore/utils/pruneHistory.js +1 -0
  21. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  22. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  23. package/lib/chain/blocks/importExecutionPayload.js +13 -0
  24. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  25. package/lib/chain/chain.d.ts +10 -0
  26. package/lib/chain/chain.d.ts.map +1 -1
  27. package/lib/chain/chain.js +85 -16
  28. package/lib/chain/chain.js.map +1 -1
  29. package/lib/chain/errors/envelopeReconstructionError.d.ts +23 -0
  30. package/lib/chain/errors/envelopeReconstructionError.d.ts.map +1 -0
  31. package/lib/chain/errors/envelopeReconstructionError.js +13 -0
  32. package/lib/chain/errors/envelopeReconstructionError.js.map +1 -0
  33. package/lib/chain/errors/index.d.ts +1 -0
  34. package/lib/chain/errors/index.d.ts.map +1 -1
  35. package/lib/chain/errors/index.js +1 -0
  36. package/lib/chain/errors/index.js.map +1 -1
  37. package/lib/chain/errors/payloadAttestation.d.ts +4 -0
  38. package/lib/chain/errors/payloadAttestation.d.ts.map +1 -1
  39. package/lib/chain/errors/payloadAttestation.js +1 -0
  40. package/lib/chain/errors/payloadAttestation.js.map +1 -1
  41. package/lib/chain/interface.d.ts +6 -1
  42. package/lib/chain/interface.d.ts.map +1 -1
  43. package/lib/chain/interface.js.map +1 -1
  44. package/lib/chain/options.d.ts +2 -4
  45. package/lib/chain/options.d.ts.map +1 -1
  46. package/lib/chain/options.js +1 -1
  47. package/lib/chain/options.js.map +1 -1
  48. package/lib/chain/produceBlock/computeNewStateRoot.d.ts.map +1 -1
  49. package/lib/chain/produceBlock/computeNewStateRoot.js +4 -2
  50. package/lib/chain/produceBlock/computeNewStateRoot.js.map +1 -1
  51. package/lib/chain/validation/payloadAttestationMessage.d.ts.map +1 -1
  52. package/lib/chain/validation/payloadAttestationMessage.js +8 -1
  53. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  54. package/lib/db/beacon.d.ts +1 -2
  55. package/lib/db/beacon.d.ts.map +1 -1
  56. package/lib/db/beacon.js +1 -3
  57. package/lib/db/beacon.js.map +1 -1
  58. package/lib/db/buckets.d.ts +0 -1
  59. package/lib/db/buckets.d.ts.map +1 -1
  60. package/lib/db/buckets.js +1 -1
  61. package/lib/db/buckets.js.map +1 -1
  62. package/lib/db/interface.d.ts +1 -2
  63. package/lib/db/interface.d.ts.map +1 -1
  64. package/lib/db/repositories/blockArchiveIndex.d.ts +2 -2
  65. package/lib/db/repositories/blockArchiveIndex.d.ts.map +1 -1
  66. package/lib/db/repositories/executionPayloadEnvelopeArchive.d.ts +21 -9
  67. package/lib/db/repositories/executionPayloadEnvelopeArchive.d.ts.map +1 -1
  68. package/lib/db/repositories/executionPayloadEnvelopeArchive.js +32 -12
  69. package/lib/db/repositories/executionPayloadEnvelopeArchive.js.map +1 -1
  70. package/lib/db/repositories/index.d.ts +1 -2
  71. package/lib/db/repositories/index.d.ts.map +1 -1
  72. package/lib/db/repositories/index.js +1 -2
  73. package/lib/db/repositories/index.js.map +1 -1
  74. package/lib/execution/engine/disabled.d.ts +1 -0
  75. package/lib/execution/engine/disabled.d.ts.map +1 -1
  76. package/lib/execution/engine/disabled.js +3 -0
  77. package/lib/execution/engine/disabled.js.map +1 -1
  78. package/lib/execution/engine/http.d.ts +2 -1
  79. package/lib/execution/engine/http.d.ts.map +1 -1
  80. package/lib/execution/engine/http.js +7 -1
  81. package/lib/execution/engine/http.js.map +1 -1
  82. package/lib/execution/engine/interface.d.ts +3 -1
  83. package/lib/execution/engine/interface.d.ts.map +1 -1
  84. package/lib/execution/engine/mock.d.ts +1 -0
  85. package/lib/execution/engine/mock.d.ts.map +1 -1
  86. package/lib/execution/engine/mock.js +14 -2
  87. package/lib/execution/engine/mock.js.map +1 -1
  88. package/lib/execution/engine/types.d.ts +11 -0
  89. package/lib/execution/engine/types.d.ts.map +1 -1
  90. package/lib/execution/engine/types.js +10 -0
  91. package/lib/execution/engine/types.js.map +1 -1
  92. package/lib/metrics/metrics/beacon.d.ts +9 -0
  93. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  94. package/lib/metrics/metrics/beacon.js +16 -0
  95. package/lib/metrics/metrics/beacon.js.map +1 -1
  96. package/lib/metrics/metrics/lodestar.d.ts +21 -11
  97. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  98. package/lib/metrics/metrics/lodestar.js +48 -23
  99. package/lib/metrics/metrics/lodestar.js.map +1 -1
  100. package/lib/metrics/metrics.d.ts +3 -1
  101. package/lib/metrics/metrics.d.ts.map +1 -1
  102. package/lib/metrics/metrics.js +2 -2
  103. package/lib/metrics/metrics.js.map +1 -1
  104. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRange.d.ts.map +1 -1
  105. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRange.js +47 -34
  106. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRange.js.map +1 -1
  107. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRoot.d.ts.map +1 -1
  108. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRoot.js +23 -4
  109. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRoot.js.map +1 -1
  110. package/lib/network/reqresp/handlers/index.d.ts.map +1 -1
  111. package/lib/network/reqresp/handlers/index.js +20 -4
  112. package/lib/network/reqresp/handlers/index.js.map +1 -1
  113. package/lib/node/nodejs.d.ts +2 -7
  114. package/lib/node/nodejs.d.ts.map +1 -1
  115. package/lib/node/nodejs.js +2 -22
  116. package/lib/node/nodejs.js.map +1 -1
  117. package/lib/sync/interface.d.ts +1 -2
  118. package/lib/sync/interface.d.ts.map +1 -1
  119. package/lib/sync/options.d.ts +0 -6
  120. package/lib/sync/options.d.ts.map +1 -1
  121. package/lib/sync/options.js +0 -2
  122. package/lib/sync/options.js.map +1 -1
  123. package/lib/sync/types.d.ts +18 -3
  124. package/lib/sync/types.d.ts.map +1 -1
  125. package/lib/sync/types.js +19 -3
  126. package/lib/sync/types.js.map +1 -1
  127. package/lib/sync/unknownBlock.d.ts +19 -0
  128. package/lib/sync/unknownBlock.d.ts.map +1 -1
  129. package/lib/sync/unknownBlock.js +184 -15
  130. package/lib/sync/unknownBlock.js.map +1 -1
  131. package/lib/util/execution.d.ts +42 -0
  132. package/lib/util/execution.d.ts.map +1 -1
  133. package/lib/util/execution.js +123 -2
  134. package/lib/util/execution.js.map +1 -1
  135. package/lib/util/headerEnvelope.d.ts +17 -0
  136. package/lib/util/headerEnvelope.d.ts.map +1 -0
  137. package/lib/util/headerEnvelope.js +43 -0
  138. package/lib/util/headerEnvelope.js.map +1 -0
  139. package/lib/util/shuffle.d.ts +0 -4
  140. package/lib/util/shuffle.d.ts.map +1 -1
  141. package/lib/util/shuffle.js +0 -8
  142. package/lib/util/shuffle.js.map +1 -1
  143. package/package.json +16 -16
  144. package/src/api/impl/beacon/blocks/index.ts +16 -3
  145. package/src/api/impl/beacon/pool/index.ts +6 -2
  146. package/src/chain/archiveStore/archiveStore.ts +6 -9
  147. package/src/chain/archiveStore/historicalState/metrics.ts +5 -7
  148. package/src/chain/archiveStore/utils/archiveBlocks.ts +54 -32
  149. package/src/chain/archiveStore/utils/pruneHistory.ts +4 -2
  150. package/src/chain/blocks/importExecutionPayload.ts +14 -0
  151. package/src/chain/chain.ts +96 -20
  152. package/src/chain/errors/envelopeReconstructionError.ts +22 -0
  153. package/src/chain/errors/index.ts +1 -0
  154. package/src/chain/errors/payloadAttestation.ts +2 -0
  155. package/src/chain/interface.ts +6 -1
  156. package/src/chain/options.ts +3 -5
  157. package/src/chain/produceBlock/computeNewStateRoot.ts +9 -2
  158. package/src/chain/validation/payloadAttestationMessage.ts +9 -0
  159. package/src/db/beacon.ts +0 -5
  160. package/src/db/buckets.ts +2 -2
  161. package/src/db/interface.ts +0 -3
  162. package/src/db/repositories/executionPayloadEnvelopeArchive.ts +43 -13
  163. package/src/db/repositories/index.ts +6 -2
  164. package/src/execution/engine/disabled.ts +4 -0
  165. package/src/execution/engine/http.ts +12 -0
  166. package/src/execution/engine/interface.ts +4 -1
  167. package/src/execution/engine/mock.ts +22 -2
  168. package/src/execution/engine/types.ts +25 -0
  169. package/src/metrics/metrics/beacon.ts +16 -0
  170. package/src/metrics/metrics/lodestar.ts +58 -26
  171. package/src/metrics/metrics.ts +7 -2
  172. package/src/network/reqresp/handlers/executionPayloadEnvelopesByRange.ts +57 -39
  173. package/src/network/reqresp/handlers/executionPayloadEnvelopesByRoot.ts +27 -5
  174. package/src/network/reqresp/handlers/index.ts +49 -5
  175. package/src/node/nodejs.ts +0 -27
  176. package/src/sync/interface.ts +1 -2
  177. package/src/sync/options.ts +0 -8
  178. package/src/sync/types.ts +19 -3
  179. package/src/sync/unknownBlock.ts +192 -14
  180. package/src/util/execution.ts +175 -2
  181. package/src/util/headerEnvelope.ts +76 -0
  182. package/src/util/shuffle.ts +0 -9
  183. package/lib/chain/archiveStore/utils/updateBackfillRange.d.ts +0 -20
  184. package/lib/chain/archiveStore/utils/updateBackfillRange.d.ts.map +0 -1
  185. package/lib/chain/archiveStore/utils/updateBackfillRange.js +0 -40
  186. package/lib/chain/archiveStore/utils/updateBackfillRange.js.map +0 -1
  187. package/lib/db/repositories/backfilledRanges.d.ts +0 -18
  188. package/lib/db/repositories/backfilledRanges.d.ts.map +0 -1
  189. package/lib/db/repositories/backfilledRanges.js +0 -26
  190. package/lib/db/repositories/backfilledRanges.js.map +0 -1
  191. package/lib/sync/backfill/backfill.d.ts +0 -169
  192. package/lib/sync/backfill/backfill.d.ts.map +0 -1
  193. package/lib/sync/backfill/backfill.js +0 -686
  194. package/lib/sync/backfill/backfill.js.map +0 -1
  195. package/lib/sync/backfill/errors.d.ts +0 -30
  196. package/lib/sync/backfill/errors.d.ts.map +0 -1
  197. package/lib/sync/backfill/errors.js +0 -15
  198. package/lib/sync/backfill/errors.js.map +0 -1
  199. package/lib/sync/backfill/index.d.ts +0 -2
  200. package/lib/sync/backfill/index.d.ts.map +0 -1
  201. package/lib/sync/backfill/index.js +0 -2
  202. package/lib/sync/backfill/index.js.map +0 -1
  203. package/lib/sync/backfill/verify.d.ts +0 -18
  204. package/lib/sync/backfill/verify.d.ts.map +0 -1
  205. package/lib/sync/backfill/verify.js +0 -36
  206. package/lib/sync/backfill/verify.js.map +0 -1
  207. package/src/chain/archiveStore/utils/updateBackfillRange.ts +0 -50
  208. package/src/db/repositories/backfilledRanges.ts +0 -29
  209. package/src/sync/backfill/backfill.ts +0 -916
  210. package/src/sync/backfill/errors.ts +0 -23
  211. package/src/sync/backfill/index.ts +0 -1
  212. package/src/sync/backfill/verify.ts +0 -58
@@ -1,15 +1,16 @@
1
1
  import path from "node:path";
2
2
  import {ChainForkConfig} from "@lodestar/config";
3
3
  import {KeyValue} from "@lodestar/db";
4
- import {CheckpointWithHex, IForkChoice, PayloadStatus, ProtoBlock} from "@lodestar/fork-choice";
4
+ import {CheckpointWithHex, ExecutionStatus, IForkChoice, PayloadStatus, ProtoBlock} from "@lodestar/fork-choice";
5
5
  import {ForkSeq, SLOTS_PER_EPOCH} from "@lodestar/params";
6
6
  import {computeEpochAtSlot, computeStartSlotAtEpoch} from "@lodestar/state-transition";
7
7
  import {Epoch, Slot} from "@lodestar/types";
8
8
  import {Logger, fromAsync, fromHex, prettyPrintIndices, toRootHex} from "@lodestar/utils";
9
9
  import {IBeaconDb} from "../../../db/index.js";
10
- import {BlockArchiveBatchPutBinaryItem} from "../../../db/repositories/index.js";
10
+ import {BlockArchiveBatchPutBinaryItem, encodeArchivedHeaderEnvelope} from "../../../db/repositories/index.js";
11
11
  import {Metrics} from "../../../metrics/metrics.js";
12
12
  import {ensureDir, writeIfNotExist} from "../../../util/file.js";
13
+ import {toSignedHeaderEnvelope} from "../../../util/headerEnvelope.js";
13
14
  import {BlockRootHex} from "../../../util/sszBytes.js";
14
15
  import {LightClientServer} from "../../lightClient/index.js";
15
16
 
@@ -69,7 +70,8 @@ export async function archiveBlocks(
69
70
  isNodeSynced: boolean,
70
71
  archiveDataEpochs?: number,
71
72
  persistOrphanedBlocks?: boolean,
72
- persistOrphanedBlocksDir?: string
73
+ persistOrphanedBlocksDir?: string,
74
+ dedupePayloads = true
73
75
  ): Promise<void> {
74
76
  // Use fork choice to determine the blocks to archive and delete.
75
77
  // `ancestors` is the canonical walk back from the finalized root, including the previous finalized
@@ -156,7 +158,8 @@ export async function archiveBlocks(
156
158
  config,
157
159
  db,
158
160
  logger,
159
- finalizedCanonicalBlocks
161
+ finalizedCanonicalBlocks,
162
+ dedupePayloads
160
163
  );
161
164
  logger.verbose("Migrated executionPayloadEnvelopes from hot DB to cold DB", {
162
165
  ...logCtx,
@@ -475,49 +478,68 @@ async function migrateDataColumnSidecarsFromHotToColdDb(
475
478
  /**
476
479
  * Post-gloas given a finalized checkpoint at a block root, payload of that block root
477
480
  * is not considered finalized, hence they are archived in the next run.
481
+ *
482
+ * With `dedupePayloads` (default), execution-valid envelopes are archived as header envelopes. Envelopes of
483
+ * still-optimistic blocks are archived in full, since the EL may not serve their bodies, and are not
484
+ * converted later. Archive put + hot delete are one atomic db batch.
478
485
  */
479
- async function migrateExecutionPayloadEnvelopesFromHotToColdDb(
486
+ export async function migrateExecutionPayloadEnvelopesFromHotToColdDb(
480
487
  config: ChainForkConfig,
481
488
  db: IBeaconDb,
482
489
  logger: Logger,
483
- canonicalBlocks: ProtoBlock[]
490
+ canonicalBlocks: ProtoBlock[],
491
+ dedupePayloads: boolean
484
492
  ): Promise<Slot[]> {
485
493
  const payloadBlocks = canonicalBlocks.filter(
486
- (block) => config.getForkSeq(block.slot) < ForkSeq.gloas || block.payloadStatus === PayloadStatus.FULL
494
+ (block) => config.getForkSeq(block.slot) >= ForkSeq.gloas && block.payloadStatus === PayloadStatus.FULL
487
495
  );
488
496
  if (payloadBlocks.length === 0) return [];
489
- const blocks = payloadBlocks.map((block) => ({slot: block.slot, root: fromHex(block.blockRoot)}));
490
497
 
491
- const envelopeEntries: KeyValue<Slot, Uint8Array>[] = [];
492
- const migratedRoots: Uint8Array[] = [];
498
+ const migratedSlots: Slot[] = [];
493
499
 
494
- const envelopeBytesArray = await Promise.all(
495
- blocks.map((block) => db.executionPayloadEnvelope.getBinary(block.root))
496
- );
500
+ // Process in chunks to bound memory: after a long non-finality period the ancestor walk can span
501
+ // thousands of blocks, and each full envelope is a few hundred KB when deserialized.
502
+ for (let i = 0; i < payloadBlocks.length; i += BLOCK_BATCH_SIZE) {
503
+ const batch = payloadBlocks.slice(i, i + BLOCK_BATCH_SIZE);
504
+ // Only header envelopes need deserializing; full ones are copied as bytes
505
+ const archivedBytesArray = await Promise.all(
506
+ batch.map(async (block) => {
507
+ const root = fromHex(block.blockRoot);
508
+ if (dedupePayloads && block.executionStatus === ExecutionStatus.Valid) {
509
+ const envelope = await db.executionPayloadEnvelope.get(root);
510
+ return envelope === null ? null : encodeArchivedHeaderEnvelope(toSignedHeaderEnvelope(envelope));
511
+ }
512
+ return db.executionPayloadEnvelope.getBinary(root);
513
+ })
514
+ );
515
+
516
+ const entries: {slot: Slot; archivedBytes: Uint8Array; hotKey: Uint8Array}[] = [];
517
+ for (let j = 0; j < batch.length; j++) {
518
+ const block = batch[j];
519
+ const archivedBytes = archivedBytesArray[j];
520
+ if (archivedBytes === null) {
521
+ logger.debug("ExecutionPayloadEnvelope in forkchoice but missing in hot db, could be already archived", {
522
+ slot: block.slot,
523
+ root: block.blockRoot,
524
+ });
525
+ continue;
526
+ }
497
527
 
498
- for (let i = 0; i < blocks.length; i++) {
499
- const bytes = envelopeBytesArray[i];
500
- if (bytes !== null) {
501
- envelopeEntries.push({key: blocks[i].slot, value: bytes});
502
- migratedRoots.push(blocks[i].root);
503
- } else {
504
- logger.debug("ExecutionPayloadEnvelope in forkchoice but missing in hot db, could be already archived", {
505
- slot: blocks[i].slot,
506
- root: toRootHex(blocks[i].root),
528
+ entries.push({
529
+ slot: block.slot,
530
+ archivedBytes,
531
+ hotKey: db.executionPayloadEnvelope.encodeKey(fromHex(block.blockRoot)),
507
532
  });
533
+ migratedSlots.push(block.slot);
508
534
  }
509
- }
510
535
 
511
- if (envelopeEntries.length === 0) return [];
512
-
513
- await Promise.all([
514
- db.executionPayloadEnvelopeArchive.batchPutBinary(envelopeEntries),
515
- db.executionPayloadEnvelope.batchDelete(migratedRoots),
516
- ]);
536
+ if (entries.length > 0) {
537
+ await db.executionPayloadEnvelopeArchive.batchArchiveAndDeleteHot(entries);
538
+ }
539
+ }
517
540
 
518
- // Slots are ascending in hot-db key order — sort to guarantee `prettyPrintIndices` output is clean
519
- // regardless of ancestor-walk order (newest to oldest).
520
- return envelopeEntries.map((entry) => entry.key).sort((a, b) => a - b);
541
+ // Ancestor walk is newest to oldest; sort ascending so `prettyPrintIndices` renders cleanly.
542
+ return migratedSlots.sort((a, b) => a - b);
521
543
  }
522
544
 
523
545
  /**
@@ -1,6 +1,6 @@
1
1
  import {ChainConfig} from "@lodestar/config";
2
2
  import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
3
- import {Epoch} from "@lodestar/types";
3
+ import {Epoch, Slot} from "@lodestar/types";
4
4
  import {Logger, prettyPrintIndices} from "@lodestar/utils";
5
5
  import {IBeaconDb} from "../../../db/interface.js";
6
6
  import {Metrics} from "../../../metrics/index.js";
@@ -12,7 +12,7 @@ export async function pruneHistory(
12
12
  metrics: Metrics | null | undefined,
13
13
  finalizedEpoch: Epoch,
14
14
  currentEpoch: Epoch
15
- ): Promise<void> {
15
+ ): Promise<Slot> {
16
16
  const blockCutoffEpoch = Math.min(
17
17
  // set by config, with underflow protection
18
18
  Math.max(currentEpoch - config.MIN_EPOCHS_FOR_BLOCK_REQUESTS, 0),
@@ -63,4 +63,6 @@ export async function pruneHistory(
63
63
  });
64
64
 
65
65
  metrics?.pruneHistory.pruneCount.inc();
66
+
67
+ return blockCutoffSlot;
66
68
  }
@@ -12,6 +12,7 @@ import {isQueueErrorAborted} from "../../util/queue/index.js";
12
12
  import {BeaconChain} from "../chain.js";
13
13
  import {RegenCaller} from "../regen/interface.js";
14
14
  import {PayloadEnvelopeInput} from "../seenCache/seenPayloadEnvelopeInput.js";
15
+ import {PayloadEnvelopeInputSource} from "./payloadEnvelopeInput/index.js";
15
16
  import {ImportPayloadOpts} from "./types.js";
16
17
  import {
17
18
  verifyExecutionPayloadEnvelope,
@@ -172,6 +173,9 @@ export async function importExecutionPayload(
172
173
  }
173
174
 
174
175
  // 4a. Run EL and signature verification in parallel
176
+ const logCtx = {slot, root: blockRootHex, executionBlock: envelope.payload.blockNumber};
177
+ this.logger.debug("Call engine api newPayload", logCtx);
178
+ const verifyStartSec = Date.now() / 1000;
175
179
  const [execResult, signatureValid] = await Promise.all([
176
180
  this.executionEngine.notifyNewPayload(
177
181
  fork,
@@ -191,6 +195,8 @@ export async function importExecutionPayload(
191
195
  this.bls
192
196
  ),
193
197
  ]);
198
+ this.logger.debug("Receive engine api newPayload result", {...logCtx, status: execResult.status});
199
+ this.metrics?.engineNotifyNewPayloadResult.inc({result: execResult.status});
194
200
 
195
201
  // 4b. Check signature verification result
196
202
  if (!signatureValid) {
@@ -223,6 +229,14 @@ export async function importExecutionPayload(
223
229
  });
224
230
  }
225
231
 
232
+ const {source, seenTimestampSec} = payloadInput.getPayloadEnvelopeSource();
233
+ if (execResult.status === ExecutionPayloadStatus.VALID && source === PayloadEnvelopeInputSource.gossip) {
234
+ const nowSec = Date.now() / 1000;
235
+ this.metrics?.gossipExecutionPayloadEnvelope.executionPayload.recvToValidation.observe(nowSec - seenTimestampSec);
236
+ // same metric as pre-gloas, it tracks EL verification time regardless of fork
237
+ this.metrics?.gossipBlock.executionPayload.validationTime.observe(nowSec - verifyStartSec);
238
+ }
239
+
226
240
  // 5. Persist payload envelope to hot DB. Wait for write-queue space here to apply backpressure
227
241
  // on the import pipeline during sync, then perform the write asynchronously to avoid blocking.
228
242
  await this.unfinalizedPayloadEnvelopeWrites.waitForSpace();
@@ -61,6 +61,7 @@ import {ProcessShutdownCallback} from "@lodestar/validator";
61
61
  import {GENESIS_EPOCH, ZERO_HASH} from "../constants/index.js";
62
62
  import {IBeaconDb} from "../db/index.js";
63
63
  import {BLOB_SIDECARS_IN_WRAPPER_INDEX} from "../db/repositories/blobSidecars.js";
64
+ import {decodeArchivedEnvelope} from "../db/repositories/index.js";
64
65
  import {BuilderApiClient, BuilderApiClientOpts} from "../execution/builder/apiClient.js";
65
66
  import {BuilderStatus} from "../execution/builder/http.js";
66
67
  import {IExecutionBuilder, IExecutionEngine} from "../execution/index.js";
@@ -70,6 +71,7 @@ import {BufferPool} from "../util/bufferPool.js";
70
71
  import {Clock, ClockEvent, IClock} from "../util/clock.js";
71
72
  import {CustodyConfig, getValidatorsCustodyRequirement} from "../util/dataColumns.js";
72
73
  import {callInNextEventLoop} from "../util/eventLoop.js";
74
+ import {ReconstructMismatchPolicy, isRebuildMiss, reconstructExecutionPayloadEnvelopes} from "../util/execution.js";
73
75
  import {ensureDir, writeIfNotExist} from "../util/file.js";
74
76
  import {isOptimisticBlock} from "../util/forkChoice.js";
75
77
  import {JobItemQueue} from "../util/queue/itemQueue.js";
@@ -926,21 +928,71 @@ export class BeaconChain implements IBeaconChain {
926
928
  }
927
929
 
928
930
  async getSerializedExecutionPayloadEnvelope(blockSlot: Slot, blockRootHex: string): Promise<Uint8Array | null> {
929
- const payloadInput = this.seenPayloadEnvelopeInputCache.get(blockRootHex);
930
- if (payloadInput?.hasPayloadEnvelope()) {
931
- const envelope = payloadInput.getPayloadEnvelope();
932
- const serialized = this.serializedCache.get(envelope);
933
- if (serialized) {
934
- return serialized;
931
+ const [bytes] = await this.getSerializedExecutionPayloadEnvelopes([{blockSlot, blockRootHex}]);
932
+ return bytes;
933
+ }
934
+
935
+ /**
936
+ * Batch variant: archived header envelopes are rebuilt 32 per EL round-trip. Aligned with `requests`.
937
+ * A body root mismatch is a local inconsistency: `"throw"` surfaces it, `"omit"` logs it and
938
+ * returns null for that entry, for peer-facing paths where the spec allows omission.
939
+ */
940
+ async getSerializedExecutionPayloadEnvelopes(
941
+ requests: {blockSlot: Slot; blockRootHex: RootHex}[],
942
+ onMismatch: ReconstructMismatchPolicy = "throw"
943
+ ): Promise<(Uint8Array | null)[]> {
944
+ const out: (Uint8Array | null)[] = new Array(requests.length).fill(null);
945
+ const headerEnvelopes: gloas.SignedExecutionPayloadHeaderEnvelope[] = [];
946
+ const headerEnvelopeIdxs: number[] = [];
947
+
948
+ for (let i = 0; i < requests.length; i++) {
949
+ const {blockSlot, blockRootHex} = requests[i];
950
+
951
+ const payloadInput = this.seenPayloadEnvelopeInputCache.get(blockRootHex);
952
+ if (payloadInput?.hasPayloadEnvelope()) {
953
+ const envelope = payloadInput.getPayloadEnvelope();
954
+ out[i] = this.serializedCache.get(envelope) ?? ssz.gloas.SignedExecutionPayloadEnvelope.serialize(envelope);
955
+ continue;
956
+ }
957
+
958
+ const hot = await this.db.executionPayloadEnvelope.getBinary(fromHex(blockRootHex));
959
+ if (hot !== null) {
960
+ out[i] = hot;
961
+ continue;
962
+ }
963
+
964
+ const archivedBytes = await this.db.executionPayloadEnvelopeArchive.getBinary(blockSlot);
965
+ if (archivedBytes === null) continue;
966
+
967
+ const archived = decodeArchivedEnvelope(archivedBytes);
968
+ if (archived.envelopeBytes !== undefined) {
969
+ out[i] = archived.envelopeBytes;
970
+ continue;
971
+ }
972
+ headerEnvelopes.push(archived.headerEnvelope);
973
+ headerEnvelopeIdxs.push(i);
974
+ }
975
+
976
+ if (headerEnvelopes.length > 0) {
977
+ const rebuilt = await reconstructExecutionPayloadEnvelopes(this.executionEngine, this.metrics, headerEnvelopes);
978
+ for (let j = 0; j < rebuilt.length; j++) {
979
+ const result = rebuilt[j];
980
+ if (isRebuildMiss(result)) {
981
+ if (result.reason === "mismatch") {
982
+ if (onMismatch === "throw") throw result.error;
983
+ this.logger.debug(
984
+ "Archived envelope failed body root check against EL bodies",
985
+ {slot: result.slot},
986
+ result.error
987
+ );
988
+ }
989
+ continue;
990
+ }
991
+ out[headerEnvelopeIdxs[j]] = ssz.gloas.SignedExecutionPayloadEnvelope.serialize(result);
935
992
  }
936
- return ssz.gloas.SignedExecutionPayloadEnvelope.serialize(envelope);
937
993
  }
938
994
 
939
- return (
940
- (await this.db.executionPayloadEnvelope.getBinary(fromHex(blockRootHex))) ??
941
- (await this.db.executionPayloadEnvelopeArchive.getBinary(blockSlot)) ??
942
- null
943
- );
995
+ return out;
944
996
  }
945
997
 
946
998
  async getExecutionPayloadEnvelope(
@@ -952,11 +1004,23 @@ export class BeaconChain implements IBeaconChain {
952
1004
  return payloadInput.getPayloadEnvelope();
953
1005
  }
954
1006
 
955
- return (
956
- (await this.db.executionPayloadEnvelope.get(fromHex(blockRootHex))) ??
957
- (await this.db.executionPayloadEnvelopeArchive.get(blockSlot)) ??
958
- null
959
- );
1007
+ const hot = await this.db.executionPayloadEnvelope.get(fromHex(blockRootHex));
1008
+ if (hot !== null) return hot;
1009
+
1010
+ const archivedBytes = await this.db.executionPayloadEnvelopeArchive.getBinary(blockSlot);
1011
+ if (archivedBytes === null) return null;
1012
+ const archived = decodeArchivedEnvelope(archivedBytes);
1013
+ if (archived.envelopeBytes !== undefined) {
1014
+ return ssz.gloas.SignedExecutionPayloadEnvelope.deserialize(archived.envelopeBytes);
1015
+ }
1016
+ const [result] = await reconstructExecutionPayloadEnvelopes(this.executionEngine, this.metrics, [
1017
+ archived.headerEnvelope,
1018
+ ]);
1019
+ if (isRebuildMiss(result)) {
1020
+ if (result.reason === "mismatch") throw result.error;
1021
+ return null;
1022
+ }
1023
+ return result;
960
1024
  }
961
1025
 
962
1026
  async getParentExecutionRequests(
@@ -967,11 +1031,23 @@ export class BeaconChain implements IBeaconChain {
967
1031
  if (!isForkPostGloas(this.config.getForkName(parentBlockSlot))) {
968
1032
  return ssz.gloas.ExecutionRequests.defaultValue();
969
1033
  }
970
- const envelope = await this.getExecutionPayloadEnvelope(parentBlockSlot, parentBlockRootHex);
971
- if (envelope === null) {
1034
+ // executionRequests is kept in the header envelope, so read it without reconstructing
1035
+ const payloadInput = this.seenPayloadEnvelopeInputCache.get(parentBlockRootHex);
1036
+ if (payloadInput?.hasPayloadEnvelope()) {
1037
+ return payloadInput.getPayloadEnvelope().message.executionRequests;
1038
+ }
1039
+
1040
+ const hot = await this.db.executionPayloadEnvelope.get(fromHex(parentBlockRootHex));
1041
+ if (hot !== null) return hot.message.executionRequests;
1042
+
1043
+ const archivedBytes = await this.db.executionPayloadEnvelopeArchive.getBinary(parentBlockSlot);
1044
+ if (archivedBytes === null) {
972
1045
  throw Error(`Parent execution payload envelope not found slot=${parentBlockSlot}, root=${parentBlockRootHex}`);
973
1046
  }
974
- return envelope.message.executionRequests;
1047
+ const archived = decodeArchivedEnvelope(archivedBytes);
1048
+ return archived.envelopeBytes !== undefined
1049
+ ? ssz.gloas.SignedExecutionPayloadEnvelope.deserialize(archived.envelopeBytes).message.executionRequests
1050
+ : archived.headerEnvelope.message.executionRequests;
975
1051
  }
976
1052
 
977
1053
  async getDataColumnSidecars(blockSlot: Slot, blockRootHex: string): Promise<DataColumnSidecar[]> {
@@ -0,0 +1,22 @@
1
+ import {Slot} from "@lodestar/types";
2
+ import {LodestarError} from "@lodestar/utils";
3
+
4
+ export enum EnvelopeReconstructionErrorCode {
5
+ /** The EL failed to answer engine_getPayloadBodiesByHashV2 (transport / EL down). Transient. */
6
+ ENGINE_UNAVAILABLE = "ENVELOPE_RECONSTRUCTION_ERROR_ENGINE_UNAVAILABLE",
7
+ /** A body returned by the EL does not hash to the root stored in the header envelope. Local DB/EL inconsistency. */
8
+ BODY_ROOT_MISMATCH = "ENVELOPE_RECONSTRUCTION_ERROR_BODY_ROOT_MISMATCH",
9
+ /** A by-range stream stopped short at a slot that cannot be served; the response so far is still valid */
10
+ RANGE_UNSERVABLE = "ENVELOPE_RECONSTRUCTION_ERROR_RANGE_UNSERVABLE",
11
+ }
12
+
13
+ export type EnvelopeReconstructionErrorType =
14
+ | {code: EnvelopeReconstructionErrorCode.ENGINE_UNAVAILABLE}
15
+ | {
16
+ code: EnvelopeReconstructionErrorCode.BODY_ROOT_MISMATCH;
17
+ slot: Slot;
18
+ field: "transactions" | "withdrawals" | "blockAccessList";
19
+ }
20
+ | {code: EnvelopeReconstructionErrorCode.RANGE_UNSERVABLE; slot: Slot};
21
+
22
+ export class EnvelopeReconstructionError extends LodestarError<EnvelopeReconstructionErrorType> {}
@@ -4,6 +4,7 @@ export * from "./blobSidecarError.js";
4
4
  export * from "./blockError.js";
5
5
  export * from "./blsToExecutionChangeError.js";
6
6
  export * from "./dataColumnSidecarError.js";
7
+ export * from "./envelopeReconstructionError.js";
7
8
  export * from "./executionPayloadBid.js";
8
9
  export * from "./executionPayloadEnvelope.js";
9
10
  export * from "./gossipValidation.js";
@@ -6,6 +6,7 @@ export enum PayloadAttestationErrorCode {
6
6
  PAYLOAD_ATTESTATION_ALREADY_KNOWN = "PAYLOAD_ATTESTATION_ERROR_PAYLOAD_ATTESTATION_ALREADY_KNOWN",
7
7
  UNKNOWN_BLOCK_ROOT = "PAYLOAD_ATTESTATION_ERROR_UNKNOWN_BLOCK_ROOT",
8
8
  INVALID_BLOCK_SLOT = "PAYLOAD_ATTESTATION_ERROR_INVALID_BLOCK_SLOT",
9
+ PRE_GLOAS_SLOT = "PAYLOAD_ATTESTATION_ERROR_PRE_GLOAS_SLOT",
9
10
  INVALID_BLOCK = "PAYLOAD_ATTESTATION_ERROR_INVALID_BLOCK",
10
11
  INVALID_ATTESTER = "PAYLOAD_ATTESTATION_ERROR_INVALID_ATTESTER",
11
12
  INVALID_SIGNATURE = "PAYLOAD_ATTESTATION_ERROR_INVALID_SIGNATURE",
@@ -20,6 +21,7 @@ export type PayloadAttestationErrorType =
20
21
  }
21
22
  | {code: PayloadAttestationErrorCode.UNKNOWN_BLOCK_ROOT; blockRoot: RootHex}
22
23
  | {code: PayloadAttestationErrorCode.INVALID_BLOCK_SLOT; blockRoot: RootHex; blockSlot: Slot; slot: Slot}
24
+ | {code: PayloadAttestationErrorCode.PRE_GLOAS_SLOT; slot: Slot}
23
25
  | {code: PayloadAttestationErrorCode.INVALID_BLOCK; blockRoot: RootHex}
24
26
  | {code: PayloadAttestationErrorCode.INVALID_ATTESTER; attesterIndex: ValidatorIndex}
25
27
  | {code: PayloadAttestationErrorCode.INVALID_SIGNATURE};
@@ -30,6 +30,7 @@ import {Metrics} from "../metrics/metrics.js";
30
30
  import {BufferPool} from "../util/bufferPool.js";
31
31
  import {IClock} from "../util/clock.js";
32
32
  import {CustodyConfig} from "../util/dataColumns.js";
33
+ import {ReconstructMismatchPolicy} from "../util/execution.js";
33
34
  import {SerializedCache} from "../util/serializedCache.js";
34
35
  import {IArchiveStore} from "./archiveStore/interface.js";
35
36
  import {CheckpointBalancesCache} from "./balancesCache.js";
@@ -96,7 +97,7 @@ export enum FindHeadFnName {
96
97
  export interface IBeaconChain {
97
98
  readonly genesisTime: UintNum64;
98
99
  readonly genesisValidatorsRoot: Root;
99
- readonly earliestAvailableSlot: Slot;
100
+ earliestAvailableSlot: Slot;
100
101
  readonly executionEngine: IExecutionEngine;
101
102
  readonly executionBuilder?: IExecutionBuilder;
102
103
  readonly builderCircuitBreaker: BuilderCircuitBreaker;
@@ -236,6 +237,10 @@ export interface IBeaconChain {
236
237
  indices: number[]
237
238
  ): Promise<(Uint8Array | undefined)[]>;
238
239
  getSerializedExecutionPayloadEnvelope(blockSlot: Slot, blockRootHex: string): Promise<Uint8Array | null>;
240
+ getSerializedExecutionPayloadEnvelopes(
241
+ requests: {blockSlot: Slot; blockRootHex: RootHex}[],
242
+ onMismatch?: ReconstructMismatchPolicy
243
+ ): Promise<(Uint8Array | null)[]>;
239
244
  getExecutionPayloadEnvelope(
240
245
  blockSlot: Slot,
241
246
  blockRootHex: string
@@ -29,6 +29,8 @@ export type IChainOptions = BlockProcessOpts &
29
29
  blacklistedBlocks?: string[];
30
30
  // TODO GLOAS: add similar option for execution payload envelopes?
31
31
  persistProducedBlocks?: boolean;
32
+ /** Archive finalized Gloas payload envelopes as headers (bodies reconstructed from the EL on read) */
33
+ dedupePayloads?: boolean;
32
34
  persistInvalidSszObjects?: boolean;
33
35
  persistInvalidSszObjectsDir?: string;
34
36
  persistOrphanedBlocks?: boolean;
@@ -63,10 +65,6 @@ export type BlockProcessOpts = {
63
65
  * Will double processing times. Use only for debugging purposes.
64
66
  */
65
67
  disableBlsBatchVerify?: boolean;
66
- /**
67
- * Assert progressive balances the same to EpochTransitionCache
68
- */
69
- assertCorrectProgressiveBalances?: boolean;
70
68
  /** Used for fork_choice spec tests */
71
69
  disableOnBlockError?: boolean;
72
70
  /** Used for fork_choice spec tests */
@@ -109,12 +107,12 @@ export const defaultChainOptions: IChainOptions = {
109
107
  disableBlsBatchVerify: false,
110
108
  proposerBoost: true,
111
109
  proposerBoostReorg: true,
110
+ dedupePayloads: true,
112
111
  computeUnrealized: true,
113
112
  fastConfirmation: false,
114
113
  suggestedFeeRecipient: defaultValidatorOptions.suggestedFeeRecipient,
115
114
  graffitiAppend: true,
116
115
  serveHistoricalState: false,
117
- assertCorrectProgressiveBalances: false,
118
116
  archiveStateEpochFrequency: 1024,
119
117
  archiveMode: DEFAULT_ARCHIVE_MODE,
120
118
  pruneHistory: false,
@@ -1,4 +1,4 @@
1
- import {EMPTY_SIGNATURE, IBeaconStateView} from "@lodestar/state-transition";
1
+ import {EMPTY_SIGNATURE, IBeaconStateView, StateHashTreeRootSource} from "@lodestar/state-transition";
2
2
  import {BeaconBlock, BlindedBeaconBlock, Gwei, Root} from "@lodestar/types";
3
3
  import {Metrics} from "../../metrics/index.js";
4
4
 
@@ -14,5 +14,12 @@ export function computeNewStateRoot(
14
14
  ): {newStateRoot: Root; proposerReward: Gwei; postState: IBeaconStateView} {
15
15
  // Set signature to zero to re-use stateTransition() function which requires the SignedBeaconBlock type
16
16
  const signedBlock = {message: block, signature: EMPTY_SIGNATURE};
17
- return state.computeNewStateRoot({block: signedBlock}, {metrics});
17
+ const {newStateRoot, proposerReward, postState, hashTreeRootTime} = state.computeNewStateRoot(
18
+ {block: signedBlock},
19
+ {metrics}
20
+ );
21
+
22
+ metrics?.stateHashTreeRootTime.observe({source: StateHashTreeRootSource.computeNewStateRoot}, hashTreeRootTime);
23
+
24
+ return {newStateRoot, proposerReward, postState};
18
25
  }
@@ -1,4 +1,5 @@
1
1
  import {
2
+ computeEpochAtSlot,
2
3
  createIndexedSignatureSetFromComponents,
3
4
  getPayloadAttestationDataSigningRoot,
4
5
  isStatePostGloas,
@@ -35,6 +36,14 @@ async function validatePayloadAttestationMessage(
35
36
  ): Promise<PayloadAttestationValidationResult> {
36
37
  const {data, validatorIndex} = payloadAttestationMessage;
37
38
 
39
+ // [REJECT] The payload attestation slot is at or after the Gloas fork.
40
+ if (computeEpochAtSlot(data.slot) < chain.config.GLOAS_FORK_EPOCH) {
41
+ throw new PayloadAttestationError(GossipAction.REJECT, {
42
+ code: PayloadAttestationErrorCode.PRE_GLOAS_SLOT,
43
+ slot: data.slot,
44
+ });
45
+ }
46
+
38
47
  // [IGNORE] The message's slot is for the current slot (with a `MAXIMUM_GOSSIP_CLOCK_DISPARITY` allowance), i.e. `data.slot == current_slot`.
39
48
  if (!chain.clock.isCurrentSlotGivenGossipDisparity(data.slot)) {
40
49
  throw new PayloadAttestationError(GossipAction.IGNORE, {
package/src/db/beacon.ts CHANGED
@@ -11,7 +11,6 @@ import {CheckpointStateRepository} from "./repositories/checkpointState.js";
11
11
  import {
12
12
  AttesterSlashingRepository,
13
13
  BLSToExecutionChangeRepository,
14
- BackfilledRanges,
15
14
  BestLightClientUpdateRepository,
16
15
  BlobSidecarsArchiveRepository,
17
16
  BlobSidecarsRepository,
@@ -61,8 +60,6 @@ export class BeaconDb implements IBeaconDb {
61
60
  syncCommittee: SyncCommitteeRepository;
62
61
  syncCommitteeWitness: SyncCommitteeWitnessRepository;
63
62
 
64
- backfilledRanges: BackfilledRanges;
65
-
66
63
  readonly dataColumns: IDataColumnStore;
67
64
  lastLegacyArchiveSlot: Slot | null = null;
68
65
  private readonly flatFileStore: FlatFileStore;
@@ -97,8 +94,6 @@ export class BeaconDb implements IBeaconDb {
97
94
  this.syncCommittee = new SyncCommitteeRepository(config, db);
98
95
  this.syncCommitteeWitness = new SyncCommitteeWitnessRepository(config, db);
99
96
 
100
- this.backfilledRanges = new BackfilledRanges(config, db);
101
-
102
97
  this.flatFileStore = new FlatFileStore(opts.dataColumnDir, config, opts.logger, opts.metrics);
103
98
  this.dataColumns = new LegacyDataColumnStore(
104
99
  this.flatFileStore,
package/src/db/buckets.ts CHANGED
@@ -56,7 +56,7 @@ export enum Bucket {
56
56
  // altair_lightClientSyncCommitteeProof = 35, // DEPRECATED on v0.32.0
57
57
  // index_lightClientInitProof = 36, // DEPRECATED on v0.32.0
58
58
 
59
- backfilled_ranges = 42, // Backfilled From to To, inclusive of both From, To
59
+ // backfilled_ranges = 42, // DEPRECATED on v1.48.0
60
60
 
61
61
  // Buckets to support LightClient server v2
62
62
  lightClient_syncCommitteeWitness = 51, // BlockRoot -> SyncCommitteeWitness
@@ -71,7 +71,7 @@ export enum Bucket {
71
71
  allForks_dataColumnSidecarsArchive = 58, // BeaconBlockSlot -> DataColumnSidecars
72
72
 
73
73
  gloas_executionPayloadEnvelope = 59, // GLOAS BeaconBlockRoot -> SignedExecutionPayloadEnvelope
74
- gloas_executionPayloadEnvelopeArchive = 60, // GLOAS Slot -> SignedExecutionPayloadEnvelope
74
+ gloas_executionPayloadEnvelopeArchive = 60, // GLOAS Slot -> SignedExecutionPayloadEnvelope, or 0x00 + SignedExecutionPayloadHeaderEnvelope
75
75
  }
76
76
 
77
77
  export function getBucketNameByValue<T extends Bucket>(enumValue: T): keyof typeof Bucket {
@@ -6,7 +6,6 @@ import {CheckpointStateRepository} from "./repositories/checkpointState.js";
6
6
  import {
7
7
  AttesterSlashingRepository,
8
8
  BLSToExecutionChangeRepository,
9
- BackfilledRanges,
10
9
  BestLightClientUpdateRepository,
11
10
  BlobSidecarsArchiveRepository,
12
11
  BlobSidecarsRepository,
@@ -60,8 +59,6 @@ export interface IBeaconDb {
60
59
  syncCommittee: SyncCommitteeRepository;
61
60
  syncCommitteeWitness: SyncCommitteeWitnessRepository;
62
61
 
63
- backfilledRanges: BackfilledRanges;
64
-
65
62
  dataColumns: IDataColumnStore;
66
63
  /** Highest legacy column slot at startup; later archival writes the block-root index first. */
67
64
  readonly lastLegacyArchiveSlot: Slot | null;
@@ -1,25 +1,44 @@
1
1
  import {ChainForkConfig} from "@lodestar/config";
2
- import {BUCKET_LENGTH, Db, Repository, encodeKey as encodeDbKey} from "@lodestar/db";
2
+ import {BUCKET_LENGTH, BinaryRepository, Db, DbBatch, encodeKey as encodeDbKey} from "@lodestar/db";
3
3
  import {Slot, gloas, ssz} from "@lodestar/types";
4
4
  import {bytesToInt} from "@lodestar/utils";
5
5
  import {Bucket, getBucketNameByValue} from "../buckets.js";
6
6
 
7
7
  /**
8
- * Used to store finalized `SignedExecutionPayloadEnvelope`
9
- *
10
- * Indexed by slot for chronological archival
8
+ * Prefix of a header entry. A full `SignedExecutionPayloadEnvelope` starts with the offset of its
9
+ * variable-size `message` field (4 + 96 = 0x64), so a leading 0x00 byte is unambiguous and full
10
+ * entries can be stored as the hot db bytes, untouched.
11
11
  */
12
- export class ExecutionPayloadEnvelopeArchiveRepository extends Repository<Slot, gloas.SignedExecutionPayloadEnvelope> {
12
+ const HEADER_ENVELOPE_PREFIX = 0x00;
13
+
14
+ /** An archive entry as the serving paths need it: full stays bytes, header is deserialized for reconstruction */
15
+ export type ArchivedEnvelope =
16
+ | {headerEnvelope: gloas.SignedExecutionPayloadHeaderEnvelope; envelopeBytes?: undefined}
17
+ | {headerEnvelope?: undefined; envelopeBytes: Uint8Array};
18
+
19
+ export function decodeArchivedEnvelope(bytes: Uint8Array): ArchivedEnvelope {
20
+ return bytes[0] === HEADER_ENVELOPE_PREFIX
21
+ ? {headerEnvelope: ssz.gloas.SignedExecutionPayloadHeaderEnvelope.deserialize(bytes.subarray(1))}
22
+ : {envelopeBytes: bytes};
23
+ }
24
+
25
+ export function encodeArchivedHeaderEnvelope(headerEnvelope: gloas.SignedExecutionPayloadHeaderEnvelope): Uint8Array {
26
+ const value = ssz.gloas.SignedExecutionPayloadHeaderEnvelope.serialize(headerEnvelope);
27
+ const out = new Uint8Array(1 + value.length);
28
+ out[0] = HEADER_ENVELOPE_PREFIX;
29
+ out.set(value, 1);
30
+ return out;
31
+ }
32
+
33
+ /**
34
+ * Finalized envelopes indexed by slot: `SignedExecutionPayloadEnvelope` bytes as-is
35
+ * (`--chain.dedupePayloads=false`, or the block was still optimistic when archived), or a
36
+ * `SignedExecutionPayloadHeaderEnvelope` behind a 0x00 prefix. See {@link decodeArchivedEnvelope}.
37
+ */
38
+ export class ExecutionPayloadEnvelopeArchiveRepository extends BinaryRepository<Slot> {
13
39
  constructor(config: ChainForkConfig, db: Db) {
14
40
  const bucket = Bucket.gloas_executionPayloadEnvelopeArchive;
15
- super(config, db, bucket, ssz.gloas.SignedExecutionPayloadEnvelope, getBucketNameByValue(bucket));
16
- }
17
-
18
- /**
19
- * Id is the slot from the envelope
20
- */
21
- getId(value: gloas.SignedExecutionPayloadEnvelope): Slot {
22
- return value.message.payload.slotNumber;
41
+ super(config, db, bucket, getBucketNameByValue(bucket));
23
42
  }
24
43
 
25
44
  encodeKey(id: Slot): Uint8Array {
@@ -29,4 +48,15 @@ export class ExecutionPayloadEnvelopeArchiveRepository extends Repository<Slot,
29
48
  decodeKey(data: Uint8Array): number {
30
49
  return bytesToInt(data.subarray(BUCKET_LENGTH), "be");
31
50
  }
51
+
52
+ /** Archive entries and delete their hot counterparts (`hotKey` pre-encoded) in one atomic batch */
53
+ async batchArchiveAndDeleteHot(
54
+ entries: {slot: Slot; archivedBytes: Uint8Array; hotKey: Uint8Array}[]
55
+ ): Promise<void> {
56
+ const operations: DbBatch<Uint8Array, Uint8Array> = [];
57
+ for (const {slot, archivedBytes, hotKey} of entries) {
58
+ operations.push({type: "put", key: this.encodeKey(slot), value: archivedBytes}, {type: "del", key: hotKey});
59
+ }
60
+ await this.db.batch(operations, this.dbReqOpts);
61
+ }
32
62
  }