@lodestar/state-transition 1.41.0-dev.f2caa915ab → 1.41.0-dev.f7a5f4ddda

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 (198) hide show
  1. package/lib/block/externalData.js +4 -2
  2. package/lib/block/externalData.js.map +1 -1
  3. package/lib/block/index.d.ts +3 -3
  4. package/lib/block/index.js.map +1 -1
  5. package/lib/block/initiateValidatorExit.js.map +1 -1
  6. package/lib/block/isValidIndexedAttestation.js.map +1 -1
  7. package/lib/block/isValidIndexedPayloadAttestation.js.map +1 -1
  8. package/lib/block/processAttestationPhase0.js.map +1 -1
  9. package/lib/block/processAttestations.js.map +1 -1
  10. package/lib/block/processAttestationsAltair.js.map +1 -1
  11. package/lib/block/processAttesterSlashing.js.map +1 -1
  12. package/lib/block/processBlobKzgCommitments.js.map +1 -1
  13. package/lib/block/processBlockHeader.js.map +1 -1
  14. package/lib/block/processBlsToExecutionChange.js.map +1 -1
  15. package/lib/block/processConsolidationRequest.js.map +1 -1
  16. package/lib/block/processDeposit.js.map +1 -1
  17. package/lib/block/processDepositRequest.js.map +1 -1
  18. package/lib/block/processEth1Data.js.map +1 -1
  19. package/lib/block/processExecutionPayload.js.map +1 -1
  20. package/lib/block/processExecutionPayloadBid.d.ts +1 -1
  21. package/lib/block/processExecutionPayloadBid.js.map +1 -1
  22. package/lib/block/processExecutionPayloadEnvelope.d.ts +5 -2
  23. package/lib/block/processExecutionPayloadEnvelope.d.ts.map +1 -1
  24. package/lib/block/processExecutionPayloadEnvelope.js +20 -14
  25. package/lib/block/processExecutionPayloadEnvelope.js.map +1 -1
  26. package/lib/block/processOperations.js.map +1 -1
  27. package/lib/block/processPayloadAttestation.d.ts +1 -1
  28. package/lib/block/processPayloadAttestation.js.map +1 -1
  29. package/lib/block/processProposerSlashing.js.map +1 -1
  30. package/lib/block/processRandao.js.map +1 -1
  31. package/lib/block/processSyncCommittee.js.map +1 -1
  32. package/lib/block/processVoluntaryExit.js +2 -1
  33. package/lib/block/processVoluntaryExit.js.map +1 -1
  34. package/lib/block/processWithdrawalRequest.js.map +1 -1
  35. package/lib/block/processWithdrawals.js.map +1 -1
  36. package/lib/block/slashValidator.js.map +1 -1
  37. package/lib/block/types.js +2 -1
  38. package/lib/block/types.js.map +1 -1
  39. package/lib/cache/effectiveBalanceIncrements.js.map +1 -1
  40. package/lib/cache/epochCache.d.ts +2 -0
  41. package/lib/cache/epochCache.d.ts.map +1 -1
  42. package/lib/cache/epochCache.js +21 -6
  43. package/lib/cache/epochCache.js.map +1 -1
  44. package/lib/cache/epochTransitionCache.js.map +1 -1
  45. package/lib/cache/pubkeyCache.js.map +1 -1
  46. package/lib/cache/rewardCache.js.map +1 -1
  47. package/lib/cache/stateCache.js.map +1 -1
  48. package/lib/cache/syncCommitteeCache.js.map +1 -1
  49. package/lib/epoch/computeUnrealizedCheckpoints.js.map +1 -1
  50. package/lib/epoch/getAttestationDeltas.js.map +1 -1
  51. package/lib/epoch/getRewardsAndPenalties.js.map +1 -1
  52. package/lib/epoch/index.d.ts +1 -1
  53. package/lib/epoch/index.js +2 -1
  54. package/lib/epoch/index.js.map +1 -1
  55. package/lib/epoch/processBuilderPendingPayments.d.ts +1 -1
  56. package/lib/epoch/processBuilderPendingPayments.js.map +1 -1
  57. package/lib/epoch/processEffectiveBalanceUpdates.js.map +1 -1
  58. package/lib/epoch/processEth1DataReset.js.map +1 -1
  59. package/lib/epoch/processHistoricalRootsUpdate.js.map +1 -1
  60. package/lib/epoch/processHistoricalSummariesUpdate.js.map +1 -1
  61. package/lib/epoch/processInactivityUpdates.js.map +1 -1
  62. package/lib/epoch/processJustificationAndFinalization.js.map +1 -1
  63. package/lib/epoch/processParticipationFlagUpdates.js.map +1 -1
  64. package/lib/epoch/processParticipationRecordUpdates.js.map +1 -1
  65. package/lib/epoch/processPendingAttestations.js.map +1 -1
  66. package/lib/epoch/processPendingConsolidations.js.map +1 -1
  67. package/lib/epoch/processPendingDeposits.js.map +1 -1
  68. package/lib/epoch/processProposerLookahead.js.map +1 -1
  69. package/lib/epoch/processRandaoMixesReset.js.map +1 -1
  70. package/lib/epoch/processRegistryUpdates.js.map +1 -1
  71. package/lib/epoch/processRewardsAndPenalties.js.map +1 -1
  72. package/lib/epoch/processSlashings.js.map +1 -1
  73. package/lib/epoch/processSlashingsReset.js.map +1 -1
  74. package/lib/epoch/processSyncCommitteeUpdates.js.map +1 -1
  75. package/lib/lightClient/proofs.js.map +1 -1
  76. package/lib/metrics.d.ts.map +1 -1
  77. package/lib/metrics.js.map +1 -1
  78. package/lib/rewards/attestationsRewards.js.map +1 -1
  79. package/lib/rewards/blockRewards.js.map +1 -1
  80. package/lib/rewards/syncCommitteeRewards.js.map +1 -1
  81. package/lib/signatureSets/attesterSlashings.js.map +1 -1
  82. package/lib/signatureSets/blsToExecutionChange.js.map +1 -1
  83. package/lib/signatureSets/executionPayloadBid.js.map +1 -1
  84. package/lib/signatureSets/executionPayloadEnvelope.js.map +1 -1
  85. package/lib/signatureSets/index.js.map +1 -1
  86. package/lib/signatureSets/indexedAttestation.js.map +1 -1
  87. package/lib/signatureSets/indexedPayloadAttestation.js.map +1 -1
  88. package/lib/signatureSets/proposer.js.map +1 -1
  89. package/lib/signatureSets/proposerSlashings.js.map +1 -1
  90. package/lib/signatureSets/randao.js.map +1 -1
  91. package/lib/signatureSets/voluntaryExits.js.map +1 -1
  92. package/lib/slot/index.js.map +1 -1
  93. package/lib/slot/upgradeStateToAltair.js.map +1 -1
  94. package/lib/slot/upgradeStateToBellatrix.js.map +1 -1
  95. package/lib/slot/upgradeStateToCapella.js.map +1 -1
  96. package/lib/slot/upgradeStateToDeneb.js.map +1 -1
  97. package/lib/slot/upgradeStateToElectra.js.map +1 -1
  98. package/lib/slot/upgradeStateToFulu.js.map +1 -1
  99. package/lib/slot/upgradeStateToGloas.js.map +1 -1
  100. package/lib/stateTransition.js +4 -2
  101. package/lib/stateTransition.js.map +1 -1
  102. package/lib/stateView/beaconStateView.d.ts.map +1 -1
  103. package/lib/stateView/beaconStateView.js.map +1 -1
  104. package/lib/testUtils/cache.d.ts +2 -0
  105. package/lib/testUtils/cache.d.ts.map +1 -0
  106. package/lib/testUtils/cache.js +7 -0
  107. package/lib/testUtils/cache.js.map +1 -0
  108. package/lib/testUtils/index.d.ts +6 -0
  109. package/lib/testUtils/index.d.ts.map +1 -0
  110. package/lib/testUtils/index.js +6 -0
  111. package/lib/testUtils/index.js.map +1 -0
  112. package/lib/testUtils/infura.d.ts +3 -0
  113. package/lib/testUtils/infura.d.ts.map +1 -0
  114. package/lib/testUtils/infura.js +8 -0
  115. package/lib/testUtils/infura.js.map +1 -0
  116. package/lib/testUtils/interop.d.ts +2 -0
  117. package/lib/testUtils/interop.d.ts.map +1 -0
  118. package/lib/testUtils/interop.js +24 -0
  119. package/lib/testUtils/interop.js.map +1 -0
  120. package/lib/testUtils/params.d.ts +18 -0
  121. package/lib/testUtils/params.d.ts.map +1 -0
  122. package/lib/testUtils/params.js +20 -0
  123. package/lib/testUtils/params.js.map +1 -0
  124. package/lib/testUtils/state.d.ts +20 -0
  125. package/lib/testUtils/state.d.ts.map +1 -0
  126. package/lib/testUtils/state.js +78 -0
  127. package/lib/testUtils/state.js.map +1 -0
  128. package/lib/testUtils/testFileCache.d.ts +17 -0
  129. package/lib/testUtils/testFileCache.d.ts.map +1 -0
  130. package/lib/testUtils/testFileCache.js +96 -0
  131. package/lib/testUtils/testFileCache.js.map +1 -0
  132. package/lib/testUtils/util.d.ts +50 -0
  133. package/lib/testUtils/util.d.ts.map +1 -0
  134. package/lib/testUtils/util.js +329 -0
  135. package/lib/testUtils/util.js.map +1 -0
  136. package/lib/util/aggregator.js.map +1 -1
  137. package/lib/util/altair.js.map +1 -1
  138. package/lib/util/array.js.map +1 -1
  139. package/lib/util/attestation.js.map +1 -1
  140. package/lib/util/attesterStatus.js.map +1 -1
  141. package/lib/util/balance.js.map +1 -1
  142. package/lib/util/blindedBlock.js.map +1 -1
  143. package/lib/util/blockRoot.js.map +1 -1
  144. package/lib/util/capella.js.map +1 -1
  145. package/lib/util/computeAnchorCheckpoint.js.map +1 -1
  146. package/lib/util/deposit.js.map +1 -1
  147. package/lib/util/domain.js.map +1 -1
  148. package/lib/util/electra.js.map +1 -1
  149. package/lib/util/epoch.js.map +1 -1
  150. package/lib/util/epochShuffling.js.map +1 -1
  151. package/lib/util/execution.js.map +1 -1
  152. package/lib/util/finality.js.map +1 -1
  153. package/lib/util/fulu.js.map +1 -1
  154. package/lib/util/genesis.js.map +1 -1
  155. package/lib/util/gloas.js.map +1 -1
  156. package/lib/util/interop.js.map +1 -1
  157. package/lib/util/loadState/findModifiedInactivityScores.js.map +1 -1
  158. package/lib/util/loadState/findModifiedValidators.js.map +1 -1
  159. package/lib/util/loadState/loadState.js.map +1 -1
  160. package/lib/util/loadState/loadValidator.js.map +1 -1
  161. package/lib/util/rootCache.d.ts.map +1 -1
  162. package/lib/util/rootCache.js.map +1 -1
  163. package/lib/util/seed.d.ts +0 -8
  164. package/lib/util/seed.d.ts.map +1 -1
  165. package/lib/util/seed.js +0 -64
  166. package/lib/util/seed.js.map +1 -1
  167. package/lib/util/shuffling.js +2 -1
  168. package/lib/util/shuffling.js.map +1 -1
  169. package/lib/util/signatureSets.js +2 -1
  170. package/lib/util/signatureSets.js.map +1 -1
  171. package/lib/util/signingRoot.js.map +1 -1
  172. package/lib/util/slot.js.map +1 -1
  173. package/lib/util/sszBytes.js.map +1 -1
  174. package/lib/util/syncCommittee.js.map +1 -1
  175. package/lib/util/targetUnslashedBalance.js.map +1 -1
  176. package/lib/util/validator.js.map +1 -1
  177. package/lib/util/weakSubjectivity.js.map +1 -1
  178. package/package.json +14 -9
  179. package/src/block/index.ts +3 -3
  180. package/src/block/isValidIndexedPayloadAttestation.ts +2 -2
  181. package/src/block/processAttestationsAltair.ts +1 -1
  182. package/src/block/processExecutionPayloadBid.ts +4 -4
  183. package/src/block/processExecutionPayloadEnvelope.ts +35 -21
  184. package/src/block/processOperations.ts +1 -1
  185. package/src/block/processPayloadAttestation.ts +2 -2
  186. package/src/block/processWithdrawals.ts +1 -1
  187. package/src/cache/epochCache.ts +27 -5
  188. package/src/epoch/index.ts +1 -1
  189. package/src/epoch/processBuilderPendingPayments.ts +2 -2
  190. package/src/testUtils/cache.ts +8 -0
  191. package/src/testUtils/index.ts +5 -0
  192. package/src/testUtils/infura.ts +10 -0
  193. package/src/testUtils/interop.ts +29 -0
  194. package/src/testUtils/params.ts +23 -0
  195. package/src/testUtils/state.ts +110 -0
  196. package/src/testUtils/testFileCache.ts +127 -0
  197. package/src/testUtils/util.ts +429 -0
  198. package/src/util/seed.ts +0 -71
