@lodestar/state-transition 1.41.0-dev.702f7932c2 → 1.41.0-dev.8578102bd2

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 (309) hide show
  1. package/lib/block/externalData.d.ts +2 -1
  2. package/lib/block/externalData.d.ts.map +1 -1
  3. package/lib/block/externalData.js +6 -2
  4. package/lib/block/externalData.js.map +1 -1
  5. package/lib/block/index.d.ts +3 -3
  6. package/lib/block/index.js.map +1 -1
  7. package/lib/block/initiateValidatorExit.js.map +1 -1
  8. package/lib/block/isValidIndexedAttestation.d.ts +3 -3
  9. package/lib/block/isValidIndexedAttestation.d.ts.map +1 -1
  10. package/lib/block/isValidIndexedAttestation.js +4 -4
  11. package/lib/block/isValidIndexedAttestation.js.map +1 -1
  12. package/lib/block/isValidIndexedPayloadAttestation.js +1 -1
  13. package/lib/block/isValidIndexedPayloadAttestation.js.map +1 -1
  14. package/lib/block/processAttestationPhase0.js +1 -1
  15. package/lib/block/processAttestationPhase0.js.map +1 -1
  16. package/lib/block/processAttestations.js.map +1 -1
  17. package/lib/block/processAttestationsAltair.js +1 -1
  18. package/lib/block/processAttestationsAltair.js.map +1 -1
  19. package/lib/block/processAttesterSlashing.d.ts +2 -2
  20. package/lib/block/processAttesterSlashing.d.ts.map +1 -1
  21. package/lib/block/processAttesterSlashing.js +3 -3
  22. package/lib/block/processAttesterSlashing.js.map +1 -1
  23. package/lib/block/processBlobKzgCommitments.js.map +1 -1
  24. package/lib/block/processBlockHeader.js.map +1 -1
  25. package/lib/block/processBlsToExecutionChange.js.map +1 -1
  26. package/lib/block/processConsolidationRequest.js.map +1 -1
  27. package/lib/block/processDeposit.js.map +1 -1
  28. package/lib/block/processDepositRequest.d.ts +1 -1
  29. package/lib/block/processDepositRequest.d.ts.map +1 -1
  30. package/lib/block/processDepositRequest.js +6 -5
  31. package/lib/block/processDepositRequest.js.map +1 -1
  32. package/lib/block/processEth1Data.js.map +1 -1
  33. package/lib/block/processExecutionPayload.js.map +1 -1
  34. package/lib/block/processExecutionPayloadBid.d.ts +1 -1
  35. package/lib/block/processExecutionPayloadBid.d.ts.map +1 -1
  36. package/lib/block/processExecutionPayloadBid.js +5 -0
  37. package/lib/block/processExecutionPayloadBid.js.map +1 -1
  38. package/lib/block/processExecutionPayloadEnvelope.d.ts +5 -2
  39. package/lib/block/processExecutionPayloadEnvelope.d.ts.map +1 -1
  40. package/lib/block/processExecutionPayloadEnvelope.js +25 -24
  41. package/lib/block/processExecutionPayloadEnvelope.js.map +1 -1
  42. package/lib/block/processOperations.js.map +1 -1
  43. package/lib/block/processPayloadAttestation.d.ts +1 -1
  44. package/lib/block/processPayloadAttestation.js.map +1 -1
  45. package/lib/block/processProposerSlashing.d.ts +2 -2
  46. package/lib/block/processProposerSlashing.d.ts.map +1 -1
  47. package/lib/block/processProposerSlashing.js +3 -3
  48. package/lib/block/processProposerSlashing.js.map +1 -1
  49. package/lib/block/processRandao.js +1 -1
  50. package/lib/block/processRandao.js.map +1 -1
  51. package/lib/block/processSyncCommittee.js +1 -1
  52. package/lib/block/processSyncCommittee.js.map +1 -1
  53. package/lib/block/processVoluntaryExit.js +3 -2
  54. package/lib/block/processVoluntaryExit.js.map +1 -1
  55. package/lib/block/processWithdrawalRequest.js +2 -2
  56. package/lib/block/processWithdrawalRequest.js.map +1 -1
  57. package/lib/block/processWithdrawals.d.ts.map +1 -1
  58. package/lib/block/processWithdrawals.js +9 -1
  59. package/lib/block/processWithdrawals.js.map +1 -1
  60. package/lib/block/slashValidator.js.map +1 -1
  61. package/lib/block/types.js +2 -1
  62. package/lib/block/types.js.map +1 -1
  63. package/lib/cache/effectiveBalanceIncrements.js.map +1 -1
  64. package/lib/cache/epochCache.d.ts +11 -18
  65. package/lib/cache/epochCache.d.ts.map +1 -1
  66. package/lib/cache/epochCache.js +43 -41
  67. package/lib/cache/epochCache.js.map +1 -1
  68. package/lib/cache/epochTransitionCache.js.map +1 -1
  69. package/lib/cache/pubkeyCache.d.ts +21 -6
  70. package/lib/cache/pubkeyCache.d.ts.map +1 -1
  71. package/lib/cache/pubkeyCache.js +39 -14
  72. package/lib/cache/pubkeyCache.js.map +1 -1
  73. package/lib/cache/rewardCache.js.map +1 -1
  74. package/lib/cache/stateCache.d.ts +1 -1
  75. package/lib/cache/stateCache.d.ts.map +1 -1
  76. package/lib/cache/stateCache.js +3 -7
  77. package/lib/cache/stateCache.js.map +1 -1
  78. package/lib/cache/syncCommitteeCache.d.ts +3 -2
  79. package/lib/cache/syncCommitteeCache.d.ts.map +1 -1
  80. package/lib/cache/syncCommitteeCache.js +4 -4
  81. package/lib/cache/syncCommitteeCache.js.map +1 -1
  82. package/lib/epoch/computeUnrealizedCheckpoints.js.map +1 -1
  83. package/lib/epoch/getAttestationDeltas.js.map +1 -1
  84. package/lib/epoch/getRewardsAndPenalties.js.map +1 -1
  85. package/lib/epoch/index.d.ts +1 -1
  86. package/lib/epoch/index.js +2 -1
  87. package/lib/epoch/index.js.map +1 -1
  88. package/lib/epoch/processBuilderPendingPayments.d.ts +1 -1
  89. package/lib/epoch/processBuilderPendingPayments.js.map +1 -1
  90. package/lib/epoch/processEffectiveBalanceUpdates.js.map +1 -1
  91. package/lib/epoch/processEth1DataReset.js.map +1 -1
  92. package/lib/epoch/processHistoricalRootsUpdate.js.map +1 -1
  93. package/lib/epoch/processHistoricalSummariesUpdate.js.map +1 -1
  94. package/lib/epoch/processInactivityUpdates.js.map +1 -1
  95. package/lib/epoch/processJustificationAndFinalization.js.map +1 -1
  96. package/lib/epoch/processParticipationFlagUpdates.js.map +1 -1
  97. package/lib/epoch/processParticipationRecordUpdates.js.map +1 -1
  98. package/lib/epoch/processPendingAttestations.js.map +1 -1
  99. package/lib/epoch/processPendingConsolidations.js.map +1 -1
  100. package/lib/epoch/processPendingDeposits.js.map +1 -1
  101. package/lib/epoch/processProposerLookahead.js.map +1 -1
  102. package/lib/epoch/processRandaoMixesReset.js.map +1 -1
  103. package/lib/epoch/processRegistryUpdates.js.map +1 -1
  104. package/lib/epoch/processRewardsAndPenalties.js.map +1 -1
  105. package/lib/epoch/processSlashings.js.map +1 -1
  106. package/lib/epoch/processSlashingsReset.js.map +1 -1
  107. package/lib/epoch/processSyncCommitteeUpdates.js.map +1 -1
  108. package/lib/index.d.ts +3 -1
  109. package/lib/index.d.ts.map +1 -1
  110. package/lib/index.js +2 -1
  111. package/lib/index.js.map +1 -1
  112. package/lib/lightClient/proofs.d.ts +10 -0
  113. package/lib/lightClient/proofs.d.ts.map +1 -0
  114. package/lib/lightClient/proofs.js +63 -0
  115. package/lib/lightClient/proofs.js.map +1 -0
  116. package/lib/lightClient/types.d.ts +34 -0
  117. package/lib/lightClient/types.d.ts.map +1 -0
  118. package/lib/lightClient/types.js +2 -0
  119. package/lib/lightClient/types.js.map +1 -0
  120. package/lib/metrics.d.ts.map +1 -1
  121. package/lib/metrics.js.map +1 -1
  122. package/lib/rewards/attestationsRewards.d.ts +2 -2
  123. package/lib/rewards/attestationsRewards.d.ts.map +1 -1
  124. package/lib/rewards/attestationsRewards.js +4 -4
  125. package/lib/rewards/attestationsRewards.js.map +1 -1
  126. package/lib/rewards/blockRewards.js.map +1 -1
  127. package/lib/rewards/syncCommitteeRewards.d.ts +2 -2
  128. package/lib/rewards/syncCommitteeRewards.d.ts.map +1 -1
  129. package/lib/rewards/syncCommitteeRewards.js +5 -2
  130. package/lib/rewards/syncCommitteeRewards.js.map +1 -1
  131. package/lib/signatureSets/attesterSlashings.js.map +1 -1
  132. package/lib/signatureSets/blsToExecutionChange.js.map +1 -1
  133. package/lib/signatureSets/executionPayloadBid.js.map +1 -1
  134. package/lib/signatureSets/executionPayloadEnvelope.js.map +1 -1
  135. package/lib/signatureSets/index.js.map +1 -1
  136. package/lib/signatureSets/indexedAttestation.js.map +1 -1
  137. package/lib/signatureSets/indexedPayloadAttestation.d.ts +3 -4
  138. package/lib/signatureSets/indexedPayloadAttestation.d.ts.map +1 -1
  139. package/lib/signatureSets/indexedPayloadAttestation.js +4 -4
  140. package/lib/signatureSets/indexedPayloadAttestation.js.map +1 -1
  141. package/lib/signatureSets/proposer.d.ts +2 -2
  142. package/lib/signatureSets/proposer.d.ts.map +1 -1
  143. package/lib/signatureSets/proposer.js +2 -2
  144. package/lib/signatureSets/proposer.js.map +1 -1
  145. package/lib/signatureSets/proposerSlashings.js.map +1 -1
  146. package/lib/signatureSets/randao.d.ts +2 -2
  147. package/lib/signatureSets/randao.d.ts.map +1 -1
  148. package/lib/signatureSets/randao.js +2 -2
  149. package/lib/signatureSets/randao.js.map +1 -1
  150. package/lib/signatureSets/voluntaryExits.d.ts +2 -2
  151. package/lib/signatureSets/voluntaryExits.d.ts.map +1 -1
  152. package/lib/signatureSets/voluntaryExits.js +2 -2
  153. package/lib/signatureSets/voluntaryExits.js.map +1 -1
  154. package/lib/slot/index.js.map +1 -1
  155. package/lib/slot/upgradeStateToAltair.js.map +1 -1
  156. package/lib/slot/upgradeStateToBellatrix.js.map +1 -1
  157. package/lib/slot/upgradeStateToCapella.js.map +1 -1
  158. package/lib/slot/upgradeStateToDeneb.js.map +1 -1
  159. package/lib/slot/upgradeStateToElectra.js.map +1 -1
  160. package/lib/slot/upgradeStateToFulu.js.map +1 -1
  161. package/lib/slot/upgradeStateToGloas.d.ts.map +1 -1
  162. package/lib/slot/upgradeStateToGloas.js +50 -0
  163. package/lib/slot/upgradeStateToGloas.js.map +1 -1
  164. package/lib/stateTransition.d.ts +2 -1
  165. package/lib/stateTransition.d.ts.map +1 -1
  166. package/lib/stateTransition.js +6 -3
  167. package/lib/stateTransition.js.map +1 -1
  168. package/lib/stateView/beaconStateView.d.ts +144 -0
  169. package/lib/stateView/beaconStateView.d.ts.map +1 -0
  170. package/lib/stateView/beaconStateView.js +496 -0
  171. package/lib/stateView/beaconStateView.js.map +1 -0
  172. package/lib/stateView/index.d.ts +3 -0
  173. package/lib/stateView/index.d.ts.map +1 -0
  174. package/lib/stateView/index.js +3 -0
  175. package/lib/stateView/index.js.map +1 -0
  176. package/lib/stateView/interface.d.ts +118 -0
  177. package/lib/stateView/interface.d.ts.map +1 -0
  178. package/lib/stateView/interface.js +2 -0
  179. package/lib/stateView/interface.js.map +1 -0
  180. package/lib/testUtils/cache.d.ts +2 -0
  181. package/lib/testUtils/cache.d.ts.map +1 -0
  182. package/lib/testUtils/cache.js +7 -0
  183. package/lib/testUtils/cache.js.map +1 -0
  184. package/lib/testUtils/index.d.ts +6 -0
  185. package/lib/testUtils/index.d.ts.map +1 -0
  186. package/lib/testUtils/index.js +6 -0
  187. package/lib/testUtils/index.js.map +1 -0
  188. package/lib/testUtils/infura.d.ts +3 -0
  189. package/lib/testUtils/infura.d.ts.map +1 -0
  190. package/lib/testUtils/infura.js +8 -0
  191. package/lib/testUtils/infura.js.map +1 -0
  192. package/lib/testUtils/interop.d.ts +2 -0
  193. package/lib/testUtils/interop.d.ts.map +1 -0
  194. package/lib/testUtils/interop.js +24 -0
  195. package/lib/testUtils/interop.js.map +1 -0
  196. package/lib/testUtils/params.d.ts +18 -0
  197. package/lib/testUtils/params.d.ts.map +1 -0
  198. package/lib/testUtils/params.js +20 -0
  199. package/lib/testUtils/params.js.map +1 -0
  200. package/lib/testUtils/state.d.ts +20 -0
  201. package/lib/testUtils/state.d.ts.map +1 -0
  202. package/lib/testUtils/state.js +78 -0
  203. package/lib/testUtils/state.js.map +1 -0
  204. package/lib/testUtils/testFileCache.d.ts +17 -0
  205. package/lib/testUtils/testFileCache.d.ts.map +1 -0
  206. package/lib/testUtils/testFileCache.js +96 -0
  207. package/lib/testUtils/testFileCache.js.map +1 -0
  208. package/lib/testUtils/util.d.ts +50 -0
  209. package/lib/testUtils/util.d.ts.map +1 -0
  210. package/lib/testUtils/util.js +329 -0
  211. package/lib/testUtils/util.js.map +1 -0
  212. package/lib/util/aggregator.js.map +1 -1
  213. package/lib/util/altair.js.map +1 -1
  214. package/lib/util/array.js.map +1 -1
  215. package/lib/util/attestation.js.map +1 -1
  216. package/lib/util/attesterStatus.js.map +1 -1
  217. package/lib/util/balance.js.map +1 -1
  218. package/lib/util/blindedBlock.js.map +1 -1
  219. package/lib/util/blockRoot.js.map +1 -1
  220. package/lib/util/capella.js.map +1 -1
  221. package/lib/util/computeAnchorCheckpoint.js.map +1 -1
  222. package/lib/util/deposit.js.map +1 -1
  223. package/lib/util/domain.js.map +1 -1
  224. package/lib/util/electra.js.map +1 -1
  225. package/lib/util/epoch.js.map +1 -1
  226. package/lib/util/epochShuffling.js.map +1 -1
  227. package/lib/util/execution.js.map +1 -1
  228. package/lib/util/finality.js.map +1 -1
  229. package/lib/util/fulu.js.map +1 -1
  230. package/lib/util/genesis.js.map +1 -1
  231. package/lib/util/gloas.d.ts.map +1 -1
  232. package/lib/util/gloas.js +10 -3
  233. package/lib/util/gloas.js.map +1 -1
  234. package/lib/util/interop.js.map +1 -1
  235. package/lib/util/loadState/findModifiedInactivityScores.js.map +1 -1
  236. package/lib/util/loadState/findModifiedValidators.js.map +1 -1
  237. package/lib/util/loadState/loadState.js.map +1 -1
  238. package/lib/util/loadState/loadValidator.js.map +1 -1
  239. package/lib/util/rootCache.d.ts.map +1 -1
  240. package/lib/util/rootCache.js.map +1 -1
  241. package/lib/util/seed.d.ts +20 -12
  242. package/lib/util/seed.d.ts.map +1 -1
  243. package/lib/util/seed.js +80 -72
  244. package/lib/util/seed.js.map +1 -1
  245. package/lib/util/shuffling.js +2 -1
  246. package/lib/util/shuffling.js.map +1 -1
  247. package/lib/util/signatureSets.d.ts +7 -7
  248. package/lib/util/signatureSets.d.ts.map +1 -1
  249. package/lib/util/signatureSets.js +20 -13
  250. package/lib/util/signatureSets.js.map +1 -1
  251. package/lib/util/signingRoot.js.map +1 -1
  252. package/lib/util/slot.js.map +1 -1
  253. package/lib/util/sszBytes.js.map +1 -1
  254. package/lib/util/syncCommittee.js.map +1 -1
  255. package/lib/util/targetUnslashedBalance.js.map +1 -1
  256. package/lib/util/validator.js.map +1 -1
  257. package/lib/util/weakSubjectivity.js +1 -1
  258. package/lib/util/weakSubjectivity.js.map +1 -1
  259. package/package.json +14 -9
  260. package/src/block/externalData.ts +2 -0
  261. package/src/block/index.ts +3 -3
  262. package/src/block/isValidIndexedAttestation.ts +5 -5
  263. package/src/block/isValidIndexedPayloadAttestation.ts +4 -4
  264. package/src/block/processAttestationPhase0.ts +1 -1
  265. package/src/block/processAttestationsAltair.ts +2 -2
  266. package/src/block/processAttesterSlashing.ts +4 -4
  267. package/src/block/processDepositRequest.ts +8 -5
  268. package/src/block/processExecutionPayloadBid.ts +12 -4
  269. package/src/block/processExecutionPayloadEnvelope.ts +40 -37
  270. package/src/block/processOperations.ts +1 -1
  271. package/src/block/processPayloadAttestation.ts +2 -2
  272. package/src/block/processProposerSlashing.ts +4 -4
  273. package/src/block/processRandao.ts +1 -1
  274. package/src/block/processSyncCommittee.ts +1 -1
  275. package/src/block/processVoluntaryExit.ts +1 -1
  276. package/src/block/processWithdrawalRequest.ts +2 -2
  277. package/src/block/processWithdrawals.ts +11 -2
  278. package/src/cache/epochCache.ts +62 -54
  279. package/src/cache/pubkeyCache.ts +62 -21
  280. package/src/cache/stateCache.ts +4 -8
  281. package/src/cache/syncCommitteeCache.ts +4 -5
  282. package/src/epoch/index.ts +1 -1
  283. package/src/epoch/processBuilderPendingPayments.ts +2 -2
  284. package/src/index.ts +3 -1
  285. package/src/lightClient/proofs.ts +83 -0
  286. package/src/lightClient/types.ts +33 -0
  287. package/src/rewards/attestationsRewards.ts +5 -5
  288. package/src/rewards/syncCommitteeRewards.ts +6 -5
  289. package/src/signatureSets/indexedPayloadAttestation.ts +4 -6
  290. package/src/signatureSets/proposer.ts +3 -3
  291. package/src/signatureSets/randao.ts +3 -7
  292. package/src/signatureSets/voluntaryExits.ts +3 -3
  293. package/src/slot/upgradeStateToGloas.ts +74 -0
  294. package/src/stateTransition.ts +2 -1
  295. package/src/stateView/beaconStateView.ts +744 -0
  296. package/src/stateView/index.ts +2 -0
  297. package/src/stateView/interface.ts +196 -0
  298. package/src/testUtils/cache.ts +8 -0
  299. package/src/testUtils/index.ts +5 -0
  300. package/src/testUtils/infura.ts +10 -0
  301. package/src/testUtils/interop.ts +29 -0
  302. package/src/testUtils/params.ts +23 -0
  303. package/src/testUtils/state.ts +110 -0
  304. package/src/testUtils/testFileCache.ts +127 -0
  305. package/src/testUtils/util.ts +429 -0
  306. package/src/util/gloas.ts +11 -3
  307. package/src/util/seed.ts +106 -89
  308. package/src/util/signatureSets.ts +23 -17
  309. package/src/util/weakSubjectivity.ts +1 -1
