@aztec-labs/epoch-cache 6.0.0-nightly.20260829

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.
@@ -0,0 +1,452 @@
1
+ import { createEthereumChain } from '@aztec-labs/ethereum/chain';
2
+ import { makeL1HttpTransport } from '@aztec-labs/ethereum/client';
3
+ import { NoCommitteeError, RollupContract } from '@aztec-labs/ethereum/contracts';
4
+ import { getFinalizedL1Block } from '@aztec-labs/ethereum/queries';
5
+ import { SlotNumber } from '@aztec-labs/foundation/branded-types';
6
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
7
+ import { createLogger } from '@aztec-labs/foundation/log';
8
+ import { DateProvider } from '@aztec-labs/foundation/timer';
9
+ import { getEpochAtSlot, getEpochNumberAtTimestamp, getNextL1SlotTimestamp, getSlotAtNextL1Block, getSlotAtTimestamp, getSlotRangeForEpoch, getStartTimestampForEpoch, getTimestampForSlot } from '@aztec-labs/stdlib/epoch-helpers';
10
+ import { createPublicClient, encodeAbiParameters, keccak256 } from 'viem';
11
+ import { getEpochCacheConfigEnvVars } from './config.js';
12
+ /** The proposer pipelines by building one slot ahead. */ export const PROPOSER_PIPELINING_SLOT_OFFSET = 1;
13
+ /**
14
+ * Epoch cache
15
+ *
16
+ * This class is responsible for managing traffic to the l1 node, by caching the validator set.
17
+ * Keeps the last N epochs in cache.
18
+ * It also provides a method to get the current or next proposer, and to check who is in the current slot.
19
+ *
20
+ * Note: This class is very dependent on the system clock being in sync.
21
+ */ export class EpochCache {
22
+ rollup;
23
+ l1constants;
24
+ dateProvider;
25
+ config;
26
+ /**
27
+ * Single map holding both resolved entries and in-flight promises.
28
+ * A `Promise` value means a fetch is in progress; concurrent callers await it.
29
+ */ cache;
30
+ allValidators;
31
+ lastValidatorRefresh;
32
+ log;
33
+ constructor(rollup, l1constants, dateProvider = new DateProvider(), config = {
34
+ cacheSize: 12,
35
+ validatorRefreshIntervalSeconds: 60
36
+ }){
37
+ this.rollup = rollup;
38
+ this.l1constants = l1constants;
39
+ this.dateProvider = dateProvider;
40
+ this.config = config;
41
+ this.cache = new Map();
42
+ this.allValidators = new Set();
43
+ this.lastValidatorRefresh = 0;
44
+ this.log = createLogger('epoch-cache');
45
+ this.log.debug(`Initialized EpochCache`, {
46
+ l1constants
47
+ });
48
+ }
49
+ static async create(rollupOrAddress, config, deps = {}) {
50
+ config = config ?? getEpochCacheConfigEnvVars();
51
+ // Load the rollup contract if we were given an address
52
+ let rollup;
53
+ if ('address' in rollupOrAddress) {
54
+ rollup = rollupOrAddress;
55
+ } else {
56
+ const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
57
+ const publicClient = createPublicClient({
58
+ chain: chain.chainInfo,
59
+ transport: makeL1HttpTransport(config.l1RpcUrls, {
60
+ timeout: config.l1HttpTimeoutMS
61
+ }),
62
+ pollingInterval: config.viemPollingIntervalMS
63
+ });
64
+ rollup = new RollupContract(publicClient, rollupOrAddress.toString());
65
+ }
66
+ const [l1StartBlock, l1GenesisTime, proofSubmissionEpochs, slotDuration, epochDuration, lagInEpochsForValidatorSet, lagInEpochsForRandao, targetCommitteeSize, rollupManaLimit] = await Promise.all([
67
+ rollup.getL1StartBlock(),
68
+ rollup.getL1GenesisTime(),
69
+ rollup.getProofSubmissionEpochs(),
70
+ rollup.getSlotDuration(),
71
+ rollup.getEpochDuration(),
72
+ rollup.getLagInEpochsForValidatorSet(),
73
+ rollup.getLagInEpochsForRandao(),
74
+ rollup.getTargetCommitteeSize(),
75
+ rollup.getManaLimit()
76
+ ]);
77
+ const l1RollupConstants = {
78
+ l1StartBlock,
79
+ l1GenesisTime,
80
+ proofSubmissionEpochs: Number(proofSubmissionEpochs),
81
+ slotDuration: Number(slotDuration),
82
+ epochDuration: Number(epochDuration),
83
+ ethereumSlotDuration: config.ethereumSlotDuration,
84
+ lagInEpochsForValidatorSet: Number(lagInEpochsForValidatorSet),
85
+ lagInEpochsForRandao: Number(lagInEpochsForRandao),
86
+ targetCommitteeSize: Number(targetCommitteeSize),
87
+ rollupManaLimit: Number(rollupManaLimit)
88
+ };
89
+ return new EpochCache(rollup, l1RollupConstants, deps.dateProvider, {
90
+ cacheSize: 12,
91
+ validatorRefreshIntervalSeconds: 60
92
+ });
93
+ }
94
+ getL1Constants() {
95
+ return this.l1constants;
96
+ }
97
+ /**
98
+ * The number of epochs by which validator-set sampling lags. The committee for epoch `E` samples the
99
+ * validator set as of `lagInEpochsForValidatorSet` epochs before `E` (see
100
+ * `ValidatorSelectionLib.stableEpochToValidatorSetSampleTime` on L1), so a newly staked validator only
101
+ * becomes eligible for a committee this many epochs after staking.
102
+ */ getLagInEpochsForValidatorSet() {
103
+ return this.l1constants.lagInEpochsForValidatorSet;
104
+ }
105
+ getSlotNow() {
106
+ return this.getEpochAndSlotNow().slot;
107
+ }
108
+ getTargetSlot() {
109
+ const slotNow = this.getSlotNow();
110
+ const offset = PROPOSER_PIPELINING_SLOT_OFFSET;
111
+ return SlotNumber(slotNow + offset);
112
+ }
113
+ getEpochNow() {
114
+ return this.getEpochAndSlotNow().epoch;
115
+ }
116
+ getTargetEpoch() {
117
+ return getEpochAtSlot(this.getTargetSlot(), this.l1constants);
118
+ }
119
+ getEpochAndSlotNow() {
120
+ const nowMs = BigInt(this.dateProvider.now());
121
+ const nowSeconds = nowMs / 1000n;
122
+ return {
123
+ ...this.getEpochAndSlotAtTimestamp(nowSeconds),
124
+ nowMs
125
+ };
126
+ }
127
+ getEpochAndSlotAtSlot(slot) {
128
+ return this.getEpochAndSlotAtTimestamp(getTimestampForSlot(slot, this.l1constants));
129
+ }
130
+ getEpochAndSlotInNextL1Slot() {
131
+ const nowSeconds = this.dateProvider.nowInSeconds();
132
+ const nextSlotTs = getNextL1SlotTimestamp(nowSeconds, this.l1constants);
133
+ return {
134
+ ...this.getEpochAndSlotAtTimestamp(nextSlotTs),
135
+ nowSeconds: BigInt(nowSeconds)
136
+ };
137
+ }
138
+ getTargetEpochAndSlotInNextL1Slot() {
139
+ const result = this.getEpochAndSlotInNextL1Slot();
140
+ const offset = PROPOSER_PIPELINING_SLOT_OFFSET;
141
+ const targetSlot = SlotNumber(result.slot + offset);
142
+ return {
143
+ ...result,
144
+ slot: targetSlot,
145
+ epoch: getEpochAtSlot(targetSlot, this.l1constants)
146
+ };
147
+ }
148
+ getEpochAndSlotAtTimestamp(ts) {
149
+ const slot = getSlotAtTimestamp(ts, this.l1constants);
150
+ const epoch = getEpochNumberAtTimestamp(ts, this.l1constants);
151
+ return {
152
+ slot,
153
+ epoch,
154
+ ts: getTimestampForSlot(slot, this.l1constants)
155
+ };
156
+ }
157
+ getCommitteeForEpoch(epoch) {
158
+ const [startSlot] = getSlotRangeForEpoch(epoch, this.l1constants);
159
+ return this.getCommittee(startSlot);
160
+ }
161
+ /** Returns whether the escape hatch is open for the given epoch. */ async isEscapeHatchOpen(epoch) {
162
+ const info = await this.getCommitteeForEpoch(epoch);
163
+ return info.isEscapeHatchOpen;
164
+ }
165
+ /**
166
+ * Returns whether the escape hatch is open for the epoch containing the given slot.
167
+ *
168
+ * This is a lightweight helper intended for callers that already have a slot number and only
169
+ * need the escape hatch flag (without pulling full committee info).
170
+ */ async isEscapeHatchOpenAtSlot(slot = 'now') {
171
+ const epoch = slot === 'now' ? this.getEpochNow() : slot === 'next' ? this.getEpochAndSlotInNextL1Slot().epoch : getEpochAtSlot(slot, this.l1constants);
172
+ return await this.isEscapeHatchOpen(epoch);
173
+ }
174
+ /**
175
+ * Get the current validator set.
176
+ *
177
+ * Returns cached data if the entry is finalized or still fresh (queried less than one
178
+ * Ethereum slot ago). Stale non-finalized entries are re-queried, and concurrent callers
179
+ * coalesce on the same in-flight promise so the L1 query happens only once.
180
+ */ async getCommittee(slot = 'now') {
181
+ const { epoch, ts } = this.getEpochAndTimestamp(slot);
182
+ const cached = this.cache.get(epoch);
183
+ // In-flight promise: another caller is already fetching this epoch — just await it.
184
+ if (cached instanceof Promise) {
185
+ return (await cached).data;
186
+ }
187
+ // Resolved entry: return it if finalized or still fresh.
188
+ if (cached && (cached.finalized || !this.isStale(cached))) {
189
+ return cached.data;
190
+ }
191
+ // Stale non-finalized entry: do a lightweight refresh first (check block hash + finalized ts).
192
+ // Only fall back to a full re-fetch if the L1 block was reorged.
193
+ if (cached) {
194
+ const promise = this.refreshStaleEntry(cached, epoch, ts);
195
+ this.cache.set(epoch, promise);
196
+ try {
197
+ return (await promise).data;
198
+ } catch (err) {
199
+ this.cache.set(epoch, cached);
200
+ throw err;
201
+ }
202
+ }
203
+ // No entry at all: full fetch.
204
+ const promise = this.fetchAndCache(epoch, ts);
205
+ this.cache.set(epoch, promise);
206
+ try {
207
+ return (await promise).data;
208
+ } catch (err) {
209
+ this.cache.delete(epoch);
210
+ throw err;
211
+ }
212
+ }
213
+ getEpochAndTimestamp(slot = 'now') {
214
+ if (slot === 'now') {
215
+ return this.getEpochAndSlotNow();
216
+ } else if (slot === 'next') {
217
+ return this.getEpochAndSlotInNextL1Slot();
218
+ } else {
219
+ return this.getEpochAndSlotAtSlot(slot);
220
+ }
221
+ }
222
+ /** Evicts oldest cache entries (resolved or in-flight) beyond cacheSize. */ purgeCache() {
223
+ if (this.cache.size <= this.config.cacheSize) {
224
+ return;
225
+ }
226
+ const toPurge = Array.from(this.cache.keys()).sort((a, b)=>Number(b - a)).slice(this.config.cacheSize);
227
+ toPurge.forEach((key)=>this.cache.delete(key));
228
+ }
229
+ /** Returns true if a non-finalized cache entry is older than one Ethereum slot. */ isStale(entry) {
230
+ const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
231
+ return nowSeconds - entry.lastRefreshL1Timestamp >= BigInt(this.l1constants.ethereumSlotDuration);
232
+ }
233
+ /** Whether a cached epoch entry has been marked as finalized. Returns undefined if not cached or still in-flight. */ isFinalized(epoch) {
234
+ const entry = this.cache.get(epoch);
235
+ if (!entry || entry instanceof Promise) {
236
+ return undefined;
237
+ }
238
+ return entry.finalized;
239
+ }
240
+ /** Returns the latest L1 timestamp stored in the cached entry. Undefined if not cached or in-flight. */ getCachedLastRefreshL1Timestamp(epoch) {
241
+ const entry = this.cache.get(epoch);
242
+ if (!entry || entry instanceof Promise) {
243
+ return undefined;
244
+ }
245
+ return entry.lastRefreshL1Timestamp;
246
+ }
247
+ /** Computes the sampling timestamp for an epoch's committee data. */ getSamplingTimestamp(epoch) {
248
+ const { lagInEpochsForRandao, epochDuration, slotDuration } = this.l1constants;
249
+ const epochStartTs = getStartTimestampForEpoch(epoch, this.l1constants);
250
+ return epochStartTs - BigInt(lagInEpochsForRandao) * BigInt(epochDuration) * BigInt(slotDuration);
251
+ }
252
+ /**
253
+ * Lightweight refresh for a stale non-finalized entry. Queries only the block hash at
254
+ * the original block number and the finalized block timestamp — avoids the expensive
255
+ * getCommitteeAt and getSampleSeedAt calls on the rollup contract.
256
+ *
257
+ * If the block hash still matches (no L1 reorg), we keep the existing data and just
258
+ * update the provenance timestamp. If the finalized block has caught up, we promote the
259
+ * entry to finalized. If there was a reorg (hash mismatch), we fall back to a full fetch.
260
+ */ async refreshStaleEntry(stale, epoch, ts) {
261
+ const [blockAtOriginal, l1FinalizedBlock, latestBlock] = await Promise.all([
262
+ this.rollup.client.getBlock({
263
+ blockNumber: stale.lastQueryL1BlockNumber,
264
+ includeTransactions: false
265
+ }),
266
+ getFinalizedL1Block(this.rollup.client),
267
+ this.rollup.client.getBlock({
268
+ includeTransactions: false
269
+ })
270
+ ]);
271
+ if (blockAtOriginal.hash === stale.lastQueryL1BlockHash) {
272
+ // No reorg: the data is still valid. Check if we can now mark it as finalized.
273
+ const samplingTs = this.getSamplingTimestamp(epoch);
274
+ const finalized = !!(stale.data.committee && stale.data.committee.length > 0) && l1FinalizedBlock !== undefined && samplingTs <= l1FinalizedBlock.timestamp;
275
+ const refreshed = {
276
+ ...stale,
277
+ lastRefreshL1Timestamp: latestBlock.timestamp,
278
+ finalized
279
+ };
280
+ this.cache.set(epoch, refreshed);
281
+ return refreshed;
282
+ }
283
+ // Reorg detected: block hash mismatch. Do a full re-fetch.
284
+ // Pass the already-fetched block timestamps to avoid redundant queries.
285
+ this.log.warn(`L1 reorg detected for epoch ${epoch}: block ${stale.lastQueryL1BlockNumber} hash changed`, {
286
+ epoch,
287
+ expectedHash: stale.lastQueryL1BlockHash,
288
+ actualHash: blockAtOriginal.hash
289
+ });
290
+ return this.fetchAndCache(epoch, ts, {
291
+ latestBlock,
292
+ finalizedBlock: l1FinalizedBlock
293
+ });
294
+ }
295
+ /**
296
+ * Fetches committee data from L1, determines finalization status, and stores in the cache.
297
+ *
298
+ * Uses `lagInEpochsForRandao` (the binding constraint, always <= lagInEpochsForValidatorSet)
299
+ * and computes the sampling timestamp from the epoch start to match the L1 contract's logic.
300
+ *
301
+ * When called from refreshStaleEntry after a reorg, the latest and finalized blocks are
302
+ * passed in to avoid redundant L1 queries.
303
+ */ async fetchAndCache(epoch, ts, prefetched) {
304
+ const [committee, seedBuffer, latestBlock, finalizedBlock, isEscapeHatchOpen] = await Promise.all([
305
+ this.rollup.getCommitteeAt(ts),
306
+ this.rollup.getSampleSeedAt(ts),
307
+ prefetched?.latestBlock ?? this.rollup.client.getBlock({
308
+ includeTransactions: false
309
+ }),
310
+ prefetched !== undefined ? prefetched.finalizedBlock : getFinalizedL1Block(this.rollup.client),
311
+ this.rollup.isEscapeHatchOpen(epoch)
312
+ ]);
313
+ const samplingTs = this.getSamplingTimestamp(epoch);
314
+ if (samplingTs > latestBlock.timestamp) {
315
+ throw new Error(`Cannot query committee for future epoch ${epoch}: ` + `sampling timestamp ${samplingTs} is beyond latest L1 block at ${latestBlock.timestamp}. ` + `Check your Ethereum node is synced.`);
316
+ }
317
+ // Empty committees are never marked finalized so they always get re-queried after TTL.
318
+ // If L1 has no finalized block yet (devnet startup), entries stay unfinalized.
319
+ const hasCommittee = !!(committee && committee.length > 0);
320
+ const finalized = hasCommittee && finalizedBlock !== undefined && samplingTs <= finalizedBlock.timestamp;
321
+ const data = {
322
+ committee,
323
+ seed: seedBuffer.toBigInt(),
324
+ epoch,
325
+ isEscapeHatchOpen
326
+ };
327
+ const entry = {
328
+ data,
329
+ lastQueryL1BlockNumber: latestBlock.number,
330
+ lastQueryL1BlockHash: latestBlock.hash,
331
+ lastRefreshL1Timestamp: latestBlock.timestamp,
332
+ finalized
333
+ };
334
+ this.cache.set(epoch, entry);
335
+ this.purgeCache();
336
+ return entry;
337
+ }
338
+ /**
339
+ * Get the ABI encoding of the proposer index - see ValidatorSelectionLib.sol computeProposerIndex
340
+ */ getProposerIndexEncoding(epoch, slot, seed) {
341
+ return encodeAbiParameters([
342
+ {
343
+ type: 'uint256',
344
+ name: 'epoch'
345
+ },
346
+ {
347
+ type: 'uint256',
348
+ name: 'slot'
349
+ },
350
+ {
351
+ type: 'uint256',
352
+ name: 'seed'
353
+ }
354
+ ], [
355
+ BigInt(epoch),
356
+ BigInt(slot),
357
+ seed
358
+ ]);
359
+ }
360
+ computeProposerIndex(slot, epoch, seed, size) {
361
+ // if committe size is 0, then mod 1 is 0
362
+ if (size === 0n) {
363
+ return 0n;
364
+ }
365
+ return BigInt(keccak256(this.getProposerIndexEncoding(epoch, slot, seed))) % size;
366
+ }
367
+ /** Returns the current and next L2 slot in next eth L1 Slot. */ getCurrentAndNextSlot() {
368
+ const currentSlot = this.getSlotNow();
369
+ const next = this.getEpochAndSlotInNextL1Slot();
370
+ return {
371
+ currentSlot,
372
+ nextSlot: next.slot
373
+ };
374
+ }
375
+ /** Returns the target and next L2 slot in the next L1 slot. */ getTargetAndNextSlot() {
376
+ const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
377
+ const offset = PROPOSER_PIPELINING_SLOT_OFFSET;
378
+ const currentSlot = getSlotAtTimestamp(nowSeconds, this.l1constants);
379
+ const targetSlot = SlotNumber(currentSlot + offset);
380
+ const nextL2SlotOnL1 = getSlotAtNextL1Block(nowSeconds, this.l1constants);
381
+ const nextSlot = SlotNumber(nextL2SlotOnL1 + offset);
382
+ return {
383
+ targetSlot,
384
+ nextSlot
385
+ };
386
+ }
387
+ /**
388
+ * Get the proposer attester address in the given L2 slot
389
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
390
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
391
+ */ getProposerAttesterAddressInSlot(slot) {
392
+ const epochAndSlot = this.getEpochAndSlotAtSlot(slot);
393
+ return this.getProposerAttesterAddressAt(epochAndSlot);
394
+ }
395
+ /**
396
+ * Get the proposer attester address in the next slot
397
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
398
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
399
+ */ getProposerAttesterAddressInNextSlot() {
400
+ const epochAndSlot = this.getEpochAndSlotInNextL1Slot();
401
+ return this.getProposerAttesterAddressAt(epochAndSlot);
402
+ }
403
+ /**
404
+ * Get the proposer attester address at a given epoch and slot
405
+ * @param when - The epoch and slot to get the proposer attester address at
406
+ * @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
407
+ * If the committee is empty (i.e. target committee size is 0, and anyone can propose), we return undefined.
408
+ */ async getProposerAttesterAddressAt(when) {
409
+ const { epoch, slot } = when;
410
+ const { committee, seed } = await this.getCommittee(slot);
411
+ if (!committee) {
412
+ throw new NoCommitteeError();
413
+ } else if (committee.length === 0) {
414
+ return undefined;
415
+ }
416
+ const proposerIndex = this.computeProposerIndex(slot, epoch, seed, BigInt(committee.length));
417
+ return committee[Number(proposerIndex)];
418
+ }
419
+ getProposerFromEpochCommittee(epochCommitteeInfo, slot) {
420
+ if (!epochCommitteeInfo.committee || epochCommitteeInfo.committee.length === 0) {
421
+ return undefined;
422
+ }
423
+ const proposerIndex = this.computeProposerIndex(slot, epochCommitteeInfo.epoch, epochCommitteeInfo.seed, BigInt(epochCommitteeInfo.committee.length));
424
+ return epochCommitteeInfo.committee[Number(proposerIndex)];
425
+ }
426
+ /** Check if a validator is in the given slot's committee */ async isInCommittee(slot, validator) {
427
+ const { committee } = await this.getCommittee(slot);
428
+ if (!committee) {
429
+ return false;
430
+ }
431
+ return committee.some((v)=>v.equals(validator));
432
+ }
433
+ /** From the set of given addresses, return all that are on the committee for the given slot */ async filterInCommittee(slot, validators) {
434
+ const { committee } = await this.getCommittee(slot);
435
+ if (!committee) {
436
+ return [];
437
+ }
438
+ const committeeSet = new Set(committee.map((v)=>v.toString()));
439
+ return validators.filter((v)=>committeeSet.has(v.toString()));
440
+ }
441
+ async getRegisteredValidators() {
442
+ const validatorRefreshIntervalMs = this.config.validatorRefreshIntervalSeconds * 1000;
443
+ const validatorRefreshTime = this.lastValidatorRefresh + validatorRefreshIntervalMs;
444
+ const now = this.dateProvider.now();
445
+ if (validatorRefreshTime < now) {
446
+ const currentSet = await this.rollup.getAttesters(BigInt(Math.floor(now / 1000)));
447
+ this.allValidators = new Set(currentSet.map((v)=>v.toString()));
448
+ this.lastValidatorRefresh = now;
449
+ }
450
+ return Array.from(this.allValidators.keys()).map((v)=>EthAddress.fromString(v));
451
+ }
452
+ }
@@ -0,0 +1,3 @@
1
+ export * from './epoch_cache.js';
2
+ export * from './config.js';
3
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxjQUFjLGtCQUFrQixDQUFDO0FBQ2pDLGNBQWMsYUFBYSxDQUFDIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,kBAAkB,CAAC;AACjC,cAAc,aAAa,CAAC"}
package/dest/index.js ADDED
@@ -0,0 +1,2 @@
1
+ export * from './epoch_cache.js';
2
+ export * from './config.js';
@@ -0,0 +1,2 @@
1
+ export * from './test_epoch_cache.js';
2
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90ZXN0L2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLGNBQWMsdUJBQXVCLENBQUMifQ==
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/test/index.ts"],"names":[],"mappings":"AAAA,cAAc,uBAAuB,CAAC"}
@@ -0,0 +1 @@
1
+ export * from './test_epoch_cache.js';
@@ -0,0 +1,91 @@
1
+ import { EpochNumber, SlotNumber } from '@aztec-labs/foundation/branded-types';
2
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
3
+ import type { L1RollupConstants } from '@aztec-labs/stdlib/epoch-helpers';
4
+ import { type EpochAndSlot, type EpochCacheInterface, type EpochCommitteeInfo, type SlotTag } from '../epoch_cache.js';
5
+ /**
6
+ * A test implementation of EpochCacheInterface that allows manual configuration
7
+ * of committee, proposer, slot, and escape hatch state for use in tests.
8
+ *
9
+ * Unlike the real EpochCache, this class doesn't require any RPC connections
10
+ * or mock setup. Simply use the setter methods to configure the test state.
11
+ */
12
+ export declare class TestEpochCache implements EpochCacheInterface {
13
+ private committee;
14
+ private proposerAddress;
15
+ private currentSlot;
16
+ private escapeHatchOpen;
17
+ private seed;
18
+ private registeredValidators;
19
+ private l1Constants;
20
+ private lagInEpochsForValidatorSet;
21
+ constructor(l1Constants?: Partial<L1RollupConstants>);
22
+ setLagInEpochsForValidatorSet(lag: number): this;
23
+ /**
24
+ * Sets the committee members. Used in validation and attestation flows.
25
+ * @param committee - Array of committee member addresses.
26
+ */
27
+ setCommittee(committee: EthAddress[]): this;
28
+ /**
29
+ * Sets the proposer address returned by getProposerAttesterAddressInSlot.
30
+ * @param proposer - The address of the current proposer.
31
+ */
32
+ setProposer(proposer: EthAddress | undefined): this;
33
+ /**
34
+ * Sets the current slot number.
35
+ * @param slot - The slot number to set.
36
+ */
37
+ setCurrentSlot(slot: SlotNumber): this;
38
+ /**
39
+ * Sets whether the escape hatch is open.
40
+ * @param open - True if escape hatch should be open.
41
+ */
42
+ setEscapeHatchOpen(open: boolean): this;
43
+ /**
44
+ * Sets the randomness seed used for proposer selection.
45
+ * @param seed - The seed value.
46
+ */
47
+ setSeed(seed: bigint): this;
48
+ /**
49
+ * Sets the list of registered validators (all validators, not just committee).
50
+ * @param validators - Array of validator addresses.
51
+ */
52
+ setRegisteredValidators(validators: EthAddress[]): this;
53
+ /**
54
+ * Sets the L1 constants used for epoch/slot calculations.
55
+ * @param constants - Partial constants to override defaults.
56
+ */
57
+ setL1Constants(constants: Partial<L1RollupConstants>): this;
58
+ getL1Constants(): L1RollupConstants;
59
+ getLagInEpochsForValidatorSet(): number;
60
+ getCommittee(_slot?: SlotTag): Promise<EpochCommitteeInfo>;
61
+ getSlotNow(): SlotNumber;
62
+ getTargetSlot(): SlotNumber;
63
+ getEpochNow(): EpochNumber;
64
+ getTargetEpoch(): EpochNumber;
65
+ getEpochAndSlotNow(): EpochAndSlot & {
66
+ nowMs: bigint;
67
+ };
68
+ getEpochAndSlotInNextL1Slot(): EpochAndSlot & {
69
+ nowSeconds: bigint;
70
+ };
71
+ getTargetEpochAndSlotInNextL1Slot(): EpochAndSlot & {
72
+ nowSeconds: bigint;
73
+ };
74
+ getProposerIndexEncoding(epoch: EpochNumber, slot: SlotNumber, seed: bigint): `0x${string}`;
75
+ computeProposerIndex(slot: SlotNumber, _epoch: EpochNumber, _seed: bigint, size: bigint): bigint;
76
+ getCurrentAndNextSlot(): {
77
+ currentSlot: SlotNumber;
78
+ nextSlot: SlotNumber;
79
+ };
80
+ getTargetAndNextSlot(): {
81
+ targetSlot: SlotNumber;
82
+ nextSlot: SlotNumber;
83
+ };
84
+ getProposerAttesterAddressInSlot(_slot: SlotNumber): Promise<EthAddress | undefined>;
85
+ getRegisteredValidators(): Promise<EthAddress[]>;
86
+ isInCommittee(_slot: SlotTag, validator: EthAddress): Promise<boolean>;
87
+ filterInCommittee(_slot: SlotTag, validators: EthAddress[]): Promise<EthAddress[]>;
88
+ isEscapeHatchOpen(_epoch: EpochNumber): Promise<boolean>;
89
+ isEscapeHatchOpenAtSlot(_slot?: SlotTag): Promise<boolean>;
90
+ }
91
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdF9lcG9jaF9jYWNoZS5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL3Rlc3QvdGVzdF9lcG9jaF9jYWNoZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQUUsV0FBVyxFQUFFLFVBQVUsRUFBRSxNQUFNLHNDQUFzQyxDQUFDO0FBQy9FLE9BQU8sRUFBRSxVQUFVLEVBQUUsTUFBTSxvQ0FBb0MsQ0FBQztBQUNoRSxPQUFPLEtBQUssRUFBRSxpQkFBaUIsRUFBRSxNQUFNLGtDQUFrQyxDQUFDO0FBUTFFLE9BQU8sRUFDTCxLQUFLLFlBQVksRUFDakIsS0FBSyxtQkFBbUIsRUFDeEIsS0FBSyxrQkFBa0IsRUFFdkIsS0FBSyxPQUFPLEVBQ2IsTUFBTSxtQkFBbUIsQ0FBQztBQWMzQjs7Ozs7O0dBTUc7QUFDSCxxQkFBYSxjQUFlLFlBQVcsbUJBQW1CO0lBQ3hELE9BQU8sQ0FBQyxTQUFTLENBQW9CO0lBQ3JDLE9BQU8sQ0FBQyxlQUFlLENBQXlCO0lBQ2hELE9BQU8sQ0FBQyxXQUFXLENBQTZCO0lBQ2hELE9BQU8sQ0FBQyxlQUFlLENBQWtCO0lBQ3pDLE9BQU8sQ0FBQyxJQUFJLENBQWM7SUFDMUIsT0FBTyxDQUFDLG9CQUFvQixDQUFvQjtJQUNoRCxPQUFPLENBQUMsV0FBVyxDQUFvQjtJQUN2QyxPQUFPLENBQUMsMEJBQTBCLENBQUs7SUFFdkMsWUFBWSxXQUFXLEdBQUUsT0FBTy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