@lodestar/beacon-node 1.39.0-dev.882891d89c → 1.39.0-dev.b37f2bd1bd

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 (338) hide show
  1. package/lib/api/impl/beacon/blocks/utils.js +1 -1
  2. package/lib/api/impl/beacon/blocks/utils.js.map +1 -1
  3. package/lib/chain/blocks/verifyBlock.d.ts.map +1 -1
  4. package/lib/chain/blocks/verifyBlock.js +1 -1
  5. package/lib/chain/blocks/verifyBlock.js.map +1 -1
  6. package/lib/chain/blocks/verifyBlocksSignatures.d.ts +1 -2
  7. package/lib/chain/blocks/verifyBlocksSignatures.d.ts.map +1 -1
  8. package/lib/chain/blocks/verifyBlocksSignatures.js +2 -2
  9. package/lib/chain/blocks/verifyBlocksSignatures.js.map +1 -1
  10. package/lib/chain/chain.d.ts +4 -1
  11. package/lib/chain/chain.d.ts.map +1 -1
  12. package/lib/chain/chain.js +16 -8
  13. package/lib/chain/chain.js.map +1 -1
  14. package/lib/chain/genesis/genesis.d.ts +51 -0
  15. package/lib/chain/genesis/genesis.d.ts.map +1 -0
  16. package/lib/chain/genesis/genesis.js +123 -0
  17. package/lib/chain/genesis/genesis.js.map +1 -0
  18. package/lib/chain/genesis/interface.d.ts +13 -0
  19. package/lib/chain/genesis/interface.d.ts.map +1 -0
  20. package/lib/chain/genesis/interface.js +2 -0
  21. package/lib/chain/genesis/interface.js.map +1 -0
  22. package/lib/chain/initState.d.ts +14 -1
  23. package/lib/chain/initState.d.ts.map +1 -1
  24. package/lib/chain/initState.js +62 -1
  25. package/lib/chain/initState.js.map +1 -1
  26. package/lib/chain/interface.d.ts +2 -0
  27. package/lib/chain/interface.d.ts.map +1 -1
  28. package/lib/chain/interface.js.map +1 -1
  29. package/lib/chain/opPools/aggregatedAttestationPool.d.ts +4 -4
  30. package/lib/chain/opPools/aggregatedAttestationPool.d.ts.map +1 -1
  31. package/lib/chain/opPools/aggregatedAttestationPool.js +4 -4
  32. package/lib/chain/opPools/aggregatedAttestationPool.js.map +1 -1
  33. package/lib/chain/opPools/opPool.d.ts +0 -3
  34. package/lib/chain/opPools/opPool.d.ts.map +1 -1
  35. package/lib/chain/opPools/opPool.js +8 -9
  36. package/lib/chain/opPools/opPool.js.map +1 -1
  37. package/lib/chain/prepareNextSlot.d.ts +4 -0
  38. package/lib/chain/prepareNextSlot.d.ts.map +1 -1
  39. package/lib/chain/prepareNextSlot.js +21 -1
  40. package/lib/chain/prepareNextSlot.js.map +1 -1
  41. package/lib/chain/produceBlock/produceBlockBody.d.ts +1 -0
  42. package/lib/chain/produceBlock/produceBlockBody.d.ts.map +1 -1
  43. package/lib/chain/produceBlock/produceBlockBody.js +11 -8
  44. package/lib/chain/produceBlock/produceBlockBody.js.map +1 -1
  45. package/lib/chain/rewards/attestationsRewards.d.ts +1 -2
  46. package/lib/chain/rewards/attestationsRewards.d.ts.map +1 -1
  47. package/lib/chain/rewards/attestationsRewards.js +8 -8
  48. package/lib/chain/rewards/attestationsRewards.js.map +1 -1
  49. package/lib/chain/rewards/blockRewards.d.ts +1 -2
  50. package/lib/chain/rewards/blockRewards.d.ts.map +1 -1
  51. package/lib/chain/rewards/blockRewards.js +5 -5
  52. package/lib/chain/rewards/blockRewards.js.map +1 -1
  53. package/lib/chain/rewards/syncCommitteeRewards.d.ts +1 -2
  54. package/lib/chain/rewards/syncCommitteeRewards.d.ts.map +1 -1
  55. package/lib/chain/rewards/syncCommitteeRewards.js +2 -2
  56. package/lib/chain/rewards/syncCommitteeRewards.js.map +1 -1
  57. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts +1 -4
  58. package/lib/chain/stateCache/persistentCheckpointsCache.d.ts.map +1 -1
  59. package/lib/chain/stateCache/persistentCheckpointsCache.js +2 -4
  60. package/lib/chain/stateCache/persistentCheckpointsCache.js.map +1 -1
  61. package/lib/chain/validation/attesterSlashing.js +1 -1
  62. package/lib/chain/validation/attesterSlashing.js.map +1 -1
  63. package/lib/chain/validation/block.js +1 -1
  64. package/lib/chain/validation/block.js.map +1 -1
  65. package/lib/chain/validation/blsToExecutionChange.js +1 -1
  66. package/lib/chain/validation/proposerSlashing.js +1 -1
  67. package/lib/chain/validation/proposerSlashing.js.map +1 -1
  68. package/lib/chain/validation/signatureSets/aggregateAndProof.js +1 -1
  69. package/lib/chain/validation/signatureSets/aggregateAndProof.js.map +1 -1
  70. package/lib/chain/validation/signatureSets/contributionAndProof.d.ts +1 -2
  71. package/lib/chain/validation/signatureSets/contributionAndProof.d.ts.map +1 -1
  72. package/lib/chain/validation/signatureSets/contributionAndProof.js +2 -2
  73. package/lib/chain/validation/signatureSets/contributionAndProof.js.map +1 -1
  74. package/lib/chain/validation/signatureSets/syncCommittee.d.ts +1 -2
  75. package/lib/chain/validation/signatureSets/syncCommittee.d.ts.map +1 -1
  76. package/lib/chain/validation/signatureSets/syncCommittee.js +2 -2
  77. package/lib/chain/validation/signatureSets/syncCommittee.js.map +1 -1
  78. package/lib/chain/validation/signatureSets/syncCommitteeContribution.d.ts +1 -2
  79. package/lib/chain/validation/signatureSets/syncCommitteeContribution.d.ts.map +1 -1
  80. package/lib/chain/validation/signatureSets/syncCommitteeContribution.js +2 -2
  81. package/lib/chain/validation/signatureSets/syncCommitteeContribution.js.map +1 -1
  82. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.d.ts +1 -2
  83. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.d.ts.map +1 -1
  84. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.js +2 -1
  85. package/lib/chain/validation/signatureSets/syncCommitteeSelectionProof.js.map +1 -1
  86. package/lib/chain/validation/syncCommittee.js +1 -1
  87. package/lib/chain/validation/syncCommittee.js.map +1 -1
  88. package/lib/chain/validation/syncCommitteeContributionAndProof.d.ts.map +1 -1
  89. package/lib/chain/validation/syncCommitteeContributionAndProof.js +3 -3
  90. package/lib/chain/validation/syncCommitteeContributionAndProof.js.map +1 -1
  91. package/lib/chain/validation/voluntaryExit.js +1 -1
  92. package/lib/chain/validation/voluntaryExit.js.map +1 -1
  93. package/lib/db/beacon.d.ts +7 -3
  94. package/lib/db/beacon.d.ts.map +1 -1
  95. package/lib/db/beacon.js +12 -33
  96. package/lib/db/beacon.js.map +1 -1
  97. package/lib/db/buckets.d.ts +6 -12
  98. package/lib/db/buckets.d.ts.map +1 -1
  99. package/lib/db/buckets.js +1 -6
  100. package/lib/db/buckets.js.map +1 -1
  101. package/lib/db/interface.d.ts +7 -2
  102. package/lib/db/interface.d.ts.map +1 -1
  103. package/lib/db/repositories/depositDataRoot.d.ts +22 -0
  104. package/lib/db/repositories/depositDataRoot.d.ts.map +1 -0
  105. package/lib/db/repositories/depositDataRoot.js +62 -0
  106. package/lib/db/repositories/depositDataRoot.js.map +1 -0
  107. package/lib/db/repositories/depositEvent.d.ts +13 -0
  108. package/lib/db/repositories/depositEvent.d.ts.map +1 -0
  109. package/lib/db/repositories/depositEvent.js +27 -0
  110. package/lib/db/repositories/depositEvent.js.map +1 -0
  111. package/lib/db/repositories/eth1Data.d.ts +13 -0
  112. package/lib/db/repositories/eth1Data.d.ts.map +1 -0
  113. package/lib/db/repositories/eth1Data.js +26 -0
  114. package/lib/db/repositories/eth1Data.js.map +1 -0
  115. package/lib/db/repositories/index.d.ts +3 -0
  116. package/lib/db/repositories/index.d.ts.map +1 -1
  117. package/lib/db/repositories/index.js +3 -0
  118. package/lib/db/repositories/index.js.map +1 -1
  119. package/lib/db/single/index.d.ts +3 -0
  120. package/lib/db/single/index.d.ts.map +1 -0
  121. package/lib/db/single/index.js +3 -0
  122. package/lib/db/single/index.js.map +1 -0
  123. package/lib/db/single/preGenesisState.d.ts +16 -0
  124. package/lib/db/single/preGenesisState.d.ts.map +1 -0
  125. package/lib/db/single/preGenesisState.js +29 -0
  126. package/lib/db/single/preGenesisState.js.map +1 -0
  127. package/lib/db/single/preGenesisStateLastProcessedBlock.d.ts +14 -0
  128. package/lib/db/single/preGenesisStateLastProcessedBlock.d.ts.map +1 -0
  129. package/lib/db/single/preGenesisStateLastProcessedBlock.js +27 -0
  130. package/lib/db/single/preGenesisStateLastProcessedBlock.js.map +1 -0
  131. package/lib/eth1/errors.d.ts +66 -0
  132. package/lib/eth1/errors.d.ts.map +1 -0
  133. package/lib/eth1/errors.js +27 -0
  134. package/lib/eth1/errors.js.map +1 -0
  135. package/lib/eth1/eth1DataCache.d.ts +19 -0
  136. package/lib/eth1/eth1DataCache.d.ts.map +1 -0
  137. package/lib/eth1/eth1DataCache.js +19 -0
  138. package/lib/eth1/eth1DataCache.js.map +1 -0
  139. package/lib/eth1/eth1DepositDataTracker.d.ts +80 -0
  140. package/lib/eth1/eth1DepositDataTracker.d.ts.map +1 -0
  141. package/lib/eth1/eth1DepositDataTracker.js +317 -0
  142. package/lib/eth1/eth1DepositDataTracker.js.map +1 -0
  143. package/lib/eth1/eth1DepositsCache.d.ts +42 -0
  144. package/lib/eth1/eth1DepositsCache.d.ts.map +1 -0
  145. package/lib/eth1/eth1DepositsCache.js +119 -0
  146. package/lib/eth1/eth1DepositsCache.js.map +1 -0
  147. package/lib/eth1/index.d.ts +31 -0
  148. package/lib/eth1/index.d.ts.map +1 -0
  149. package/lib/eth1/index.js +71 -0
  150. package/lib/eth1/index.js.map +1 -0
  151. package/lib/eth1/interface.d.ts +74 -0
  152. package/lib/eth1/interface.d.ts.map +1 -0
  153. package/lib/eth1/interface.js +8 -0
  154. package/lib/eth1/interface.js.map +1 -0
  155. package/lib/eth1/options.d.ts +22 -0
  156. package/lib/eth1/options.d.ts.map +1 -0
  157. package/lib/eth1/options.js +8 -0
  158. package/lib/eth1/options.js.map +1 -0
  159. package/lib/eth1/provider/eth1Provider.d.ts +39 -0
  160. package/lib/eth1/provider/eth1Provider.d.ts.map +1 -0
  161. package/lib/eth1/provider/eth1Provider.js +147 -0
  162. package/lib/eth1/provider/eth1Provider.js.map +1 -0
  163. package/lib/{execution/engine → eth1/provider}/jsonRpcHttpClient.d.ts +1 -1
  164. package/lib/eth1/provider/jsonRpcHttpClient.d.ts.map +1 -0
  165. package/lib/eth1/provider/jsonRpcHttpClient.js.map +1 -0
  166. package/lib/eth1/provider/jwt.d.ts.map +1 -0
  167. package/lib/eth1/provider/jwt.js.map +1 -0
  168. package/lib/eth1/provider/utils.d.ts +65 -0
  169. package/lib/eth1/provider/utils.d.ts.map +1 -0
  170. package/lib/eth1/provider/utils.js +120 -0
  171. package/lib/eth1/provider/utils.js.map +1 -0
  172. package/lib/eth1/stream.d.ts +15 -0
  173. package/lib/eth1/stream.d.ts.map +1 -0
  174. package/lib/eth1/stream.js +54 -0
  175. package/lib/eth1/stream.js.map +1 -0
  176. package/lib/eth1/utils/depositContract.d.ts +14 -0
  177. package/lib/eth1/utils/depositContract.d.ts.map +1 -0
  178. package/lib/eth1/utils/depositContract.js +33 -0
  179. package/lib/eth1/utils/depositContract.js.map +1 -0
  180. package/lib/eth1/utils/deposits.d.ts +8 -0
  181. package/lib/eth1/utils/deposits.d.ts.map +1 -0
  182. package/lib/eth1/utils/deposits.js +47 -0
  183. package/lib/eth1/utils/deposits.js.map +1 -0
  184. package/lib/eth1/utils/eth1Data.d.ts +22 -0
  185. package/lib/eth1/utils/eth1Data.d.ts.map +1 -0
  186. package/lib/eth1/utils/eth1Data.js +77 -0
  187. package/lib/eth1/utils/eth1Data.js.map +1 -0
  188. package/lib/eth1/utils/eth1DepositEvent.d.ts +7 -0
  189. package/lib/eth1/utils/eth1DepositEvent.d.ts.map +1 -0
  190. package/lib/eth1/utils/eth1DepositEvent.js +13 -0
  191. package/lib/eth1/utils/eth1DepositEvent.js.map +1 -0
  192. package/lib/eth1/utils/eth1Vote.d.ts +17 -0
  193. package/lib/eth1/utils/eth1Vote.d.ts.map +1 -0
  194. package/lib/eth1/utils/eth1Vote.js +111 -0
  195. package/lib/eth1/utils/eth1Vote.js.map +1 -0
  196. package/lib/eth1/utils/groupDepositEventsByBlock.d.ts +9 -0
  197. package/lib/eth1/utils/groupDepositEventsByBlock.d.ts.map +1 -0
  198. package/lib/eth1/utils/groupDepositEventsByBlock.js +17 -0
  199. package/lib/eth1/utils/groupDepositEventsByBlock.js.map +1 -0
  200. package/lib/eth1/utils/optimizeNextBlockDiffForGenesis.d.ts +10 -0
  201. package/lib/eth1/utils/optimizeNextBlockDiffForGenesis.d.ts.map +1 -0
  202. package/lib/eth1/utils/optimizeNextBlockDiffForGenesis.js +14 -0
  203. package/lib/eth1/utils/optimizeNextBlockDiffForGenesis.js.map +1 -0
  204. package/lib/execution/engine/http.d.ts +1 -1
  205. package/lib/execution/engine/http.d.ts.map +1 -1
  206. package/lib/execution/engine/http.js +3 -2
  207. package/lib/execution/engine/http.js.map +1 -1
  208. package/lib/execution/engine/index.d.ts.map +1 -1
  209. package/lib/execution/engine/index.js +1 -1
  210. package/lib/execution/engine/index.js.map +1 -1
  211. package/lib/execution/engine/interface.d.ts +1 -1
  212. package/lib/execution/engine/interface.d.ts.map +1 -1
  213. package/lib/execution/engine/interface.js.map +1 -1
  214. package/lib/execution/engine/mock.d.ts.map +1 -1
  215. package/lib/execution/engine/mock.js +1 -1
  216. package/lib/execution/engine/mock.js.map +1 -1
  217. package/lib/execution/engine/payloadIdCache.d.ts +1 -1
  218. package/lib/execution/engine/payloadIdCache.d.ts.map +1 -1
  219. package/lib/execution/engine/types.d.ts +1 -1
  220. package/lib/execution/engine/types.d.ts.map +1 -1
  221. package/lib/execution/engine/types.js +1 -1
  222. package/lib/execution/engine/types.js.map +1 -1
  223. package/lib/execution/engine/utils.d.ts +2 -64
  224. package/lib/execution/engine/utils.d.ts.map +1 -1
  225. package/lib/execution/engine/utils.js +2 -91
  226. package/lib/execution/engine/utils.js.map +1 -1
  227. package/lib/index.d.ts +2 -1
  228. package/lib/index.d.ts.map +1 -1
  229. package/lib/index.js +2 -1
  230. package/lib/index.js.map +1 -1
  231. package/lib/metrics/metrics/lodestar.d.ts +35 -0
  232. package/lib/metrics/metrics/lodestar.d.ts.map +1 -1
  233. package/lib/metrics/metrics/lodestar.js +90 -0
  234. package/lib/metrics/metrics/lodestar.js.map +1 -1
  235. package/lib/node/nodejs.d.ts.map +1 -1
  236. package/lib/node/nodejs.js +9 -10
  237. package/lib/node/nodejs.js.map +1 -1
  238. package/lib/node/options.d.ts +2 -0
  239. package/lib/node/options.d.ts.map +1 -1
  240. package/lib/node/options.js +2 -0
  241. package/lib/node/options.js.map +1 -1
  242. package/lib/node/utils/interop/deposits.d.ts +1 -2
  243. package/lib/node/utils/interop/deposits.d.ts.map +1 -1
  244. package/lib/node/utils/interop/deposits.js.map +1 -1
  245. package/lib/node/utils/interop/state.d.ts +1 -1
  246. package/lib/node/utils/interop/state.d.ts.map +1 -1
  247. package/lib/node/utils/state.d.ts +7 -1
  248. package/lib/node/utils/state.d.ts.map +1 -1
  249. package/lib/node/utils/state.js +14 -1
  250. package/lib/node/utils/state.js.map +1 -1
  251. package/lib/sync/backfill/backfill.d.ts.map +1 -1
  252. package/lib/sync/backfill/backfill.js +4 -2
  253. package/lib/sync/backfill/backfill.js.map +1 -1
  254. package/lib/sync/backfill/verify.d.ts +1 -1
  255. package/lib/sync/backfill/verify.d.ts.map +1 -1
  256. package/lib/sync/backfill/verify.js +2 -2
  257. package/lib/sync/backfill/verify.js.map +1 -1
  258. package/package.json +20 -14
  259. package/src/api/impl/beacon/blocks/utils.ts +1 -1
  260. package/src/chain/blocks/verifyBlock.ts +0 -1
  261. package/src/chain/blocks/verifyBlocksSignatures.ts +1 -3
  262. package/src/chain/chain.ts +19 -7
  263. package/src/chain/genesis/genesis.ts +190 -0
  264. package/src/chain/genesis/interface.ts +14 -0
  265. package/src/chain/initState.ts +97 -1
  266. package/src/chain/interface.ts +2 -0
  267. package/src/chain/opPools/aggregatedAttestationPool.ts +7 -7
  268. package/src/chain/opPools/opPool.ts +8 -8
  269. package/src/chain/prepareNextSlot.ts +28 -1
  270. package/src/chain/produceBlock/produceBlockBody.ts +12 -8
  271. package/src/chain/rewards/attestationsRewards.ts +4 -13
  272. package/src/chain/rewards/blockRewards.ts +3 -6
  273. package/src/chain/rewards/syncCommitteeRewards.ts +1 -3
  274. package/src/chain/stateCache/persistentCheckpointsCache.ts +2 -15
  275. package/src/chain/validation/attesterSlashing.ts +1 -1
  276. package/src/chain/validation/block.ts +1 -1
  277. package/src/chain/validation/blsToExecutionChange.ts +1 -1
  278. package/src/chain/validation/proposerSlashing.ts +1 -1
  279. package/src/chain/validation/signatureSets/aggregateAndProof.ts +1 -1
  280. package/src/chain/validation/signatureSets/contributionAndProof.ts +1 -3
  281. package/src/chain/validation/signatureSets/syncCommittee.ts +1 -3
  282. package/src/chain/validation/signatureSets/syncCommitteeContribution.ts +1 -3
  283. package/src/chain/validation/signatureSets/syncCommitteeSelectionProof.ts +1 -2
  284. package/src/chain/validation/syncCommittee.ts +1 -1
  285. package/src/chain/validation/syncCommitteeContributionAndProof.ts +3 -8
  286. package/src/chain/validation/voluntaryExit.ts +1 -1
  287. package/src/db/beacon.ts +16 -38
  288. package/src/db/buckets.ts +7 -12
  289. package/src/db/interface.ts +13 -2
  290. package/src/db/repositories/depositDataRoot.ts +80 -0
  291. package/src/db/repositories/depositEvent.ts +32 -0
  292. package/src/db/repositories/eth1Data.ts +33 -0
  293. package/src/db/repositories/index.ts +3 -0
  294. package/src/db/single/index.ts +2 -0
  295. package/src/db/single/preGenesisState.ts +37 -0
  296. package/src/db/single/preGenesisStateLastProcessedBlock.ts +34 -0
  297. package/src/eth1/errors.ts +40 -0
  298. package/src/eth1/eth1DataCache.ts +26 -0
  299. package/src/eth1/eth1DepositDataTracker.ts +410 -0
  300. package/src/eth1/eth1DepositsCache.ts +141 -0
  301. package/src/eth1/index.ts +94 -0
  302. package/src/eth1/interface.ts +87 -0
  303. package/src/eth1/options.ts +28 -0
  304. package/src/eth1/provider/eth1Provider.ts +229 -0
  305. package/src/{execution/engine → eth1/provider}/jsonRpcHttpClient.ts +1 -1
  306. package/src/eth1/provider/utils.ts +136 -0
  307. package/src/eth1/stream.ts +75 -0
  308. package/src/eth1/utils/depositContract.ts +37 -0
  309. package/src/eth1/utils/deposits.ts +70 -0
  310. package/src/eth1/utils/eth1Data.ts +100 -0
  311. package/src/eth1/utils/eth1DepositEvent.ts +12 -0
  312. package/src/eth1/utils/eth1Vote.ts +142 -0
  313. package/src/eth1/utils/groupDepositEventsByBlock.ts +19 -0
  314. package/src/eth1/utils/optimizeNextBlockDiffForGenesis.ts +18 -0
  315. package/src/execution/engine/http.ts +9 -8
  316. package/src/execution/engine/index.ts +1 -1
  317. package/src/execution/engine/interface.ts +1 -1
  318. package/src/execution/engine/mock.ts +2 -1
  319. package/src/execution/engine/payloadIdCache.ts +1 -1
  320. package/src/execution/engine/types.ts +9 -9
  321. package/src/execution/engine/utils.ts +5 -111
  322. package/src/index.ts +2 -1
  323. package/src/metrics/metrics/lodestar.ts +92 -0
  324. package/src/node/nodejs.ts +9 -11
  325. package/src/node/options.ts +3 -0
  326. package/src/node/utils/interop/deposits.ts +1 -3
  327. package/src/node/utils/interop/state.ts +1 -1
  328. package/src/node/utils/state.ts +18 -3
  329. package/src/sync/backfill/backfill.ts +3 -8
  330. package/src/sync/backfill/verify.ts +1 -3
  331. package/lib/execution/engine/jsonRpcHttpClient.d.ts.map +0 -1
  332. package/lib/execution/engine/jsonRpcHttpClient.js.map +0 -1
  333. package/lib/execution/engine/jwt.d.ts.map +0 -1
  334. package/lib/execution/engine/jwt.js.map +0 -1
  335. /package/lib/{execution/engine → eth1/provider}/jsonRpcHttpClient.js +0 -0
  336. /package/lib/{execution/engine → eth1/provider}/jwt.d.ts +0 -0
  337. /package/lib/{execution/engine → eth1/provider}/jwt.js +0 -0
  338. /package/src/{execution/engine → eth1/provider}/jwt.ts +0 -0