@@ -0,0 +1,429 @@
1
+ import {PublicKey, SecretKey} from "@chainsafe/blst";
2
+ import {BitArray, fromHexString} from "@chainsafe/ssz";
3
+ import {createBeaconConfig, createChainForkConfig} from "@lodestar/config";
4
+ import {config} from "@lodestar/config/default";
5
+ import {
6
+ EPOCHS_PER_ETH1_VOTING_PERIOD,
7
+ EPOCHS_PER_HISTORICAL_VECTOR,
8
+ ForkName,
9
+ ForkSeq,
10
+ MAX_ATTESTATIONS,
11
+ MAX_EFFECTIVE_BALANCE,
12
+ SLOTS_PER_EPOCH,
13
+ SLOTS_PER_HISTORICAL_ROOT,
14
+ } from "@lodestar/params";
15
+ import {BeaconState, Slot, phase0, ssz} from "@lodestar/types";
16
+ import {getEffectiveBalanceIncrements} from "../cache/effectiveBalanceIncrements.js";
17
+ import {
18
+ computeCommitteeCount,
19
+ computeEpochAtSlot,
20
+ createCachedBeaconState,
21
+ createPubkeyCache,
22
+ interopSecretKey,
23
+ newFilledArray,
24
+ processSlots,
25
+ } from "../index.js";
26
+ import {
27
+ BeaconStateAltair,
28
+ BeaconStatePhase0,
29
+ CachedBeaconStateAllForks,
30
+ CachedBeaconStateAltair,
31
+ CachedBeaconStatePhase0,
32
+ } from "../types.js";
33
+ import {getNextSyncCommittee} from "../util/syncCommittee.js";
34
+ import {getActiveValidatorIndices} from "../util/validator.js";
35
+ import {interopPubkeysCached} from "./interop.js";
36
+
37
+ let phase0State: BeaconStatePhase0 | null = null;
38
+ let phase0CachedState23637: CachedBeaconStatePhase0 | null = null;
39
+ let phase0CachedState23638: CachedBeaconStatePhase0 | null = null;
40
+ let phase0SignedBlock: phase0.SignedBeaconBlock | null = null;
41
+ let altairState: BeaconStateAltair | null = null;
42
+ let altairCachedState23637: CachedBeaconStateAltair | null = null;
43
+ let altairCachedState23638: CachedBeaconStateAltair | null = null;
44
+
45
+ /**
46
+ * Number of validators in prater is 210000 as of May 2021
47
+ */
48
+ export const numValidators = 250000;
49
+ export const keypairsMod = 100;
50
+
51
+ /**
52
+ * As of Jul 07 2021, the performance state has
53
+ * out.prevEpochUnslashedStake.targetStake 7750000000000000n
54
+ * out.currEpochUnslashedTargetStake 7750000000000000n
55
+ * This prefix represent the total stake in Peta Wei
56
+ */
57
+ export const perfStateId = `${numValidators} vs - 7PWei`;
58
+
59
+ /** Cache interop secret keys */
60
+ const secretKeyByModIndex = new Map<number, SecretKey>();
61
+ const epoch = 23638;
62
+ export const perfStateEpoch = epoch;
63
+
64
+ export function getPubkeys(vc = numValidators) {
65
+ const pubkeysMod = interopPubkeysCached(keypairsMod);
66
+ const pubkeysModObj = pubkeysMod.map((pk) => PublicKey.fromBytes(pk));
67
+ const pubkeys = Array.from({length: vc}, (_, i) => pubkeysMod[i % keypairsMod]);
68
+ return {pubkeysMod, pubkeysModObj, pubkeys};
69
+ }
70
+
71
+ /** Get secret key of a validatorIndex, if the pubkeys are generated with `getPubkeys()` */
72
+ export function getSecretKeyFromIndex(validatorIndex: number): SecretKey {
73
+ return interopSecretKey(validatorIndex % keypairsMod);
74
+ }
75
+
76
+ /** Get secret key of a validatorIndex, if the pubkeys are generated with `getPubkeys()` */
77
+ export function getSecretKeyFromIndexCached(validatorIndex: number): SecretKey {
78
+ const keyIndex = validatorIndex % keypairsMod;
79
+ let sk = secretKeyByModIndex.get(keyIndex);
80
+ if (!sk) {
81
+ sk = interopSecretKey(keyIndex);
82
+ secretKeyByModIndex.set(keyIndex, sk);
83
+ }
84
+ return sk;
85
+ }
86
+
87
+ function getPubkeyCaches({pubkeysMod}: ReturnType<typeof getPubkeys>) {
88
+ // Manually sync pubkeys to prevent doing BLS opts 110_000 times
89
+ const pubkeyCache = createPubkeyCache();
90
+ for (let i = 0; i < numValidators; i++) {
91
+ const pubkey = pubkeysMod[i % keypairsMod];
92
+ pubkeyCache.set(i, pubkey);
93
+ }
94
+
95
+ return {pubkeyCache};
96
+ }
97
+
98
+ export function generatePerfTestCachedStatePhase0(opts?: {goBackOneSlot: boolean}): CachedBeaconStatePhase0 {
99
+ // Generate only some publicKeys
100
+ const {pubkeys, pubkeysMod, pubkeysModObj} = getPubkeys();
101
+ const {pubkeyCache} = getPubkeyCaches({pubkeys, pubkeysMod, pubkeysModObj});
102
+
103
+ if (!phase0State) {
104
+ const state = buildPerformanceStatePhase0();
105
+
106
+ // no justificationBits
107
+ phase0State = ssz.phase0.BeaconState.toViewDU(state);
108
+
109
+ // cache roots
110
+ phase0State.hashTreeRoot();
111
+ }
112
+
113
+ if (!phase0CachedState23637) {
114
+ const state = phase0State.clone();
115
+ state.slot -= 1;
116
+ phase0CachedState23637 = createCachedBeaconState(state, {
117
+ config: createBeaconConfig(config, state.genesisValidatorsRoot),
118
+ pubkeyCache,
119
+ });
120
+
121
+ const currentEpoch = computeEpochAtSlot(state.slot - 1);
122
+ const previousEpoch = currentEpoch - 1;
123
+
124
+ // previous epoch attestations
125
+ const numPrevAttestations = SLOTS_PER_EPOCH * MAX_ATTESTATIONS;
126
+ const activeValidatorCount = pubkeys.length;
127
+ const committeesPerSlot = computeCommitteeCount(activeValidatorCount);
128
+ for (let i = 0; i < numPrevAttestations; i++) {
129
+ const slotInEpoch = i % SLOTS_PER_EPOCH;
130
+ const slot = previousEpoch * SLOTS_PER_EPOCH + slotInEpoch;
131
+ const index = i % committeesPerSlot;
132
+ const shuffling = phase0CachedState23637.epochCtx.getShufflingAtEpoch(previousEpoch);
133
+ const committee = shuffling.committees[slotInEpoch][index];
134
+ phase0CachedState23637.previousEpochAttestations.push(
135
+ ssz.phase0.PendingAttestation.toViewDU({
136
+ aggregationBits: BitArray.fromBoolArray(Array.from({length: committee.length}, () => true)),
137
+ data: {
138
+ beaconBlockRoot: phase0CachedState23637.blockRoots.get(slotInEpoch % SLOTS_PER_HISTORICAL_ROOT),
139
+ index,
140
+ slot,
141
+ source: state.previousJustifiedCheckpoint,
142
+ target: state.currentJustifiedCheckpoint,
143
+ },
144
+ inclusionDelay: 1,
145
+ proposerIndex: i,
146
+ })
147
+ );
148
+ }
149
+
150
+ // current epoch attestations
151
+ const numCurAttestations = (SLOTS_PER_EPOCH - 1) * MAX_ATTESTATIONS;
152
+ for (let i = 0; i < numCurAttestations; i++) {
153
+ const slotInEpoch = i % SLOTS_PER_EPOCH;
154
+ const slot = currentEpoch * SLOTS_PER_EPOCH + slotInEpoch;
155
+ const index = i % committeesPerSlot;
156
+ const shuffling = phase0CachedState23637.epochCtx.getShufflingAtEpoch(previousEpoch);
157
+ const committee = shuffling.committees[slotInEpoch][index];
158
+
159
+ phase0CachedState23637.currentEpochAttestations.push(
160
+ ssz.phase0.PendingAttestation.toViewDU({
161
+ aggregationBits: BitArray.fromBoolArray(Array.from({length: committee.length}, () => true)),
162
+ data: {
163
+ beaconBlockRoot: phase0CachedState23637.blockRoots.get(slotInEpoch % SLOTS_PER_HISTORICAL_ROOT),
164
+ index,
165
+ slot,
166
+ source: state.currentJustifiedCheckpoint,
167
+ target: {
168
+ epoch: currentEpoch,
169
+ root: phase0CachedState23637.blockRoots.get((currentEpoch * SLOTS_PER_EPOCH) % SLOTS_PER_HISTORICAL_ROOT),
170
+ },
171
+ },
172
+ inclusionDelay: 1,
173
+ proposerIndex: i,
174
+ })
175
+ );
176
+ }
177
+ }
178
+ if (!phase0CachedState23638) {
179
+ phase0CachedState23638 = processSlots(
180
+ phase0CachedState23637,
181
+ phase0CachedState23637.slot + 1
182
+ ) as CachedBeaconStatePhase0;
183
+ phase0CachedState23638.slot += 1;
184
+ }
185
+ const resultingState = opts?.goBackOneSlot ? phase0CachedState23637 : phase0CachedState23638;
186
+
187
+ return resultingState.clone();
188
+ }
189
+
190
+ export function cachedStateAltairPopulateCaches(state: CachedBeaconStateAltair): void {
191
+ // Populate caches
192
+ state.blockRoots.getAllReadonly();
193
+ state.eth1DataVotes.getAllReadonly();
194
+ state.validators.getAllReadonly();
195
+ state.balances.getAll();
196
+ state.previousEpochParticipation.getAll();
197
+ state.currentEpochParticipation.getAll();
198
+ state.inactivityScores.getAll();
199
+ }
200
+
201
+ /**
202
+ * Warning: This function has side effects on the cached state
203
+ * The order in which the caches are populated is important and can cause stable tests to fail.
204
+ */
205
+ export function generatePerfTestCachedStateAltair(opts?: {
206
+ goBackOneSlot: boolean;
207
+ vc?: number;
208
+ }): CachedBeaconStateAltair {
209
+ const {pubkeys, pubkeysMod, pubkeysModObj} = getPubkeys(opts?.vc);
210
+ const {pubkeyCache} = getPubkeyCaches({pubkeys, pubkeysMod, pubkeysModObj});
211
+
212
+ const altairConfig = createChainForkConfig({ALTAIR_FORK_EPOCH: 0});
213
+
214
+ const origState = generatePerformanceStateAltair(pubkeys);
215
+
216
+ if (!altairCachedState23637) {
217
+ const state = origState.clone();
218
+ state.slot -= 1;
219
+ altairCachedState23637 = createCachedBeaconState(state, {
220
+ config: createBeaconConfig(altairConfig, state.genesisValidatorsRoot),
221
+ pubkeyCache,
222
+ });
223
+ }
224
+ if (!altairCachedState23638) {
225
+ altairCachedState23638 = processSlots(
226
+ altairCachedState23637,
227
+ altairCachedState23637.slot + 1
228
+ ) as CachedBeaconStateAltair;
229
+ altairCachedState23638.slot += 1;
230
+ }
231
+ const resultingState = opts?.goBackOneSlot ? altairCachedState23637 : altairCachedState23638;
232
+
233
+ return resultingState.clone();
234
+ }
235
+
236
+ /**
237
+ * This is generated from Medalla state 756416
238
+ */
239
+ export function generatePerformanceStateAltair(pubkeysArg?: Uint8Array[]): BeaconStateAltair {
240
+ if (!altairState) {
241
+ const pubkeys = pubkeysArg || getPubkeys().pubkeys;
242
+ const statePhase0 = buildPerformanceStatePhase0(pubkeys);
243
+ const state = statePhase0 as BeaconState as BeaconState<ForkName.altair>;
244
+
245
+ state.previousEpochParticipation = newFilledArray(pubkeys.length, 0b111);
246
+ state.currentEpochParticipation = state.previousEpochParticipation;
247
+ state.inactivityScores = Array.from({length: pubkeys.length}, (_, i) => i % 2);
248
+
249
+ // Placeholder syncCommittees
250
+ state.currentSyncCommittee = ssz.altair.SyncCommittee.defaultValue();
251
+ state.nextSyncCommittee = state.currentSyncCommittee;
252
+
253
+ // Now the state is fully populated to convert to ViewDU
254
+ altairState = ssz.altair.BeaconState.toViewDU(state);
255
+
256
+ // Now set correct syncCommittees
257
+ const epoch = computeEpochAtSlot(state.slot);
258
+ const activeValidatorIndices = getActiveValidatorIndices(altairState, epoch);
259
+
260
+ const effectiveBalanceIncrements = getEffectiveBalanceIncrements(altairState);
261
+ const {syncCommittee} = getNextSyncCommittee(
262
+ ForkSeq.altair,
263
+ altairState,
264
+ activeValidatorIndices,
265
+ effectiveBalanceIncrements
266
+ );
267
+ state.currentSyncCommittee = syncCommittee;
268
+ state.nextSyncCommittee = syncCommittee;
269
+
270
+ altairState = ssz.altair.BeaconState.toViewDU(state);
271
+ // cache roots
272
+ altairState.hashTreeRoot();
273
+ }
274
+ return altairState.clone();
275
+ }
276
+
277
+ /**
278
+ * This is generated from Medalla block 756417
279
+ */
280
+ export function generatePerformanceBlockPhase0(): phase0.SignedBeaconBlock {
281
+ if (!phase0SignedBlock) {
282
+ const block = ssz.phase0.SignedBeaconBlock.defaultValue();
283
+ const parentState = generatePerfTestCachedStatePhase0();
284
+ block.message.slot = parentState.slot;
285
+ block.message.proposerIndex = parentState.epochCtx.getBeaconProposer(parentState.slot);
286
+ block.message.parentRoot = ssz.phase0.BeaconBlockHeader.hashTreeRoot(parentState.latestBlockHeader);
287
+ block.message.stateRoot = fromHexString("0x6c86ca3c4c6688cf189421b8a68bf2dbc91521609965e6f4e207d44347061fee");
288
+ block.message.body.randaoReveal = fromHexString(
289
+ "0x8a5d2673c48f22f6ed19462efec35645db490df29eed2f56321dbe4a89b2463b0c902095a7ab74a2dc5b7f67edb1a19507ea3d4361d5af9cb0a524945c91638dfd6568841486813a2c45142659d6d9403f5081febb123a7931edbc248b9d0025"
290
+ );
291
+ // eth1Data, graffiti, attestations
292
+ phase0SignedBlock = block;
293
+ }
294
+
295
+ return phase0SignedBlock;
296
+ }
297
+
298
+ function buildPerformanceStatePhase0(pubkeysArg?: Uint8Array[]): phase0.BeaconState {
299
+ const slot = epoch * SLOTS_PER_EPOCH;
300
+ const pubkeys = pubkeysArg || getPubkeys().pubkeys;
301
+ const currentEpoch = computeEpochAtSlot(slot - 1);
302
+
303
+ return {
304
+ // Misc
305
+ genesisTime: 1596546008,
306
+ genesisValidatorsRoot: fromHexString("0x04700007fabc8282644aed6d1c7c9e21d38a03a0c4ba193f3afe428824b3a673"),
307
+ slot: epoch * SLOTS_PER_EPOCH,
308
+ fork: {
309
+ currentVersion: fromHexString("0x00000001"),
310
+ previousVersion: fromHexString("0x00000001"),
311
+ epoch: 0,
312
+ },
313
+ // History
314
+ latestBlockHeader: {
315
+ slot: slot - 1,
316
+ proposerIndex: 80882,
317
+ parentRoot: fromHexString("0x5b83c3078e474b86af60043eda82a34c3c2e5ebf83146b14d9d909aea4163ef2"),
318
+ stateRoot: fromHexString("0x2761ae355e8a53c11e0e37d5e417f8984db0c53fa83f1bc65f89c6af35a196a7"),
319
+ bodyRoot: fromHexString("0x249a1962eef90e122fa2447040bfac102798b1dba9c73e5593bc5aa32eb92bfd"),
320
+ },
321
+ blockRoots: Array.from({length: SLOTS_PER_HISTORICAL_ROOT}, (_, i) => Buffer.alloc(32, i)),
322
+ stateRoots: Array.from({length: SLOTS_PER_HISTORICAL_ROOT}, (_, i) => Buffer.alloc(32, i)),
323
+ historicalRoots: [],
324
+ // Eth1
325
+ eth1Data: {
326
+ depositCount: pubkeys.length,
327
+ depositRoot: fromHexString("0xcb1f89a924cfd31224823db5a41b1643f10faa7aedf231f1e28887f6ee98c047"),
328
+ blockHash: fromHexString("0x701fb2869ce16d0f1d14f6705725adb0dec6799da29006dfc6fff83960298f21"),
329
+ },
330
+ // minus one so that inserting 1 from block works
331
+ eth1DataVotes: newFilledArray(EPOCHS_PER_ETH1_VOTING_PERIOD * SLOTS_PER_EPOCH - 1, {
332
+ depositCount: 1,
333
+ depositRoot: Buffer.alloc(32, 1),
334
+ blockHash: Buffer.alloc(32, 1),
335
+ }),
336
+ eth1DepositIndex: pubkeys.length,
337
+ // Registry
338
+ validators: pubkeys.map((_, i) => ({
339
+ pubkey: pubkeys[i],
340
+ withdrawalCredentials: Buffer.alloc(32, i),
341
+ effectiveBalance: 31000000000,
342
+ slashed: false,
343
+ activationEligibilityEpoch: 0,
344
+ activationEpoch: 0,
345
+ exitEpoch: Infinity,
346
+ withdrawableEpoch: Infinity,
347
+ })),
348
+ balances: Array.from({length: pubkeys.length}, () => 31217089836),
349
+ randaoMixes: Array.from({length: EPOCHS_PER_HISTORICAL_VECTOR}, (_, i) => Buffer.alloc(32, i)),
350
+ // Slashings
351
+ slashings: ssz.phase0.Slashings.defaultValue(),
352
+ previousEpochAttestations: [],
353
+ currentEpochAttestations: [],
354
+ // Finality
355
+ justificationBits: BitArray.fromBitLen(4),
356
+ previousJustifiedCheckpoint: {
357
+ epoch: currentEpoch - 2,
358
+ root: fromHexString("0x3fe60bf06a57b0956cd1f8181d26649cf8bf79e48bf82f55562e04b33d4785d4"),
359
+ },
360
+ currentJustifiedCheckpoint: {
361
+ epoch: currentEpoch - 1,
362
+ root: fromHexString("0x3ba0913d2fb5e4cbcfb0d39eb15803157c1e769d63b8619285d8fdabbd8181c7"),
363
+ },
364
+ finalizedCheckpoint: {
365
+ epoch: currentEpoch - 3,
366
+ root: fromHexString("0x122b8ff579d0c8f8a8b66326bdfec3f685007d2842f01615a0768870961ccc17"),
367
+ },
368
+ };
369
+ }
370
+
371
+ export function generateTestCachedBeaconStateOnlyValidators({
372
+ vc,
373
+ slot,
374
+ }: {
375
+ vc: number;
376
+ slot: Slot;
377
+ }): CachedBeaconStateAllForks {
378
+ // Generate only some publicKeys
379
+ const {pubkeys, pubkeysMod} = getPubkeys(vc);
380
+
381
+ // Manually sync pubkeys to prevent doing BLS opts 110_000 times
382
+ const pubkeyCache = createPubkeyCache();
383
+ for (let i = 0; i < vc; i++) {
384
+ const pubkey = pubkeysMod[i % keypairsMod];
385
+ pubkeyCache.set(i, pubkey);
386
+ }
387
+
388
+ const state = ssz.phase0.BeaconState.defaultViewDU();
389
+ state.slot = slot;
390
+
391
+ const activeValidator = ssz.phase0.Validator.toViewDU({
392
+ pubkey: Buffer.alloc(48, 0),
393
+ withdrawalCredentials: Buffer.alloc(32, 0),
394
+ effectiveBalance: MAX_EFFECTIVE_BALANCE,
395
+ slashed: false,
396
+ activationEligibilityEpoch: 0,
397
+ activationEpoch: 0,
398
+ exitEpoch: Infinity,
399
+ withdrawableEpoch: Infinity,
400
+ });
401
+
402
+ for (let i = 0; i < vc; i++) {
403
+ const validator = activeValidator.clone();
404
+ validator.pubkey = pubkeys[i];
405
+ state.validators.push(validator);
406
+ }
407
+
408
+ state.balances = ssz.phase0.Balances.toViewDU(newFilledArray(pubkeys.length, MAX_EFFECTIVE_BALANCE));
409
+ state.randaoMixes = ssz.phase0.RandaoMixes.toViewDU(
410
+ newFilledArray(EPOCHS_PER_HISTORICAL_VECTOR, Buffer.alloc(32, 0xdd))
411
+ );
412
+
413
+ // Commit ViewDU changes
414
+ state.commit();
415
+
416
+ // Sanity check for .commit() above
417
+ if (state.validators.length !== vc) {
418
+ throw Error(`Wrong number of validators in the state: ${state.validators.length} !== ${vc}`);
419
+ }
420
+
421
+ return createCachedBeaconState(
422
+ state,
423
+ {
424
+ config: createBeaconConfig(config, state.genesisValidatorsRoot),
425
+ pubkeyCache,
426
+ },
427
+ {skipSyncPubkeys: true}
428
+ );
429
+ }
package/src/util/gloas.ts CHANGED
@@ -28,12 +28,18 @@ export function getBuilderPaymentQuorumThreshold(state: CachedBeaconStateGloas):
28
28
  return Math.floor(quorum / BUILDER_PAYMENT_THRESHOLD_DENOMINATOR);
