@aztec/epoch-cache 0.0.0-test.1 → 0.0.1-commit.017a351

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.
@@ -1,231 +1,587 @@
1
- import { RollupContract, createEthereumChain } from '@aztec/ethereum';
1
+ import { createEthereumChain } from '@aztec/ethereum/chain';
2
+ import { makeL1HttpTransport } from '@aztec/ethereum/client';
3
+ import { NoCommitteeError, RollupContract } from '@aztec/ethereum/contracts';
4
+ import { getFinalizedL1Block } from '@aztec/ethereum/queries';
5
+ import { EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
6
  import { EthAddress } from '@aztec/foundation/eth-address';
3
7
  import { type Logger, createLogger } from '@aztec/foundation/log';
4
8
  import { DateProvider } from '@aztec/foundation/timer';
5
9
  import {
6
- EmptyL1RollupConstants,
7
10
  type L1RollupConstants,
11
+ getEpochAtSlot,
8
12
  getEpochNumberAtTimestamp,
13
+ getNextL1SlotTimestamp,
14
+ getSlotAtNextL1Block,
9
15
  getSlotAtTimestamp,
16
+ getSlotRangeForEpoch,
17
+ getStartTimestampForEpoch,
18
+ getTimestampForSlot,
10
19
  } from '@aztec/stdlib/epoch-helpers';
11
20
 
12
- import { EventEmitter } from 'node:events';
13
- import { createPublicClient, encodeAbiParameters, fallback, http, keccak256 } from 'viem';
21
+ import { createPublicClient, encodeAbiParameters, keccak256 } from 'viem';
14
22
 
15
23
  import { type EpochCacheConfig, getEpochCacheConfigEnvVars } from './config.js';
16
24
 
17
- type EpochAndSlot = {
18
- epoch: bigint;
19
- slot: bigint;
25
+ /** The proposer pipelines by building one slot ahead. */
26
+ export const PROPOSER_PIPELINING_SLOT_OFFSET = 1;
27
+
28
+ /** Flat return type for compound epoch/slot getters. */
29
+ export type EpochAndSlot = {
30
+ slot: SlotNumber;
31
+ epoch: EpochNumber;
20
32
  ts: bigint;
21
33
  };
22
34
 
35
+ export type EpochCommitteeInfo = {
36
+ committee: EthAddress[] | undefined;
37
+ seed: bigint;
38
+ epoch: EpochNumber;
39
+ /** True if the epoch is within an open escape hatch window. */
40
+ isEscapeHatchOpen: boolean;
41
+ };
42
+
43
+ export type SlotTag = 'now' | 'next' | SlotNumber;
44
+
45
+ /** Minimal L1 block info used for cache provenance. */
46
+ type L1BlockInfo = { number: bigint; hash: `0x${string}`; timestamp: bigint };
47
+
48
+ /** Resolved cache entry with L1 provenance metadata. */
49
+ type CachedEpochEntry = {
50
+ data: EpochCommitteeInfo;
51
+ /** L1 block number at which the committee data was originally queried. */
52
+ lastQueryL1BlockNumber: bigint;
53
+ /** L1 block hash at which the committee data was originally queried. Used to detect reorgs. */
54
+ lastQueryL1BlockHash: `0x${string}`;
55
+ /** Latest L1 block timestamp at the time of the most recent refresh (full fetch or lightweight check). */
56
+ lastRefreshL1Timestamp: bigint;
57
+ /** Whether the epoch's sampling data falls within finalized L1 history. */
58
+ finalized: boolean;
59
+ };
60
+
23
61
  export interface EpochCacheInterface {
24
- getCommittee(nextSlot: boolean): Promise<EthAddress[]>;
25
- getEpochAndSlotNow(): EpochAndSlot;
26
- getProposerIndexEncoding(epoch: bigint, slot: bigint, seed: bigint): `0x${string}`;
27
- computeProposerIndex(slot: bigint, epoch: bigint, seed: bigint, size: bigint): bigint;
28
- getProposerInCurrentOrNextSlot(): Promise<{
29
- currentProposer: EthAddress;
30
- nextProposer: EthAddress;
31
- currentSlot: bigint;
32
- nextSlot: bigint;
33
- }>;
34
- isInCommittee(validator: EthAddress): Promise<boolean>;
62
+ getCommittee(slot: SlotTag | undefined): Promise<EpochCommitteeInfo>;
63
+ getSlotNow(): SlotNumber;
64
+ getTargetSlot(): SlotNumber;
65
+ getEpochNow(): EpochNumber;
66
+ getTargetEpoch(): EpochNumber;
67
+ getEpochAndSlotNow(): EpochAndSlot & { nowMs: bigint };
68
+ getEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint };
69
+ /** Returns epoch/slot info for the next L1 slot with pipeline offset applied. */
70
+ getTargetEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint };
71
+ isEscapeHatchOpen(epoch: EpochNumber): Promise<boolean>;
72
+ isEscapeHatchOpenAtSlot(slot: SlotTag): Promise<boolean>;
73
+ getProposerIndexEncoding(epoch: EpochNumber, slot: SlotNumber, seed: bigint): `0x${string}`;
74
+ computeProposerIndex(slot: SlotNumber, epoch: EpochNumber, seed: bigint, size: bigint): bigint;
75
+ getCurrentAndNextSlot(): { currentSlot: SlotNumber; nextSlot: SlotNumber };
76
+ getTargetAndNextSlot(): { targetSlot: SlotNumber; nextSlot: SlotNumber };
77
+ getProposerAttesterAddressInSlot(slot: SlotNumber): Promise<EthAddress | undefined>;
78
+ getRegisteredValidators(): Promise<EthAddress[]>;
79
+ isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean>;
80
+ filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]>;
81
+ getL1Constants(): L1RollupConstants;
35
82
  }
