@lodestar/beacon-node 1.52.0-dev.53c3aab4e9 → 1.52.0-dev.643dd3c5bf

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 (372) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +63 -39
  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 +19 -11
  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/blockInput/blockInput.d.ts.map +1 -1
  29. package/lib/chain/blocks/blockInput/blockInput.js +3 -1
  30. package/lib/chain/blocks/blockInput/blockInput.js.map +1 -1
  31. package/lib/chain/blocks/importExecutionPayload.d.ts +1 -1
  32. package/lib/chain/blocks/importExecutionPayload.d.ts.map +1 -1
  33. package/lib/chain/blocks/importExecutionPayload.js +25 -5
  34. package/lib/chain/blocks/importExecutionPayload.js.map +1 -1
  35. package/lib/chain/blocks/index.d.ts.map +1 -1
  36. package/lib/chain/blocks/index.js +3 -17
  37. package/lib/chain/blocks/index.js.map +1 -1
  38. package/lib/chain/blocks/verifyBlock.d.ts.map +1 -1
  39. package/lib/chain/blocks/verifyBlock.js +21 -17
  40. package/lib/chain/blocks/verifyBlock.js.map +1 -1
  41. package/lib/chain/blocks/verifyBlocksDataAvailability.d.ts +2 -2
  42. package/lib/chain/blocks/verifyBlocksDataAvailability.d.ts.map +1 -1
  43. package/lib/chain/blocks/verifyBlocksDataAvailability.js +3 -3
  44. package/lib/chain/blocks/verifyBlocksDataAvailability.js.map +1 -1
  45. package/lib/chain/blocks/verifyBlocksExecutionPayloads.d.ts.map +1 -1
  46. package/lib/chain/blocks/verifyBlocksExecutionPayloads.js +7 -5
  47. package/lib/chain/blocks/verifyBlocksExecutionPayloads.js.map +1 -1
  48. package/lib/chain/blocks/verifyBlocksSignatures.d.ts +2 -2
  49. package/lib/chain/blocks/verifyBlocksSignatures.d.ts.map +1 -1
  50. package/lib/chain/blocks/verifyBlocksSignatures.js +2 -1
  51. package/lib/chain/blocks/verifyBlocksSignatures.js.map +1 -1
  52. package/lib/chain/blocks/verifyPayloadsDataAvailability.d.ts +2 -2
  53. package/lib/chain/blocks/verifyPayloadsDataAvailability.d.ts.map +1 -1
  54. package/lib/chain/blocks/verifyPayloadsDataAvailability.js +3 -3
  55. package/lib/chain/blocks/verifyPayloadsDataAvailability.js.map +1 -1
  56. package/lib/chain/bls/utils.js +1 -1
  57. package/lib/chain/bls/utils.js.map +1 -1
  58. package/lib/chain/chain.d.ts +6 -5
  59. package/lib/chain/chain.d.ts.map +1 -1
  60. package/lib/chain/chain.js +83 -31
  61. package/lib/chain/chain.js.map +1 -1
  62. package/lib/chain/errors/attestationError.d.ts +15 -1
  63. package/lib/chain/errors/attestationError.d.ts.map +1 -1
  64. package/lib/chain/errors/attestationError.js +8 -0
  65. package/lib/chain/errors/attestationError.js.map +1 -1
  66. package/lib/chain/errors/executionPayloadBid.d.ts +9 -3
  67. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  68. package/lib/chain/errors/executionPayloadBid.js +2 -1
  69. package/lib/chain/errors/executionPayloadBid.js.map +1 -1
  70. package/lib/chain/errors/executionPayloadEnvelope.d.ts +55 -0
  71. package/lib/chain/errors/executionPayloadEnvelope.d.ts.map +1 -1
  72. package/lib/chain/errors/executionPayloadEnvelope.js +8 -0
  73. package/lib/chain/errors/executionPayloadEnvelope.js.map +1 -1
  74. package/lib/chain/forkChoice/index.d.ts +1 -4
  75. package/lib/chain/forkChoice/index.d.ts.map +1 -1
  76. package/lib/chain/forkChoice/index.js +1 -4
  77. package/lib/chain/forkChoice/index.js.map +1 -1
  78. package/lib/chain/forkChoiceExecutionEngine.d.ts +5 -3
  79. package/lib/chain/forkChoiceExecutionEngine.d.ts.map +1 -1
  80. package/lib/chain/forkChoiceExecutionEngine.js +34 -11
  81. package/lib/chain/forkChoiceExecutionEngine.js.map +1 -1
  82. package/lib/chain/interface.d.ts +1 -1
  83. package/lib/chain/interface.d.ts.map +1 -1
  84. package/lib/chain/lightClient/index.d.ts +13 -6
  85. package/lib/chain/lightClient/index.d.ts.map +1 -1
  86. package/lib/chain/lightClient/index.js +95 -115
  87. package/lib/chain/lightClient/index.js.map +1 -1
  88. package/lib/chain/opPools/inclusionListStore.d.ts +4 -1
  89. package/lib/chain/opPools/inclusionListStore.d.ts.map +1 -1
  90. package/lib/chain/opPools/inclusionListStore.js +5 -2
  91. package/lib/chain/opPools/inclusionListStore.js.map +1 -1
  92. package/lib/chain/opPools/opPool.js +6 -6
  93. package/lib/chain/opPools/opPool.js.map +1 -1
  94. package/lib/chain/options.js +2 -2
  95. package/lib/chain/options.js.map +1 -1
  96. package/lib/chain/prepareNextSlot.d.ts +45 -0
  97. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  98. package/lib/chain/prepareNextSlot.js +265 -69
  99. package/lib/chain/prepareNextSlot.js.map +1 -1
  100. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  101. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  102. package/lib/chain/produceBlock/produceBlockBody.js +23 -15
  103. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  104. package/lib/chain/seenCache/seenAttesters.d.ts +1 -0
  105. package/lib/chain/seenCache/seenAttesters.d.ts.map +1 -1
  106. package/lib/chain/seenCache/seenAttesters.js +1 -1
  107. package/lib/chain/seenCache/seenAttesters.js.map +1 -1
  108. package/lib/chain/seenCache/seenBlockAttesters.d.ts +8 -2
  109. package/lib/chain/seenCache/seenBlockAttesters.d.ts.map +1 -1
  110. package/lib/chain/seenCache/seenBlockAttesters.js +43 -6
  111. package/lib/chain/seenCache/seenBlockAttesters.js.map +1 -1
  112. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts +13 -4
  113. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts.map +1 -1
  114. package/lib/chain/seenCache/seenExecutionPayloadBids.js +13 -12
  115. package/lib/chain/seenCache/seenExecutionPayloadBids.js.map +1 -1
  116. package/lib/chain/shufflingCache.d.ts +5 -0
  117. package/lib/chain/shufflingCache.d.ts.map +1 -1
  118. package/lib/chain/shufflingCache.js +39 -1
  119. package/lib/chain/shufflingCache.js.map +1 -1
  120. package/lib/chain/validation/aggregateAndProof.d.ts.map +1 -1
  121. package/lib/chain/validation/aggregateAndProof.js +37 -9
  122. package/lib/chain/validation/aggregateAndProof.js.map +1 -1
  123. package/lib/chain/validation/attestation.d.ts.map +1 -1
  124. package/lib/chain/validation/attestation.js +32 -16
  125. package/lib/chain/validation/attestation.js.map +1 -1
  126. package/lib/chain/validation/block.d.ts.map +1 -1
  127. package/lib/chain/validation/block.js +9 -1
  128. package/lib/chain/validation/block.js.map +1 -1
  129. package/lib/chain/validation/dataColumnSidecar.d.ts.map +1 -1
  130. package/lib/chain/validation/dataColumnSidecar.js +8 -1
  131. package/lib/chain/validation/dataColumnSidecar.js.map +1 -1
  132. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  133. package/lib/chain/validation/executionPayloadBid.js +47 -42
  134. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  135. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  136. package/lib/chain/validation/executionPayloadEnvelope.js +100 -9
  137. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  138. package/lib/chain/validation/payloadAttestationMessage.js +9 -0
  139. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  140. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  141. package/lib/chain/validation/voluntaryExit.js +39 -6
  142. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  143. package/lib/execution/engine/blockHash.d.ts +12 -0
  144. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  145. package/lib/execution/engine/blockHash.js +17 -0
  146. package/lib/execution/engine/blockHash.js.map +1 -0
  147. package/lib/execution/engine/http.d.ts +2 -2
  148. package/lib/execution/engine/http.d.ts.map +1 -1
  149. package/lib/execution/engine/http.js +13 -7
  150. package/lib/execution/engine/http.js.map +1 -1
  151. package/lib/execution/engine/interface.d.ts +16 -3
  152. package/lib/execution/engine/interface.d.ts.map +1 -1
  153. package/lib/execution/engine/interface.js +11 -0
  154. package/lib/execution/engine/interface.js.map +1 -1
  155. package/lib/execution/engine/jsonRpcHttpClient.d.ts +2 -0
  156. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +1 -1
  157. package/lib/execution/engine/jsonRpcHttpClient.js +14 -6
  158. package/lib/execution/engine/jsonRpcHttpClient.js.map +1 -1
  159. package/lib/execution/engine/jsonRpcTransport.d.ts +2 -2
  160. package/lib/execution/engine/jsonRpcTransport.d.ts.map +1 -1
  161. package/lib/execution/engine/jsonRpcTransport.js +4 -4
  162. package/lib/execution/engine/jsonRpcTransport.js.map +1 -1
  163. package/lib/execution/engine/mock.d.ts.map +1 -1
  164. package/lib/execution/engine/mock.js +6 -6
  165. package/lib/execution/engine/mock.js.map +1 -1
  166. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  167. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  168. package/lib/execution/engine/payloadIdCache.js +7 -2
  169. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  170. package/lib/execution/engine/restHttpClient.d.ts.map +1 -1
  171. package/lib/execution/engine/restHttpClient.js +9 -5
  172. package/lib/execution/engine/restHttpClient.js.map +1 -1
  173. package/lib/execution/engine/restTransport.d.ts +2 -2
  174. package/lib/execution/engine/restTransport.d.ts.map +1 -1
  175. package/lib/execution/engine/restTransport.js +4 -4
  176. package/lib/execution/engine/restTransport.js.map +1 -1
  177. package/lib/execution/engine/signal.d.ts +6 -0
  178. package/lib/execution/engine/signal.d.ts.map +1 -0
  179. package/lib/execution/engine/signal.js +24 -0
  180. package/lib/execution/engine/signal.js.map +1 -0
  181. package/lib/execution/engine/transport.d.ts +2 -2
  182. package/lib/execution/engine/transport.d.ts.map +1 -1
  183. package/lib/index.d.ts +1 -1
  184. package/lib/index.d.ts.map +1 -1
  185. package/lib/index.js +1 -1
  186. package/lib/index.js.map +1 -1
  187. package/lib/metrics/metrics/beacon.d.ts +9 -0
  188. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  189. package/lib/metrics/metrics/beacon.js +16 -2
  190. package/lib/metrics/metrics/beacon.js.map +1 -1
  191. package/lib/metrics/metrics/lodestar.d.ts +3 -0
  192. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  193. package/lib/metrics/metrics/lodestar.js +42 -28
  194. package/lib/metrics/metrics/lodestar.js.map +1 -1
  195. package/lib/network/core/events.d.ts +6 -2
  196. package/lib/network/core/events.d.ts.map +1 -1
  197. package/lib/network/core/events.js +9 -0
  198. package/lib/network/core/events.js.map +1 -1
  199. package/lib/network/core/networkCoreWorkerHandler.d.ts.map +1 -1
  200. package/lib/network/core/networkCoreWorkerHandler.js +3 -2
  201. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  202. package/lib/network/gossip/gossipsub.d.ts +1 -0
  203. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  204. package/lib/network/gossip/gossipsub.js +5 -2
  205. package/lib/network/gossip/gossipsub.js.map +1 -1
  206. package/lib/network/gossip/topic.d.ts +1 -7
  207. package/lib/network/gossip/topic.d.ts.map +1 -1
  208. package/lib/network/gossip/topic.js +0 -13
  209. package/lib/network/gossip/topic.js.map +1 -1
  210. package/lib/network/network.d.ts +1 -0
  211. package/lib/network/network.d.ts.map +1 -1
  212. package/lib/network/network.js +26 -12
  213. package/lib/network/network.js.map +1 -1
  214. package/lib/network/peers/peerManager.d.ts.map +1 -1
  215. package/lib/network/peers/peerManager.js +22 -2
  216. package/lib/network/peers/peerManager.js.map +1 -1
  217. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  218. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  219. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  220. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  221. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  222. package/lib/network/processor/gossipHandlers.js +19 -6
  223. package/lib/network/processor/gossipHandlers.js.map +1 -1
  224. package/lib/network/processor/gossipValidatorFn.d.ts.map +1 -1
  225. package/lib/network/processor/gossipValidatorFn.js +4 -1
  226. package/lib/network/processor/gossipValidatorFn.js.map +1 -1
  227. package/lib/network/processor/index.d.ts.map +1 -1
  228. package/lib/network/processor/index.js +4 -2
  229. package/lib/network/processor/index.js.map +1 -1
  230. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  231. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  232. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  233. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  234. package/lib/network/reqresp/utils/collect.d.ts +4 -4
  235. package/lib/network/reqresp/utils/collect.d.ts.map +1 -1
  236. package/lib/network/reqresp/utils/collect.js +9 -8
  237. package/lib/network/reqresp/utils/collect.js.map +1 -1
  238. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts +1 -1
  239. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts.map +1 -1
  240. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js +2 -2
  241. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js.map +1 -1
  242. package/lib/sync/range/batch.d.ts +10 -0
  243. package/lib/sync/range/batch.d.ts.map +1 -1
  244. package/lib/sync/range/batch.js +29 -0
  245. package/lib/sync/range/batch.js.map +1 -1
  246. package/lib/sync/range/chain.d.ts +17 -2
  247. package/lib/sync/range/chain.d.ts.map +1 -1
  248. package/lib/sync/range/chain.js +60 -20
  249. package/lib/sync/range/chain.js.map +1 -1
  250. package/lib/sync/range/range.d.ts.map +1 -1
  251. package/lib/sync/range/range.js +44 -3
  252. package/lib/sync/range/range.js.map +1 -1
  253. package/lib/sync/range/utils/batches.d.ts +20 -4
  254. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  255. package/lib/sync/range/utils/batches.js +31 -13
  256. package/lib/sync/range/utils/batches.js.map +1 -1
  257. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  258. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  259. package/lib/sync/range/utils/peerBalancer.js +5 -2
  260. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  261. package/lib/sync/types.d.ts +14 -1
  262. package/lib/sync/types.d.ts.map +1 -1
  263. package/lib/sync/types.js +2 -0
  264. package/lib/sync/types.js.map +1 -1
  265. package/lib/sync/unknownBlock.d.ts +28 -1
  266. package/lib/sync/unknownBlock.d.ts.map +1 -1
  267. package/lib/sync/unknownBlock.js +340 -27
  268. package/lib/sync/unknownBlock.js.map +1 -1
  269. package/lib/sync/utils/downloadByRange.d.ts +22 -1
  270. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  271. package/lib/sync/utils/downloadByRange.js +55 -25
  272. package/lib/sync/utils/downloadByRange.js.map +1 -1
  273. package/lib/sync/utils/downloadByRoot.d.ts +24 -2
  274. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  275. package/lib/sync/utils/downloadByRoot.js +48 -5
  276. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  277. package/lib/util/asyncIterableToEvents.d.ts +20 -3
  278. package/lib/util/asyncIterableToEvents.d.ts.map +1 -1
  279. package/lib/util/asyncIterableToEvents.js +76 -20
  280. package/lib/util/asyncIterableToEvents.js.map +1 -1
  281. package/lib/util/dataColumns.d.ts +1 -1
  282. package/lib/util/dataColumns.d.ts.map +1 -1
  283. package/lib/util/dataColumns.js +4 -1
  284. package/lib/util/dataColumns.js.map +1 -1
  285. package/lib/util/eventLoop.d.ts +3 -3
  286. package/lib/util/eventLoop.d.ts.map +1 -1
  287. package/lib/util/eventLoop.js +3 -3
  288. package/lib/util/eventLoop.js.map +1 -1
  289. package/package.json +27 -27
  290. package/src/api/impl/beacon/blocks/index.ts +74 -47
  291. package/src/api/impl/beacon/pool/index.ts +9 -7
  292. package/src/api/impl/beacon/state/utils.ts +2 -1
  293. package/src/api/impl/debug/index.ts +6 -2
  294. package/src/api/impl/validator/index.ts +21 -11
  295. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  296. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  297. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  298. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  299. package/src/chain/blocks/blockInput/blockInput.ts +4 -1
  300. package/src/chain/blocks/importExecutionPayload.ts +30 -4
  301. package/src/chain/blocks/index.ts +3 -31
  302. package/src/chain/blocks/verifyBlock.ts +24 -17
  303. package/src/chain/blocks/verifyBlocksDataAvailability.ts +4 -4
  304. package/src/chain/blocks/verifyBlocksExecutionPayloads.ts +7 -4
  305. package/src/chain/blocks/verifyBlocksSignatures.ts +3 -0
  306. package/src/chain/blocks/verifyPayloadsDataAvailability.ts +5 -4
  307. package/src/chain/bls/utils.ts +1 -1
  308. package/src/chain/chain.ts +116 -48
  309. package/src/chain/errors/attestationError.ts +11 -1
  310. package/src/chain/errors/executionPayloadBid.ts +9 -2
  311. package/src/chain/errors/executionPayloadEnvelope.ts +58 -0
  312. package/src/chain/forkChoice/index.ts +1 -4
  313. package/src/chain/forkChoiceExecutionEngine.ts +48 -15
  314. package/src/chain/interface.ts +1 -1
  315. package/src/chain/lightClient/index.ts +108 -142
  316. package/src/chain/opPools/inclusionListStore.ts +5 -2
  317. package/src/chain/opPools/opPool.ts +6 -6
  318. package/src/chain/options.ts +2 -2
  319. package/src/chain/prepareNextSlot.ts +347 -89
  320. package/src/chain/produceBlock/produceBlockBody.ts +25 -16
  321. package/src/chain/seenCache/seenAttesters.ts +1 -1
  322. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  323. package/src/chain/seenCache/seenExecutionPayloadBids.ts +35 -15
  324. package/src/chain/shufflingCache.ts +40 -1
  325. package/src/chain/validation/aggregateAndProof.ts +43 -14
  326. package/src/chain/validation/attestation.ts +31 -20
  327. package/src/chain/validation/block.ts +9 -1
  328. package/src/chain/validation/dataColumnSidecar.ts +7 -1
  329. package/src/chain/validation/executionPayloadBid.ts +60 -44
  330. package/src/chain/validation/executionPayloadEnvelope.ts +115 -8
  331. package/src/chain/validation/payloadAttestationMessage.ts +10 -0
  332. package/src/chain/validation/voluntaryExit.ts +44 -6
  333. package/src/execution/engine/blockHash.ts +27 -0
  334. package/src/execution/engine/http.ts +18 -10
  335. package/src/execution/engine/interface.ts +18 -3
  336. package/src/execution/engine/jsonRpcHttpClient.ts +26 -14
  337. package/src/execution/engine/jsonRpcTransport.ts +8 -4
  338. package/src/execution/engine/mock.ts +13 -8
  339. package/src/execution/engine/payloadIdCache.ts +12 -4
  340. package/src/execution/engine/restHttpClient.ts +17 -11
  341. package/src/execution/engine/restTransport.ts +5 -4
  342. package/src/execution/engine/signal.ts +28 -0
  343. package/src/execution/engine/transport.ts +3 -2
  344. package/src/index.ts +6 -1
  345. package/src/metrics/metrics/beacon.ts +20 -2
  346. package/src/metrics/metrics/lodestar.ts +42 -28
  347. package/src/network/core/events.ts +12 -0
  348. package/src/network/core/networkCoreWorkerHandler.ts +6 -2
  349. package/src/network/gossip/gossipsub.ts +6 -2
  350. package/src/network/gossip/topic.ts +1 -14
  351. package/src/network/network.ts +39 -13
  352. package/src/network/peers/peerManager.ts +26 -2
  353. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  354. package/src/network/processor/gossipHandlers.ts +25 -13
  355. package/src/network/processor/gossipValidatorFn.ts +4 -0
  356. package/src/network/processor/index.ts +7 -2
  357. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  358. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  359. package/src/network/reqresp/utils/collect.ts +16 -8
  360. package/src/network/reqresp/utils/collectSequentialBlocksInRange.ts +3 -2
  361. package/src/sync/range/batch.ts +33 -0
  362. package/src/sync/range/chain.ts +72 -17
  363. package/src/sync/range/range.ts +57 -3
  364. package/src/sync/range/utils/batches.ts +38 -13
  365. package/src/sync/range/utils/peerBalancer.ts +4 -1
  366. package/src/sync/types.ts +13 -0
  367. package/src/sync/unknownBlock.ts +389 -29
  368. package/src/sync/utils/downloadByRange.ts +89 -29
  369. package/src/sync/utils/downloadByRoot.ts +75 -7
  370. package/src/util/asyncIterableToEvents.ts +100 -21
  371. package/src/util/dataColumns.ts +4 -1
  372. 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});
