@aztec/epoch-cache 0.0.0-test.1 → 0.0.1-fake-ceab37513c

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.
package/dest/config.d.ts CHANGED
@@ -1,4 +1,4 @@
1
1
  import { type L1ContractsConfig, type L1ReaderConfig } from '@aztec/ethereum';
2
- export type EpochCacheConfig = Pick<L1ReaderConfig & L1ContractsConfig, 'l1RpcUrls' | 'l1ChainId' | 'viemPollingIntervalMS' | 'aztecSlotDuration' | 'ethereumSlotDuration' | 'aztecEpochDuration'>;
2
+ export type EpochCacheConfig = Pick<L1ReaderConfig & L1ContractsConfig, 'l1RpcUrls' | 'l1ChainId' | 'viemPollingIntervalMS' | 'ethereumSlotDuration'>;
3
3
  export declare function getEpochCacheConfigEnvVars(): EpochCacheConfig;
4
4
  //# sourceMappingURL=config.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,cAAc,EAGpB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,MAAM,gBAAgB,GAAG,IAAI,CACjC,cAAc,GAAG,iBAAiB,EAChC,WAAW,GACX,WAAW,GACX,uBAAuB,GACvB,mBAAmB,GACnB,sBAAsB,GACtB,oBAAoB,CACvB,CAAC;AAEF,wBAAgB,0BAA0B,IAAI,gBAAgB,CAE7D"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,iBAAiB,EACtB,KAAK,cAAc,EAGpB,MAAM,iBAAiB,CAAC;AAEzB,MAAM,MAAM,gBAAgB,GAAG,IAAI,CACjC,cAAc,GAAG,iBAAiB,EAClC,WAAW,GAAG,WAAW,GAAG,uBAAuB,GAAG,sBAAsB,CAC7E,CAAC;AAEF,wBAAgB,0BAA0B,IAAI,gBAAgB,CAE7D"}
@@ -1,87 +1,125 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
1
  import { RollupContract } from '@aztec/ethereum';
3
2
  import { EthAddress } from '@aztec/foundation/eth-address';
4
3
  import { DateProvider } from '@aztec/foundation/timer';