29
29
  }
30
30
 
31
+ function hasBuilderIndexFlag(index: number): boolean {
32
+ // Equivalent to `(index & BUILDER_INDEX_FLAG) != 0`
33
+ return Math.floor(index / BUILDER_INDEX_FLAG) % 2 === 1;
34
+ }
35
+
31
36
  /**
32
37
  * Check if a validator index represents a builder (has the builder flag set).
33
38
  * Spec: https://github.com/ethereum/consensus-specs/blob/v1.7.0-alpha.1/specs/gloas/beacon-chain.md#new-is_builder_index
34
39
  */
35
40
  export function isBuilderIndex(validatorIndex: number): boolean {
36
- return (validatorIndex & BUILDER_INDEX_FLAG) !== 0;
41
+ // Note: Can't use bitwise AND (&) because BUILDER_INDEX_FLAG exceeds 32 bits in JS bitwise operations.
42
+ return hasBuilderIndexFlag(validatorIndex);
37
43
  }
38
44
 
39
45
  /**
@@ -41,7 +47,8 @@ export function isBuilderIndex(validatorIndex: number): boolean {
41
47
  * Spec: https://github.com/ethereum/consensus-specs/blob/v1.7.0-alpha.1/specs/gloas/beacon-chain.md#new-convert_builder_index_to_validator_index
42
48
  */
