@aztec/epoch-cache 0.0.1-commit.7b86788 → 0.0.1-commit.7cbc774
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/README.md +211 -0
- package/dest/config.d.ts +3 -2
- package/dest/config.d.ts.map +1 -1
- package/dest/config.js +3 -1
- package/dest/epoch_cache.d.ts +77 -17
- package/dest/epoch_cache.d.ts.map +1 -1
- package/dest/epoch_cache.js +228 -72
- package/dest/test/test_epoch_cache.d.ts +19 -3
- package/dest/test/test_epoch_cache.d.ts.map +1 -1
- package/dest/test/test_epoch_cache.js +59 -12
- package/package.json +6 -7
- package/src/config.ts +9 -3
- package/src/epoch_cache.ts +287 -63
- package/src/test/test_epoch_cache.ts +84 -12
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aztec/epoch-cache",
|
|
3
|
-
"version": "0.0.1-commit.
|
|
3
|
+
"version": "0.0.1-commit.7cbc774",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"exports": {
|
|
6
6
|
".": "./dest/index.js",
|
|
@@ -26,17 +26,16 @@
|
|
|
26
26
|
"../package.common.json"
|
|
27
27
|
],
|
|
28
28
|
"dependencies": {
|
|
29
|
-
"@aztec/ethereum": "0.0.1-commit.
|
|
30
|
-
"@aztec/foundation": "0.0.1-commit.
|
|
31
|
-
"@aztec/l1-artifacts": "0.0.1-commit.
|
|
32
|
-
"@aztec/stdlib": "0.0.1-commit.
|
|
33
|
-
"@viem/anvil": "^0.0.10",
|
|
29
|
+
"@aztec/ethereum": "0.0.1-commit.7cbc774",
|
|
30
|
+
"@aztec/foundation": "0.0.1-commit.7cbc774",
|
|
31
|
+
"@aztec/l1-artifacts": "0.0.1-commit.7cbc774",
|
|
32
|
+
"@aztec/stdlib": "0.0.1-commit.7cbc774",
|
|
34
33
|
"dotenv": "^16.0.3",
|
|
35
34
|
"get-port": "^7.1.0",
|
|
36
35
|
"jest-mock-extended": "^4.0.0",
|
|
37
36
|
"tslib": "^2.4.0",
|
|
38
37
|
"viem": "npm:@aztec/viem@2.38.2",
|
|
39
|
-
"zod": "^
|
|
38
|
+
"zod": "^4"
|
|
40
39
|
},
|
|
41
40
|
"devDependencies": {
|
|
42
41
|
"@jest/globals": "^30.0.0",
|
package/src/config.ts
CHANGED
|
@@ -1,11 +1,17 @@
|
|
|
1
1
|
import { type L1ContractsConfig, getL1ContractsConfigEnvVars } from '@aztec/ethereum/config';
|
|
2
2
|
import { type L1ReaderConfig, getL1ReaderConfigFromEnv } from '@aztec/ethereum/l1-reader';
|
|
3
|
+
import { type PipelineConfig, getPipelineConfigEnvVars } from '@aztec/stdlib/config';
|
|
3
4
|
|
|
4
5
|
export type EpochCacheConfig = Pick<
|
|
5
|
-
L1ReaderConfig & L1ContractsConfig,
|
|
6
|
-
|
|
6
|
+
L1ReaderConfig & L1ContractsConfig & PipelineConfig,
|
|
7
|
+
| 'l1RpcUrls'
|
|
8
|
+
| 'l1ChainId'
|
|
9
|
+
| 'viemPollingIntervalMS'
|
|
10
|
+
| 'ethereumSlotDuration'
|
|
11
|
+
| 'l1HttpTimeoutMS'
|
|
12
|
+
| 'enableProposerPipelining'
|
|
7
13
|
>;
|
|
8
14
|
|
|
9
15
|
export function getEpochCacheConfigEnvVars(): EpochCacheConfig {
|
|
10
|
-
return { ...getL1ReaderConfigFromEnv(), ...getL1ContractsConfigEnvVars() };
|
|
16
|
+
return { ...getL1ReaderConfigFromEnv(), ...getL1ContractsConfigEnvVars(), ...getPipelineConfigEnvVars() };
|
|
11
17
|
}
|
package/src/epoch_cache.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { createEthereumChain } from '@aztec/ethereum/chain';
|
|
2
|
+
import { makeL1HttpTransport } from '@aztec/ethereum/client';
|
|
2
3
|
import { NoCommitteeError, RollupContract } from '@aztec/ethereum/contracts';
|
|
4
|
+
import { getFinalizedL1Block } from '@aztec/ethereum/queries';
|
|
3
5
|
import { EpochNumber, SlotNumber } from '@aztec/foundation/branded-types';
|
|
4
6
|
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
5
7
|
import { type Logger, createLogger } from '@aztec/foundation/log';
|
|
@@ -8,19 +10,25 @@ import {
|
|
|
8
10
|
type L1RollupConstants,
|
|
9
11
|
getEpochAtSlot,
|
|
10
12
|
getEpochNumberAtTimestamp,
|
|
13
|
+
getNextL1SlotTimestamp,
|
|
14
|
+
getSlotAtNextL1Block,
|
|
11
15
|
getSlotAtTimestamp,
|
|
12
16
|
getSlotRangeForEpoch,
|
|
17
|
+
getStartTimestampForEpoch,
|
|
13
18
|
getTimestampForSlot,
|
|
14
|
-
getTimestampRangeForEpoch,
|
|
15
19
|
} from '@aztec/stdlib/epoch-helpers';
|
|
16
20
|
|
|
17
|
-
import { createPublicClient, encodeAbiParameters,
|
|
21
|
+
import { createPublicClient, encodeAbiParameters, keccak256 } from 'viem';
|
|
18
22
|
|
|
19
23
|
import { type EpochCacheConfig, getEpochCacheConfigEnvVars } from './config.js';
|
|
20
24
|
|
|
25
|
+
/** When proposer pipelining is enabled, the proposer builds one slot ahead. */
|
|
26
|
+
export const PROPOSER_PIPELINING_SLOT_OFFSET = 1;
|
|
27
|
+
|
|
28
|
+
/** Flat return type for compound epoch/slot getters. */
|
|
21
29
|
export type EpochAndSlot = {
|
|
22
|
-
epoch: EpochNumber;
|
|
23
30
|
slot: SlotNumber;
|
|
31
|
+
epoch: EpochNumber;
|
|
24
32
|
ts: bigint;
|
|
25
33
|
};
|
|
26
34
|
|
|
@@ -34,13 +42,40 @@ export type EpochCommitteeInfo = {
|
|
|
34
42
|
|
|
35
43
|
export type SlotTag = 'now' | 'next' | SlotNumber;
|
|
36
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
|
+
|
|
37
61
|
export interface EpochCacheInterface {
|
|
38
62
|
getCommittee(slot: SlotTag | undefined): Promise<EpochCommitteeInfo>;
|
|
63
|
+
getSlotNow(): SlotNumber;
|
|
64
|
+
getTargetSlot(): SlotNumber;
|
|
65
|
+
getEpochNow(): EpochNumber;
|
|
66
|
+
getTargetEpoch(): EpochNumber;
|
|
39
67
|
getEpochAndSlotNow(): EpochAndSlot & { nowMs: bigint };
|
|
40
|
-
getEpochAndSlotInNextL1Slot(): EpochAndSlot & {
|
|
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
|
+
isProposerPipeliningEnabled(): boolean;
|
|
72
|
+
pipeliningOffset(): number;
|
|
73
|
+
isEscapeHatchOpen(epoch: EpochNumber): Promise<boolean>;
|
|
74
|
+
isEscapeHatchOpenAtSlot(slot: SlotTag): Promise<boolean>;
|
|
41
75
|
getProposerIndexEncoding(epoch: EpochNumber, slot: SlotNumber, seed: bigint): `0x${string}`;
|
|
42
76
|
computeProposerIndex(slot: SlotNumber, epoch: EpochNumber, seed: bigint, size: bigint): bigint;
|
|
43
77
|
getCurrentAndNextSlot(): { currentSlot: SlotNumber; nextSlot: SlotNumber };
|
|
78
|
+
getTargetAndNextSlot(): { targetSlot: SlotNumber; nextSlot: SlotNumber };
|
|
44
79
|
getProposerAttesterAddressInSlot(slot: SlotNumber): Promise<EthAddress | undefined>;
|
|
45
80
|
getRegisteredValidators(): Promise<EthAddress[]>;
|
|
46
81
|
isInCommittee(slot: SlotTag, validator: EthAddress): Promise<boolean>;
|
|
@@ -58,12 +93,17 @@ export interface EpochCacheInterface {
|
|
|
58
93
|
* Note: This class is very dependent on the system clock being in sync.
|
|
59
94
|
*/
|
|
60
95
|
export class EpochCache implements EpochCacheInterface {
|
|
61
|
-
|
|
62
|
-
|
|
96
|
+
/**
|
|
97
|
+
* Single map holding both resolved entries and in-flight promises.
|
|
98
|
+
* A `Promise` value means a fetch is in progress; concurrent callers await it.
|
|
99
|
+
*/
|
|
100
|
+
protected cache: Map<EpochNumber, CachedEpochEntry | Promise<CachedEpochEntry>> = new Map();
|
|
63
101
|
private allValidators: Set<string> = new Set();
|
|
64
102
|
private lastValidatorRefresh = 0;
|
|
65
103
|
private readonly log: Logger = createLogger('epoch-cache');
|
|
66
104
|
|
|
105
|
+
protected enableProposerPipelining: boolean;
|
|
106
|
+
|
|
67
107
|
constructor(
|
|
68
108
|
private rollup: RollupContract,
|
|
69
109
|
private readonly l1constants: L1RollupConstants & {
|
|
@@ -71,10 +111,12 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
71
111
|
lagInEpochsForRandao: number;
|
|
72
112
|
},
|
|
73
113
|
private readonly dateProvider: DateProvider = new DateProvider(),
|
|
74
|
-
protected readonly config = { cacheSize: 12, validatorRefreshIntervalSeconds: 60 },
|
|
114
|
+
protected readonly config = { cacheSize: 12, validatorRefreshIntervalSeconds: 60, enableProposerPipelining: false },
|
|
75
115
|
) {
|
|
116
|
+
this.enableProposerPipelining = this.config.enableProposerPipelining;
|
|
76
117
|
this.log.debug(`Initialized EpochCache`, {
|
|
77
118
|
l1constants,
|
|
119
|
+
enableProposerPipelining: this.enableProposerPipelining,
|
|
78
120
|
});
|
|
79
121
|
}
|
|
80
122
|
|
|
@@ -93,7 +135,7 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
93
135
|
const chain = createEthereumChain(config.l1RpcUrls, config.l1ChainId);
|
|
94
136
|
const publicClient = createPublicClient({
|
|
95
137
|
chain: chain.chainInfo,
|
|
96
|
-
transport:
|
|
138
|
+
transport: makeL1HttpTransport(config.l1RpcUrls, { timeout: config.l1HttpTimeoutMS }),
|
|
97
139
|
pollingInterval: config.viemPollingIntervalMS,
|
|
98
140
|
});
|
|
99
141
|
rollup = new RollupContract(publicClient, rollupOrAddress.toString());
|
|
@@ -108,6 +150,7 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
108
150
|
lagInEpochsForValidatorSet,
|
|
109
151
|
lagInEpochsForRandao,
|
|
110
152
|
targetCommitteeSize,
|
|
153
|
+
rollupManaLimit,
|
|
111
154
|
] = await Promise.all([
|
|
112
155
|
rollup.getL1StartBlock(),
|
|
113
156
|
rollup.getL1GenesisTime(),
|
|
@@ -117,6 +160,7 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
117
160
|
rollup.getLagInEpochsForValidatorSet(),
|
|
118
161
|
rollup.getLagInEpochsForRandao(),
|
|
119
162
|
rollup.getTargetCommitteeSize(),
|
|
163
|
+
rollup.getManaLimit(),
|
|
120
164
|
] as const);
|
|
121
165
|
|
|
122
166
|
const l1RollupConstants = {
|
|
@@ -129,43 +173,80 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
129
173
|
lagInEpochsForValidatorSet: Number(lagInEpochsForValidatorSet),
|
|
130
174
|
lagInEpochsForRandao: Number(lagInEpochsForRandao),
|
|
131
175
|
targetCommitteeSize: Number(targetCommitteeSize),
|
|
176
|
+
rollupManaLimit: Number(rollupManaLimit),
|
|
132
177
|
};
|
|
133
178
|
|
|
134
|
-
return new EpochCache(rollup, l1RollupConstants, deps.dateProvider
|
|
179
|
+
return new EpochCache(rollup, l1RollupConstants, deps.dateProvider, {
|
|
180
|
+
cacheSize: 12,
|
|
181
|
+
validatorRefreshIntervalSeconds: 60,
|
|
182
|
+
enableProposerPipelining: config.enableProposerPipelining,
|
|
183
|
+
});
|
|
135
184
|
}
|
|
136
185
|
|
|
137
186
|
public getL1Constants(): L1RollupConstants {
|
|
138
187
|
return this.l1constants;
|
|
139
188
|
}
|
|
140
189
|
|
|
190
|
+
public isProposerPipeliningEnabled(): boolean {
|
|
191
|
+
return this.enableProposerPipelining;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
public pipeliningOffset(): number {
|
|
195
|
+
return this.enableProposerPipelining ? PROPOSER_PIPELINING_SLOT_OFFSET : 0;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
public getSlotNow(): SlotNumber {
|
|
199
|
+
return this.getEpochAndSlotNow().slot;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
public getTargetSlot(): SlotNumber {
|
|
203
|
+
const slotNow = this.getSlotNow();
|
|
204
|
+
const offset = this.isProposerPipeliningEnabled() ? PROPOSER_PIPELINING_SLOT_OFFSET : 0;
|
|
205
|
+
return SlotNumber(slotNow + offset);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
public getEpochNow(): EpochNumber {
|
|
209
|
+
return this.getEpochAndSlotNow().epoch;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
public getTargetEpoch(): EpochNumber {
|
|
213
|
+
return getEpochAtSlot(this.getTargetSlot(), this.l1constants);
|
|
214
|
+
}
|
|
215
|
+
|
|
141
216
|
public getEpochAndSlotNow(): EpochAndSlot & { nowMs: bigint } {
|
|
142
217
|
const nowMs = BigInt(this.dateProvider.now());
|
|
143
218
|
const nowSeconds = nowMs / 1000n;
|
|
144
219
|
return { ...this.getEpochAndSlotAtTimestamp(nowSeconds), nowMs };
|
|
145
220
|
}
|
|
146
221
|
|
|
147
|
-
|
|
148
|
-
return
|
|
222
|
+
private getEpochAndSlotAtSlot(slot: SlotNumber): EpochAndSlot {
|
|
223
|
+
return this.getEpochAndSlotAtTimestamp(getTimestampForSlot(slot, this.l1constants));
|
|
149
224
|
}
|
|
150
225
|
|
|
151
|
-
|
|
152
|
-
const
|
|
153
|
-
const
|
|
154
|
-
return {
|
|
226
|
+
public getEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint } {
|
|
227
|
+
const nowSeconds = this.dateProvider.nowInSeconds();
|
|
228
|
+
const nextSlotTs = getNextL1SlotTimestamp(nowSeconds, this.l1constants);
|
|
229
|
+
return { ...this.getEpochAndSlotAtTimestamp(nextSlotTs), nowSeconds: BigInt(nowSeconds) };
|
|
155
230
|
}
|
|
156
231
|
|
|
157
|
-
public
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
232
|
+
public getTargetEpochAndSlotInNextL1Slot(): EpochAndSlot & { nowSeconds: bigint } {
|
|
233
|
+
if (!this.isProposerPipeliningEnabled()) {
|
|
234
|
+
return this.getEpochAndSlotInNextL1Slot();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
const result = this.getEpochAndSlotInNextL1Slot();
|
|
238
|
+
const offset = PROPOSER_PIPELINING_SLOT_OFFSET;
|
|
239
|
+
const targetSlot = SlotNumber(result.slot + offset);
|
|
240
|
+
return { ...result, slot: targetSlot, epoch: getEpochAtSlot(targetSlot, this.l1constants) };
|
|
161
241
|
}
|
|
162
242
|
|
|
163
243
|
private getEpochAndSlotAtTimestamp(ts: bigint): EpochAndSlot {
|
|
164
244
|
const slot = getSlotAtTimestamp(ts, this.l1constants);
|
|
245
|
+
const epoch = getEpochNumberAtTimestamp(ts, this.l1constants);
|
|
165
246
|
return {
|
|
166
|
-
epoch: getEpochNumberAtTimestamp(ts, this.l1constants),
|
|
167
|
-
ts: getTimestampForSlot(slot, this.l1constants),
|
|
168
247
|
slot,
|
|
248
|
+
epoch,
|
|
249
|
+
ts: getTimestampForSlot(slot, this.l1constants),
|
|
169
250
|
};
|
|
170
251
|
}
|
|
171
252
|
|
|
@@ -174,17 +255,8 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
174
255
|
return this.getCommittee(startSlot);
|
|
175
256
|
}
|
|
176
257
|
|
|
177
|
-
/**
|
|
178
|
-
* Returns whether the escape hatch is open for the given epoch.
|
|
179
|
-
*
|
|
180
|
-
* Uses the already-cached EpochCommitteeInfo when available. If not cached, it will fetch
|
|
181
|
-
* the epoch committee info (which includes the escape hatch flag) and return it.
|
|
182
|
-
*/
|
|
258
|
+
/** Returns whether the escape hatch is open for the given epoch. */
|
|
183
259
|
public async isEscapeHatchOpen(epoch: EpochNumber): Promise<boolean> {
|
|
184
|
-
const cached = this.cache.get(epoch);
|
|
185
|
-
if (cached) {
|
|
186
|
-
return cached.isEscapeHatchOpen;
|
|
187
|
-
}
|
|
188
260
|
const info = await this.getCommitteeForEpoch(epoch);
|
|
189
261
|
return info.isEscapeHatchOpen;
|
|
190
262
|
}
|
|
@@ -198,7 +270,7 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
198
270
|
public async isEscapeHatchOpenAtSlot(slot: SlotTag = 'now'): Promise<boolean> {
|
|
199
271
|
const epoch =
|
|
200
272
|
slot === 'now'
|
|
201
|
-
? this.
|
|
273
|
+
? this.getEpochNow()
|
|
202
274
|
: slot === 'next'
|
|
203
275
|
? this.getEpochAndSlotInNextL1Slot().epoch
|
|
204
276
|
: getEpochAtSlot(slot, this.l1constants);
|
|
@@ -207,33 +279,52 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
207
279
|
}
|
|
208
280
|
|
|
209
281
|
/**
|
|
210
|
-
* Get the current validator set
|
|
211
|
-
*
|
|
212
|
-
*
|
|
282
|
+
* Get the current validator set.
|
|
283
|
+
*
|
|
284
|
+
* Returns cached data if the entry is finalized or still fresh (queried less than one
|
|
285
|
+
* Ethereum slot ago). Stale non-finalized entries are re-queried, and concurrent callers
|
|
286
|
+
* coalesce on the same in-flight promise so the L1 query happens only once.
|
|
213
287
|
*/
|
|
214
288
|
public async getCommittee(slot: SlotTag = 'now'): Promise<EpochCommitteeInfo> {
|
|
215
289
|
const { epoch, ts } = this.getEpochAndTimestamp(slot);
|
|
216
290
|
|
|
217
|
-
|
|
218
|
-
|
|
291
|
+
const cached = this.cache.get(epoch);
|
|
292
|
+
|
|
293
|
+
// In-flight promise: another caller is already fetching this epoch — just await it.
|
|
294
|
+
if (cached instanceof Promise) {
|
|
295
|
+
return (await cached).data;
|
|
219
296
|
}
|
|
220
297
|
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
return epochData;
|
|
298
|
+
// Resolved entry: return it if finalized or still fresh.
|
|
299
|
+
if (cached && (cached.finalized || !this.isStale(cached))) {
|
|
300
|
+
return cached.data;
|
|
225
301
|
}
|
|
226
|
-
this.cache.set(epoch, epochData);
|
|
227
302
|
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
303
|
+
// Stale non-finalized entry: do a lightweight refresh first (check block hash + finalized ts).
|
|
304
|
+
// Only fall back to a full re-fetch if the L1 block was reorged.
|
|
305
|
+
if (cached) {
|
|
306
|
+
const promise = this.refreshStaleEntry(cached, epoch, ts);
|
|
307
|
+
this.cache.set(epoch, promise);
|
|
308
|
+
try {
|
|
309
|
+
return (await promise).data;
|
|
310
|
+
} catch (err) {
|
|
311
|
+
this.cache.set(epoch, cached);
|
|
312
|
+
throw err;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
232
315
|
|
|
233
|
-
|
|
316
|
+
// No entry at all: full fetch.
|
|
317
|
+
const promise = this.fetchAndCache(epoch, ts);
|
|
318
|
+
this.cache.set(epoch, promise);
|
|
319
|
+
try {
|
|
320
|
+
return (await promise).data;
|
|
321
|
+
} catch (err) {
|
|
322
|
+
this.cache.delete(epoch);
|
|
323
|
+
throw err;
|
|
324
|
+
}
|
|
234
325
|
}
|
|
235
326
|
|
|
236
|
-
private getEpochAndTimestamp(slot: SlotTag = 'now') {
|
|
327
|
+
private getEpochAndTimestamp(slot: SlotTag = 'now'): { epoch: EpochNumber; ts: bigint } {
|
|
237
328
|
if (slot === 'now') {
|
|
238
329
|
return this.getEpochAndSlotNow();
|
|
239
330
|
} else if (slot === 'next') {
|
|
@@ -243,22 +334,140 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
243
334
|
}
|
|
244
335
|
}
|
|
245
336
|
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
337
|
+
/** Evicts oldest cache entries (resolved or in-flight) beyond cacheSize. */
|
|
338
|
+
private purgeCache(): void {
|
|
339
|
+
if (this.cache.size <= this.config.cacheSize) {
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const toPurge = Array.from(this.cache.keys())
|
|
343
|
+
.sort((a, b) => Number(b - a))
|
|
344
|
+
.slice(this.config.cacheSize);
|
|
345
|
+
toPurge.forEach(key => this.cache.delete(key));
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
/** Returns true if a non-finalized cache entry is older than one Ethereum slot. */
|
|
349
|
+
private isStale(entry: CachedEpochEntry): boolean {
|
|
350
|
+
const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
|
|
351
|
+
return nowSeconds - entry.lastRefreshL1Timestamp >= BigInt(this.l1constants.ethereumSlotDuration);
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
/** Whether a cached epoch entry has been marked as finalized. Returns undefined if not cached or still in-flight. */
|
|
355
|
+
public isFinalized(epoch: EpochNumber): boolean | undefined {
|
|
356
|
+
const entry = this.cache.get(epoch);
|
|
357
|
+
if (!entry || entry instanceof Promise) {
|
|
358
|
+
return undefined;
|
|
359
|
+
}
|
|
360
|
+
return entry.finalized;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
/** Returns the latest L1 timestamp stored in the cached entry. Undefined if not cached or in-flight. */
|
|
364
|
+
public getCachedLastRefreshL1Timestamp(epoch: EpochNumber): bigint | undefined {
|
|
365
|
+
const entry = this.cache.get(epoch);
|
|
366
|
+
if (!entry || entry instanceof Promise) {
|
|
367
|
+
return undefined;
|
|
368
|
+
}
|
|
369
|
+
return entry.lastRefreshL1Timestamp;
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
/** Computes the sampling timestamp for an epoch's committee data. */
|
|
373
|
+
private getSamplingTimestamp(epoch: EpochNumber): bigint {
|
|
374
|
+
const { lagInEpochsForRandao, epochDuration, slotDuration } = this.l1constants;
|
|
375
|
+
const epochStartTs = getStartTimestampForEpoch(epoch, this.l1constants);
|
|
376
|
+
return epochStartTs - BigInt(lagInEpochsForRandao) * BigInt(epochDuration) * BigInt(slotDuration);
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/**
|
|
380
|
+
* Lightweight refresh for a stale non-finalized entry. Queries only the block hash at
|
|
381
|
+
* the original block number and the finalized block timestamp — avoids the expensive
|
|
382
|
+
* getCommitteeAt and getSampleSeedAt calls on the rollup contract.
|
|
383
|
+
*
|
|
384
|
+
* If the block hash still matches (no L1 reorg), we keep the existing data and just
|
|
385
|
+
* update the provenance timestamp. If the finalized block has caught up, we promote the
|
|
386
|
+
* entry to finalized. If there was a reorg (hash mismatch), we fall back to a full fetch.
|
|
387
|
+
*/
|
|
388
|
+
private async refreshStaleEntry(stale: CachedEpochEntry, epoch: EpochNumber, ts: bigint): Promise<CachedEpochEntry> {
|
|
389
|
+
const [blockAtOriginal, l1FinalizedBlock, latestBlock] = await Promise.all([
|
|
390
|
+
this.rollup.client.getBlock({ blockNumber: stale.lastQueryL1BlockNumber, includeTransactions: false }),
|
|
391
|
+
getFinalizedL1Block(this.rollup.client),
|
|
392
|
+
this.rollup.client.getBlock({ includeTransactions: false }),
|
|
393
|
+
]);
|
|
394
|
+
|
|
395
|
+
if (blockAtOriginal.hash === stale.lastQueryL1BlockHash) {
|
|
396
|
+
// No reorg: the data is still valid. Check if we can now mark it as finalized.
|
|
397
|
+
const samplingTs = this.getSamplingTimestamp(epoch);
|
|
398
|
+
const finalized =
|
|
399
|
+
!!(stale.data.committee && stale.data.committee.length > 0) &&
|
|
400
|
+
l1FinalizedBlock !== undefined &&
|
|
401
|
+
samplingTs <= l1FinalizedBlock.timestamp;
|
|
402
|
+
|
|
403
|
+
const refreshed: CachedEpochEntry = {
|
|
404
|
+
...stale,
|
|
405
|
+
lastRefreshL1Timestamp: latestBlock.timestamp,
|
|
406
|
+
finalized,
|
|
407
|
+
};
|
|
408
|
+
this.cache.set(epoch, refreshed);
|
|
409
|
+
return refreshed;
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// Reorg detected: block hash mismatch. Do a full re-fetch.
|
|
413
|
+
// Pass the already-fetched block timestamps to avoid redundant queries.
|
|
414
|
+
this.log.warn(`L1 reorg detected for epoch ${epoch}: block ${stale.lastQueryL1BlockNumber} hash changed`, {
|
|
415
|
+
epoch,
|
|
416
|
+
expectedHash: stale.lastQueryL1BlockHash,
|
|
417
|
+
actualHash: blockAtOriginal.hash,
|
|
418
|
+
});
|
|
419
|
+
return this.fetchAndCache(epoch, ts, { latestBlock, finalizedBlock: l1FinalizedBlock });
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Fetches committee data from L1, determines finalization status, and stores in the cache.
|
|
424
|
+
*
|
|
425
|
+
* Uses `lagInEpochsForRandao` (the binding constraint, always <= lagInEpochsForValidatorSet)
|
|
426
|
+
* and computes the sampling timestamp from the epoch start to match the L1 contract's logic.
|
|
427
|
+
*
|
|
428
|
+
* When called from refreshStaleEntry after a reorg, the latest and finalized blocks are
|
|
429
|
+
* passed in to avoid redundant L1 queries.
|
|
430
|
+
*/
|
|
431
|
+
private async fetchAndCache(
|
|
432
|
+
epoch: EpochNumber,
|
|
433
|
+
ts: bigint,
|
|
434
|
+
prefetched?: { latestBlock: L1BlockInfo; finalizedBlock: { timestamp: bigint } | undefined },
|
|
435
|
+
): Promise<CachedEpochEntry> {
|
|
436
|
+
const [committee, seedBuffer, latestBlock, finalizedBlock, isEscapeHatchOpen] = await Promise.all([
|
|
249
437
|
this.rollup.getCommitteeAt(ts),
|
|
250
438
|
this.rollup.getSampleSeedAt(ts),
|
|
251
|
-
this.rollup.client.getBlock({ includeTransactions: false })
|
|
439
|
+
prefetched?.latestBlock ?? this.rollup.client.getBlock({ includeTransactions: false }),
|
|
440
|
+
prefetched !== undefined ? prefetched.finalizedBlock : getFinalizedL1Block(this.rollup.client),
|
|
252
441
|
this.rollup.isEscapeHatchOpen(epoch),
|
|
253
442
|
]);
|
|
254
|
-
|
|
255
|
-
const
|
|
256
|
-
|
|
443
|
+
|
|
444
|
+
const samplingTs = this.getSamplingTimestamp(epoch);
|
|
445
|
+
|
|
446
|
+
if (samplingTs > latestBlock.timestamp) {
|
|
257
447
|
throw new Error(
|
|
258
|
-
`Cannot query committee for future epoch ${epoch}
|
|
448
|
+
`Cannot query committee for future epoch ${epoch}: ` +
|
|
449
|
+
`sampling timestamp ${samplingTs} is beyond latest L1 block at ${latestBlock.timestamp}. ` +
|
|
450
|
+
`Check your Ethereum node is synced.`,
|
|
259
451
|
);
|
|
260
452
|
}
|
|
261
|
-
|
|
453
|
+
|
|
454
|
+
// Empty committees are never marked finalized so they always get re-queried after TTL.
|
|
455
|
+
// If L1 has no finalized block yet (devnet startup), entries stay unfinalized.
|
|
456
|
+
const hasCommittee = !!(committee && committee.length > 0);
|
|
457
|
+
const finalized = hasCommittee && finalizedBlock !== undefined && samplingTs <= finalizedBlock.timestamp;
|
|
458
|
+
const data: EpochCommitteeInfo = { committee, seed: seedBuffer.toBigInt(), epoch, isEscapeHatchOpen };
|
|
459
|
+
const entry: CachedEpochEntry = {
|
|
460
|
+
data,
|
|
461
|
+
lastQueryL1BlockNumber: latestBlock.number!,
|
|
462
|
+
lastQueryL1BlockHash: latestBlock.hash!,
|
|
463
|
+
lastRefreshL1Timestamp: latestBlock.timestamp,
|
|
464
|
+
finalized,
|
|
465
|
+
};
|
|
466
|
+
|
|
467
|
+
this.cache.set(epoch, entry);
|
|
468
|
+
this.purgeCache();
|
|
469
|
+
|
|
470
|
+
return entry;
|
|
262
471
|
}
|
|
263
472
|
|
|
264
473
|
/**
|
|
@@ -283,17 +492,31 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
283
492
|
return BigInt(keccak256(this.getProposerIndexEncoding(epoch, slot, seed))) % size;
|
|
284
493
|
}
|
|
285
494
|
|
|
286
|
-
/** Returns the current and next L2 slot
|
|
495
|
+
/** Returns the current and next L2 slot in next eth L1 Slot. */
|
|
287
496
|
public getCurrentAndNextSlot(): { currentSlot: SlotNumber; nextSlot: SlotNumber } {
|
|
288
|
-
const
|
|
497
|
+
const currentSlot = this.getSlotNow();
|
|
289
498
|
const next = this.getEpochAndSlotInNextL1Slot();
|
|
290
499
|
|
|
291
500
|
return {
|
|
292
|
-
currentSlot
|
|
501
|
+
currentSlot,
|
|
293
502
|
nextSlot: next.slot,
|
|
294
503
|
};
|
|
295
504
|
}
|
|
296
505
|
|
|
506
|
+
/** Returns the target and next L2 slot in the next L1 slot. */
|
|
507
|
+
public getTargetAndNextSlot(): { targetSlot: SlotNumber; nextSlot: SlotNumber } {
|
|
508
|
+
const nowSeconds = BigInt(this.dateProvider.nowInSeconds());
|
|
509
|
+
const offset = this.isProposerPipeliningEnabled() ? PROPOSER_PIPELINING_SLOT_OFFSET : 0;
|
|
510
|
+
|
|
511
|
+
const currentSlot = getSlotAtTimestamp(nowSeconds, this.l1constants);
|
|
512
|
+
const targetSlot = SlotNumber(currentSlot + offset);
|
|
513
|
+
|
|
514
|
+
const nextL2SlotOnL1 = getSlotAtNextL1Block(nowSeconds, this.l1constants);
|
|
515
|
+
const nextSlot = SlotNumber(nextL2SlotOnL1 + offset);
|
|
516
|
+
|
|
517
|
+
return { targetSlot, nextSlot };
|
|
518
|
+
}
|
|
519
|
+
|
|
297
520
|
/**
|
|
298
521
|
* Get the proposer attester address in the given L2 slot
|
|
299
522
|
* @returns The proposer attester address. If the committee does not exist, we throw a NoCommitteeError.
|
|
@@ -372,10 +595,11 @@ export class EpochCache implements EpochCacheInterface {
|
|
|
372
595
|
async getRegisteredValidators(): Promise<EthAddress[]> {
|
|
373
596
|
const validatorRefreshIntervalMs = this.config.validatorRefreshIntervalSeconds * 1000;
|
|
374
597
|
const validatorRefreshTime = this.lastValidatorRefresh + validatorRefreshIntervalMs;
|
|
375
|
-
|
|
376
|
-
|
|
598
|
+
const now = this.dateProvider.now();
|
|
599
|
+
if (validatorRefreshTime < now) {
|
|
600
|
+
const currentSet = await this.rollup.getAttesters(BigInt(Math.floor(now / 1000)));
|
|
377
601
|
this.allValidators = new Set(currentSet.map(v => v.toString()));
|
|
378
|
-
this.lastValidatorRefresh =
|
|
602
|
+
this.lastValidatorRefresh = now;
|
|
379
603
|
}
|
|
380
604
|
return Array.from(this.allValidators.keys()).map(v => EthAddress.fromString(v));
|
|
381
605
|
}
|