5
4
  import { type L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
6
- import { EventEmitter } from 'node:events';
7
5
  import { type EpochCacheConfig } from './config.js';
8
- type EpochAndSlot = {
6
+ export type EpochAndSlot = {
9
7
  epoch: bigint;
10
8
  slot: bigint;
11
9
  ts: bigint;
12
10
  };
11
+ export type EpochCommitteeInfo = {
12
+ committee: EthAddress[] | undefined;
13
+ seed: bigint;
14
+ epoch: bigint;
15
+ };
16
+ export type SlotTag = 'now' | 'next' | bigint;
13
17
  export interface EpochCacheInterface {
14
- getCommittee(nextSlot: boolean): Promise<EthAddress[]>;
18
+ getCommittee(slot: SlotTag | undefined): Promise<EpochCommitteeInfo>;
15
19
  getEpochAndSlotNow(): EpochAndSlot;
20
+ getEpochAndSlotInNextL1Slot(): EpochAndSlot & {
21
+ now: bigint;
22
+ };
16
23
  getProposerIndexEncoding(epoch: bigint, slot: bigint, seed: bigint): `0x${string}`;
17
24
  computeProposerIndex(slot: bigint, epoch: bigint, seed: bigint, size: bigint): bigint;
18
- getProposerInCurrentOrNextSlot(): Promise<{
19
- currentProposer: EthAddress;
20
- nextProposer: EthAddress;
25
+ getProposerAttesterAddressInCurrentOrNextSlot(): Promise<{
26
+ currentProposer: EthAddress | undefined;
27
+ nextProposer: EthAddress | undefined;
21
28
  currentSlot: bigint;
22
29
  nextSlot: bigint;
23
30
  }>;
24
- isInCommittee(validator: EthAddress): Promise<boolean>;
31
+ getRegisteredValidators(): Promise<EthAddress[]>;
32
+ isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean>;
33
+ filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]>;
25
34
  }
26
35
  /**
27
36
  * Epoch cache
28
37
  *
29
38
  * This class is responsible for managing traffic to the l1 node, by caching the validator set.
39
+ * Keeps the last N epochs in cache.
30
40
  * It also provides a method to get the current or next proposer, and to check who is in the current slot.
31
41
  *
32
- * If the epoch changes, then we update the stored validator set.
33
- *
34
42
  * Note: This class is very dependent on the system clock being in sync.
35
43
  */
36
- export declare class EpochCache extends EventEmitter<{
37
- committeeChanged: [EthAddress[], bigint];
38
- }> implements EpochCacheInterface {
44
+ export declare class EpochCache implements EpochCacheInterface {
39
45
  private rollup;
40
46
  private readonly l1constants;
41
47
  private readonly dateProvider;
42
- private committee;
43
- private cachedEpoch;
44
- private cachedSampleSeed;
48
+ protected readonly config: {
49
+ cacheSize: number;
50
+ validatorRefreshIntervalSeconds: number;
51
+ };
52
+ protected cache: Map<bigint, EpochCommitteeInfo>;
53
+ private allValidators;
54
+ private lastValidatorRefresh;
45
55
  private readonly log;
46
- constructor(rollup: RollupContract, initialValidators?: EthAddress[], initialSampleSeed?: bigint, l1constants?: L1RollupConstants, dateProvider?: DateProvider);
47
- static create(rollupAddress: EthAddress, config?: EpochCacheConfig, deps?: {
56
+ constructor(rollup: RollupContract, l1constants?: L1RollupConstants, dateProvider?: DateProvider, config?: {
57
+ cacheSize: number;
58
+ validatorRefreshIntervalSeconds: number;
59
+ });
60
+ static create(rollupOrAddress: EthAddress | RollupContract, config?: EpochCacheConfig, deps?: {
48
61
  dateProvider?: DateProvider;
49
62
  }): Promise<EpochCache>;
50
- private nowInSeconds;
51
- getEpochAndSlotNow(): EpochAndSlot;
52
- private getEpochAndSlotInNextSlot;
63
+ getL1Constants(): L1RollupConstants;
64
+ getEpochAndSlotNow(): EpochAndSlot & {
65
+ now: bigint;
66
+ };
67
+ nowInSeconds(): bigint;
68
+ private getEpochAndSlotAtSlot;
69
+ getEpochAndSlotInNextL1Slot(): EpochAndSlot & {
70
+ now: bigint;
71
+ };
53
72
  private getEpochAndSlotAtTimestamp;
73
+ getCommitteeForEpoch(epoch: bigint): Promise<EpochCommitteeInfo>;
54
74
  /**
55
75
  * Get the current validator set
56
- *
57
76
  * @param nextSlot - If true, get the validator set for the next slot.
58
77
  * @returns The current validator set.
59
78
  */
60
- getCommittee(nextSlot?: boolean): Promise<EthAddress[]>;
79
+ getCommittee(slot?: SlotTag): Promise<EpochCommitteeInfo>;
80
+ private getEpochAndTimestamp;
81
+ private computeCommittee;
61
82
  /**
62
83
  * Get the ABI encoding of the proposer index - see ValidatorSelectionLib.sol computeProposerIndex
63
84
  */
64
85
  getProposerIndexEncoding(epoch: bigint, slot: bigint, seed: bigint): `0x${string}`;
65
86
  computeProposerIndex(slot: bigint, epoch: bigint, seed: bigint, size: bigint): bigint;
66
87
  /**
67
- * Returns the current and next proposer
88
+ * Returns the current and next proposer's attester address
68
89
  *
69
- * We return the next proposer as the node will check if it is the proposer at the next ethereum block, which
70
- * can be the next slot. If this is the case, then it will send proposals early.
71
- *
72
- * If we are at an epoch boundary, then we can update the cache for the next epoch, this is the last check
73
- * we do in the validator client, so we can update the cache here.
90
+ * We return the next proposer's attester address as the node will check if it is the proposer at the next ethereum block,
91
+ * which can be the next slot. If this is the case, then it will send proposals early.
74
92
  */
75
- getProposerInCurrentOrNextSlot(): Promise<{
76
- currentProposer: EthAddress;
77
- nextProposer: EthAddress;
93
+ getProposerAttesterAddressInCurrentOrNextSlot(): Promise<{
78
94
  currentSlot: bigint;
79
95
  nextSlot: bigint;
96
+ currentProposer: EthAddress | undefined;
97
+ nextProposer: EthAddress | undefined;
80
98
  }>;
81
99
  /**
82
- * Check if a validator is in the current epoch's committee
100
+ * Get the proposer attester address in the given L2 slot
101
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
102
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
103
+ */
104
+ getProposerAttesterAddressInSlot(slot: bigint): Promise<EthAddress | undefined>;
105
+ /**
106
+ * Get the proposer attester address in the next slot
107
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
108
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
109
+ */
110
+ getProposerAttesterAddressInNextSlot(): Promise<EthAddress | undefined>;
111
+ /**
112
+ * Get the proposer attester address at a given epoch and slot
113
+ * @param when - The epoch and slot to get the proposer attester address at
114
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
115
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
83
116
  */
84
- isInCommittee(validator: EthAddress): Promise<boolean>;
117
+ private getProposerAttesterAddressAt;
118
+ getProposerFromEpochCommittee(epochCommitteeInfo: EpochCommitteeInfo, slot: bigint): EthAddress | undefined;
119
+ /** Check if a validator is in the given slot's committee */
120
+ isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean>;
121
+ /** From the set of given addresses, return all that are on the committee for the given slot */
122
+ filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]>;
123
+ getRegisteredValidators(): Promise<EthAddress[]>;
85
124
  }
86
- export {};
87
125
  //# sourceMappingURL=epoch_cache.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"epoch_cache.d.ts","sourceRoot":"","sources":["../src/epoch_cache.ts"],"names":[],"mappings":";AAAA,OAAO,EAAE,cAAc,EAAuB,MAAM,iBAAiB,CAAC;AACtE,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAE3D,OAAO,EAAE,YAAY,EAAE,MAAM,yBAAyB,CAAC;AACvD,OAAO,EAEL,KAAK,iBAAiB,EAGvB,MAAM,6BAA6B,CAAC;AAErC,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAC;AAG3C,OAAO,EAAE,KAAK,gBAAgB,EAA8B,MAAM,aAAa,CAAC;AAEhF,KAAK,YAAY,GAAG;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,EAAE,EAAE,MAAM,CAAC;CACZ,CAAC;AAEF,MAAM,WAAW,mBAAmB;IAClC,YAAY,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CA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AO,CAAC;QACpE,WAAW,EAAE,MAAM,CAAC;QACpB,QAAQ,EAAE,MAAM,CAAC;QACjB,eAAe,EAAE,UAAU,GAAG,SAAS,CAAC;QACxC,YAAY,EAAE,UAAU,GAAG,SAAS,CAAC;KACtC,CAAC;IAYF;;;;OAIG;IACI,gCAAgC,CAAC,IAAI,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC;IAKtF;;;;OAIG;IACI,oCAAoC,IAAI,OAAO,CAAC,UAAU,GAAG,SAAS,CAAC;IAK9E;;;;;OAKG;YACW,4BAA4B;IAanC,6BAA6B,CAAC,kBAAkB,EAAE,kBAAkB,EAAE,IAAI,EAAE,MAAM,GAAG,UAAU,GAAG,SAAS;IAclH,4DAA4D;IACtD,aAAa,CAAC,IAAI,EAAE,OAAO,EAAE,SAAS,EAAE,UAAU,GAAG,OAAO,CAAC,OAAO,CAAC;IAQ3E,+FAA+F;IACzF,iBAAiB,CAAC,IAAI,EAAE,OAAO,EAAE,UAAU,EAAE,UAAU,EAAE,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IASjF,uBAAuB,IAAI,OAAO,CAAC,UAAU,EAAE,CAAC;CAUvD"}
@@ -1,105 +1,160 @@
1
- import { RollupContract, createEthereumChain } from '@aztec/ethereum';
1
+ import { NoCommitteeError, RollupContract, createEthereumChain } from '@aztec/ethereum';
2
2
  import { EthAddress } from '@aztec/foundation/eth-address';
3
3
  import { createLogger } from '@aztec/foundation/log';
4
4
  import { DateProvider } from '@aztec/foundation/timer';
5
- import { EmptyL1RollupConstants, getEpochNumberAtTimestamp, getSlotAtTimestamp } from '@aztec/stdlib/epoch-helpers';
6
- import { EventEmitter } from 'node:events';
5
+ import { EmptyL1RollupConstants, getEpochAtSlot, getEpochNumberAtTimestamp, getSlotAtTimestamp, getSlotRangeForEpoch, getTimestampForSlot, getTimestampRangeForEpoch } from '@aztec/stdlib/epoch-helpers';
7
6
  import { createPublicClient, encodeAbiParameters, fallback, http, keccak256 } from 'viem';
8
7
  import { getEpochCacheConfigEnvVars } from './config.js';
9
8
  /**
10
9
  * Epoch cache
11
10
  *
12
11
  * This class is responsible for managing traffic to the l1 node, by caching the validator set.
12
+ * Keeps the last N epochs in cache.
13
13
  * It also provides a method to get the current or next proposer, and to check who is in the current slot.
14
14
  *
15
- * If the epoch changes, then we update the stored validator set.
16
- *
17
15
  * Note: This class is very dependent on the system clock being in sync.
18
- */ export class EpochCache extends EventEmitter {
16
+ */ export class EpochCache {
19
17
  rollup;
20
18
  l1constants;
21
19
  dateProvider;
22
- committee;
23
- cachedEpoch;
24
- cachedSampleSeed;
20
+ config;
21
+ cache;
22
+ allValidators;
23
+ lastValidatorRefresh;
25
24
  log;
26
- constructor(rollup, initialValidators = [], initialSampleSeed = 0n, l1constants = EmptyL1RollupConstants, dateProvider = new DateProvider()){
27
- super(), this.rollup = rollup, this.l1constants = l1constants, this.dateProvider = dateProvider, this.log = createLogger('epoch-cache');
28
- this.committee = initialValidators;
29
- this.cachedSampleSeed = initialSampleSeed;
30
- this.log.debug(`Initialized EpochCache with constants and validators`, {
31
- l1constants,
32
- initialValidators
25
+ constructor(rollup, l1constants = EmptyL1RollupConstants, dateProvider = new DateProvider(), config = {
26
+ cacheSize: 12,
27
+ validatorRefreshIntervalSeconds: 60
28
+ }){
29
+ this.rollup = rollup;
30
+ this.l1constants = l1constants;
31
+ this.dateProvider = dateProvider;
32
+ this.config = config;
33
+ this.cache = new Map();
34
+ this.allValidators = new Set();
35
+ this.lastValidatorRefresh = 0;
36
+ this.log = createLogger('epoch-cache');
37
+ this.log.debug(`Initialized EpochCache`, {
38
+ l1constants
33
39
  });
34
- this.cachedEpoch = getEpochNumberAtTimestamp(this.nowInSeconds(), this.l1constants);
35
40
  }
36
- static async create(rollupAddress, config, deps = {}) {
41
+ static async create(rollupOrAddress, config, deps = {}) {
37
42
  config = config ?? getEpochCacheConfigEnvVars();
38
- const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
39
- const publicClient = createPublicClient({
40
- chain: chain.chainInfo,
41
- transport: fallback(config.l1RpcUrls.map((url)=>http(url))),
42
- pollingInterval: config.viemPollingIntervalMS
43
- });
44
- const rollup = new RollupContract(publicClient, rollupAddress.toString());
45
- const [l1StartBlock, l1GenesisTime, initialValidators, sampleSeed] = await Promise.all([
43
+ // Load the rollup contract if we were given an address
44
+ let rollup;
45
+ if ('address' in rollupOrAddress) {
46
+ rollup = rollupOrAddress;
47
+ } else {
48
+ const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
49
+ const publicClient = createPublicClient({
50
+ chain: chain.chainInfo,
51
+ transport: fallback(config.l1RpcUrls.map((url)=>http(url))),
52
+ pollingInterval: config.viemPollingIntervalMS
53
+ });
54
+ rollup = new RollupContract(publicClient, rollupOrAddress.toString());
55
+ }
56
+ const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs, slotDuration, epochDuration] = await Promise.all([
46
57
  rollup.getL1StartBlock(),
47
58
  rollup.getL1GenesisTime(),
48
- rollup.getCurrentEpochCommittee(),
49
- rollup.getCurrentSampleSeed()
59
+ rollup.getProofSubmissionEpochs(),
60
+ rollup.getSlotDuration(),
61
+ rollup.getEpochDuration()
50
62
  ]);
51
63
  const l1RollupConstants = {
52
64
  l1StartBlock,
53
65
  l1GenesisTime,
54
- slotDuration: config.aztecSlotDuration,
55
- epochDuration: config.aztecEpochDuration,
66
+ proofSubmissionEpochs: Number(proofSubmissionEpochs),
67
+ slotDuration: Number(slotDuration),
68
+ epochDuration: Number(epochDuration),
56
69
  ethereumSlotDuration: config.ethereumSlotDuration
57
70
  };
58
- return new EpochCache(rollup, initialValidators.map((v)=>EthAddress.fromString(v)), sampleSeed, l1RollupConstants, deps.dateProvider);
71
+ return new EpochCache(rollup, l1RollupConstants, deps.dateProvider);
72
+ }
73
+ getL1Constants() {
74
+ return this.l1constants;
75
+ }
76
+ getEpochAndSlotNow() {
77
+ const now = this.nowInSeconds();
78
+ return {
79
+ ...this.getEpochAndSlotAtTimestamp(now),
80
+ now
81
+ };
59
82
  }
60
83
  nowInSeconds() {
61
84
  return BigInt(Math.floor(this.dateProvider.now() / 1000));
62
85
  }
63
- getEpochAndSlotNow() {
64
- return this.getEpochAndSlotAtTimestamp(this.nowInSeconds());
86
+ getEpochAndSlotAtSlot(slot) {
87
+ const epoch = getEpochAtSlot(slot, this.l1constants);
88
+ const ts = getTimestampRangeForEpoch(epoch, this.l1constants)[0];
89
+ return {
90
+ epoch,
91
+ ts,
92
+ slot
93
+ };
65
94
  }
66
- getEpochAndSlotInNextSlot() {
67
- const nextSlotTs = this.nowInSeconds() + BigInt(this.l1constants.slotDuration);
68
- return this.getEpochAndSlotAtTimestamp(nextSlotTs);
95
+ getEpochAndSlotInNextL1Slot() {
96
+ const now = this.nowInSeconds();
97
+ const nextSlotTs = now + BigInt(this.l1constants.ethereumSlotDuration);
98
+ return {
99
+ ...this.getEpochAndSlotAtTimestamp(nextSlotTs),
100
+ now
101
+ };
69
102
  }
70
103
  getEpochAndSlotAtTimestamp(ts) {
104
+ const slot = getSlotAtTimestamp(ts, this.l1constants);
71
105
  return {
72
106
  epoch: getEpochNumberAtTimestamp(ts, this.l1constants),
73
- slot: getSlotAtTimestamp(ts, this.l1constants),
74
- ts
107
+ ts: getTimestampForSlot(slot, this.l1constants),
108
+ slot
75
109
  };
76
110
  }
111
+ getCommitteeForEpoch(epoch) {
112
+ const [startSlot] = getSlotRangeForEpoch(epoch, this.l1constants);
113
+ return this.getCommittee(startSlot);
114
+ }
77
115
  /**
78
116
  * Get the current validator set
79
- *
80
117
  * @param nextSlot - If true, get the validator set for the next slot.
81
118
  * @returns The current validator set.
82
- */ async getCommittee(nextSlot = false) {
83
- // If the current epoch has changed, then we need to make a request to update the validator set
84
- const { epoch: calculatedEpoch, ts } = nextSlot ? this.getEpochAndSlotInNextSlot() : this.getEpochAndSlotNow();
85
- if (calculatedEpoch !== this.cachedEpoch) {
86
- this.log.debug(`Updating validator set for new epoch ${calculatedEpoch}`, {
87
- epoch: calculatedEpoch,
88
- previousEpoch: this.cachedEpoch
89
- });
90
- const [committeeAtTs, sampleSeedAtTs] = await Promise.all([
91
- this.rollup.getCommitteeAt(ts),
92
- this.rollup.getSampleSeedAt(ts)
93
- ]);
94
- this.committee = committeeAtTs.map((v)=>EthAddress.fromString(v));
95
- this.cachedEpoch = calculatedEpoch;
96
- this.cachedSampleSeed = sampleSeedAtTs;
97
- this.log.debug(`Updated validator set for epoch ${calculatedEpoch}`, {
98
- commitee: this.committee
99
- });
100
- this.emit('committeeChanged', this.committee, calculatedEpoch);
119
+ */ async getCommittee(slot = 'now') {
120
+ const { epoch, ts } = this.getEpochAndTimestamp(slot);
121
+ if (this.cache.has(epoch)) {
122
+ return this.cache.get(epoch);
123
+ }
124
+ const epochData = await this.computeCommittee({
125
+ epoch,
126
+ ts
127
+ });
128
+ // If the committee size is 0 or undefined, then do not cache
129
+ if (!epochData.committee || epochData.committee.length === 0) {
130
+ return epochData;
131
+ }
132
+ this.cache.set(epoch, epochData);
133
+ const toPurge = Array.from(this.cache.keys()).sort((a, b)=>Number(b - a)).slice(this.config.cacheSize);
134
+ toPurge.forEach((key)=>this.cache.delete(key));
135
+ return epochData;
136
+ }
137
+ getEpochAndTimestamp(slot = 'now') {
138
+ if (slot === 'now') {
139
+ return this.getEpochAndSlotNow();
140
+ } else if (slot === 'next') {
141
+ return this.getEpochAndSlotInNextL1Slot();
142
+ } else {
143
+ return this.getEpochAndSlotAtSlot(slot);
101
144
  }
102
- return this.committee;
145
+ }
146
+ async computeCommittee(when) {
147
+ const { ts, epoch } = when;
148
+ const [committeeHex, seed] = await Promise.all([
149
+ this.rollup.getCommitteeAt(ts),
150
+ this.rollup.getSampleSeedAt(ts)
151
+ ]);
152
+ const committee = committeeHex?.map((v)=>EthAddress.fromString(v));
153
+ return {
154
+ committee,
155
+ seed,
156
+ epoch
157
+ };
103
158
  }
104
159
  /**
105
160
  * Get the ABI encoding of the proposer index - see ValidatorSelectionLib.sol computeProposerIndex
@@ -124,41 +179,89 @@ import { getEpochCacheConfigEnvVars } from './config.js';
124
179
  ]);
125
180
  }
126
181
  computeProposerIndex(slot, epoch, seed, size) {
182
+ // if committe size is 0, then mod 1 is 0
183
+ if (size === 0n) {
184
+ return 0n;
185
+ }
127
186
  return BigInt(keccak256(this.getProposerIndexEncoding(epoch, slot, seed))) % size;
128
187
  }
129
188
  /**
130
- * Returns the current and next proposer
131
- *
132
- * We return the next proposer as the node will check if it is the proposer at the next ethereum block, which
133
- * can be the next slot. If this is the case, then it will send proposals early.
189
+ * Returns the current and next proposer's attester address
134
190
  *
135
- * If we are at an epoch boundary, then we can update the cache for the next epoch, this is the last check
136
- * we do in the validator client, so we can update the cache here.
137
- */ async getProposerInCurrentOrNextSlot() {
138
- // Validators are sorted by their index in the committee, and getValidatorSet will cache
139
- const committee = await this.getCommittee();
140
- const { slot: currentSlot, epoch: currentEpoch } = this.getEpochAndSlotNow();
141
- const { slot: nextSlot, epoch: nextEpoch } = this.getEpochAndSlotInNextSlot();
142
- // Compute the proposer in this and the next slot
143
- const proposerIndex = this.computeProposerIndex(currentSlot, this.cachedEpoch, this.cachedSampleSeed, BigInt(committee.length));
144
- // Check if the next proposer is in the next epoch
145
- if (nextEpoch !== currentEpoch) {
146
- await this.getCommittee(/*next slot*/ true);
147
- }
148
- const nextProposerIndex = this.computeProposerIndex(nextSlot, this.cachedEpoch, this.cachedSampleSeed, BigInt(committee.length));
149
- const currentProposer = committee[Number(proposerIndex)];
150
- const nextProposer = committee[Number(nextProposerIndex)];
191
+ * We return the next proposer's attester address as the node will check if it is the proposer at the next ethereum block,
192
+ * which can be the next slot. If this is the case, then it will send proposals early.
193
+ */ async getProposerAttesterAddressInCurrentOrNextSlot() {
194
+ const current = this.getEpochAndSlotNow();
195
+ const next = this.getEpochAndSlotInNextL1Slot();
151
196
  return {
152
- currentProposer,
153
- nextProposer,
154
- currentSlot,
155
- nextSlot
197
+ currentProposer: await this.getProposerAttesterAddressAt(current),
198
+ nextProposer: await this.getProposerAttesterAddressAt(next),
199
+ currentSlot: current.slot,
200
+ nextSlot: next.slot
156
201
  };
157
202
  }
158
203
  /**
159
- * Check if a validator is in the current epoch's committee
160
- */ async isInCommittee(validator) {
161
- const committee = await this.getCommittee();
204
+ * Get the proposer attester address in the given L2 slot
205
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
206
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
207
+ */ getProposerAttesterAddressInSlot(slot) {
208
+ const epochAndSlot = this.getEpochAndSlotAtSlot(slot);
209
+ return this.getProposerAttesterAddressAt(epochAndSlot);
210
+ }
211
+ /**
212
+ * Get the proposer attester address in the next slot
213
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
214
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
215
+ */ getProposerAttesterAddressInNextSlot() {
216
+ const epochAndSlot = this.getEpochAndSlotInNextL1Slot();
217
+ return this.getProposerAttesterAddressAt(epochAndSlot);
218
+ }
219
+ /**
220
+ * Get the proposer attester address at a given epoch and slot
221
+ * @param when - The epoch and slot to get the proposer attester address at
222
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
223
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
224
+ */ async getProposerAttesterAddressAt(when) {
225
+ const { epoch, slot } = when;
226
+ const { committee, seed } = await this.getCommittee(slot);
227
+ if (!committee) {
228
+ throw new NoCommitteeError();
229
+ } else if (committee.length === 0) {
230
+ return undefined;
231
+ }
232
+ const proposerIndex = this.computeProposerIndex(slot, epoch, seed, BigInt(committee.length));
233
+ return committee[Number(proposerIndex)];
234
+ }
235
+ getProposerFromEpochCommittee(epochCommitteeInfo, slot) {
236
+ if (!epochCommitteeInfo.committee || epochCommitteeInfo.committee.length === 0) {
237
+ return undefined;
238
+ }
239
+ const proposerIndex = this.computeProposerIndex(slot, epochCommitteeInfo.epoch, epochCommitteeInfo.seed, BigInt(epochCommitteeInfo.committee.length));
240
+ return epochCommitteeInfo.committee[Number(proposerIndex)];
241
+ }
242
+ /** Check if a validator is in the given slot's committee */ async isInCommittee(slot, validator) {
243
+ const { committee } = await this.getCommittee(slot);
244
+ if (!committee) {
245
+ return false;
246
+ }
162
247
  return committee.some((v)=>v.equals(validator));
163
248
  }
249
+ /** From the set of given addresses, return all that are on the committee for the given slot */ async filterInCommittee(slot, validators) {
250
+ const { committee } = await this.getCommittee(slot);
251
+ if (!committee) {
252
+ return [];
253
+ }
254
+ const committeeSet = new Set(committee.map((v)=>v.toString()));
255
+ return validators.filter((v)=>committeeSet.has(v.toString()));
256
+ }
257
+ async getRegisteredValidators() {
258
+ const validatorRefreshIntervalMs = this.config.validatorRefreshIntervalSeconds * 1000;
259
+ const validatorRefreshTime = this.lastValidatorRefresh + validatorRefreshIntervalMs;
260
+ if (validatorRefreshTime < this.dateProvider.now()) {
261
+ const currentSet = await this.rollup.getAttesters();
262
+ this.allValidators = new Set(currentSet);
263
+ this.lastValidatorRefresh = this.dateProvider.now();
264
+ }
265
+ return Array.from(this.allValidators.keys().map((v)=>EthAddress.fromString(v)));
266
+ }
164
267
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aztec/epoch-cache",
3
- "version": "0.0.0-test.1",
3
+ "version": "0.0.1-fake-ceab37513c",
4
4
  "type": "module",
5
5
  "exports": {
6
6
  ".": "./dest/index.js",
@@ -18,8 +18,6 @@
18
18
  "build": "yarn clean && tsc -b",
19
19
  "build:dev": "tsc -b --watch",
20
20
  "clean": "rm -rf ./dest .tsbuildinfo",
21
- "formatting": "run -T prettier --check ./src && run -T eslint ./src",
22
- "formatting:fix": "run -T eslint --fix ./src && run -T prettier -w ./src",
23
21
  "start:dev": "tsc-watch -p tsconfig.json --onSuccess 'yarn start'",
24
22
  "start": "node ./dest/index.js",
25
23
  "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
@@ -28,25 +26,25 @@
28
26
  "../package.common.json"
29
27
  ],
30
28
  "dependencies": {
31
- "@aztec/ethereum": "0.0.0-test.1",
32
- "@aztec/foundation": "0.0.0-test.1",
33
- "@aztec/l1-artifacts": "0.0.0-test.1",
34
- "@aztec/stdlib": "0.0.0-test.1",
29
+ "@aztec/ethereum": "0.0.1-fake-ceab37513c",
30
+ "@aztec/foundation": "0.0.1-fake-ceab37513c",
31
+ "@aztec/l1-artifacts": "0.0.1-fake-ceab37513c",
32
+ "@aztec/stdlib": "0.0.1-fake-ceab37513c",
35
33
  "@viem/anvil": "^0.0.10",
36
34
  "dotenv": "^16.0.3",
37
35
  "get-port": "^7.1.0",
38
- "jest-mock-extended": "^3.0.7",
36
+ "jest-mock-extended": "^4.0.0",
39
37
  "tslib": "^2.4.0",
40
- "viem": "2.22.8",
38
+ "viem": "npm:@spalladino/viem@2.38.2-eip7594.0",
41
39
  "zod": "^3.23.8"
42
40
  },
43
41
  "devDependencies": {
44
- "@jest/globals": "^29.5.0",
45
- "@types/jest": "^29.5.0",
46
- "@types/node": "^18.14.6",
47
- "jest": "^29.5.0",
42
+ "@jest/globals": "^30.0.0",
43
+ "@types/jest": "^30.0.0",
44
+ "@types/node": "^22.15.17",
45
+ "jest": "^30.0.0",
48
46
  "ts-node": "^10.9.1",
49
- "typescript": "^5.0.4"
47
+ "typescript": "^5.3.3"
50
48
  },
51
49
  "files": [
52
50
  "dest",
@@ -85,9 +83,13 @@
85
83
  "testTimeout": 120000,
86
84
  "setupFiles": [
87
85
  "../../foundation/src/jest/setup.mjs"
86
+ ],
87
+ "testEnvironment": "../../foundation/src/jest/env.mjs",
88
+ "setupFilesAfterEnv": [
89
+ "../../foundation/src/jest/setupAfterEnv.mjs"
88
90
  ]
89
91
  },
90
92
  "engines": {
91
- "node": ">=18"
93
+ "node": ">=20.10"
92
94
  }
93
95
  }
package/src/config.ts CHANGED
@@ -7,12 +7,7 @@ import {
7
7
 
8
8
  export type EpochCacheConfig = Pick<
9
9
  L1ReaderConfig & L1ContractsConfig,
10
- | 'l1RpcUrls'
11
- | 'l1ChainId'
12
- | 'viemPollingIntervalMS'
13
- | 'aztecSlotDuration'
14
- | 'ethereumSlotDuration'
15
- | 'aztecEpochDuration'
10
+ 'l1RpcUrls' | 'l1ChainId' | 'viemPollingIntervalMS' | 'ethereumSlotDuration'
16
11
  >;
17
12
 
18
13
  export function getEpochCacheConfigEnvVars(): EpochCacheConfig {
@@ -1,161 +1,201 @@
1
- import { RollupContract, createEthereumChain } from '@aztec/ethereum';
1
+ import { NoCommitteeError, RollupContract, createEthereumChain } from '@aztec/ethereum';
2
2
  import { EthAddress } from '@aztec/foundation/eth-address';
3
3
  import { type Logger, createLogger } from '@aztec/foundation/log';
4
4
  import { DateProvider } from '@aztec/foundation/timer';
5
5
  import {
6
6
  EmptyL1RollupConstants,
7
7
  type L1RollupConstants,
8
+ getEpochAtSlot,
8
9
  getEpochNumberAtTimestamp,
9
10
  getSlotAtTimestamp,
11
+ getSlotRangeForEpoch,
12
+ getTimestampForSlot,
13
+ getTimestampRangeForEpoch,
10
14
  } from '@aztec/stdlib/epoch-helpers';
11
15
 
12
- import { EventEmitter } from 'node:events';
13
16
  import { createPublicClient, encodeAbiParameters, fallback, http, keccak256 } from 'viem';
14
17
 
15
18
  import { type EpochCacheConfig, getEpochCacheConfigEnvVars } from './config.js';
16
19
 
17
- type EpochAndSlot = {
20
+ export type EpochAndSlot = {
18
21
  epoch: bigint;
19
22
  slot: bigint;
20
23
  ts: bigint;
21
24
  };
22
25
 
26
+ export type EpochCommitteeInfo = {
27
+ committee: EthAddress[] | undefined;
28
+ seed: bigint;
29
+ epoch: bigint;
30
+ };
31
+
32
+ export type SlotTag = 'now' | 'next' | bigint;
33
+
23
34
  export interface EpochCacheInterface {
24
- getCommittee(nextSlot: boolean): Promise<EthAddress[]>;
35
+ getCommittee(slot: SlotTag | undefined): Promise<EpochCommitteeInfo>;
25
36
  getEpochAndSlotNow(): EpochAndSlot;
37
+ getEpochAndSlotInNextL1Slot(): EpochAndSlot & { now: bigint };
26
38
  getProposerIndexEncoding(epoch: bigint, slot: bigint, seed: bigint): `0x${string}`;
27
39
  computeProposerIndex(slot: bigint, epoch: bigint, seed: bigint, size: bigint): bigint;
28
- getProposerInCurrentOrNextSlot(): Promise<{
29
- currentProposer: EthAddress;
30
- nextProposer: EthAddress;
40
+ getProposerAttesterAddressInCurrentOrNextSlot(): Promise<{
41
+ currentProposer: EthAddress | undefined;
42
+ nextProposer: EthAddress | undefined;
31
43
  currentSlot: bigint;
32
44
  nextSlot: bigint;
33
45
  }>;
34
- isInCommittee(validator: EthAddress): Promise<boolean>;
46
+ getRegisteredValidators(): Promise<EthAddress[]>;
47
+ isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean>;
48
+ filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]>;
35
49
  }
36
50
 
37
51
  /**
38
52
  * Epoch cache
39
53
  *
40
54
  * This class is responsible for managing traffic to the l1 node, by caching the validator set.
55
+ * Keeps the last N epochs in cache.
41
56
  * It also provides a method to get the current or next proposer, and to check who is in the current slot.
42
57
  *
43
- * If the epoch changes, then we update the stored validator set.
44
- *
45
58
  * Note: This class is very dependent on the system clock being in sync.
46
59
  */
47
- export class EpochCache
48
- extends EventEmitter<{ committeeChanged: [EthAddress[], bigint] }>
49
- implements EpochCacheInterface
50
- {
51
- private committee: EthAddress[];
52
- private cachedEpoch: bigint;
53
- private cachedSampleSeed: bigint;
60
+ export class EpochCache implements EpochCacheInterface {
61
+ protected cache: Map<bigint, EpochCommitteeInfo> = new Map();
62
+ private allValidators: Set<string> = new Set();
63
+ private lastValidatorRefresh = 0;
54
64
  private readonly log: Logger = createLogger('epoch-cache');
55
65
 
56
66
  constructor(
57
67
  private rollup: RollupContract,
58
- initialValidators: EthAddress[] = [],
59
- initialSampleSeed: bigint = 0n,
60
68
  private readonly l1constants: L1RollupConstants = EmptyL1RollupConstants,
61
69
  private readonly dateProvider: DateProvider = new DateProvider(),
70
+ protected readonly config = { cacheSize: 12, validatorRefreshIntervalSeconds: 60 },
62
71
  ) {
63
- super();
64
- this.committee = initialValidators;
65
- this.cachedSampleSeed = initialSampleSeed;
66
-
67
- this.log.debug(`Initialized EpochCache with constants and validators`, { l1constants, initialValidators });
68
-
69
- this.cachedEpoch = getEpochNumberAtTimestamp(this.nowInSeconds(), this.l1constants);
72
+ this.log.debug(`Initialized EpochCache`, {
73
+ l1constants,
74
+ });
70
75
  }
71
76
 
72
77
  static async create(
73
- rollupAddress: EthAddress,
78
+ rollupOrAddress: EthAddress | RollupContract,
74
79
  config?: EpochCacheConfig,
75
80
  deps: { dateProvider?: DateProvider } = {},
76
81
  ) {
77
82
  config = config ?? getEpochCacheConfigEnvVars();
78
83
 
79
- const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
80
- const publicClient = createPublicClient({
81
- chain: chain.chainInfo,
82
- transport: fallback(config.l1RpcUrls.map(url => http(url))),
83
- pollingInterval: config.viemPollingIntervalMS,
84
- });
84
+ // Load the rollup contract if we were given an address
85
+ let rollup: RollupContract;
86
+ if ('address' in rollupOrAddress) {
87
+ rollup = rollupOrAddress;
88
+ } else {
89
+ const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
90
+ const publicClient = createPublicClient({
91
+ chain: chain.chainInfo,
92
+ transport: fallback(config.l1RpcUrls.map(url => http(url))),
93
+ pollingInterval: config.viemPollingIntervalMS,
94
+ });
95
+ rollup = new RollupContract(publicClient, rollupOrAddress.toString());
96
+ }
85
97
 
86
- const rollup = new RollupContract(publicClient, rollupAddress.toString());
87
- const [l1StartBlock, l1GenesisTime, initialValidators, sampleSeed] = await Promise.all([
98
+ const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs, slotDuration, epochDuration] = await Promise.all([
88
99
  rollup.getL1StartBlock(),
89
100
  rollup.getL1GenesisTime(),
90
- rollup.getCurrentEpochCommittee(),
91
- rollup.getCurrentSampleSeed(),
101
+ rollup.getProofSubmissionEpochs(),
102
+ rollup.getSlotDuration(),
103
+ rollup.getEpochDuration(),
92
104
  ] as const);
93
105
 
94
106
  const l1RollupConstants: L1RollupConstants = {
95
107
  l1StartBlock,
96
108
  l1GenesisTime,
97
- slotDuration: config.aztecSlotDuration,
98
- epochDuration: config.aztecEpochDuration,
109
+ proofSubmissionEpochs: Number(proofSubmissionEpochs),
110
+ slotDuration: Number(slotDuration),
111
+ epochDuration: Number(epochDuration),
99
112
  ethereumSlotDuration: config.ethereumSlotDuration,
100
113
  };
101
114
 
102
- return new EpochCache(
103
- rollup,
104
- initialValidators.map(v => EthAddress.fromString(v)),
105
- sampleSeed,
106
- l1RollupConstants,
107
- deps.dateProvider,
108
- );
115
+ return new EpochCache(rollup, l1RollupConstants, deps.dateProvider);
116
+ }
117
+
118
+ public getL1Constants(): L1RollupConstants {
119
+ return this.l1constants;
120
+ }
121
+
122
+ public getEpochAndSlotNow(): EpochAndSlot & { now: bigint } {
123
+ const now = this.nowInSeconds();
124
+ return { ...this.getEpochAndSlotAtTimestamp(now), now };
109
125
  }
110
126
 
111
- private nowInSeconds(): bigint {
127
+ public nowInSeconds(): bigint {
112
128
  return BigInt(Math.floor(this.dateProvider.now() / 1000));
113
129
  }
114
130
 
115
- getEpochAndSlotNow(): EpochAndSlot {
116
- return this.getEpochAndSlotAtTimestamp(this.nowInSeconds());
131
+ private getEpochAndSlotAtSlot(slot: bigint): EpochAndSlot {
132
+ const epoch = getEpochAtSlot(slot, this.l1constants);
133
+ const ts = getTimestampRangeForEpoch(epoch, this.l1constants)[0];
134
+ return { epoch, ts, slot };
117
135
  }
118
136
 
119
- private getEpochAndSlotInNextSlot(): EpochAndSlot {
120
- const nextSlotTs = this.nowInSeconds() + BigInt(this.l1constants.slotDuration);
121
- return this.getEpochAndSlotAtTimestamp(nextSlotTs);
137
+ public getEpochAndSlotInNextL1Slot(): EpochAndSlot & { now: bigint } {
138
+ const now = this.nowInSeconds();
139
+ const nextSlotTs = now + BigInt(this.l1constants.ethereumSlotDuration);
140
+ return { ...this.getEpochAndSlotAtTimestamp(nextSlotTs), now };
122
141
  }
123
142
 
124
143
  private getEpochAndSlotAtTimestamp(ts: bigint): EpochAndSlot {
144
+ const slot = getSlotAtTimestamp(ts, this.l1constants);
125
145
  return {
126
146
  epoch: getEpochNumberAtTimestamp(ts, this.l1constants),
127
- slot: getSlotAtTimestamp(ts, this.l1constants),
128
- ts,
147
+ ts: getTimestampForSlot(slot, this.l1constants),
148
+ slot,
129
149
  };
130
150
  }
131
151
 
152
+ public getCommitteeForEpoch(epoch: bigint): Promise<EpochCommitteeInfo> {
153
+ const [startSlot] = getSlotRangeForEpoch(epoch, this.l1constants);
154
+ return this.getCommittee(startSlot);
155
+ }
156
+
132
157
  /**
133
158
  * Get the current validator set
134
- *
135
159
  * @param nextSlot - If true, get the validator set for the next slot.
136
160
  * @returns The current validator set.
137
161
  */
138
- async getCommittee(nextSlot: boolean = false): Promise<EthAddress[]> {
139
- // If the current epoch has changed, then we need to make a request to update the validator set
140
- const { epoch: calculatedEpoch, ts } = nextSlot ? this.getEpochAndSlotInNextSlot() : this.getEpochAndSlotNow();
141
-
142
- if (calculatedEpoch !== this.cachedEpoch) {
143
- this.log.debug(`Updating validator set for new epoch ${calculatedEpoch}`, {
144
- epoch: calculatedEpoch,
145
- previousEpoch: this.cachedEpoch,
146
- });
147
- const [committeeAtTs, sampleSeedAtTs] = await Promise.all([
148
- this.rollup.getCommitteeAt(ts),
149
- this.rollup.getSampleSeedAt(ts),
150
- ]);
151
- this.committee = committeeAtTs.map((v: `0x${string}`) => EthAddress.fromString(v));
152
- this.cachedEpoch = calculatedEpoch;
153
- this.cachedSampleSeed = sampleSeedAtTs;
154
- this.log.debug(`Updated validator set for epoch ${calculatedEpoch}`, { commitee: this.committee });
155
- this.emit('committeeChanged', this.committee, calculatedEpoch);
162
+ public async getCommittee(slot: SlotTag = 'now'): Promise<EpochCommitteeInfo> {
163
+ const { epoch, ts } = this.getEpochAndTimestamp(slot);
164
+
165
+ if (this.cache.has(epoch)) {
166
+ return this.cache.get(epoch)!;
167
+ }
168
+
169
+ const epochData = await this.computeCommittee({ epoch, ts });
170
+ // If the committee size is 0 or undefined, then do not cache
171
+ if (!epochData.committee || epochData.committee.length === 0) {
172
+ return epochData;
156
173
  }
174
+ this.cache.set(epoch, epochData);
175
+
176
+ const toPurge = Array.from(this.cache.keys())
177
+ .sort((a, b) => Number(b - a))
178
+ .slice(this.config.cacheSize);
179
+ toPurge.forEach(key => this.cache.delete(key));
157
180
 
158
- return this.committee;
181
+ return epochData;
182
+ }
183
+
184
+ private getEpochAndTimestamp(slot: SlotTag = 'now') {
185
+ if (slot === 'now') {
186
+ return this.getEpochAndSlotNow();
187
+ } else if (slot === 'next') {
188
+ return this.getEpochAndSlotInNextL1Slot();
189
+ } else {
190
+ return this.getEpochAndSlotAtSlot(slot);
191
+ }
192
+ }
193
+
194
+ private async computeCommittee(when: { epoch: bigint; ts: bigint }): Promise<EpochCommitteeInfo> {
195
+ const { ts, epoch } = when;
196
+ const [committeeHex, seed] = await Promise.all([this.rollup.getCommitteeAt(ts), this.rollup.getSampleSeedAt(ts)]);
197
+ const committee = committeeHex?.map((v: `0x${string}`) => EthAddress.fromString(v));
198
+ return { committee, seed, epoch };
159
199
  }
160
200
 
161
201
  /**
@@ -172,60 +212,117 @@ export class EpochCache
172
212
  );
173
213
  }
174
214
 
175
- computeProposerIndex(slot: bigint, epoch: bigint, seed: bigint, size: bigint): bigint {
215
+ public computeProposerIndex(slot: bigint, epoch: bigint, seed: bigint, size: bigint): bigint {
216
+ // if committe size is 0, then mod 1 is 0
217
+ if (size === 0n) {
218
+ return 0n;
219
+ }
176
220
  return BigInt(keccak256(this.getProposerIndexEncoding(epoch, slot, seed))) % size;
177
221
  }
178
222
 
179
223
  /**
180
- * Returns the current and next proposer
181
- *
182
- * We return the next proposer as the node will check if it is the proposer at the next ethereum block, which
183
- * can be the next slot. If this is the case, then it will send proposals early.
224
+ * Returns the current and next proposer's attester address
184
225
  *
185
- * If we are at an epoch boundary, then we can update the cache for the next epoch, this is the last check
186
- * we do in the validator client, so we can update the cache here.
226
+ * We return the next proposer's attester address as the node will check if it is the proposer at the next ethereum block,
227
+ * which can be the next slot. If this is the case, then it will send proposals early.
187
228
  */
188
- async getProposerInCurrentOrNextSlot(): Promise<{
189
- currentProposer: EthAddress;
190
- nextProposer: EthAddress;
229
+ public async getProposerAttesterAddressInCurrentOrNextSlot(): Promise<{
191
230
  currentSlot: bigint;
192
231
  nextSlot: bigint;
232
+ currentProposer: EthAddress | undefined;
233
+ nextProposer: EthAddress | undefined;
193
234
  }> {
194
- // Validators are sorted by their index in the committee, and getValidatorSet will cache
195
- const committee = await this.getCommittee();
196
- const { slot: currentSlot, epoch: currentEpoch } = this.getEpochAndSlotNow();
197
- const { slot: nextSlot, epoch: nextEpoch } = this.getEpochAndSlotInNextSlot();
235
+ const current = this.getEpochAndSlotNow();
236
+ const next = this.getEpochAndSlotInNextL1Slot();
198
237
 
199
- // Compute the proposer in this and the next slot
200
- const proposerIndex = this.computeProposerIndex(
201
- currentSlot,
202
- this.cachedEpoch,
203
- this.cachedSampleSeed,
204
- BigInt(committee.length),
205
- );
206
-
207
- // Check if the next proposer is in the next epoch
208
- if (nextEpoch !== currentEpoch) {
209
- await this.getCommittee(/*next slot*/ true);
210
- }
211
- const nextProposerIndex = this.computeProposerIndex(
212
- nextSlot,
213
- this.cachedEpoch,
214
- this.cachedSampleSeed,
215
- BigInt(committee.length),
216
- );
238
+ return {
239
+ currentProposer: await this.getProposerAttesterAddressAt(current),
240
+ nextProposer: await this.getProposerAttesterAddressAt(next),
241
+ currentSlot: current.slot,
242
+ nextSlot: next.slot,
243
+ };
244
+ }
217
245
 
218
- const currentProposer = committee[Number(proposerIndex)];
219
- const nextProposer = committee[Number(nextProposerIndex)];
246
+ /**
247
+ * Get the proposer attester address in the given L2 slot
248
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
249
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
250
+ */
251
+ public getProposerAttesterAddressInSlot(slot: bigint): Promise<EthAddress | undefined> {
252
+ const epochAndSlot = this.getEpochAndSlotAtSlot(slot);
253
+ return this.getProposerAttesterAddressAt(epochAndSlot);
254
+ }
220
255
 
221
- return { currentProposer, nextProposer, currentSlot, nextSlot };
256
+ /**
257
+ * Get the proposer attester address in the next slot
258
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
259
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
260
+ */
261
+ public getProposerAttesterAddressInNextSlot(): Promise<EthAddress | undefined> {
262
+ const epochAndSlot = this.getEpochAndSlotInNextL1Slot();
263
+ return this.getProposerAttesterAddressAt(epochAndSlot);
222
264
  }
223
265
 
224
266
  /**
225
- * Check if a validator is in the current epoch's committee
267
+ * Get the proposer attester address at a given epoch and slot
268
+ * @param when - The epoch and slot to get the proposer attester address at
269
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
270
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
226
271
  */
227
- async isInCommittee(validator: EthAddress): Promise<boolean> {
228
- const committee = await this.getCommittee();
272
+ private async getProposerAttesterAddressAt(when: EpochAndSlot) {
273
+ const { epoch, slot } = when;
274
+ const { committee, seed } = await this.getCommittee(slot);
275
+ if (!committee) {
276
+ throw new NoCommitteeError();
277
+ } else if (committee.length === 0) {
278
+ return undefined;
279
+ }
280
+
281
+ const proposerIndex = this.computeProposerIndex(slot, epoch, seed, BigInt(committee.length));
282
+ return committee[Number(proposerIndex)];
283
+ }
284
+
285
+ public getProposerFromEpochCommittee(epochCommitteeInfo: EpochCommitteeInfo, slot: bigint): EthAddress | undefined {
286
+ if (!epochCommitteeInfo.committee || epochCommitteeInfo.committee.length === 0) {
287
+ return undefined;
288
+ }
289
+ const proposerIndex = this.computeProposerIndex(
290
+ slot,
291
+ epochCommitteeInfo.epoch,
292
+ epochCommitteeInfo.seed,
293
+ BigInt(epochCommitteeInfo.committee.length),
294
+ );
295
+
296
+ return epochCommitteeInfo.committee[Number(proposerIndex)];
297
+ }
298
+
299
+ /** Check if a validator is in the given slot's committee */
300
+ async isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean> {
301
+ const { committee } = await this.getCommittee(slot);
302
+ if (!committee) {
303
+ return false;
304
+ }
229
305
  return committee.some(v => v.equals(validator));
230
306
  }
307
+
308
+ /** From the set of given addresses, return all that are on the committee for the given slot */
309
+ async filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]> {
310
+ const { committee } = await this.getCommittee(slot);
311
+ if (!committee) {
312
+ return [];
313
+ }
314
+ const committeeSet = new Set(committee.map(v => v.toString()));
315
+ return validators.filter(v => committeeSet.has(v.toString()));
316
+ }
317
+
318
+ async getRegisteredValidators(): Promise<EthAddress[]> {
319
+ const validatorRefreshIntervalMs = this.config.validatorRefreshIntervalSeconds * 1000;
320
+ const validatorRefreshTime = this.lastValidatorRefresh + validatorRefreshIntervalMs;
321
+ if (validatorRefreshTime < this.dateProvider.now()) {
322
+ const currentSet = await this.rollup.getAttesters();
323
+ this.allValidators = new Set(currentSet);
324
+ this.lastValidatorRefresh = this.dateProvider.now();
325
+ }
326
+ return Array.from(this.allValidators.keys().map(v => EthAddress.fromString(v)));
327
+ }
231
328
  }
@@ -1,2 +0,0 @@
1
- export {};
2
- //# sourceMappingURL=timestamp_provider.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"timestamp_provider.d.ts","sourceRoot":"","sources":["../src/timestamp_provider.ts"],"names":[],"mappings":""}
File without changes
File without changes