@lodestar/beacon-node 1.52.0-dev.269cf1aa5b → 1.52.0-dev.31011e1c39

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 (353) hide show
  1. package/lib/api/impl/beacon/blocks/index.d.ts.map +1 -1
  2. package/lib/api/impl/beacon/blocks/index.js +47 -26
  3. package/lib/api/impl/beacon/blocks/index.js.map +1 -1
  4. package/lib/api/impl/beacon/pool/index.d.ts.map +1 -1
  5. package/lib/api/impl/beacon/pool/index.js +4 -2
  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 +87 -48
  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 +7 -6
  36. package/lib/chain/chain.d.ts.map +1 -1
  37. package/lib/chain/chain.js +80 -41
  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 +9 -3
  44. package/lib/chain/errors/executionPayloadBid.d.ts.map +1 -1
  45. package/lib/chain/errors/executionPayloadBid.js +2 -1
  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 +6 -2
  64. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  65. package/lib/chain/produceBlock/produceBlockBody.js +54 -64
  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/seenCache/seenExecutionPayloadBids.d.ts +13 -4
  76. package/lib/chain/seenCache/seenExecutionPayloadBids.d.ts.map +1 -1
  77. package/lib/chain/seenCache/seenExecutionPayloadBids.js +13 -12
  78. package/lib/chain/seenCache/seenExecutionPayloadBids.js.map +1 -1
  79. package/lib/chain/validation/aggregateAndProof.d.ts.map +1 -1
  80. package/lib/chain/validation/aggregateAndProof.js +24 -7
  81. package/lib/chain/validation/aggregateAndProof.js.map +1 -1
  82. package/lib/chain/validation/attestation.d.ts.map +1 -1
  83. package/lib/chain/validation/attestation.js +32 -16
  84. package/lib/chain/validation/attestation.js.map +1 -1
  85. package/lib/chain/validation/attesterSlashing.d.ts.map +1 -1
  86. package/lib/chain/validation/attesterSlashing.js +4 -2
  87. package/lib/chain/validation/attesterSlashing.js.map +1 -1
  88. package/lib/chain/validation/block.d.ts.map +1 -1
  89. package/lib/chain/validation/block.js +9 -1
  90. package/lib/chain/validation/block.js.map +1 -1
  91. package/lib/chain/validation/executionPayloadBid.d.ts.map +1 -1
  92. package/lib/chain/validation/executionPayloadBid.js +47 -42
  93. package/lib/chain/validation/executionPayloadBid.js.map +1 -1
  94. package/lib/chain/validation/executionPayloadEnvelope.d.ts.map +1 -1
  95. package/lib/chain/validation/executionPayloadEnvelope.js +100 -9
  96. package/lib/chain/validation/executionPayloadEnvelope.js.map +1 -1
  97. package/lib/chain/validation/payloadAttestationMessage.js +9 -0
  98. package/lib/chain/validation/payloadAttestationMessage.js.map +1 -1
  99. package/lib/chain/validation/proposerSlashing.js +4 -2
  100. package/lib/chain/validation/proposerSlashing.js.map +1 -1
  101. package/lib/chain/validation/signatureSets/contributionAndProof.d.ts +2 -2
  102. package/lib/chain/validation/signatureSets/contributionAndProof.d.ts.map +1 -1
  103. package/lib/chain/validation/signatureSets/contributionAndProof.js +2 -2
  104. package/lib/chain/validation/signatureSets/contributionAndProof.js.map +1 -1
  105. package/lib/chain/validation/signatureSets/syncCommittee.d.ts +2 -2
  106. package/lib/chain/validation/signatureSets/syncCommittee.d.ts.map +1 -1
  107. package/lib/chain/validation/signatureSets/syncCommittee.js +2 -2
  108. package/lib/chain/validation/signatureSets/syncCommittee.js.map +1 -1
  109. package/lib/chain/validation/signatureSets/syncCommitteeContribution.d.ts +2 -2
  110. package/lib/chain/validation/signatureSets/syncCommitteeContribution.d.ts.map +1 -1
  111. package/lib/chain/validation/signatureSets/syncCommitteeContribution.js +2 -2
  112. package/lib/chain/validation/signatureSets/syncCommitteeContribution.js.map +1 -1
  113. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.d.ts +2 -2
  114. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.d.ts.map +1 -1
  115. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.js +2 -2
  116. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.js.map +1 -1
  117. package/lib/chain/validation/syncCommittee.d.ts +1 -1
  118. package/lib/chain/validation/syncCommittee.d.ts.map +1 -1
  119. package/lib/chain/validation/syncCommittee.js +5 -5
  120. package/lib/chain/validation/syncCommittee.js.map +1 -1
  121. package/lib/chain/validation/syncCommitteeContributionAndProof.js +3 -3
  122. package/lib/chain/validation/syncCommitteeContributionAndProof.js.map +1 -1
  123. package/lib/chain/validation/voluntaryExit.d.ts.map +1 -1
  124. package/lib/chain/validation/voluntaryExit.js +39 -6
  125. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  126. package/lib/chain/validatorMonitor.js +43 -43
  127. package/lib/chain/validatorMonitor.js.map +1 -1
  128. package/lib/execution/engine/blockHash.d.ts +12 -0
  129. package/lib/execution/engine/blockHash.d.ts.map +1 -0
  130. package/lib/execution/engine/blockHash.js +17 -0
  131. package/lib/execution/engine/blockHash.js.map +1 -0
  132. package/lib/execution/engine/http.d.ts +2 -2
  133. package/lib/execution/engine/http.d.ts.map +1 -1
  134. package/lib/execution/engine/http.js +13 -7
  135. package/lib/execution/engine/http.js.map +1 -1
  136. package/lib/execution/engine/interface.d.ts +16 -3
  137. package/lib/execution/engine/interface.d.ts.map +1 -1
  138. package/lib/execution/engine/interface.js +11 -0
  139. package/lib/execution/engine/interface.js.map +1 -1
  140. package/lib/execution/engine/jsonRpcHttpClient.d.ts +2 -0
  141. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +1 -1
  142. package/lib/execution/engine/jsonRpcHttpClient.js +14 -6
  143. package/lib/execution/engine/jsonRpcHttpClient.js.map +1 -1
  144. package/lib/execution/engine/jsonRpcTransport.d.ts +2 -2
  145. package/lib/execution/engine/jsonRpcTransport.d.ts.map +1 -1
  146. package/lib/execution/engine/jsonRpcTransport.js +4 -4
  147. package/lib/execution/engine/jsonRpcTransport.js.map +1 -1
  148. package/lib/execution/engine/mock.d.ts.map +1 -1
  149. package/lib/execution/engine/mock.js +6 -6
  150. package/lib/execution/engine/mock.js.map +1 -1
  151. package/lib/execution/engine/payloadIdCache.d.ts +6 -1
  152. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  153. package/lib/execution/engine/payloadIdCache.js +7 -2
  154. package/lib/execution/engine/payloadIdCache.js.map +1 -1
  155. package/lib/execution/engine/restHttpClient.d.ts.map +1 -1
  156. package/lib/execution/engine/restHttpClient.js +9 -5
  157. package/lib/execution/engine/restHttpClient.js.map +1 -1
  158. package/lib/execution/engine/restTransport.d.ts +2 -2
  159. package/lib/execution/engine/restTransport.d.ts.map +1 -1
  160. package/lib/execution/engine/restTransport.js +4 -4
  161. package/lib/execution/engine/restTransport.js.map +1 -1
  162. package/lib/execution/engine/signal.d.ts +6 -0
  163. package/lib/execution/engine/signal.d.ts.map +1 -0
  164. package/lib/execution/engine/signal.js +24 -0
  165. package/lib/execution/engine/signal.js.map +1 -0
  166. package/lib/execution/engine/transport.d.ts +2 -2
  167. package/lib/execution/engine/transport.d.ts.map +1 -1
  168. package/lib/index.d.ts +1 -1
  169. package/lib/index.d.ts.map +1 -1
  170. package/lib/index.js +1 -1
  171. package/lib/index.js.map +1 -1
  172. package/lib/metrics/metrics/beacon.d.ts +5 -0
  173. package/lib/metrics/metrics/beacon.d.ts.map +1 -1
  174. package/lib/metrics/metrics/beacon.js +5 -0
  175. package/lib/metrics/metrics/beacon.js.map +1 -1
  176. package/lib/metrics/metrics/lodestar.d.ts +1 -0
  177. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  178. package/lib/metrics/metrics/lodestar.js +5 -0
  179. package/lib/metrics/metrics/lodestar.js.map +1 -1
  180. package/lib/network/core/events.d.ts +6 -2
  181. package/lib/network/core/events.d.ts.map +1 -1
  182. package/lib/network/core/events.js +9 -0
  183. package/lib/network/core/events.js.map +1 -1
  184. package/lib/network/core/networkCoreWorkerHandler.d.ts.map +1 -1
  185. package/lib/network/core/networkCoreWorkerHandler.js +3 -2
  186. package/lib/network/core/networkCoreWorkerHandler.js.map +1 -1
  187. package/lib/network/gossip/gossipsub.d.ts +1 -0
  188. package/lib/network/gossip/gossipsub.d.ts.map +1 -1
  189. package/lib/network/gossip/gossipsub.js +5 -2
  190. package/lib/network/gossip/gossipsub.js.map +1 -1
  191. package/lib/network/gossip/topic.d.ts +1 -7
  192. package/lib/network/gossip/topic.d.ts.map +1 -1
  193. package/lib/network/gossip/topic.js +0 -13
  194. package/lib/network/gossip/topic.js.map +1 -1
  195. package/lib/network/network.d.ts +1 -0
  196. package/lib/network/network.d.ts.map +1 -1
  197. package/lib/network/network.js +26 -12
  198. package/lib/network/network.js.map +1 -1
  199. package/lib/network/peers/peerManager.d.ts.map +1 -1
  200. package/lib/network/peers/peerManager.js +22 -2
  201. package/lib/network/peers/peerManager.js.map +1 -1
  202. package/lib/network/peers/utils/prioritizePeers.d.ts +2 -0
  203. package/lib/network/peers/utils/prioritizePeers.d.ts.map +1 -1
  204. package/lib/network/peers/utils/prioritizePeers.js +11 -2
  205. package/lib/network/peers/utils/prioritizePeers.js.map +1 -1
  206. package/lib/network/processor/gossipHandlers.d.ts.map +1 -1
  207. package/lib/network/processor/gossipHandlers.js +19 -6
  208. package/lib/network/processor/gossipHandlers.js.map +1 -1
  209. package/lib/network/processor/gossipValidatorFn.d.ts.map +1 -1
  210. package/lib/network/processor/gossipValidatorFn.js +4 -1
  211. package/lib/network/processor/gossipValidatorFn.js.map +1 -1
  212. package/lib/network/processor/index.d.ts.map +1 -1
  213. package/lib/network/processor/index.js +4 -2
  214. package/lib/network/processor/index.js.map +1 -1
  215. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js +1 -1
  216. package/lib/network/reqresp/handlers/dataColumnSidecarsByRange.js.map +1 -1
  217. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js +1 -1
  218. package/lib/network/reqresp/handlers/dataColumnSidecarsByRoot.js.map +1 -1
  219. package/lib/network/reqresp/utils/collect.d.ts +4 -4
  220. package/lib/network/reqresp/utils/collect.d.ts.map +1 -1
  221. package/lib/network/reqresp/utils/collect.js +9 -8
  222. package/lib/network/reqresp/utils/collect.js.map +1 -1
  223. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts +1 -1
  224. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.d.ts.map +1 -1
  225. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js +2 -2
  226. package/lib/network/reqresp/utils/collectSequentialBlocksInRange.js.map +1 -1
  227. package/lib/sync/range/batch.d.ts +10 -0
  228. package/lib/sync/range/batch.d.ts.map +1 -1
  229. package/lib/sync/range/batch.js +29 -0
  230. package/lib/sync/range/batch.js.map +1 -1
  231. package/lib/sync/range/chain.d.ts +17 -2
  232. package/lib/sync/range/chain.d.ts.map +1 -1
  233. package/lib/sync/range/chain.js +60 -20
  234. package/lib/sync/range/chain.js.map +1 -1
  235. package/lib/sync/range/range.d.ts.map +1 -1
  236. package/lib/sync/range/range.js +44 -3
  237. package/lib/sync/range/range.js.map +1 -1
  238. package/lib/sync/range/utils/batches.d.ts +20 -4
  239. package/lib/sync/range/utils/batches.d.ts.map +1 -1
  240. package/lib/sync/range/utils/batches.js +31 -13
  241. package/lib/sync/range/utils/batches.js.map +1 -1
  242. package/lib/sync/range/utils/peerBalancer.d.ts +1 -1
  243. package/lib/sync/range/utils/peerBalancer.d.ts.map +1 -1
  244. package/lib/sync/range/utils/peerBalancer.js +5 -2
  245. package/lib/sync/range/utils/peerBalancer.js.map +1 -1
  246. package/lib/sync/types.d.ts +14 -1
  247. package/lib/sync/types.d.ts.map +1 -1
  248. package/lib/sync/types.js +2 -0
  249. package/lib/sync/types.js.map +1 -1
  250. package/lib/sync/unknownBlock.d.ts +28 -1
  251. package/lib/sync/unknownBlock.d.ts.map +1 -1
  252. package/lib/sync/unknownBlock.js +340 -27
  253. package/lib/sync/unknownBlock.js.map +1 -1
  254. package/lib/sync/utils/downloadByRange.d.ts +22 -1
  255. package/lib/sync/utils/downloadByRange.d.ts.map +1 -1
  256. package/lib/sync/utils/downloadByRange.js +55 -25
  257. package/lib/sync/utils/downloadByRange.js.map +1 -1
  258. package/lib/sync/utils/downloadByRoot.d.ts +24 -2
  259. package/lib/sync/utils/downloadByRoot.d.ts.map +1 -1
  260. package/lib/sync/utils/downloadByRoot.js +48 -5
  261. package/lib/sync/utils/downloadByRoot.js.map +1 -1
  262. package/lib/util/asyncIterableToEvents.d.ts +20 -3
  263. package/lib/util/asyncIterableToEvents.d.ts.map +1 -1
  264. package/lib/util/asyncIterableToEvents.js +76 -20
  265. package/lib/util/asyncIterableToEvents.js.map +1 -1
  266. package/lib/util/dataColumns.d.ts +1 -1
  267. package/lib/util/dataColumns.d.ts.map +1 -1
  268. package/lib/util/dataColumns.js +4 -1
  269. package/lib/util/dataColumns.js.map +1 -1
  270. package/lib/util/eventLoop.d.ts +3 -3
  271. package/lib/util/eventLoop.d.ts.map +1 -1
  272. package/lib/util/eventLoop.js +3 -3
  273. package/lib/util/eventLoop.js.map +1 -1
  274. package/package.json +27 -27
  275. package/src/api/impl/beacon/blocks/index.ts +53 -28
  276. package/src/api/impl/beacon/pool/index.ts +10 -8
  277. package/src/api/impl/beacon/state/utils.ts +2 -1
  278. package/src/api/impl/debug/index.ts +6 -2
  279. package/src/api/impl/validator/index.ts +122 -66
  280. package/src/chain/ColumnReconstructionTracker.ts +5 -0
  281. package/src/chain/archiveStore/historicalState/getHistoricalState.ts +9 -0
  282. package/src/chain/archiveStore/utils/archiveBlocks.ts +1 -1
  283. package/src/chain/archiveStore/utils/pruneHistory.ts +9 -4
  284. package/src/chain/blocks/importExecutionPayload.ts +9 -2
  285. package/src/chain/blocks/index.ts +3 -31
  286. package/src/chain/chain.ts +112 -78
  287. package/src/chain/errors/attestationError.ts +11 -1
  288. package/src/chain/errors/executionPayloadBid.ts +9 -2
  289. package/src/chain/errors/executionPayloadEnvelope.ts +58 -0
  290. package/src/chain/interface.ts +1 -1
  291. package/src/chain/lightClient/index.ts +108 -142
  292. package/src/chain/opPools/opPool.ts +6 -6
  293. package/src/chain/prepareNextSlot.ts +347 -89
  294. package/src/chain/produceBlock/produceBlockBody.ts +69 -80
  295. package/src/chain/seenCache/seenAttesters.ts +1 -1
  296. package/src/chain/seenCache/seenBlockAttesters.ts +48 -6
  297. package/src/chain/seenCache/seenExecutionPayloadBids.ts +35 -15
  298. package/src/chain/validation/aggregateAndProof.ts +24 -9
  299. package/src/chain/validation/attestation.ts +31 -20
  300. package/src/chain/validation/attesterSlashing.ts +4 -2
  301. package/src/chain/validation/block.ts +9 -1
  302. package/src/chain/validation/executionPayloadBid.ts +60 -44
  303. package/src/chain/validation/executionPayloadEnvelope.ts +115 -8
  304. package/src/chain/validation/payloadAttestationMessage.ts +10 -0
  305. package/src/chain/validation/proposerSlashing.ts +4 -2
  306. package/src/chain/validation/signatureSets/contributionAndProof.ts +4 -6
  307. package/src/chain/validation/signatureSets/syncCommittee.ts +2 -3
  308. package/src/chain/validation/signatureSets/syncCommitteeContribution.ts +2 -3
  309. package/src/chain/validation/signatureSets/syncCommitteeSelectionProof.ts +2 -3
  310. package/src/chain/validation/syncCommittee.ts +3 -5
  311. package/src/chain/validation/syncCommitteeContributionAndProof.ts +3 -3
  312. package/src/chain/validation/voluntaryExit.ts +44 -6
  313. package/src/chain/validatorMonitor.ts +43 -43
  314. package/src/execution/engine/blockHash.ts +27 -0
  315. package/src/execution/engine/http.ts +18 -10
  316. package/src/execution/engine/interface.ts +18 -3
  317. package/src/execution/engine/jsonRpcHttpClient.ts +26 -14
  318. package/src/execution/engine/jsonRpcTransport.ts +8 -4
  319. package/src/execution/engine/mock.ts +13 -8
  320. package/src/execution/engine/payloadIdCache.ts +12 -4
  321. package/src/execution/engine/restHttpClient.ts +17 -11
  322. package/src/execution/engine/restTransport.ts +5 -4
  323. package/src/execution/engine/signal.ts +28 -0
  324. package/src/execution/engine/transport.ts +3 -2
  325. package/src/index.ts +6 -1
  326. package/src/metrics/metrics/beacon.ts +9 -0
  327. package/src/metrics/metrics/lodestar.ts +5 -0
  328. package/src/network/core/events.ts +12 -0
  329. package/src/network/core/networkCoreWorkerHandler.ts +6 -2
  330. package/src/network/gossip/gossipsub.ts +6 -2
  331. package/src/network/gossip/topic.ts +1 -14
  332. package/src/network/network.ts +39 -13
  333. package/src/network/peers/peerManager.ts +26 -2
  334. package/src/network/peers/utils/prioritizePeers.ts +14 -1
  335. package/src/network/processor/gossipHandlers.ts +25 -13
  336. package/src/network/processor/gossipValidatorFn.ts +4 -0
  337. package/src/network/processor/index.ts +7 -2
  338. package/src/network/reqresp/handlers/dataColumnSidecarsByRange.ts +1 -1
  339. package/src/network/reqresp/handlers/dataColumnSidecarsByRoot.ts +1 -1
  340. package/src/network/reqresp/utils/collect.ts +16 -8
  341. package/src/network/reqresp/utils/collectSequentialBlocksInRange.ts +3 -2
  342. package/src/sync/range/batch.ts +33 -0
  343. package/src/sync/range/chain.ts +72 -17
  344. package/src/sync/range/range.ts +57 -3
  345. package/src/sync/range/utils/batches.ts +38 -13
  346. package/src/sync/range/utils/peerBalancer.ts +4 -1
  347. package/src/sync/types.ts +13 -0
  348. package/src/sync/unknownBlock.ts +389 -29
  349. package/src/sync/utils/downloadByRange.ts +89 -29
  350. package/src/sync/utils/downloadByRoot.ts +75 -7
  351. package/src/util/asyncIterableToEvents.ts +100 -21
  352. package/src/util/dataColumns.ts +4 -1
  353. package/src/util/eventLoop.ts +3 -3