43
49
  export function convertBuilderIndexToValidatorIndex(builderIndex: BuilderIndex): ValidatorIndex {
44
- return builderIndex | BUILDER_INDEX_FLAG;
50
+ // Note: Can't use bitwise OR (|) because BUILDER_INDEX_FLAG exceeds 32 bits in JS bitwise operations.
51
+ return hasBuilderIndexFlag(builderIndex) ? builderIndex : builderIndex + BUILDER_INDEX_FLAG;
45
52
  }
46
53
 
47
54
  /**
@@ -49,7 +56,8 @@ export function convertBuilderIndexToValidatorIndex(builderIndex: BuilderIndex):
49
56
  * Spec: https://github.com/ethereum/consensus-specs/blob/v1.7.0-alpha.1/specs/gloas/beacon-chain.md#new-convert_validator_index_to_builder_index
50
57
  */
51
58
  export function convertValidatorIndexToBuilderIndex(validatorIndex: ValidatorIndex): BuilderIndex {
52
- return validatorIndex & ~BUILDER_INDEX_FLAG;
59
+ // Note: Can't use bitwise AND (&) because BUILDER_INDEX_FLAG exceeds 32 bits in JS bitwise operations.
60
+ return hasBuilderIndexFlag(validatorIndex) ? validatorIndex - BUILDER_INDEX_FLAG : validatorIndex;
53
61
  }
