@lodestar/beacon-node 1.52.0-dev.0f379f3b22 → 1.52.0-dev.119f1f9fe6

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 (272) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +18 -5
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/beacon/state/utils.d.ts.map +1 -1
  5. package/lib/api/impl/beacon/state/utils.js +2 -1
  6. package/lib/api/impl/beacon/state/utils.js.map +1 -1
  7. package/lib/api/impl/debug/index.d.ts.map +1 -1
  8. package/lib/api/impl/debug/index.js +6 -2
  9. package/lib/api/impl/debug/index.js.map +1 -1
  10. package/lib/api/impl/validator/index.d.ts.map +1 -1
  11. package/lib/api/impl/validator/index.js +15 -8
  12. package/lib/api/impl/validator/index.js.map +1 -1
  13. package/lib/chain/ColumnReconstructionTracker.d.ts +4 -0
  14. package/lib/chain/ColumnReconstructionTracker.d.ts.map +1 -1
  15. package/lib/chain/ColumnReconstructionTracker.js +4 -0
  16. package/lib/chain/ColumnReconstructionTracker.js.map +1 -1
  17. package/lib/chain/archiveStore/historicalState/getHistoricalState.d.ts.map +1 -1
  18. package/lib/chain/archiveStore/historicalState/getHistoricalState.js +7 -0
  19. package/lib/chain/archiveStore/historicalState/getHistoricalState.js.map +1 -1
  20. package/lib/chain/archiveStore/utils/archiveBlocks.js +1 -1
  21. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  22. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  23. package/lib/chain/archiveStore/utils/pruneHistory.js +8 -4
  24. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  25. package/lib/chain/blocks/importExecutionPayload.d.ts +1 -1
  26. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  27. package/lib/chain/blocks/importExecutionPayload.js +9 -3
  28. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  29. package/lib/chain/blocks/index.d.ts.map +1 -1
  30. package/lib/chain/blocks/index.js +3 -17
  31. package/lib/chain/blocks/index.js.map +1 -1
  32. package/lib/chain/chain.d.ts +6 -5
  33. package/lib/chain/chain.d.ts.map +1 -1
  34. package/lib/chain/chain.js +71 -25
  35. package/lib/chain/chain.js.map +1 -1
  36. package/lib/chain/errors/attestationError.d.ts +15 -1
  37. package/lib/chain/errors/attestationError.d.ts.map +1 -1
  38. package/lib/chain/errors/attestationError.js +8 -0
  39. package/lib/chain/errors/attestationError.js.map +1 -1
  40. package/lib/chain/errors/executionPayloadBid.d.ts +6 -1
  41. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  42. package/lib/chain/errors/executionPayloadBid.js +1 -0
  43. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  44. package/lib/chain/errors/executionPayloadEnvelope.d.ts +55 -0
  45. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  46. package/lib/chain/errors/executionPayloadEnvelope.js +8 -0
  47. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  48. package/lib/chain/interface.d.ts +1 -1
  49. package/lib/chain/interface.d.ts.map +1 -1
  50. package/lib/chain/lightClient/index.d.ts +13 -6
  51. package/lib/chain/lightClient/index.d.ts.map +1 -1
  52. package/lib/chain/lightClient/index.js +95 -115
  53. package/lib/chain/lightClient/index.js.map +1 -1
  54. package/lib/chain/prepareNextSlot.d.ts +45 -0
  55. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  56. package/lib/chain/prepareNextSlot.js +265 -69
  57. package/lib/chain/prepareNextSlot.js.map +1 -1
  58. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  59. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  60. package/lib/chain/produceBlock/produceBlockBody.js +23 -15
  61. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  62. package/lib/chain/seenCache/seenAttesters.d.ts +1 -0
  63. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  64. package/lib/chain/seenCache/seenAttesters.js +1 -1
  65. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  66. package/lib/chain/seenCache/seenBlockAttesters.d.ts +8 -2
  67. package/lib/chain/seenCache/seenBlockAttesters.d.ts.map +1 -1
  68. package/lib/chain/seenCache/seenBlockAttesters.js +43 -6
  69. package/lib/chain/seenCache/seenBlockAttesters.js.map +1 -1
  70. package/lib/chain/validation/aggregateAndProof.d.ts.map +1 -1
  71. package/lib/chain/validation/aggregateAndProof.js +24 -7
  72. package/lib/chain/validation/aggregateAndProof.js.map +1 -1
  73. package/lib/chain/validation/attestation.d.ts.map +1 -1
  74. package/lib/chain/validation/attestation.js +32 -16
  75. package/lib/chain/validation/attestation.js.map +1 -1
  76. package/lib/chain/validation/block.d.ts.map +1 -1
  77. package/lib/chain/validation/block.js +9 -1
  78. package/lib/chain/validation/block.js.map +1 -1
  79. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  80. package/lib/chain/validation/executionPayloadBid.js +18 -31
  81. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  82. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  83. package/lib/chain/validation/executionPayloadEnvelope.js +100 -9
  84. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  85. package/lib/chain/validation/payloadAttestationMessage.js +9 -0
  86. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  87. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  88. package/lib/chain/validation/voluntaryExit.js +39 -6
  89. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  90. package/lib/chain/validatorMonitor.js +43 -43
  91. package/lib/chain/validatorMonitor.js.map +1 -1
  92. package/lib/execution/engine/blockHash.d.ts +12 -0
  93. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  94. package/lib/execution/engine/blockHash.js +17 -0
  95. package/lib/execution/engine/blockHash.js.map +1 -0
  96. package/lib/execution/engine/http.d.ts +2 -2
  97. package/lib/execution/engine/http.d.ts.map +1 -1
  98. package/lib/execution/engine/http.js +13 -7
  99. package/lib/execution/engine/http.js.map +1 -1
  100. package/lib/execution/engine/interface.d.ts +16 -3
  101. package/lib/execution/engine/interface.d.ts.map +1 -1
  102. package/lib/execution/engine/interface.js +11 -0
  103. package/lib/execution/engine/interface.js.map +1 -1
  104. package/lib/execution/engine/jsonRpcHttpClient.d.ts +2 -0
  105. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +1 -1
  106. package/lib/execution/engine/jsonRpcHttpClient.js +14 -6
  107. package/lib/execution/engine/jsonRpcHttpClient.js.map +1 -1
  108. package/lib/execution/engine/jsonRpcTransport.d.ts +2 -2
  109. package/lib/execution/engine/jsonRpcTransport.d.ts.map +1 -1
  110. package/lib/execution/engine/jsonRpcTransport.js +4 -4
  111. package/lib/execution/engine/jsonRpcTransport.js.map +1 -1
  112. package/lib/execution/engine/mock.d.ts.map +1 -1
  113. package/lib/execution/engine/mock.js +6 -6
  114. package/lib/execution/engine/mock.js.map +1 -1
  115. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  116. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  117. package/lib/execution/engine/payloadIdCache.js +7 -2
  118. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  119. package/lib/execution/engine/restHttpClient.d.ts.map +1 -1
  120. package/lib/execution/engine/restHttpClient.js +9 -5
  121. package/lib/execution/engine/restHttpClient.js.map +1 -1
  122. package/lib/execution/engine/restTransport.d.ts +2 -2
  123. package/lib/execution/engine/restTransport.d.ts.map +1 -1
  124. package/lib/execution/engine/restTransport.js +4 -4
  125. package/lib/execution/engine/restTransport.js.map +1 -1
  126. package/lib/execution/engine/signal.d.ts +6 -0
  127. package/lib/execution/engine/signal.d.ts.map +1 -0
  128. package/lib/execution/engine/signal.js +24 -0
  129. package/lib/execution/engine/signal.js.map +1 -0
  130. package/lib/execution/engine/transport.d.ts +2 -2
  131. package/lib/execution/engine/transport.d.ts.map +1 -1
  132. package/lib/index.d.ts +1 -1
  133. package/lib/index.d.ts.map +1 -1
  134. package/lib/index.js +1 -1
  135. package/lib/index.js.map +1 -1
  136. package/lib/metrics/metrics/beacon.d.ts +5 -0
  137. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  138. package/lib/metrics/metrics/beacon.js +5 -0
  139. package/lib/metrics/metrics/beacon.js.map +1 -1
  140. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  141. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  142. package/lib/metrics/metrics/lodestar.js +5 -0
  143. package/lib/metrics/metrics/lodestar.js.map +1 -1
  144. package/lib/network/gossip/gossipsub.d.ts +1 -0
  145. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  146. package/lib/network/gossip/gossipsub.js +5 -2
  147. package/lib/network/gossip/gossipsub.js.map +1 -1
  148. package/lib/network/network.d.ts.map +1 -1
  149. package/lib/network/network.js +6 -1
  150. package/lib/network/network.js.map +1 -1
  151. package/lib/network/peers/peerManager.d.ts.map +1 -1
  152. package/lib/network/peers/peerManager.js +22 -2
  153. package/lib/network/peers/peerManager.js.map +1 -1
  154. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  155. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  156. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  157. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  158. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  159. package/lib/network/processor/gossipHandlers.js +15 -5
  160. package/lib/network/processor/gossipHandlers.js.map +1 -1
  161. package/lib/network/processor/index.d.ts.map +1 -1
  162. package/lib/network/processor/index.js +4 -2
  163. package/lib/network/processor/index.js.map +1 -1
  164. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  165. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  166. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  167. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  168. package/lib/sync/range/batch.d.ts +10 -0
  169. package/lib/sync/range/batch.d.ts.map +1 -1
  170. package/lib/sync/range/batch.js +29 -0
  171. package/lib/sync/range/batch.js.map +1 -1
  172. package/lib/sync/range/chain.d.ts +17 -2
  173. package/lib/sync/range/chain.d.ts.map +1 -1
  174. package/lib/sync/range/chain.js +60 -20
  175. package/lib/sync/range/chain.js.map +1 -1
  176. package/lib/sync/range/range.d.ts.map +1 -1
  177. package/lib/sync/range/range.js +44 -3
  178. package/lib/sync/range/range.js.map +1 -1
  179. package/lib/sync/range/utils/batches.d.ts +20 -4
  180. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  181. package/lib/sync/range/utils/batches.js +31 -13
  182. package/lib/sync/range/utils/batches.js.map +1 -1
  183. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  184. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  185. package/lib/sync/range/utils/peerBalancer.js +5 -2
  186. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  187. package/lib/sync/types.d.ts +14 -1
  188. package/lib/sync/types.d.ts.map +1 -1
  189. package/lib/sync/types.js +2 -0
  190. package/lib/sync/types.js.map +1 -1
  191. package/lib/sync/unknownBlock.d.ts +28 -1
  192. package/lib/sync/unknownBlock.d.ts.map +1 -1
  193. package/lib/sync/unknownBlock.js +338 -26
  194. package/lib/sync/unknownBlock.js.map +1 -1
  195. package/lib/sync/utils/downloadByRange.d.ts +22 -1
  196. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  197. package/lib/sync/utils/downloadByRange.js +55 -25
  198. package/lib/sync/utils/downloadByRange.js.map +1 -1
  199. package/lib/sync/utils/downloadByRoot.d.ts +24 -2
  200. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  201. package/lib/sync/utils/downloadByRoot.js +48 -5
  202. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  203. package/lib/util/dataColumns.d.ts +1 -1
  204. package/lib/util/dataColumns.d.ts.map +1 -1
  205. package/lib/util/dataColumns.js +4 -1
  206. package/lib/util/dataColumns.js.map +1 -1
  207. package/lib/util/eventLoop.d.ts +3 -3
  208. package/lib/util/eventLoop.d.ts.map +1 -1
  209. package/lib/util/eventLoop.js +3 -3
  210. package/lib/util/eventLoop.js.map +1 -1
  211. package/package.json +27 -27
  212. package/src/api/impl/beacon/blocks/index.ts +20 -5
  213. package/src/api/impl/beacon/state/utils.ts +2 -1
  214. package/src/api/impl/debug/index.ts +6 -2
  215. package/src/api/impl/validator/index.ts +17 -9
  216. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  217. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  218. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  219. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  220. package/src/chain/blocks/importExecutionPayload.ts +9 -2
  221. package/src/chain/blocks/index.ts +3 -31
  222. package/src/chain/chain.ts +104 -42
  223. package/src/chain/errors/attestationError.ts +11 -1
  224. package/src/chain/errors/executionPayloadBid.ts +6 -0
  225. package/src/chain/errors/executionPayloadEnvelope.ts +58 -0
  226. package/src/chain/interface.ts +1 -1
  227. package/src/chain/lightClient/index.ts +108 -142
  228. package/src/chain/prepareNextSlot.ts +347 -89
  229. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  230. package/src/chain/seenCache/seenAttesters.ts +1 -1
  231. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  232. package/src/chain/validation/aggregateAndProof.ts +24 -9
  233. package/src/chain/validation/attestation.ts +31 -20
  234. package/src/chain/validation/block.ts +9 -1
  235. package/src/chain/validation/executionPayloadBid.ts +21 -33
  236. package/src/chain/validation/executionPayloadEnvelope.ts +115 -8
  237. package/src/chain/validation/payloadAttestationMessage.ts +10 -0
  238. package/src/chain/validation/voluntaryExit.ts +44 -6
  239. package/src/chain/validatorMonitor.ts +43 -43
  240. package/src/execution/engine/blockHash.ts +27 -0
  241. package/src/execution/engine/http.ts +18 -10
  242. package/src/execution/engine/interface.ts +18 -3
  243. package/src/execution/engine/jsonRpcHttpClient.ts +26 -14
  244. package/src/execution/engine/jsonRpcTransport.ts +8 -4
  245. package/src/execution/engine/mock.ts +13 -8
  246. package/src/execution/engine/payloadIdCache.ts +12 -4
  247. package/src/execution/engine/restHttpClient.ts +17 -11
  248. package/src/execution/engine/restTransport.ts +5 -4
  249. package/src/execution/engine/signal.ts +28 -0
  250. package/src/execution/engine/transport.ts +3 -2
  251. package/src/index.ts +6 -1
  252. package/src/metrics/metrics/beacon.ts +9 -0
  253. package/src/metrics/metrics/lodestar.ts +5 -0
  254. package/src/network/gossip/gossipsub.ts +6 -2
  255. package/src/network/network.ts +6 -2
  256. package/src/network/peers/peerManager.ts +26 -2
  257. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  258. package/src/network/processor/gossipHandlers.ts +15 -6
  259. package/src/network/processor/index.ts +7 -2
  260. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  261. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  262. package/src/sync/range/batch.ts +33 -0
  263. package/src/sync/range/chain.ts +72 -17
  264. package/src/sync/range/range.ts +57 -3
  265. package/src/sync/range/utils/batches.ts +38 -13
  266. package/src/sync/range/utils/peerBalancer.ts +4 -1
  267. package/src/sync/types.ts +13 -0
  268. package/src/sync/unknownBlock.ts +387 -28
  269. package/src/sync/utils/downloadByRange.ts +89 -29
  270. package/src/sync/utils/downloadByRoot.ts +75 -7
  271. package/src/util/dataColumns.ts +4 -1
  272. package/src/util/eventLoop.ts +3 -3