36
83
 
37
84
  /**
38
85
  * Epoch cache
39
86
  *
40
87
  * This class is responsible for managing traffic to the l1 node, by caching the validator set.
88
+ * Keeps the last N epochs in cache.
41
89
  * It also provides a method to get the current or next proposer, and to check who is in the current slot.
42
90
  *
43
- * If the epoch changes, then we update the stored validator set.
44
- *
45
91
  * Note: This class is very dependent on the system clock being in sync.
46
92
  */
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;
93
+ export class EpochCache implements EpochCacheInterface {
94
+ /**
95
+ * Single map holding both resolved entries and in-flight promises.
96
+ * A `Promise` value means a fetch is in progress; concurrent callers await it.
97
+ */
98
+ protected cache: Map<EpochNumber, CachedEpochEntry | Promise<CachedEpochEntry>> = new Map();
99
+ private allValidators: Set<string> = new Set();
100
+ private lastValidatorRefresh = 0;
54
101
  private readonly log: Logger = createLogger('epoch-cache');
55
102
 
56
103
  constructor(
57
104
  private rollup: RollupContract,
58
- initialValidators: EthAddress[] = [],
59
- initialSampleSeed: bigint = 0n,
60
- private readonly l1constants: L1RollupConstants = EmptyL1RollupConstants,
105
+ private readonly l1constants: L1RollupConstants & {
106
+ lagInEpochsForValidatorSet: number;
107
+ lagInEpochsForRandao: number;
108
+ },
61
109
  private readonly dateProvider: DateProvider = new DateProvider(),
110
+ protected readonly config = { cacheSize: 12, validatorRefreshIntervalSeconds: 60 },
62
111
  ) {
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);
112
+ this.log.debug(`Initialized EpochCache`, {
113
+ l1constants,
114
+ });
70
115
  }
71
116
 
72
117
  static async create(
73
- rollupAddress: EthAddress,
118
+ rollupOrAddress: EthAddress | RollupContract,
74
119
  config?: EpochCacheConfig,
75
120
  deps: { dateProvider?: DateProvider } = {},
76
121
  ) {
77
122
  config = config ?? getEpochCacheConfigEnvVars();
78
123
 
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
- });
124
+ // Load the rollup contract if we were given an address
125
+ let rollup: RollupContract;
126
+ if ('address' in rollupOrAddress) {
127
+ rollup = rollupOrAddress;
128
+ } else {
129
+ const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
130
+ const publicClient = createPublicClient({
131
+ chain: chain.chainInfo,
132
+ transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
133
+ pollingInterval: config.viemPollingIntervalMS,
134
+ });
135
+ rollup = new RollupContract(publicClient, rollupOrAddress.toString());
136
+ }
85
137
 