@@ -376,7 +400,8 @@ export class BlockInputSync {
376
400
  // because the payload at the finalized block is not finalized
377
401
  const finalizedSlot = this.chain.forkChoice.getFinalizedBlock().slot;
378
402
  const nowSec = Date.now() / 1000;
379
- const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * this.config.SLOT_DURATION_MS) / 1000;
403
+ const slotDurationMs = this.config.getSlotDurationMs(this.config.getForkName(this.chain.clock.currentSlot));
404
+ const maxSecInCache = (PRUNE_UNRESOLVED_SLOT_EPOCHS * SLOTS_PER_EPOCH * slotDurationMs) / 1000;
380
405
 
381
406
  let belowFinalizedPayloads = 0;
382
407
  let agedOutPayloads = 0;
@@ -484,13 +509,7 @@ export class BlockInputSync {
484
509
  pendingBlock.peerIdStrings.add(peerIdStr);
485
510
  }
486
511
 
487
- // TODO: check this prune methodology
488
- // Limit pending blocks to prevent DOS attacks that cause OOM
489
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
490
- if (prunedItemCount > 0) {
491
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
492
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
493
- }
512
+ this.prunePendingBlocks();
494
513
  return added;
495
514
  };
496
515
 
@@ -526,15 +545,68 @@ export class BlockInputSync {
526
545
  pendingBlock.peerIdStrings.add(peerIdStr);
527
546
  }