54
62
 
55
63
  /**
package/src/util/seed.ts CHANGED
@@ -21,7 +21,7 @@ import {
21
21
  import {Bytes32, DomainType, Epoch, ValidatorIndex} from "@lodestar/types";
22
22
  import {assert, bytesToBigInt, bytesToInt, intToBytes} from "@lodestar/utils";
23
23
  import {EffectiveBalanceIncrements} from "../cache/effectiveBalanceIncrements.js";
24
- import {BeaconStateAllForks, BeaconStateGloas, CachedBeaconStateAllForks} from "../types.js";
24
+ import {BeaconStateAllForks, CachedBeaconStateAllForks} from "../types.js";
25
25
  import {computeEpochAtSlot, computeStartSlotAtEpoch} from "./epoch.js";
26
26
 
27
27
  /**
@@ -268,29 +268,117 @@ export function getNextSyncCommitteeIndices(
268
268
  );
269
269
  }
270
270
 
271
- export function naiveGetPayloadTimlinessCommitteeIndices(
272
- state: BeaconStateGloas,
273
- shuffling: {committees: Uint32Array[][]},
274
- effectiveBalanceIncrements: EffectiveBalanceIncrements,
275
- epoch: Epoch
276
- ): ValidatorIndex[][] {
271
+ /**
272
+ * Compute PTC for all slots in an epoch eagerly.
273
+ */
274
+ export function computePayloadTimelinessCommitteesForEpoch(
275
+ state: BeaconStateAllForks,
276
+ epoch: number,
277
+ committees: Uint32Array[][],
278
+ effectiveBalanceIncrements: EffectiveBalanceIncrements
279
+ ): Uint32Array[] {
277
280
  const epochSeed = getSeed(state, epoch, DOMAIN_PTC_ATTESTER);
278
- const startSlot = computeStartSlotAtEpoch(epoch);
279
- const committeeIndices = [];
281
+ const startSlot = epoch * SLOTS_PER_EPOCH;
282
+ const result: Uint32Array[] = new Array(SLOTS_PER_EPOCH);
283
+
284
+ // Pre-allocate slot seed buffer once, reuse across all slots
285
+ const slotSeedInput = new Uint8Array(epochSeed.length + 8);
286
+ slotSeedInput.set(epochSeed, 0);
287
+ const slotSeedView = new DataView(slotSeedInput.buffer, slotSeedInput.byteOffset, slotSeedInput.byteLength);
288
+
289
+ for (let i = 0; i < SLOTS_PER_EPOCH; i++) {
290
+ const slot = startSlot + i;
291
+ // Write slot as little-endian uint64 (fits in uint32 range)
292
+ slotSeedView.setUint32(epochSeed.length, slot, true);
293
+ slotSeedView.setUint32(epochSeed.length + 4, 0, true);
294
+ const slotSeed = digest(slotSeedInput);
295
+
296
+ result[i] = computePayloadTimelinessCommitteeForSlot(slotSeed, committees[i], effectiveBalanceIncrements);
297
+ }
298
+ return result;
299
+ }
280
300
 