@@ -89,7 +89,7 @@ import {validateGossipProposerPreferences} from "../../chain/validation/proposer
89
89
  import {OpSource} from "../../chain/validatorMonitor.js";
90
90
  import {Metrics} from "../../metrics/index.js";
91
91
  import {getBlobKzgCommitments, getDataColumnSidecarSlot} from "../../util/dataColumns.js";
92
- import {callImmediate, callInNextEventLoop} from "../../util/eventLoop.js";
92
+ import {callAfterIO, callInNextEventLoop} from "../../util/eventLoop.js";
93
93
  import {INetworkCore} from "../core/index.js";
94
94
  import {NetworkEventBus} from "../events.js";
95
95
  import {
@@ -269,6 +269,16 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
269
269
  // The block is retained for unknown parent sync without full validation. Authenticate it first, this
270
270
  // does not need the parent state
271
271
  const proposerIndex = signedBlock.message.proposerIndex;
272
+ // An active proposer missing from the cache comes from a branch that finalized validators this node never
273
+ // processed, range sync recovers that branch from peer status
274
+ if (proposerIndex >= chain.pubkeyCache.size) {
275
+ throw new BlockGossipError(GossipAction.REJECT, {
276
+ code: BlockErrorCode.UNKNOWN_PROPOSER,
277
+ slot,
278
+ root: blockRootHex,
279
+ proposerIndex,
280
+ });
281
+ }
272
282
  await verifyBlockProposerSignature(chain, signedBlock, blockRootHex);
273
283
  chain.seenBlockProposers.observeBlockRoot(
274
284
  slot,
@@ -676,7 +686,7 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
676
686
  try {
677
687
  const blockInput = await validateBeaconBlock(signedBlock, topic.boundary.fork, peerIdStr, seenTimestampSec);
678
688
  // Runs after the validation result is reported, except with `network.useWorker: false`
679
- callImmediate(() => {
689
+ callAfterIO(() => {
680
690
  try {
681
691
  chain.serializedCache.set(signedBlock, serializedData);
682
692
  handleValidBeaconBlock(blockInput, peerIdStr, seenTimestampSec);
@@ -1301,13 +1311,16 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
1301
1311
  }
1302
1312
  }
1303
1313
 
1304
- chain.forkChoice.notifyPtcMessages(
1305
- toRootHex(payloadAttestationMessage.data.beaconBlockRoot),
1306
- payloadAttestationMessage.data.slot,
1307
- validationResult.validatorCommitteeIndices,
1308
- payloadAttestationMessage.data.payloadPresent,
1309
- payloadAttestationMessage.data.blobDataAvailable
1310
- );
1314
+ // Gossip accepts adjacent slots within the clock disparity but fork choice only counts the current slot
1315
+ if (payloadAttestationMessage.data.slot === chain.clock.currentSlot) {
1316
+ chain.forkChoice.notifyPtcMessages(
1317
+ toRootHex(payloadAttestationMessage.data.beaconBlockRoot),
1318
+ payloadAttestationMessage.data.slot,
1319
+ validationResult.validatorCommitteeIndices,
1320
+ payloadAttestationMessage.data.payloadPresent,
1321
+ payloadAttestationMessage.data.blobDataAvailable
1322
+ );
1323
+ }
1311
1324
 
1312
1325
  chain.emitter.emit(routes.events.EventType.payloadAttestationMessage, {
1313
1326
  version: config.getForkName(payloadAttestationMessage.data.slot),
@@ -1422,12 +1435,11 @@ function getSequentialHandlers(modules: ValidatorFnsModules, options: GossipHand
1422
1435
  try {
1423
1436
  metrics?.inclusionListsValid.inc({source: InclusionListSource.gossip});
1424
1437
  metrics?.inclusionListsValidSize.inc(totalBytes);
1425
- // Timely only if received within its own slot before the deadline, so a list for the next slot that
1426
- // passed validation under clock disparity is untimely. Late lists are still stored, marked untimely
1438
+ // A list received before its slot is timely, the spec delays it until the slot starts. Only gossip
1439
+ // validation bounds how early a list can be. Late lists are still stored, marked untimely
1427
1440
  const secFromSlot = chain.clock.secFromSlot(slot, seenTimestampSec);
1428
1441
  metrics?.inclusionListArrivalTime.observe(secFromSlot);
1429
- const isTimely =
1430
- secFromSlot >= 0 && secFromSlot * 1000 < config.getInclusionListDueMs(config.getForkName(slot));
1442
+ const isTimely = secFromSlot * 1000 < config.getInclusionListDueMs(config.getForkName(slot));
1431
1443
 
1432
1444
  const insertOutcome = chain.inclusionListStore.process(signedInclusionList, committeeIndices, isTimely);
1433
1445
  metrics?.inclusionListStore.insertOutcome.inc({insertOutcome});
@@ -12,6 +12,7 @@ import {
12
12
  ExecutionPayloadEnvelopeErrorCode,
13
13
  GossipAction,
14
14
  GossipActionError,
15
+ GossipErrorCode,
15
16
  InclusionListErrorCode,
16
17
  PayloadAttestationErrorCode,
17
18
  ProposerPreferencesErrorCode,
@@ -116,6 +117,9 @@ const gossipRejectPeerAction: Record<GossipType, RejectPeerActionRule> = {
116
117
  };
117
118
 
118
119
  export function rejectPeerAction(type: GossipType, code: string): PeerAction {
120
+ if (code === GossipErrorCode.INVALID_SERIALIZED_BYTES_ERROR_CODE) {
121
+ return PeerAction.LowToleranceError;
122
+ }
119
123
  const rule = gossipRejectPeerAction[type];
120
124
  return rule.byCode?.[code] ?? rule.default;
121
125
  }
@@ -1,7 +1,7 @@
1
1
  import {TopicValidatorResult} from "@libp2p/gossipsub";
2
2
  import {routes} from "@lodestar/api";
3
3
  import {ForkSeq, NUMBER_OF_COLUMNS, isForkPostGloas} from "@lodestar/params";
4
- import {computeStartSlotAtEpoch} from "@lodestar/state-transition";
4
+ import {computeEpochAtSlot, computeStartSlotAtEpoch} from "@lodestar/state-transition";
5
5
  import {RootHex, Slot, SlotRootHex} from "@lodestar/types";
6
6
  import {Logger, MapDef, mapValues, sleep} from "@lodestar/utils";
7
7
  import {BlockInputSource} from "../../chain/blocks/blockInput/types.js";
@@ -947,8 +947,13 @@ export class NetworkProcessor {
947
947
  this.bufferedRootsBySlot.delete(slot);
948
948
  }
949
949
 
950
+ // A slot's search budget lives as long as gossip accepts messages for it, a pruned budget would start over
951
+ const minSearchedSlot = Math.min(
952
+ clockSlot - DEFAULT_EARLIEST_PERMISSIBLE_SLOT_DISTANCE,
953
+ computeStartSlotAtEpoch(computeEpochAtSlot(clockSlot) - 1)
954
+ );
950
955
  for (const slot of this.searchedRootsBySlot.keys()) {
951
- if (slot <= minSlot) this.searchedRootsBySlot.delete(slot);
956
+ if (slot < minSearchedSlot) this.searchedRootsBySlot.delete(slot);
952
957
  }
953
958
 
954
959
  for (const [peer, slot] of this.fatalPeers) {
@@ -216,7 +216,7 @@ export function validateDataColumnSidecarsByRangeRequest(
216
216
  throw new ResponseError(RespStatus.INVALID_REQUEST, "startSlot < genesis");
217
217
  }
218
218
 
219
- // Spec: [max(compute_blob_data_retention_start_epoch(current_epoch), FULU_FORK_EPOCH), current_epoch]
219
+ // Spec: [max(current_epoch - MIN_EPOCHS_FOR_DATA_COLUMN_SIDECARS_REQUESTS, FULU_FORK_EPOCH), current_epoch]
220
220
  const minimumRequestEpoch = Math.max(getBlobDataRetentionStartEpoch(config, currentEpoch), config.FULU_FORK_EPOCH);
221
221
  if (computeEpochAtSlot(startSlot) < minimumRequestEpoch) {
222
222
  throw new ResponseError(RespStatus.RESOURCE_UNAVAILABLE, "startSlot is before the blob data retention window");
@@ -19,7 +19,7 @@ export async function* onDataColumnSidecarsByRoot(
19
19
  peerId: PeerId,
20
20
  peerClient: string
21
21
  ): AsyncIterable<ResponseOutgoing> {
22
- // SPEC: minimum_request_epoch = max(compute_blob_data_retention_start_epoch(current_epoch), FULU_FORK_EPOCH)
22
+ // SPEC: minimum_request_epoch = max(current_epoch - MIN_EPOCHS_FOR_DATA_COLUMN_SIDECARS_REQUESTS, FULU_FORK_EPOCH)
23
23
  const currentEpoch = chain.clock.currentEpoch;
24
24
  const minimumRequestEpoch = Math.max(
25
25
  getBlobDataRetentionStartEpoch(chain.config, currentEpoch),
@@ -12,11 +12,12 @@ import {ResponseTypeGetter} from "../types.js";
12
12
  */
13
13
  export async function collectExactOneTyped<T>(
14
14
  source: AsyncIterable<ResponseIncoming>,
15
- typeFn: ResponseTypeGetter<T>
15
+ typeFn: ResponseTypeGetter<T>,
16
+ onInvalidResponse?: (chunk: ResponseIncoming) => void
16
17
  ): Promise<T> {
17
18
  for await (const chunk of source) {
18
19
  const type = typeFn(chunk.fork, chunk.protocolVersion);
19
- const response = sszDeserializeResponse(type, chunk.data);
20
+ const response = sszDeserializeResponse(type, chunk, onInvalidResponse);
20
21
  return response;
21
22
  }
22
23
  throw new RequestError({code: RequestErrorCode.EMPTY_RESPONSE});
@@ -33,13 +34,14 @@ export async function collectMaxResponseTyped<T>(
33
34
  source: AsyncIterable<ResponseIncoming>,
34
35
  maxResponses: number,
35
36
  typeFn: ResponseTypeGetter<T>,
36
- serializedCache?: SerializedCache
37
+ serializedCache?: SerializedCache,
38
+ onInvalidResponse?: (chunk: ResponseIncoming) => void
37
39
  ): Promise<T[]> {
38
40
  // else: zero or more responses
39
41
  const responses: T[] = [];
40
42
  for await (const chunk of source) {
41
43
  const type = typeFn(chunk.fork, chunk.protocolVersion);
42
- const response = sszDeserializeResponse(type, chunk.data);
44
+ const response = sszDeserializeResponse(type, chunk, onInvalidResponse);
43
45
  // optionally cache the serialized response if the cache is available
44
46
  serializedCache?.set(response as object, chunk.data);
45
47
  responses.push(response);
@@ -62,13 +64,14 @@ export async function collectMaxResponseTypedWithBytes<T>(
62
64
  source: AsyncIterable<ResponseIncoming>,
63
65
  maxResponses: number,
64
66
  typeFn: ResponseTypeGetter<T>,
65
- serializedCache?: SerializedCache
67
+ serializedCache?: SerializedCache,
68
+ onInvalidResponse?: (chunk: ResponseIncoming) => void
66
69
  ): Promise<T[]> {
67
70
  // else: zero or more responses
68
71
  const responses: T[] = [];
69
72
  for await (const chunk of source) {
70
73
  const type = typeFn(chunk.fork, chunk.protocolVersion);
71
- const data = sszDeserializeResponse(type, chunk.data);
74
+ const data = sszDeserializeResponse(type, chunk, onInvalidResponse);
72
75
  responses.push(data);
73
76
  // optionally cache the serialized response if the cache is available
74
77
  serializedCache?.set(data as object, chunk.data);
@@ -81,10 +84,15 @@ export async function collectMaxResponseTypedWithBytes<T>(
81
84
  }
82
85
 
83
86
  /** Light wrapper on type to wrap deserialize errors */
84
- export function sszDeserializeResponse<T>(type: Type<T>, bytes: Uint8Array): T {
87
+ export function sszDeserializeResponse<T>(
88
+ type: Type<T>,
89
+ chunk: ResponseIncoming,
90
+ onInvalidResponse?: (chunk: ResponseIncoming) => void
91
+ ): T {
85
92
  try {
86
- return type.deserialize(bytes);
93
+ return type.deserialize(chunk.data);
87
94
  } catch (e) {
95
+ onInvalidResponse?.(chunk);
88
96
  throw new RequestError({code: RequestErrorCode.INVALID_RESPONSE_SSZ, errorMessage: (e as Error).message});
89
97
  }
90
98
  }
@@ -12,13 +12,14 @@ import {sszDeserializeResponse} from "./collect.js";
12
12
  export async function collectSequentialBlocksInRange(
13
13
  blockStream: AsyncIterable<ResponseIncoming>,
14
14
  {count, startSlot}: Pick<phase0.BeaconBlocksByRangeRequest, "count" | "startSlot">,
15
- serializedCache?: SerializedCache
15
+ serializedCache?: SerializedCache,
16
+ onInvalidResponse?: (chunk: ResponseIncoming) => void
16
17
  ): Promise<SignedBeaconBlock[]> {
17
18
  const blocks: SignedBeaconBlock[] = [];
18
19
 
19
20
  for await (const chunk of blockStream) {
20
21
  const blockType = responseSszTypeByMethod[ReqRespMethod.BeaconBlocksByRange](chunk.fork, chunk.protocolVersion);
21
- const block = sszDeserializeResponse(blockType, chunk.data);
22
+ const block = sszDeserializeResponse(blockType, chunk, onInvalidResponse);
22
23
 
23
24
  const blockSlot = block.message.slot;
24
25
 
@@ -430,6 +430,19 @@ export class Batch {
430
430
  return [...this.failedProcessingAttempts, ...this.executionErrorAttempts].filter((a) => a.peerAttributable);
431
431
  }
432
432
 
433
+ /**
434
+ * How many failed processing/execution attempts each peer took part in, peer-attributable or not
435
+ */
436
+ getTriedPeerCounts(): Map<PeerIdStr, number> {
437
+ const counts = new Map<PeerIdStr, number>();
438
+ for (const attempt of [...this.failedProcessingAttempts, ...this.executionErrorAttempts]) {
439
+ for (const peer of attempt.peers) {
440
+ counts.set(peer, (counts.get(peer) ?? 0) + 1);
441
+ }
442
+ }
443
+ return counts;
444
+ }
445
+
433
446
  /**
434
447
  * True only if the peer has already returned a successful response for the current request.
435
448
  * A by_range success may update `this.requests` to parent_payload, and the same peer is then
@@ -633,6 +646,26 @@ export class Batch {
633
646
  };
634
647
  }
635
648
 
649
+ /**
650
+ * Downloading -> AwaitingDownload
651
+ *
652
+ * The batch may hold an evicted invalid block, drop every downloaded block and request the whole batch again
653
+ */
654
+ downloadingInvalidBlock(peer: PeerIdStr): void {
655
+ if (this.state.status !== BatchStatus.Downloading) {
656
+ throw new BatchError(this.wrongStatusErrorType(BatchStatus.Downloading));
657
+ }
658
+
659
+ this.failedDownloadAttempts.push(peer);
660
+ if (this.failedDownloadAttempts.length > MAX_BATCH_DOWNLOAD_ATTEMPTS) {
661
+ throw new BatchError(this.errorType({code: BatchErrorCode.MAX_DOWNLOAD_ATTEMPTS}));
662
+ }
663
+
664
+ this.successfulDownloads.clear();
665
+ this.state = {status: BatchStatus.AwaitingDownload, blocks: [], payloadEnvelopes: null};
666
+ this.resetRequests();
667
+ }
668
+
636
669
  /**
637
670
  * Downloading -> AwaitingDownload (without counting as a failed attempt).
638
671
  * Used when the peer rate-limited us — the request was never actually served.
@@ -1,5 +1,5 @@
1
1
  import {ChainForkConfig} from "@lodestar/config";
2
- import {Epoch, Root, Slot} from "@lodestar/types";
2
+ import {Epoch, Root, RootHex, Slot} from "@lodestar/types";
3
3
  import {ErrorAborted, LodestarError, Logger, prettyPrintIndices, toRootHex} from "@lodestar/utils";
4
4
  import {isBlockInputColumns} from "../../chain/blocks/blockInput/blockInput.js";
5
5
  import {BlockInputErrorCode} from "../../chain/blocks/blockInput/errors.js";
@@ -68,6 +68,8 @@ export type SyncChainFns = {
68
68
  onEnd: (err: Error | null, target: ChainTarget | null) => void;
69
69
  /** Deletes an array of BlockInputs from the BlockInputCache */
70
70
  pruneBlockInputs: (blockInputs: IBlockInput[]) => void;
71
+ /** Returns true if the block is known to fork choice */
72
+ hasBlock: (blockRoot: Root) => boolean;
71
73
  };
72
74
 
73
75
  /**
@@ -81,6 +83,15 @@ export type ChainTarget = {
81
83
 
82
84
  export class SyncChainStartError extends Error {}
83
85
 
86
+ export enum SyncChainErrorCode {
87
+ /** The terminal batch has 0 blocks but the target block is not known */
88
+ MISSING_TARGET_BLOCK = "SYNC_CHAIN_ERROR_MISSING_TARGET_BLOCK",
89
+ }
90
+
91
+ type SyncChainErrorType = {code: SyncChainErrorCode.MISSING_TARGET_BLOCK; targetSlot: Slot; targetRoot: RootHex};
92
+
93
+ export class SyncChainError extends LodestarError<SyncChainErrorType> {}
94
+
84
95
  export type SyncChainDebugState = {
85
96
  targetRoot: string | null;
86
97
  targetSlot: number | null;
@@ -136,6 +147,7 @@ export class SyncChain {
136
147
  private readonly reportPeer: SyncChainFns["reportPeer"];
137
148
  private readonly getConnectedPeerSyncMeta: SyncChainFns["getConnectedPeerSyncMeta"];
138
149
  private readonly pruneBlockInputs: SyncChainFns["pruneBlockInputs"];
150
+ private readonly hasBlock: SyncChainFns["hasBlock"];
139
151
 
140
152
  /** AsyncIterable that guarantees processChainSegment is run only at once at anytime */
141
153
  private readonly batchProcessor = new ItTrigger();
@@ -178,6 +190,7 @@ export class SyncChain {
178
190
  this.downloadByRange = fns.downloadByRange;
179
191
  this.reportPeer = fns.reportPeer;
180
192
  this.pruneBlockInputs = fns.pruneBlockInputs;
193
+ this.hasBlock = fns.hasBlock;
181
194
  this.getConnectedPeerSyncMeta = fns.getConnectedPeerSyncMeta;
182
195
  this.config = config;
183
196
  this.clock = clock;
@@ -335,6 +348,32 @@ export class SyncChain {
335
348
 
336
349
  // Returns true if SyncChain has processed all possible blocks with slot <= target.slot
337
350
  if (isSyncChainDone(toArr(this.batches), this.lastEpochWithProcessBlocks, this.target.slot)) {
351
+ // A 0-block terminal batch is only trusted once the target block is known, otherwise a peer returning no
352
+ // blocks for the last range ends the chain short of its target
353
+ const lastAwaitingValidation = toArr(this.batches).findLast(
354
+ (b) => b.state.status === BatchStatus.AwaitingValidation
355
+ );
356
+ if (
357
+ lastAwaitingValidation !== undefined &&
358
+ lastAwaitingValidation.getBlocks().length === 0 &&
359
+ !this.hasBlock(this.target.root)
360
+ ) {
361
+ this.logger.verbose("Terminal 0-block batch without target block", {
362
+ id: this.logId,
363
+ ...lastAwaitingValidation.getMetadata(),
364
+ });
365
+ // Not peer attributable: throws MAX_PROCESSING_ATTEMPTS after MAX_BATCH_PROCESSING_ATTEMPTS without
366
+ // reporting any peer
367
+ lastAwaitingValidation.validationError(
368
+ new SyncChainError({
369
+ code: SyncChainErrorCode.MISSING_TARGET_BLOCK,
370
+ targetSlot: this.target.slot,
371
+ targetRoot: toRootHex(this.target.root),
372
+ })
373
+ );
374
+ this.triggerBatchDownloader();
375
+ continue;
376
+ }
338
377
  break;
339
378
  }
340
379
 
@@ -509,9 +548,12 @@ export class SyncChain {
509
548
  // if last processed epoch is n, we don't want to request batches with epoch > n + MAX_LOOK_AHEAD_EPOCHS
510
549
  // we should have enough batches to process in the buffer: n + 1, ..., n + MAX_LOOK_AHEAD_EPOCHS
511
550
  // let's focus on redownloading these batches first because it may have to reach different peers to get enough sampled columns
551
+ // Note: Don't count batches in the AwaitingValidation state, 0-block batches never advance
552
+ // lastEpochWithProcessBlocks so more than MAX_LOOK_AHEAD_EPOCHS of them in a row would stall sync
553
+ const pendingBatches = batches.filter((batch) => batch.state.status !== BatchStatus.AwaitingValidation);
512
554
  if (
513
- batches.length > 0 &&
514
- Math.max(...batches.map((b) => b.startEpoch)) >= this.lastEpochWithProcessBlocks + MAX_LOOK_AHEAD_EPOCHS
555
+ pendingBatches.length > 0 &&
556
+ Math.max(...pendingBatches.map((b) => b.startEpoch)) >= this.lastEpochWithProcessBlocks + MAX_LOOK_AHEAD_EPOCHS
515
557
  ) {
516
558
  return null;
517
559
  }
@@ -576,6 +618,7 @@ export class SyncChain {
576
618
  }
577
619
  }
578
620
  switch (errCode) {
621
+ case DownloadByRangeErrorCode.DATA_WITHOUT_BLOCKS:
579
622
  case DownloadByRangeErrorCode.EXTRA_BLOCKS:
580
623
  case DownloadByRangeErrorCode.OUT_OF_ORDER_BLOCKS:
581
624
  case DownloadByRangeErrorCode.OUT_OF_RANGE_BLOCKS:
@@ -602,6 +645,14 @@ export class SyncChain {
602
645
  this.scheduleRateLimitBackoffRetry();
603
646
  batch.downloadingRateLimited();
604
647
  this.triggerBatchDownloader();
648
+ } else if (
649
+ res.err instanceof DownloadByRangeError &&
650
+ res.err.type.code === DownloadByRangeErrorCode.INVALID_CACHED_BLOCK
651
+ ) {
652
+ if (res.err.type.blockPeer !== undefined) {
653
+ this.reportPeer(res.err.type.blockPeer, PeerAction.LowToleranceError, res.err.message);
654
+ }
655
+ batch.downloadingInvalidBlock(res.err.type.blockPeer ?? peer.peerId); // Throws after MAX_DOWNLOAD_ATTEMPTS
605
656
  } else {
606
657
  batch.downloadingError(peer.peerId); // Throws after MAX_DOWNLOAD_ATTEMPTS
607
658
  }
@@ -714,39 +765,43 @@ export class SyncChain {
714
765
  } else {
715
766
  this.logger.verbose("Batch process error", logCtx, res.err);
716
767
 
717
- const invalidatePreviousBatches = (): number => {
718
- let invalidatedCount = 0;
768
+ // advanceChain() drops every batch before the last batch with blocks, so the AwaitingValidation batches before
769
+ // `batch` are that batch followed by 0-block batches, see classifyProcessingFault(). With no batch with blocks
770
+ // yet, fall back to the first 0-block batch so a wrong 0-block answer at the start of the chain is retried
771
+ const awaitingValidationBefore = toArr(this.batches).filter(
772
+ (b) => b.startEpoch < batch.startEpoch && b.state.status === BatchStatus.AwaitingValidation
773
+ );
774
+ const parentBatch =
775
+ awaitingValidationBefore.findLast((b) => b.getBlocks().length > 0) ?? awaitingValidationBefore[0];
776
+ // The 0-block batches after `parentBatch` are invalidated with it: an AwaitingValidation batch must not follow a
777
+ // batch that is downloaded again, see validateBatchesStatus()
778
+ const invalidateFromParentBatch = (faultyParentBatch: Batch): void => {
719
779
  for (const pendingBatch of this.batches.values()) {
720
780
  if (
781
+ pendingBatch.startEpoch >= faultyParentBatch.startEpoch &&
721
782
  pendingBatch.startEpoch < batch.startEpoch &&
722
783
  pendingBatch.state.status === BatchStatus.AwaitingValidation
723
784
  ) {
724
785
  this.logger.verbose("Batch validation error", {id: this.logId, ...pendingBatch.getMetadata()});
725
786
  pendingBatch.validationError(res.err);
726
- invalidatedCount++;
727
787
  }
728
788
  }
729
- return invalidatedCount;
730
789
  };
731
790
 
732
- const prevBatch = this.batches.get(batch.startEpoch - EPOCHS_PER_BATCH);
733
- switch (classifyProcessingFault(res.err, batch, prevBatch)) {
791
+ const fault = classifyProcessingFault(res.err, batch, parentBatch);
792
+ switch (fault.kind) {
734
793
  case ProcessingFaultKind.CurrentBatch:
735
794
  batch.processingError(res.err);
736
795
  break;
737
796
 
738
- case ProcessingFaultKind.PreviousBatch:
739
- // If no previous batch was invalidated, it means the error is on this batch
740
- if (invalidatePreviousBatches() === 0) {
741
- batch.processingError(res.err);
742
- } else {
743
- batch.retainForReprocessing();
744
- }
797
+ case ProcessingFaultKind.ParentBatch:
798
+ invalidateFromParentBatch(fault.parentBatch);
799
+ batch.retainForReprocessing();
745
800
  break;
746
801
 
747
802
  case ProcessingFaultKind.Ambiguous:
748
803
  batch.processingError(res.err);
749
- invalidatePreviousBatches();
804
+ invalidateFromParentBatch(fault.parentBatch);
750
805
  break;
751
806
  }
752
807
  }
@@ -3,13 +3,20 @@ import {StrictEventEmitter} from "strict-event-emitter-types";
3
3
  import {BeaconConfig} from "@lodestar/config";
4
4
  import {IBeaconStateViewGloas, computeStartSlotAtEpoch, isStatePostGloas} from "@lodestar/state-transition";
5
5
  import {Epoch, Status, fulu, ssz} from "@lodestar/types";
6
- import {Logger, byteArrayEquals, prettyPrintIndices, toRootHex} from "@lodestar/utils";
6
+ import {Logger, byteArrayEquals, prettyPrintIndices, toHex, toRootHex} from "@lodestar/utils";
7
7
  import {IBlockInput} from "../../chain/blocks/blockInput/types.js";
8
8
  import {PayloadError, PayloadErrorCode} from "../../chain/blocks/importExecutionPayload.js";
9
9
  import {AttestationImportOpt, ImportBlockOpts} from "../../chain/blocks/index.js";
10
10
  import {assertLinearChainSegment} from "../../chain/blocks/utils/chainSegment.js";
11
- import {BlockError} from "../../chain/errors/index.js";
11
+ import {
12
+ BlockError,
13
+ BlockErrorCode,
14
+ BlockGossipError,
15
+ DataColumnSidecarErrorCode,
16
+ DataColumnSidecarValidationError,
17
+ } from "../../chain/errors/index.js";
12
18
  import {IBeaconChain} from "../../chain/index.js";
19
+ import {verifyBlockProposerSignature} from "../../chain/validation/block.js";
13
20
  import {Metrics} from "../../metrics/index.js";
14
21
  import {INetwork} from "../../network/index.js";
15
22
  import {PeerIdStr} from "../../util/peerId.js";
@@ -291,7 +298,7 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
291
298
  ...requests,
292
299
  });
293
300
  const {responses, payloadEnvelopes: downloadedPayloadEnvelopes} = result;
294
- const {blocks, payloadEnvelopes} = cacheByRangeResponses({
301
+ const {blocks, payloadEnvelopes, signatureMismatch} = cacheByRangeResponses({
295
302
  cache: this.chain.seenBlockInputCache,
296
303
  seenPayloadEnvelopeInputCache: this.chain.seenPayloadEnvelopeInputCache,
297
304
  peerIdStr: peer.peerId,
@@ -304,6 +311,52 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
304
311
  seenTimestampSec: Date.now() / 1000,
305
312
  });
306
313
 
314
+ if (signatureMismatch !== null) {
315
+ const {blockInput, columnSidecar} = signatureMismatch;
316
+ const block = blockInput.getBlock();
317
+ let isValidBlockSignature: boolean | null = true;
318
+ try {
319
+ await verifyBlockProposerSignature(this.chain, block, blockInput.blockRootHex);
320
+ } catch (e) {
321
+ isValidBlockSignature =
322
+ e instanceof BlockGossipError && e.type.code === BlockErrorCode.PROPOSAL_SIGNATURE_INVALID ? false : null;
323
+ }
324
+
325
+ if (isValidBlockSignature) {
326
+ throw new DataColumnSidecarValidationError(
327
+ {
328
+ code: DataColumnSidecarErrorCode.INCORRECT_BLOCK,
329
+ slot: blockInput.slot,
330
+ columnIndex: columnSidecar.index,
331
+ expected: toHex(block.signature),
332
+ actual: toHex(columnSidecar.signedBlockHeader.signature),
333
+ },
334
+ "DataColumnSidecar header signature doesn't match block signature"
335
+ );
336
+ }
337
+
338
+ // Later downloads reuse a cached block, evict it and the other unverified blocks of a peer
339
+ // proven to serve invalid signatures
340
+ const blockPeer = isValidBlockSignature === false ? blockInput.getBlockSource().peerIdStr : undefined;
341
+ const cache = this.chain.seenBlockInputCache;
342
+ for (const b of blocks) {
343
+ const isSuspect = b === blockInput || (blockPeer !== undefined && b.getBlockSource().peerIdStr === blockPeer);
344
+ if (
345
+ isSuspect &&
346
+ cache.get(b.blockRootHex) === b &&
347
+ !cache.isVerifiedProposerSignature(b.slot, b.blockRootHex, b.getBlock().signature)
348
+ ) {
349
+ cache.remove(b.blockRootHex);
350
+ }
351
+ }
352
+ throw new DownloadByRangeError({
353
+ code: DownloadByRangeErrorCode.INVALID_CACHED_BLOCK,
354
+ slot: blockInput.slot,
355
+ blockRoot: blockInput.blockRootHex,
356
+ blockPeer,
357
+ });
358
+ }
359
+
307
360
  const segmentBlocks = blocks.filter((b) => b.hasBlock()).sort((a, b) => a.slot - b.slot);
308
361
  const envelopeSlots = payloadEnvelopes
309
362
  ? Array.from(payloadEnvelopes.entries())
@@ -408,6 +461,7 @@ export class RangeSync extends (EventEmitter as {new (): RangeSyncEmitter}) {
408
461
  reportPeer: this.reportPeer,
409
462
  getConnectedPeerSyncMeta: this.getConnectedPeerSyncMeta,
410
463
  pruneBlockInputs: this.pruneBlockInputs,
464
+ hasBlock: (blockRoot) => this.chain.forkChoice.hasBlock(blockRoot),
411
465
  onEnd: this.onSyncChainEnd,
412
466
  },
413
467
  {
@@ -125,39 +125,64 @@ export function isSyncChainDone(batches: Batch[], lastEpochWithProcessBlocks: Ep
125
125
  export enum ProcessingFaultKind {
126
126
  /** This batch's own blocks are bad or incomplete, so redownload this batch. */
127
127
  CurrentBatch = "CurrentBatch",
128
- /** This batch is valid, but a previous batch did not deliver the parent. */
129
- PreviousBatch = "PreviousBatch",
130
- /** The fault could be in this batch or a previous batch, so hedge both ways. */
128
+ /** This batch is valid, but the parent batch did not deliver the parent. */
129
+ ParentBatch = "ParentBatch",
130
+ /** The fault could be in this batch or the parent batch, so hedge both ways. */
131
131
  Ambiguous = "Ambiguous",
132
132
  }
133
133
 
134
+ export type ProcessingFault =
135
+ | {kind: ProcessingFaultKind.CurrentBatch}
136
+ | {kind: ProcessingFaultKind.ParentBatch; parentBatch: Batch}
137
+ | {kind: ProcessingFaultKind.Ambiguous; parentBatch: Batch};
138
+
134
139
  /**
135
140
  * Classify a processChainSegment error for a batch so range sync only redownloads
136
141
  * the batch or batches that could actually be at fault.
137
142
  * Note that range sync is supposed to only handle linear chain, for forky condition we'll handle it via backward sync
138
143
  * in BlockInputSync or the upcoming/TODO beacon_blocks_by_head req/resp.
144
+ *
145
+ * `parentBatch` is the last batch with blocks before `batch`, it may be followed by 0-block batches. If no batch with
146
+ * blocks awaits validation, it is the first 0-block batch before `batch`.
147
+ * Epochs with 0 blocks usually happen on devnets, during periods of poor liveness when no proposer gets a block
148
+ * included for whole epochs. A wrong 0-block response only shows up as an unknown parent in `batch`, so with 0-block
149
+ * batches in between the fault is never pinned on `batch` alone: `parentBatch` and the 0-block batches after it are
150
+ * downloaded again.
139
151
  */
140
- export function classifyProcessingFault(err: Error, batch: Batch, prevBatch: Batch | undefined): ProcessingFaultKind {
152
+ export function classifyProcessingFault(err: Error, batch: Batch, parentBatch: Batch | undefined): ProcessingFault {
141
153
  if (!(err instanceof BlockError)) {
142
- return ProcessingFaultKind.CurrentBatch;
154
+ return {kind: ProcessingFaultKind.CurrentBatch};
143
155
  }
144
156
 
145
157
  const {code} = err.type;
146
158
  if (code !== BlockErrorCode.PARENT_BLOCK_UNKNOWN && code !== BlockErrorCode.PARENT_PAYLOAD_UNKNOWN) {
147
- return ProcessingFaultKind.CurrentBatch;
159
+ return {kind: ProcessingFaultKind.CurrentBatch};
160
+ }
161
+
162
+ if (parentBatch === undefined) {
163
+ return {kind: ProcessingFaultKind.CurrentBatch};
148
164
  }
149
165
 
150
166
  const firstErrorSlot = err.signedBlock.message.slot;
151
167
  if (firstErrorSlot === batch.startSlot) {
152
- // note that range sync is for linear chain, so this is clearly an issue of the previous batch
153
- return prevBatch === undefined ? ProcessingFaultKind.CurrentBatch : ProcessingFaultKind.PreviousBatch;
168
+ // note that range sync is for linear chain, so this is clearly an issue of the parent batch
169
+ return {kind: ProcessingFaultKind.ParentBatch, parentBatch};
154
170
  }
155
171
 
156
- const prevTailSlot = batch.startSlot - 1;
157
- const prevHasFullTail =
172
+ // `parentBatch` can be followed by 0-block batches, so its tail is the end of its own range
173
+ const parentTailSlot = parentBatch.startSlot + parentBatch.count - 1;
174
+ const parentHasFullTail =
158
175
  code === BlockErrorCode.PARENT_PAYLOAD_UNKNOWN
159
- ? (prevBatch?.getPayloadEnvelopes()?.get(prevTailSlot)?.hasPayloadEnvelope() ?? false)
160
- : (prevBatch?.getBlocks().some((b) => b.slot === prevTailSlot) ?? false);
176
+ ? (parentBatch.getPayloadEnvelopes()?.get(parentTailSlot)?.hasPayloadEnvelope() ?? false)
177
+ : parentBatch.getBlocks().some((b) => b.slot === parentTailSlot);
161
178
 
162
- return prevHasFullTail ? ProcessingFaultKind.CurrentBatch : ProcessingFaultKind.Ambiguous;
179
+ // With 0-block batches in between, it could be a wrong 0-block batch
180
+ const hasZeroBlockGap = parentTailSlot + 1 < batch.startSlot;
181
+
182
+ // Assumes the tail block / payload delivered by `parentBatch` is canonical. If it is orphaned, `parentBatch` is at
183
+ // fault: `batch` keeps failing until MAX_PROCESSING_ATTEMPTS and a new SyncChain is created.
184
+ if (parentHasFullTail && !hasZeroBlockGap) {
185
+ return {kind: ProcessingFaultKind.CurrentBatch};
186
+ }
187
+ return {kind: ProcessingFaultKind.Ambiguous, parentBatch};
163
188
  }
@@ -52,7 +52,7 @@ export class ChainPeersBalancer {
52
52
 
53
53
  /**
54
54
  * Return the most suitable peer to retry
55
- * Sort peers by (1) less active requests (2) most columns we need.
55
+ * Sort peers by (1) fewer failed attempts for this batch (2) less active requests (3) most columns we need.
56
56
  * Peers that failed this batch or already succeeded for the same request are excluded inside `filterPeers`.
57
57
  */
58
58
  bestPeerToRetryBatch(batch: Batch): PeerSyncMeta | undefined {
@@ -63,9 +63,12 @@ export class ChainPeersBalancer {
63
63
  // TODO(fulu): This is fulu specific and hinders our peer selection PreFulu
64
64
  const pendingDataColumns = columnsRequest?.columns ?? this.custodyConfig.sampledColumns;
65
65
  const eligiblePeers = this.filterPeers(batch, pendingDataColumns, false);
66
+ const triedPeerCounts = batch.getTriedPeerCounts();
66
67
 
67
68
  const sortedBestPeers = sortBy(
68
69
  eligiblePeers,
70
+ // prefer peers not tried for this batch yet
71
+ ({syncInfo}) => triedPeerCounts.get(syncInfo.peerId) ?? 0,
69
72
  ({syncInfo}) => this.activeRequestsByPeer.get(syncInfo.peerId) ?? 0, // prefer peers with least active req
70
73
  ({columns}) => -1 * columns // prefer peers with the most columns
71
74
  );