@lodestar/state-transition 1.41.0-dev.aeb5a213ee → 1.41.0-dev.bb33751bfd

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 (106) 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 +2 -0
  4. package/lib/block/externalData.js.map +1 -1
  5. package/lib/block/isValidIndexedAttestation.d.ts +3 -3
  6. package/lib/block/isValidIndexedAttestation.d.ts.map +1 -1
  7. package/lib/block/isValidIndexedAttestation.js +4 -4
  8. package/lib/block/isValidIndexedAttestation.js.map +1 -1
  9. package/lib/block/isValidIndexedPayloadAttestation.js +1 -1
  10. package/lib/block/isValidIndexedPayloadAttestation.js.map +1 -1
  11. package/lib/block/processAttestationPhase0.js +1 -1
  12. package/lib/block/processAttestationPhase0.js.map +1 -1
  13. package/lib/block/processAttestationsAltair.js +1 -1
  14. package/lib/block/processAttestationsAltair.js.map +1 -1
  15. package/lib/block/processAttesterSlashing.d.ts +2 -2
  16. package/lib/block/processAttesterSlashing.d.ts.map +1 -1
  17. package/lib/block/processAttesterSlashing.js +3 -3
  18. package/lib/block/processAttesterSlashing.js.map +1 -1
  19. package/lib/block/processExecutionPayloadEnvelope.js +5 -1
  20. package/lib/block/processExecutionPayloadEnvelope.js.map +1 -1
  21. package/lib/block/processProposerSlashing.d.ts +2 -2
  22. package/lib/block/processProposerSlashing.d.ts.map +1 -1
  23. package/lib/block/processProposerSlashing.js +3 -3
  24. package/lib/block/processProposerSlashing.js.map +1 -1
  25. package/lib/block/processRandao.js +1 -1
  26. package/lib/block/processRandao.js.map +1 -1
  27. package/lib/block/processSyncCommittee.js +1 -1
  28. package/lib/block/processSyncCommittee.js.map +1 -1
  29. package/lib/block/processVoluntaryExit.js +1 -1
  30. package/lib/block/processVoluntaryExit.js.map +1 -1
  31. package/lib/block/processWithdrawalRequest.js +2 -2
  32. package/lib/block/processWithdrawalRequest.js.map +1 -1
  33. package/lib/cache/epochCache.d.ts +6 -15
  34. package/lib/cache/epochCache.d.ts.map +1 -1
  35. package/lib/cache/epochCache.js +15 -28
  36. package/lib/cache/epochCache.js.map +1 -1
  37. package/lib/cache/pubkeyCache.d.ts +21 -6
  38. package/lib/cache/pubkeyCache.d.ts.map +1 -1
  39. package/lib/cache/pubkeyCache.js +39 -14
  40. package/lib/cache/pubkeyCache.js.map +1 -1
  41. package/lib/cache/stateCache.d.ts.map +1 -1
  42. package/lib/cache/stateCache.js +3 -7
  43. package/lib/cache/stateCache.js.map +1 -1
  44. package/lib/cache/syncCommitteeCache.d.ts +3 -2
  45. package/lib/cache/syncCommitteeCache.d.ts.map +1 -1
  46. package/lib/cache/syncCommitteeCache.js +4 -4
  47. package/lib/cache/syncCommitteeCache.js.map +1 -1
  48. package/lib/index.d.ts +1 -1
  49. package/lib/index.d.ts.map +1 -1
  50. package/lib/index.js +1 -1
  51. package/lib/index.js.map +1 -1
  52. package/lib/rewards/attestationsRewards.d.ts +2 -2
  53. package/lib/rewards/attestationsRewards.d.ts.map +1 -1
  54. package/lib/rewards/attestationsRewards.js +4 -4
  55. package/lib/rewards/attestationsRewards.js.map +1 -1
  56. package/lib/rewards/syncCommitteeRewards.d.ts +2 -2
  57. package/lib/rewards/syncCommitteeRewards.d.ts.map +1 -1
  58. package/lib/rewards/syncCommitteeRewards.js +5 -2
  59. package/lib/rewards/syncCommitteeRewards.js.map +1 -1
  60. package/lib/signatureSets/proposer.d.ts +2 -2
  61. package/lib/signatureSets/proposer.d.ts.map +1 -1
  62. package/lib/signatureSets/proposer.js +2 -2
  63. package/lib/signatureSets/proposer.js.map +1 -1
  64. package/lib/signatureSets/randao.d.ts +2 -2
  65. package/lib/signatureSets/randao.d.ts.map +1 -1
  66. package/lib/signatureSets/randao.js +2 -2
  67. package/lib/signatureSets/randao.js.map +1 -1
  68. package/lib/signatureSets/voluntaryExits.d.ts +2 -2
  69. package/lib/signatureSets/voluntaryExits.d.ts.map +1 -1
  70. package/lib/signatureSets/voluntaryExits.js +2 -2
  71. package/lib/signatureSets/voluntaryExits.js.map +1 -1
  72. package/lib/stateTransition.js +1 -1
  73. package/lib/stateTransition.js.map +1 -1
  74. package/lib/stateView/beaconStateView.d.ts.map +1 -1
  75. package/lib/stateView/beaconStateView.js +10 -12
  76. package/lib/stateView/beaconStateView.js.map +1 -1
  77. package/lib/util/signatureSets.d.ts +7 -7
  78. package/lib/util/signatureSets.d.ts.map +1 -1
  79. package/lib/util/signatureSets.js +18 -12
  80. package/lib/util/signatureSets.js.map +1 -1
  81. package/package.json +7 -7
  82. package/src/block/externalData.ts +2 -0
  83. package/src/block/isValidIndexedAttestation.ts +5 -5
  84. package/src/block/isValidIndexedPayloadAttestation.ts +1 -1
  85. package/src/block/processAttestationPhase0.ts +1 -1
  86. package/src/block/processAttestationsAltair.ts +1 -1
  87. package/src/block/processAttesterSlashing.ts +4 -4
  88. package/src/block/processExecutionPayloadEnvelope.ts +5 -1
  89. package/src/block/processProposerSlashing.ts +4 -4
  90. package/src/block/processRandao.ts +1 -1
  91. package/src/block/processSyncCommittee.ts +1 -1
  92. package/src/block/processVoluntaryExit.ts +1 -1
  93. package/src/block/processWithdrawalRequest.ts +2 -2
  94. package/src/cache/epochCache.ts +17 -31
  95. package/src/cache/pubkeyCache.ts +62 -21
  96. package/src/cache/stateCache.ts +3 -7
  97. package/src/cache/syncCommitteeCache.ts +4 -5
  98. package/src/index.ts +1 -1
  99. package/src/rewards/attestationsRewards.ts +5 -5
  100. package/src/rewards/syncCommitteeRewards.ts +6 -5
  101. package/src/signatureSets/proposer.ts +3 -3
  102. package/src/signatureSets/randao.ts +3 -7
  103. package/src/signatureSets/voluntaryExits.ts +3 -3
  104. package/src/stateTransition.ts +1 -1
  105. package/src/stateView/beaconStateView.ts +10 -12
  106. package/src/util/signatureSets.ts +23 -17
