@lodestar/beacon-node 1.49.0-dev.ee3c432d85 → 1.49.0-dev.f1b14bce8f

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 (127) 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/chain/archiveStore/archiveStore.d.ts.map +1 -1
  5. package/lib/chain/archiveStore/archiveStore.js +5 -3
  6. package/lib/chain/archiveStore/archiveStore.js.map +1 -1
  7. package/lib/chain/archiveStore/historicalState/metrics.d.ts.map +1 -1
  8. package/lib/chain/archiveStore/historicalState/metrics.js +2 -1
  9. package/lib/chain/archiveStore/historicalState/metrics.js.map +1 -1
  10. package/lib/chain/archiveStore/utils/archiveBlocks.d.ts +11 -2
  11. package/lib/chain/archiveStore/utils/archiveBlocks.d.ts.map +1 -1
  12. package/lib/chain/archiveStore/utils/archiveBlocks.js +46 -28
  13. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  14. package/lib/chain/archiveStore/utils/pruneHistory.d.ts +2 -2
  15. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  16. package/lib/chain/archiveStore/utils/pruneHistory.js +1 -0
  17. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  18. package/lib/chain/chain.d.ts +10 -0
  19. package/lib/chain/chain.d.ts.map +1 -1
  20. package/lib/chain/chain.js +85 -16
  21. package/lib/chain/chain.js.map +1 -1
  22. package/lib/chain/errors/envelopeReconstructionError.d.ts +23 -0
  23. package/lib/chain/errors/envelopeReconstructionError.d.ts.map +1 -0
  24. package/lib/chain/errors/envelopeReconstructionError.js +13 -0
  25. package/lib/chain/errors/envelopeReconstructionError.js.map +1 -0
  26. package/lib/chain/errors/index.d.ts +1 -0
  27. package/lib/chain/errors/index.d.ts.map +1 -1
  28. package/lib/chain/errors/index.js +1 -0
  29. package/lib/chain/errors/index.js.map +1 -1
  30. package/lib/chain/interface.d.ts +6 -1
  31. package/lib/chain/interface.d.ts.map +1 -1
  32. package/lib/chain/interface.js.map +1 -1
  33. package/lib/chain/options.d.ts +2 -0
  34. package/lib/chain/options.d.ts.map +1 -1
  35. package/lib/chain/options.js +1 -0
  36. package/lib/chain/options.js.map +1 -1
  37. package/lib/db/repositories/executionPayloadEnvelopeArchive.d.ts +21 -9
  38. package/lib/db/repositories/executionPayloadEnvelopeArchive.d.ts.map +1 -1
  39. package/lib/db/repositories/executionPayloadEnvelopeArchive.js +32 -12
  40. package/lib/db/repositories/executionPayloadEnvelopeArchive.js.map +1 -1
  41. package/lib/db/repositories/index.d.ts +1 -1
  42. package/lib/db/repositories/index.d.ts.map +1 -1
  43. package/lib/db/repositories/index.js +1 -1
  44. package/lib/db/repositories/index.js.map +1 -1
  45. package/lib/execution/engine/disabled.d.ts +1 -0
  46. package/lib/execution/engine/disabled.d.ts.map +1 -1
  47. package/lib/execution/engine/disabled.js +3 -0
  48. package/lib/execution/engine/disabled.js.map +1 -1
  49. package/lib/execution/engine/http.d.ts +2 -1
  50. package/lib/execution/engine/http.d.ts.map +1 -1
  51. package/lib/execution/engine/http.js +7 -1
  52. package/lib/execution/engine/http.js.map +1 -1
  53. package/lib/execution/engine/interface.d.ts +3 -1
  54. package/lib/execution/engine/interface.d.ts.map +1 -1
  55. package/lib/execution/engine/mock.d.ts +1 -0
  56. package/lib/execution/engine/mock.d.ts.map +1 -1
  57. package/lib/execution/engine/mock.js +14 -2
  58. package/lib/execution/engine/mock.js.map +1 -1
  59. package/lib/execution/engine/types.d.ts +11 -0
  60. package/lib/execution/engine/types.d.ts.map +1 -1
  61. package/lib/execution/engine/types.js +10 -0
  62. package/lib/execution/engine/types.js.map +1 -1
  63. package/lib/metrics/metrics/beacon.d.ts +9 -0
  64. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  65. package/lib/metrics/metrics/beacon.js +16 -0
  66. package/lib/metrics/metrics/beacon.js.map +1 -1
  67. package/lib/metrics/metrics/lodestar.d.ts +9 -0
  68. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  69. package/lib/metrics/metrics/lodestar.js +23 -0
  70. package/lib/metrics/metrics/lodestar.js.map +1 -1
  71. package/lib/metrics/metrics.d.ts +3 -1
  72. package/lib/metrics/metrics.d.ts.map +1 -1
  73. package/lib/metrics/metrics.js +2 -2
  74. package/lib/metrics/metrics.js.map +1 -1
  75. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRange.d.ts.map +1 -1
  76. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRange.js +47 -34
  77. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRange.js.map +1 -1
  78. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRoot.d.ts.map +1 -1
  79. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRoot.js +23 -4
  80. package/lib/network/reqresp/handlers/executionPayloadEnvelopesByRoot.js.map +1 -1
  81. package/lib/network/reqresp/handlers/index.d.ts.map +1 -1
  82. package/lib/network/reqresp/handlers/index.js +20 -4
  83. package/lib/network/reqresp/handlers/index.js.map +1 -1
  84. package/lib/sync/types.d.ts +0 -2
  85. package/lib/sync/types.d.ts.map +1 -1
  86. package/lib/sync/types.js +0 -2
  87. package/lib/sync/types.js.map +1 -1
  88. package/lib/sync/unknownBlock.d.ts.map +1 -1
  89. package/lib/sync/unknownBlock.js +41 -13
  90. package/lib/sync/unknownBlock.js.map +1 -1
  91. package/lib/util/execution.d.ts +42 -0
  92. package/lib/util/execution.d.ts.map +1 -1
  93. package/lib/util/execution.js +123 -2
  94. package/lib/util/execution.js.map +1 -1
  95. package/lib/util/headerEnvelope.d.ts +17 -0
  96. package/lib/util/headerEnvelope.d.ts.map +1 -0
  97. package/lib/util/headerEnvelope.js +43 -0
  98. package/lib/util/headerEnvelope.js.map +1 -0
  99. package/package.json +15 -14
  100. package/src/api/impl/beacon/blocks/index.ts +16 -3
  101. package/src/chain/archiveStore/archiveStore.ts +6 -3
  102. package/src/chain/archiveStore/historicalState/metrics.ts +3 -2
  103. package/src/chain/archiveStore/utils/archiveBlocks.ts +54 -32
  104. package/src/chain/archiveStore/utils/pruneHistory.ts +4 -2
  105. package/src/chain/chain.ts +96 -20
  106. package/src/chain/errors/envelopeReconstructionError.ts +22 -0
  107. package/src/chain/errors/index.ts +1 -0
  108. package/src/chain/interface.ts +6 -1
  109. package/src/chain/options.ts +3 -0
  110. package/src/db/buckets.ts +1 -1
  111. package/src/db/repositories/executionPayloadEnvelopeArchive.ts +43 -13
  112. package/src/db/repositories/index.ts +6 -1
  113. package/src/execution/engine/disabled.ts +4 -0
  114. package/src/execution/engine/http.ts +12 -0
  115. package/src/execution/engine/interface.ts +4 -1
  116. package/src/execution/engine/mock.ts +22 -2
  117. package/src/execution/engine/types.ts +25 -0
  118. package/src/metrics/metrics/beacon.ts +16 -0
  119. package/src/metrics/metrics/lodestar.ts +24 -0
  120. package/src/metrics/metrics.ts +7 -2
  121. package/src/network/reqresp/handlers/executionPayloadEnvelopesByRange.ts +57 -39
  122. package/src/network/reqresp/handlers/executionPayloadEnvelopesByRoot.ts +27 -5
  123. package/src/network/reqresp/handlers/index.ts +49 -5
  124. package/src/sync/types.ts +0 -2
  125. package/src/sync/unknownBlock.ts +41 -13
  126. package/src/util/execution.ts +175 -2
  127. package/src/util/headerEnvelope.ts +76 -0