@@ -10,7 +10,14 @@ import {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";
12
12
  import {PayloadEnvelopeInput, PayloadEnvelopeInputSource} from "../chain/blocks/payloadEnvelopeInput/index.js";
13
- import {BlockError, BlockErrorCode} from "../chain/errors/index.js";
13
+ import {
14
+ BlockError,
15
+ BlockErrorCode,
16
+ DataColumnSidecarErrorCode,
17
+ DataColumnSidecarValidationError,
18
+ ExecutionPayloadEnvelopeError,
19
+ ExecutionPayloadEnvelopeErrorCode,
20
+ } from "../chain/errors/index.js";
14
21
  import {ChainEvent, ChainEventData, IBeaconChain} from "../chain/index.js";
15
22
  import {validateGloasBlockDataColumnSidecars} from "../chain/validation/dataColumnSidecar.js";
16
23
  import {validateGossipExecutionPayloadEnvelope} from "../chain/validation/executionPayloadEnvelope.js";
@@ -47,13 +54,22 @@ import {
47
54
  isPendingPayloadEnvelope,
48
55
  isPendingPayloadInput,
49
56
  } from "./types.js";
50
- import {DownloadByRootError, downloadByRoot} from "./utils/downloadByRoot.js";
57
+ import {DownloadByRootError, DownloadByRootErrorCode, downloadByRoot} from "./utils/downloadByRoot.js";
51
58
  import {getAllDescendantBlocks, getUnknownAndAncestorBlocks} from "./utils/pendingBlocksTree.js";
52
59
  import {getRateLimitedUntilMs} from "./utils/rateLimit.js";
53
60
 
54
61
  const MAX_ATTEMPTS_PER_BLOCK = 5;
55
62
  const MAX_KNOWN_BAD_BLOCKS = 500;
56
63
  const MAX_PENDING_BLOCKS = 100;
64
+ /**
65
+ * A failed download is retried after this delay, doubling per failure up to one slot.
66
+ */
67
+ const DOWNLOAD_RETRY_BASE_MS = 1_000;
68
+ /**
69
+ * Requests per peer per window, half the BeaconBlocksByRoot quota peers enforce, they disconnect a peer that exceeds it.
70
+ */
71
+ const MAX_REQUESTS_PER_PEER = 64;
72
+ const REQUESTS_PER_PEER_WINDOW_MS = 10_000;
57
73
  /**
58
74
  * A pending payload without slot can only stay at most 2 epochs.
59
75
  */
@@ -127,6 +143,8 @@ export class BlockInputSync {
127
143
  private subscribedToNetworkEvents = false;
128
144
  private peerBalancer: UnknownBlockPeerBalancer;
129
145
  private rateLimitBackoffTimeout: NodeJS.Timeout | undefined;
146
+ private downloadRetryTimeout: NodeJS.Timeout | undefined;
147
+ private downloadRetryAtMs: number | undefined;
130
148
  /**
131
149
  * Search unknown payload starting at PAYLOAD_DUE_BPS.
132
150
  */
@@ -178,6 +196,7 @@ export class BlockInputSync {
178
196
  this.network.events.on(NetworkEvent.peerConnected, this.onPeerConnected);
179
197
  this.network.events.on(NetworkEvent.peerDisconnected, this.onPeerDisconnected);
180
198
  this.chain.clock.on(ClockEvent.slot, this.startPayloadPollAtSlot);
199
+ this.chain.clock.on(ClockEvent.slot, this.pruneUnresolvedBlocks);
181
200
 
182
201
  // Seed the balancer with peers that connected before we subscribed
183
202
  for (const peerId of this.network.getConnectedPeers()) {
@@ -198,7 +217,9 @@ export class BlockInputSync {
198
217
  unsubscribeFromNetwork(): void {
199
218
  this.logger.verbose("BlockInputSync disabled.");
200
219
  this.clearRateLimitBackoffTimer();
220
+ this.clearDownloadRetryTimer();
201
221
  this.chain.clock.off(ClockEvent.slot, this.startPayloadPollAtSlot);
222
+ this.chain.clock.off(ClockEvent.slot, this.pruneUnresolvedBlocks);
202
223
  this.payloadPollAbortController?.abort();
203
224
  this.payloadPollAbortController = undefined;
204
225
  this.deferredPayloadRoots.clear();
@@ -346,6 +367,9 @@ export class BlockInputSync {
346
367
  this.addByRootHex(missingDependency.rootHex, data.peer);
347
368
  }
348
369
  this.addByBlockInput(data.blockInput, data.peer);
370
+ if (data.source === BlockInputSource.gossip) {
371
+ this.limitRetainedBlocks(data.blockInput, data.peer);
372
+ }
349
373
  this.triggerUnknownBlockSearch();
350
374
  this.metrics?.blockInputSync.requests.inc({type: PendingBlockType.UNKNOWN_PARENT});
351
375
  this.metrics?.blockInputSync.source.inc({source: data.source});
@@ -485,13 +509,7 @@ export class BlockInputSync {
485
509
  pendingBlock.peerIdStrings.add(peerIdStr);
486
510
  }
487
511
 
488
- // TODO: check this prune methodology
489
- // Limit pending blocks to prevent DOS attacks that cause OOM
490
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
491
- if (prunedItemCount > 0) {
492
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
493
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
494
- }
512
+ this.prunePendingBlocks();
495
513
  return added;
496
514
  };
497
515
 
@@ -527,15 +545,68 @@ export class BlockInputSync {
527
545
  pendingBlock.peerIdStrings.add(peerIdStr);
528
546
  }
529
547
 
530
- // TODO: check this prune methodology
531
- // Limit pending blocks to prevent DOS attacks that cause OOM
532
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
533
- if (prunedItemCount > 0) {
534
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
535
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
536
- }
548
+ this.prunePendingBlocks();
537
549
  };
538
550
 
551
+ /**
552
+ * Limit pending blocks to prevent DOS attacks that cause OOM. Any gossip message with an unknown root adds a root-only
553
+ * entry before validation, so those nothing waits on are evicted before a block or a root a pending block waits on.
554
+ * A downloaded block is only checked against its root and proposer signature, not that the proposer is due at its
555
+ * slot, so this only applies while blocks and the roots they wait on fill at most half the cap, otherwise they could
556
+ * pin it and evict every new root on insertion.
557
+ */
558
+ private prunePendingBlocks(): void {
559
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
560
+ return;
561
+ }
562
+
563
+ const awaitedRoots = new Set<RootHex>();
564
+ for (const pendingBlock of this.pendingBlocks.values()) {
565
+ if (isPendingBlockInput(pendingBlock)) {
566
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
567
+ }
568
+ }
569
+ const isKept = (rootHex: RootHex, pendingBlock: BlockInputSyncCacheItem): boolean =>
570
+ isPendingBlockInput(pendingBlock) || awaitedRoots.has(rootHex);
571
+ let keptCount = 0;
572
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
573
+ if (isKept(rootHex, pendingBlock)) {
574
+ keptCount++;
575
+ }
576
+ }
577
+
578
+ let prunedItemCount = 0;
579
+ if (keptCount <= this.maxPendingBlocks / 2) {
580
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
581
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
582
+ break;
583
+ }
584
+ if (!isKept(rootHex, pendingBlock)) {
585
+ this.pendingBlocks.delete(rootHex);
586
+ prunedItemCount++;
587
+ }
588
+ }
589
+ }
590
+ for (const [rootHex, pendingBlock] of this.pendingBlocks) {
591
+ if (this.pendingBlocks.size <= this.maxPendingBlocks) {
592
+ break;
593
+ }
594
+ this.pendingBlocks.delete(rootHex);
595
+ prunedItemCount++;
596
+ // The block input cache is only trimmed on import, a block whose parent never resolves would stay there
597
+ if (
598
+ isPendingBlockInput(pendingBlock) &&
599
+ pendingBlock.status !== PendingBlockInputStatus.processing &&
600
+ this.getMissingBlockDependency(pendingBlock.blockInput).kind === "parentBlock"
601
+ ) {
602
+ this.chain.seenBlockInputCache.remove(rootHex);
603
+ }
604
+ }
605
+
606
+ this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
607
+ this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
608
+ }
609
+
539
610
  private addByPayloadRootHex = (rootHex: RootHex, peerIdStr?: PeerIdStr, slot?: Slot): boolean => {
540
611
  if (this.knownBadBlocks.has(rootHex)) {
541
612
  this.logger.debug("Ignoring payload for known bad block root", {
@@ -666,6 +737,79 @@ export class BlockInputSync {
666
737
  this.scheduleRateLimitBackoffRetry();
667
738
  };
668
739
 
740
+ /**
741
+ * A peer can make us retain a signed block per validator key and slot until its parent resolves. Bound the bytes
742
+ * retained per peer, its oldest blocks still waiting on their parent are removed first.
743
+ */
744
+ private limitRetainedBlocks(blockInput: IBlockInput, peerIdStr: PeerIdStr): void {
745
+ const pendingBlock = this.pendingBlocks.get(blockInput.blockRootHex);
746
+ if (pendingBlock === undefined || !isPendingBlockInput(pendingBlock) || pendingBlock.retainedBy !== undefined) {
747
+ return;
748
+ }
749
+ pendingBlock.retainedBy = peerIdStr;
750
+ pendingBlock.retainedBytes = this.config
751
+ .getForkTypes(blockInput.slot)
752
+ .SignedBeaconBlock.value_serializedSize(blockInput.getBlock());
753
+
754
+ const retainedBlocks: PendingBlockInput[] = [];
755
+ let retainedBytes = 0;
756
+ for (const item of this.pendingBlocks.values()) {
757
+ if (isPendingBlockInput(item) && item.retainedBy === peerIdStr && this.isWaitingOnParent(item)) {
758
+ retainedBlocks.push(item);
759
+ retainedBytes += item.retainedBytes ?? 0;
760
+ }
761
+ }
762
+ // One block of the max gossip size fits, honest blocks are far smaller
763
+ for (const item of retainedBlocks) {
764
+ if (retainedBytes <= this.config.MAX_PAYLOAD_SIZE) {
765
+ break;
766
+ }
767
+ retainedBytes -= item.retainedBytes ?? 0;
768
+ this.removeUnresolvedBlock(item, DroppedItemReason.peerBudget);
769
+ }
770
+ }
771
+
772
+ /**
773
+ * Blocks are otherwise only pruned once finalization passes them, which never happens for a parent that does not resolve
774
+ */
775
+ private pruneUnresolvedBlocks = (): void => {
776
+ const nowSec = Date.now() / 1000;
777
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
778
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
779
+ for (const pendingBlock of this.pendingBlocks.values()) {
780
+ if (
781
+ isPendingBlockInput(pendingBlock) &&
782
+ nowSec - pendingBlock.timeAddedSec > maxSecInCache &&
783
+ this.isWaitingOnParent(pendingBlock)
784
+ ) {
785
+ this.removeUnresolvedBlock(pendingBlock, DroppedItemReason.agedOut);
786
+ }
787
+ }
788
+ };
789
+
790
+ private isWaitingOnParent(pendingBlock: PendingBlockInput): boolean {
791
+ if (pendingBlock.status === PendingBlockInputStatus.processing) {
792
+ return false;
793
+ }
794
+ const {kind} = this.getMissingBlockDependency(pendingBlock.blockInput);
795
+ return kind === "parentBlock" || kind === "parentPayload";
796
+ }
797
+
798
+ /**
799
+ * Removes only the block itself, its descendants request it again by root and its claimed ancestors stay cached
800
+ */
801
+ private removeUnresolvedBlock(pendingBlock: PendingBlockInput, reason: DroppedItemReason): void {
802
+ const rootHex = pendingBlock.blockInput.blockRootHex;
803
+ this.pendingBlocks.delete(rootHex);
804
+ this.chain.seenBlockInputCache.remove(rootHex);
805
+ this.metrics?.blockInputSync.removedBlocks.inc({reason});
806
+ this.logger.debug("Removed unresolved BlockInputSync block", {
807
+ slot: pendingBlock.blockInput.slot,
808
+ root: rootHex,
809
+ reason,
810
+ });
811
+ }
812
+
669
813
  /**
670
814
  * Post-gloas, a locally complete block can still be blocked on its parent's execution payload lineage.
671
815
  * Distinguish which dependency is missing so the scheduler can enqueue the right follow-up work.
@@ -814,8 +958,19 @@ export class BlockInputSync {
814
958
  if (!hasConnectedPeers) {
815
959
  this.logger.debug("No connected peers, skipping unknown block download.");
816
960
  } else {
961
+ // Blocks and roots a pending block waits on are downloaded first, any gossip message with an unknown root adds
962
+ // another root, and they all share the per-peer request budget
963
+ const awaitedRoots = new Set<RootHex>();
964
+ for (const pendingBlock of this.pendingBlocks.values()) {
965
+ if (isPendingBlockInput(pendingBlock)) {
966
+ awaitedRoots.add(pendingBlock.blockInput.parentRootHex);
967
+ }
968
+ }
969
+ const isAwaited = (block: BlockInputSyncCacheItem): boolean =>
970
+ isPendingBlockInput(block) || awaitedRoots.has(block.rootHex);
971
+
817
972
  // Most of the time there is exactly 1 unknown block
818
- for (const block of unknowns) {
973
+ for (const block of [...unknowns.filter(isAwaited), ...unknowns.filter((block) => !isAwaited(block))]) {
819
974
  this.downloadBlock(block).catch((e) => {
820
975
  this.logger.debug("Unexpected error - downloadBlock", {root: getBlockInputSyncCacheItemRootHex(block)}, e);
821
976
  });
@@ -898,6 +1053,31 @@ export class BlockInputSync {
898
1053
  }
899
1054
  }
900
1055
 
1056
+ private scheduleDownloadRetry(retryAtMs: number): void {
1057
+ if (this.downloadRetryAtMs !== undefined && this.downloadRetryAtMs <= retryAtMs) {
1058
+ return;
1059
+ }
1060
+
1061
+ this.clearDownloadRetryTimer();
1062
+ this.downloadRetryAtMs = retryAtMs;
1063
+ this.downloadRetryTimeout = setTimeout(
1064
+ () => {
1065
+ this.downloadRetryTimeout = undefined;
1066
+ this.downloadRetryAtMs = undefined;
1067
+ this.triggerUnknownBlockSearch();
1068
+ },
1069
+ Math.max(0, retryAtMs - Date.now())
1070
+ );
1071
+ }
1072
+
1073
+ private clearDownloadRetryTimer(): void {
1074
+ if (this.downloadRetryTimeout !== undefined) {
1075
+ clearTimeout(this.downloadRetryTimeout);
1076
+ this.downloadRetryTimeout = undefined;
1077
+ }
1078
+ this.downloadRetryAtMs = undefined;
1079
+ }
1080
+
901
1081
  /**
902
1082
  * Start this slot's payload poll: end the previous slot's loop, move roots it never got to
903
1083
  * into pendingPayloads, then poll from PAYLOAD_DUE to the end of the slot.
@@ -1019,6 +1199,10 @@ export class BlockInputSync {
1019
1199
  if (block.status !== PendingBlockInputStatus.pending) {
1020
1200
  return;
1021
1201
  }
1202
+ if (block.retryAtMs !== undefined && block.retryAtMs > Date.now()) {
1203
+ this.scheduleDownloadRetry(block.retryAtMs);
1204
+ return;
1205
+ }
1022
1206
 
1023
1207
  const rootHex = getBlockInputSyncCacheItemRootHex(block);
1024
1208
  const blockSlot = getBlockInputSyncCacheItemSlot(block);
@@ -1099,6 +1283,7 @@ export class BlockInputSync {
1099
1283
  const pendingBlock = this.pendingBlocks.get(rootHex);
1100
1284
  if (pendingBlock) {
1101
1285
  pendingBlock.status = PendingBlockInputStatus.pending;
1286
+ pendingBlock.retryAtMs = res.err.retryAt;
1102
1287
  }
1103
1288
  this.logger.debug("Deferring unknown block download due to peer rate limit", logCtx, res.err);
1104
1289
  if (!this.scheduleRateLimitBackoffRetry() || res.err.retryAt <= Date.now()) {
@@ -1109,11 +1294,31 @@ export class BlockInputSync {
1109
1294
  return;
1110
1295
  }
1111
1296
 
1297
+ if (
1298
+ res.err instanceof DownloadByRootError &&
1299
+ res.err.type.code === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT
1300
+ ) {
1301
+ this.logger.debug("Downloaded block is before finalized slot", logCtx, res.err);
1302
+ this.removeAllDescendants(block, DroppedItemReason.belowFinalized);
1303
+ return;
1304
+ }
1305
+
1112
1306
  this.metrics?.blockInputSync.downloadedBlocksError.inc();
1113
1307
  this.logger.debug("Failed to download unknown block root, retained for retry", logCtx, res.err);
1114
1308
  const pendingBlock = this.pendingBlocks.get(rootHex);
1115
- if (pendingBlock && pendingBlock.status === PendingBlockInputStatus.fetching) {
1309
+ // A partial download replaces the entry with a pending one that does not carry the failure count
1310
+ if (
1311
+ pendingBlock &&
1312
+ (pendingBlock.status === PendingBlockInputStatus.fetching ||
1313
+ pendingBlock.status === PendingBlockInputStatus.pending)
1314
+ ) {
1116
1315
  pendingBlock.status = PendingBlockInputStatus.pending;
1316
+ // Not retried on every search, any gossip message with an unknown root triggers one
1317
+ pendingBlock.failedDownloads = (block.failedDownloads ?? 0) + 1;
1318
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
1319
+ pendingBlock.retryAtMs =
1320
+ Date.now() + Math.min(DOWNLOAD_RETRY_BASE_MS * 2 ** (pendingBlock.failedDownloads - 1), slotDurationMs);
1321
+ this.scheduleDownloadRetry(pendingBlock.retryAtMs);
1117
1322
  }
1118
1323
  }
1119
1324
  }
@@ -1296,19 +1501,35 @@ export class BlockInputSync {
1296
1501
  return;
1297
1502
  }
1298
1503
  if (validationResult.err) {
1504
+ const err = validationResult.err;
1505
+ const {envelopePeerId} = pendingPayload;
1506
+ // Same penalties as for an envelope validated right after download in fetchPayloadInput
1507
+ if (
1508
+ envelopePeerId !== undefined &&
1509
+ err instanceof ExecutionPayloadEnvelopeError &&
1510
+ (pendingPayload.envelope.message.payload.slotNumber !== payloadInput.slot ||
1511
+ toRootHex(pendingPayload.envelope.message.payload.blockHash) !== payloadInput.getBlockHashHex())
1512
+ ) {
1513
+ this.network.reportPeer(envelopePeerId, PeerAction.LowToleranceError, err.type.code);
1514
+ }
1515
+
1299
1516
  this.logger.debug(
1300
1517
  "Pending payload envelope failed validation after block import, refetching by root",
1301
1518
  {slot: pendingPayload.envelope.message.payload.slotNumber, root: rootHex},
1302
- validationResult.err
1519
+ err
1303
1520
  );
1304
1521
 
1305
1522
  const pendingPayloadByRoot: PendingPayloadRootHex = {
1306
1523
  status: PendingPayloadInputStatus.pending,
1307
1524
  rootHex,
1308
- slot: pendingPayload.envelope.message.payload.slotNumber,
1525
+ slot: payloadInput.slot,
1309
1526
  timeAddedSec: pendingPayload.timeAddedSec,
1310
1527
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1311
1528
  };
1529
+ // Do not prefer the peer whose envelope just failed validation
1530
+ if (envelopePeerId !== undefined) {
1531
+ pendingPayloadByRoot.peerIdStrings.delete(envelopePeerId);
1532
+ }
1312
1533
  this.pendingPayloads.set(rootHex, pendingPayloadByRoot);
1313
1534
 
1314
1535
  if (this.network.getConnectedPeers().length > 0) {
@@ -1517,6 +1738,8 @@ export class BlockInputSync {
1517
1738
  ? cacheItem.payloadInput
1518
1739
  : await this.chain.seenPayloadEnvelopeInputCache.getOrReload(rootHex);
1519
1740
  let envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1741
+ // An envelope downloaded in an earlier attempt is validated with the peer of a later one
1742
+ let envelopePeerId: PeerIdStr | undefined;
1520
1743
 
1521
1744
  const fetchStartSec = Date.now() / 1000;
1522
1745
  if (typeof slot === "number") {
@@ -1564,6 +1787,7 @@ export class BlockInputSync {
1564
1787
  try {
1565
1788
  if (!envelope) {
1566
1789
  envelope = await this.fetchExecutionPayloadEnvelope(peerId, blockRoot, rootHex);
1790
+ envelopePeerId = peerId;
1567
1791
  cacheItem.peerIdStrings.add(peerId);
1568
1792
  const slotWasUnknown = typeof slot !== "number";
1569
1793
  slot = envelope.message.payload.slotNumber;
@@ -1587,6 +1811,7 @@ export class BlockInputSync {
1587
1811
  return {
1588
1812
  status: PendingPayloadInputStatus.waitingForBlock,
1589
1813
  envelope,
1814
+ envelopePeerId,
1590
1815
  timeAddedSec: cacheItem.timeAddedSec,
1591
1816
  peerIdStrings: cacheItem.peerIdStrings,
1592
1817
  };
@@ -1671,6 +1896,42 @@ export class BlockInputSync {
1671
1896
  } else {
1672
1897
  excludedPeers.add(peerId);
1673
1898
  }
1899
+
1900
+ // Honest peers serve the requested root and columns, and every path that stores payload columns verifies them
1901
+ if (e instanceof DownloadByRootError || e instanceof DataColumnSidecarValidationError) {
1902
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, e.type.code);
1903
+ }
1904
+
1905
+ if (e instanceof ExecutionPayloadEnvelopeError) {
1906
+ // Range sync stores an envelope after checking only its root, slot and block hash, so an honest peer may
1907
+ // serve one that fails the other checks. Compared directly since validation stops at the first failure.
1908
+ if (
1909
+ envelope !== undefined &&
1910
+ payloadInput &&
1911
+ (envelope.message.payload.slotNumber !== payloadInput.slot ||
1912
+ toRootHex(envelope.message.payload.blockHash) !== payloadInput.getBlockHashHex())
1913
+ ) {
1914
+ if (envelopePeerId !== undefined) {
1915
+ this.network.reportPeer(envelopePeerId, PeerAction.LowToleranceError, e.type.code);
1916
+ }
1917
+ envelope = payloadInput.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1918
+ } else {
1919
+ switch (e.type.code) {
1920
+ // Caused by local state, the downloaded envelope may still be valid
1921
+ case ExecutionPayloadEnvelopeErrorCode.BLOCK_ROOT_UNKNOWN:
1922
+ case ExecutionPayloadEnvelopeErrorCode.ENVELOPE_ALREADY_KNOWN:
1923
+ case ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING:
1924
+ case ExecutionPayloadEnvelopeErrorCode.UNKNOWN_BLOCK_STATE:
1925
+ // Every copy fails once the block is finalized
1926
+ case ExecutionPayloadEnvelopeErrorCode.BELONG_TO_FINALIZED_BLOCK:
1927
+ break;
1928
+ // The served copy is invalid, take the envelope from payloadInput or another peer on the next attempt
1929
+ default:
1930
+ envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1931
+ break;
1932
+ }
1933
+ }
1934
+ }
1674
1935
  } finally {
1675
1936
  this.peerBalancer.onRequestCompleted(peerId);
1676
1937
  }
@@ -1705,7 +1966,12 @@ export class BlockInputSync {
1705
1966
 
1706
1967
  const receivedRootHex = toRootHex(envelope.message.beaconBlockRoot);
1707
1968
  if (receivedRootHex !== rootHex) {
1708
- throw new Error(`Execution payload envelope root mismatch requested=${rootHex} received=${receivedRootHex}`);
1969
+ throw new DownloadByRootError({
1970
+ code: DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT,
1971
+ peer: prettyPrintPeerIdStr(peerIdStr),
1972
+ requestedBlockRoot: rootHex,
1973
+ receivedBlockRoot: receivedRootHex,
1974
+ });
1709
1975
  }
1710
1976
 
1711
1977
  return envelope;
@@ -1734,9 +2000,13 @@ export class BlockInputSync {
1734
2000
  const requestedColumnsSet = new Set(requestedColumns);
1735
2001
  const extraColumns = columnSidecars.filter((columnSidecar) => !requestedColumnsSet.has(columnSidecar.index));
1736
2002
  if (extraColumns.length > 0) {
1737
- throw new Error(
1738
- `Received unexpected payload data columns indices=${prettyPrintIndices(extraColumns.map((column) => column.index))}`
1739
- );
2003
+ throw new DownloadByRootError({
2004
+ code: DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED,
2005
+ peer: prettyPrintPeerIdStr(peerIdStr),
2006
+ slot: payloadInput.slot,
2007
+ blockRoot: payloadInput.blockRootHex,
2008
+ invalidIndices: prettyPrintIndices(extraColumns.map((column) => column.index)),
2009
+ });
1740
2010
  }
1741
2011
 
1742
2012
  // PayloadEnvelopeInput already carries the block slot, root, and commitments, so reuse the
@@ -1773,7 +2043,20 @@ export class BlockInputSync {
1773
2043
 
1774
2044
  let i = 0;
1775
2045
  let deferredByRateLimit = false;
2046
+ let requestedWhenReconstructable = false;
1776
2047
  while (i++ < this.getMaxDownloadAttempts()) {
2048
+ const reconstructable =
2049
+ isPendingBlockInput(cacheItem) &&
2050
+ isBlockInputColumns(cacheItem.blockInput) &&
2051
+ cacheItem.blockInput.hasBlockAndAllData();
2052
+ // Reconstruction recovers whole rows however many columns are missing, so only one more request is worth it,
2053
+ // further peers could each hold the import until their response times out
2054
+ if (reconstructable) {
2055
+ if (requestedWhenReconstructable) {
2056
+ break;
2057
+ }
2058
+ requestedWhenReconstructable = true;
2059
+ }
1777
2060
  const pendingColumns =
1778
2061
  isPendingBlockInput(cacheItem) && isBlockInputColumns(cacheItem.blockInput)
1779
2062
  ? new Set(cacheItem.blockInput.getMissingSampledColumnMeta().missing)
@@ -1788,6 +2071,10 @@ export class BlockInputSync {
1788
2071
  now
1789
2072
  );
1790
2073
  if (peerMeta === null) {
2074
+ if (reconstructable) {
2075
+ break;
2076
+ }
2077
+
1791
2078
  const retryAt = this.peerBalancer.getNextRateLimitRetryAt(pendingColumns, excludedPeers, now);
1792
2079
  if (retryAt !== null) {
1793
2080
  throw new UnknownBlockRateLimitedError(
@@ -1832,8 +2119,16 @@ export class BlockInputSync {
1832
2119
  for (const warning of warnings) {
1833
2120
  this.logger.debug("BlockInputSync.fetchBlockInput: downloaded with warning", logCtx, warning);
1834
2121
  this.metrics?.blockInputSync.downloadByRoot.warn.inc({code: warning.type.code, client: peerClient});
2122
+ // A partial response is legal, columns that were not requested are not
2123
+ if (warning.type.code === DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED) {
2124
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, warning.type.code);
2125
+ excludedPeers.add(peerId);
2126
+ }
2127
+ // Not picked again for this block, it would be preferred as a previous source of it
2128
+ if (warning.type.code === DownloadByRootErrorCode.NOT_ENOUGH_SIDECARS_RECEIVED) {
2129
+ excludedPeers.add(peerId);
2130
+ }
1835
2131
  }
1836
- // TODO: penalize peer?
1837
2132
  }
1838
2133
  } catch (e) {
1839
2134
  this.logger.debug(
@@ -1842,10 +2137,36 @@ export class BlockInputSync {
1842
2137
  e as Error
1843
2138
  );
1844
2139
  const downloadByRootMetrics = this.metrics?.blockInputSync.downloadByRoot;
1845
- // TODO: penalize peer?
1846
2140
  if (e instanceof DownloadByRootError) {
1847
2141
  const errorCode = e.type.code;
1848
2142
  downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
2143
+ if (errorCode === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT) {
2144
+ throw e;
2145
+ }
2146
+ // Low as in range sync, not Fatal as peers may serve unverified copies of a root with a bad signature
2147
+ if (
2148
+ errorCode === DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT ||
2149
+ errorCode === DownloadByRootErrorCode.PROPOSAL_SIGNATURE_INVALID ||
2150
+ errorCode === DownloadByRootErrorCode.UNKNOWN_PROPOSER
2151
+ ) {
2152
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2153
+ }
2154
+ excludedPeers.add(peerId);
2155
+ } else if (e instanceof DataColumnSidecarValidationError) {
2156
+ const errorCode = e.type.code;
2157
+ downloadByRootMetrics?.error.inc({code: errorCode, client: peerClient});
2158
+ // Not PROPOSAL_SIGNATURE_INVALID or INCORRECT_HEADER_ROOT, which compares signatures too: the spec does not
2159
+ // require verifying the header signature of req/resp columns, so honest peers may serve a bad one
2160
+ switch (errorCode) {
2161
+ case DataColumnSidecarErrorCode.INCORRECT_BLOCK:
2162
+ case DataColumnSidecarErrorCode.INVALID_INDEX:
2163
+ case DataColumnSidecarErrorCode.INCORRECT_CELL_COUNT:
2164
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_COMMITMENTS_COUNT:
2165
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_PROOF_COUNT:
2166
+ case DataColumnSidecarErrorCode.INCLUSION_PROOF_INVALID:
2167
+ case DataColumnSidecarErrorCode.INVALID_KZG_PROOF_BATCH:
2168
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
2169
+ }
1849
2170
  excludedPeers.add(peerId);
1850
2171
  } else if (e instanceof RequestError) {
1851
2172
  // should look into req_resp metrics in this case
@@ -1898,6 +2219,30 @@ export class BlockInputSync {
1898
2219
 
1899
2220
  const message = `Error fetching BlockInput with slot=${slot} root=${rootHex} after ${i - 1} attempts.`;
1900
2221
 
2222
+ if (
2223
+ isPendingBlockInput(cacheItem) &&
2224
+ isBlockInputColumns(cacheItem.blockInput) &&
2225
+ cacheItem.blockInput.hasBlockAndAllData()
2226
+ ) {
2227
+ // Peers cannot serve the remaining columns now, half of them is enough to reconstruct the rest
2228
+ this.logger.verbose("BlockInputSync.fetchBlockInput: reconstructing columns peers could not serve", {
2229
+ slot,
2230
+ rootHex,
2231
+ missing: cacheItem.blockInput.getMissingSampledColumnMeta().missing.length,
2232
+ });
2233
+ this.chain.columnReconstructionTracker.triggerColumnReconstruction(cacheItem.blockInput);
2234
+ cacheItem = {...cacheItem, status: PendingBlockInputStatus.downloaded, timeSyncedSec: Date.now() / 1000};
2235
+ if (this.pendingBlocks.has(rootHex)) {
2236
+ this.pendingBlocks.set(rootHex, cacheItem);
2237
+ }
2238
+ const result = this.chain.forkChoice.hasBlockHex(cacheItem.blockInput.parentRootHex)
2239
+ ? FetchResult.SuccessResolved
2240
+ : FetchResult.SuccessMissingParent;
2241
+ this.metrics?.blockInputSync.fetchTime.observe({result}, Date.now() / 1000 - fetchStartSec);
2242
+ this.metrics?.blockInputSync.fetchPeers.set({result}, i - 1);
2243
+ return cacheItem;
2244
+ }
2245
+
1901
2246
  const retryAt = deferredByRateLimit ? this.peerBalancer.getNextRateLimitRetryAt() : null;
1902
2247
  if (retryAt !== null) {
1903
2248
  throw new UnknownBlockRateLimitedError(`${message} Peers are rate-limited.`, retryAt);
@@ -2051,11 +2396,13 @@ export class UnknownBlockPeerBalancer {
2051
2396
  readonly peersMeta: Map<PeerIdStr, PeerSyncMeta>;
2052
2397
  readonly activeRequests: Map<PeerIdStr, number>;
2053
2398
  readonly rateLimitedUntilByPeer: Map<PeerIdStr, number>;
2399
+ readonly requestTimesByPeer: Map<PeerIdStr, number[]>;
2054
2400
 
2055
2401
  constructor() {
2056
2402
  this.peersMeta = new Map();
2057
2403
  this.activeRequests = new Map();
2058
2404
  this.rateLimitedUntilByPeer = new Map();
2405
+ this.requestTimesByPeer = new Map();
2059
2406
  }
2060
2407
 
2061
2408
  /** Trigger on each peer re-status */
@@ -2071,6 +2418,7 @@ export class UnknownBlockPeerBalancer {
2071
2418
  this.peersMeta.delete(peerId);
2072
2419
  this.activeRequests.delete(peerId);
2073
2420
  this.rateLimitedUntilByPeer.delete(peerId);
2421
+ this.requestTimesByPeer.delete(peerId);
2074
2422
  }
2075
2423
 
2076
2424
  /** Reset all tracked peer state, e.g. when BlockInputSync unsubscribes from the network. */
@@ -2078,6 +2426,7 @@ export class UnknownBlockPeerBalancer {
2078
2426
  this.peersMeta.clear();
2079
2427
  this.activeRequests.clear();
2080
2428
  this.rateLimitedUntilByPeer.clear();
2429
+ this.requestTimesByPeer.clear();
2081
2430
  }
2082
2431
 
2083
2432
  onRateLimited(peerId: PeerIdStr, rateLimitedUntilMs: number): void {
@@ -2144,7 +2493,7 @@ export class UnknownBlockPeerBalancer {
2144
2493
  );
2145
2494
 
2146
2495
  const bestPeerId = sortedEligiblePeers[0];
2147
- this.onRequest(bestPeerId);
2496
+ this.onRequest(bestPeerId, now);
2148
2497
  return this.peersMeta.get(bestPeerId) ?? null;
2149
2498
  }
2150
2499
 
@@ -2152,8 +2501,18 @@ export class UnknownBlockPeerBalancer {
2152
2501
  * Consumers don't need to call this method directly, it is called internally by bestPeer*() methods
2153
2502
  * make this public for testing
2154
2503
  */
2155
- onRequest(peerId: PeerIdStr): void {
2504
+ onRequest(peerId: PeerIdStr, now = Date.now()): void {
2156
2505
  this.activeRequests.set(peerId, (this.activeRequests.get(peerId) ?? 0) + 1);
2506
+
2507
+ const requestTimes = (this.requestTimesByPeer.get(peerId) ?? []).filter(
2508
+ (time) => now - time < REQUESTS_PER_PEER_WINDOW_MS
2509
+ );
2510
+ requestTimes.push(now);
2511
+ this.requestTimesByPeer.set(peerId, requestTimes);
2512
+ if (requestTimes.length >= MAX_REQUESTS_PER_PEER) {
2513
+ const budgetUntilMs = requestTimes[0] + REQUESTS_PER_PEER_WINDOW_MS;
2514
+ this.onRateLimited(peerId, Math.max(this.rateLimitedUntilByPeer.get(peerId) ?? 0, budgetUntilMs));
2515
+ }
2157
2516
  }
2158
2517
 
2159
2518
  /**