281
- for (let slot = startSlot; slot < startSlot + SLOTS_PER_EPOCH; slot++) {
282
- const slotCommittees = shuffling.committees[slot % SLOTS_PER_EPOCH];
283
- const indices = naiveComputePayloadTimelinessCommitteeIndices(
284
- effectiveBalanceIncrements,
285
- slotCommittees.flatMap((c) => Array.from(c)),
286
- digest(Buffer.concat([epochSeed, intToBytes(slot, 8)]))
287
- );
288
- committeeIndices.push(indices);
301
+ /**
302
+ * Compute PTC for a single slot.
303
+ */
304
+ export function computePayloadTimelinessCommitteeForSlot(
305
+ slotSeed: Uint8Array,
306
+ slotCommittees: Uint32Array[],
307
+ effectiveBalanceIncrements: EffectiveBalanceIncrements
308
+ ): Uint32Array {
309
+ // Concatenate all committee Uint32Arrays for this slot
310
+ const totalLen = slotCommittees.reduce((sum, c) => sum + c.length, 0);
311
+ const allIndices = new Uint32Array(totalLen);
312
+ let offset = 0;
313
+ for (const c of slotCommittees) {
314
+ allIndices.set(c, offset);
315
+ offset += c.length;
316
+ }
317
+ return computePayloadTimelinessCommitteeIndices(effectiveBalanceIncrements, allIndices, slotSeed);
318
+ }
319
+
320
+ /**
321
+ * Optimized version of PTC indices computation.
322
+ * Avoids BigInt conversions and uses DataView for efficient byte reading.
323
+ */
324
+ export function computePayloadTimelinessCommitteeIndices(
325
+ effectiveBalanceIncrements: EffectiveBalanceIncrements,
326
+ indices: Uint32Array,
327
+ seed: Uint8Array
328
+ ): Uint32Array {
329
+ if (indices.length === 0) {
330
+ throw Error("Validator indices must not be empty");
289
331
  }
290
332
 
291
- return committeeIndices;
333
+ const result = new Uint32Array(PTC_SIZE);
334
+ let resultLen = 0;
335
+
336
+ const MAX_RANDOM_VALUE = 0xffff; // 2^16 - 1
337
+ const MAX_EFFECTIVE_BALANCE_INCREMENT = MAX_EFFECTIVE_BALANCE_ELECTRA / EFFECTIVE_BALANCE_INCREMENT;
338
+ const indicesLen = indices.length;
339
+
340
+ // Pre-allocate hash input buffer: seed + 8 bytes for block index
341
+ const hashInput = new Uint8Array(seed.length + 8);
342
+ hashInput.set(seed, 0);
343
+ const hashInputView = new DataView(hashInput.buffer, hashInput.byteOffset, hashInput.byteLength);
344
+ const seedLen = seed.length;
345
+
346
+ let i = 0;
347
+ let randomBytesView: DataView = new DataView(new ArrayBuffer(0));
348
+ let lastBlock = -1;
349
+
350
+ while (resultLen < PTC_SIZE) {
351
+ const candidateIndex = indices[i % indicesLen];
352
+
353
+ // Only recompute hash every 16 iterations
354
+ const block = i >>> 4; // Math.floor(i / 16)
355
+ if (block !== lastBlock) {
356
+ // Write block as little-endian uint64 (block always fits in uint32 range)
357
+ hashInputView.setUint32(seedLen, block, true);
358
+ hashInputView.setUint32(seedLen + 4, 0, true);
359
+ const randomBytes = digest(hashInput);
360
+ randomBytesView = new DataView(randomBytes.buffer, randomBytes.byteOffset, randomBytes.byteLength);
361
+ lastBlock = block;
362
+ }
363
+
364
+ const randomValue = randomBytesView.getUint16((i & 15) * 2, true);
365
+
366
+ const effectiveBalanceIncrement = effectiveBalanceIncrements[candidateIndex];
367
+ if (effectiveBalanceIncrement * MAX_RANDOM_VALUE >= MAX_EFFECTIVE_BALANCE_INCREMENT * randomValue) {
368
+ result[resultLen++] = candidateIndex;
369
+ }
370
+ i += 1;
371
+ }
372
+
373
+ return result;
292
374
  }
293
375
 
376
+ /**
377
+ * Naive version of PTC indices computation.
378
+ * Used to verify the optimized `computePayloadTimelinessCommitteeIndices`.
379
+ *
380
+ * SLOW CODE - 🐢
381
+ */
294
382
  export function naiveComputePayloadTimelinessCommitteeIndices(
295
383
  effectiveBalanceIncrements: EffectiveBalanceIncrements,
296
384
  indices: ArrayLike<ValidatorIndex>,
@@ -329,8 +417,6 @@ export function naiveComputePayloadTimelinessCommitteeIndices(
329
417
  * https://link.springer.com/content/pdf/10.1007%2F978-3-642-32009-5_1.pdf
330
418
  *
331
419
  * See the 'generalized domain' algorithm on page 3.
332
- * This is the naive implementation just to make sure lodestar follows the spec, this is not for production.
333
- * The optimized version is in `getComputeShuffledIndexFn`.
334
420
  */
335
421
  export function computeShuffledIndex(index: number, indexCount: number, seed: Bytes32): number {
336
422
  let permuted = index;
@@ -351,75 +437,6 @@ export function computeShuffledIndex(index: number, indexCount: number, seed: By
351
437
  return permuted;
352
438
  }
353
439
 
354
- type ComputeShuffledIndexFn = (index: number) => number;
355
-
356
- /**
357
- * An optimized version of `computeShuffledIndex`, this is for production.
358
- */
359
- export function getComputeShuffledIndexFn(indexCount: number, seed: Bytes32): ComputeShuffledIndexFn {
360
- // there are possibly SHUFFLE_ROUND_COUNT (90 for mainnet) values for this cache
361
- // this cache will always hit after the 1st call
362
- const pivotByIndex: Map<number, number> = new Map();
363
- // given 2M active validators, there are 2 M / 256 = 8k possible positionDiv
364
- // it means there are at most 8k different sources for each round
365
- const sourceByPositionDivByIndex: Map<number, Map<number, Uint8Array>> = new Map();
366
- // 32 bytes seed + 1 byte i
367
- const pivotBuffer = Buffer.alloc(32 + 1);
368
- pivotBuffer.set(seed, 0);
369
- // 32 bytes seed + 1 byte i + 4 bytes positionDiv
370
- const sourceBuffer = Buffer.alloc(32 + 1 + 4);
371
- sourceBuffer.set(seed, 0);
372
-
373
- return (index): number => {
374
- assert.lt(index, indexCount, "indexCount must be less than index");
375
- assert.lte(indexCount, 2 ** 40, "indexCount too big");
376
- let permuted = index;
377
- // const _seed = seed;
378
- for (let i = 0; i < SHUFFLE_ROUND_COUNT; i++) {
379
- // optimized version of the below naive code
380
- // const pivot = Number(
381
- // bytesToBigInt(digest(Buffer.concat([_seed, intToBytes(i, 1)])).slice(0, 8)) % BigInt(indexCount)
382
- // );
383
-
384
- let pivot = pivotByIndex.get(i);
385
- if (pivot == null) {
386
- // naive version always creates a new buffer, we can reuse the buffer
387
- // pivot = Number(
388
- // bytesToBigInt(digest(Buffer.concat([_seed, intToBytes(i, 1)])).slice(0, 8)) % BigInt(indexCount)
389
- // );
390
- pivotBuffer[32] = i % 256;
391
- pivot = Number(bytesToBigInt(digest(pivotBuffer).subarray(0, 8)) % BigInt(indexCount));
392
- pivotByIndex.set(i, pivot);
393
- }
394
-
395
- const flip = (pivot + indexCount - permuted) % indexCount;
396
- const position = Math.max(permuted, flip);
397
-
398
- // optimized version of the below naive code
399
- // const source = digest(Buffer.concat([_seed, intToBytes(i, 1), intToBytes(Math.floor(position / 256), 4)]));
400
- let sourceByPositionDiv = sourceByPositionDivByIndex.get(i);
401
- if (sourceByPositionDiv == null) {
402
- sourceByPositionDiv = new Map<number, Uint8Array>();
403
- sourceByPositionDivByIndex.set(i, sourceByPositionDiv);
404
- }
405
- const positionDiv256 = Math.floor(position / 256);
406
- let source = sourceByPositionDiv.get(positionDiv256);
407
- if (source == null) {
408
- // naive version always creates a new buffer, we can reuse the buffer
409
- // don't want to go through intToBytes() to avoid BigInt
410
- sourceBuffer[32] = i % 256;
411
- sourceBuffer.writeUint32LE(positionDiv256, 33);
412
- source = digest(sourceBuffer);
413
- sourceByPositionDiv.set(positionDiv256, source);
414
- }
415
- const byte = source[Math.floor((position % 256) / 8)];
416
- const bit = (byte >> (position % 8)) % 2;
417
- permuted = bit ? flip : permuted;
418
- }
419
- return permuted;
420
- };
421
- }
422
-
423
440
  /**
424
441
  * Return the randao mix at a recent [[epoch]].
425
442
  */