528
547
 
529
- // TODO: check this prune methodology
530
- // Limit pending blocks to prevent DOS attacks that cause OOM
531
- const prunedItemCount = pruneSetToMax(this.pendingBlocks, this.maxPendingBlocks);
532
- if (prunedItemCount > 0) {
533
- this.metrics?.blockInputSync.removedBlocks.inc({reason: DroppedItemReason.capacity}, prunedItemCount);
534
- this.logger.verbose(`Pruned ${prunedItemCount} items from BlockInputSync.pendingBlocks`);
535
- }
548
+ this.prunePendingBlocks();
536
549
  };
537
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
+
538
610
  private addByPayloadRootHex = (rootHex: RootHex, peerIdStr?: PeerIdStr, slot?: Slot): boolean => {
539
611
  if (this.knownBadBlocks.has(rootHex)) {
540
612
  this.logger.debug("Ignoring payload for known bad block root", {
@@ -665,6 +737,79 @@ export class BlockInputSync {
665
737
  this.scheduleRateLimitBackoffRetry();
666
738
  };
667
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
+
668
813
  /**
669
814
  * Post-gloas, a locally complete block can still be blocked on its parent's execution payload lineage.
670
815
  * Distinguish which dependency is missing so the scheduler can enqueue the right follow-up work.
@@ -813,8 +958,19 @@ export class BlockInputSync {
813
958
  if (!hasConnectedPeers) {
814
959
  this.logger.debug("No connected peers, skipping unknown block download.");
815
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
+
816
972
  // Most of the time there is exactly 1 unknown block
817
- for (const block of unknowns) {
973
+ for (const block of [...unknowns.filter(isAwaited), ...unknowns.filter((block) => !isAwaited(block))]) {
818
974
  this.downloadBlock(block).catch((e) => {
819
975
  this.logger.debug("Unexpected error - downloadBlock", {root: getBlockInputSyncCacheItemRootHex(block)}, e);
820
976
  });
@@ -897,6 +1053,31 @@ export class BlockInputSync {
897
1053
  }
898
1054
  }
899
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
+
900
1081
  /**
901
1082
  * Start this slot's payload poll: end the previous slot's loop, move roots it never got to
902
1083
  * into pendingPayloads, then poll from PAYLOAD_DUE to the end of the slot.
@@ -1018,6 +1199,10 @@ export class BlockInputSync {
1018
1199
  if (block.status !== PendingBlockInputStatus.pending) {
1019
1200
  return;
1020
1201
  }
1202
+ if (block.retryAtMs !== undefined && block.retryAtMs > Date.now()) {
1203
+ this.scheduleDownloadRetry(block.retryAtMs);
1204
+ return;
1205
+ }
1021
1206
 
1022
1207
  const rootHex = getBlockInputSyncCacheItemRootHex(block);
1023
1208
  const blockSlot = getBlockInputSyncCacheItemSlot(block);
@@ -1098,6 +1283,7 @@ export class BlockInputSync {
1098
1283
  const pendingBlock = this.pendingBlocks.get(rootHex);
1099
1284
  if (pendingBlock) {
1100
1285
  pendingBlock.status = PendingBlockInputStatus.pending;
1286
+ pendingBlock.retryAtMs = res.err.retryAt;
1101
1287
  }
1102
1288
  this.logger.debug("Deferring unknown block download due to peer rate limit", logCtx, res.err);
1103
1289
  if (!this.scheduleRateLimitBackoffRetry() || res.err.retryAt <= Date.now()) {
@@ -1108,11 +1294,31 @@ export class BlockInputSync {
1108
1294
  return;
1109
1295
  }
1110
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
+
1111
1306
  this.metrics?.blockInputSync.downloadedBlocksError.inc();
1112
1307
  this.logger.debug("Failed to download unknown block root, retained for retry", logCtx, res.err);
1113
1308
  const pendingBlock = this.pendingBlocks.get(rootHex);
1114
- 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
+ ) {
1115
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);
1116
1322
  }
1117
1323
  }
1118
1324
  }
@@ -1295,19 +1501,35 @@ export class BlockInputSync {
1295
1501
  return;
1296
1502
  }
1297
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
+
1298
1516
  this.logger.debug(
1299
1517
  "Pending payload envelope failed validation after block import, refetching by root",
1300
1518
  {slot: pendingPayload.envelope.message.payload.slotNumber, root: rootHex},
1301
- validationResult.err
1519
+ err
1302
1520
  );
1303
1521
 
1304
1522
  const pendingPayloadByRoot: PendingPayloadRootHex = {
1305
1523
  status: PendingPayloadInputStatus.pending,
1306
1524
  rootHex,
1307
- slot: pendingPayload.envelope.message.payload.slotNumber,
1525
+ slot: payloadInput.slot,
1308
1526
  timeAddedSec: pendingPayload.timeAddedSec,
1309
1527
  peerIdStrings: new Set(pendingPayload.peerIdStrings),
1310
1528
  };
1529
+ // Do not prefer the peer whose envelope just failed validation
1530
+ if (envelopePeerId !== undefined) {
1531
+ pendingPayloadByRoot.peerIdStrings.delete(envelopePeerId);
1532
+ }
1311
1533
  this.pendingPayloads.set(rootHex, pendingPayloadByRoot);
1312
1534
 
1313
1535
  if (this.network.getConnectedPeers().length > 0) {
@@ -1516,6 +1738,8 @@ export class BlockInputSync {
1516
1738
  ? cacheItem.payloadInput
1517
1739
  : await this.chain.seenPayloadEnvelopeInputCache.getOrReload(rootHex);
1518
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;
1519
1743
 
1520
1744
  const fetchStartSec = Date.now() / 1000;
1521
1745
  if (typeof slot === "number") {
@@ -1563,6 +1787,7 @@ export class BlockInputSync {
1563
1787
  try {
1564
1788
  if (!envelope) {
1565
1789
  envelope = await this.fetchExecutionPayloadEnvelope(peerId, blockRoot, rootHex);
1790
+ envelopePeerId = peerId;
1566
1791
  cacheItem.peerIdStrings.add(peerId);
1567
1792
  const slotWasUnknown = typeof slot !== "number";
1568
1793
  slot = envelope.message.payload.slotNumber;
@@ -1586,6 +1811,7 @@ export class BlockInputSync {
1586
1811
  return {
1587
1812
  status: PendingPayloadInputStatus.waitingForBlock,
1588
1813
  envelope,
1814
+ envelopePeerId,
1589
1815
  timeAddedSec: cacheItem.timeAddedSec,
1590
1816
  peerIdStrings: cacheItem.peerIdStrings,
1591
1817
  };
@@ -1670,6 +1896,42 @@ export class BlockInputSync {
1670
1896
  } else {
1671
1897
  excludedPeers.add(peerId);
1672
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
+ }
1673
1935
  } finally {
1674
1936
  this.peerBalancer.onRequestCompleted(peerId);
1675
1937
  }
@@ -1704,7 +1966,12 @@ export class BlockInputSync {
1704
1966
 
1705
1967
  const receivedRootHex = toRootHex(envelope.message.beaconBlockRoot);
1706
1968
  if (receivedRootHex !== rootHex) {
1707
- 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
+ });
1708
1975
  }
1709
1976
 
1710
1977
  return envelope;
@@ -1733,9 +2000,13 @@ export class BlockInputSync {
1733
2000
  const requestedColumnsSet = new Set(requestedColumns);
1734
2001
  const extraColumns = columnSidecars.filter((columnSidecar) => !requestedColumnsSet.has(columnSidecar.index));
1735
2002
  if (extraColumns.length > 0) {
1736
- throw new Error(
1737
- `Received unexpected payload data columns indices=${prettyPrintIndices(extraColumns.map((column) => column.index))}`
1738
- );
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
+ });
1739
2010
  }
1740
2011
 
1741
2012
  // PayloadEnvelopeInput already carries the block slot, root, and commitments, so reuse the
@@ -1772,7 +2043,20 @@ export class BlockInputSync {
1772
2043
 
1773
2044
  let i = 0;
1774
2045
  let deferredByRateLimit = false;
2046
+ let requestedWhenReconstructable = false;
1775
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
+ }
1776
2060
  const pendingColumns =
1777
2061
  isPendingBlockInput(cacheItem) && isBlockInputColumns(cacheItem.blockInput)
1778
2062
  ? new Set(cacheItem.blockInput.getMissingSampledColumnMeta().missing)
@@ -1787,6 +2071,10 @@ export class BlockInputSync {
1787
2071
  now
1788
2072
  );
1789
2073
  if (peerMeta === null) {
2074
+ if (reconstructable) {
2075
+ break;
2076
+ }
2077
+
1790
2078
  const retryAt = this.peerBalancer.getNextRateLimitRetryAt(pendingColumns, excludedPeers, now);
1791
2079
  if (retryAt !== null) {
1792
2080
  throw new UnknownBlockRateLimitedError(
@@ -1831,8 +2119,16 @@ export class BlockInputSync {
1831
2119
  for (const warning of warnings) {
1832
2120
  this.logger.debug("BlockInputSync.fetchBlockInput: downloaded with warning", logCtx, warning);
1833
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
+ }
1834
2131
  }
1835
- // TODO: penalize peer?
1836
2132
  }
1837
2133
  } catch (e) {
1838
2134
  this.logger.debug(
@@ -1841,10 +2137,36 @@ export class BlockInputSync {
1841
2137
  e as Error
1842
2138
  );
1843
2139
  const downloadByRootMetrics = this.metrics?.blockInputSync.downloadByRoot;
1844
- // TODO: penalize peer?
1845
2140
  if (e instanceof DownloadByRootError) {
1846
2141
  const errorCode = e.type.code;
1847
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
+ }
1848
2170
  excludedPeers.add(peerId);
1849
2171
  } else if (e instanceof RequestError) {
1850
2172
  // should look into req_resp metrics in this case
@@ -1897,6 +2219,30 @@ export class BlockInputSync {
1897
2219
 
1898
2220
  const message = `Error fetching BlockInput with slot=${slot} root=${rootHex} after ${i - 1} attempts.`;
1899
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
+
1900
2246
  const retryAt = deferredByRateLimit ? this.peerBalancer.getNextRateLimitRetryAt() : null;
1901
2247
  if (retryAt !== null) {
1902
2248
  throw new UnknownBlockRateLimitedError(`${message} Peers are rate-limited.`, retryAt);
@@ -2050,11 +2396,13 @@ export class UnknownBlockPeerBalancer {
2050
2396
  readonly peersMeta: Map<PeerIdStr, PeerSyncMeta>;
2051
2397
  readonly activeRequests: Map<PeerIdStr, number>;
2052
2398
  readonly rateLimitedUntilByPeer: Map<PeerIdStr, number>;
2399
+ readonly requestTimesByPeer: Map<PeerIdStr, number[]>;
2053
2400
 
2054
2401
  constructor() {
2055
2402
  this.peersMeta = new Map();
2056
2403
  this.activeRequests = new Map();
2057
2404
  this.rateLimitedUntilByPeer = new Map();
2405
+ this.requestTimesByPeer = new Map();
2058
2406
  }
2059
2407
 
2060
2408
  /** Trigger on each peer re-status */
@@ -2070,6 +2418,7 @@ export class UnknownBlockPeerBalancer {
2070
2418
  this.peersMeta.delete(peerId);
2071
2419
  this.activeRequests.delete(peerId);
2072
2420
  this.rateLimitedUntilByPeer.delete(peerId);
2421
+ this.requestTimesByPeer.delete(peerId);
2073
2422
  }
2074
2423
 
2075
2424
  /** Reset all tracked peer state, e.g. when BlockInputSync unsubscribes from the network. */
@@ -2077,6 +2426,7 @@ export class UnknownBlockPeerBalancer {
2077
2426
  this.peersMeta.clear();
2078
2427
  this.activeRequests.clear();
2079
2428
  this.rateLimitedUntilByPeer.clear();
2429
+ this.requestTimesByPeer.clear();
2080
2430
  }
2081
2431
 
2082
2432
  onRateLimited(peerId: PeerIdStr, rateLimitedUntilMs: number): void {
@@ -2143,7 +2493,7 @@ export class UnknownBlockPeerBalancer {
2143
2493
  );
2144
2494
 
2145
2495
  const bestPeerId = sortedEligiblePeers[0];
2146
- this.onRequest(bestPeerId);
2496
+ this.onRequest(bestPeerId, now);
2147
2497
  return this.peersMeta.get(bestPeerId) ?? null;
2148
2498
  }
2149
2499
 
@@ -2151,8 +2501,18 @@ export class UnknownBlockPeerBalancer {
2151
2501
  * Consumers don't need to call this method directly, it is called internally by bestPeer*() methods
2152
2502
  * make this public for testing
2153
2503
  */
2154
- onRequest(peerId: PeerIdStr): void {
2504
+ onRequest(peerId: PeerIdStr, now = Date.now()): void {
2155
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
+ }
2156
2516
  }
2157
2517
 
2158
2518
  /**