@aztec-labs/epoch-cache 6.0.0-rc.3 → 6.0.0

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,7 +1,8 @@
1
1
  import { createEthereumChain } from '@aztec-labs/ethereum/chain';
2
2
  import { makeL1HttpTransport } from '@aztec-labs/ethereum/client';
3
- import { NoCommitteeError, RollupContract } from '@aztec-labs/ethereum/contracts';
3
+ import { RollupContract, isEpochNotStableError } from '@aztec-labs/ethereum/contracts';
4
4
  import { getFinalizedL1Block } from '@aztec-labs/ethereum/queries';
5
+ import { maxBigint } from '@aztec-labs/foundation/bigint';
5
6
  import { EpochNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
6
7
  import { EthAddress } from '@aztec-labs/foundation/eth-address';
7
8
  import { type Logger, createLogger } from '@aztec-labs/foundation/log';
@@ -14,11 +15,20 @@ import {
14
15
  getSlotAtNextL1Block,
15
16
  getSlotAtTimestamp,
16
17
  getSlotRangeForEpoch,
17
- getStartTimestampForEpoch,
18
18
  getTimestampForSlot,
19
+ getTimestampRangeForEpoch,
19
20
  } from '@aztec-labs/stdlib/epoch-helpers';
20
21
  import { createPublicClient, encodeAbiParameters, keccak256 } from 'viem';
21
22
 
23
+ import {
24
+ type CommitteeLookup,
25
+ type CommitteeMembershipLookup,
26
+ type EscapeHatchLookup,
27
+ type KnownCommitteeLookup,
28
+ type ProposerLookup,
29
+ toCommitteeLookup,
30
+ withoutMembers,
31
+ } from './committee_lookup.js';
22
32
  import { type EpochCacheConfig, getEpochCacheConfigEnvVars } from './config.js';
23
33
 
24
34
  /** The proposer pipelines by building one slot ahead. */
@@ -31,34 +41,39 @@ export type EpochAndSlot = {
31
41
  ts: bigint;
32
42
  };
33
43
 
34
- export type EpochCommitteeInfo = {
35
- committee: EthAddress[] | undefined;
36
- seed: bigint;
37
- epoch: EpochNumber;
38
- /** True if the epoch is within an open escape hatch window. */
39
- isEscapeHatchOpen: boolean;
40
- };
41
-
42
44
  export type SlotTag = 'now' | 'next' | SlotNumber;
43
45
 
44
46
  /** Minimal L1 block info used for cache provenance. */
45
47
  type L1BlockInfo = { number: bigint; hash: `0x${string}`; timestamp: bigint };
46
48
 
47
- /** Resolved cache entry with L1 provenance metadata. */
49
+ /** Resolved cache entry for an epoch whose seed is fixed on L1, with L1 provenance metadata. */
48
50
  type CachedEpochEntry = {
49
- data: EpochCommitteeInfo;
51
+ kind: 'committee';
52
+ data: KnownCommitteeLookup;
50
53
  /** L1 block number at which the committee data was originally queried. */
51
54
  lastQueryL1BlockNumber: bigint;
52
55
  /** L1 block hash at which the committee data was originally queried. Used to detect reorgs. */
53
56
  lastQueryL1BlockHash: `0x${string}`;
54
57
  /** Latest L1 block timestamp at the time of the most recent refresh (full fetch or lightweight check). */
55
58
  lastRefreshL1Timestamp: bigint;
56
- /** Whether the epoch's sampling data falls within finalized L1 history. */
59
+ /** Whether the L1 block the entry was read at is finalized. */
57
60
  finalized: boolean;
58
61
  };
59
62
 
63
+ /** Marker for an epoch whose seed could still change as of an L1 block. Re-checked against L1 once it expires. */
64
+ type UnstableEpochEntry = {
65
+ kind: 'unstable';
66
+ /** L1 block at which the seed was found not to be fixed yet. */
67
+ l1BlockNumber: bigint;
68
+ /** The later of that block's timestamp and the check's local time, so a lagging L1 tip is not re-checked early. */
69
+ lastRefreshL1Timestamp: bigint;
70
+ };
71
+
72
+ type EpochEntry = CachedEpochEntry | UnstableEpochEntry;
73
+
60
74
  export interface EpochCacheInterface {
61
- getCommittee(slot: SlotTag | undefined): Promise<EpochCommitteeInfo>;
75
+ /** Looks up the committee of the epoch containing the given slot. */
76
+ getCommittee(slot: SlotTag | undefined): Promise<CommitteeLookup>;
62
77
  getSlotNow(): SlotNumber;
63
78
  getTargetSlot(): SlotNumber;
64
79
  getEpochNow(): EpochNumber;
@@ -67,16 +82,21 @@ export interface EpochCacheInterface {
67
82
  getEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint };
68
83
  /** Returns epoch/slot info for the next L1 slot with pipeline offset applied. */
69
84
  getTargetEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint };
70
- isEscapeHatchOpen(epoch: EpochNumber): Promise<boolean>;
71
- isEscapeHatchOpenAtSlot(slot: SlotTag): Promise<boolean>;
85
+ /** Looks up whether the escape hatch is open for the given epoch. */
86
+ lookupEscapeHatch(epoch: EpochNumber): Promise<EscapeHatchLookup>;
87
+ /** Looks up whether the escape hatch is open for the epoch containing the given slot. */
88
+ lookupEscapeHatchAtSlot(slot: SlotTag): Promise<EscapeHatchLookup>;
72
89
  getProposerIndexEncoding(epoch: EpochNumber, slot: SlotNumber, seed: bigint): `0x${string}`;
73
90
  computeProposerIndex(slot: SlotNumber, epoch: EpochNumber, seed: bigint, size: bigint): bigint;
74
91
  getCurrentAndNextSlot(): { currentSlot: SlotNumber; nextSlot: SlotNumber };
75
92
  getTargetAndNextSlot(): { targetSlot: SlotNumber; nextSlot: SlotNumber };
76
- getProposerAttesterAddressInSlot(slot: SlotNumber): Promise<EthAddress | undefined>;
93
+ /** Looks up the proposer for the given slot. */
94
+ lookupProposer(slot: SlotNumber): Promise<ProposerLookup>;
77
95
  getRegisteredValidators(): Promise<EthAddress[]>;
78
- isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean>;
79
- filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]>;
96
+ /** Looks up whether a validator sits on the given slot's committee. */
97
+ lookupMembership(slot: SlotTag, validator: EthAddress): Promise<CommitteeMembershipLookup<boolean>>;
98
+ /** Looks up which of the given validators sit on the given slot's committee. */
99
+ filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<CommitteeMembershipLookup<EthAddress[]>>;
80
100
  getL1Constants(): L1RollupConstants;
