@lodestar/beacon-node 1.52.0-dev.c90a21c764 → 1.52.0-dev.dad8e3af98

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 (175) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +46 -26
  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 +3 -1
  6. package/lib/api/impl/beacon/pool/index.js.map +1 -1
  7. package/lib/api/impl/beacon/state/utils.d.ts.map +1 -1
  8. package/lib/api/impl/beacon/state/utils.js +2 -1
  9. package/lib/api/impl/beacon/state/utils.js.map +1 -1
  10. package/lib/api/impl/debug/index.d.ts.map +1 -1
  11. package/lib/api/impl/debug/index.js +6 -2
  12. package/lib/api/impl/debug/index.js.map +1 -1
  13. package/lib/api/impl/validator/index.d.ts.map +1 -1
  14. package/lib/api/impl/validator/index.js +13 -4
  15. package/lib/api/impl/validator/index.js.map +1 -1
  16. package/lib/chain/ColumnReconstructionTracker.d.ts +4 -0
  17. package/lib/chain/ColumnReconstructionTracker.d.ts.map +1 -1
  18. package/lib/chain/ColumnReconstructionTracker.js +4 -0
  19. package/lib/chain/ColumnReconstructionTracker.js.map +1 -1
  20. package/lib/chain/blocks/importExecutionPayload.d.ts +1 -1
  21. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  22. package/lib/chain/blocks/importExecutionPayload.js +9 -3
  23. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  24. package/lib/chain/blocks/index.d.ts.map +1 -1
  25. package/lib/chain/blocks/index.js +3 -17
  26. package/lib/chain/blocks/index.js.map +1 -1
  27. package/lib/chain/chain.d.ts +6 -5
  28. package/lib/chain/chain.d.ts.map +1 -1
  29. package/lib/chain/chain.js +62 -20
  30. package/lib/chain/chain.js.map +1 -1
  31. package/lib/chain/errors/attestationError.d.ts +15 -1
  32. package/lib/chain/errors/attestationError.d.ts.map +1 -1
  33. package/lib/chain/errors/attestationError.js +8 -0
  34. package/lib/chain/errors/attestationError.js.map +1 -1
  35. package/lib/chain/errors/executionPayloadBid.d.ts +3 -2
  36. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  37. package/lib/chain/errors/executionPayloadBid.js +1 -1
  38. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  39. package/lib/chain/errors/executionPayloadEnvelope.d.ts +48 -0
  40. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  41. package/lib/chain/errors/executionPayloadEnvelope.js +7 -0
  42. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  43. package/lib/chain/interface.d.ts +1 -1
  44. package/lib/chain/interface.d.ts.map +1 -1
  45. package/lib/chain/opPools/opPool.js +6 -6
  46. package/lib/chain/opPools/opPool.js.map +1 -1
  47. package/lib/chain/seenCache/seenAttesters.d.ts +1 -0
  48. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  49. package/lib/chain/seenCache/seenAttesters.js +1 -1
  50. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  51. package/lib/chain/seenCache/seenBlockAttesters.d.ts +8 -2
  52. package/lib/chain/seenCache/seenBlockAttesters.d.ts.map +1 -1
  53. package/lib/chain/seenCache/seenBlockAttesters.js +43 -6
  54. package/lib/chain/seenCache/seenBlockAttesters.js.map +1 -1
  55. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts +13 -4
  56. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts.map +1 -1
  57. package/lib/chain/seenCache/seenExecutionPayloadBids.js +13 -12
  58. package/lib/chain/seenCache/seenExecutionPayloadBids.js.map +1 -1
  59. package/lib/chain/validation/aggregateAndProof.d.ts.map +1 -1
  60. package/lib/chain/validation/aggregateAndProof.js +24 -7
  61. package/lib/chain/validation/aggregateAndProof.js.map +1 -1
  62. package/lib/chain/validation/attestation.d.ts.map +1 -1
  63. package/lib/chain/validation/attestation.js +32 -16
  64. package/lib/chain/validation/attestation.js.map +1 -1
  65. package/lib/chain/validation/block.d.ts.map +1 -1
  66. package/lib/chain/validation/block.js +9 -1
  67. package/lib/chain/validation/block.js.map +1 -1
  68. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  69. package/lib/chain/validation/executionPayloadBid.js +30 -40
  70. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  71. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  72. package/lib/chain/validation/executionPayloadEnvelope.js +79 -4
  73. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  74. package/lib/chain/validation/payloadAttestationMessage.js +9 -0
  75. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  76. package/lib/chain/validatorMonitor.js +43 -43
  77. package/lib/chain/validatorMonitor.js.map +1 -1
  78. package/lib/network/gossip/gossipsub.js +2 -2
  79. package/lib/network/gossip/gossipsub.js.map +1 -1
  80. package/lib/network/gossip/topic.d.ts +1 -7
  81. package/lib/network/gossip/topic.d.ts.map +1 -1
  82. package/lib/network/gossip/topic.js +0 -13
  83. package/lib/network/gossip/topic.js.map +1 -1
  84. package/lib/network/network.d.ts +1 -0
  85. package/lib/network/network.d.ts.map +1 -1
  86. package/lib/network/network.js +20 -11
  87. package/lib/network/network.js.map +1 -1
  88. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  89. package/lib/network/processor/gossipHandlers.js +19 -6
  90. package/lib/network/processor/gossipHandlers.js.map +1 -1
  91. package/lib/network/processor/gossipValidatorFn.d.ts.map +1 -1
  92. package/lib/network/processor/gossipValidatorFn.js +4 -1
  93. package/lib/network/processor/gossipValidatorFn.js.map +1 -1
  94. package/lib/network/processor/index.d.ts.map +1 -1
  95. package/lib/network/processor/index.js +4 -2
  96. package/lib/network/processor/index.js.map +1 -1
  97. package/lib/network/reqresp/utils/collect.d.ts +4 -4
  98. package/lib/network/reqresp/utils/collect.d.ts.map +1 -1
  99. package/lib/network/reqresp/utils/collect.js +9 -8
  100. package/lib/network/reqresp/utils/collect.js.map +1 -1
  101. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts +1 -1
  102. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts.map +1 -1
  103. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js +2 -2
  104. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js.map +1 -1
  105. package/lib/sync/range/batch.d.ts +6 -0
  106. package/lib/sync/range/batch.d.ts.map +1 -1
  107. package/lib/sync/range/batch.js +17 -0
  108. package/lib/sync/range/batch.js.map +1 -1
  109. package/lib/sync/range/chain.d.ts.map +1 -1
  110. package/lib/sync/range/chain.js +8 -1
  111. package/lib/sync/range/chain.js.map +1 -1
  112. package/lib/sync/range/range.d.ts.map +1 -1
  113. package/lib/sync/range/range.js +43 -3
  114. package/lib/sync/range/range.js.map +1 -1
  115. package/lib/sync/types.d.ts +12 -1
  116. package/lib/sync/types.d.ts.map +1 -1
  117. package/lib/sync/types.js +2 -0
  118. package/lib/sync/types.js.map +1 -1
  119. package/lib/sync/unknownBlock.d.ts +28 -1
  120. package/lib/sync/unknownBlock.d.ts.map +1 -1
  121. package/lib/sync/unknownBlock.js +234 -22
  122. package/lib/sync/unknownBlock.js.map +1 -1
  123. package/lib/sync/utils/downloadByRange.d.ts +14 -1
  124. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  125. package/lib/sync/utils/downloadByRange.js +12 -2
  126. package/lib/sync/utils/downloadByRange.js.map +1 -1
  127. package/lib/sync/utils/downloadByRoot.d.ts +24 -2
  128. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  129. package/lib/sync/utils/downloadByRoot.js +43 -1
  130. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  131. package/lib/util/eventLoop.d.ts +3 -3
  132. package/lib/util/eventLoop.d.ts.map +1 -1
  133. package/lib/util/eventLoop.js +3 -3
  134. package/lib/util/eventLoop.js.map +1 -1
  135. package/package.json +17 -17
  136. package/src/api/impl/beacon/blocks/index.ts +52 -28
  137. package/src/api/impl/beacon/pool/index.ts +9 -7
  138. package/src/api/impl/beacon/state/utils.ts +2 -1
  139. package/src/api/impl/debug/index.ts +6 -2
  140. package/src/api/impl/validator/index.ts +15 -5
  141. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  142. package/src/chain/blocks/importExecutionPayload.ts +9 -2
  143. package/src/chain/blocks/index.ts +3 -31
  144. package/src/chain/chain.ts +95 -37
  145. package/src/chain/errors/attestationError.ts +11 -1
  146. package/src/chain/errors/executionPayloadBid.ts +3 -2
  147. package/src/chain/errors/executionPayloadEnvelope.ts +50 -0
  148. package/src/chain/interface.ts +1 -1
  149. package/src/chain/opPools/opPool.ts +6 -6
  150. package/src/chain/seenCache/seenAttesters.ts +1 -1
  151. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  152. package/src/chain/seenCache/seenExecutionPayloadBids.ts +35 -15
  153. package/src/chain/validation/aggregateAndProof.ts +24 -9
  154. package/src/chain/validation/attestation.ts +31 -20
  155. package/src/chain/validation/block.ts +9 -1
  156. package/src/chain/validation/executionPayloadBid.ts +40 -42
  157. package/src/chain/validation/executionPayloadEnvelope.ts +87 -3
  158. package/src/chain/validation/payloadAttestationMessage.ts +10 -0
  159. package/src/chain/validatorMonitor.ts +43 -43
  160. package/src/network/gossip/gossipsub.ts +2 -2
  161. package/src/network/gossip/topic.ts +1 -14
  162. package/src/network/network.ts +33 -11
  163. package/src/network/processor/gossipHandlers.ts +25 -13
  164. package/src/network/processor/gossipValidatorFn.ts +4 -0
  165. package/src/network/processor/index.ts +7 -2
  166. package/src/network/reqresp/utils/collect.ts +16 -8
  167. package/src/network/reqresp/utils/collectSequentialBlocksInRange.ts +3 -2
  168. package/src/sync/range/batch.ts +20 -0
  169. package/src/sync/range/chain.ts +8 -0
  170. package/src/sync/range/range.ts +56 -3
  171. package/src/sync/types.ts +11 -0
  172. package/src/sync/unknownBlock.ts +272 -22
  173. package/src/sync/utils/downloadByRange.ts +29 -3
  174. package/src/sync/utils/downloadByRoot.ts +68 -2
  175. package/src/util/eventLoop.ts +3 -3