@@ -5,8 +5,10 @@ import {GENESIS_SLOT} from "@lodestar/params";
5
5
  import {RespStatus, ResponseError, ResponseOutgoing} from "@lodestar/reqresp";
6
6
  import {computeEpochAtSlot} from "@lodestar/state-transition";
7
7
  import {gloas} from "@lodestar/types";
8
+ import {EnvelopeReconstructionError} from "../../../chain/errors/index.js";
8
9
  import {IBeaconChain} from "../../../chain/index.js";
9
10
  import {IBeaconDb} from "../../../db/index.js";
11
+ import {reconstructExecutionPayloadEnvelopesByRange} from "../../../util/execution.js";
10
12
  import {prettyPrintPeerId} from "../../util.js";
11
13
 
12
14
  export async function* onExecutionPayloadEnvelopesByRange(
@@ -35,58 +37,74 @@ export async function* onExecutionPayloadEnvelopesByRange(
35
37
  );
36
38
  }
37
39
 
38
- const finalized = db.executionPayloadEnvelopeArchive;
39
40
  // Use the finalized block's actual slot as the checkpoint epoch-boundary slot may be skipped
40
41
  const finalizedSlot = chain.forkChoice.getFinalizedBlock().slot;
41
42
  // The finalized block's envelope stays in the hot db until the next finalization run
42
43
  const archiveMaxSlot = finalizedSlot - 1;
43
44
 