86
- const rollup = new RollupContract(publicClient, rollupAddress.toString());
87
- const [l1StartBlock, l1GenesisTime, initialValidators, sampleSeed] = await Promise.all([
138
+ const [
139
+ l1StartBlock,
140
+ l1GenesisTime,
141
+ proofSubmissionEpochs,
142
+ slotDuration,
143
+ epochDuration,
144
+ lagInEpochsForValidatorSet,
145
+ lagInEpochsForRandao,
146
+ targetCommitteeSize,
147
+ rollupManaLimit,
148
+ ] = await Promise.all([
88
149
  rollup.getL1StartBlock(),
89
150
  rollup.getL1GenesisTime(),
90
- rollup.getCurrentEpochCommittee(),
91
- rollup.getCurrentSampleSeed(),
151
+ rollup.getProofSubmissionEpochs(),
152
+ rollup.getSlotDuration(),
153
+ rollup.getEpochDuration(),
154
+ rollup.getLagInEpochsForValidatorSet(),
155
+ rollup.getLagInEpochsForRandao(),
156
+ rollup.getTargetCommitteeSize(),
157
+ rollup.getManaLimit(),
92
158
  ] as const);
93
159
 
94
- const l1RollupConstants: L1RollupConstants = {
160
+ const l1RollupConstants = {
95
161
  l1StartBlock,
96
162
  l1GenesisTime,
97
- slotDuration: config.aztecSlotDuration,
98
- epochDuration: config.aztecEpochDuration,
163
+ proofSubmissionEpochs: Number(proofSubmissionEpochs),
164
+ slotDuration: Number(slotDuration),
165
+ epochDuration: Number(epochDuration),
99
166
  ethereumSlotDuration: config.ethereumSlotDuration,
167
+ lagInEpochsForValidatorSet: Number(lagInEpochsForValidatorSet),
168
+ lagInEpochsForRandao: Number(lagInEpochsForRandao),
169
+ targetCommitteeSize: Number(targetCommitteeSize),
170
+ rollupManaLimit: Number(rollupManaLimit),
100
171
  };
101
172
 
102
- return new EpochCache(
103
- rollup,
104
- initialValidators.map(v => EthAddress.fromString(v)),
105
- sampleSeed,
106
- l1RollupConstants,
107
- deps.dateProvider,
108
- );
173
+ return new EpochCache(rollup, l1RollupConstants, deps.dateProvider, {
174
+ cacheSize: 12,
175
+ validatorRefreshIntervalSeconds: 60,
176
+ });
177
+ }
178
+
179
+ public getL1Constants(): L1RollupConstants {
180
+ return this.l1constants;
181
+ }
182
+
183
+ public getSlotNow(): SlotNumber {
184
+ return this.getEpochAndSlotNow().slot;
185
+ }
186
+
187
+ public getTargetSlot(): SlotNumber {
188
+ const slotNow = this.getSlotNow();
189
+ const offset = PROPOSER_PIPELINING_SLOT_OFFSET;
190
+ return SlotNumber(slotNow + offset);
191
+ }
192
+
193
+ public getEpochNow(): EpochNumber {
194
+ return this.getEpochAndSlotNow().epoch;
195
+ }
196
+
197
+ public getTargetEpoch(): EpochNumber {
198
+ return getEpochAtSlot(this.getTargetSlot(), this.l1constants);
199
+ }
200
+
201
+ public getEpochAndSlotNow(): EpochAndSlot & { nowMs: bigint } {
202
+ const nowMs = BigInt(this.dateProvider.now());
203
+ const nowSeconds = nowMs / 1000n;
204
+ return { ...this.getEpochAndSlotAtTimestamp(nowSeconds), nowMs };
109
205
  }
110
206
 
111
- private nowInSeconds(): bigint {
112
- return BigInt(Math.floor(this.dateProvider.now() / 1000));
207
+ private getEpochAndSlotAtSlot(slot: SlotNumber): EpochAndSlot {
208
+ return this.getEpochAndSlotAtTimestamp(getTimestampForSlot(slot, this.l1constants));
113
209
  }
114
210
 
115
- getEpochAndSlotNow(): EpochAndSlot {
116
- return this.getEpochAndSlotAtTimestamp(this.nowInSeconds());
211
+ public getEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint } {
212
+ const nowSeconds = this.dateProvider.nowInSeconds();
213
+ const nextSlotTs = getNextL1SlotTimestamp(nowSeconds, this.l1constants);
214
+ return { ...this.getEpochAndSlotAtTimestamp(nextSlotTs), nowSeconds: BigInt(nowSeconds) };
117
215
  }
118
216
 
119
- private getEpochAndSlotInNextSlot(): EpochAndSlot {
120
- const nextSlotTs = this.nowInSeconds() + BigInt(this.l1constants.slotDuration);
121
- return this.getEpochAndSlotAtTimestamp(nextSlotTs);
217
+ public getTargetEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint } {
218
+ const result = this.getEpochAndSlotInNextL1Slot();
219
+ const offset = PROPOSER_PIPELINING_SLOT_OFFSET;
220
+ const targetSlot = SlotNumber(result.slot + offset);
221
+ return { ...result, slot: targetSlot, epoch: getEpochAtSlot(targetSlot, this.l1constants) };
122
222
  }
123
223
 
124
224
  private getEpochAndSlotAtTimestamp(ts: bigint): EpochAndSlot {
225
+ const slot = getSlotAtTimestamp(ts, this.l1constants);
226
+ const epoch = getEpochNumberAtTimestamp(ts, this.l1constants);
125
227
  return {
126
- epoch: getEpochNumberAtTimestamp(ts, this.l1constants),
127
- slot: getSlotAtTimestamp(ts, this.l1constants),
128
- ts,
228
+ slot,
229
+ epoch,
230
+ ts: getTimestampForSlot(slot, this.l1constants),
129
231
  };
130
232
  }
131
233
 
234
+ public getCommitteeForEpoch(epoch: EpochNumber): Promise<EpochCommitteeInfo> {
235
+ const [startSlot] = getSlotRangeForEpoch(epoch, this.l1constants);
236
+ return this.getCommittee(startSlot);
237
+ }
238
+
239
+ /** Returns whether the escape hatch is open for the given epoch. */
240
+ public async isEscapeHatchOpen(epoch: EpochNumber): Promise<boolean> {
241
+ const info = await this.getCommitteeForEpoch(epoch);
242
+ return info.isEscapeHatchOpen;
243
+ }
244
+
132
245
  /**
133
- * Get the current validator set
246
+ * Returns whether the escape hatch is open for the epoch containing the given slot.
134
247
  *
135
- * @param nextSlot - If true, get the validator set for the next slot.
136
- * @returns The current validator set.
248
+ * This is a lightweight helper intended for callers that already have a slot number and only
249
+ * need the escape hatch flag (without pulling full committee info).
137
250
  */
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);
251
+ public async isEscapeHatchOpenAtSlot(slot: SlotTag = 'now'): Promise<boolean> {
252
+ const epoch =
253
+ slot === 'now'
254
+ ? this.getEpochNow()
255
+ : slot === 'next'
256
+ ? this.getEpochAndSlotInNextL1Slot().epoch
257
+ : getEpochAtSlot(slot, this.l1constants);
258
+
259
+ return await this.isEscapeHatchOpen(epoch);
260
+ }
261
+
262
+ /**
263
+ * Get the current validator set.
264
+ *
265
+ * Returns cached data if the entry is finalized or still fresh (queried less than one
266
+ * Ethereum slot ago). Stale non-finalized entries are re-queried, and concurrent callers
267
+ * coalesce on the same in-flight promise so the L1 query happens only once.
268
+ */
269
+ public async getCommittee(slot: SlotTag = 'now'): Promise<EpochCommitteeInfo> {
270
+ const { epoch, ts } = this.getEpochAndTimestamp(slot);
271
+
272
+ const cached = this.cache.get(epoch);
273
+
274
+ // In-flight promise: another caller is already fetching this epoch — just await it.
275
+ if (cached instanceof Promise) {
276
+ return (await cached).data;
277
+ }
278
+
279
+ // Resolved entry: return it if finalized or still fresh.
280
+ if (cached && (cached.finalized || !this.isStale(cached))) {
281
+ return cached.data;
282
+ }
283
+
284
+ // Stale non-finalized entry: do a lightweight refresh first (check block hash + finalized ts).
285
+ // Only fall back to a full re-fetch if the L1 block was reorged.
286
+ if (cached) {
287
+ const promise = this.refreshStaleEntry(cached, epoch, ts);
288
+ this.cache.set(epoch, promise);
289
+ try {
290
+ return (await promise).data;
291
+ } catch (err) {
292
+ this.cache.set(epoch, cached);
293
+ throw err;
294
+ }
295
+ }
296
+
297
+ // No entry at all: full fetch.
298
+ const promise = this.fetchAndCache(epoch, ts);
299
+ this.cache.set(epoch, promise);
300
+ try {
301
+ return (await promise).data;
302
+ } catch (err) {
303
+ this.cache.delete(epoch);
304
+ throw err;
305
+ }
306
+ }
307
+
308
+ private getEpochAndTimestamp(slot: SlotTag = 'now'): { epoch: EpochNumber; ts: bigint } {
309
+ if (slot === 'now') {
310
+ return this.getEpochAndSlotNow();
311
+ } else if (slot === 'next') {
312
+ return this.getEpochAndSlotInNextL1Slot();
313
+ } else {
314
+ return this.getEpochAndSlotAtSlot(slot);
315
+ }
316
+ }
317
+
318
+ /** Evicts oldest cache entries (resolved or in-flight) beyond cacheSize. */
319
+ private purgeCache(): void {
320
+ if (this.cache.size <= this.config.cacheSize) {
321
+ return;
322
+ }
323
+ const toPurge = Array.from(this.cache.keys())
324
+ .sort((a, b) => Number(b - a))
325
+ .slice(this.config.cacheSize);
326
+ toPurge.forEach(key => this.cache.delete(key));
327
+ }
328
+
329
+ /** Returns true if a non-finalized cache entry is older than one Ethereum slot. */
330
+ private isStale(entry: CachedEpochEntry): boolean {
331
+ const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
332
+ return nowSeconds - entry.lastRefreshL1Timestamp >= BigInt(this.l1constants.ethereumSlotDuration);
333
+ }
334
+
335
+ /** Whether a cached epoch entry has been marked as finalized. Returns undefined if not cached or still in-flight. */
336
+ public isFinalized(epoch: EpochNumber): boolean | undefined {
337
+ const entry = this.cache.get(epoch);
338
+ if (!entry || entry instanceof Promise) {
339
+ return undefined;
340
+ }
341
+ return entry.finalized;
342
+ }
343
+
344
+ /** Returns the latest L1 timestamp stored in the cached entry. Undefined if not cached or in-flight. */
345
+ public getCachedLastRefreshL1Timestamp(epoch: EpochNumber): bigint | undefined {
346
+ const entry = this.cache.get(epoch);
347
+ if (!entry || entry instanceof Promise) {
348
+ return undefined;
349
+ }
350
+ return entry.lastRefreshL1Timestamp;
351
+ }
352
+
353
+ /** Computes the sampling timestamp for an epoch's committee data. */
354
+ private getSamplingTimestamp(epoch: EpochNumber): bigint {
355
+ const { lagInEpochsForRandao, epochDuration, slotDuration } = this.l1constants;
356
+ const epochStartTs = getStartTimestampForEpoch(epoch, this.l1constants);
357
+ return epochStartTs - BigInt(lagInEpochsForRandao) * BigInt(epochDuration) * BigInt(slotDuration);
358
+ }
359
+
360
+ /**
361
+ * Lightweight refresh for a stale non-finalized entry. Queries only the block hash at
362
+ * the original block number and the finalized block timestamp — avoids the expensive
363
+ * getCommitteeAt and getSampleSeedAt calls on the rollup contract.
364
+ *
365
+ * If the block hash still matches (no L1 reorg), we keep the existing data and just
366
+ * update the provenance timestamp. If the finalized block has caught up, we promote the
367
+ * entry to finalized. If there was a reorg (hash mismatch), we fall back to a full fetch.
368
+ */
369
+ private async refreshStaleEntry(stale: CachedEpochEntry, epoch: EpochNumber, ts: bigint): Promise<CachedEpochEntry> {
370
+ const [blockAtOriginal, l1FinalizedBlock, latestBlock] = await Promise.all([
371
+ this.rollup.client.getBlock({ blockNumber: stale.lastQueryL1BlockNumber, includeTransactions: false }),
372
+ getFinalizedL1Block(this.rollup.client),
373
+ this.rollup.client.getBlock({ includeTransactions: false }),
374
+ ]);
375
+
376
+ if (blockAtOriginal.hash === stale.lastQueryL1BlockHash) {
377
+ // No reorg: the data is still valid. Check if we can now mark it as finalized.
378
+ const samplingTs = this.getSamplingTimestamp(epoch);
379
+ const finalized =
380
+ !!(stale.data.committee && stale.data.committee.length > 0) &&
381
+ l1FinalizedBlock !== undefined &&
382
+ samplingTs <= l1FinalizedBlock.timestamp;
383
+
384
+ const refreshed: CachedEpochEntry = {
385
+ ...stale,
386
+ lastRefreshL1Timestamp: latestBlock.timestamp,
387
+ finalized,
388
+ };
389
+ this.cache.set(epoch, refreshed);
390
+ return refreshed;
391
+ }
392
+
393
+ // Reorg detected: block hash mismatch. Do a full re-fetch.
394
+ // Pass the already-fetched block timestamps to avoid redundant queries.
395
+ this.log.warn(`L1 reorg detected for epoch ${epoch}: block ${stale.lastQueryL1BlockNumber} hash changed`, {
396
+ epoch,
397
+ expectedHash: stale.lastQueryL1BlockHash,
398
+ actualHash: blockAtOriginal.hash,
399
+ });
400
+ return this.fetchAndCache(epoch, ts, { latestBlock, finalizedBlock: l1FinalizedBlock });
401
+ }
402
+
403
+ /**
404
+ * Fetches committee data from L1, determines finalization status, and stores in the cache.
405
+ *
406
+ * Uses `lagInEpochsForRandao` (the binding constraint, always <= lagInEpochsForValidatorSet)
407
+ * and computes the sampling timestamp from the epoch start to match the L1 contract's logic.
408
+ *
409
+ * When called from refreshStaleEntry after a reorg, the latest and finalized blocks are
410
+ * passed in to avoid redundant L1 queries.
411
+ */
412
+ private async fetchAndCache(
413
+ epoch: EpochNumber,
414
+ ts: bigint,
415
+ prefetched?: { latestBlock: L1BlockInfo; finalizedBlock: { timestamp: bigint } | undefined },
416
+ ): Promise<CachedEpochEntry> {
417
+ const [committee, seedBuffer, latestBlock, finalizedBlock, isEscapeHatchOpen] = await Promise.all([
418
+ this.rollup.getCommitteeAt(ts),
419
+ this.rollup.getSampleSeedAt(ts),
420
+ prefetched?.latestBlock ?? this.rollup.client.getBlock({ includeTransactions: false }),
421
+ prefetched !== undefined ? prefetched.finalizedBlock : getFinalizedL1Block(this.rollup.client),
422
+ this.rollup.isEscapeHatchOpen(epoch),
423
+ ]);
424
+
425
+ const samplingTs = this.getSamplingTimestamp(epoch);
426
+
427
+ if (samplingTs > latestBlock.timestamp) {
428
+ throw new Error(
429
+ `Cannot query committee for future epoch ${epoch}: ` +
430
+ `sampling timestamp ${samplingTs} is beyond latest L1 block at ${latestBlock.timestamp}. ` +
431
+ `Check your Ethereum node is synced.`,
432
+ );
156
433
  }
157
434
 
158
- return this.committee;
435
+ // Empty committees are never marked finalized so they always get re-queried after TTL.
436
+ // If L1 has no finalized block yet (devnet startup), entries stay unfinalized.
437
+ const hasCommittee = !!(committee && committee.length > 0);
438
+ const finalized = hasCommittee && finalizedBlock !== undefined && samplingTs <= finalizedBlock.timestamp;
439
+ const data: EpochCommitteeInfo = { committee, seed: seedBuffer.toBigInt(), epoch, isEscapeHatchOpen };
440
+ const entry: CachedEpochEntry = {
441
+ data,
442
+ lastQueryL1BlockNumber: latestBlock.number!,
443
+ lastQueryL1BlockHash: latestBlock.hash!,
444
+ lastRefreshL1Timestamp: latestBlock.timestamp,
445
+ finalized,
446
+ };
447
+
448
+ this.cache.set(epoch, entry);
449
+ this.purgeCache();
450
+
451
+ return entry;
159
452
  }
160
453
 
161
454
  /**
162
455
  * Get the ABI encoding of the proposer index - see ValidatorSelectionLib.sol computeProposerIndex
163
456
  */
164
- getProposerIndexEncoding(epoch: bigint, slot: bigint, seed: bigint): `0x${string}` {
457
+ getProposerIndexEncoding(epoch: EpochNumber, slot: SlotNumber, seed: bigint): `0x${string}` {
165
458
  return encodeAbiParameters(
166
459
  [
167
460
  { type: 'uint256', name: 'epoch' },
168
461
  { type: 'uint256', name: 'slot' },
169
462
  { type: 'uint256', name: 'seed' },
170
463
  ],
171
- [epoch, slot, seed],
464
+ [BigInt(epoch), BigInt(slot), seed],
172
465
  );
173
466
  }
174
467
 
175
- computeProposerIndex(slot: bigint, epoch: bigint, seed: bigint, size: bigint): bigint {
468
+ public computeProposerIndex(slot: SlotNumber, epoch: EpochNumber, seed: bigint, size: bigint): bigint {
469
+ // if committe size is 0, then mod 1 is 0
470
+ if (size === 0n) {
471
+ return 0n;
472
+ }
176
473
  return BigInt(keccak256(this.getProposerIndexEncoding(epoch, slot, seed))) % size;
177
474
  }
178
475
 
179
- /**
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.
184
- *
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.
187
- */
188
- async getProposerInCurrentOrNextSlot(): Promise<{
189
- currentProposer: EthAddress;
190
- nextProposer: EthAddress;
191
- currentSlot: bigint;
192
- nextSlot: bigint;
193
- }> {
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();
198
-
199
- // Compute the proposer in this and the next slot
200
- const proposerIndex = this.computeProposerIndex(
476
+ /** Returns the current and next L2 slot in next eth L1 Slot. */
477
+ public getCurrentAndNextSlot(): { currentSlot: SlotNumber; nextSlot: SlotNumber } {
478
+ const currentSlot = this.getSlotNow();
479
+ const next = this.getEpochAndSlotInNextL1Slot();
480
+
481
+ return {
201
482
  currentSlot,
202
- this.cachedEpoch,
203
- this.cachedSampleSeed,
204
- BigInt(committee.length),
205
- );
483
+ nextSlot: next.slot,
484
+ };
485
+ }
206
486
 
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
- );
487
+ /** Returns the target and next L2 slot in the next L1 slot. */
488
+ public getTargetAndNextSlot(): { targetSlot: SlotNumber; nextSlot: SlotNumber } {
489
+ const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
490
+ const offset = PROPOSER_PIPELINING_SLOT_OFFSET;
491
+
492
+ const currentSlot = getSlotAtTimestamp(nowSeconds, this.l1constants);
493
+ const targetSlot = SlotNumber(currentSlot + offset);
494
+
495
+ const nextL2SlotOnL1 = getSlotAtNextL1Block(nowSeconds, this.l1constants);
496
+ const nextSlot = SlotNumber(nextL2SlotOnL1 + offset);
217
497
 
218
- const currentProposer = committee[Number(proposerIndex)];
219
- const nextProposer = committee[Number(nextProposerIndex)];
498
+ return { targetSlot, nextSlot };
499
+ }
500
+
501
+ /**
502
+ * Get the proposer attester address in the given L2 slot
503
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
504
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
505
+ */
506
+ public getProposerAttesterAddressInSlot(slot: SlotNumber): Promise<EthAddress | undefined> {
507
+ const epochAndSlot = this.getEpochAndSlotAtSlot(slot);
508
+ return this.getProposerAttesterAddressAt(epochAndSlot);
509
+ }
220
510
 
221
- return { currentProposer, nextProposer, currentSlot, nextSlot };
511
+ /**
512
+ * Get the proposer attester address in the next slot
513
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
514
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
515
+ */
516
+ public getProposerAttesterAddressInNextSlot(): Promise<EthAddress | undefined> {
517
+ const epochAndSlot = this.getEpochAndSlotInNextL1Slot();
518
+ return this.getProposerAttesterAddressAt(epochAndSlot);
222
519
  }
223
520
 
224
521
  /**
225
- * Check if a validator is in the current epoch's committee
522
+ * Get the proposer attester address at a given epoch and slot
523
+ * @param when - The epoch and slot to get the proposer attester address at
524
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
525
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
226
526
  */
227
- async isInCommittee(validator: EthAddress): Promise<boolean> {
228
- const committee = await this.getCommittee();
527
+ private async getProposerAttesterAddressAt(when: EpochAndSlot) {
528
+ const { epoch, slot } = when;
529
+ const { committee, seed } = await this.getCommittee(slot);
530
+ if (!committee) {
531
+ throw new NoCommitteeError();
532
+ } else if (committee.length === 0) {
533
+ return undefined;
534
+ }
535
+
536
+ const proposerIndex = this.computeProposerIndex(slot, epoch, seed, BigInt(committee.length));
537
+ return committee[Number(proposerIndex)];
538
+ }
539
+
540
+ public getProposerFromEpochCommittee(
541
+ epochCommitteeInfo: EpochCommitteeInfo,
542
+ slot: SlotNumber,
543
+ ): EthAddress | undefined {
544
+ if (!epochCommitteeInfo.committee || epochCommitteeInfo.committee.length === 0) {
545
+ return undefined;
546
+ }
547
+ const proposerIndex = this.computeProposerIndex(
548
+ slot,
549
+ epochCommitteeInfo.epoch,
550
+ epochCommitteeInfo.seed,
551
+ BigInt(epochCommitteeInfo.committee.length),
552
+ );
553
+
554
+ return epochCommitteeInfo.committee[Number(proposerIndex)];
555
+ }
556
+
557
+ /** Check if a validator is in the given slot's committee */
558
+ async isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean> {
559
+ const { committee } = await this.getCommittee(slot);
560
+ if (!committee) {
561
+ return false;
562
+ }
229
563
  return committee.some(v => v.equals(validator));
230
564
  }
565
+
566
+ /** From the set of given addresses, return all that are on the committee for the given slot */
567
+ async filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]> {
568
+ const { committee } = await this.getCommittee(slot);
569
+ if (!committee) {
570
+ return [];
571
+ }
572
+ const committeeSet = new Set(committee.map(v => v.toString()));
573
+ return validators.filter(v => committeeSet.has(v.toString()));
574
+ }
575
+
576
+ async getRegisteredValidators(): Promise<EthAddress[]> {
577
+ const validatorRefreshIntervalMs = this.config.validatorRefreshIntervalSeconds * 1000;
578
+ const validatorRefreshTime = this.lastValidatorRefresh + validatorRefreshIntervalMs;
579
+ const now = this.dateProvider.now();
580
+ if (validatorRefreshTime < now) {
581
+ const currentSet = await this.rollup.getAttesters(BigInt(Math.floor(now / 1000)));
582
+ this.allValidators = new Set(currentSet.map(v => v.toString()));
583
+ this.lastValidatorRefresh = now;
584
+ }
585
+ return Array.from(this.allValidators.keys()).map(v => EthAddress.fromString(v));
586
+ }
231
587
  }