@@ -7,18 +7,25 @@ import {
7
7
  } from "@lodestar/params";
8
8
  import {gloas, ssz} from "@lodestar/types";
9
9
  import {byteArrayEquals, toHex, toRootHex} from "@lodestar/utils";
10
- import {CachedBeaconStateGloas} from "../types.ts";
11
- import {computeSigningRoot, computeTimeAtSlot} from "../util/index.ts";
12
- import {processConsolidationRequest} from "./processConsolidationRequest.ts";
13
- import {processDepositRequest} from "./processDepositRequest.ts";
14
- import {processWithdrawalRequest} from "./processWithdrawalRequest.ts";
15
-
16
- // This function does not call execution engine to verify payload. Need to call it from other place
10
+ import {CachedBeaconStateGloas} from "../types.js";
11
+ import {computeSigningRoot, computeTimeAtSlot} from "../util/index.js";
12
+ import {processConsolidationRequest} from "./processConsolidationRequest.js";
13
+ import {processDepositRequest} from "./processDepositRequest.js";
14
+ import {processWithdrawalRequest} from "./processWithdrawalRequest.js";
15
+
16
+ export type ProcessExecutionPayloadEnvelopeOpts = {
17
+ dontTransferCache?: boolean;
18
+ };
19
+
20
+ // Unlike other block processing functions which mutate state in-place, this function
21
+ // clones the state and returns the post-state, similar to stateTransition().
22
+ // This function does not call execution engine to verify payload. Need to call it from other place.
17
23
  export function processExecutionPayloadEnvelope(
18
24
  state: CachedBeaconStateGloas,
19
25
  signedEnvelope: gloas.SignedExecutionPayloadEnvelope,
20
- verify: boolean
21
- ): void {
26
+ verify: boolean,
27
+ opts?: ProcessExecutionPayloadEnvelopeOpts
28
+ ): CachedBeaconStateGloas {
22
29
  const envelope = signedEnvelope.message;
23
30
  const payload = envelope.payload;
24
31
  const fork = state.config.getForkSeq(envelope.slot);
@@ -27,42 +34,49 @@ export function processExecutionPayloadEnvelope(
27
34
  throw Error(`Execution payload envelope has invalid signature builderIndex=${envelope.builderIndex}`);
28
35
  }
29
36
 
30
- validateExecutionPayloadEnvelope(state, envelope);
37
+ // .clone() before mutating state, similar to stateTransition()
38
+ const postState = state.clone(opts?.dontTransferCache) as CachedBeaconStateGloas;
39
+
40
+ validateExecutionPayloadEnvelope(postState, envelope);
31
41
 
32
42
  const requests = envelope.executionRequests;
33
43
 
34
44
  for (const deposit of requests.deposits) {
35
- processDepositRequest(fork, state, deposit);
45
+ processDepositRequest(fork, postState, deposit);
36
46
  }
37
47
 
38
48
  for (const withdrawal of requests.withdrawals) {
39
- processWithdrawalRequest(fork, state, withdrawal);
49
+ processWithdrawalRequest(fork, postState, withdrawal);
40
50
  }
41
51
 
42
52
  for (const consolidation of requests.consolidations) {
43
- processConsolidationRequest(state, consolidation);
53
+ processConsolidationRequest(postState, consolidation);
44
54
  }
45
55
 
46
56
  // Queue the builder payment
47
- const paymentIndex = SLOTS_PER_EPOCH + (state.slot % SLOTS_PER_EPOCH);
48
- const payment = state.builderPendingPayments.get(paymentIndex).clone();
57
+ const paymentIndex = SLOTS_PER_EPOCH + (postState.slot % SLOTS_PER_EPOCH);
58
+ const payment = postState.builderPendingPayments.get(paymentIndex).clone();
49
59
  const amount = payment.withdrawal.amount;
50
60
 
51
61
  if (amount > 0) {
52
- state.builderPendingWithdrawals.push(payment.withdrawal);
62
+ postState.builderPendingWithdrawals.push(payment.withdrawal);
53
63
  }
54
64
 
55
- state.builderPendingPayments.set(paymentIndex, ssz.gloas.BuilderPendingPayment.defaultViewDU());
65
+ postState.builderPendingPayments.set(paymentIndex, ssz.gloas.BuilderPendingPayment.defaultViewDU());
56
66
 
57
67
  // Cache the execution payload hash
58
- state.executionPayloadAvailability.set(state.slot % SLOTS_PER_HISTORICAL_ROOT, true);
59
- state.latestBlockHash = payload.blockHash;
68
+ postState.executionPayloadAvailability.set(postState.slot % SLOTS_PER_HISTORICAL_ROOT, true);
69
+ postState.latestBlockHash = payload.blockHash;
60
70
 
61
- if (verify && !byteArrayEquals(envelope.stateRoot, state.hashTreeRoot())) {
71
+ postState.commit();
72
+
73
+ if (verify && !byteArrayEquals(envelope.stateRoot, postState.hashTreeRoot())) {
62
74
  throw new Error(
63
- `Envelope's state root does not match state envelope=${toRootHex(envelope.stateRoot)} state=${toRootHex(state.hashTreeRoot())}`
75
+ `Envelope's state root does not match state envelope=${toRootHex(envelope.stateRoot)} state=${toRootHex(postState.hashTreeRoot())}`
64
76
  );
65
77
  }
78
+
79
+ return postState;
66
80
  }
67
81
 
68
82
  function validateExecutionPayloadEnvelope(
@@ -14,7 +14,7 @@ import {processBlsToExecutionChange} from "./processBlsToExecutionChange.js";
14
14
  import {processConsolidationRequest} from "./processConsolidationRequest.js";
15
15
  import {processDeposit} from "./processDeposit.js";
16
16
  import {processDepositRequest} from "./processDepositRequest.js";
17
- import {processPayloadAttestation} from "./processPayloadAttestation.ts";
17
+ import {processPayloadAttestation} from "./processPayloadAttestation.js";
18
18
  import {processProposerSlashing} from "./processProposerSlashing.js";
19
19
  import {processVoluntaryExit} from "./processVoluntaryExit.js";
20
20
  import {processWithdrawalRequest} from "./processWithdrawalRequest.js";
@@ -1,7 +1,7 @@
1
1
  import {gloas} from "@lodestar/types";
2
2
  import {byteArrayEquals} from "@lodestar/utils";
3
- import {CachedBeaconStateGloas} from "../types.ts";
4
- import {isValidIndexedPayloadAttestation} from "./isValidIndexedPayloadAttestation.ts";
3
+ import {CachedBeaconStateGloas} from "../types.js";
4
+ import {isValidIndexedPayloadAttestation} from "./isValidIndexedPayloadAttestation.js";
5
5
 
6
6
  export function processPayloadAttestation(
7
7
  state: CachedBeaconStateGloas,
@@ -16,7 +16,7 @@ import {
16
16
  convertValidatorIndexToBuilderIndex,
17
17
  isBuilderIndex,
18
18
  isParentBlockFull,
19
- } from "../util/gloas.ts";
19
+ } from "../util/gloas.js";
20
20
  import {
21
21
  decreaseBalance,
22
22
  getMaxEffectiveBalance,
@@ -226,7 +226,9 @@ export class EpochCache {
226
226
  /** TODO: Indexed SyncCommitteeCache */
227
227
  nextSyncCommitteeIndexed: SyncCommitteeCache;
228
228
 
229
- // TODO GLOAS: See if we need to cached PTC for prev/next epoch
229
+ // TODO GLOAS: See if we need to cache PTC for next epoch
230
+ // PTC for previous epoch, required for slot N block validating slot N-1 attestations
231
+ previousPayloadTimelinessCommittees: Uint32Array[];
230
232
  // PTC for current epoch, computed eagerly at epoch transition
231
233
  payloadTimelinessCommittees: Uint32Array[];
232
234
 
@@ -266,6 +268,7 @@ export class EpochCache {
266
268
  previousTargetUnslashedBalanceIncrements: number;
267
269
  currentSyncCommitteeIndexed: SyncCommitteeCache;
268
270
  nextSyncCommitteeIndexed: SyncCommitteeCache;
271
+ previousPayloadTimelinessCommittees: Uint32Array[];
269
272
  payloadTimelinessCommittees: Uint32Array[];
270
273
  epoch: Epoch;
271
274
  syncPeriod: SyncPeriod;
@@ -296,6 +299,7 @@ export class EpochCache {
296
299
  this.previousTargetUnslashedBalanceIncrements = data.previousTargetUnslashedBalanceIncrements;
297
300
  this.currentSyncCommitteeIndexed = data.currentSyncCommitteeIndexed;
298
301
  this.nextSyncCommitteeIndexed = data.nextSyncCommitteeIndexed;
302
+ this.previousPayloadTimelinessCommittees = data.previousPayloadTimelinessCommittees;
299
303
  this.payloadTimelinessCommittees = data.payloadTimelinessCommittees;
300
304
  this.epoch = data.epoch;
301
305
  this.syncPeriod = data.syncPeriod;
@@ -447,7 +451,8 @@ export class EpochCache {
447
451
  nextSyncCommitteeIndexed = new SyncCommitteeCacheEmpty();
448
452
  }
449
453
 
450
- // Compute PTC eagerly for all slots in the epoch
454
+ // Compute PTC for all slots in the prev/current epoch
455
+ let previousPayloadTimelinessCommittees: Uint32Array[] = [];
451
456
  let payloadTimelinessCommittees: Uint32Array[] = [];
452
457
  if (currentEpoch >= config.GLOAS_FORK_EPOCH) {
453
458
  payloadTimelinessCommittees = computePayloadTimelinessCommitteesForEpoch(
@@ -456,6 +461,15 @@ export class EpochCache {
456
461
  currentShuffling.committees,
457
462
  effectiveBalanceIncrements
458
463
  );
464
+
465
+ if (!isGenesis && previousEpoch >= config.GLOAS_FORK_EPOCH) {
466
+ previousPayloadTimelinessCommittees = computePayloadTimelinessCommitteesForEpoch(
467
+ state,
468
+ previousEpoch,
469
+ previousShuffling.committees,
470
+ effectiveBalanceIncrements
471
+ );
472
+ }
459
473
  }
460
474
 
461
475
  // Precompute churnLimit for efficient initiateValidatorExit() during block proposing MUST be recompute everytime the
@@ -530,6 +544,7 @@ export class EpochCache {
530
544
  currentTargetUnslashedBalanceIncrements,
531
545
  currentSyncCommitteeIndexed,
532
546
  nextSyncCommitteeIndexed,
547
+ previousPayloadTimelinessCommittees,
533
548
  payloadTimelinessCommittees,
534
549
  epoch: currentEpoch,
535
550
  syncPeriod: computeSyncPeriodAtEpoch(currentEpoch),
@@ -575,6 +590,7 @@ export class EpochCache {
575
590
  currentTargetUnslashedBalanceIncrements: this.currentTargetUnslashedBalanceIncrements,
576
591
  currentSyncCommitteeIndexed: this.currentSyncCommitteeIndexed,
577
592
  nextSyncCommitteeIndexed: this.nextSyncCommitteeIndexed,
593
+ previousPayloadTimelinessCommittees: this.previousPayloadTimelinessCommittees,
578
594
  payloadTimelinessCommittees: this.payloadTimelinessCommittees,
579
595
  epoch: this.epoch,
580
596
  syncPeriod: this.syncPeriod,
@@ -686,6 +702,8 @@ export class EpochCache {
686
702
 
687
703
  this.proposersPrevEpoch = this.proposers;
688
704
  if (upcomingEpoch >= this.config.GLOAS_FORK_EPOCH) {
705
+ // Shift and compute current epoch PTC eagerly for all slots
706
+ this.previousPayloadTimelinessCommittees = this.payloadTimelinessCommittees;
689
707
  this.payloadTimelinessCommittees = computePayloadTimelinessCommitteesForEpoch(
690
708
  state,
691
709
  upcomingEpoch,
@@ -1016,11 +1034,15 @@ export class EpochCache {
1016
1034
  throw new Error("Payload Timeliness Committee is not available before gloas fork");
1017
1035
  }
1018
1036
 
1019
- if (epoch !== this.epoch) {
1020
- throw new Error(`Payload Timeliness Committee is not available for slot=${slot}`);
1037
+ if (epoch === this.epoch) {
1038
+ return this.payloadTimelinessCommittees[slot % SLOTS_PER_EPOCH];
1039
+ }
1040
+
1041
+ if (epoch === this.epoch - 1 && this.previousPayloadTimelinessCommittees.length > 0) {
1042
+ return this.previousPayloadTimelinessCommittees[slot % SLOTS_PER_EPOCH];
1021
1043
  }
1022
1044
 
1023
- return this.payloadTimelinessCommittees[slot % SLOTS_PER_EPOCH];
1045
+ throw new Error(`Payload Timeliness Committee is not available for slot=${slot}`);
1024
1046
  }
1025
1047
 
1026
1048
  getIndexedPayloadAttestation(
@@ -16,7 +16,7 @@ import {
16
16
  CachedBeaconStatePhase0,
17
17
  EpochTransitionCache,
18
18
  } from "../types.js";
19
- import {processBuilderPendingPayments} from "./processBuilderPendingPayments.ts";
19
+ import {processBuilderPendingPayments} from "./processBuilderPendingPayments.js";
20
20
  import {processEffectiveBalanceUpdates} from "./processEffectiveBalanceUpdates.js";
21
21
  import {processEth1DataReset} from "./processEth1DataReset.js";
22
22
  import {processHistoricalRootsUpdate} from "./processHistoricalRootsUpdate.js";
@@ -1,7 +1,7 @@
1
1
  import {SLOTS_PER_EPOCH} from "@lodestar/params";
2
2
  import {ssz} from "@lodestar/types";
3
- import {CachedBeaconStateGloas} from "../types.ts";
4
- import {getBuilderPaymentQuorumThreshold} from "../util/gloas.ts";
3
+ import {CachedBeaconStateGloas} from "../types.js";
4
+ import {getBuilderPaymentQuorumThreshold} from "../util/gloas.js";
5
5
 
6
6
  /**
7
7
  * Processes the builder pending payments from the previous epoch.
@@ -0,0 +1,8 @@
1
+ import path from "node:path";
2
+ import {fileURLToPath} from "node:url";
3
+
4
+ // Global variable __dirname no longer available in ES6 modules.
5
+ // Solutions: https://stackoverflow.com/questions/46745014/alternative-for-dirname-in-node-js-when-using-es6-modules
6
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
7
+
8
+ export const testCachePath = path.join(__dirname, "../../test/test-cache");
@@ -0,0 +1,5 @@
1
+ export * from "./cache.js";
2
+ export * from "./interop.js";
3
+ export * from "./params.js";
4
+ export * from "./testFileCache.js";
5
+ export * from "./util.js";
@@ -0,0 +1,10 @@
1
+ import {NetworkName} from "@lodestar/config/networks";
2
+
3
+ export function getInfuraBeaconUrl(network: NetworkName): string {
4
+ const INFURA_ETH2_CREDENTIALS = process.env.INFURA_ETH2_CREDENTIALS;
5
+ if (!INFURA_ETH2_CREDENTIALS) {
6
+ throw Error("Must set ENV INFURA_ETH2_CREDENTIALS");
7
+ }
8
+
9
+ return `https://${INFURA_ETH2_CREDENTIALS}@eth2-beacon-${network}.infura.io`;
10
+ }
@@ -0,0 +1,29 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import {fromHexString, toHexString} from "@chainsafe/ssz";
4
+ import {interopSecretKey} from "../index.js";
5
+ import {testCachePath} from "./cache.js";
6
+
7
+ const interopPubkeysCachedPath = path.join(testCachePath, "interop-pubkeys.json");
8
+
9
+ export function interopPubkeysCached(validatorCount: number): Uint8Array[] {
10
+ fs.mkdirSync(path.dirname(interopPubkeysCachedPath), {recursive: true});
11
+
12
+ const cachedKeysHex = fs.existsSync(interopPubkeysCachedPath)
13
+ ? (JSON.parse(fs.readFileSync(interopPubkeysCachedPath, "utf8")) as string[])
14
+ : ([] as string[]);
15
+
16
+ const keys = cachedKeysHex.slice(0, validatorCount).map((hex) => fromHexString(hex));
17
+
18
+ if (cachedKeysHex.length < validatorCount) {
19
+ for (let i = cachedKeysHex.length; i < validatorCount; i++) {
20
+ const sk = interopSecretKey(i);
21
+ const pk = sk.toPublicKey().toBytes();
22
+ keys.push(pk);
23
+ }
24
+ const keysHex = keys.map((pk) => toHexString(pk));
25
+ fs.writeFileSync(interopPubkeysCachedPath, JSON.stringify(keysHex, null, 2));
26
+ }
27
+
28
+ return keys;
29
+ }
@@ -0,0 +1,23 @@
1
+ // DON'T MODIFY OR FORMAT THIS FILE
2
+ // USE FOR GA CACHE
3
+
4
+ export const phase0State = {
5
+ network: "mainnet" as const,
6
+ epoch: 58758, // Pre-altair fork
7
+ };
8
+
9
+ export const altairState = {
10
+ network: "mainnet" as const,
11
+ epoch: 81889, // Post altair fork
12
+ };
13
+
14
+ export const capellaState = {
15
+ network: "mainnet" as const,
16
+ epoch: 217614, // Post capella fork
17
+ };
18
+
19
+ export const rangeSyncTest = {
20
+ network: "mainnet" as const,
21
+ startSlot: 3766816, // Post altair, first slot in epoch 117713
22
+ endSlot: 3766847, // 3766816 + 31, all blocks in same epoch
23
+ };
@@ -0,0 +1,110 @@
1
+ import {ChainForkConfig, createBeaconConfig} from "@lodestar/config";
2
+ import {config, config as minimalConfig} from "@lodestar/config/default";
3
+ import {
4
+ EPOCHS_PER_HISTORICAL_VECTOR,
5
+ EPOCHS_PER_SLASHINGS_VECTOR,
6
+ GENESIS_EPOCH,
7
+ GENESIS_SLOT,
8
+ SLOTS_PER_HISTORICAL_ROOT,
9
+ } from "@lodestar/params";
10
+ import {phase0, ssz} from "@lodestar/types";
11
+ import {EpochCacheOpts} from "../cache/epochCache.js";
12
+ import {BeaconStateCache} from "../cache/stateCache.js";
13
+ import {ZERO_HASH} from "../constants/index.js";
14
+ import {
15
+ BeaconStateAllForks,
16
+ BeaconStatePhase0,
17
+ CachedBeaconStateAllForks,
18
+ createCachedBeaconState,
19
+ createPubkeyCache,
20
+ } from "../index.js";
21
+ import {newZeroedArray} from "../util/index.js";
22
+
23
+ /**
24
+ * Copy of BeaconState, but all fields are marked optional to allow for swapping out variables as needed.
25
+ */
26
+ type TestBeaconState = Partial<phase0.BeaconState>;
27
+
28
+ /**
29
+ * Generate beaconState, by default it will use the initial state defined when the `ChainStart` log is emitted.
30
+ * NOTE: All fields can be overridden through `opts`.
31
+ * @param {TestBeaconState} opts
32
+ * @returns {BeaconState}
33
+ */
34
+ export function generateState(opts?: TestBeaconState): BeaconStatePhase0 {
35
+ return ssz.phase0.BeaconState.toViewDU({
36
+ genesisTime: Math.floor(Date.now() / 1000),
37
+ genesisValidatorsRoot: ZERO_HASH,
38
+ slot: GENESIS_SLOT,
39
+ fork: {
40
+ previousVersion: config.GENESIS_FORK_VERSION,
41
+ currentVersion: config.GENESIS_FORK_VERSION,
42
+ epoch: GENESIS_EPOCH,
43
+ },
44
+ latestBlockHeader: {
45
+ slot: 0,
46
+ proposerIndex: 0,
47
+ parentRoot: Buffer.alloc(32),
48
+ stateRoot: Buffer.alloc(32),
49
+ bodyRoot: ssz.phase0.BeaconBlockBody.hashTreeRoot(ssz.phase0.BeaconBlockBody.defaultValue()),
50
+ },
51
+ blockRoots: Array.from({length: SLOTS_PER_HISTORICAL_ROOT}, () => ZERO_HASH),
52
+ stateRoots: Array.from({length: SLOTS_PER_HISTORICAL_ROOT}, () => ZERO_HASH),
53
+ historicalRoots: [],
54
+ eth1Data: {
55
+ depositRoot: Buffer.alloc(32),
56
+ blockHash: Buffer.alloc(32),
57
+ depositCount: 0,
58
+ },
59
+ eth1DataVotes: [],
60
+ eth1DepositIndex: 0,
61
+ validators: [],
62
+ balances: [],
63
+ randaoMixes: Array.from({length: EPOCHS_PER_HISTORICAL_VECTOR}, () => ZERO_HASH),
64
+ slashings: newZeroedArray(EPOCHS_PER_SLASHINGS_VECTOR),
65
+ previousEpochAttestations: [],
66
+ currentEpochAttestations: [],
67
+ justificationBits: ssz.phase0.JustificationBits.defaultValue(),
68
+ previousJustifiedCheckpoint: {
69
+ epoch: GENESIS_EPOCH,
70
+ root: ZERO_HASH,
71
+ },
72
+ currentJustifiedCheckpoint: {
73
+ epoch: GENESIS_EPOCH,
74
+ root: ZERO_HASH,
75
+ },
76
+ finalizedCheckpoint: {
77
+ epoch: GENESIS_EPOCH,
78
+ root: ZERO_HASH,
79
+ },
80
+ ...opts,
81
+ });
82
+ }
83
+
84
+ export function generateCachedState(
85
+ config: ChainForkConfig = minimalConfig,
86
+ opts: TestBeaconState = {}
87
+ ): CachedBeaconStateAllForks {
88
+ const state = generateState(opts);
89
+ return createCachedBeaconState(state, {
90
+ config: createBeaconConfig(config, state.genesisValidatorsRoot),
91
+ // This is a test state, there's no need to have a global shared cache of keys
92
+ pubkeyCache: createPubkeyCache(),
93
+ });
94
+ }
95
+
96
+ export function createCachedBeaconStateTest<T extends BeaconStateAllForks>(
97
+ state: T,
98
+ configCustom: ChainForkConfig = config,
99
+ opts?: EpochCacheOpts
100
+ ): T & BeaconStateCache {
101
+ return createCachedBeaconState<T>(
102
+ state,
103
+ {
104
+ config: createBeaconConfig(configCustom, state.genesisValidatorsRoot),
105
+ // This is a test state, there's no need to have a global shared cache of keys
106
+ pubkeyCache: createPubkeyCache(),
107
+ },
108
+ opts
109
+ );
110
+ }
@@ -0,0 +1,127 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import {getClient} from "@lodestar/api";
4
+ import {ChainForkConfig, createChainForkConfig} from "@lodestar/config";
5
+ import {NetworkName, networksChainConfig} from "@lodestar/config/networks";
6
+ import {SignedBeaconBlock} from "@lodestar/types";
7
+ import {fetch} from "@lodestar/utils";
8
+ import {CachedBeaconStateAllForks} from "../index.js";
9
+ import {testCachePath} from "./cache.js";
10
+ import {getInfuraBeaconUrl} from "./infura.js";
11
+ import {createCachedBeaconStateTest} from "./state.js";
12
+
13
+ /**
14
+ * Full link example:
15
+ * ```
16
+ * https://github.com/dapplion/ethereum-consensus-test-data/releases/download/v0.1.0/block_mainnet_3766821.ssz
17
+ * ``` */
18
+ const TEST_FILES_BASE_URL = "https://github.com/dapplion/ethereum-consensus-test-data/releases/download/v0.1.0";
19
+
20
+ /**
21
+ * Create a network config from known network params
22
+ */
23
+ export function getNetworkConfig(network: NetworkName): ChainForkConfig {
24
+ const configNetwork = networksChainConfig[network];
25
+ return createChainForkConfig(configNetwork);
26
+ }
27
+
28
+ /**
29
+ * Download a state from Infura. Caches states in local fs by network and slot to only download once.
30
+ */
31
+ export async function getNetworkCachedState(
32
+ network: NetworkName,
33
+ slot: number,
34
+ timeout?: number
35
+ ): Promise<CachedBeaconStateAllForks> {
36
+ const config = getNetworkConfig(network);
37
+ const fileId = `state_${network}_${slot}.ssz`;
38
+
39
+ const filepath = path.join(testCachePath, fileId);
40
+
41
+ if (fs.existsSync(filepath)) {
42
+ const stateSsz = fs.readFileSync(filepath);
43
+ return createCachedBeaconStateTest(config.getForkTypes(slot).BeaconState.deserializeToViewDU(stateSsz), config);
44
+ }
45
+
46
+ const stateSsz = await tryEach([
47
+ () => downloadTestFile(fileId),
48
+ () => {
49
+ const client = getClient(
50
+ {baseUrl: getInfuraBeaconUrl(network), globalInit: {timeoutMs: timeout ?? 300_000}},
51
+ {config}
52
+ );
53
+ return client.debug.getStateV2({stateId: slot}).then((r) => {
54
+ return r.ssz();
55
+ });
56
+ },
57
+ ]);
58
+
59
+ fs.writeFileSync(filepath, stateSsz);
60
+ return createCachedBeaconStateTest(config.getForkTypes(slot).BeaconState.deserializeToViewDU(stateSsz), config);
61
+ }
62
+
63
+ /**
64
+ * Download a state from Infura. Caches states in local fs by network and slot to only download once.
65
+ */
66
+ export async function getNetworkCachedBlock(
67
+ network: NetworkName,
68
+ slot: number,
69
+ timeout?: number
70
+ ): Promise<SignedBeaconBlock> {
71
+ const config = getNetworkConfig(network);
72
+ const fileId = `block_${network}_${slot}.ssz`;
73
+
74
+ const filepath = path.join(testCachePath, fileId);
75
+
76
+ if (fs.existsSync(filepath)) {
77
+ const blockSsz = fs.readFileSync(filepath);
78
+ return config.getForkTypes(slot).SignedBeaconBlock.deserialize(blockSsz);
79
+ }
80
+
81
+ const blockSsz = await tryEach([
82
+ () => downloadTestFile(fileId),
83
+ async () => {
84
+ const client = getClient(
85
+ {baseUrl: getInfuraBeaconUrl(network), globalInit: {timeoutMs: timeout ?? 300_000}},
86
+ {config}
87
+ );
88
+
89
+ return (await client.beacon.getBlockV2({blockId: slot})).ssz();
90
+ },
91
+ ]);
92
+
93
+ fs.writeFileSync(filepath, blockSsz);
94
+ return config.getForkTypes(slot).SignedBeaconBlock.deserialize(blockSsz);
95
+ }
96
+
97
+ async function downloadTestFile(fileId: string): Promise<Uint8Array> {
98
+ const fileUrl = `${TEST_FILES_BASE_URL}/${fileId}`;
99
+ // biome-ignore lint/suspicious/noConsole: We explicity need to log to console
100
+ console.log(`Downloading file ${fileUrl}`);
101
+
102
+ try {
103
+ const res = await fetch(fileUrl);
104
+ if (!res.ok) {
105
+ throw new Error(`Error downloading ${fileUrl}: ${res.status} ${res.statusText}`);
106
+ }
107
+ return new Uint8Array(await res.arrayBuffer());
108
+ } catch (e) {
109
+ const error = e as Error;
110
+ error.message = `Error downloading ${fileUrl}: ${error.message}`;
111
+ throw error;
112
+ }
113
+ }
114
+
115
+ async function tryEach<T>(promises: (() => Promise<T>)[]): Promise<T> {
116
+ const errors: Error[] = [];
117
+
118
+ for (let i = 0; i < promises.length; i++) {
119
+ try {
120
+ return await promises[i]();
121
+ } catch (e) {
122
+ errors.push(e as Error);
123
+ }
124
+ }
125
+
126
+ throw Error(errors.map((e, i) => `Error[${i}] ${e.message}`).join("\n"));
127
+ }