44
- // Finalized range of envelopes
45
- if (startSlot <= archiveMaxSlot) {
46
- for await (const {key, value: envelopeBytes} of finalized.binaryEntriesStream({
47
- gte: startSlot,
48
- lt: Math.min(endSlot, archiveMaxSlot + 1),
49
- })) {
50
- const slot = finalized.decodeKey(key);
51
- yield {
52
- data: envelopeBytes,
53
- boundary: chain.config.getForkBoundaryAtEpoch(computeEpochAtSlot(slot)),
54
- };
45
+ let yielded = 0;
46
+ try {
47
+ if (startSlot <= archiveMaxSlot) {
48
+ for await (const {slot, envelopeBytes} of reconstructExecutionPayloadEnvelopesByRange(
49
+ db,
50
+ chain.executionEngine,
51
+ chain.logger,
52
+ chain.metrics,
53
+ startSlot,
54
+ Math.min(endSlot, archiveMaxSlot + 1)
55
+ )) {
56
+ yielded++;
57
+ yield {
58
+ data: envelopeBytes,
59
+ boundary: chain.config.getForkBoundaryAtEpoch(computeEpochAtSlot(slot)),
60
+ };
61
+ }
55
62
  }
56
- }
57
63
 
58
- // Non-finalized range of envelopes
59
- if (endSlot > archiveMaxSlot) {
60
- const headBlock = chain.forkChoice.getHead();
61
- const headRoot = headBlock.blockRoot;
62
- const headChain = chain.forkChoice.getAllAncestorBlocks(headRoot, headBlock.payloadStatus);
64
+ // Non-finalized range of envelopes. The finalized block's own envelope may be archived by a
65
+ // migration that ran since archiveMaxSlot was computed, so this read can reconstruct too.
66
+ if (endSlot > archiveMaxSlot) {
67
+ const headBlock = chain.forkChoice.getHead();
68
+ const headRoot = headBlock.blockRoot;
69
+ const headChain = chain.forkChoice.getAllAncestorBlocks(headRoot, headBlock.payloadStatus);
63
70
 
64
- // Iterate head chain with ascending block numbers
65
- for (let i = headChain.length - 1; i >= 0; i--) {
66
- const block = headChain[i];
71
+ // Iterate head chain with ascending block numbers
72
+ for (let i = headChain.length - 1; i >= 0; i--) {
73
+ const block = headChain[i];
67
74
 
68
- if (block.slot > archiveMaxSlot && block.slot >= startSlot && block.slot < endSlot) {
69
- // Skip EMPTY blocks
70
- if (block.payloadStatus !== PayloadStatus.FULL) {
71
- continue;
72
- }
75
+ if (block.slot > archiveMaxSlot && block.slot >= startSlot && block.slot < endSlot) {
76
+ // Skip EMPTY blocks
77
+ if (block.payloadStatus !== PayloadStatus.FULL) {
78
+ continue;
79
+ }
73
80
 
74
- const envelopeBytes = await chain.getSerializedExecutionPayloadEnvelope(block.slot, block.blockRoot);
75
- if (!envelopeBytes) {
76
- throw new ResponseError(
77
- RespStatus.SERVER_ERROR,
78
- `No envelope for root ${block.blockRoot} slot ${block.slot}, startSlot=${startSlot} endSlot=${endSlot} finalizedSlot=${finalizedSlot}`
79
- );
80
- }
81
+ const envelopeBytes = await chain.getSerializedExecutionPayloadEnvelope(block.slot, block.blockRoot);
82
+ if (!envelopeBytes) {
83
+ throw new ResponseError(
84
+ RespStatus.SERVER_ERROR,
85
+ `No envelope for root ${block.blockRoot} slot ${block.slot}, startSlot=${startSlot} endSlot=${endSlot} finalizedSlot=${finalizedSlot}`
86
+ );
87
+ }
81
88
 
82
- yield {
83
- data: envelopeBytes,
84
- boundary: chain.config.getForkBoundaryAtEpoch(computeEpochAtSlot(block.slot)),
85
- };
86
- } else if (block.slot >= endSlot) {
87
- break;
89
+ yielded++;
90
+ yield {
91
+ data: envelopeBytes,
92
+ boundary: chain.config.getForkBoundaryAtEpoch(computeEpochAtSlot(block.slot)),
93
+ };
94
+ } else if (block.slot >= endSlot) {
95
+ break;
96
+ }
88
97
  }
89
98
  }
99
+ } catch (e) {
100
+ if (e instanceof EnvelopeReconstructionError) {
101
+ // An unservable entry or our own EL failing: after some envelopes, end short (spec-legal, the
102
+ // peer fetches the rest elsewhere); with nothing served, RESOURCE_UNAVAILABLE rather than
103
+ // SERVER_ERROR so peers don't downscore us for it
104
+ if (yielded > 0) return;
105
+ throw new ResponseError(RespStatus.RESOURCE_UNAVAILABLE, `Failed to serve envelopes: ${e.message}`);
106
+ }
107
+ throw e;
90
108
  }
91
109
  }
92
110
 
@@ -1,7 +1,9 @@
1
1
  import {PeerId} from "@libp2p/interface";
2
- import {ResponseOutgoing} from "@lodestar/reqresp";
2
+ import {RespStatus, ResponseError, ResponseOutgoing} from "@lodestar/reqresp";
3
3
  import {computeEpochAtSlot} from "@lodestar/state-transition";
4
+ import {RootHex, Slot} from "@lodestar/types";
4
5
  import {toRootHex} from "@lodestar/utils";
6
+ import {EnvelopeReconstructionError} from "../../../chain/errors/index.js";
5
7
  import {IBeaconChain} from "../../../chain/index.js";
6
8
  import {IBeaconDb} from "../../../db/index.js";
7
9
  import {ExecutionPayloadEnvelopesByRootRequest} from "../../../util/types.js";
@@ -17,6 +19,8 @@ export async function* onExecutionPayloadEnvelopesByRoot(
17
19
  // The gloas req/resp spec uses MIN_EPOCHS_FOR_BLOCK_REQUESTS to define the minimum range peers MUST serve.
18
20
  // Archival nodes may still serve older retained payloads to allow genesis sync.
19
21
 
22
+ // Resolve slots first so archived header envelopes are rebuilt in one EL batch, not one call per root
23
+ const requests: {blockSlot: Slot; blockRootHex: RootHex}[] = [];
20
24
  for (const root of requestBody) {
21
25
  const rootHex = toRootHex(root);
22
26
  const block = chain.forkChoice.getBlockHexDefaultStatus(rootHex);
@@ -34,17 +38,35 @@ export async function* onExecutionPayloadEnvelopesByRoot(
34
38
  );
35
39
  continue;
36
40
  }
41
+ requests.push({blockSlot: slot, blockRootHex: rootHex});
42
+ }
43
+
44
+ let envelopesBytes: (Uint8Array | null)[];
45
+ try {
46
+ // by-root allows omission, so a mismatched envelope is left out rather than failing the response
47
+ envelopesBytes = await chain.getSerializedExecutionPayloadEnvelopes(requests, "omit");
48
+ } catch (e) {
49
+ if (e instanceof EnvelopeReconstructionError) {
50
+ throw new ResponseError(
51
+ RespStatus.RESOURCE_UNAVAILABLE,
52
+ `Failed to reconstruct archived envelopes: ${e.message}`
53
+ );
54
+ }
55
+ throw e;
56
+ }
37
57
 
38
- const envelopeBytes = await chain.getSerializedExecutionPayloadEnvelope(slot, rootHex);
58
+ for (let i = 0; i < requests.length; i++) {
59
+ const {blockSlot, blockRootHex} = requests[i];
60
+ const envelopeBytes = envelopesBytes[i];
39
61
  if (envelopeBytes) {
40
62
  yield {
41
63
  data: envelopeBytes,
42
- boundary: chain.config.getForkBoundaryAtEpoch(computeEpochAtSlot(slot)),
64
+ boundary: chain.config.getForkBoundaryAtEpoch(computeEpochAtSlot(blockSlot)),
43
65
  };
44
66
  } else {
45
67
  chain.logger.debug("Cannot serve ExecutionPayloadEnvelopesByRoot: envelope not found", {
46
- slot,
47
- root: rootHex,
68
+ slot: blockSlot,
69
+ root: blockRootHex,
48
70
  peer: prettyPrintPeerId(peerId),
49
71
  client: peerClient,
50
72
  });
@@ -1,5 +1,5 @@
1
1
  import type {Type} from "@chainsafe/ssz";
2
- import {ProtocolHandler, RespStatus, ResponseError} from "@lodestar/reqresp";
2
+ import {ProtocolHandler, RespStatus, ResponseError, ResponseOutgoing} from "@lodestar/reqresp";
3
3
  import {ssz} from "@lodestar/types";
4
4
  import {IBeaconChain} from "../../../chain/index.js";
5
5
  import {IBeaconDb} from "../../../db/index.js";
@@ -38,6 +38,29 @@ function deserializeRequestBody<T>(type: Type<T>, data: Uint8Array): T {
38
38
  }
39
39
  }
40
40
 
41
+ async function* trackByRangeResponse(
42
+ chain: IBeaconChain,
43
+ method: ReqRespMethod,
44
+ count: number,
45
+ source: AsyncIterable<ResponseOutgoing>,
46
+ columns?: number
47
+ ): AsyncIterable<ResponseOutgoing> {
48
+ chain.metrics?.reqRespByRange.requestedSlots.observe({method}, count);
49
+ if (columns !== undefined) {
50
+ chain.metrics?.reqRespByRange.requestedColumns.observe(columns);
51
+ }
52
+
53
+ let servedBytes = 0;
54
+ try {
55
+ for await (const chunk of source) {
56
+ servedBytes += chunk.data.length;
57
+ yield chunk;
58
+ }
59
+ } finally {
60
+ chain.metrics?.reqRespByRange.servedBytes.observe({method}, servedBytes);
61
+ }
62
+ }
63
+
41
64
  /**
42
65
  * The ReqRespHandler module handles app-level requests / responses from other peers,
43
66
  * fetching state from the chain and database as needed.
@@ -50,7 +73,12 @@ export function getReqRespHandlers({db, chain}: {db: IBeaconDb; chain: IBeaconCh
50
73
  [ReqRespMethod.Metadata]: notImplemented(ReqRespMethod.Metadata),
51
74
  [ReqRespMethod.BeaconBlocksByRange]: (req, peerId, peerClient) => {
52
75
  const body = deserializeRequestBody(ssz.phase0.BeaconBlocksByRangeRequest, req.data);
53
- return onBeaconBlocksByRange(body, chain, db, peerId, peerClient);
76
+ return trackByRangeResponse(
77
+ chain,
78
+ ReqRespMethod.BeaconBlocksByRange,
79
+ body.count,
80
+ onBeaconBlocksByRange(body, chain, db, peerId, peerClient)
81
+ );
54
82
  },
55
83
  [ReqRespMethod.BeaconBlocksByRoot]: (req) => {
56
84
  const fork = chain.config.getForkName(chain.clock.currentSlot);
@@ -68,11 +96,22 @@ export function getReqRespHandlers({db, chain}: {db: IBeaconDb; chain: IBeaconCh
68
96
  },
69
97
  [ReqRespMethod.BlobSidecarsByRange]: (req) => {
70
98
  const body = deserializeRequestBody(ssz.deneb.BlobSidecarsByRangeRequest, req.data);
71
- return onBlobSidecarsByRange(body, chain, db);
99
+ return trackByRangeResponse(
100
+ chain,
101
+ ReqRespMethod.BlobSidecarsByRange,
102
+ body.count,
103
+ onBlobSidecarsByRange(body, chain, db)
104
+ );
72
105
  },
73
106
  [ReqRespMethod.DataColumnSidecarsByRange]: (req, peerId, peerClient) => {
74
107
  const body = deserializeRequestBody(ssz.fulu.DataColumnSidecarsByRangeRequest, req.data);
75
- return onDataColumnSidecarsByRange(body, chain, db, peerId, peerClient);
108
+ return trackByRangeResponse(
109
+ chain,
110
+ ReqRespMethod.DataColumnSidecarsByRange,
111
+ body.count,
112
+ onDataColumnSidecarsByRange(body, chain, db, peerId, peerClient),
113
+ body.columns.length
114
+ );
76
115
  },
77
116
  [ReqRespMethod.DataColumnSidecarsByRoot]: (req, peerId, peerClient) => {
78
117
  const body = deserializeRequestBody(DataColumnSidecarsByRootRequestType(chain.config), req.data);
@@ -85,7 +124,12 @@ export function getReqRespHandlers({db, chain}: {db: IBeaconDb; chain: IBeaconCh
85
124
  },
86
125
  [ReqRespMethod.ExecutionPayloadEnvelopesByRange]: (req, peerId, peerClient) => {
87
126
  const body = deserializeRequestBody(ssz.gloas.ExecutionPayloadEnvelopesByRangeRequest, req.data);
88
- return onExecutionPayloadEnvelopesByRange(body, chain, db, peerId, peerClient);
127
+ return trackByRangeResponse(
128
+ chain,
129
+ ReqRespMethod.ExecutionPayloadEnvelopesByRange,
130
+ body.count,
131
+ onExecutionPayloadEnvelopesByRange(body, chain, db, peerId, peerClient)
132
+ );
89
133
  },
90
134
 
91
135
  [ReqRespMethod.LightClientBootstrap]: (req) => {
package/src/sync/types.ts CHANGED
@@ -105,8 +105,6 @@ export enum DroppedItemReason {
105
105
  invalidEnvelope = "invalid_envelope",
106
106
  /** a payload had an invalid signature (INVALID_SIGNATURE) */
107
107
  invalidSignature = "invalid_signature",
108
- /** a block root was given up on after exhausting download attempts (data could not be fetched) */
109
- unavailable = "unavailable",
110
108
  /** an unexpected / unhandled error code led to removal */
111
109
  unknown = "unknown",
112
110
  }
@@ -227,8 +227,11 @@ export class BlockInputSync {
227
227
  private onUnknownBlockRoot = (data: ChainEventData[ChainEvent.unknownBlockRoot]): void => {
228
228
  try {
229
229
  const isNewRoot = this.addByRootHex(data.rootHex, data.peer);
230
- if (isNewRoot) {
230
+ // A retained entry (an earlier download failed, #10018) is not new but still needs a retry pass.
231
+ if (this.pendingBlocks.get(data.rootHex)?.status === PendingBlockInputStatus.pending) {
231
232
  this.triggerUnknownBlockSearch();
233
+ }
234
+ if (isNewRoot) {
232
235
  this.metrics?.blockInputSync.requests.inc({type: PendingBlockType.UNKNOWN_BLOCK_ROOT});
233
236
  this.metrics?.blockInputSync.source.inc({source: data.source});
234
237
  }
@@ -393,12 +396,21 @@ export class BlockInputSync {
393
396
  }
394
397
  }
395
398
 
396
- let deletedBlocks = 0;
399
+ let belowFinalizedBlocks = 0;
400
+ let agedOutBlocks = 0;
397
401
  for (const [rootHex, block] of this.pendingBlocks) {
398
402
  const slot = getBlockInputSyncCacheItemSlot(block);
399
- if (typeof slot === "number" && slot < finalizedSlot) {
403
+ if (typeof slot !== "number") {
404
+ // we may not be able to download a root, hence there is no slot for it
405
+ if (nowSec - block.timeAddedSec > maxSecInCache) {
406
+ this.pendingBlocks.delete(rootHex);
407
+ agedOutBlocks++;
408
+ }
409
+ continue;
410
+ }
411
+ if (slot < finalizedSlot) {
400
412
  this.pendingBlocks.delete(rootHex);
401
- deletedBlocks++;
413
+ belowFinalizedBlocks++;
402
414
  }
403
415
  }
404
416
 
@@ -411,16 +423,20 @@ export class BlockInputSync {
411
423
  if (agedOutPayloads > 0) {
412
424
  this.metrics?.blockInputSync.removedPayloads.inc({reason: DroppedItemReason.agedOut}, agedOutPayloads);
413
425
  }
414
- if (deletedBlocks > 0) {
415
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.belowFinalized}, deletedBlocks);
426
+ if (belowFinalizedBlocks > 0) {
427
+ this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.belowFinalized}, belowFinalizedBlocks);
428
+ }
429
+ if (agedOutBlocks > 0) {
430
+ this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.agedOut}, agedOutBlocks);
416
431
  }
417
432
 
418
- this.logger.debug("BlockInputSync.pruneFinalized dropped pre-finalized pending items", {
433
+ this.logger.debug("BlockInputSync.pruneFinalized dropped stale pending items", {
419
434
  finalizedSlot,
420
435
  finalizedRoot: checkpoint.rootHex,
421
436
  belowFinalizedPayloads,
422
437
  agedOutPayloads,
423
- deletedBlocks,
438
+ belowFinalizedBlocks,
439
+ agedOutBlocks,
424
440
  unresolvedSlotPayloads,
425
441
  });
426
442
  };
@@ -973,7 +989,12 @@ export class BlockInputSync {
973
989
  if (!res.err) {
974
990
  this.metrics?.blockInputSync.downloadedBlocksSuccess.inc();
975
991
  const pending = res.result;
976
- this.pendingBlocks.set(pending.blockInput.blockRootHex, pending);
992
+ // pruning may have deleted this entry while we were awaiting the network, do not resurrect it via the set below
993
+ if (!this.pendingBlocks.has(rootHex)) {
994
+ this.logger.verbose("Dropping downloaded block, entry pruned during fetch", logCtx);
995
+ return;
996
+ }
997
+ this.pendingBlocks.set(rootHex, pending);
977
998
  const blockSlot = pending.blockInput.slot;
978
999
  const finalizedSlot = this.chain.forkChoice.getFinalizedBlock().slot;
979
1000
  const delaySec = Date.now() / 1000 - computeTimeAtSlot(this.config, blockSlot, this.chain.genesisTime);
@@ -1035,8 +1056,11 @@ export class BlockInputSync {
1035
1056
  }
1036
1057
 
1037
1058
  this.metrics?.blockInputSync.downloadedBlocksError.inc();
1038
- this.logger.debug("Ignoring unknown block root after many failed downloads", logCtx, res.err);
1039
- this.removeAndDownScoreAllDescendants(block, DroppedItemReason.unavailable);
1059
+ this.logger.debug("Failed to download unknown block root, retained for retry", logCtx, res.err);
1060
+ const pendingBlock = this.pendingBlocks.get(rootHex);
1061
+ if (pendingBlock && pendingBlock.status === PendingBlockInputStatus.fetching) {
1062
+ pendingBlock.status = PendingBlockInputStatus.pending;
1063
+ }
1040
1064
  }
1041
1065
  }
1042
1066
 
@@ -1303,7 +1327,7 @@ export class BlockInputSync {
1303
1327
  }
1304
1328
 
1305
1329
  this.metrics?.blockInputSync.downloadedPayloadsResult.inc({result: DownloadResult.Failed});
1306
- this.logger.debug("Ignoring unknown payload root after failed download", logCtx, res.err);
1330
+ this.logger.debug("Failed to download unknown payload root, retained for retry", logCtx, res.err);
1307
1331
  if (!isPendingPayloadEnvelope(payload)) {
1308
1332
  payload.status = PendingPayloadInputStatus.pending;
1309
1333
  }
@@ -1763,7 +1787,11 @@ export class BlockInputSync {
1763
1787
  this.peerBalancer.onRequestCompleted(peerId);
1764
1788
  }
1765
1789
 
1766
- this.pendingBlocks.set(getBlockInputSyncCacheItemRootHex(cacheItem), cacheItem);
1790
+ const cacheItemRootHex = getBlockInputSyncCacheItemRootHex(cacheItem);
1791
+ // pruning may have dropped it mid-fetch
1792
+ if (this.pendingBlocks.has(cacheItemRootHex)) {
1793
+ this.pendingBlocks.set(cacheItemRootHex, cacheItem);
1794
+ }
1767
1795
 
1768
1796
  if (cacheItem.status === PendingBlockInputStatus.downloaded) {
1769
1797
  // download was successful, no need to go with another peer, return
@@ -2,12 +2,18 @@ import {routes} from "@lodestar/api";
2
2
  import {ChainForkConfig} from "@lodestar/config";
3
3
  import {ForkPostFulu, ForkPreFulu} from "@lodestar/params";
4
4
  import {signedBlockToSignedHeader} from "@lodestar/state-transition";
5
- import {DataColumnSidecar, SignedBeaconBlock, deneb, isGloasDataColumnSidecar} from "@lodestar/types";
6
- import {fromHex, toHex} from "@lodestar/utils";
5
+ import {DataColumnSidecar, SignedBeaconBlock, Slot, deneb, gloas, isGloasDataColumnSidecar, ssz} from "@lodestar/types";
6
+ import {Logger, fromHex, toHex, toRootHex} from "@lodestar/utils";
7
7
  import {isBlockInputBlobs, isBlockInputColumns} from "../chain/blocks/blockInput/blockInput.js";
8
8
  import {BlockInputSource, IBlockInput} from "../chain/blocks/blockInput/types.js";
9
9
  import {PayloadEnvelopeInput, PayloadEnvelopeInputSource} from "../chain/blocks/payloadEnvelopeInput/index.js";
10
10
  import {ChainEvent, ChainEventEmitter} from "../chain/emitter.js";
11
+ import {
12
+ EnvelopeReconstructionError,
13
+ EnvelopeReconstructionErrorCode,
14
+ } from "../chain/errors/envelopeReconstructionError.js";
15
+ import {IBeaconDb} from "../db/index.js";
16
+ import {ArchivedEnvelope, decodeArchivedEnvelope} from "../db/repositories/index.js";
11
17
  import {IExecutionEngine} from "../execution/index.js";
12
18
  import {Metrics} from "../metrics/index.js";
13
19
  import {computePreFuluKzgCommitmentsInclusionProof} from "./blobs.js";
@@ -17,6 +23,7 @@ import {
17
23
  getDataColumnSidecarsFromColumnSidecar,
18
24
  getGloasDataColumnSidecars,
19
25
  } from "./dataColumns.js";
26
+ import {signedHeaderEnvelopeToFull} from "./headerEnvelope.js";
20
27
 
21
28
  export enum DataColumnEngineResult {
22
29
  PreFulu = "pre_fulu",
@@ -251,3 +258,169 @@ export async function getDataColumnSidecarsFromExecution(
251
258
  );
252
259
  return DataColumnEngineResult.SuccessResolved;
253
260
  }
261
+
262
+ /** engine_getPayloadBodiesByHashV2: ELs MUST support at least 32 hashes per request. */
263
+ const MAX_BODIES_REQUEST = 32;
264
+
265
+ type SlotEnvelopeBytes = {slot: Slot; envelopeBytes: Uint8Array};
266
+
267
+ type RangeEntry = ArchivedEnvelope & {slot: Slot};
268
+
269
+ /** What a body root mismatch means on a given serving path */
270
+ export type ReconstructMismatchPolicy = "throw" | "omit";
271
+
272
+ export type RebuildMiss =
273
+ /** EL does not have the block, or has pruned its block access list */
274
+ | {slot: Slot; reason: "unavailable"}
275
+ /** An EL body does not hash to its stored root (local inconsistency) */
276
+ | {slot: Slot; reason: "mismatch"; error: EnvelopeReconstructionError};
277
+
278
+ /**
279
+ * Stream finalized envelopes over [startSlot, endSlot) as serialized bytes, rebuilding header
280
+ * entries from EL bodies 32 per round-trip.
281
+ *
282
+ * Ends at the first entry that cannot be served by throwing RANGE_UNSERVABLE with that slot: the
283
+ * by-range spec inherits BeaconBlocksByRange v2 semantics (consecutive, MAY be short), and a hole
284
+ * looks like a lying peer to one that already holds the blocks. Entries are attempted regardless of
285
+ * age; the EL's block access list retention is the floor, not MIN_EPOCHS_FOR_BLOCK_REQUESTS.
286
+ *
287
+ * Throws ENGINE_UNAVAILABLE if the EL call fails. Either may surface after envelopes were yielded.
288
+ */
289
+ export async function* reconstructExecutionPayloadEnvelopesByRange(
290
+ db: IBeaconDb,
291
+ executionEngine: IExecutionEngine,
292
+ logger: Logger,
293
+ metrics: Metrics | null,
294
+ startSlot: Slot,
295
+ endSlot: Slot
296
+ ): AsyncIterable<SlotEnvelopeBytes> {
297
+ const archive = db.executionPayloadEnvelopeArchive;
298
+ let batch: RangeEntry[] = [];
299
+
300
+ for await (const {key, value: bytes} of archive.binaryEntriesStream({gte: startSlot, lt: endSlot})) {
301
+ batch.push({slot: archive.decodeKey(key), ...decodeArchivedEnvelope(bytes)});
302
+ if (batch.length === MAX_BODIES_REQUEST) {
303
+ yield* reconstructBatch(executionEngine, logger, metrics, batch);
304
+ batch = [];
305
+ }
306
+ }
307
+ if (batch.length > 0) {
308
+ yield* reconstructBatch(executionEngine, logger, metrics, batch);
309
+ }
310
+ }
311
+
312
+ /**
313
+ * Rebuild a range batch, yielding what precedes the first unservable entry before throwing
314
+ * RANGE_UNSERVABLE for it
315
+ */
316
+ async function* reconstructBatch(
317
+ executionEngine: IExecutionEngine,
318
+ logger: Logger,
319
+ metrics: Metrics | null,
320
+ batch: RangeEntry[]
321
+ ): AsyncIterable<SlotEnvelopeBytes> {
322
+ const headerEnvelopes: gloas.SignedExecutionPayloadHeaderEnvelope[] = [];
323
+ for (const entry of batch) {
324
+ if (entry.headerEnvelope !== undefined) headerEnvelopes.push(entry.headerEnvelope);
325
+ }
326
+ const rebuilt = await reconstructEnvelopesBatch(executionEngine, metrics, headerEnvelopes);
327
+
328
+ let rebuiltIdx = 0;
329
+ for (const entry of batch) {
330
+ if (entry.envelopeBytes !== undefined) {
331
+ yield {slot: entry.slot, envelopeBytes: entry.envelopeBytes};
332
+ continue;
333
+ }
334
+ const result = rebuilt[rebuiltIdx++];
335
+ if (isRebuildMiss(result)) {
336
+ // Peer-triggered, so debug: a persistent local mismatch would otherwise log on every request
337
+ if (result.reason === "mismatch") {
338
+ logger.debug("Archived envelope failed body root check against EL bodies", {slot: entry.slot}, result.error);
339
+ } else {
340
+ logger.debug("EL cannot serve bodies for archived envelope, ending range", {slot: entry.slot});
341
+ }
342
+ throw new EnvelopeReconstructionError(
343
+ {code: EnvelopeReconstructionErrorCode.RANGE_UNSERVABLE, slot: entry.slot},
344
+ `archived envelope range unservable from slot=${entry.slot}`
345
+ );
346
+ }
347
+ yield {slot: entry.slot, envelopeBytes: ssz.gloas.SignedExecutionPayloadEnvelope.serialize(result)};
348
+ }
349
+ }
350
+
351
+ /**
352
+ * Rebuild header envelopes from EL bodies, 32 per round-trip. Aligned with the input, with a
353
+ * {@link RebuildMiss} where the envelope could not be rebuilt; the caller decides what a miss means
354
+ * on its path. Throws ENGINE_UNAVAILABLE only.
355
+ */
356
+ export async function reconstructExecutionPayloadEnvelopes(
357
+ executionEngine: IExecutionEngine,
358
+ metrics: Metrics | null,
359
+ headerEnvelopes: gloas.SignedExecutionPayloadHeaderEnvelope[]
360
+ ): Promise<(gloas.SignedExecutionPayloadEnvelope | RebuildMiss)[]> {
361
+ const out: (gloas.SignedExecutionPayloadEnvelope | RebuildMiss)[] = [];
362
+ for (let i = 0; i < headerEnvelopes.length; i += MAX_BODIES_REQUEST) {
363
+ out.push(
364
+ ...(await reconstructEnvelopesBatch(executionEngine, metrics, headerEnvelopes.slice(i, i + MAX_BODIES_REQUEST)))
365
+ );
366
+ }
367
+ return out;
368
+ }
369
+
370
+ export function isRebuildMiss(result: gloas.SignedExecutionPayloadEnvelope | RebuildMiss): result is RebuildMiss {
371
+ return "reason" in result;
372
+ }
373
+
374
+ /**
375
+ * One EL round-trip. Aligned with the input; never throws per envelope, only ENGINE_UNAVAILABLE.
376
+ * Every serving path (by-range, by-root, REST) comes through here, so the outcome metrics are
377
+ * incremented once, in this function.
378
+ */
379
+ async function reconstructEnvelopesBatch(
380
+ executionEngine: IExecutionEngine,
381
+ metrics: Metrics | null,
382
+ headerEnvelopes: gloas.SignedExecutionPayloadHeaderEnvelope[]
383
+ ): Promise<(gloas.SignedExecutionPayloadEnvelope | RebuildMiss)[]> {
384
+ if (headerEnvelopes.length === 0) return [];
385
+ const hashes = headerEnvelopes.map((headerEnvelope) => toRootHex(headerEnvelope.message.payloadHeader.blockHash));
386
+
387
+ let bodies: Awaited<ReturnType<IExecutionEngine["getPayloadBodiesByHashV2"]>>;
388
+ try {
389
+ bodies = await executionEngine.getPayloadBodiesByHashV2(hashes);
390
+ } catch (e) {
391
+ metrics?.payloadEnvelopeReconstruction.engineErrors.inc();
392
+ throw new EnvelopeReconstructionError(
393
+ {code: EnvelopeReconstructionErrorCode.ENGINE_UNAVAILABLE},
394
+ `engine_getPayloadBodiesByHashV2 failed: ${(e as Error).message}`
395
+ );
396
+ }
397
+
398
+ return headerEnvelopes.map((headerEnvelope, i) => {
399
+ const slot = headerEnvelope.message.payloadHeader.slotNumber;
400
+ const body = bodies[i];
401
+ // A zero-length block access list cannot be valid, RLP encodes an empty list as 0xc0
402
+ if (body == null || body.withdrawals == null || body.blockAccessList == null || body.blockAccessList.length === 0) {
403
+ metrics?.payloadEnvelopeReconstruction.envelopes.inc({result: "unavailable"});
404
+ return {slot, reason: "unavailable"};
405
+ }
406
+ try {
407
+ const envelope = signedHeaderEnvelopeToFull(headerEnvelope, {
408
+ transactions: body.transactions,
409
+ withdrawals: body.withdrawals,
410
+ blockAccessList: body.blockAccessList,
411
+ });
412
+ metrics?.payloadEnvelopeReconstruction.envelopes.inc({result: "ok"});
413
+ return envelope;
414
+ } catch (e) {
415
+ if (
416
+ e instanceof EnvelopeReconstructionError &&
417
+ e.type.code === EnvelopeReconstructionErrorCode.BODY_ROOT_MISMATCH
418
+ ) {
419
+ metrics?.payloadEnvelopeReconstruction.envelopes.inc({result: "mismatch"});
420
+ metrics?.payloadEnvelopeReconstruction.mismatchByField.inc({field: e.type.field});
421
+ return {slot, reason: "mismatch", error: e};
422
+ }
423
+ throw e;
424
+ }
425
+ });
426
+ }
@@ -0,0 +1,76 @@
1
+ import {ssz} from "@lodestar/types";
2
+ import {
3
+ BlockAccessList,
4
+ ExecutionPayloadEnvelope,
5
+ ExecutionPayloadHeaderEnvelope,
6
+ SignedExecutionPayloadEnvelope,
7
+ SignedExecutionPayloadHeaderEnvelope,
8
+ Transactions,
9
+ Withdrawals,
10
+ } from "@lodestar/types/gloas";
11
+ import {toRootHex} from "@lodestar/utils";
12
+ import {
13
+ EnvelopeReconstructionError,
14
+ EnvelopeReconstructionErrorCode,
15
+ } from "../chain/errors/envelopeReconstructionError.js";
16
+
17
+ /** The parts of an execution payload the EL serves back via engine_getPayloadBodiesByHashV2 */
18
+ export type ExecutionPayloadBodies = {
19
+ transactions: Transactions;
20
+ withdrawals: Withdrawals;
21
+ blockAccessList: BlockAccessList;
22
+ };
23
+
24
+ export type ExecutionPayloadBodyField = keyof ExecutionPayloadBodies;
25
+
26
+ const {transactions, withdrawals, blockAccessList} = ssz.gloas.ExecutionPayload.fields;
27
+
28
+ /** Replace the three body lists by their roots; hashes to the same root as the full envelope */
29
+ export function toHeaderEnvelope(envelope: ExecutionPayloadEnvelope): ExecutionPayloadHeaderEnvelope {
30
+ const {payload, ...envelopeFields} = envelope;
31
+ const {transactions: txs, withdrawals: wds, blockAccessList: bal, ...scalars} = payload;
32
+ return {
33
+ ...envelopeFields,
34
+ payloadHeader: {
35
+ ...scalars,
36
+ transactionsRoot: transactions.hashTreeRoot(txs),
37
+ withdrawalsRoot: withdrawals.hashTreeRoot(wds),
38
+ blockAccessListRoot: blockAccessList.hashTreeRoot(bal),
39
+ },
40
+ };
41
+ }
42
+
43
+ export function toSignedHeaderEnvelope(envelope: SignedExecutionPayloadEnvelope): SignedExecutionPayloadHeaderEnvelope {
44
+ return {message: toHeaderEnvelope(envelope.message), signature: envelope.signature};
45
+ }
46
+
47
+ /**
48
+ * Rebuild the full signed envelope from header envelope + EL bodies, each body verified against its stored
49
+ * root. Throws {@link EnvelopeReconstructionError} BODY_ROOT_MISMATCH naming the first body that differs.
50
+ */
51
+ export function signedHeaderEnvelopeToFull(
52
+ headerEnvelope: SignedExecutionPayloadHeaderEnvelope,
53
+ bodies: ExecutionPayloadBodies
54
+ ): SignedExecutionPayloadEnvelope {
55
+ const {payloadHeader, ...envelopeFields} = headerEnvelope.message;
56
+ const {transactionsRoot, withdrawalsRoot, blockAccessListRoot, ...scalars} = payloadHeader;
57
+ const slot = scalars.slotNumber;
58
+
59
+ assertBodyRoot("transactions", slot, transactionsRoot, transactions.hashTreeRoot(bodies.transactions));
60
+ assertBodyRoot("withdrawals", slot, withdrawalsRoot, withdrawals.hashTreeRoot(bodies.withdrawals));
61
+ assertBodyRoot("blockAccessList", slot, blockAccessListRoot, blockAccessList.hashTreeRoot(bodies.blockAccessList));
62
+
63
+ return {
64
+ message: {...envelopeFields, payload: {...scalars, ...bodies}},
65
+ signature: headerEnvelope.signature,
66
+ };
67
+ }
68
+
69
+ function assertBodyRoot(field: ExecutionPayloadBodyField, slot: number, stored: Uint8Array, rebuilt: Uint8Array): void {
70
+ if (!ssz.Root.equals(stored, rebuilt)) {
71
+ throw new EnvelopeReconstructionError(
72
+ {code: EnvelopeReconstructionErrorCode.BODY_ROOT_MISMATCH, slot, field},
73
+ `reconstructed ${field} root mismatch slot=${slot} stored=${toRootHex(stored)} rebuilt=${toRootHex(rebuilt)}`
74
+ );
75
+ }
76
+ }