@@ -59,6 +59,8 @@ export declare class BlockInputSync {
59
59
  private subscribedToNetworkEvents;
60
60
  private peerBalancer;
61
61
  private rateLimitBackoffTimeout;
62
+ private downloadRetryTimeout;
63
+ private downloadRetryAtMs;
62
64
  /**
63
65
  * Search unknown payload starting at PAYLOAD_DUE_BPS.
64
66
  */
@@ -93,6 +95,14 @@ export declare class BlockInputSync {
93
95
  private pruneFinalized;
94
96
  private addByRootHex;
95
97
  private addByBlockInput;
98
+ /**
99
+ * Limit pending blocks to prevent DOS attacks that cause OOM. Any gossip message with an unknown root adds a root-only
100
+ * entry before validation, so those nothing waits on are evicted before a block or a root a pending block waits on.
101
+ * A downloaded block is only checked against its root and proposer signature, not that the proposer is due at its
102
+ * slot, so this only applies while blocks and the roots they wait on fill at most half the cap, otherwise they could
103
+ * pin it and evict every new root on insertion.
104
+ */
105
+ private prunePendingBlocks;
96
106
  private addByPayloadRootHex;
97
107
  /**
98
108
  * Resolve the block slot for a payload root.
@@ -101,6 +111,20 @@ export declare class BlockInputSync {
101
111
  private addByPayloadInput;
102
112
  private onPeerConnected;
103
113
  private onPeerDisconnected;
114
+ /**
115
+ * A peer can make us retain a signed block per validator key and slot until its parent resolves. Bound the bytes
116
+ * retained per peer, its oldest blocks still waiting on their parent are removed first.
117
+ */
118
+ private limitRetainedBlocks;
119
+ /**
120
+ * Blocks are otherwise only pruned once finalization passes them, which never happens for a parent that does not resolve
121
+ */
122
+ private pruneUnresolvedBlocks;
123
+ private isWaitingOnParent;
124
+ /**
125
+ * Removes only the block itself, its descendants request it again by root and its claimed ancestors stay cached
126
+ */
127
+ private removeUnresolvedBlock;
104
128
  /**
105
129
  * Post-gloas, a locally complete block can still be blocked on its parent's execution payload lineage.
106
130
  * Distinguish which dependency is missing so the scheduler can enqueue the right follow-up work.
@@ -117,6 +141,8 @@ export declare class BlockInputSync {
117
141
  */
118
142
  private scheduleRateLimitBackoffRetry;
119
143
  private clearRateLimitBackoffTimer;
144
+ private scheduleDownloadRetry;
145
+ private clearDownloadRetryTimer;
120
146
  /**
121
147
  * Start this slot's payload poll: end the previous slot's loop, move roots it never got to
122
148
  * into pendingPayloads, then poll from PAYLOAD_DUE to the end of the slot.
@@ -181,6 +207,7 @@ export declare class UnknownBlockPeerBalancer {
181
207
  readonly peersMeta: Map<PeerIdStr, PeerSyncMeta>;
182
208
  readonly activeRequests: Map<PeerIdStr, number>;
183
209
  readonly rateLimitedUntilByPeer: Map<PeerIdStr, number>;
210
+ readonly requestTimesByPeer: Map<PeerIdStr, number[]>;
184
211
  constructor();
185
212
  /** Trigger on each peer re-status */
186
213
  onPeerConnected(peerId: PeerIdStr, syncMeta: PeerSyncMeta): void;
@@ -201,7 +228,7 @@ export declare class UnknownBlockPeerBalancer {
201
228
  * Consumers don't need to call this method directly, it is called internally by bestPeer*() methods
202
229
  * make this public for testing
203
230
  */
204
- onRequest(peerId: PeerIdStr): void;
231
+ onRequest(peerId: PeerIdStr, now?: number): void;
205
232
  /**
206
233
  * Consumers should call this method when a request is completed for a peer.
207
234
  */
@@ -1 +1 @@
1
- {"version":3,"file":"unknownBlock.d.ts","sourceRoot":"","sources":["../../src/sync/unknownBlock.ts"],"names":[],"mappings":"AACA,OAAO,EAAC,eAAe,EAAC,MAAM,kBAAkB,CAAC;AAMjD,OAAO,EAAC,MAAM,EAA+E,MAAM,iBAAiB,CAAC;AAMrH,OAAO,EAA6B,YAAY,EAAC,MAAM,mBAAmB,CAAC;AAG3E,OAAO,EAAC,OAAO,EAAC,MAAM,qBAAqB,CAAC;AAC5C,OAAO,EAAC,QAAQ,EAAmE,MAAM,qBAAqB,CAAC;AAC/G,OAAO,EAAC,YAAY,EAAC,MAAM,+BAA+B,CAAC;AAG3D,OAAO,EAAC,SAAS,EAAC,MAAM,mBAAmB,CAAC;AAK5C,OAAO,EAAC,WAAW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CAAC,EAAE,GAAG,CAAC,SAAS,CAAC,EAC9B,GAAG,SAAa,GACf,MAAM,GAAG,IAAI,CA2Bf;IAED;;;;;;OAMG;IACH,yBAAyB,CACvB,cAAc,EAAE,GAAG,CAAC,MAAM,CAAC,EAC3B,aAAa,EAAE,GAAG,CAAC,SAAS,CAAC,EAC7B,cAAc,CAAC,EAAE,GAAG,CAAC,SAAS,CAAC,EAC/B,GAAG,SAAa,GACf,YAAY,GAAG,IAAI,CAiBrB;IAED;;;OAGG;IACH,SAAS,CAAC,MAAM,EAAE,SAAS,EAAE,GAAG,SAAa,GAAG,IAAI,CAYnD;IAED;;OAEG;IACH,kBAAkB,CAAC,MAAM,EAAE,SAAS,GAAG,IAAI,CAE1C;IAED,sBAAsB,IAAI,MAAM,CAM/B;IAED,OAAO,CAAC,WAAW;IA6DnB,OAAO,CAAC,qBAAqB;CAO9B"}
@@ -7,7 +7,7 @@ import { isBlockInputColumns } from "../chain/blocks/blockInput/blockInput.js";
7
7
  import { BlockInputSource } from "../chain/blocks/blockInput/types.js";
8
8
  import { PayloadError, PayloadErrorCode } from "../chain/blocks/importExecutionPayload.js";
9
9
  import { PayloadEnvelopeInputSource } from "../chain/blocks/payloadEnvelopeInput/index.js";
10
- import { BlockError, BlockErrorCode } from "../chain/errors/index.js";
10
+ import { BlockError, BlockErrorCode, ExecutionPayloadEnvelopeError, ExecutionPayloadEnvelopeErrorCode, } from "../chain/errors/index.js";
11
11
  import { ChainEvent } from "../chain/index.js";
12
12
  import { validateGloasBlockDataColumnSidecars } from "../chain/validation/dataColumnSidecar.js";
13
13
  import { validateGossipExecutionPayloadEnvelope } from "../chain/validation/executionPayloadEnvelope.js";
@@ -19,12 +19,21 @@ import { sortBy } from "../util/sortBy.js";
19
19
  import { wrapError } from "../util/wrapError.js";
20
20
  import { MAX_CONCURRENT_REQUESTS } from "./constants.js";
21
21
  import { DeferredPayloadResult, DownloadResult, DroppedItemReason, FetchResult, PendingBlockInputStatus, PendingBlockType, PendingPayloadInputStatus, getBlockInputSyncCacheItemRootHex, getBlockInputSyncCacheItemSlot, getPayloadSyncCacheItemRootHex, getPayloadSyncCacheItemSlot, isPendingBlockInput, isPendingPayloadEnvelope, isPendingPayloadInput, } from "./types.js";
22
- import { DownloadByRootError, downloadByRoot } from "./utils/downloadByRoot.js";
22
+ import { DownloadByRootError, DownloadByRootErrorCode, downloadByRoot } from "./utils/downloadByRoot.js";
23
23
  import { getAllDescendantBlocks, getUnknownAndAncestorBlocks } from "./utils/pendingBlocksTree.js";
24
24
  import { getRateLimitedUntilMs } from "./utils/rateLimit.js";
25
25
  const MAX_ATTEMPTS_PER_BLOCK = 5;
26
26
  const MAX_KNOWN_BAD_BLOCKS = 500;
27
27
  const MAX_PENDING_BLOCKS = 100;
28
+ /**
29
+ * A failed download is retried after this delay, doubling per failure up to one slot.
30
+ */
31
+ const DOWNLOAD_RETRY_BASE_MS = 1_000;
32
+ /**
33
+ * Requests per peer per window, half the BeaconBlocksByRoot quota peers enforce, they disconnect a peer that exceeds it.
34
+ */
35
+ const MAX_REQUESTS_PER_PEER = 64;
36
+ const REQUESTS_PER_PEER_WINDOW_MS = 10_000;
28
37
  /**
29
38
  * A pending payload without slot can only stay at most 2 epochs.
30
39
  */
@@ -93,6 +102,8 @@ export class BlockInputSync {
93
102
  subscribedToNetworkEvents = false;
94
103
  peerBalancer;
95
104
  rateLimitBackoffTimeout;
105
+ downloadRetryTimeout;
106
+ downloadRetryAtMs;
96
107
  /**
97
108
  * Search unknown payload starting at PAYLOAD_DUE_BPS.
98
109
  */
@@ -133,6 +144,7 @@ export class BlockInputSync {
133
144
  this.network.events.on(NetworkEvent.peerConnected, this.onPeerConnected);
134
145
  this.network.events.on(NetworkEvent.peerDisconnected, this.onPeerDisconnected);
135
146
  this.chain.clock.on(ClockEvent.slot, this.startPayloadPollAtSlot);
147
+ this.chain.clock.on(ClockEvent.slot, this.pruneUnresolvedBlocks);
136
148
  // Seed the balancer with peers that connected before we subscribed
137
149
  for (const peerId of this.network.getConnectedPeers()) {
138
150
  try {
@@ -151,7 +163,9 @@ export class BlockInputSync {
151
163
  unsubscribeFromNetwork() {
152
164
  this.logger.verbose("BlockInputSync disabled.");
153
165
  this.clearRateLimitBackoffTimer();
166
+ this.clearDownloadRetryTimer();
154
167
  this.chain.clock.off(ClockEvent.slot, this.startPayloadPollAtSlot);
168
+ this.chain.clock.off(ClockEvent.slot, this.pruneUnresolvedBlocks);
155
169
  this.payloadPollAbortController?.abort();
156
170
  this.payloadPollAbortController = undefined;
157
171
  this.deferredPayloadRoots.clear();
@@ -293,6 +307,9 @@ export class BlockInputSync {
293
307
  this.addByRootHex(missingDependency.rootHex, data.peer);
294
308
  }
295
309
  this.addByBlockInput(data.blockInput, data.peer);
310
+ if (data.source === BlockInputSource.gossip) {
311
+ this.limitRetainedBlocks(data.blockInput, data.peer);
312
+ }
296
313
  this.triggerUnknownBlockSearch();
297
314
  this.metrics?.blockInputSync.requests.inc({ type: PendingBlockType.UNKNOWN_PARENT });
298
315
  this.metrics?.blockInputSync.source.inc({ source: data.source });
@@ -319,7 +336,8 @@ export class BlockInputSync {
319
336
  // because the payload at the finalized block is not finalized
320
337
  const finalizedSlot = this.chain.forkChoice.getFinalizedBlock().slot;
321
338
  const nowSec = Date.now() / 1000;
322
- const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * this.config.SLOT_DURATION_MS) / 1000;
339
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
340
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
323
341
  let belowFinalizedPayloads = 0;
324
342
  let agedOutPayloads = 0;
325
343
  let unresolvedSlotPayloads = 0;
@@ -414,13 +432,7 @@ export class BlockInputSync {
414
432
  if (peerIdStr && pendingBlock.peerIdStrings.size < MAX_PEERS_PER_ROOT) {
415
433
  pendingBlock.peerIdStrings.add(peerIdStr);
416
434
  }
417
- // TODO: check this prune methodology
418
- // Limit pending blocks to prevent DOS attacks that cause OOM
419
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
420
- if (prunedItemCount > 0) {
421
- this.metrics?.blockInputSync.removedBlocks.inc({ reason: DroppedItemReason.capacity }, prunedItemCount);
422
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
423
- }
435
+ this.prunePendingBlocks();
424
436
  return added;
425
437
  };
426
438
  addByBlockInput = (blockInput, peerIdStr) => {
@@ -451,14 +463,60 @@ export class BlockInputSync {
451
463
  if (peerIdStr && pendingBlock.peerIdStrings.size < MAX_PEERS_PER_ROOT) {
452
464
  pendingBlock.peerIdStrings.add(peerIdStr);
453
465
  }
454
- // TODO: check this prune methodology
455
- // Limit pending blocks to prevent DOS attacks that cause OOM
456
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
457
- if (prunedItemCount > 0) {
458
- this.metrics?.blockInputSync.removedBlocks.inc({ reason: DroppedItemReason.capacity }, prunedItemCount);
459
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
460
- }
466
+ this.prunePendingBlocks();
461
467
  };
468
+ /**
469
+ * Limit pending blocks to prevent DOS attacks that cause OOM. Any gossip message with an unknown root adds a root-only
470
+ * entry before validation, so those nothing waits on are evicted before a block or a root a pending block waits on.
471
+ * A downloaded block is only checked against its root and proposer signature, not that the proposer is due at its
472
+ * slot, so this only applies while blocks and the roots they wait on fill at most half the cap, otherwise they could
473
+ * pin it and evict every new root on insertion.
474
+ */
475
+ prunePendingBlocks() {
476
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
477
+ return;
478
+ }
479
+ const awaitedRoots = new Set();
480
+ for (const pendingBlock of this.pendingBlocks.values()) {
481
+ if (isPendingBlockInput(pendingBlock)) {
482
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
483
+ }
484
+ }
485
+ const isKept = (rootHex, pendingBlock) => isPendingBlockInput(pendingBlock) || awaitedRoots.has(rootHex);
486
+ let keptCount = 0;
487
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
488
+ if (isKept(rootHex, pendingBlock)) {
489
+ keptCount++;
490
+ }
491
+ }
492
+ let prunedItemCount = 0;
493
+ if (keptCount <= this.maxPendingBlocks / 2) {
494
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
495
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
496
+ break;
497
+ }
498
+ if (!isKept(rootHex, pendingBlock)) {
499
+ this.pendingBlocks.delete(rootHex);
500
+ prunedItemCount++;
501
+ }
502
+ }
503
+ }
504
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
505
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
506
+ break;
507
+ }
508
+ this.pendingBlocks.delete(rootHex);
509
+ prunedItemCount++;
510
+ // The block input cache is only trimmed on import, a block whose parent never resolves would stay there
511
+ if (isPendingBlockInput(pendingBlock) &&
512
+ pendingBlock.status !== PendingBlockInputStatus.processing &&
513
+ this.getMissingBlockDependency(pendingBlock.blockInput).kind === "parentBlock") {
514
+ this.chain.seenBlockInputCache.remove(rootHex);
515
+ }
516
+ }
517
+ this.metrics?.blockInputSync.removedBlocks.inc({ reason: DroppedItemReason.capacity }, prunedItemCount);
518
+ this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
519
+ }
462
520
  addByPayloadRootHex = (rootHex, peerIdStr, slot) => {
463
521
  if (this.knownBadBlocks.has(rootHex)) {
464
522
  this.logger.debug("Ignoring payload for known bad block root", {
@@ -574,6 +632,72 @@ export class BlockInputSync {
574
632
  this.peerBalancer.onPeerDisconnected(peerId);
575
633
  this.scheduleRateLimitBackoffRetry();
576
634
  };
635
+ /**
636
+ * A peer can make us retain a signed block per validator key and slot until its parent resolves. Bound the bytes
637
+ * retained per peer, its oldest blocks still waiting on their parent are removed first.
638
+ */
639
+ limitRetainedBlocks(blockInput, peerIdStr) {
640
+ const pendingBlock = this.pendingBlocks.get(blockInput.blockRootHex);
641
+ if (pendingBlock === undefined || !isPendingBlockInput(pendingBlock) || pendingBlock.retainedBy !== undefined) {
642
+ return;
643
+ }
644
+ pendingBlock.retainedBy = peerIdStr;
645
+ pendingBlock.retainedBytes = this.config
646
+ .getForkTypes(blockInput.slot)
647
+ .SignedBeaconBlock.value_serializedSize(blockInput.getBlock());
648
+ const retainedBlocks = [];
649
+ let retainedBytes = 0;
650
+ for (const item of this.pendingBlocks.values()) {
651
+ if (isPendingBlockInput(item) && item.retainedBy === peerIdStr && this.isWaitingOnParent(item)) {
652
+ retainedBlocks.push(item);
653
+ retainedBytes += item.retainedBytes ?? 0;
654
+ }
655
+ }
656
+ // One block of the max gossip size fits, honest blocks are far smaller
657
+ for (const item of retainedBlocks) {
658
+ if (retainedBytes <= this.config.MAX_PAYLOAD_SIZE) {
659
+ break;
660
+ }
661
+ retainedBytes -= item.retainedBytes ?? 0;
662
+ this.removeUnresolvedBlock(item, DroppedItemReason.peerBudget);
663
+ }
664
+ }
665
+ /**
666
+ * Blocks are otherwise only pruned once finalization passes them, which never happens for a parent that does not resolve
667
+ */
668
+ pruneUnresolvedBlocks = () => {
669
+ const nowSec = Date.now() / 1000;
670
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
671
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
672
+ for (const pendingBlock of this.pendingBlocks.values()) {
673
+ if (isPendingBlockInput(pendingBlock) &&
674
+ nowSec - pendingBlock.timeAddedSec > maxSecInCache &&
675
+ this.isWaitingOnParent(pendingBlock)) {
676
+ this.removeUnresolvedBlock(pendingBlock, DroppedItemReason.agedOut);
677
+ }
678
+ }
679
+ };
680
+ isWaitingOnParent(pendingBlock) {
681
+ if (pendingBlock.status === PendingBlockInputStatus.processing) {
682
+ return false;
683
+ }
684
+ const { kind } = this.getMissingBlockDependency(pendingBlock.blockInput);
685
+ return kind === "parentBlock" || kind === "parentPayload";
686
+ }
687
+ /**
688
+ * Removes only the block itself, its descendants request it again by root and its claimed ancestors stay cached
689
+ */
690
+ removeUnresolvedBlock(pendingBlock, reason) {
691
+ const rootHex = pendingBlock.blockInput.blockRootHex;
692
+ this.pendingBlocks.delete(rootHex);
693
+ this.chain.seenBlockInputCache.remove(rootHex);
694
+ this.metrics?.blockInputSync.removedBlocks.inc({ reason });
695
+ this.logger.debug("Removed unresolved BlockInputSync block", {
696
+ slot: pendingBlock.blockInput.slot,
697
+ root: rootHex,
698
+ reason,
699
+ });
700
+ }
577
701
  /**
578
702
  * Post-gloas, a locally complete block can still be blocked on its parent's execution payload lineage.
579
703
  * Distinguish which dependency is missing so the scheduler can enqueue the right follow-up work.
@@ -692,8 +816,17 @@ export class BlockInputSync {
692
816
  this.logger.debug("No connected peers, skipping unknown block download.");
693
817
  }
694
818
  else {
819
+ // Blocks and roots a pending block waits on are downloaded first, any gossip message with an unknown root adds
820
+ // another root, and they all share the per-peer request budget
821
+ const awaitedRoots = new Set();
822
+ for (const pendingBlock of this.pendingBlocks.values()) {
823
+ if (isPendingBlockInput(pendingBlock)) {
824
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
825
+ }
826
+ }
827
+ const isAwaited = (block) => isPendingBlockInput(block) || awaitedRoots.has(block.rootHex);
695
828
  // Most of the time there is exactly 1 unknown block
696
- for (const block of unknowns) {
829
+ for (const block of [...unknowns.filter(isAwaited), ...unknowns.filter((block) => !isAwaited(block))]) {
697
830
  this.downloadBlock(block).catch((e) => {
698
831
  this.logger.debug("Unexpected error - downloadBlock", { root: getBlockInputSyncCacheItemRootHex(block) }, e);
699
832
  });
@@ -763,6 +896,25 @@ export class BlockInputSync {
763
896
  this.rateLimitBackoffTimeout = undefined;
764
897
  }
765
898
  }
899
+ scheduleDownloadRetry(retryAtMs) {
900
+ if (this.downloadRetryAtMs !== undefined && this.downloadRetryAtMs <= retryAtMs) {
901
+ return;
902
+ }
903
+ this.clearDownloadRetryTimer();
904
+ this.downloadRetryAtMs = retryAtMs;
905
+ this.downloadRetryTimeout = setTimeout(() => {
906
+ this.downloadRetryTimeout = undefined;
907
+ this.downloadRetryAtMs = undefined;
908
+ this.triggerUnknownBlockSearch();
909
+ }, Math.max(0, retryAtMs - Date.now()));
910
+ }
911
+ clearDownloadRetryTimer() {
912
+ if (this.downloadRetryTimeout !== undefined) {
913
+ clearTimeout(this.downloadRetryTimeout);
914
+ this.downloadRetryTimeout = undefined;
915
+ }
916
+ this.downloadRetryAtMs = undefined;
917
+ }
766
918
  /**
767
919
  * Start this slot's payload poll: end the previous slot's loop, move roots it never got to
768
920
  * into pendingPayloads, then poll from PAYLOAD_DUE to the end of the slot.
@@ -877,6 +1029,10 @@ export class BlockInputSync {
877
1029
  if (block.status !== PendingBlockInputStatus.pending) {
878
1030
  return;
879
1031
  }
1032
+ if (block.retryAtMs !== undefined && block.retryAtMs > Date.now()) {
1033
+ this.scheduleDownloadRetry(block.retryAtMs);
1034
+ return;
1035
+ }
880
1036
  const rootHex = getBlockInputSyncCacheItemRootHex(block);
881
1037
  const blockSlot = getBlockInputSyncCacheItemSlot(block);
882
1038
  const logCtx = {
@@ -951,6 +1107,7 @@ export class BlockInputSync {
951
1107
  const pendingBlock = this.pendingBlocks.get(rootHex);
952
1108
  if (pendingBlock) {
953
1109
  pendingBlock.status = PendingBlockInputStatus.pending;
1110
+ pendingBlock.retryAtMs = res.err.retryAt;
954
1111
  }
955
1112
  this.logger.debug("Deferring unknown block download due to peer rate limit", logCtx, res.err);
956
1113
  if (!this.scheduleRateLimitBackoffRetry() || res.err.retryAt <= Date.now()) {
@@ -960,11 +1117,26 @@ export class BlockInputSync {
960
1117
  }
961
1118
  return;
962
1119
  }
1120
+ if (res.err instanceof DownloadByRootError &&
1121
+ res.err.type.code === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT) {
1122
+ this.logger.debug("Downloaded block is before finalized slot", logCtx, res.err);
1123
+ this.removeAllDescendants(block, DroppedItemReason.belowFinalized);
1124
+ return;
1125
+ }
963
1126
  this.metrics?.blockInputSync.downloadedBlocksError.inc();
964
1127
  this.logger.debug("Failed to download unknown block root, retained for retry", logCtx, res.err);
965
1128
  const pendingBlock = this.pendingBlocks.get(rootHex);
966
- if (pendingBlock && pendingBlock.status === PendingBlockInputStatus.fetching) {
1129
+ // A partial download replaces the entry with a pending one that does not carry the failure count
1130
+ if (pendingBlock &&
1131
+ (pendingBlock.status === PendingBlockInputStatus.fetching ||
1132
+ pendingBlock.status === PendingBlockInputStatus.pending)) {
967
1133
  pendingBlock.status = PendingBlockInputStatus.pending;
1134
+ // Not retried on every search, any gossip message with an unknown root triggers one
1135
+ pendingBlock.failedDownloads = (block.failedDownloads ?? 0) + 1;
1136
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
1137
+ pendingBlock.retryAtMs =
1138
+ Date.now() + Math.min(DOWNLOAD_RETRY_BASE_MS * 2 ** (pendingBlock.failedDownloads - 1), slotDurationMs);
1139
+ this.scheduleDownloadRetry(pendingBlock.retryAtMs);
968
1140
  }
969
1141
  }
970
1142
  }
@@ -1127,7 +1299,7 @@ export class BlockInputSync {
1127
1299
  const pendingPayloadByRoot = {
1128
1300
  status: PendingPayloadInputStatus.pending,
1129
1301
  rootHex,
1130
- slot: pendingPayload.envelope.message.payload.slotNumber,
1302
+ slot: payloadInput.slot,
1131
1303
  timeAddedSec: pendingPayload.timeAddedSec,
1132
1304
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1133
1305
  };
@@ -1429,6 +1601,26 @@ export class BlockInputSync {
1429
1601
  else {
1430
1602
  excludedPeers.add(peerId);
1431
1603
  }
1604
+ if (e instanceof ExecutionPayloadEnvelopeError) {
1605
+ switch (e.type.code) {
1606
+ // Caused by local state, the downloaded envelope may still be valid
1607
+ case ExecutionPayloadEnvelopeErrorCode.BLOCK_ROOT_UNKNOWN:
1608
+ case ExecutionPayloadEnvelopeErrorCode.ENVELOPE_ALREADY_KNOWN:
1609
+ case ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING:
1610
+ case ExecutionPayloadEnvelopeErrorCode.UNKNOWN_BLOCK_STATE:
1611
+ break;
1612
+ // Every copy fails once the block is finalized, only a wrong slot makes the served copy invalid
1613
+ case ExecutionPayloadEnvelopeErrorCode.BELONG_TO_FINALIZED_BLOCK:
1614
+ if (envelope?.message.payload.slotNumber !== payloadInput?.slot) {
1615
+ envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1616
+ }
1617
+ break;
1618
+ // The served copy is invalid, take the envelope from payloadInput or another peer on the next attempt
1619
+ default:
1620
+ envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1621
+ break;
1622
+ }
1623
+ }
1432
1624
  }
1433
1625
  finally {
1434
1626
  this.peerBalancer.onRequestCompleted(peerId);
@@ -1552,6 +1744,15 @@ export class BlockInputSync {
1552
1744
  if (e instanceof DownloadByRootError) {
1553
1745
  const errorCode = e.type.code;
1554
1746
  downloadByRootMetrics?.error.inc({ code: errorCode, client: peerClient });
1747
+ if (errorCode === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT) {
1748
+ throw e;
1749
+ }
1750
+ // Low as in range sync, not Fatal as peers may serve unverified copies of a root with a bad signature
1751
+ if (errorCode === DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT ||
1752
+ errorCode === DownloadByRootErrorCode.PROPOSAL_SIGNATURE_INVALID ||
1753
+ errorCode === DownloadByRootErrorCode.UNKNOWN_PROPOSER) {
1754
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
1755
+ }
1555
1756
  excludedPeers.add(peerId);
1556
1757
  }
1557
1758
  else if (e instanceof RequestError) {
@@ -1727,10 +1928,12 @@ export class UnknownBlockPeerBalancer {
1727
1928
  peersMeta;
1728
1929
  activeRequests;
1729
1930
  rateLimitedUntilByPeer;
1931
+ requestTimesByPeer;
1730
1932
  constructor() {
1731
1933
  this.peersMeta = new Map();
1732
1934
  this.activeRequests = new Map();
1733
1935
  this.rateLimitedUntilByPeer = new Map();
1936
+ this.requestTimesByPeer = new Map();
1734
1937
  }
1735
1938
  /** Trigger on each peer re-status */
1736
1939
  onPeerConnected(peerId, syncMeta) {
@@ -1743,12 +1946,14 @@ export class UnknownBlockPeerBalancer {
1743
1946
  this.peersMeta.delete(peerId);
1744
1947
  this.activeRequests.delete(peerId);
1745
1948
  this.rateLimitedUntilByPeer.delete(peerId);
1949
+ this.requestTimesByPeer.delete(peerId);
1746
1950
  }
1747
1951
  /** Reset all tracked peer state, e.g. when BlockInputSync unsubscribes from the network. */
1748
1952
  clear() {
1749
1953
  this.peersMeta.clear();
1750
1954
  this.activeRequests.clear();
1751
1955
  this.rateLimitedUntilByPeer.clear();
1956
+ this.requestTimesByPeer.clear();
1752
1957
  }
1753
1958
  onRateLimited(peerId, rateLimitedUntilMs) {
1754
1959
  this.rateLimitedUntilByPeer.set(peerId, rateLimitedUntilMs);
@@ -1793,15 +1998,22 @@ export class UnknownBlockPeerBalancer {
1793
1998
  // 2nd key (tiebreak): prefer peers with least active req
1794
1999
  (peerId) => this.activeRequests.get(peerId) ?? 0);
1795
2000
  const bestPeerId = sortedEligiblePeers[0];
1796
- this.onRequest(bestPeerId);
2001
+ this.onRequest(bestPeerId, now);
1797
2002
  return this.peersMeta.get(bestPeerId) ?? null;
1798
2003
  }
1799
2004
  /**
1800
2005
  * Consumers don't need to call this method directly, it is called internally by bestPeer*() methods
1801
2006
  * make this public for testing
1802
2007
  */
1803
- onRequest(peerId) {
2008
+ onRequest(peerId, now = Date.now()) {
1804
2009
  this.activeRequests.set(peerId, (this.activeRequests.get(peerId) ?? 0) + 1);
2010
+ const requestTimes = (this.requestTimesByPeer.get(peerId) ?? []).filter((time) => now - time < REQUESTS_PER_PEER_WINDOW_MS);
2011
+ requestTimes.push(now);
2012
+ this.requestTimesByPeer.set(peerId, requestTimes);
2013
+ if (requestTimes.length >= MAX_REQUESTS_PER_PEER) {
2014
+ const budgetUntilMs = requestTimes[0] + REQUESTS_PER_PEER_WINDOW_MS;
2015
+ this.onRateLimited(peerId, Math.max(this.rateLimitedUntilByPeer.get(peerId) ?? 0, budgetUntilMs));
2016
+ }
1805
2017
  }
1806
2018
  /**
1807
2019
  * Consumers should call this method when a request is completed for a peer.