@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
@@ -8,7 +8,6 @@ import {BeaconConfig} from "@lodestar/config";
8
8
  import type {LoggerNode} from "@lodestar/logger/node";
9
9
  import {ZERO_HASH_HEX} from "@lodestar/params";
10
10
  import {IBeaconStateView, isStatePostBellatrix, isStatePostGloas} from "@lodestar/state-transition";
11
- import {phase0} from "@lodestar/types";
12
11
  import {sleep, toRootHex} from "@lodestar/utils";
13
12
  import {ProcessShutdownCallback} from "@lodestar/validator";
14
13
  import {BeaconRestApiServer, getApi} from "../api/index.js";
@@ -19,7 +18,6 @@ import {initializeExecutionBuilder, initializeExecutionEngine} from "../executio
19
18
  import {HttpMetricsServer, Metrics, createMetrics, getHttpMetricsServer} from "../metrics/index.js";
20
19
  import {MonitoringService} from "../monitoring/index.js";
21
20
  import {Network, getReqRespHandlers} from "../network/index.js";
22
- import {BackfillSync} from "../sync/backfill/index.js";
23
21
  import {BeaconSync, IBeaconSync} from "../sync/index.js";
24
22
  import {Clock} from "../util/clock.js";
25
23
  import {startDeferredVoluntaryExitPublisher} from "./deferredVoluntaryExitPublisher.js";