@@ -64,7 +64,7 @@ export function processAttestationsAltair(
64
64
  // we can verify only that and nothing else.
65
65
  if (verifySignature) {
66
66
  const sigSet = getAttestationWithIndicesSignatureSet(state.config, state.slot, attestation, attestingIndices);
67
- if (!verifySignatureSet(sigSet, state.epochCtx.index2pubkey)) {
67
+ if (!verifySignatureSet(sigSet, state.epochCtx.pubkeyCache)) {
68
68
  throw new Error("Attestation signature is not valid");
69
69
  }
70
70
  }
@@ -1,7 +1,7 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {ForkSeq} from "@lodestar/params";
3
3
  import {AttesterSlashing, Slot} from "@lodestar/types";
4
- import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
4
+ import {PubkeyCache} from "../cache/pubkeyCache.js";
5
5
  import {CachedBeaconStateAllForks} from "../types.js";
6
6
  import {getAttesterSlashableIndices, isSlashableAttestationData, isSlashableValidator} from "../util/index.js";
7
7
  import {isValidIndexedAttestationBigint} from "./isValidIndexedAttestation.js";
@@ -22,7 +22,7 @@ export function processAttesterSlashing(
22
22
  const {epochCtx} = state;
23
23
  assertValidAttesterSlashing(
24
24
  state.config,
25
- epochCtx.index2pubkey,
25
+ epochCtx.pubkeyCache,
26
26
  state.slot,
27
27
  state.validators.length,
28
28
  attesterSlashing,
@@ -48,7 +48,7 @@ export function processAttesterSlashing(
48
48
 
49
49
  export function assertValidAttesterSlashing(
50
50
  config: BeaconConfig,
51
- index2pubkey: Index2PubkeyCache,
51
+ pubkeyCache: PubkeyCache,
52
52
  stateSlot: Slot,
53
53
  validatorsLen: number,
54
54
  attesterSlashing: AttesterSlashing,
@@ -66,7 +66,7 @@ export function assertValidAttesterSlashing(
66
66
  // can be any arbitrary value. Must use bigint variants to hash correctly to all possible values
67
67
  for (const [i, attestation] of [attestation1, attestation2].entries()) {
68
68
  if (
69
- !isValidIndexedAttestationBigint(config, index2pubkey, stateSlot, validatorsLen, attestation, verifySignatures)
69
+ !isValidIndexedAttestationBigint(config, pubkeyCache, stateSlot, validatorsLen, attestation, verifySignatures)
70
70
  ) {
71
71
  throw new Error(`AttesterSlashing attestation${i} is invalid`);
72
72
  }
@@ -156,7 +156,11 @@ function verifyExecutionPayloadEnvelopeSignature(
156
156
 
157
157
  if (builderIndex === BUILDER_INDEX_SELF_BUILD) {
158
158
  const validatorIndex = state.latestBlockHeader.proposerIndex;
159
- publicKey = state.epochCtx.index2pubkey[validatorIndex];
159
+ const proposerPubkey = state.epochCtx.pubkeyCache.get(validatorIndex);
160
+ if (!proposerPubkey) {
161
+ return false;
162
+ }
163
+ publicKey = proposerPubkey;
160
164
  } else {
161
165
  publicKey = PublicKey.fromBytes(state.builders.getReadonly(builderIndex).pubkey);
162
166
  }
@@ -2,7 +2,7 @@ import {BeaconConfig} from "@lodestar/config";
2
2
  import {ForkSeq, SLOTS_PER_EPOCH} from "@lodestar/params";
3
3
  import {Slot, phase0, ssz} from "@lodestar/types";
4
4
  import {Validator} from "@lodestar/types/phase0";
5
- import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
5
+ import {PubkeyCache} from "../cache/pubkeyCache.js";
6
6
  import {getProposerSlashingSignatureSets} from "../signatureSets/index.js";
7
7
  import {CachedBeaconStateAllForks, CachedBeaconStateGloas} from "../types.js";
8
8
  import {computeEpochAtSlot, isSlashableValidator} from "../util/index.js";
@@ -24,7 +24,7 @@ export function processProposerSlashing(
24
24
  const proposer = state.validators.getReadonly(proposerSlashing.signedHeader1.message.proposerIndex);
25
25
  assertValidProposerSlashing(
26
26
  state.config,
27
- state.epochCtx.index2pubkey,
27
+ state.epochCtx.pubkeyCache,
28
28
  state.slot,
29
29
  proposerSlashing,
30
30
  proposer,
@@ -57,7 +57,7 @@ export function processProposerSlashing(
57
57
 
58
58
  export function assertValidProposerSlashing(
59
59
  config: BeaconConfig,
60
- index2pubkey: Index2PubkeyCache,
60
+ pubkeyCache: PubkeyCache,
61
61
  stateSlot: Slot,
62
62
  proposerSlashing: phase0.ProposerSlashing,
63
63
  proposer: Validator,
@@ -94,7 +94,7 @@ export function assertValidProposerSlashing(
94
94
  if (verifySignatures) {
95
95
  const signatureSets = getProposerSlashingSignatureSets(config, stateSlot, proposerSlashing);
96
96
  for (let i = 0; i < signatureSets.length; i++) {
97
- if (!verifySignatureSet(signatureSets[i], index2pubkey)) {
97
+ if (!verifySignatureSet(signatureSets[i], pubkeyCache)) {
98
98
  throw new Error(`ProposerSlashing header${i + 1} signature invalid`);
99
99
  }
100
100
  }
@@ -17,7 +17,7 @@ export function processRandao(state: CachedBeaconStateAllForks, block: BeaconBlo
17
17
  const randaoReveal = block.body.randaoReveal;
18
18
 
19
19
  // verify RANDAO reveal
20
- if (verifySignature && !verifyRandaoSignature(config, epochCtx.index2pubkey, block)) {
20
+ if (verifySignature && !verifyRandaoSignature(config, epochCtx.pubkeyCache, block)) {
21
21
  throw new Error("RANDAO reveal is an invalid signature");
22
22
  }
23
23
 
@@ -32,7 +32,7 @@ export function processSyncAggregate(
32
32
  participantIndices
33
33
  );
34
34
  // When there's no participation we consider the signature valid and just ignore it
35
- if (signatureSet !== null && !verifySignatureSet(signatureSet, state.epochCtx.index2pubkey)) {
35
+ if (signatureSet !== null && !verifySignatureSet(signatureSet, state.epochCtx.pubkeyCache)) {
36
36
  throw Error("Sync committee signature invalid");
37
37
  }
38
38
  }
@@ -131,7 +131,7 @@ export function getVoluntaryExitValidity(
131
131
 
132
132
  if (
133
133
  verifySignature &&
134
- !verifyVoluntaryExitSignature(state.config, epochCtx.index2pubkey, state.slot, signedVoluntaryExit)
134
+ !verifyVoluntaryExitSignature(state.config, epochCtx.pubkeyCache, state.slot, signedVoluntaryExit)
135
135
  ) {
136
136
  return VoluntaryExitValidity.invalidSignature;
137
137
  }
@@ -21,7 +21,7 @@ export function processWithdrawalRequest(
21
21
  const amount = Number(withdrawalRequest.amount);
22
22
  const {pendingPartialWithdrawals, validators, epochCtx} = state;
23
23
  // no need to use unfinalized pubkey cache from 6110 as validator won't be active anyway
24
- const {pubkey2index, config} = epochCtx;
24
+ const {pubkeyCache, config} = epochCtx;
25
25
  const isFullExitRequest = amount === FULL_EXIT_REQUEST_AMOUNT;
26
26
 
27
27
  // If partial withdrawal queue is full, only full exits are processed
@@ -31,7 +31,7 @@ export function processWithdrawalRequest(
31
31
 
32
32
  // bail out if validator is not in beacon state
33
33
  // note that we don't need to check for 6110 unfinalized vals as they won't be eligible for withdraw/exit anyway
34
- const validatorIndex = pubkey2index.get(withdrawalRequest.validatorPubkey);
34
+ const validatorIndex = pubkeyCache.getIndex(withdrawalRequest.validatorPubkey);
35
35
  if (validatorIndex === null) {
36
36
  return;
37
37
  }
@@ -1,5 +1,4 @@
1
1
  import {PublicKey} from "@chainsafe/blst";
2
- import {PubkeyIndexMap} from "@chainsafe/pubkey-index-map";
3
2
  import {BeaconConfig, ChainConfig, createBeaconConfig} from "@lodestar/config";
4
3
  import {
5
4
  ATTESTATION_SUBNET_COUNT,
@@ -56,7 +55,7 @@ import {computeBaseRewardPerIncrement, computeSyncParticipantReward} from "../ut
56
55
  import {sumTargetUnslashedBalanceIncrements} from "../util/targetUnslashedBalance.js";
57
56
  import {EffectiveBalanceIncrements, getEffectiveBalanceIncrementsWithLen} from "./effectiveBalanceIncrements.js";
58
57
  import {EpochTransitionCache} from "./epochTransitionCache.js";
59
- import {Index2PubkeyCache, syncPubkeys} from "./pubkeyCache.js";
58
+ import {PubkeyCache, createPubkeyCache, syncPubkeys} from "./pubkeyCache.js";
60
59
  import {CachedBeaconStateAllForks, CachedBeaconStateFulu} from "./stateCache.js";
61
60
  import {
62
61
  SyncCommitteeCache,
@@ -71,8 +70,7 @@ export const PROPOSER_WEIGHT_FACTOR = PROPOSER_WEIGHT / (WEIGHT_DENOMINATOR - PR
71
70
 
72
71
  export type EpochCacheImmutableData = {
73
72
  config: BeaconConfig;
74
- pubkey2index: PubkeyIndexMap;
75
- index2pubkey: Index2PubkeyCache;
73
+ pubkeyCache: PubkeyCache;
76
74
  };
77
75
 
78
76
  export type EpochCacheOpts = {
@@ -111,15 +109,9 @@ export class EpochCache {
111
109
  /**
112
110
  * Unique globally shared pubkey registry. There should only exist one for the entire application.
113
111
  *
114
- * $VALIDATOR_COUNT x 192 char String -> Number Map
112
+ * Couples both index→pubkey and pubkey→index lookups, keeping them in sync atomically.
115
113
  */
116
- pubkey2index: PubkeyIndexMap;
117
- /**
118
- * Unique globally shared pubkey registry. There should only exist one for the entire application.
119
- *
120
- * $VALIDATOR_COUNT x BLST deserialized pubkey (Jacobian coordinates)
121
- */
122
- index2pubkey: Index2PubkeyCache;
114
+ pubkeyCache: PubkeyCache;
123
115
  /**
124
116
  * Indexes of the block proposers for the current epoch.
125
117
  * For pre-fulu, this is computed and cached from the current shuffling.
@@ -249,8 +241,7 @@ export class EpochCache {
249
241
 
250
242
  constructor(data: {
251
243
  config: BeaconConfig;
252
- pubkey2index: PubkeyIndexMap;
253
- index2pubkey: Index2PubkeyCache;
244
+ pubkeyCache: PubkeyCache;
254
245
  proposers: number[];
255
246
  proposersPrevEpoch: number[] | null;
256
247
  proposersNextEpoch: ProposersDeferred;
@@ -280,8 +271,7 @@ export class EpochCache {
280
271
  syncPeriod: SyncPeriod;
281
272
  }) {
282
273
  this.config = data.config;
283
- this.pubkey2index = data.pubkey2index;
284
- this.index2pubkey = data.index2pubkey;
274
+ this.pubkeyCache = data.pubkeyCache;
285
275
  this.proposers = data.proposers;
286
276
  this.proposersPrevEpoch = data.proposersPrevEpoch;
287
277
  this.proposersNextEpoch = data.proposersNextEpoch;
@@ -319,7 +309,7 @@ export class EpochCache {
319
309
  */
320
310
  static createFromState(
321
311
  state: BeaconStateAllForks,
322
- {config, pubkey2index, index2pubkey}: EpochCacheImmutableData,
312
+ {config, pubkeyCache}: EpochCacheImmutableData,
323
313
  opts?: EpochCacheOpts
324
314
  ): EpochCache {
325
315
  const currentEpoch = computeEpochAtSlot(state.slot);
@@ -335,9 +325,9 @@ export class EpochCache {
335
325
  const validatorCount = validators.length;
336
326
 
337
327
  // syncPubkeys here to ensure EpochCacheImmutableData is popualted before computing the rest of caches
338
- // - computeSyncCommitteeCache() needs a fully populated pubkey2index cache
328
+ // - computeSyncCommitteeCache() needs a fully populated pubkeyCache
339
329
  if (!opts?.skipSyncPubkeys) {
340
- syncPubkeys(validators, pubkey2index, index2pubkey);
330
+ syncPubkeys(pubkeyCache, validators);
341
331
  }
342
332
 
343
333
  const effectiveBalanceIncrements = getEffectiveBalanceIncrementsWithLen(validatorCount);
@@ -450,8 +440,8 @@ export class EpochCache {
450
440
  // Allow to skip populating sync committee for initializeBeaconStateFromEth1()
451
441
  if (afterAltairFork && !opts?.skipSyncCommitteeCache) {
452
442
  const altairState = state as BeaconStateAltair;
453
- currentSyncCommitteeIndexed = computeSyncCommitteeCache(altairState.currentSyncCommittee, pubkey2index);
454
- nextSyncCommitteeIndexed = computeSyncCommitteeCache(altairState.nextSyncCommittee, pubkey2index);
443
+ currentSyncCommitteeIndexed = computeSyncCommitteeCache(altairState.currentSyncCommittee, pubkeyCache);
444
+ nextSyncCommitteeIndexed = computeSyncCommitteeCache(altairState.nextSyncCommittee, pubkeyCache);
455
445
  } else {
456
446
  currentSyncCommitteeIndexed = new SyncCommitteeCacheEmpty();
457
447
  nextSyncCommitteeIndexed = new SyncCommitteeCacheEmpty();
@@ -514,8 +504,7 @@ export class EpochCache {
514
504
 
515
505
  return new EpochCache({
516
506
  config,
517
- pubkey2index,
518
- index2pubkey,
507
+ pubkeyCache,
519
508
  proposers,
520
509
  // On first epoch, set to null to prevent unnecessary work since this is only used for metrics
521
510
  proposersPrevEpoch: null,
@@ -557,8 +546,7 @@ export class EpochCache {
557
546
  return new EpochCache({
558
547
  config: this.config,
559
548
  // Common append-only structures shared with all states, no need to clone
560
- pubkey2index: this.pubkey2index,
561
- index2pubkey: this.index2pubkey,
549
+ pubkeyCache: this.pubkeyCache,
562
550
  // Immutable data
563
551
  proposers: this.proposers,
564
552
  proposersPrevEpoch: this.proposersPrevEpoch,
@@ -882,16 +870,15 @@ export class EpochCache {
882
870
  * Return pubkey given the validator index.
883
871
  */
884
872
  getPubkey(index: ValidatorIndex): PublicKey | undefined {
885
- return this.index2pubkey[index];
873
+ return this.pubkeyCache.get(index);
886
874
  }
887
875
 
888
876
  getValidatorIndex(pubkey: Uint8Array): ValidatorIndex | null {
889
- return this.pubkey2index.get(pubkey);
877
+ return this.pubkeyCache.getIndex(pubkey);
890
878
  }
891
879
 
892
880
  addPubkey(index: ValidatorIndex, pubkey: Uint8Array): void {
893
- this.pubkey2index.set(pubkey, index);
894
- this.index2pubkey[index] = PublicKey.fromBytes(pubkey); // Optimize for aggregation
881
+ this.pubkeyCache.set(index, pubkey);
895
882
  }
896
883
 
897
884
  getShufflingAtSlot(slot: Slot): EpochShuffling {
@@ -1099,7 +1086,6 @@ export function createEmptyEpochCacheImmutableData(
1099
1086
  return {
1100
1087
  config: createBeaconConfig(chainConfig, state.genesisValidatorsRoot),
1101
1088
  // This is a test state, there's no need to have a global shared cache of keys
1102
- pubkey2index: new PubkeyIndexMap(),
1103
- index2pubkey: [],
1089
+ pubkeyCache: createPubkeyCache(),
1104
1090
  };
1105
1091
  }
@@ -1,33 +1,74 @@
1
1
  import {PublicKey} from "@chainsafe/blst";
2
2
  import {PubkeyIndexMap} from "@chainsafe/pubkey-index-map";
3
- import {phase0} from "@lodestar/types";
3
+ import {ValidatorIndex, phase0} from "@lodestar/types";
4
4
 
5
- export type Index2PubkeyCache = PublicKey[];
5
+ /**
6
+ * Unified pubkey cache coupling index→pubkey and pubkey→index lookups.
7
+ * Both directions are kept in sync atomically via `set()`.
8
+ */
9
+ export interface PubkeyCache {
10
+ /** Get deserialized PublicKey by validator index */
11
+ get(index: ValidatorIndex): PublicKey | undefined;
12
+ /** Get deserialized PublicKey by validator index or throw if not found */
13
+ getOrThrow(index: ValidatorIndex): PublicKey;
14
+ /** Get validator index by pubkey bytes */
15
+ getIndex(pubkey: Uint8Array): ValidatorIndex | null;
16
+ /** Set both directions atomically. Takes raw pubkey bytes — deserialization is handled internally. */
17
+ set(index: ValidatorIndex, pubkey: Uint8Array): void;
18
+ /** Number of entries */
19
+ readonly size: number;
20
+ }
21
+
22
+ class StandardPubkeyCache implements PubkeyCache {
23
+ private readonly pubkey2index: PubkeyIndexMap;
24
+ private readonly index2pubkey: (PublicKey | undefined)[];
25
+
26
+ constructor(pubkey2index?: PubkeyIndexMap, index2pubkey?: (PublicKey | undefined)[]) {
27
+ this.pubkey2index = pubkey2index ?? new PubkeyIndexMap();
28
+ this.index2pubkey = index2pubkey ?? [];
29
+ }
30
+
31
+ get size(): number {
32
+ return this.pubkey2index.size;
33
+ }
34
+
35
+ get(index: ValidatorIndex): PublicKey | undefined {
36
+ return this.index2pubkey[index];
37
+ }
38
+
39
+ getOrThrow(index: ValidatorIndex): PublicKey {
40
+ const pubkey = this.get(index);
41
+ if (!pubkey) throw Error(`Missing pubkey for validator index ${index}`);
42
+ return pubkey;
43
+ }
44
+
45
+ getIndex(pubkey: Uint8Array): ValidatorIndex | null {
46
+ return this.pubkey2index.get(pubkey);
47
+ }
48
+
49
+ set(index: ValidatorIndex, pubkey: Uint8Array): void {
50
+ this.pubkey2index.set(pubkey, index);
51
+ // Pubkeys must be checked for group + inf. This must be done only once when the validator deposit is processed.
52
+ // Afterwards any public key in the state is considered validated.
53
+ // > Do not do any validation here
54
+ this.index2pubkey[index] = PublicKey.fromBytes(pubkey); // Optimize for aggregation
55
+ }
56
+ }
57
+
58
+ export function createPubkeyCache(): PubkeyCache {
59
+ return new StandardPubkeyCache();
60
+ }
6
61
 
7
62
  /**
8
63
  * Checks the pubkey indices against a state and adds missing pubkeys
9
64
  *
10
- * Mutates `pubkey2index` and `index2pubkey`
65
+ * Mutates `pubkeyCache`
11
66
  *
12
- * If pubkey caches are empty: SLOW CODE - 🐢
67
+ * If pubkey cache is empty: SLOW CODE - 🐢
13
68
  */
14
- export function syncPubkeys(
15
- validators: phase0.Validator[],
16
- pubkey2index: PubkeyIndexMap,
17
- index2pubkey: Index2PubkeyCache
18
- ): void {
19
- if (pubkey2index.size !== index2pubkey.length) {
20
- throw new Error(`Pubkey indices have fallen out of sync: ${pubkey2index.size} != ${index2pubkey.length}`);
21
- }
22
-
69
+ export function syncPubkeys(pubkeyCache: PubkeyCache, validators: phase0.Validator[]): void {
23
70
  const newCount = validators.length;
24
- index2pubkey.length = newCount;
25
- for (let i = pubkey2index.size; i < newCount; i++) {
26
- const pubkey = validators[i].pubkey;
27
- pubkey2index.set(pubkey, i);
28
- // Pubkeys must be checked for group + inf. This must be done only once when the validator deposit is processed.
29
- // Afterwards any public key is the state consider validated.
30
- // > Do not do any validation here
31
- index2pubkey[i] = PublicKey.fromBytes(pubkey); // Optimize for aggregation
71
+ for (let i = pubkeyCache.size; i < newCount; i++) {
72
+ pubkeyCache.set(i, validators[i].pubkey);
32
73
  }
33
74
  }
@@ -1,4 +1,3 @@
1
- import {PublicKey} from "@chainsafe/blst";
2
1
  import {BeaconConfig} from "@lodestar/config";
3
2
  import {loadState} from "../util/loadState/loadState.js";
4
3
  import {EpochCache, EpochCacheImmutableData, EpochCacheOpts} from "./epochCache.js";
@@ -180,22 +179,19 @@ export function loadCachedBeaconState<T extends CachedBeaconStateAllForks>(
180
179
  stateBytes,
181
180
  seedValidatorsBytes
182
181
  );
183
- const {pubkey2index, index2pubkey} = cachedSeedState.epochCtx;
182
+ const {pubkeyCache} = cachedSeedState.epochCtx;
184
183
  // Get the validators sub tree once for all the loop
185
184
  const validators = migratedState.validators;
186
185
  for (const validatorIndex of modifiedValidators) {
187
186
  const validator = validators.getReadonly(validatorIndex);
188
- const pubkey = validator.pubkey;
189
- pubkey2index.set(pubkey, validatorIndex);
190
- index2pubkey[validatorIndex] = PublicKey.fromBytes(pubkey);
187
+ pubkeyCache.set(validatorIndex, validator.pubkey);
191
188
  }
192
189
 
193
190
  return createCachedBeaconState(
194
191
  migratedState,
195
192
  {
196
193
  config: cachedSeedState.config,
197
- pubkey2index,
198
- index2pubkey,
194
+ pubkeyCache,
199
195
  },
200
196
  {...(opts ?? {}), ...{skipSyncPubkeys: true}}
201
197
  ) as T;
@@ -1,4 +1,3 @@
1
- import {PubkeyIndexMap} from "@chainsafe/pubkey-index-map";
2
1
  import {CompositeViewDU} from "@chainsafe/ssz";
3
2
  import {ValidatorIndex, ssz} from "@lodestar/types";
4
3
  import {toPubkeyHex} from "@lodestar/utils";
@@ -39,9 +38,9 @@ export function getSyncCommitteeCache(validatorIndices: Uint32Array): SyncCommit
39
38
 
40
39
  export function computeSyncCommitteeCache(
41
40
  syncCommittee: CompositeViewDU<typeof ssz.altair.SyncCommittee>,
42
- pubkey2index: PubkeyIndexMap
41
+ pubkeyCache: {getIndex(pubkey: Uint8Array): number | null}
43
42
  ): SyncCommitteeCache {
44
- const validatorIndices = computeSyncCommitteeValidatorIndices(syncCommittee, pubkey2index);
43
+ const validatorIndices = computeSyncCommitteeValidatorIndices(syncCommittee, pubkeyCache);
45
44
  const validatorIndexMap = computeValidatorSyncCommitteeIndexMap(validatorIndices);
46
45
  return {
47
46
  validatorIndices,
@@ -79,12 +78,12 @@ export function computeValidatorSyncCommitteeIndexMap(
79
78
  */
80
79
  function computeSyncCommitteeValidatorIndices(
81
80
  syncCommittee: CompositeViewDU<typeof ssz.altair.SyncCommittee>,
82
- pubkey2index: PubkeyIndexMap
81
+ pubkeyCache: {getIndex(pubkey: Uint8Array): number | null}
83
82
  ): Uint32Array {
84
83
  const pubkeys = syncCommittee.pubkeys.getAllReadonly();
85
84
  const validatorIndices = new Uint32Array(pubkeys.length);
86
85
  for (const [i, pubkey] of pubkeys.entries()) {
87
- const validatorIndex = pubkey2index.get(pubkey);
86
+ const validatorIndex = pubkeyCache.getIndex(pubkey);
88
87
  if (validatorIndex === null) {
89
88
  throw Error(`SyncCommittee pubkey is unknown ${toPubkeyHex(pubkey)}`);
90
89
  }
package/src/index.ts CHANGED
@@ -25,7 +25,7 @@ export {
25
25
  createEmptyEpochCacheImmutableData,
26
26
  } from "./cache/epochCache.js";
27
27
  export {type EpochTransitionCache, beforeProcessEpoch} from "./cache/epochTransitionCache.js";
28
- export {type Index2PubkeyCache, syncPubkeys} from "./cache/pubkeyCache.js";
28
+ export {type PubkeyCache, createPubkeyCache, syncPubkeys} from "./cache/pubkeyCache.js";
29
29
  // Main state caches
30
30
  export {
31
31
  type BeaconStateCache,
@@ -1,4 +1,3 @@
1
- import {PubkeyIndexMap} from "@chainsafe/pubkey-index-map";
2
1
  import {BeaconConfig} from "@lodestar/config";
3
2
  import {
4
3
  EFFECTIVE_BALANCE_INCREMENT,
@@ -16,6 +15,7 @@ import {
16
15
  import {ValidatorIndex, rewards} from "@lodestar/types";
17
16
  import {fromHex} from "@lodestar/utils";
18
17
  import {EpochTransitionCache, beforeProcessEpoch} from "../cache/epochTransitionCache.js";
18
+ import {PubkeyCache} from "../cache/pubkeyCache.js";
19
19
  import {CachedBeaconStateAllForks, CachedBeaconStateAltair} from "../types.js";
20
20
  import {
21
21
  FLAG_ELIGIBLE_ATTESTER,
@@ -34,7 +34,7 @@ const defaultAttestationsPenalty = {target: 0, source: 0};
34
34
 
35
35
  export async function computeAttestationsRewards(
36
36
  config: BeaconConfig,
37
- pubkey2index: PubkeyIndexMap,
37
+ pubkeyCache: PubkeyCache,
38
38
  state: CachedBeaconStateAllForks,
39
39
  validatorIds?: (ValidatorIndex | string)[]
40
40
  ): Promise<rewards.AttestationsRewards> {
@@ -53,7 +53,7 @@ export async function computeAttestationsRewards(
53
53
  );
54
54
  const totalRewards = computeTotalAttestationsRewardsAltair(
55
55
  config,
56
- pubkey2index,
56
+ pubkeyCache,
57
57
  stateAltair,
58
58
  transitionCache,
59
59
  idealRewards,
@@ -142,7 +142,7 @@ function computeIdealAttestationsRewardsAndPenaltiesAltair(
142
142
  // Same calculation as `getRewardsAndPenaltiesAltair` but returns the breakdown of rewards instead of aggregated
143
143
  function computeTotalAttestationsRewardsAltair(
144
144
  config: BeaconConfig,
145
- pubkey2index: PubkeyIndexMap,
145
+ pubkeyCache: PubkeyCache,
146
146
  state: CachedBeaconStateAltair,
147
147
  transitionCache: EpochTransitionCache,
148
148
  idealRewards: rewards.IdealAttestationsReward[],
@@ -153,7 +153,7 @@ function computeTotalAttestationsRewardsAltair(
153
153
  const {flags} = transitionCache;
154
154
  const {epochCtx} = state;
155
155
  const validatorIndices = validatorIds
156
- .map((id) => (typeof id === "number" ? id : pubkey2index.get(fromHex(id))))
156
+ .map((id) => (typeof id === "number" ? id : pubkeyCache.getIndex(fromHex(id))))
157
157
  .filter((index) => index !== undefined); // Validator indices to include in the result
158
158
 
159
159
  const inactivityPenaltyDenominator = config.INACTIVITY_SCORE_BIAS * INACTIVITY_PENALTY_QUOTIENT_ALTAIR;
@@ -1,12 +1,12 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {ForkName, SYNC_COMMITTEE_SIZE} from "@lodestar/params";
3
3
  import {BeaconBlock, ValidatorIndex, altair, rewards} from "@lodestar/types";
4
- import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
4
+ import {PubkeyCache} from "../cache/pubkeyCache.js";
5
5
  import {CachedBeaconStateAllForks, CachedBeaconStateAltair} from "../cache/stateCache.js";
6
6
 
7
7
  export async function computeSyncCommitteeRewards(
8
8
  config: BeaconConfig,
9
- index2pubkey: Index2PubkeyCache,
9
+ pubkeyCache: PubkeyCache,
10
10
  block: BeaconBlock,
11
11
  preState: CachedBeaconStateAllForks,
12
12
  validatorIds: (ValidatorIndex | string)[] = []
@@ -47,9 +47,10 @@ export async function computeSyncCommitteeRewards(
47
47
 
48
48
  if (validatorIds.length) {
49
49
  const filtersSet = new Set(validatorIds);
50
- return rewards.filter(
51
- (reward) => filtersSet.has(reward.validatorIndex) || filtersSet.has(index2pubkey[reward.validatorIndex].toHex())
52
- );
50
+ return rewards.filter((reward) => {
51
+ const pubkeyHex = pubkeyCache.get(reward.validatorIndex)?.toHex();
52
+ return filtersSet.has(reward.validatorIndex) || (pubkeyHex !== undefined && filtersSet.has(pubkeyHex));
53
+ });
53
54
  }
54
55
 
55
56
  return rewards;
@@ -1,17 +1,17 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {DOMAIN_BEACON_PROPOSER} from "@lodestar/params";
3
3
  import {SignedBeaconBlock, SignedBlindedBeaconBlock, Slot, isBlindedBeaconBlock, phase0, ssz} from "@lodestar/types";
4
- import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
4
+ import {PubkeyCache} from "../cache/pubkeyCache.js";
5
5
  import {computeSigningRoot} from "../util/index.js";
6
6
  import {ISignatureSet, SignatureSetType, verifySignatureSet} from "../util/signatureSets.js";
7
7
 
8
8
  export function verifyProposerSignature(
9
9
  config: BeaconConfig,
10
- index2pubkey: Index2PubkeyCache,
10
+ pubkeyCache: PubkeyCache,
11
11
  signedBlock: SignedBeaconBlock | SignedBlindedBeaconBlock
12
12
  ): boolean {
13
13
  const signatureSet = getBlockProposerSignatureSet(config, signedBlock);
14
- return verifySignatureSet(signatureSet, index2pubkey);
14
+ return verifySignatureSet(signatureSet, pubkeyCache);
15
15
  }
16
16
 
17
17
  export function getBlockProposerSignatureSet(
@@ -1,7 +1,7 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {DOMAIN_RANDAO} from "@lodestar/params";
3
3
  import {BeaconBlock, ssz} from "@lodestar/types";
4
- import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
4
+ import {PubkeyCache} from "../cache/pubkeyCache.js";
5
5
  import {
6
6
  ISignatureSet,
7
7
  SignatureSetType,
@@ -10,12 +10,8 @@ import {
10
10
  verifySignatureSet,
11
11
  } from "../util/index.js";
12
12
 
13
- export function verifyRandaoSignature(
14
- config: BeaconConfig,
15
- index2pubkey: Index2PubkeyCache,
16
- block: BeaconBlock
17
- ): boolean {
18
- return verifySignatureSet(getRandaoRevealSignatureSet(config, block), index2pubkey);
13
+ export function verifyRandaoSignature(config: BeaconConfig, pubkeyCache: PubkeyCache, block: BeaconBlock): boolean {
14
+ return verifySignatureSet(getRandaoRevealSignatureSet(config, block), pubkeyCache);
19
15
  }
20
16
 
21
17
  /**
@@ -1,6 +1,6 @@
1
1
  import {BeaconConfig} from "@lodestar/config";
2
2
  import {SignedBeaconBlock, Slot, phase0, ssz} from "@lodestar/types";
3
- import {Index2PubkeyCache} from "../cache/pubkeyCache.js";
3
+ import {PubkeyCache} from "../cache/pubkeyCache.js";
4
4
  import {
5
5
  ISignatureSet,
6
6
  SignatureSetType,
@@ -11,11 +11,11 @@ import {
11
11
 
12
12
  export function verifyVoluntaryExitSignature(
13
13
  config: BeaconConfig,
14
- index2pubkey: Index2PubkeyCache,
14
+ pubkeyCache: PubkeyCache,
15
15
  stateSlot: Slot,
16
16
  signedVoluntaryExit: phase0.SignedVoluntaryExit
17
17
  ): boolean {
18
- return verifySignatureSet(getVoluntaryExitSignatureSet(config, stateSlot, signedVoluntaryExit), index2pubkey);
18
+ return verifySignatureSet(getVoluntaryExitSignatureSet(config, stateSlot, signedVoluntaryExit), pubkeyCache);
19
19
  }
20
20
 
21
21
  /**
@@ -112,7 +112,7 @@ export function stateTransition(
112
112
  postState = processSlotsWithTransientCache(postState, blockSlot, options, {metrics, validatorMonitor});
113
113
 
114
114
  // Verify proposer signature only
115
- if (verifyProposer && !verifyProposerSignature(postState.config, postState.epochCtx.index2pubkey, signedBlock)) {
115
+ if (verifyProposer && !verifyProposerSignature(postState.config, postState.epochCtx.pubkeyCache, signedBlock)) {
116
116
  throw new Error("Invalid block signature");
117
117
  }
118
118