@@ -0,0 +1,136 @@
1
+ import {RootHex} from "@lodestar/types";
2
+ import {bigIntToBytes, bytesToBigInt, fromHex, fromHexInto, toHex} from "@lodestar/utils";
3
+ import {ErrorParseJson} from "./jsonRpcHttpClient.js";
4
+
5
+ /** QUANTITY as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API */
6
+ export type QUANTITY = string;
7
+ /** DATA as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API */
8
+ export type DATA = string;
9
+
10
+ export const rootHexRegex = /^0x[a-fA-F0-9]{64}$/;
11
+
12
+ export function numberToHex(n: number | bigint): string {
13
+ return "0x" + n.toString(16);
14
+ }
15
+
16
+ export function isJsonRpcTruncatedError(error: Error): boolean {
17
+ return (
18
+ // Truncated responses usually get as 200 but since it's truncated the JSON will be invalid
19
+ error instanceof ErrorParseJson ||
20
+ // Otherwise guess Infura error message of too many events
21
+ (error instanceof Error && error.message.includes("query returned more than 10000 results")) ||
22
+ // Nethermind enforces limits on JSON RPC batch calls
23
+ (error instanceof Error && error.message.toLowerCase().includes("batch size limit exceeded"))
24
+ );
25
+ }
26
+
27
+ export function bytesToHex(bytes: Uint8Array): string {
28
+ // Handle special case in Ethereum hex formating where hex values may include a single letter
29
+ // 0x0, 0x1 are valid values
30
+ if (bytes.length === 1 && bytes[0] <= 0xf) {
31
+ return "0x" + bytes[0].toString(16);
32
+ }
33
+
34
+ return toHex(bytes);
35
+ }
36
+
37
+ /**
38
+ * QUANTITY as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API
39
+ *
40
+ * When encoding QUANTITIES (integers, numbers): encode as hex, prefix with “0x”, the most compact representation (slight exception: zero should be represented as “0x0”). Examples:
41
+ * - 0x41 (65 in decimal)
42
+ * - 0x400 (1024 in decimal)
43
+ * - WRONG: 0x (should always have at least one digit - zero is “0x0”)
44
+ * - WRONG: 0x0400 (no leading zeroes allowed)
45
+ * - WRONG: ff (must be prefixed 0x)
46
+ */
47
+ export function numToQuantity(num: number | bigint): QUANTITY {
48
+ return "0x" + num.toString(16);
49
+ }
50
+
51
+ /**
52
+ * QUANTITY as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API
53
+ */
54
+ export function quantityToNum(hex: QUANTITY, id = ""): number {
55
+ const num = parseInt(hex, 16);
56
+ if (Number.isNaN(num) || num < 0) throw Error(`Invalid hex decimal ${id} '${hex}'`);
57
+ return num;
58
+ }
59
+
60
+ /**
61
+ * QUANTITY as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API.
62
+ * Typesafe fn to convert hex string to bigint. The BigInt constructor param is any
63
+ */
64
+ export function quantityToBigint(hex: QUANTITY, id = ""): bigint {
65
+ try {
66
+ return BigInt(hex);
67
+ } catch (e) {
68
+ throw Error(`Invalid hex bigint ${id} '${hex}': ${(e as Error).message}`);
69
+ }
70
+ }
71
+
72
+ /**
73
+ * QUANTITY as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API.
74
+ */
75
+ export function quantityToBytes(hex: QUANTITY): Uint8Array {
76
+ const bn = quantityToBigint(hex);
77
+ return bigIntToBytes(bn, 32, "le");
78
+ }
79
+
80
+ /**
81
+ * QUANTITY as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API.
82
+ * Compress a 32 ByteVector into a QUANTITY
83
+ */
84
+ export function bytesToQuantity(bytes: Uint8Array): QUANTITY {
85
+ const bn = bytesToBigInt(bytes, "le");
86
+ return numToQuantity(bn);
87
+ }
88
+
89
+ /**
90
+ * DATA as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API
91
+ *
92
+ * When encoding UNFORMATTED DATA (byte arrays, account addresses, hashes, bytecode arrays): encode as hex, prefix with
93
+ * “0x”, two hex digits per byte. Examples:
94
+ *
95
+ * - 0x41 (size 1, “A”)
96
+ * - 0x004200 (size 3, “\0B\0”)
97
+ * - 0x (size 0, “”)
98
+ * - WRONG: 0xf0f0f (must be even number of digits)
99
+ * - WRONG: 004200 (must be prefixed 0x)
100
+ */
101
+ export function bytesToData(bytes: Uint8Array): DATA {
102
+ return toHex(bytes);
103
+ }
104
+
105
+ /**
106
+ * DATA as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API
107
+ */
108
+ export function dataToBytes(hex: DATA, fixedLength: number | null): Uint8Array {
109
+ try {
110
+ const bytes = fromHex(hex);
111
+ if (fixedLength != null && bytes.length !== fixedLength) {
112
+ throw Error(`Wrong data length ${bytes.length} expected ${fixedLength}`);
113
+ }
114
+ return bytes;
115
+ } catch (e) {
116
+ (e as Error).message = `Invalid hex string: ${(e as Error).message}`;
117
+ throw e;
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Convert DATA into a preallocated buffer
123
+ * fromHexInto will throw if buffer's length is not the same as the decoded hex length
124
+ */
125
+ export function dataIntoBytes(hex: DATA, buffer: Uint8Array): Uint8Array {
126
+ fromHexInto(hex, buffer);
127
+ return buffer;
128
+ }
129
+
130
+ /**
131
+ * DATA as defined in ethereum execution layer JSON RPC https://eth.wiki/json-rpc/API
132
+ */
133
+ export function dataToRootHex(hex: DATA, id = ""): RootHex {
134
+ if (!rootHexRegex.test(hex)) throw Error(`Invalid hex root ${id} '${hex}'`);
135
+ return hex;
136
+ }
@@ -0,0 +1,75 @@
1
+ import {phase0} from "@lodestar/types";
2
+ import {sleep} from "@lodestar/utils";
3
+ import {BatchDepositEvents, Eth1Block, IEth1Provider, IEth1StreamParams} from "./interface.js";
4
+ import {parseEth1Block} from "./provider/eth1Provider.js";
5
+ import {groupDepositEventsByBlock} from "./utils/groupDepositEventsByBlock.js";
6
+ import {optimizeNextBlockDiffForGenesis} from "./utils/optimizeNextBlockDiffForGenesis.js";
7
+
8
+ /**
9
+ * Phase 1 of genesis building.
10
+ * Not enough validators, only stream deposits
11
+ * @param signal Abort stream returning after a while loop cycle. Aborts internal sleep
12
+ */
13
+ export async function* getDepositsStream(
14
+ fromBlock: number,
15
+ provider: IEth1Provider,
16
+ params: IEth1StreamParams,
17
+ signal?: AbortSignal
18
+ ): AsyncGenerator<BatchDepositEvents> {
19
+ fromBlock = Math.max(fromBlock, provider.deployBlock);
20
+
21
+ while (true) {
22
+ const remoteFollowBlock = await getRemoteFollowBlock(provider, params);
23
+ const toBlock = Math.min(remoteFollowBlock, fromBlock + params.maxBlocksPerPoll);
24
+ const logs = await provider.getDepositEvents(fromBlock, toBlock);
25
+ for (const batchedDeposits of groupDepositEventsByBlock(logs)) {
26
+ yield batchedDeposits;
27
+ }
28
+
29
+ fromBlock = toBlock;
30
+
31
+ // If reached head, sleep for an eth1 block. Throws if signal is aborted
32
+ await sleep(toBlock >= remoteFollowBlock ? params.SECONDS_PER_ETH1_BLOCK * 1000 : 10, signal);
33
+ }
34
+ }
35
+
36
+ /**
37
+ * Phase 2 of genesis building.
38
+ * There are enough validators, stream deposits and blocks
39
+ * @param signal Abort stream returning after a while loop cycle. Aborts internal sleep
40
+ */
41
+ export async function* getDepositsAndBlockStreamForGenesis(
42
+ fromBlock: number,
43
+ provider: IEth1Provider,
44
+ params: IEth1StreamParams,
45
+ signal?: AbortSignal
46
+ ): AsyncGenerator<[phase0.DepositEvent[], Eth1Block]> {
47
+ fromBlock = Math.max(fromBlock, provider.deployBlock);
48
+ fromBlock = Math.min(fromBlock, await getRemoteFollowBlock(provider, params));
49
+ let toBlock = fromBlock; // First, fetch only the first block
50
+
51
+ while (true) {
52
+ const [logs, blockRaw] = await Promise.all([
53
+ provider.getDepositEvents(fromBlock, toBlock),
54
+ provider.getBlockByNumber(toBlock),
55
+ ]);
56
+
57
+ if (!blockRaw) throw Error(`No block found for number ${toBlock}`);
58
+ const block = parseEth1Block(blockRaw);
59
+
60
+ yield [logs, block];
61
+
62
+ const remoteFollowBlock = await getRemoteFollowBlock(provider, params);
63
+ const nextBlockDiff = optimizeNextBlockDiffForGenesis(block, params);
64
+ fromBlock = toBlock;
65
+ toBlock = Math.min(remoteFollowBlock, fromBlock + Math.min(nextBlockDiff, params.maxBlocksPerPoll));
66
+
67
+ // If reached head, sleep for an eth1 block. Throws if signal is aborted
68
+ await sleep(toBlock >= remoteFollowBlock ? params.SECONDS_PER_ETH1_BLOCK * 1000 : 10, signal);
69
+ }
70
+ }
71
+
72
+ async function getRemoteFollowBlock(provider: IEth1Provider, params: IEth1StreamParams): Promise<number> {
73
+ const remoteHighestBlock = await provider.getBlockNumber();
74
+ return Math.max(remoteHighestBlock - params.ETH1_FOLLOW_DISTANCE, 0);
75
+ }
@@ -0,0 +1,37 @@
1
+ import {Interface} from "@ethersproject/abi";
2
+ import {phase0, ssz} from "@lodestar/types";
3
+ import {fromHex} from "@lodestar/utils";
4
+
5
+ const depositEventFragment =
6
+ "event DepositEvent(bytes pubkey, bytes withdrawal_credentials, bytes amount, bytes signature, bytes index)";
7
+
8
+ const depositContractInterface = new Interface([depositEventFragment]);
9
+
10
+ /**
11
+ * Precomputed topics of DepositEvent logs
12
+ */
13
+ export const depositEventTopics = [depositContractInterface.getEventTopic("DepositEvent")];
14
+
15
+ /**
16
+ * Parse DepositEvent log
17
+ */
18
+ export function parseDepositLog(log: {blockNumber: number; data: string; topics: string[]}): phase0.DepositEvent {
19
+ const event = depositContractInterface.parseLog(log);
20
+ const values = event.args;
21
+ if (values === undefined) throw Error(`DepositEvent at ${log.blockNumber} has no values`);
22
+ return {
23
+ blockNumber: log.blockNumber,
24
+ index: parseHexNumLittleEndian(values.index),
25
+ depositData: {
26
+ pubkey: fromHex(values.pubkey),
27
+ withdrawalCredentials: fromHex(values.withdrawal_credentials),
28
+ amount: parseHexNumLittleEndian(values.amount),
29
+ signature: fromHex(values.signature),
30
+ },
31
+ };
32
+ }
33
+
34
+ function parseHexNumLittleEndian(hex: string): number {
35
+ // Can't use parseInt() because amount is a hex string in little endian
36
+ return ssz.UintNum64.deserialize(fromHex(hex));
37
+ }
@@ -0,0 +1,70 @@
1
+ import {Tree, toGindex} from "@chainsafe/persistent-merkle-tree";
2
+ import {FilterOptions} from "@lodestar/db";
3
+ import {CachedBeaconStateAllForks, getEth1DepositCount} from "@lodestar/state-transition";
4
+ import {phase0, ssz} from "@lodestar/types";
5
+ import {toRootHex} from "@lodestar/utils";
6
+ import {DepositTree} from "../../db/repositories/depositDataRoot.js";
7
+ import {Eth1Error, Eth1ErrorCode} from "../errors.js";
8
+
9
+ export type DepositGetter<T> = (indexRange: FilterOptions<number>, eth1Data: phase0.Eth1Data) => Promise<T[]>;
10
+
11
+ export async function getDeposits<T>(
12
+ // eth1_deposit_index represents the next deposit index to be added
13
+ state: CachedBeaconStateAllForks,
14
+ eth1Data: phase0.Eth1Data,
15
+ depositsGetter: DepositGetter<T>
16
+ ): Promise<T[]> {
17
+ const depositIndex = state.eth1DepositIndex;
18
+ const depositCount = eth1Data.depositCount;
19
+
20
+ if (depositIndex > depositCount) {
21
+ throw new Eth1Error({code: Eth1ErrorCode.DEPOSIT_INDEX_TOO_HIGH, depositIndex, depositCount});
22
+ }
23
+
24
+ const depositsLen = getEth1DepositCount(state, eth1Data);
25
+
26
+ if (depositsLen === 0) {
27
+ return []; // If depositsLen === 0, we can return early since no deposit with be returned from depositsGetter
28
+ }
29
+
30
+ const indexRange = {gte: depositIndex, lt: depositIndex + depositsLen};
31
+ const deposits = await depositsGetter(indexRange, eth1Data);
32
+
33
+ if (deposits.length < depositsLen) {
34
+ throw new Eth1Error({code: Eth1ErrorCode.NOT_ENOUGH_DEPOSITS, len: deposits.length, expectedLen: depositsLen});
35
+ }
36
+
37
+ if (deposits.length > depositsLen) {
38
+ throw new Eth1Error({code: Eth1ErrorCode.TOO_MANY_DEPOSITS, len: deposits.length, expectedLen: depositsLen});
39
+ }
40
+
41
+ return deposits;
42
+ }
43
+
44
+ export function getDepositsWithProofs(
45
+ depositEvents: phase0.DepositEvent[],
46
+ depositRootTree: DepositTree,
47
+ eth1Data: phase0.Eth1Data
48
+ ): phase0.Deposit[] {
49
+ // Get tree at this particular depositCount to compute correct proofs
50
+ const viewAtDepositCount = depositRootTree.sliceTo(eth1Data.depositCount - 1);
51
+
52
+ const depositRoot = viewAtDepositCount.hashTreeRoot();
53
+
54
+ if (!ssz.Root.equals(depositRoot, eth1Data.depositRoot)) {
55
+ throw new Eth1Error({
56
+ code: Eth1ErrorCode.WRONG_DEPOSIT_ROOT,
57
+ root: toRootHex(depositRoot),
58
+ expectedRoot: toRootHex(eth1Data.depositRoot),
59
+ });
60
+ }
61
+
62
+ // Already commited for .hashTreeRoot()
63
+ const treeAtDepositCount = new Tree(viewAtDepositCount.node);
64
+ const depositTreeDepth = viewAtDepositCount.type.depth;
65
+
66
+ return depositEvents.map((log) => ({
67
+ proof: treeAtDepositCount.getSingleProof(toGindex(depositTreeDepth, BigInt(log.index))),
68
+ data: log.depositData,
69
+ }));
70
+ }
@@ -0,0 +1,100 @@
1
+ import {Root, phase0} from "@lodestar/types";
2
+ import {DepositTree} from "../../db/repositories/depositDataRoot.js";
3
+ import {binarySearchLte} from "../../util/binarySearch.js";
4
+ import {Eth1Error, Eth1ErrorCode} from "../errors.js";
5
+ import {Eth1Block} from "../interface.js";
6
+
7
+ type BlockNumber = number;
8
+
9
+ /**
10
+ * Appends partial eth1 data (depositRoot, depositCount) in a sequence of blocks
11
+ * eth1 data deposit is inferred from sparse eth1 data obtained from the deposit logs
12
+ */
13
+ export async function getEth1DataForBlocks(
14
+ blocks: Eth1Block[],
15
+ depositDescendingStream: AsyncIterable<phase0.DepositEvent>,
16
+ depositRootTree: DepositTree,
17
+ lastProcessedDepositBlockNumber: BlockNumber | null
18
+ ): Promise<(phase0.Eth1Data & Eth1Block)[]> {
19
+ // Exclude blocks for which there is no valid eth1 data deposit
20
+ if (lastProcessedDepositBlockNumber !== null) {
21
+ blocks = blocks.filter((block) => block.blockNumber <= lastProcessedDepositBlockNumber);
22
+ }
23
+
24
+ // A valid block can be constructed using previous `state.eth1Data`, don't throw
25
+ if (blocks.length === 0) {
26
+ return [];
27
+ }
28
+
29
+ // Collect the latest deposit of each blockNumber in a block number range
30
+ const fromBlock = blocks[0].blockNumber;
31
+ const toBlock = blocks.at(-1)?.blockNumber as number;
32
+ const depositsByBlockNumber = await getDepositsByBlockNumber(fromBlock, toBlock, depositDescendingStream);
33
+ if (depositsByBlockNumber.length === 0) {
34
+ throw new Eth1Error({code: Eth1ErrorCode.NO_DEPOSITS_FOR_BLOCK_RANGE, fromBlock, toBlock});
35
+ }
36
+
37
+ // Precompute a map of depositCount => depositRoot (from depositRootTree)
38
+ const depositCounts = depositsByBlockNumber.map((event) => event.index + 1);
39
+ const depositRootByDepositCount = getDepositRootByDepositCount(depositCounts, depositRootTree);
40
+
41
+ const eth1Datas: (phase0.Eth1Data & Eth1Block)[] = [];
42
+ for (const block of blocks) {
43
+ const deposit = binarySearchLte(depositsByBlockNumber, block.blockNumber, (event) => event.blockNumber);
44
+ const depositCount = deposit.index + 1;
45
+ const depositRoot = depositRootByDepositCount.get(depositCount);
46
+ if (depositRoot === undefined) {
47
+ throw new Eth1Error({code: Eth1ErrorCode.NO_DEPOSIT_ROOT, depositCount});
48
+ }
49
+ eth1Datas.push({...block, depositCount, depositRoot});
50
+ }
51
+ return eth1Datas;
52
+ }
53
+
54
+ /**
55
+ * Collect depositCount by blockNumber from a stream matching a block number range
56
+ * For a given blockNumber it's depositCount is equal to the index + 1 of the
57
+ * closest deposit event whose deposit.blockNumber <= blockNumber
58
+ * @returns array ascending by blockNumber
59
+ */
60
+ export async function getDepositsByBlockNumber(
61
+ fromBlock: BlockNumber,
62
+ toBlock: BlockNumber,
63
+ depositEventDescendingStream: AsyncIterable<phase0.DepositEvent>
64
+ ): Promise<phase0.DepositEvent[]> {
65
+ const depositCountMap = new Map<BlockNumber, phase0.DepositEvent>();
66
+ // Take blocks until the block under the range lower bound (included)
67
+ for await (const deposit of depositEventDescendingStream) {
68
+ if (deposit.blockNumber <= toBlock && !depositCountMap.has(deposit.blockNumber)) {
69
+ depositCountMap.set(deposit.blockNumber, deposit);
70
+ }
71
+ if (deposit.blockNumber < fromBlock) {
72
+ break;
73
+ }
74
+ }
75
+
76
+ return Array.from(depositCountMap.values()).sort((a, b) => a.blockNumber - b.blockNumber);
77
+ }
78
+
79
+ /**
80
+ * Precompute a map of depositCount => depositRoot from a depositRootTree filled beforehand
81
+ */
82
+ export function getDepositRootByDepositCount(depositCounts: number[], depositRootTree: DepositTree): Map<number, Root> {
83
+ // Unique + sort numerically in descending order
84
+ depositCounts = [...new Set(depositCounts)].sort((a, b) => b - a);
85
+
86
+ if (depositCounts.length > 0) {
87
+ const maxIndex = depositCounts[0] - 1;
88
+ const treeLength = depositRootTree.length - 1;
89
+ if (maxIndex > treeLength) {
90
+ throw new Eth1Error({code: Eth1ErrorCode.NOT_ENOUGH_DEPOSIT_ROOTS, index: maxIndex, treeLength});
91
+ }
92
+ }
93
+
94
+ const depositRootByDepositCount = new Map<number, Root>();
95
+ for (const depositCount of depositCounts) {
96
+ depositRootTree = depositRootTree.sliceTo(depositCount - 1);
97
+ depositRootByDepositCount.set(depositCount, depositRootTree.hashTreeRoot());
98
+ }
99
+ return depositRootByDepositCount;
100
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Assert that an array of deposits are consecutive and ascending
3
+ */
4
+ export function assertConsecutiveDeposits(depositEvents: {index: number}[]): void {
5
+ for (let i = 0; i < depositEvents.length - 1; i++) {
6
+ const indexLeft = depositEvents[i].index;
7
+ const indexRight = depositEvents[i + 1].index;
8
+ if (indexLeft !== indexRight - 1) {
9
+ throw Error(`Non consecutive deposits. deposit[${i}] = ${indexLeft}, deposit[${i + 1}] ${indexRight}`);
10
+ }
11
+ }
12
+ }
@@ -0,0 +1,142 @@
1
+ import {ChainForkConfig} from "@lodestar/config";
2
+ import {EPOCHS_PER_ETH1_VOTING_PERIOD, SLOTS_PER_EPOCH, isForkPostElectra} from "@lodestar/params";
3
+ import {BeaconStateAllForks, BeaconStateElectra, computeTimeAtSlot} from "@lodestar/state-transition";
4
+ import {RootHex, phase0} from "@lodestar/types";
5
+ import {toRootHex} from "@lodestar/utils";
6
+
7
+ export type Eth1DataGetter = ({
8
+ timestampRange,
9
+ }: {
10
+ timestampRange: {gte: number; lte: number};
11
+ }) => Promise<phase0.Eth1Data[]>;
12
+
13
+ export async function getEth1VotesToConsider(
14
+ config: ChainForkConfig,
15
+ state: BeaconStateAllForks,
16
+ eth1DataGetter: Eth1DataGetter
17
+ ): Promise<phase0.Eth1Data[]> {
18
+ const fork = config.getForkName(state.slot);
19
+ if (isForkPostElectra(fork)) {
20
+ const {eth1DepositIndex, depositRequestsStartIndex} = state as BeaconStateElectra;
21
+ if (eth1DepositIndex === Number(depositRequestsStartIndex)) {
22
+ return state.eth1DataVotes.getAllReadonly();
23
+ }
24
+ }
25
+
26
+ const periodStart = votingPeriodStartTime(config, state);
27
+ const {SECONDS_PER_ETH1_BLOCK, ETH1_FOLLOW_DISTANCE} = config;
28
+
29
+ // Modified version of the spec function to fetch the required range directly from the DB
30
+ return (
31
+ await eth1DataGetter({
32
+ timestampRange: {
33
+ // Spec v0.12.2
34
+ // is_candidate_block =
35
+ // block.timestamp + SECONDS_PER_ETH1_BLOCK * ETH1_FOLLOW_DISTANCE <= period_start &&
36
+ // block.timestamp + SECONDS_PER_ETH1_BLOCK * ETH1_FOLLOW_DISTANCE * 2 >= period_start
37
+ lte: periodStart - SECONDS_PER_ETH1_BLOCK * ETH1_FOLLOW_DISTANCE,
38
+ gte: periodStart - SECONDS_PER_ETH1_BLOCK * ETH1_FOLLOW_DISTANCE * 2,
39
+ },
40
+ })
41
+ ).filter((eth1Data) => eth1Data.depositCount >= state.eth1Data.depositCount);
42
+ }
43
+
44
+ export function pickEth1Vote(state: BeaconStateAllForks, votesToConsider: phase0.Eth1Data[]): phase0.Eth1Data {
45
+ const votesToConsiderKeys = new Set<string>();
46
+ for (const eth1Data of votesToConsider) {
47
+ votesToConsiderKeys.add(getEth1DataKey(eth1Data));
48
+ }
49
+
50
+ const eth1DataHashToEth1Data = new Map<RootHex, phase0.Eth1Data>();
51
+ const eth1DataVoteCountByRoot = new Map<RootHex, number>();
52
+ const eth1DataVotesOrder: RootHex[] = [];
53
+
54
+ // BeaconStateAllForks is always represented as a tree with a hashing cache.
55
+ // To check equality its cheaper to use hashTreeRoot as keys.
56
+ // However `votesToConsider` is an array of values since those are read from DB.
57
+ // TODO: Optimize cache of known votes, to prevent re-hashing stored values.
58
+ // Note: for low validator counts it's not very important, since this runs once per proposal
59
+ const eth1DataVotes = state.eth1DataVotes.getAllReadonly();
60
+ for (const eth1DataVote of eth1DataVotes) {
61
+ const rootHex = getEth1DataKey(eth1DataVote);
62
+
63
+ if (votesToConsiderKeys.has(rootHex)) {
64
+ const prevVoteCount = eth1DataVoteCountByRoot.get(rootHex);
65
+ eth1DataVoteCountByRoot.set(rootHex, 1 + (prevVoteCount ?? 0));
66
+
67
+ // Cache eth1DataVote to root Map only once per root
68
+ if (prevVoteCount === undefined) {
69
+ eth1DataHashToEth1Data.set(rootHex, eth1DataVote);
70
+ eth1DataVotesOrder.push(rootHex);
71
+ }
72
+ }
73
+ }
74
+
75
+ const eth1DataRootsMaxVotes = getKeysWithMaxValue(eth1DataVoteCountByRoot);
76
+
77
+ // No votes, vote for the last valid vote
78
+ if (eth1DataRootsMaxVotes.length === 0) {
79
+ return votesToConsider.at(-1) ?? state.eth1Data;
80
+ }
81
+
82
+ // If there's a single winning vote with a majority vote that one
83
+ if (eth1DataRootsMaxVotes.length === 1) {
84
+ return eth1DataHashToEth1Data.get(eth1DataRootsMaxVotes[0]) ?? state.eth1Data;
85
+ }
86
+
87
+ // If there are multiple winning votes, vote for the latest one
88
+ const latestMostVotedRoot =
89
+ eth1DataVotesOrder[Math.max(...eth1DataRootsMaxVotes.map((root) => eth1DataVotesOrder.indexOf(root)))];
90
+ return eth1DataHashToEth1Data.get(latestMostVotedRoot) ?? state.eth1Data;
91
+ }
92
+
93
+ /**
94
+ * Returns the array of keys with max value. May return 0, 1 or more keys
95
+ */
96
+ function getKeysWithMaxValue<T>(map: Map<T, number>): T[] {
97
+ const entries = Array.from(map.entries());
98
+ let keysMax: T[] = [];
99
+ let valueMax = -Infinity;
100
+
101
+ for (const [key, value] of entries) {
102
+ if (value > valueMax) {
103
+ keysMax = [key];
104
+ valueMax = value;
105
+ } else if (value === valueMax) {
106
+ keysMax.push(key);
107
+ }
108
+ }
109
+
110
+ return keysMax;
111
+ }
112
+
113
+ /**
114
+ * Key-ed by fastSerializeEth1Data(). votesToConsider is read from DB as struct and always has a length of 2048.
115
+ * `state.eth1DataVotes` has a length between 0 and ETH1_FOLLOW_DISTANCE with an equal probability of each value.
116
+ * So to get the average faster time to key both votesToConsider and state.eth1DataVotes it's better to use
117
+ * fastSerializeEth1Data(). However, a long term solution is to cache valid votes in memory and prevent having
118
+ * to recompute their key on every proposal.
119
+ *
120
+ * With `fastSerializeEth1Data()`: avg time 20 ms/op
121
+ * ✓ pickEth1Vote - no votes 233.0587 ops/s 4.290764 ms/op - 121 runs 1.02 s
122
+ * ✓ pickEth1Vote - max votes 29.21546 ops/s 34.22845 ms/op - 25 runs 1.38 s
123
+ *
124
+ * With `toHexString(ssz.phase0.Eth1Data.hashTreeRoot(eth1Data))`: avg time 23 ms/op
125
+ * ✓ pickEth1Vote - no votes 46.12341 ops/s 21.68096 ms/op - 133 runs 3.40 s
126
+ * ✓ pickEth1Vote - max votes 37.89912 ops/s 26.38583 ms/op - 29 runs 1.27 s
127
+ */
128
+ function getEth1DataKey(eth1Data: phase0.Eth1Data): string {
129
+ return fastSerializeEth1Data(eth1Data);
130
+ }
131
+
132
+ /**
133
+ * Serialize eth1Data types to a unique string ID. It is only used for comparison.
134
+ */
135
+ export function fastSerializeEth1Data(eth1Data: phase0.Eth1Data): string {
136
+ return toRootHex(eth1Data.blockHash) + eth1Data.depositCount.toString(16) + toRootHex(eth1Data.depositRoot);
137
+ }
138
+
139
+ export function votingPeriodStartTime(config: ChainForkConfig, state: BeaconStateAllForks): number {
140
+ const eth1VotingPeriodStartSlot = state.slot - (state.slot % (EPOCHS_PER_ETH1_VOTING_PERIOD * SLOTS_PER_EPOCH));
141
+ return computeTimeAtSlot(config, eth1VotingPeriodStartSlot, state.genesisTime);
142
+ }
@@ -0,0 +1,19 @@
1
+ import {phase0} from "@lodestar/types";
2
+ import {BatchDepositEvents} from "../interface.js";
3
+
4
+ /**
5
+ * Return deposit events of blocks grouped/sorted by block number and deposit index
6
+ * Blocks without events are omitted
7
+ * @param depositEvents range deposit events
8
+ */
9
+ export function groupDepositEventsByBlock(depositEvents: phase0.DepositEvent[]): BatchDepositEvents[] {
10
+ depositEvents.sort((event1, event2) => event1.index - event2.index);
11
+ const depositsByBlockMap = new Map<number, phase0.DepositEvent[]>();
12
+ for (const deposit of depositEvents) {
13
+ depositsByBlockMap.set(deposit.blockNumber, [...(depositsByBlockMap.get(deposit.blockNumber) || []), deposit]);
14
+ }
15
+ return Array.from(depositsByBlockMap.entries()).map(([blockNumber, depositEvents]) => ({
16
+ blockNumber,
17
+ depositEvents,
18
+ }));
19
+ }
@@ -0,0 +1,18 @@
1
+ import {ChainConfig} from "@lodestar/config";
2
+
3
+ /**
4
+ * Utility for fetching genesis min genesis time block
5
+ * Returns an approximation of the next block diff to fetch to progressively
6
+ * get closer to the block that satisfies min genesis time condition
7
+ */
8
+ export function optimizeNextBlockDiffForGenesis(
9
+ lastFetchedBlock: {timestamp: number},
10
+ params: Pick<ChainConfig, "MIN_GENESIS_TIME" | "GENESIS_DELAY" | "SECONDS_PER_ETH1_BLOCK">
11
+ ): number {
12
+ const timeToGenesis = params.MIN_GENESIS_TIME - params.GENESIS_DELAY - lastFetchedBlock.timestamp;
13
+ const numBlocksToGenesis = Math.floor(timeToGenesis / params.SECONDS_PER_ETH1_BLOCK);
14
+ if (numBlocksToGenesis <= 2) {
15
+ return 1;
16
+ }
17
+ return Math.max(1, Math.floor(numBlocksToGenesis / 2));
18
+ }
@@ -4,6 +4,14 @@ import {BlobsBundle, ExecutionPayload, ExecutionRequests, Root, RootHex, Wei} fr
4
4
  import {BlobAndProof} from "@lodestar/types/deneb";
5
5
  import {BlobAndProofV2} from "@lodestar/types/fulu";
6
6
  import {strip0xPrefix} from "@lodestar/utils";
7
+ import {
8
+ ErrorJsonRpcResponse,
9
+ HttpRpcError,
10
+ IJsonRpcHttpClient,
11
+ JsonRpcHttpClientEvent,
12
+ ReqOpts,
13
+ } from "../../eth1/provider/jsonRpcHttpClient.js";
14
+ import {bytesToData, numToQuantity} from "../../eth1/provider/utils.js";
7
15
  import {Metrics} from "../../metrics/index.js";
8
16
  import {EPOCHS_PER_BATCH} from "../../sync/constants.js";
9
17
  import {getLodestarClientVersion} from "../../util/metadata.js";
@@ -19,13 +27,6 @@ import {
19
27
  PayloadId,
20
28
  VersionedHashes,
21
29
  } from "./interface.js";
22
- import {
23
- ErrorJsonRpcResponse,
24
- HttpRpcError,
25
- IJsonRpcHttpClient,
26
- JsonRpcHttpClientEvent,
27
- ReqOpts,
28
- } from "./jsonRpcHttpClient.js";
29
30
  import {PayloadIdCache} from "./payloadIdCache.js";
30
31
  import {
31
32
  BLOB_AND_PROOF_V2_RPC_BYTES,
@@ -44,7 +45,7 @@ import {
44
45
  serializePayloadAttributes,
45
46
  serializeVersionedHashes,
46
47
  } from "./types.js";
47
- import {bytesToData, getExecutionEngineState, numToQuantity} from "./utils.js";
48
+ import {getExecutionEngineState} from "./utils.js";
48
49
 
49
50
  export type ExecutionEngineModules = {
50
51
  signal: AbortSignal;
@@ -1,4 +1,5 @@
1
1
  import {fromHex, toPrintableUrl} from "@lodestar/utils";
2
+ import {JsonRpcHttpClient} from "../../eth1/provider/jsonRpcHttpClient.js";
2
3
  import {ExecutionEngineDisabled} from "./disabled.js";
3
4
  import {
4
5
  ExecutionEngineHttp,
@@ -7,7 +8,6 @@ import {
7
8
  defaultExecutionEngineHttpOpts,
8
9
  } from "./http.js";
9
10
  import {IExecutionEngine} from "./interface.js";
10
- import {JsonRpcHttpClient} from "./jsonRpcHttpClient.js";
11
11
  import {ExecutionEngineMockBackend, ExecutionEngineMockOpts} from "./mock.js";
12
12
  import {ExecutionEngineMockJsonRpcClient, JsonRpcBackend} from "./utils.js";
13
13
 
@@ -9,9 +9,9 @@ import {
9
9
  import {BlobsBundle, ExecutionPayload, ExecutionRequests, Root, RootHex, Wei, capella} from "@lodestar/types";
10
10
  import {BlobAndProof} from "@lodestar/types/deneb";
11
11
  import {BlobAndProofV2} from "@lodestar/types/fulu";
12
+ import {DATA} from "../../eth1/provider/utils.js";
12
13
  import {PayloadId, PayloadIdCache, WithdrawalV1} from "./payloadIdCache.js";
13
14
  import {ExecutionPayloadBody} from "./types.js";
14
- import {DATA} from "./utils.js";
15
15
 
16
16
  export {PayloadIdCache, type PayloadId, type WithdrawalV1};
17
17