@lodestar/beacon-node 1.52.0-dev.eecc873a29 → 1.52.0-dev.f343d455cc

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 (298) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +22 -8
  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 +15 -8
  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/archiveStore/historicalState/getHistoricalState.d.ts.map +1 -1
  21. package/lib/chain/archiveStore/historicalState/getHistoricalState.js +7 -0
  22. package/lib/chain/archiveStore/historicalState/getHistoricalState.js.map +1 -1
  23. package/lib/chain/archiveStore/utils/archiveBlocks.js +1 -1
  24. package/lib/chain/archiveStore/utils/archiveBlocks.js.map +1 -1
  25. package/lib/chain/archiveStore/utils/pruneHistory.d.ts.map +1 -1
  26. package/lib/chain/archiveStore/utils/pruneHistory.js +8 -4
  27. package/lib/chain/archiveStore/utils/pruneHistory.js.map +1 -1
  28. package/lib/chain/blocks/importExecutionPayload.d.ts +1 -1
  29. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  30. package/lib/chain/blocks/importExecutionPayload.js +9 -3
  31. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  32. package/lib/chain/blocks/index.d.ts.map +1 -1
  33. package/lib/chain/blocks/index.js +3 -17
  34. package/lib/chain/blocks/index.js.map +1 -1
  35. package/lib/chain/chain.d.ts +6 -5
  36. package/lib/chain/chain.d.ts.map +1 -1
  37. package/lib/chain/chain.js +71 -25
  38. package/lib/chain/chain.js.map +1 -1
  39. package/lib/chain/errors/attestationError.d.ts +15 -1
  40. package/lib/chain/errors/attestationError.d.ts.map +1 -1
  41. package/lib/chain/errors/attestationError.js +8 -0
  42. package/lib/chain/errors/attestationError.js.map +1 -1
  43. package/lib/chain/errors/executionPayloadBid.d.ts +6 -1
  44. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  45. package/lib/chain/errors/executionPayloadBid.js +1 -0
  46. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  47. package/lib/chain/errors/executionPayloadEnvelope.d.ts +55 -0
  48. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  49. package/lib/chain/errors/executionPayloadEnvelope.js +8 -0
  50. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  51. package/lib/chain/interface.d.ts +1 -1
  52. package/lib/chain/interface.d.ts.map +1 -1
  53. package/lib/chain/lightClient/index.d.ts +13 -6
  54. package/lib/chain/lightClient/index.d.ts.map +1 -1
  55. package/lib/chain/lightClient/index.js +95 -115
  56. package/lib/chain/lightClient/index.js.map +1 -1
  57. package/lib/chain/opPools/opPool.js +6 -6
  58. package/lib/chain/opPools/opPool.js.map +1 -1
  59. package/lib/chain/prepareNextSlot.d.ts +45 -0
  60. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  61. package/lib/chain/prepareNextSlot.js +265 -69
  62. package/lib/chain/prepareNextSlot.js.map +1 -1
  63. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  64. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  65. package/lib/chain/produceBlock/produceBlockBody.js +23 -15
  66. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  67. package/lib/chain/seenCache/seenAttesters.d.ts +1 -0
  68. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  69. package/lib/chain/seenCache/seenAttesters.js +1 -1
  70. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  71. package/lib/chain/seenCache/seenBlockAttesters.d.ts +8 -2
  72. package/lib/chain/seenCache/seenBlockAttesters.d.ts.map +1 -1
  73. package/lib/chain/seenCache/seenBlockAttesters.js +43 -6
  74. package/lib/chain/seenCache/seenBlockAttesters.js.map +1 -1
  75. package/lib/chain/validation/aggregateAndProof.d.ts.map +1 -1
  76. package/lib/chain/validation/aggregateAndProof.js +24 -7
  77. package/lib/chain/validation/aggregateAndProof.js.map +1 -1
  78. package/lib/chain/validation/attestation.d.ts.map +1 -1
  79. package/lib/chain/validation/attestation.js +32 -16
  80. package/lib/chain/validation/attestation.js.map +1 -1
  81. package/lib/chain/validation/block.d.ts.map +1 -1
  82. package/lib/chain/validation/block.js +9 -1
  83. package/lib/chain/validation/block.js.map +1 -1
  84. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  85. package/lib/chain/validation/executionPayloadBid.js +18 -31
  86. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  87. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  88. package/lib/chain/validation/executionPayloadEnvelope.js +100 -9
  89. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  90. package/lib/chain/validation/payloadAttestationMessage.js +9 -0
  91. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  92. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  93. package/lib/chain/validation/voluntaryExit.js +39 -6
  94. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  95. package/lib/chain/validatorMonitor.js +43 -43
  96. package/lib/chain/validatorMonitor.js.map +1 -1
  97. package/lib/execution/engine/blockHash.d.ts +12 -0
  98. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  99. package/lib/execution/engine/blockHash.js +17 -0
  100. package/lib/execution/engine/blockHash.js.map +1 -0
  101. package/lib/execution/engine/http.d.ts +2 -2
  102. package/lib/execution/engine/http.d.ts.map +1 -1
  103. package/lib/execution/engine/http.js +13 -7
  104. package/lib/execution/engine/http.js.map +1 -1
  105. package/lib/execution/engine/interface.d.ts +16 -3
  106. package/lib/execution/engine/interface.d.ts.map +1 -1
  107. package/lib/execution/engine/interface.js +11 -0
  108. package/lib/execution/engine/interface.js.map +1 -1
  109. package/lib/execution/engine/jsonRpcHttpClient.d.ts +2 -0
  110. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +1 -1
  111. package/lib/execution/engine/jsonRpcHttpClient.js +14 -6
  112. package/lib/execution/engine/jsonRpcHttpClient.js.map +1 -1
  113. package/lib/execution/engine/jsonRpcTransport.d.ts +2 -2
  114. package/lib/execution/engine/jsonRpcTransport.d.ts.map +1 -1
  115. package/lib/execution/engine/jsonRpcTransport.js +4 -4
  116. package/lib/execution/engine/jsonRpcTransport.js.map +1 -1
  117. package/lib/execution/engine/mock.d.ts.map +1 -1
  118. package/lib/execution/engine/mock.js +6 -6
  119. package/lib/execution/engine/mock.js.map +1 -1
  120. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  121. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  122. package/lib/execution/engine/payloadIdCache.js +7 -2
  123. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  124. package/lib/execution/engine/restHttpClient.d.ts.map +1 -1
  125. package/lib/execution/engine/restHttpClient.js +9 -5
  126. package/lib/execution/engine/restHttpClient.js.map +1 -1
  127. package/lib/execution/engine/restTransport.d.ts +2 -2
  128. package/lib/execution/engine/restTransport.d.ts.map +1 -1
  129. package/lib/execution/engine/restTransport.js +4 -4
  130. package/lib/execution/engine/restTransport.js.map +1 -1
  131. package/lib/execution/engine/signal.d.ts +6 -0
  132. package/lib/execution/engine/signal.d.ts.map +1 -0
  133. package/lib/execution/engine/signal.js +24 -0
  134. package/lib/execution/engine/signal.js.map +1 -0
  135. package/lib/execution/engine/transport.d.ts +2 -2
  136. package/lib/execution/engine/transport.d.ts.map +1 -1
  137. package/lib/index.d.ts +1 -1
  138. package/lib/index.d.ts.map +1 -1
  139. package/lib/index.js +1 -1
  140. package/lib/index.js.map +1 -1
  141. package/lib/metrics/metrics/beacon.d.ts +5 -0
  142. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  143. package/lib/metrics/metrics/beacon.js +5 -0
  144. package/lib/metrics/metrics/beacon.js.map +1 -1
  145. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  146. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  147. package/lib/metrics/metrics/lodestar.js +5 -0
  148. package/lib/metrics/metrics/lodestar.js.map +1 -1
  149. package/lib/network/core/events.d.ts +6 -2
  150. package/lib/network/core/events.d.ts.map +1 -1
  151. package/lib/network/core/events.js +9 -0
  152. package/lib/network/core/events.js.map +1 -1
  153. package/lib/network/core/networkCoreWorkerHandler.d.ts.map +1 -1
  154. package/lib/network/core/networkCoreWorkerHandler.js +3 -2
  155. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  156. package/lib/network/gossip/gossipsub.d.ts +1 -0
  157. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  158. package/lib/network/gossip/gossipsub.js +5 -2
  159. package/lib/network/gossip/gossipsub.js.map +1 -1
  160. package/lib/network/gossip/topic.d.ts +1 -7
  161. package/lib/network/gossip/topic.d.ts.map +1 -1
  162. package/lib/network/gossip/topic.js +0 -13
  163. package/lib/network/gossip/topic.js.map +1 -1
  164. package/lib/network/network.d.ts.map +1 -1
  165. package/lib/network/network.js +6 -1
  166. package/lib/network/network.js.map +1 -1
  167. package/lib/network/peers/peerManager.d.ts.map +1 -1
  168. package/lib/network/peers/peerManager.js +22 -2
  169. package/lib/network/peers/peerManager.js.map +1 -1
  170. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  171. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  172. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  173. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  174. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  175. package/lib/network/processor/gossipHandlers.js +19 -6
  176. package/lib/network/processor/gossipHandlers.js.map +1 -1
  177. package/lib/network/processor/index.d.ts.map +1 -1
  178. package/lib/network/processor/index.js +4 -2
  179. package/lib/network/processor/index.js.map +1 -1
  180. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  181. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  182. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  183. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  184. package/lib/sync/range/batch.d.ts +10 -0
  185. package/lib/sync/range/batch.d.ts.map +1 -1
  186. package/lib/sync/range/batch.js +29 -0
  187. package/lib/sync/range/batch.js.map +1 -1
  188. package/lib/sync/range/chain.d.ts +17 -2
  189. package/lib/sync/range/chain.d.ts.map +1 -1
  190. package/lib/sync/range/chain.js +60 -20
  191. package/lib/sync/range/chain.js.map +1 -1
  192. package/lib/sync/range/range.d.ts.map +1 -1
  193. package/lib/sync/range/range.js +44 -3
  194. package/lib/sync/range/range.js.map +1 -1
  195. package/lib/sync/range/utils/batches.d.ts +20 -4
  196. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  197. package/lib/sync/range/utils/batches.js +31 -13
  198. package/lib/sync/range/utils/batches.js.map +1 -1
  199. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  200. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  201. package/lib/sync/range/utils/peerBalancer.js +5 -2
  202. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  203. package/lib/sync/types.d.ts +14 -1
  204. package/lib/sync/types.d.ts.map +1 -1
  205. package/lib/sync/types.js +2 -0
  206. package/lib/sync/types.js.map +1 -1
  207. package/lib/sync/unknownBlock.d.ts +28 -1
  208. package/lib/sync/unknownBlock.d.ts.map +1 -1
  209. package/lib/sync/unknownBlock.js +340 -27
  210. package/lib/sync/unknownBlock.js.map +1 -1
  211. package/lib/sync/utils/downloadByRange.d.ts +22 -1
  212. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  213. package/lib/sync/utils/downloadByRange.js +55 -25
  214. package/lib/sync/utils/downloadByRange.js.map +1 -1
  215. package/lib/sync/utils/downloadByRoot.d.ts +24 -2
  216. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  217. package/lib/sync/utils/downloadByRoot.js +48 -5
  218. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  219. package/lib/util/asyncIterableToEvents.d.ts +20 -3
  220. package/lib/util/asyncIterableToEvents.d.ts.map +1 -1
  221. package/lib/util/asyncIterableToEvents.js +76 -20
  222. package/lib/util/asyncIterableToEvents.js.map +1 -1
  223. package/lib/util/dataColumns.d.ts +1 -1
  224. package/lib/util/dataColumns.d.ts.map +1 -1
  225. package/lib/util/dataColumns.js +4 -1
  226. package/lib/util/dataColumns.js.map +1 -1
  227. package/lib/util/eventLoop.d.ts +3 -3
  228. package/lib/util/eventLoop.d.ts.map +1 -1
  229. package/lib/util/eventLoop.js +3 -3
  230. package/lib/util/eventLoop.js.map +1 -1
  231. package/package.json +27 -27
  232. package/src/api/impl/beacon/blocks/index.ts +24 -8
  233. package/src/api/impl/beacon/pool/index.ts +9 -7
  234. package/src/api/impl/beacon/state/utils.ts +2 -1
  235. package/src/api/impl/debug/index.ts +6 -2
  236. package/src/api/impl/validator/index.ts +17 -9
  237. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  238. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  239. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  240. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  241. package/src/chain/blocks/importExecutionPayload.ts +9 -2
  242. package/src/chain/blocks/index.ts +3 -31
  243. package/src/chain/chain.ts +104 -42
  244. package/src/chain/errors/attestationError.ts +11 -1
  245. package/src/chain/errors/executionPayloadBid.ts +6 -0
  246. package/src/chain/errors/executionPayloadEnvelope.ts +58 -0
  247. package/src/chain/interface.ts +1 -1
  248. package/src/chain/lightClient/index.ts +108 -142
  249. package/src/chain/opPools/opPool.ts +6 -6
  250. package/src/chain/prepareNextSlot.ts +347 -89
  251. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  252. package/src/chain/seenCache/seenAttesters.ts +1 -1
  253. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  254. package/src/chain/validation/aggregateAndProof.ts +24 -9
  255. package/src/chain/validation/attestation.ts +31 -20
  256. package/src/chain/validation/block.ts +9 -1
  257. package/src/chain/validation/executionPayloadBid.ts +21 -33
  258. package/src/chain/validation/executionPayloadEnvelope.ts +115 -8
  259. package/src/chain/validation/payloadAttestationMessage.ts +10 -0
  260. package/src/chain/validation/voluntaryExit.ts +44 -6
  261. package/src/chain/validatorMonitor.ts +43 -43
  262. package/src/execution/engine/blockHash.ts +27 -0
  263. package/src/execution/engine/http.ts +18 -10
  264. package/src/execution/engine/interface.ts +18 -3
  265. package/src/execution/engine/jsonRpcHttpClient.ts +26 -14
  266. package/src/execution/engine/jsonRpcTransport.ts +8 -4
  267. package/src/execution/engine/mock.ts +13 -8
  268. package/src/execution/engine/payloadIdCache.ts +12 -4
  269. package/src/execution/engine/restHttpClient.ts +17 -11
  270. package/src/execution/engine/restTransport.ts +5 -4
  271. package/src/execution/engine/signal.ts +28 -0
  272. package/src/execution/engine/transport.ts +3 -2
  273. package/src/index.ts +6 -1
  274. package/src/metrics/metrics/beacon.ts +9 -0
  275. package/src/metrics/metrics/lodestar.ts +5 -0
  276. package/src/network/core/events.ts +12 -0
  277. package/src/network/core/networkCoreWorkerHandler.ts +6 -2
  278. package/src/network/gossip/gossipsub.ts +6 -2
  279. package/src/network/gossip/topic.ts +1 -14
  280. package/src/network/network.ts +6 -2
  281. package/src/network/peers/peerManager.ts +26 -2
  282. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  283. package/src/network/processor/gossipHandlers.ts +25 -13
  284. package/src/network/processor/index.ts +7 -2
  285. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  286. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  287. package/src/sync/range/batch.ts +33 -0
  288. package/src/sync/range/chain.ts +72 -17
  289. package/src/sync/range/range.ts +57 -3
  290. package/src/sync/range/utils/batches.ts +38 -13
  291. package/src/sync/range/utils/peerBalancer.ts +4 -1
  292. package/src/sync/types.ts +13 -0
  293. package/src/sync/unknownBlock.ts +389 -29
  294. package/src/sync/utils/downloadByRange.ts +89 -29
  295. package/src/sync/utils/downloadByRoot.ts +75 -7
  296. package/src/util/asyncIterableToEvents.ts +100 -21
  297. package/src/util/dataColumns.ts +4 -1
  298. package/src/util/eventLoop.ts +3 -3