@@ -38,7 +36,6 @@ export type BeaconNodeModules = {
38
36
  chain: IBeaconChain;
39
37
  api: BeaconApiMethods;
40
38
  sync: IBeaconSync;
41
- backfillSync: BackfillSync | null;
42
39
  metricsServer: HttpMetricsServer | null;
43
40
  monitoring: MonitoringService | null;
44
41
  restApi?: BeaconRestApiServer;
@@ -58,7 +55,6 @@ export type BeaconNodeInitModules = {
58
55
  peerStoreDir?: string;
59
56
  anchorState: IBeaconStateView;
60
57
  isAnchorStateFinalized: boolean;
61
- wsCheckpoint?: phase0.Checkpoint;
62
58
  metricsRegistries?: Registry[];
63
59
  };
64
60
 
@@ -70,7 +66,6 @@ export enum BeaconNodeStatus {
70
66
 
71
67
  enum LoggerModule {
72
68
  api = "api",
73
- backfill = "backfill",
74
69
  chain = "chain",
75
70
  execution = "execution",
76
71
  metrics = "metrics",
@@ -105,7 +100,6 @@ export class BeaconNode {
105
100
  api: BeaconApiMethods;
106
101
  restApi?: BeaconRestApiServer;
107
102
  sync: IBeaconSync;
108
- backfillSync: BackfillSync | null;
109
103
 
110
104
  status: BeaconNodeStatus;
111
105
  private controller?: AbortController;
@@ -123,7 +117,6 @@ export class BeaconNode {
123
117
  api,
124
118
  restApi,
125
119
  sync,
126
- backfillSync,
127
120
  controller,
128
121
  }: BeaconNodeModules) {
129
122
  this.opts = opts;
@@ -138,7 +131,6 @@ export class BeaconNode {
138
131
  this.restApi = restApi;
139
132
  this.network = network;
140
133
  this.sync = sync;
141
- this.backfillSync = backfillSync;
142
134
  this.controller = controller;
143
135
 
144
136
  this.status = BeaconNodeStatus.started;
@@ -161,7 +153,6 @@ export class BeaconNode {
161
153
  peerStoreDir,
162
154
  anchorState,
163
155
  isAnchorStateFinalized,
164
- wsCheckpoint,
165
156
  metricsRegistries = [],
166
157
  }: BeaconNodeInitModules): Promise<T> {
167
158
  if (hasher.name !== "hashtree") {
@@ -295,25 +286,9 @@ export class BeaconNode {
295
286
  chain,
296
287
  metrics,
297
288
  network,
298
- wsCheckpoint,
299
289
  logger: logger.child({module: LoggerModule.sync}),
300
290
  });
301
291
 
302
- const backfillSync =
303
- opts.sync.backfillBatchSize > 0
304
- ? await BackfillSync.init(opts.sync, {
305
- config,
306
- db,
307
- chain,
308
- metrics,
309
- network,
310
- wsCheckpoint,
311
- anchorState,
312
- logger: logger.child({module: LoggerModule.backfill}),
313
- signal,
314
- })
315
- : null;
316
-
317
292
  const api = getApi(opts.api, {
318
293
  config,
319
294
  logger: logger.child({module: LoggerModule.api}),
@@ -361,7 +336,6 @@ export class BeaconNode {
361
336
  api,
362
337
  restApi,
363
338
  sync,
364
- backfillSync,
365
339
  controller,
366
340
  }) as T;
367
341
  }
@@ -373,7 +347,6 @@ export class BeaconNode {
373
347
  if (this.status === BeaconNodeStatus.started) {
374
348
  this.status = BeaconNodeStatus.closing;
375
349
  this.sync.close();
376
- this.backfillSync?.close();
377
350
  if (this.restApi) await this.restApi.close();
378
351
  await this.network.close();
379
352
  if (this.metricsServer) await this.metricsServer.close();
@@ -1,6 +1,6 @@
1
1
  import {routes} from "@lodestar/api";
2
2
  import {BeaconConfig} from "@lodestar/config";
3
- import {Slot, phase0} from "@lodestar/types";
3
+ import {Slot} from "@lodestar/types";
4
4
  import {Logger} from "@lodestar/utils";
5
5
  import {IBeaconChain} from "../chain/index.js";
6
6
  import {IBeaconDb} from "../db/index.js";
@@ -51,5 +51,4 @@ export interface SyncModules {
51
51
  metrics: Metrics | null;
52
52
  logger: Logger;
53
53
  chain: IBeaconChain;
54
- wsCheckpoint?: phase0.Checkpoint;
55
54
  }
@@ -16,12 +16,6 @@ export type SyncOptions = {
16
16
  disableRangeSync?: boolean;
17
17
  /** USE FOR TESTING ONLY. Disable unknown block sync completely */
18
18
  disableBlockInputSync?: boolean;
19
- /**
20
- * The batch size of slots for backfill sync can attempt to sync/process before yielding
21
- * to sync loop. This number can be increased or decreased to make a suitable resource
22
- * allocation to backfill sync. The default of 0 would mean backfill sync will be skipped
23
- */
24
- backfillBatchSize: number;
25
19
  /** For testing only, MAX_PENDING_BLOCKS by default */
26
20
  maxPendingBlocks?: number;
27
21
 
@@ -39,7 +33,5 @@ export type SyncOptions = {
39
33
  export const defaultSyncOptions: SyncOptions = {
40
34
  isSingleNode: false,
41
35
  disableProcessAsChainSegment: false,
42
- /** By default skip the backfill sync */
43
- backfillBatchSize: 0,
44
36
  slotImportTolerance: SLOTS_PER_EPOCH,
45
37
  };
package/src/sync/types.ts CHANGED
@@ -24,9 +24,13 @@ export enum PendingBlockType {
24
24
  */
25
25
  UNKNOWN_PAYLOAD_BLOCK_ROOT = "unknown_payload_block_root",
26
26
  /**
27
- * Same as UNKNOWN_PAYLOAD_BLOCK_ROOT, but the trigger also carries the payload's slot.
27
+ * Same as UNKNOWN_PAYLOAD_BLOCK_ROOT, but the trigger also carries the payload's slot
28
28
  */
29
29
  UNKNOWN_PAYLOAD_BLOCK_ROOT_SLOT = "unknown_payload_block_root_slot",
30
+ /**
31
+ * Same as UNKNOWN_PAYLOAD_BLOCK_ROOT_SLOT for the current slot
32
+ */
33
+ DEFERRED_PAYLOAD_BLOCK_ROOT = "deferred_payload_block_root",
30
34
  /**
31
35
  * Payload analog of INCOMPLETE_BLOCK_INPUT: we have a partial payload input that did not complete in time.
32
36
  */
@@ -53,6 +57,20 @@ export enum FetchResult {
53
57
  FailureMaxAttempts = "failure_max_attempts",
54
58
  }
55
59
 
60
+ /**
61
+ * Outcome of a slot's deferred optimistic payload searches, recorded once when its poll loop ends.
62
+ */
63
+ export enum DeferredPayloadResult {
64
+ /** gossip delivered every watched payload before PAYLOAD_DUE, no search was needed */
65
+ ImportedBeforeSearch = "imported_before_search",
66
+ /** at least one was missing at PAYLOAD_DUE, we searched, and all were imported afterwards */
67
+ ImportedAfterSearch = "imported_after_search",
68
+ /** something was still not in fork choice when the slot ended */
69
+ Unresolved = "unresolved",
70
+ /** the slot had no optimistic search and no payload import at all, eg a skipped slot */
71
+ ResolvedNoRoot = "resolved_no_root",
72
+ }
73
+
56
74
  export enum PendingBlockInputStatus {
57
75
  pending = "pending",
58
76
  fetching = "fetching",
@@ -87,8 +105,6 @@ export enum DroppedItemReason {
87
105
  invalidEnvelope = "invalid_envelope",
88
106
  /** a payload had an invalid signature (INVALID_SIGNATURE) */
89
107
  invalidSignature = "invalid_signature",
90
- /** a block root was given up on after exhausting download attempts (data could not be fetched) */
91
- unavailable = "unavailable",
92
108
  /** an unexpected / unhandled error code led to removal */
93
109
  unknown = "unknown",
94
110
  }
@@ -5,7 +5,7 @@ import {ForkSeq, SLOTS_PER_EPOCH, isForkPostGloas} from "@lodestar/params";
5
5
  import {RequestError, RequestErrorCode} from "@lodestar/reqresp";
6
6
  import {computeTimeAtSlot} from "@lodestar/state-transition";
7
7
  import {RootHex, Slot, gloas} from "@lodestar/types";
8
- import {Logger, fromHex, prettyPrintIndices, pruneSetToMax, sleep, toRootHex} from "@lodestar/utils";
8
+ import {Logger, fromHex, isErrorAborted, prettyPrintIndices, pruneSetToMax, sleep, toRootHex} from "@lodestar/utils";
9
9
  import {isBlockInputBlobs, isBlockInputColumns} from "../chain/blocks/blockInput/blockInput.js";
10
10
  import {BlockInputSource, IBlockInput} from "../chain/blocks/blockInput/types.js";
11
11
  import {PayloadError, PayloadErrorCode} from "../chain/blocks/importExecutionPayload.js";
@@ -18,6 +18,7 @@ import {Metrics} from "../metrics/index.js";
18
18
  import {INetwork, NetworkEvent, NetworkEventData, prettyPrintPeerIdStr} from "../network/index.js";
19
19
  import {PeerSyncMeta} from "../network/peers/peersData.js";
20
20
  import {MAX_PEERS_PER_ROOT} from "../network/processor/constants.js";
21
+ import {ClockEvent} from "../util/clock.js";
21
22
  import {PeerIdStr} from "../util/peerId.js";
22
23
  import {shuffle} from "../util/shuffle.js";
23
24
  import {sortBy} from "../util/sortBy.js";
@@ -26,6 +27,7 @@ import {MAX_CONCURRENT_REQUESTS} from "./constants.js";
26
27
  import {SyncOptions} from "./options.js";
27
28
  import {
28
29
  BlockInputSyncCacheItem,
30
+ DeferredPayloadResult,
29
31
  DownloadResult,
30
32
  DroppedItemReason,
31
33
  FetchResult,
@@ -57,6 +59,11 @@ const MAX_PENDING_BLOCKS = 100;
57
59
  */
58
60
  const PRUNE_UNRESOLVED_SLOT_EPOCHS = 2;
59
61
 
62
+ /**
63
+ * Poll pending payloads of the current slot this often, between PAYLOAD_DUE and the end of the slot.
64
+ */
65
+ export const PAYLOAD_POLL_INTERVAL_MS = 1_000;
66
+
60
67
  type AdvancePendingBlockResult =
61
68
  | "ready"
62
69
  | "queued_block"
@@ -116,6 +123,11 @@ export class BlockInputSync {
116
123
  private subscribedToNetworkEvents = false;
117
124
  private peerBalancer: UnknownBlockPeerBalancer;
118
125
  private rateLimitBackoffTimeout: NodeJS.Timeout | undefined;
126
+ /**
127
+ * Search unknown payload starting at PAYLOAD_DUE_BPS.
128
+ */
129
+ private readonly deferredPayloadRoots = new Map<RootHex, {slot: Slot; source: BlockInputSource; peer?: PeerIdStr}>();
130
+ private payloadPollAbortController: AbortController | undefined;
119
131
 
120
132
  constructor(
121
133
  private readonly config: ChainForkConfig,
@@ -161,6 +173,7 @@ export class BlockInputSync {
161
173
  this.chain.emitter.on(routes.events.EventType.executionPayload, this.onPayloadImported);
162
174
  this.network.events.on(NetworkEvent.peerConnected, this.onPeerConnected);
163
175
  this.network.events.on(NetworkEvent.peerDisconnected, this.onPeerDisconnected);
176
+ this.chain.clock.on(ClockEvent.slot, this.startPayloadPollAtSlot);
164
177
 
165
178
  // Seed the balancer with peers that connected before we subscribed
166
179
  for (const peerId of this.network.getConnectedPeers()) {
@@ -172,12 +185,19 @@ export class BlockInputSync {
172
185
  }
173
186
 
174
187
  this.subscribedToNetworkEvents = true;
188
+ // we subscribe mid-slot, and a root can be deferred at any point in the slot, so start this
189
+ // slot's loop now instead of waiting for the next ClockEvent.slot
190
+ this.startPayloadPollAtSlot(this.chain.clock.currentSlot);
175
191
  }
176
192
  }
177
193
 
178
194
  unsubscribeFromNetwork(): void {
179
195
  this.logger.verbose("BlockInputSync disabled.");
180
196
  this.clearRateLimitBackoffTimer();
197
+ this.chain.clock.off(ClockEvent.slot, this.startPayloadPollAtSlot);
198
+ this.payloadPollAbortController?.abort();
199
+ this.payloadPollAbortController = undefined;
200
+ this.deferredPayloadRoots.clear();
181
201
  this.chain.emitter.off(ChainEvent.unknownBlockRoot, this.onUnknownBlockRoot);
182
202
  this.chain.emitter.off(ChainEvent.unknownEnvelopeBlockRoot, this.onUnknownEnvelopeBlockRoot);
183
203
  this.chain.emitter.off(ChainEvent.unknownEnvelopeBlockRootSlot, this.onUnknownEnvelopeBlockRootSlot);
@@ -207,8 +227,11 @@ export class BlockInputSync {
207
227
  private onUnknownBlockRoot = (data: ChainEventData[ChainEvent.unknownBlockRoot]): void => {
208
228
  try {
209
229
  const isNewRoot = this.addByRootHex(data.rootHex, data.peer);
210
- 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) {
211
232
  this.triggerUnknownBlockSearch();
233
+ }
234
+ if (isNewRoot) {
212
235
  this.metrics?.blockInputSync.requests.inc({type: PendingBlockType.UNKNOWN_BLOCK_ROOT});
213
236
  this.metrics?.blockInputSync.source.inc({source: data.source});
214
237
  }
@@ -246,6 +269,20 @@ export class BlockInputSync {
246
269
 
247
270
  private onUnknownEnvelopeBlockRootSlot = (data: ChainEventData[ChainEvent.unknownEnvelopeBlockRootSlot]): void => {
248
271
  try {
272
+ if (data.slot === this.chain.clock.currentSlot) {
273
+ // we receive the optimistic search, the poll loop searches it at PAYLOAD_DUE or on its next
274
+ // tick. If that loop already returned - every root it watched was imported - this root waits
275
+ // for the next slot, where startPayloadPollAtSlot moves it to pendingPayloads. That is not the normal
276
+ // scenario, and in a forking condition it only delays the search of the extra root
277
+ const deferred = this.deferredPayloadRoots.get(data.rootHex);
278
+ if (deferred === undefined) {
279
+ this.deferredPayloadRoots.set(data.rootHex, {slot: data.slot, source: data.source, peer: data.peer});
280
+ } else if (deferred.peer === undefined) {
281
+ deferred.peer = data.peer;
282
+ }
283
+ return;
284
+ }
285
+
249
286
  const isNewRoot = this.addByPayloadRootHex(data.rootHex, data.peer, data.slot);
250
287
  if (isNewRoot) {
251
288
  this.triggerUnknownBlockSearch();
@@ -359,12 +396,21 @@ export class BlockInputSync {
359
396
  }
360
397
  }
361
398
 
362
- let deletedBlocks = 0;
399
+ let belowFinalizedBlocks = 0;
400
+ let agedOutBlocks = 0;
363
401
  for (const [rootHex, block] of this.pendingBlocks) {
364
402
  const slot = getBlockInputSyncCacheItemSlot(block);
365
- 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) {
366
412
  this.pendingBlocks.delete(rootHex);
367
- deletedBlocks++;
413
+ belowFinalizedBlocks++;
368
414
  }
369
415
  }
370
416
 
@@ -377,16 +423,20 @@ export class BlockInputSync {
377
423
  if (agedOutPayloads > 0) {
378
424
  this.metrics?.blockInputSync.removedPayloads.inc({reason: DroppedItemReason.agedOut}, agedOutPayloads);
379
425
  }
380
- if (deletedBlocks > 0) {
381
- 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);
382
431
  }
383
432
 
384
- this.logger.debug("BlockInputSync.pruneFinalized dropped pre-finalized pending items", {
433
+ this.logger.debug("BlockInputSync.pruneFinalized dropped stale pending items", {
385
434
  finalizedSlot,
386
435
  finalizedRoot: checkpoint.rootHex,
387
436
  belowFinalizedPayloads,
388
437
  agedOutPayloads,
389
- deletedBlocks,
438
+ belowFinalizedBlocks,
439
+ agedOutBlocks,
390
440
  unresolvedSlotPayloads,
391
441
  });
392
442
  };
@@ -800,6 +850,122 @@ export class BlockInputSync {
800
850
  }
801
851
  }
802
852
 
853
+ /**
854
+ * Start this slot's payload poll: end the previous slot's loop, move roots it never got to
855
+ * into pendingPayloads, then poll from PAYLOAD_DUE to the end of the slot.
856
+ */
857
+ private startPayloadPollAtSlot = (slot: Slot): void => {
858
+ if (!isForkPostGloas(this.config.getForkName(slot))) {
859
+ return;
860
+ }
861
+ // end the previous slot's loop, wherever it is: its sleep is bound to this same controller
862
+ this.payloadPollAbortController?.abort();
863
+ this.payloadPollAbortController = new AbortController();
864
+ // entries from an earlier slot is not polled
865
+ for (const [rootHex, {slot: deferredSlot, source, peer}] of this.deferredPayloadRoots) {
866
+ if (deferredSlot < slot) {
867
+ if (!this.chain.forkChoice.hasPayloadHexUnsafe(rootHex)) {
868
+ this.addDeferredPayloadRoot(rootHex, deferredSlot, source, peer);
869
+ }
870
+ this.deferredPayloadRoots.delete(rootHex);
871
+ }
872
+ }
873
+ this.pollPayloadsAtSlot(slot, this.payloadPollAbortController.signal).catch((e) => {
874
+ if (!isErrorAborted(e)) {
875
+ this.logger.debug("Error polling payloads", {slot}, e as Error);
876
+ }
877
+ });
878
+ };
879
+
880
+ /**
881
+ * Poll unknown payloads of the current slot.
882
+ */
883
+ private async pollPayloadsAtSlot(slot: Slot, signal: AbortSignal): Promise<void> {
884
+ // fixed tick count so the loop cannot outlive its slot: for mainnet, it's 6 ticks
885
+ const tickCount = Math.floor(
886
+ (this.config.SLOT_DURATION_MS - this.config.getPayloadDueMs()) / PAYLOAD_POLL_INTERVAL_MS
887
+ );
888
+ // a root still missing on several ticks is searched on each of them, recorded once
889
+ const searchedRoots = new Set<RootHex>();
890
+ let polls = 0;
891
+
892
+ try {
893
+ await sleep(Math.max(0, this.config.getPayloadDueMs() - this.chain.clock.msFromSlot(slot)), signal);
894
+
895
+ for (polls = 0; polls < tickCount; polls++) {
896
+ let importedCount = 0;
897
+ for (const [rootHex, {slot: deferredSlot, source, peer}] of this.deferredPayloadRoots) {
898
+ if (this.chain.forkChoice.hasPayloadHexUnsafe(rootHex)) {
899
+ importedCount++;
900
+ continue;
901
+ }
902
+ // copy to the regular pendingPayloads so that we can search
903
+ this.addDeferredPayloadRoot(rootHex, deferredSlot, source, peer);
904
+ searchedRoots.add(rootHex);
905
+ }
906
+
907
+ // an empty deferredPayloadRoots means there is no optimistic search comes before PAYLOAD_DUE
908
+ // we have to poll until the payload of current slot is imported or slot end
909
+ if (this.deferredPayloadRoots.size > 0 && importedCount === this.deferredPayloadRoots.size) {
910
+ if (searchedRoots.size > 0) {
911
+ // the backup search was needed
912
+ this.metrics?.blockInputSync.deferredPayloadResult.inc({
913
+ result: DeferredPayloadResult.ImportedAfterSearch,
914
+ });
915
+ this.metrics?.blockInputSync.deferredPayloadPolls.observe(polls);
916
+ this.logger.verbose("Payload imported after unknown sync search", {
917
+ slot,
918
+ roots: Array.from(searchedRoots).join(","),
919
+ polls,
920
+ });
921
+ } else {
922
+ // this happens most of the time on devnet
923
+ // gossip delivered everything before PAYLOAD_DUE
924
+ this.metrics?.blockInputSync.deferredPayloadResult.inc({
925
+ result: DeferredPayloadResult.ImportedBeforeSearch,
926
+ });
927
+ }
928
+ return;
929
+ }
930
+
931
+ this.triggerUnknownBlockSearch();
932
+ if (polls < tickCount - 1) {
933
+ // no sleep after the last tick: the loop would otherwise end right at the slot boundary,
934
+ // where startPayloadPollAtSlot aborts it
935
+ await sleep(PAYLOAD_POLL_INTERVAL_MS, signal);
936
+ }
937
+ }
938
+
939
+ // reaching here means the early return never fired
940
+ if (this.deferredPayloadRoots.size > 0) {
941
+ this.metrics?.blockInputSync.deferredPayloadResult.inc({result: DeferredPayloadResult.Unresolved});
942
+ this.logger.debug("Deferred payloads still missing at end of slot", {
943
+ slot,
944
+ roots: Array.from(this.deferredPayloadRoots.keys()).join(","),
945
+ });
946
+ } else {
947
+ // no optimistic search and no payload import ended the loop, eg a skipped slot
948
+ this.metrics?.blockInputSync.deferredPayloadResult.inc({result: DeferredPayloadResult.ResolvedNoRoot});
949
+ this.logger.debug("No deferred payloads at slot", {
950
+ slot,
951
+ });
952
+ }
953
+ } catch (e) {
954
+ if (!isErrorAborted(e)) {
955
+ throw e;
956
+ }
957
+ this.logger.verbose("Payload poll aborted", {slot, polls, msIntoSlot: this.chain.clock.msFromSlot(slot)});
958
+ }
959
+ }
960
+
961
+ private addDeferredPayloadRoot(rootHex: RootHex, slot: Slot, source: BlockInputSource, peer?: PeerIdStr): void {
962
+ const isNewRoot = this.addByPayloadRootHex(rootHex, peer, slot);
963
+ if (isNewRoot) {
964
+ this.metrics?.blockInputSync.requests.inc({type: PendingBlockType.DEFERRED_PAYLOAD_BLOCK_ROOT});
965
+ this.metrics?.blockInputSync.payloadSource.inc({source});
966
+ }
967
+ }
968
+
803
969
  private async downloadBlock(block: BlockInputSyncCacheItem): Promise<void> {
804
970
  if (block.status !== PendingBlockInputStatus.pending) {
805
971
  return;
@@ -823,7 +989,12 @@ export class BlockInputSync {
823
989
  if (!res.err) {
824
990
  this.metrics?.blockInputSync.downloadedBlocksSuccess.inc();
825
991
  const pending = res.result;
826
- 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);
827
998
  const blockSlot = pending.blockInput.slot;
828
999
  const finalizedSlot = this.chain.forkChoice.getFinalizedBlock().slot;
829
1000
  const delaySec = Date.now() / 1000 - computeTimeAtSlot(this.config, blockSlot, this.chain.genesisTime);
@@ -885,8 +1056,11 @@ export class BlockInputSync {
885
1056
  }
886
1057
 
887
1058
  this.metrics?.blockInputSync.downloadedBlocksError.inc();
888
- this.logger.debug("Ignoring unknown block root after many failed downloads", logCtx, res.err);
889
- 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
+ }
890
1064
  }
891
1065
  }
892
1066
 
@@ -1153,7 +1327,7 @@ export class BlockInputSync {
1153
1327
  }
1154
1328
 
1155
1329
  this.metrics?.blockInputSync.downloadedPayloadsResult.inc({result: DownloadResult.Failed});
1156
- 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);
1157
1331
  if (!isPendingPayloadEnvelope(payload)) {
1158
1332
  payload.status = PendingPayloadInputStatus.pending;
1159
1333
  }
@@ -1613,7 +1787,11 @@ export class BlockInputSync {
1613
1787
  this.peerBalancer.onRequestCompleted(peerId);
1614
1788
  }
1615
1789
 
1616
- 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
+ }
1617
1795
 
1618
1796
  if (cacheItem.status === PendingBlockInputStatus.downloaded) {
1619
1797
  // download was successful, no need to go with another peer, return