81
101
  getLagInEpochsForValidatorSet(): number;
82
102
  }
@@ -95,7 +115,7 @@ export class EpochCache implements EpochCacheInterface {
95
115
  * Single map holding both resolved entries and in-flight promises.
96
116
  * A `Promise` value means a fetch is in progress; concurrent callers await it.
97
117
  */
98
- protected cache: Map<EpochNumber, CachedEpochEntry | Promise<CachedEpochEntry>> = new Map();
118
+ protected cache: Map<EpochNumber, EpochEntry | Promise<EpochEntry>> = new Map();
99
119
  private allValidators: Set<string> = new Set();
100
120
  private lastValidatorRefresh = 0;
101
121
  private readonly log: Logger = createLogger('epoch-cache');
@@ -241,15 +261,15 @@ export class EpochCache implements EpochCacheInterface {
241
261
  };
242
262
  }
243
263
 
244
- public getCommitteeForEpoch(epoch: EpochNumber): Promise<EpochCommitteeInfo> {
264
+ public getCommitteeForEpoch(epoch: EpochNumber): Promise<CommitteeLookup> {
245
265
  const [startSlot] = getSlotRangeForEpoch(epoch, this.l1constants);
246
266
  return this.getCommittee(startSlot);
247
267
  }
248
268
 
249
269
  /** Returns whether the escape hatch is open for the given epoch. */
250
- public async isEscapeHatchOpen(epoch: EpochNumber): Promise<boolean> {
251
- const info = await this.getCommitteeForEpoch(epoch);
252
- return info.isEscapeHatchOpen;
270
+ public async lookupEscapeHatch(epoch: EpochNumber): Promise<EscapeHatchLookup> {
271
+ const lookup = await this.getCommitteeForEpoch(epoch);
272
+ return lookup.state === 'unstable' ? lookup : { state: lookup.state, isEscapeHatchOpen: lookup.isEscapeHatchOpen };
253
273
  }
254
274
 
255
275
  /**
@@ -258,7 +278,7 @@ export class EpochCache implements EpochCacheInterface {
258
278
  * This is a lightweight helper intended for callers that already have a slot number and only
259
279
  * need the escape hatch flag (without pulling full committee info).
260
280
  */
261
- public async isEscapeHatchOpenAtSlot(slot: SlotTag = 'now'): Promise<boolean> {
281
+ public async lookupEscapeHatchAtSlot(slot: SlotTag = 'now'): Promise<EscapeHatchLookup> {
262
282
  const epoch =
263
283
  slot === 'now'
264
284
  ? this.getEpochNow()
@@ -266,7 +286,7 @@ export class EpochCache implements EpochCacheInterface {
266
286
  ? this.getEpochAndSlotInNextL1Slot().epoch
267
287
  : getEpochAtSlot(slot, this.l1constants);
268
288
 
269
- return await this.isEscapeHatchOpen(epoch);
289
+ return await this.lookupEscapeHatch(epoch);
270
290
  }
271
291
 
272
292
  /**
@@ -275,42 +295,44 @@ export class EpochCache implements EpochCacheInterface {
275
295
  * Returns cached data if the entry is finalized or still fresh (queried less than one
276
296
  * Ethereum slot ago). Stale non-finalized entries are re-queried, and concurrent callers
277
297
  * coalesce on the same in-flight promise so the L1 query happens only once.
298
+ *
299
+ * Returns `unstable` while the epoch's sample seed can still change on L1. Callers should treat that as "not known
300
+ * yet": the same query returns the committee once the seed is fixed.
278
301
  */
279
- public async getCommittee(slot: SlotTag = 'now'): Promise<EpochCommitteeInfo> {
302
+ public async getCommittee(slot: SlotTag = 'now'): Promise<CommitteeLookup> {
280
303
  const { epoch, ts } = this.getEpochAndTimestamp(slot);
304
+ const entry = await this.getEntry(epoch, ts);
305
+ if (entry.kind === 'unstable') {
306
+ return { state: 'unstable', epoch, l1BlockNumber: entry.l1BlockNumber };
307
+ }
308
+ return entry.data;
309
+ }
281
310
 
311
+ /** Returns the cached entry for an epoch, awaits the in-flight fetch for it, or starts a new one. */
312
+ private async getEntry(epoch: EpochNumber, ts: bigint): Promise<EpochEntry> {
282
313
  const cached = this.cache.get(epoch);
283
314
 
284
315
  // In-flight promise: another caller is already fetching this epoch — just await it.
285
316
  if (cached instanceof Promise) {
286
- return (await cached).data;
317
+ return cached;
287
318
  }
288
319
 
289
320
  // Resolved entry: return it if finalized or still fresh.
290
- if (cached && (cached.finalized || !this.isStale(cached))) {
291
- return cached.data;
321
+ if (cached && ((cached.kind === 'committee' && cached.finalized) || !this.isStale(cached))) {
322
+ return cached;
292
323
  }
293
324
 
294
- // Stale non-finalized entry: do a lightweight refresh first (check block hash + finalized ts).
295
- // Only fall back to a full re-fetch if the L1 block was reorged.
296
- if (cached) {
297
- const promise = this.refreshStaleEntry(cached, epoch, ts);
298
- this.cache.set(epoch, promise);
299
- try {
300
- return (await promise).data;
301
- } catch (err) {
302
- this.cache.set(epoch, cached);
303
- throw err;
304
- }
305
- }
306
-
307
- // No entry at all: full fetch.
308
- const promise = this.fetchAndCache(epoch, ts);
325
+ // Stale non-finalized entry: do a lightweight refresh first (check block hash + finalized block).
326
+ // Only fall back to a full re-fetch if the L1 block was reorged. Otherwise, do a full fetch.
327
+ const promise =
328
+ cached?.kind === 'committee' ? this.refreshStaleEntry(cached, epoch, ts) : this.fetchAndCache(epoch, ts);
309
329
  this.cache.set(epoch, promise);
310
330
  try {
311
- return (await promise).data;
331
+ return await promise;
312
332
  } catch (err) {
313
- this.cache.delete(epoch);
333
+ if (this.cache.get(epoch) === promise) {
334
+ this.cache.delete(epoch);
335
+ }
314
336
  throw err;
315
337
  }
316
338
  }
@@ -337,71 +359,99 @@ export class EpochCache implements EpochCacheInterface {
337
359
  }
338
360
 
339
361
  /** Returns true if a non-finalized cache entry is older than one Ethereum slot. */
340
- private isStale(entry: CachedEpochEntry): boolean {
362
+ private isStale(entry: EpochEntry): boolean {
341
363
  const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
342
364
  return nowSeconds - entry.lastRefreshL1Timestamp >= BigInt(this.l1constants.ethereumSlotDuration);
343
365
  }
344
366
 
345
- /** Whether a cached epoch entry has been marked as finalized. Returns undefined if not cached or still in-flight. */
367
+ /** Whether a cached epoch entry is finalized. Undefined if not cached, in-flight or unstable. */
346
368
  public isFinalized(epoch: EpochNumber): boolean | undefined {
347
369
  const entry = this.cache.get(epoch);
348
- if (!entry || entry instanceof Promise) {
370
+ if (!entry || entry instanceof Promise || entry.kind !== 'committee') {
349
371
  return undefined;
350
372
  }
351
373
  return entry.finalized;
352
374
  }
353
375
 
354
- /** Returns the latest L1 timestamp stored in the cached entry. Undefined if not cached or in-flight. */
376
+ /** Returns the latest L1 timestamp stored in the cached entry. Undefined if not cached, in-flight or unstable. */
355
377
  public getCachedLastRefreshL1Timestamp(epoch: EpochNumber): bigint | undefined {
356
378
  const entry = this.cache.get(epoch);
357
- if (!entry || entry instanceof Promise) {
379
+ if (!entry || entry instanceof Promise || entry.kind !== 'committee') {
358
380
  return undefined;
359
381
  }
360
382
  return entry.lastRefreshL1Timestamp;
361
383
  }
362
384
 
363
- /** Computes the sampling timestamp for an epoch's committee data. */
364
- private getSamplingTimestamp(epoch: EpochNumber): bigint {
365
- const { lagInEpochsForRandao, epochDuration, slotDuration } = this.l1constants;
366
- const epochStartTs = getStartTimestampForEpoch(epoch, this.l1constants);
367
- return epochStartTs - BigInt(lagInEpochsForRandao) * BigInt(epochDuration) * BigInt(slotDuration);
385
+ /**
386
+ * Whether the sample seed for `epoch` is fixed as of the given L1 block. The seed for epoch E hashes the randao
387
+ * that L1 checkpoints in epoch S = E - lagInEpochsForRandao, under the key start(S). It is fixed once that randao
388
+ * is written, or once no later L1 block can land in S, since any later checkpoint is keyed at a later epoch's start.
389
+ */
390
+ private async isSeedFixed(epoch: EpochNumber, block: L1BlockInfo): Promise<boolean> {
391
+ const { targetCommitteeSize, lagInEpochsForRandao } = this.l1constants;
392
+
393
+ // The seed is irrelevant when the committee is empty and anyone may propose.
394
+ if (targetCommitteeSize === 0) {
395
+ return true;
396
+ }
397
+
398
+ // Epochs sampled before genesis read the zero randao that precedes the genesis checkpoint.
399
+ const samplingEpoch = BigInt(epoch) - BigInt(lagInEpochsForRandao);
400
+ if (samplingEpoch < 0n) {
401
+ return true;
402
+ }
403
+
404
+ // A block in S's last L1 slot is S's last block, as L1 blocks are at least one Ethereum slot apart. Waiting for a
405
+ // block past S would also cost E's second slot, which a pipelined proposer decides on while the tip is still in S.
406
+ const [samplingEpochStart, samplingEpochLastL1Slot] = getTimestampRangeForEpoch(
407
+ EpochNumber.fromBigInt(samplingEpoch),
408
+ this.l1constants,
409
+ );
410
+ if (block.timestamp >= samplingEpochLastL1Slot) {
411
+ return true;
412
+ }
413
+ if (block.timestamp < samplingEpochStart) {
414
+ return false;
415
+ }
416
+
417
+ // v6 views don't revert while S's randao can still change, so read S's commitment, which setupEpoch stores after
418
+ // checkpointing that randao. Drop this once every supported rollup reverts with EpochNotStable (v7 onwards).
419
+ return await this.rollup.isEpochSetUp(EpochNumber.fromBigInt(samplingEpoch), { blockNumber: block.number });
368
420
  }
369
421
 
370
422
  /**
371
423
  * Lightweight refresh for a stale non-finalized entry. Queries only the block hash at
372
- * the original block number and the finalized block timestamp — avoids the expensive
424
+ * the original block number and the finalized block — avoids the expensive
373
425
  * getCommitteeAt and getSampleSeedAt calls on the rollup contract.
374
426
  *
375
427
  * If the block hash still matches (no L1 reorg), we keep the existing data and just
376
428
  * update the provenance timestamp. If the finalized block has caught up, we promote the
377
- * entry to finalized. If there was a reorg (hash mismatch), we fall back to a full fetch.
429
+ * entry to finalized. If there was a reorg (hash mismatch), we fall back to a full fetch,
430
+ * and drop the stale entry if that fetch fails.
378
431
  */
379
- private async refreshStaleEntry(stale: CachedEpochEntry, epoch: EpochNumber, ts: bigint): Promise<CachedEpochEntry> {
432
+ private async refreshStaleEntry(stale: CachedEpochEntry, epoch: EpochNumber, ts: bigint): Promise<EpochEntry> {
380
433
  const [blockAtOriginal, l1FinalizedBlock, latestBlock] = await Promise.all([
381
434
  this.rollup.client.getBlock({ blockNumber: stale.lastQueryL1BlockNumber, includeTransactions: false }),
382
435
  getFinalizedL1Block(this.rollup.client),
383
436
  this.rollup.client.getBlock({ includeTransactions: false }),
384
- ]);
437
+ ]).catch(err => {
438
+ this.cache.set(epoch, stale);
439
+ throw err;
440
+ });
385
441
 
386
442
  if (blockAtOriginal.hash === stale.lastQueryL1BlockHash) {
387
443
  // No reorg: the data is still valid. Check if we can now mark it as finalized.
388
- const samplingTs = this.getSamplingTimestamp(epoch);
389
- const finalized =
390
- !!(stale.data.committee && stale.data.committee.length > 0) &&
391
- l1FinalizedBlock !== undefined &&
392
- samplingTs <= l1FinalizedBlock.timestamp;
393
-
394
444
  const refreshed: CachedEpochEntry = {
395
445
  ...stale,
396
446
  lastRefreshL1Timestamp: latestBlock.timestamp,
397
- finalized,
447
+ finalized: this.isEntryFinalized(stale.data, stale.lastQueryL1BlockNumber, l1FinalizedBlock),
398
448
  };
399
449
  this.cache.set(epoch, refreshed);
400
450
  return refreshed;
401
451
  }
402
452
 
403
453
  // Reorg detected: block hash mismatch. Do a full re-fetch.
404
- // Pass the already-fetched block timestamps to avoid redundant queries.
454
+ // Pass the already-fetched blocks to avoid redundant queries.
405
455
  this.log.warn(`L1 reorg detected for epoch ${epoch}: block ${stale.lastQueryL1BlockNumber} hash changed`, {
406
456
  epoch,
407
457
  expectedHash: stale.lastQueryL1BlockHash,
@@ -410,57 +460,94 @@ export class EpochCache implements EpochCacheInterface {
410
460
  return this.fetchAndCache(epoch, ts, { latestBlock, finalizedBlock: l1FinalizedBlock });
411
461
  }
412
462
 
463
+ /** Fetches an epoch's entry with {@link fetchEntry} and stores it in the cache. */
464
+ private async fetchAndCache(
465
+ epoch: EpochNumber,
466
+ ts: bigint,
467
+ prefetched?: { latestBlock: L1BlockInfo; finalizedBlock: L1BlockInfo | undefined },
468
+ ): Promise<EpochEntry> {
469
+ const entry = await this.fetchEntry(epoch, ts, prefetched);
470
+ this.cache.set(epoch, entry);
471
+ this.purgeCache();
472
+ return entry;
473
+ }
474
+
413
475
  /**
414
- * Fetches committee data from L1, determines finalization status, and stores in the cache.
415
- *
416
- * Uses `lagInEpochsForRandao` (the binding constraint, always <= lagInEpochsForValidatorSet)
417
- * and computes the sampling timestamp from the epoch start to match the L1 contract's logic.
418
- *
419
- * When called from refreshStaleEntry after a reorg, the latest and finalized blocks are
420
- * passed in to avoid redundant L1 queries.
476
+ * Reads an epoch's committee from L1 and determines its finalization status, or returns an unstable marker if the
477
+ * epoch's seed can still change as of the latest L1 block. When called from refreshStaleEntry after a reorg, the
478
+ * latest and finalized blocks are passed in to avoid redundant L1 queries.
421
479
  */
422
- private async fetchAndCache(
480
+ private async fetchEntry(
423
481
  epoch: EpochNumber,
424
482
  ts: bigint,
425
- prefetched?: { latestBlock: L1BlockInfo; finalizedBlock: { timestamp: bigint } | undefined },
426
- ): Promise<CachedEpochEntry> {
427
- const [committee, seedBuffer, latestBlock, finalizedBlock, isEscapeHatchOpen] = await Promise.all([
428
- this.rollup.getCommitteeAt(ts),
429
- this.rollup.getSampleSeedAt(ts),
430
- prefetched?.latestBlock ?? this.rollup.client.getBlock({ includeTransactions: false }),
431
- prefetched !== undefined ? prefetched.finalizedBlock : getFinalizedL1Block(this.rollup.client),
432
- this.rollup.isEscapeHatchOpen(epoch),
433
- ]);
483
+ prefetched?: { latestBlock: L1BlockInfo; finalizedBlock: L1BlockInfo | undefined },
484
+ ): Promise<EpochEntry> {
485
+ // Pin the rollup reads to one L1 block so the entry's provenance matches the data it holds. The escape hatch flag
486
+ // is only partly pinned: the hatch address is resolved at the latest block, and any read error counts as closed.
487
+ const latestBlock = prefetched?.latestBlock ?? (await this.rollup.client.getBlock({ includeTransactions: false }));
488
+ const blockNumber = latestBlock.number;
489
+ const unstable: UnstableEpochEntry = {
490
+ kind: 'unstable',
491
+ l1BlockNumber: blockNumber,
492
+ lastRefreshL1Timestamp: maxBigint(latestBlock.timestamp, BigInt(this.dateProvider.nowInSeconds())),
493
+ };
434
494
 
435
- const samplingTs = this.getSamplingTimestamp(epoch);
495
+ if (!(await this.isSeedFixed(epoch, latestBlock))) {
496
+ this.log.debug(`Committee for epoch ${epoch} is not stable yet as of L1 block ${blockNumber}`, {
497
+ epoch,
498
+ l1BlockNumber: blockNumber,
499
+ l1BlockTimestamp: latestBlock.timestamp,
500
+ });
501
+ return unstable;
502
+ }
436
503
 
437
- if (samplingTs > latestBlock.timestamp) {
438
- throw new Error(
439
- `Cannot query committee for future epoch ${epoch}: ` +
440
- `sampling timestamp ${samplingTs} is beyond latest L1 block at ${latestBlock.timestamp}. ` +
441
- `Check your Ethereum node is synced.`,
442
- );
504
+ const reads = await Promise.all([
505
+ this.rollup.getCommitteeAt(ts, { blockNumber }),
506
+ this.rollup.getSampleSeedAt(ts, { blockNumber }),
507
+ prefetched !== undefined ? prefetched.finalizedBlock : getFinalizedL1Block(this.rollup.client),
508
+ this.rollup.isEscapeHatchOpen(epoch, { blockNumber }),
509
+ ]).catch(err => {
510
+ if (isEpochNotStableError(err)) {
511
+ return undefined;
512
+ }
513
+ throw err;
514
+ });
515
+ if (!reads) {
516
+ return unstable;
517
+ }
518
+ const [committee, seedBuffer, finalizedBlock, isEscapeHatchOpen] = reads;
519
+
520
+ // Reads by block number follow the canonical chain, so a reorg mid-fetch could mix the seed check above with
521
+ // committee data from another fork. Confirm the queried block is still canonical before trusting the reads.
522
+ const queriedBlock = await this.rollup.client.getBlock({ blockNumber, includeTransactions: false });
523
+ if (queriedBlock.hash !== latestBlock.hash) {
524
+ throw new Error(`L1 block ${blockNumber} was reorged out while reading the committee for epoch ${epoch}`);
443
525
  }
444
526
 
445
- // Empty committees are never marked finalized so they always get re-queried after TTL.
446
- // If L1 has no finalized block yet (devnet startup), entries stay unfinalized.
447
- const hasCommittee = !!(committee && committee.length > 0);
448
- const finalized = hasCommittee && finalizedBlock !== undefined && samplingTs <= finalizedBlock.timestamp;
449
- const data: EpochCommitteeInfo = { committee, seed: seedBuffer.toBigInt(), epoch, isEscapeHatchOpen };
527
+ const data = toCommitteeLookup(committee, { seed: seedBuffer.toBigInt(), epoch, isEscapeHatchOpen });
450
528
  const entry: CachedEpochEntry = {
529
+ kind: 'committee',
451
530
  data,
452
- lastQueryL1BlockNumber: latestBlock.number!,
453
- lastQueryL1BlockHash: latestBlock.hash!,
531
+ lastQueryL1BlockNumber: blockNumber,
532
+ lastQueryL1BlockHash: latestBlock.hash,
454
533
  lastRefreshL1Timestamp: latestBlock.timestamp,
455
- finalized,
534
+ finalized: this.isEntryFinalized(data, blockNumber, finalizedBlock),
456
535
  };
457
-
458
- this.cache.set(epoch, entry);
459
- this.purgeCache();
460
-
461
536
  return entry;
462
537
  }
463
538
 
539
+ /**
540
+ * An entry's committee and seed are final once the L1 block it was read at is finalized (the escape hatch flag is
541
+ * not). Entries without members are never marked finalized, so they get re-queried after the TTL.
542
+ */
543
+ private isEntryFinalized(
544
+ data: KnownCommitteeLookup,
545
+ queryL1BlockNumber: bigint,
546
+ finalizedBlock: L1BlockInfo | undefined,
547
+ ): boolean {
548
+ return data.state === 'members' && finalizedBlock !== undefined && finalizedBlock.number >= queryL1BlockNumber;
549
+ }
550
+
464
551
  /**
465
552
  * Get the ABI encoding of the proposer index - see ValidatorSelectionLib.sol computeProposerIndex
466
553
  */
@@ -508,79 +595,47 @@ export class EpochCache implements EpochCacheInterface {
508
595
  return { targetSlot, nextSlot };
509
596
  }
510
597
 
511
- /**
512
- * Get the proposer attester address in the given L2 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 getProposerAttesterAddressInSlot(slot: SlotNumber): Promise<EthAddress | undefined> {
517
- const epochAndSlot = this.getEpochAndSlotAtSlot(slot);
518
- return this.getProposerAttesterAddressAt(epochAndSlot);
598
+ /** Looks up the proposer for the given L2 slot. */
599
+ public lookupProposer(slot: SlotNumber): Promise<ProposerLookup> {
600
+ return this.lookupProposerAt(this.getEpochAndSlotAtSlot(slot));
519
601
  }
520
602
 
521
- /**
522
- * Get the proposer attester address in the next slot
523
- * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
524
- * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
525
- */
526
- public getProposerAttesterAddressInNextSlot(): Promise<EthAddress | undefined> {
527
- const epochAndSlot = this.getEpochAndSlotInNextL1Slot();
528
- return this.getProposerAttesterAddressAt(epochAndSlot);
603
+ /** Looks up the proposer for the L2 slot of the next L1 slot. */
604
+ public lookupProposerInNextSlot(): Promise<ProposerLookup> {
605
+ return this.lookupProposerAt(this.getEpochAndSlotInNextL1Slot());
529
606
  }
530
607
 
531
- /**
532
- * Get the proposer attester address at a given epoch and slot
533
- * @param when - The epoch and slot to get the proposer attester address at
534
- * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
535
- * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
536
- */
537
- private async getProposerAttesterAddressAt(when: EpochAndSlot) {
538
- const { epoch, slot } = when;
539
- const { committee, seed } = await this.getCommittee(slot);
540
- if (!committee) {
541
- throw new NoCommitteeError();
542
- } else if (committee.length === 0) {
543
- return undefined;
544
- }
545
-
546
- const proposerIndex = this.computeProposerIndex(slot, epoch, seed, BigInt(committee.length));
547
- return committee[Number(proposerIndex)];
608
+ private async lookupProposerAt({ slot }: EpochAndSlot): Promise<ProposerLookup> {
609
+ return this.proposerFromCommitteeLookup(await this.getCommittee(slot), slot);
548
610
  }
549
611
 
550
- public getProposerFromEpochCommittee(
551
- epochCommitteeInfo: EpochCommitteeInfo,
552
- slot: SlotNumber,
553
- ): EthAddress | undefined {
554
- if (!epochCommitteeInfo.committee || epochCommitteeInfo.committee.length === 0) {
555
- return undefined;
612
+ /** Derives the proposer for a slot from its epoch's committee lookup. */
613
+ public proposerFromCommitteeLookup(lookup: CommitteeLookup, slot: SlotNumber): ProposerLookup {
614
+ if (lookup.state !== 'members') {
615
+ return withoutMembers(lookup);
556
616
  }
557
- const proposerIndex = this.computeProposerIndex(
558
- slot,
559
- epochCommitteeInfo.epoch,
560
- epochCommitteeInfo.seed,
561
- BigInt(epochCommitteeInfo.committee.length),
562
- );
563
-
564
- return epochCommitteeInfo.committee[Number(proposerIndex)];
617
+ const { committee, epoch, seed } = lookup;
618
+ const proposerIndex = this.computeProposerIndex(slot, epoch, seed, BigInt(committee.length));
619
+ return { state: 'members', proposer: committee[Number(proposerIndex)] };
565
620
  }
566
621
 
567
622
  /** Check if a validator is in the given slot's committee */
568
- async isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean> {
569
- const { committee } = await this.getCommittee(slot);
570
- if (!committee) {
571
- return false;
623
+ async lookupMembership(slot: SlotTag, validator: EthAddress): Promise<CommitteeMembershipLookup<boolean>> {
624
+ const lookup = await this.getCommittee(slot);
625
+ if (lookup.state !== 'members') {
626
+ return withoutMembers(lookup);
572
627
  }
573
- return committee.some(v => v.equals(validator));
628
+ return { state: 'members', inCommittee: lookup.committee.some(v => v.equals(validator)) };
574
629
  }
575
630
 
576
631
  /** From the set of given addresses, return all that are on the committee for the given slot */
577
- async filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]> {
578
- const { committee } = await this.getCommittee(slot);
579
- if (!committee) {
580
- return [];
632
+ async filterInCommittee(slot: SlotTag, validators: EthAddress[]): Promise<CommitteeMembershipLookup<EthAddress[]>> {
633
+ const lookup = await this.getCommittee(slot);
634
+ if (lookup.state !== 'members') {
635
+ return withoutMembers(lookup);
581
636
  }
582
- const committeeSet = new Set(committee.map(v => v.toString()));
583
- return validators.filter(v => committeeSet.has(v.toString()));
637
+ const committeeSet = new Set(lookup.committee.map(v => v.toString()));
638
+ return { state: 'members', inCommittee: validators.filter(v => committeeSet.has(v.toString())) };
584
639
  }
585
640
 
586
641
  async getRegisteredValidators(): Promise<EthAddress[]> {
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
+ export * from './committee_lookup.js';
1
2
  export * from './epoch_cache.js';
2
3
  export * from './config.js';
package/src/test/index.ts CHANGED
@@ -1 +1,2 @@
1
+ export * from './lookups.js';
1
2
  export * from './test_epoch_cache.js';
@@ -0,0 +1,40 @@
1
+ import { EpochNumber } from '@aztec-labs/foundation/branded-types';
2
+ import type { EthAddress } from '@aztec-labs/foundation/eth-address';
3
+
4
+ import {
5
+ type CommitteeMembershipLookup,
6
+ type EpochCommitteeInfo,
7
+ type EscapeHatchLookup,
8
+ type KnownCommitteeLookup,
9
+ type ProposerLookup,
10
+ type UnstableCommittee,
11
+ toCommitteeLookup,
12
+ } from '../committee_lookup.js';
13
+
14
+ /** Builds a committee lookup from a committee as L1 returns it: `undefined` is `none` and `[]` is `open`. */
15
+ export function makeCommitteeLookup({
16
+ committee,
17
+ ...info
18
+ }: { committee: EthAddress[] | undefined } & Partial<EpochCommitteeInfo>): KnownCommitteeLookup {
19
+ return toCommitteeLookup(committee, { epoch: EpochNumber.ZERO, seed: 0n, isEscapeHatchOpen: false, ...info });
20
+ }
21
+
22
+ /** Builds a proposer lookup: `undefined` is an `open` committee, as the proposer getter used to report it. */
23
+ export function makeProposerLookup(proposer: EthAddress | undefined): ProposerLookup {
24
+ return proposer === undefined ? { state: 'open' } : { state: 'members', proposer };
25
+ }
26
+
27
+ /** Builds a membership lookup for a `members` committee. */
28
+ export function makeMembershipLookup<T>(inCommittee: T): CommitteeMembershipLookup<T> {
29
+ return { state: 'members', inCommittee };
30
+ }
31
+
32
+ /** Builds an escape hatch lookup for a `members` committee. */
33
+ export function makeEscapeHatchLookup(isEscapeHatchOpen: boolean): EscapeHatchLookup {
34
+ return { state: 'members', isEscapeHatchOpen };
35
+ }
36
+
37
+ /** Builds the lookup for a committee whose seed is not fixed on L1 yet. */
38
+ export function makeUnstableCommittee(epoch: EpochNumber = EpochNumber.ZERO, l1BlockNumber = 0n): UnstableCommittee {
39
+ return { state: 'unstable', epoch, l1BlockNumber };
40
+ }