@@ -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, DataColumnSidecarErrorCode, DataColumnSidecarValidationError, 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
  }
@@ -1123,14 +1295,27 @@ export class BlockInputSync {
1123
1295
  return;
1124
1296
  }
1125
1297
  if (validationResult.err) {
1126
- this.logger.debug("Pending payload envelope failed validation after block import, refetching by root", { slot: pendingPayload.envelope.message.payload.slotNumber, root: rootHex }, validationResult.err);
1298
+ const err = validationResult.err;
1299
+ const { envelopePeerId } = pendingPayload;
1300
+ // Same penalties as for an envelope validated right after download in fetchPayloadInput
1301
+ if (envelopePeerId !== undefined &&
1302
+ err instanceof ExecutionPayloadEnvelopeError &&
1303
+ (pendingPayload.envelope.message.payload.slotNumber !== payloadInput.slot ||
1304
+ toRootHex(pendingPayload.envelope.message.payload.blockHash) !== payloadInput.getBlockHashHex())) {
1305
+ this.network.reportPeer(envelopePeerId, PeerAction.LowToleranceError, err.type.code);
1306
+ }
1307
+ this.logger.debug("Pending payload envelope failed validation after block import, refetching by root", { slot: pendingPayload.envelope.message.payload.slotNumber, root: rootHex }, err);
1127
1308
  const pendingPayloadByRoot = {
1128
1309
  status: PendingPayloadInputStatus.pending,
1129
1310
  rootHex,
1130
- slot: pendingPayload.envelope.message.payload.slotNumber,
1311
+ slot: payloadInput.slot,
1131
1312
  timeAddedSec: pendingPayload.timeAddedSec,
1132
1313
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1133
1314
  };
1315
+ // Do not prefer the peer whose envelope just failed validation
1316
+ if (envelopePeerId !== undefined) {
1317
+ pendingPayloadByRoot.peerIdStrings.delete(envelopePeerId);
1318
+ }
1134
1319
  this.pendingPayloads.set(rootHex, pendingPayloadByRoot);
1135
1320
  if (this.network.getConnectedPeers().length > 0) {
1136
1321
  await this.downloadPayload(pendingPayloadByRoot);
@@ -1305,6 +1490,8 @@ export class BlockInputSync {
1305
1490
  ? cacheItem.payloadInput
1306
1491
  : await this.chain.seenPayloadEnvelopeInputCache.getOrReload(rootHex);
1307
1492
  let envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1493
+ // An envelope downloaded in an earlier attempt is validated with the peer of a later one
1494
+ let envelopePeerId;
1308
1495
  const fetchStartSec = Date.now() / 1000;
1309
1496
  if (typeof slot === "number") {
1310
1497
  this.metrics?.blockInputSync.payloadFetchBegin.observe(this.chain.clock.secFromSlot(slot, fetchStartSec));
@@ -1335,6 +1522,7 @@ export class BlockInputSync {
1335
1522
  try {
1336
1523
  if (!envelope) {
1337
1524
  envelope = await this.fetchExecutionPayloadEnvelope(peerId, blockRoot, rootHex);
1525
+ envelopePeerId = peerId;
1338
1526
  cacheItem.peerIdStrings.add(peerId);
1339
1527
  const slotWasUnknown = typeof slot !== "number";
1340
1528
  slot = envelope.message.payload.slotNumber;
@@ -1354,6 +1542,7 @@ export class BlockInputSync {
1354
1542
  return {
1355
1543
  status: PendingPayloadInputStatus.waitingForBlock,
1356
1544
  envelope,
1545
+ envelopePeerId,
1357
1546
  timeAddedSec: cacheItem.timeAddedSec,
1358
1547
  peerIdStrings: cacheItem.peerIdStrings,
1359
1548
  };
@@ -1429,6 +1618,39 @@ export class BlockInputSync {
1429
1618
  else {
1430
1619
  excludedPeers.add(peerId);
1431
1620
  }
1621
+ // Honest peers serve the requested root and columns, and every path that stores payload columns verifies them
1622
+ if (e instanceof DownloadByRootError || e instanceof DataColumnSidecarValidationError) {
1623
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, e.type.code);
1624
+ }
1625
+ if (e instanceof ExecutionPayloadEnvelopeError) {
1626
+ // Range sync stores an envelope after checking only its root, slot and block hash, so an honest peer may
1627
+ // serve one that fails the other checks. Compared directly since validation stops at the first failure.
1628
+ if (envelope !== undefined &&
1629
+ payloadInput &&
1630
+ (envelope.message.payload.slotNumber !== payloadInput.slot ||
1631
+ toRootHex(envelope.message.payload.blockHash) !== payloadInput.getBlockHashHex())) {
1632
+ if (envelopePeerId !== undefined) {
1633
+ this.network.reportPeer(envelopePeerId, PeerAction.LowToleranceError, e.type.code);
1634
+ }
1635
+ envelope = payloadInput.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1636
+ }
1637
+ else {
1638
+ switch (e.type.code) {
1639
+ // Caused by local state, the downloaded envelope may still be valid
1640
+ case ExecutionPayloadEnvelopeErrorCode.BLOCK_ROOT_UNKNOWN:
1641
+ case ExecutionPayloadEnvelopeErrorCode.ENVELOPE_ALREADY_KNOWN:
1642
+ case ExecutionPayloadEnvelopeErrorCode.PAYLOAD_ENVELOPE_INPUT_MISSING:
1643
+ case ExecutionPayloadEnvelopeErrorCode.UNKNOWN_BLOCK_STATE:
1644
+ // Every copy fails once the block is finalized
1645
+ case ExecutionPayloadEnvelopeErrorCode.BELONG_TO_FINALIZED_BLOCK:
1646
+ break;
1647
+ // The served copy is invalid, take the envelope from payloadInput or another peer on the next attempt
1648
+ default:
1649
+ envelope = payloadInput?.hasPayloadEnvelope() ? payloadInput.getPayloadEnvelope() : undefined;
1650
+ break;
1651
+ }
1652
+ }
1653
+ }
1432
1654
  }
1433
1655
  finally {
1434
1656
  this.peerBalancer.onRequestCompleted(peerId);
@@ -1450,7 +1672,12 @@ export class BlockInputSync {
1450
1672
  }
1451
1673
  const receivedRootHex = toRootHex(envelope.message.beaconBlockRoot);
1452
1674
  if (receivedRootHex !== rootHex) {
1453
- throw new Error(`Execution payload envelope root mismatch requested=${rootHex} received=${receivedRootHex}`);
1675
+ throw new DownloadByRootError({
1676
+ code: DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT,
1677
+ peer: prettyPrintPeerIdStr(peerIdStr),
1678
+ requestedBlockRoot: rootHex,
1679
+ receivedBlockRoot: receivedRootHex,
1680
+ });
1454
1681
  }
1455
1682
  return envelope;
1456
1683
  }
@@ -1470,7 +1697,13 @@ export class BlockInputSync {
1470
1697
  const requestedColumnsSet = new Set(requestedColumns);
1471
1698
  const extraColumns = columnSidecars.filter((columnSidecar) => !requestedColumnsSet.has(columnSidecar.index));
1472
1699
  if (extraColumns.length > 0) {
1473
- throw new Error(`Received unexpected payload data columns indices=${prettyPrintIndices(extraColumns.map((column) => column.index))}`);
1700
+ throw new DownloadByRootError({
1701
+ code: DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED,
1702
+ peer: prettyPrintPeerIdStr(peerIdStr),
1703
+ slot: payloadInput.slot,
1704
+ blockRoot: payloadInput.blockRootHex,
1705
+ invalidIndices: prettyPrintIndices(extraColumns.map((column) => column.index)),
1706
+ });
1474
1707
  }
1475
1708
  // PayloadEnvelopeInput already carries the block slot, root, and commitments, so reuse the
1476
1709
  // block-based Gloas validator rather than maintaining a second payload-specific variant.
@@ -1497,7 +1730,19 @@ export class BlockInputSync {
1497
1730
  }
1498
1731
  let i = 0;
1499
1732
  let deferredByRateLimit = false;
1733
+ let requestedWhenReconstructable = false;
1500
1734
  while (i++ < this.getMaxDownloadAttempts()) {
1735
+ const reconstructable = isPendingBlockInput(cacheItem) &&
1736
+ isBlockInputColumns(cacheItem.blockInput) &&
1737
+ cacheItem.blockInput.hasBlockAndAllData();
1738
+ // Reconstruction recovers whole rows however many columns are missing, so only one more request is worth it,
1739
+ // further peers could each hold the import until their response times out
1740
+ if (reconstructable) {
1741
+ if (requestedWhenReconstructable) {
1742
+ break;
1743
+ }
1744
+ requestedWhenReconstructable = true;
1745
+ }
1501
1746
  const pendingColumns = isPendingBlockInput(cacheItem) && isBlockInputColumns(cacheItem.blockInput)
1502
1747
  ? new Set(cacheItem.blockInput.getMissingSampledColumnMeta().missing)
1503
1748
  : defaultPendingColumns;
@@ -1506,6 +1751,9 @@ export class BlockInputSync {
1506
1751
  // prefer peers that gossiped this block root to us (#9923)
1507
1752
  const peerMeta = this.peerBalancer.bestPeerForPendingColumns(pendingColumns, excludedPeers, cacheItem.peerIdStrings, now);
1508
1753
  if (peerMeta === null) {
1754
+ if (reconstructable) {
1755
+ break;
1756
+ }
1509
1757
  const retryAt = this.peerBalancer.getNextRateLimitRetryAt(pendingColumns, excludedPeers, now);
1510
1758
  if (retryAt !== null) {
1511
1759
  throw new UnknownBlockRateLimitedError(`Error fetching UnknownBlockRoot slot=${slot} root=${rootHex} after ${i}: peers with needed columns are rate-limited`, retryAt);
@@ -1541,17 +1789,50 @@ export class BlockInputSync {
1541
1789
  for (const warning of warnings) {
1542
1790
  this.logger.debug("BlockInputSync.fetchBlockInput: downloaded with warning", logCtx, warning);
1543
1791
  this.metrics?.blockInputSync.downloadByRoot.warn.inc({ code: warning.type.code, client: peerClient });
1792
+ // A partial response is legal, columns that were not requested are not
1793
+ if (warning.type.code === DownloadByRootErrorCode.EXTRA_SIDECAR_RECEIVED) {
1794
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, warning.type.code);
1795
+ excludedPeers.add(peerId);
1796
+ }
1797
+ // Not picked again for this block, it would be preferred as a previous source of it
1798
+ if (warning.type.code === DownloadByRootErrorCode.NOT_ENOUGH_SIDECARS_RECEIVED) {
1799
+ excludedPeers.add(peerId);
1800
+ }
1544
1801
  }
1545
- // TODO: penalize peer?
1546
1802
  }
1547
1803
  }
1548
1804
  catch (e) {
1549
1805
  this.logger.debug("Error downloading in BlockInputSync.fetchBlockInput", { slot, rootHex, attempt: i, peer: peerId, peerClient }, e);
1550
1806
  const downloadByRootMetrics = this.metrics?.blockInputSync.downloadByRoot;
1551
- // TODO: penalize peer?
1552
1807
  if (e instanceof DownloadByRootError) {
1553
1808
  const errorCode = e.type.code;
1554
1809
  downloadByRootMetrics?.error.inc({ code: errorCode, client: peerClient });
1810
+ if (errorCode === DownloadByRootErrorCode.BELOW_FINALIZED_SLOT) {
1811
+ throw e;
1812
+ }
1813
+ // Low as in range sync, not Fatal as peers may serve unverified copies of a root with a bad signature
1814
+ if (errorCode === DownloadByRootErrorCode.MISMATCH_BLOCK_ROOT ||
1815
+ errorCode === DownloadByRootErrorCode.PROPOSAL_SIGNATURE_INVALID ||
1816
+ errorCode === DownloadByRootErrorCode.UNKNOWN_PROPOSER) {
1817
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
1818
+ }
1819
+ excludedPeers.add(peerId);
1820
+ }
1821
+ else if (e instanceof DataColumnSidecarValidationError) {
1822
+ const errorCode = e.type.code;
1823
+ downloadByRootMetrics?.error.inc({ code: errorCode, client: peerClient });
1824
+ // Not PROPOSAL_SIGNATURE_INVALID or INCORRECT_HEADER_ROOT, which compares signatures too: the spec does not
1825
+ // require verifying the header signature of req/resp columns, so honest peers may serve a bad one
1826
+ switch (errorCode) {
1827
+ case DataColumnSidecarErrorCode.INCORRECT_BLOCK:
1828
+ case DataColumnSidecarErrorCode.INVALID_INDEX:
1829
+ case DataColumnSidecarErrorCode.INCORRECT_CELL_COUNT:
1830
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_COMMITMENTS_COUNT:
1831
+ case DataColumnSidecarErrorCode.INCORRECT_KZG_PROOF_COUNT:
1832
+ case DataColumnSidecarErrorCode.INCLUSION_PROOF_INVALID:
1833
+ case DataColumnSidecarErrorCode.INVALID_KZG_PROOF_BATCH:
1834
+ this.network.reportPeer(peerId, PeerAction.LowToleranceError, errorCode);
1835
+ }
1555
1836
  excludedPeers.add(peerId);
1556
1837
  }
1557
1838
  else if (e instanceof RequestError) {
@@ -1604,6 +1885,27 @@ export class BlockInputSync {
1604
1885
  }
1605
1886
  } // end while loop over peers
1606
1887
  const message = `Error fetching BlockInput with slot=${slot} root=${rootHex} after ${i - 1} attempts.`;
1888
+ if (isPendingBlockInput(cacheItem) &&
1889
+ isBlockInputColumns(cacheItem.blockInput) &&
1890
+ cacheItem.blockInput.hasBlockAndAllData()) {
1891
+ // Peers cannot serve the remaining columns now, half of them is enough to reconstruct the rest
1892
+ this.logger.verbose("BlockInputSync.fetchBlockInput: reconstructing columns peers could not serve", {
1893
+ slot,
1894
+ rootHex,
1895
+ missing: cacheItem.blockInput.getMissingSampledColumnMeta().missing.length,
1896
+ });
1897
+ this.chain.columnReconstructionTracker.triggerColumnReconstruction(cacheItem.blockInput);
1898
+ cacheItem = { ...cacheItem, status: PendingBlockInputStatus.downloaded, timeSyncedSec: Date.now() / 1000 };
1899
+ if (this.pendingBlocks.has(rootHex)) {
1900
+ this.pendingBlocks.set(rootHex, cacheItem);
1901
+ }
1902
+ const result = this.chain.forkChoice.hasBlockHex(cacheItem.blockInput.parentRootHex)
1903
+ ? FetchResult.SuccessResolved
1904
+ : FetchResult.SuccessMissingParent;
1905
+ this.metrics?.blockInputSync.fetchTime.observe({ result }, Date.now() / 1000 - fetchStartSec);
1906
+ this.metrics?.blockInputSync.fetchPeers.set({ result }, i - 1);
1907
+ return cacheItem;
1908
+ }
1607
1909
  const retryAt = deferredByRateLimit ? this.peerBalancer.getNextRateLimitRetryAt() : null;
1608
1910
  if (retryAt !== null) {
1609
1911
  throw new UnknownBlockRateLimitedError(`${message} Peers are rate-limited.`, retryAt);
@@ -1727,10 +2029,12 @@ export class UnknownBlockPeerBalancer {
1727
2029
  peersMeta;
1728
2030
  activeRequests;
1729
2031
  rateLimitedUntilByPeer;
2032
+ requestTimesByPeer;
1730
2033
  constructor() {
1731
2034
  this.peersMeta = new Map();
1732
2035
  this.activeRequests = new Map();
1733
2036
  this.rateLimitedUntilByPeer = new Map();
2037
+ this.requestTimesByPeer = new Map();
1734
2038
  }
1735
2039
  /** Trigger on each peer re-status */
1736
2040
  onPeerConnected(peerId, syncMeta) {
@@ -1743,12 +2047,14 @@ export class UnknownBlockPeerBalancer {
1743
2047
  this.peersMeta.delete(peerId);
1744
2048
  this.activeRequests.delete(peerId);
1745
2049
  this.rateLimitedUntilByPeer.delete(peerId);
2050
+ this.requestTimesByPeer.delete(peerId);
1746
2051
  }
1747
2052
  /** Reset all tracked peer state, e.g. when BlockInputSync unsubscribes from the network. */
1748
2053
  clear() {
1749
2054
  this.peersMeta.clear();
1750
2055
  this.activeRequests.clear();
1751
2056
  this.rateLimitedUntilByPeer.clear();
2057
+ this.requestTimesByPeer.clear();
1752
2058
  }
1753
2059
  onRateLimited(peerId, rateLimitedUntilMs) {
1754
2060
  this.rateLimitedUntilByPeer.set(peerId, rateLimitedUntilMs);
@@ -1793,15 +2099,22 @@ export class UnknownBlockPeerBalancer {
1793
2099
  // 2nd key (tiebreak): prefer peers with least active req
1794
2100
  (peerId) => this.activeRequests.get(peerId) ?? 0);
1795
2101
  const bestPeerId = sortedEligiblePeers[0];
1796
- this.onRequest(bestPeerId);
2102
+ this.onRequest(bestPeerId, now);
1797
2103
  return this.peersMeta.get(bestPeerId) ?? null;
1798
2104
  }
1799
2105
  /**
1800
2106
  * Consumers don't need to call this method directly, it is called internally by bestPeer*() methods
1801
2107
  * make this public for testing
1802
2108
  */
1803
- onRequest(peerId) {
2109
+ onRequest(peerId, now = Date.now()) {
1804
2110
  this.activeRequests.set(peerId, (this.activeRequests.get(peerId) ?? 0) + 1);
2111
+ const requestTimes = (this.requestTimesByPeer.get(peerId) ?? []).filter((time) => now - time < REQUESTS_PER_PEER_WINDOW_MS);
2112
+ requestTimes.push(now);
2113
+ this.requestTimesByPeer.set(peerId, requestTimes);
2114
+ if (requestTimes.length >= MAX_REQUESTS_PER_PEER) {
2115
+ const budgetUntilMs = requestTimes[0] + REQUESTS_PER_PEER_WINDOW_MS;
2116
+ this.onRateLimited(peerId, Math.max(this.rateLimitedUntilByPeer.get(peerId) ?? 0, budgetUntilMs));
2117
+ }
1805
2118
  }
1806
2119
  /**
1807
2120
  * Consumers should call this method when a request is completed for a peer.