@aztec-labs/aztec-node 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.
Files changed (83) hide show
  1. package/README.md +15 -0
  2. package/dest/aztec-node/block_response_helpers.d.ts +25 -0
  3. package/dest/aztec-node/block_response_helpers.d.ts.map +1 -0
  4. package/dest/aztec-node/block_response_helpers.js +112 -0
  5. package/dest/aztec-node/config.d.ts +52 -0
  6. package/dest/aztec-node/config.d.ts.map +1 -0
  7. package/dest/aztec-node/config.js +129 -0
  8. package/dest/aztec-node/node_metrics.d.ts +12 -0
  9. package/dest/aztec-node/node_metrics.d.ts.map +1 -0
  10. package/dest/aztec-node/node_metrics.js +36 -0
  11. package/dest/aztec-node/node_public_calls_simulator.d.ts +108 -0
  12. package/dest/aztec-node/node_public_calls_simulator.d.ts.map +1 -0
  13. package/dest/aztec-node/node_public_calls_simulator.js +380 -0
  14. package/dest/aztec-node/public_data_overrides.d.ts +13 -0
  15. package/dest/aztec-node/public_data_overrides.d.ts.map +1 -0
  16. package/dest/aztec-node/public_data_overrides.js +21 -0
  17. package/dest/aztec-node/register_node_rpc_handlers.d.ts +11 -0
  18. package/dest/aztec-node/register_node_rpc_handlers.d.ts.map +1 -0
  19. package/dest/aztec-node/register_node_rpc_handlers.js +48 -0
  20. package/dest/aztec-node/server.d.ts +281 -0
  21. package/dest/aztec-node/server.d.ts.map +1 -0
  22. package/dest/aztec-node/server.js +1235 -0
  23. package/dest/bin/index.d.ts +3 -0
  24. package/dest/bin/index.d.ts.map +1 -0
  25. package/dest/bin/index.js +57 -0
  26. package/dest/factory.d.ts +33 -0
  27. package/dest/factory.d.ts.map +1 -0
  28. package/dest/factory.js +539 -0
  29. package/dest/index.d.ts +5 -0
  30. package/dest/index.d.ts.map +1 -0
  31. package/dest/index.js +4 -0
  32. package/dest/modules/block_parameter.d.ts +25 -0
  33. package/dest/modules/block_parameter.d.ts.map +1 -0
  34. package/dest/modules/block_parameter.js +100 -0
  35. package/dest/modules/node_block_provider.d.ts +19 -0
  36. package/dest/modules/node_block_provider.d.ts.map +1 -0
  37. package/dest/modules/node_block_provider.js +112 -0
  38. package/dest/modules/node_tx_receipt.d.ts +24 -0
  39. package/dest/modules/node_tx_receipt.d.ts.map +1 -0
  40. package/dest/modules/node_tx_receipt.js +70 -0
  41. package/dest/modules/node_world_state_queries.d.ts +65 -0
  42. package/dest/modules/node_world_state_queries.d.ts.map +1 -0
  43. package/dest/modules/node_world_state_queries.js +270 -0
  44. package/dest/sentinel/config.d.ts +9 -0
  45. package/dest/sentinel/config.d.ts.map +1 -0
  46. package/dest/sentinel/config.js +39 -0
  47. package/dest/sentinel/factory.d.ts +11 -0
  48. package/dest/sentinel/factory.d.ts.map +1 -0
  49. package/dest/sentinel/factory.js +24 -0
  50. package/dest/sentinel/index.d.ts +3 -0
  51. package/dest/sentinel/index.d.ts.map +1 -0
  52. package/dest/sentinel/index.js +1 -0
  53. package/dest/sentinel/sentinel.d.ts +217 -0
  54. package/dest/sentinel/sentinel.d.ts.map +1 -0
  55. package/dest/sentinel/sentinel.js +551 -0
  56. package/dest/sentinel/store.d.ts +35 -0
  57. package/dest/sentinel/store.d.ts.map +1 -0
  58. package/dest/sentinel/store.js +182 -0
  59. package/dest/test/index.d.ts +31 -0
  60. package/dest/test/index.d.ts.map +1 -0
  61. package/dest/test/index.js +1 -0
  62. package/package.json +118 -0
  63. package/src/aztec-node/block_response_helpers.ts +161 -0
  64. package/src/aztec-node/config.ts +216 -0
  65. package/src/aztec-node/node_metrics.ts +49 -0
  66. package/src/aztec-node/node_public_calls_simulator.ts +437 -0
  67. package/src/aztec-node/public_data_overrides.ts +35 -0
  68. package/src/aztec-node/register_node_rpc_handlers.ts +45 -0
  69. package/src/aztec-node/server.ts +1155 -0
  70. package/src/bin/index.ts +77 -0
  71. package/src/factory.ts +704 -0
  72. package/src/index.ts +4 -0
  73. package/src/modules/block_parameter.ts +93 -0
  74. package/src/modules/node_block_provider.ts +149 -0
  75. package/src/modules/node_tx_receipt.ts +115 -0
  76. package/src/modules/node_world_state_queries.ts +373 -0
  77. package/src/sentinel/README.md +103 -0
  78. package/src/sentinel/config.ts +49 -0
  79. package/src/sentinel/factory.ts +46 -0
  80. package/src/sentinel/index.ts +8 -0
  81. package/src/sentinel/sentinel.ts +694 -0
  82. package/src/sentinel/store.ts +193 -0
  83. package/src/test/index.ts +32 -0
@@ -0,0 +1,373 @@
1
+ import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec-labs/constants';
2
+ import { BlockNumber, type EpochNumber } from '@aztec-labs/foundation/branded-types';
3
+ import { chunkBy } from '@aztec-labs/foundation/collection';
4
+ import { Fr } from '@aztec-labs/foundation/curves/bn254';
5
+ import { type Logger, createLogger } from '@aztec-labs/foundation/log';
6
+ import { sleep } from '@aztec-labs/foundation/sleep';
7
+ import { MembershipWitness, type SiblingPath } from '@aztec-labs/foundation/trees';
8
+ import type { AztecAddress } from '@aztec-labs/stdlib/aztec-address';
9
+ import {
10
+ type BlockHash,
11
+ type BlockParameter,
12
+ type DataInBlock,
13
+ type L2BlockSource,
14
+ type NormalizedBlockParameter,
15
+ inspectBlockParameter,
16
+ } from '@aztec-labs/stdlib/block';
17
+ import { computePublicDataTreeLeafSlot } from '@aztec-labs/stdlib/hash';
18
+ import type { WorldStateSynchronizer } from '@aztec-labs/stdlib/interfaces/server';
19
+ import type { L1ToL2MessageSource, L2ToL1MembershipWitness } from '@aztec-labs/stdlib/messaging';
20
+ import {
21
+ MerkleTreeId,
22
+ type NullifierLeafPreimage,
23
+ NullifierMembershipWitness,
24
+ type PublicDataTreeLeafPreimage,
25
+ PublicDataWitness,
26
+ } from '@aztec-labs/stdlib/trees';
27
+ import type { TxHash } from '@aztec-labs/stdlib/tx';
28
+ import { WorldStateSynchronizerError } from '@aztec-labs/world-state';
29
+
30
+ import { normalizeBlockParameter } from './block_parameter.js';
31
+
32
+ /** Attempts at resolving a query and syncing world state to it before giving up (see {@link NodeWorldStateQueries.getWorldState}). */
33
+ const WORLD_STATE_SYNC_ATTEMPTS = 3;
34
+
35
+ /** Delay between world-state sync attempts. */
36
+ const WORLD_STATE_SYNC_RETRY_DELAY_MS = 100;
37
+
38
+ /** Dependencies required to build a {@link NodeWorldStateQueries}. */
39
+ export interface NodeWorldStateQueriesDeps {
40
+ worldStateSynchronizer: WorldStateSynchronizer;
41
+ blockSource: L2BlockSource;
42
+ l1ToL2MessageSource: L1ToL2MessageSource;
43
+ log?: Logger;
44
+ }
45
+
46
+ /**
47
+ * Serves the node's Merkle-tree and membership-witness queries against committed world-state at a
48
+ * requested block. Extracted from `AztecNodeService` so the block-resolution and reorg-aware sync logic
49
+ * can be unit-tested without standing up the whole node, and to keep `server.ts` smaller.
50
+ */
51
+ export class NodeWorldStateQueries {
52
+ private readonly worldStateSynchronizer: WorldStateSynchronizer;
53
+ private readonly blockSource: L2BlockSource;
54
+ private readonly l1ToL2MessageSource: L1ToL2MessageSource;
55
+ private readonly log: Logger;
56
+
57
+ constructor(deps: NodeWorldStateQueriesDeps) {
58
+ this.worldStateSynchronizer = deps.worldStateSynchronizer;
59
+ this.blockSource = deps.blockSource;
60
+ this.l1ToL2MessageSource = deps.l1ToL2MessageSource;
61
+ this.log = deps.log ?? createLogger('node:world-state-queries');
62
+ }
63
+
64
+ public async findLeavesIndexes(
65
+ referenceBlock: BlockParameter,
66
+ treeId: MerkleTreeId,
67
+ leafValues: Fr[],
68
+ ): Promise<(DataInBlock<bigint> | undefined)[]> {
69
+ const committedDb = await this.getWorldState(referenceBlock);
70
+ const maybeIndices = await committedDb.findLeafIndices(
71
+ treeId,
72
+ leafValues.map(x => x.toBuffer()),
73
+ );
74
+ // Filter out undefined values to query block numbers only for found leaves
75
+ const definedIndices = maybeIndices.filter(x => x !== undefined);
76
+
77
+ // Now we find the block numbers for the defined indices
78
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
79
+
80
+ // Build a map from leaf index to block number
81
+ const indexToBlockNumber = new Map<bigint, BlockNumber>();
82
+ for (let i = 0; i < definedIndices.length; i++) {
83
+ const blockNumber = blockNumbers[i];
84
+ if (blockNumber === undefined) {
85
+ throw new Error(
86
+ `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
87
+ );
88
+ }
89
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
90
+ }
91
+
92
+ // Get unique block numbers in order to optimize num calls to getLeafValue function.
93
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
94
+
95
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
96
+ const blockHashes = await Promise.all(
97
+ uniqueBlockNumbers.map(blockNumber => {
98
+ return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
99
+ }),
100
+ );
101
+
102
+ // Build a map from block number to block hash
103
+ const blockNumberToHash = new Map<BlockNumber, BlockHash>();
104
+ for (let i = 0; i < uniqueBlockNumbers.length; i++) {
105
+ const blockHash = blockHashes[i];
106
+ if (blockHash === undefined) {
107
+ throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
108
+ }
109
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
110
+ }
111
+
112
+ // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
113
+ return maybeIndices.map(index => {
114
+ if (index === undefined) {
115
+ return undefined;
116
+ }
117
+ const blockNumber = indexToBlockNumber.get(index);
118
+ if (blockNumber === undefined) {
119
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
120
+ }
121
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
122
+ if (l2BlockHash === undefined) {
123
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
124
+ }
125
+ return {
126
+ l2BlockNumber: blockNumber,
127
+ l2BlockHash,
128
+ data: index,
129
+ };
130
+ });
131
+ }
132
+
133
+ public async getBlockHashMembershipWitness(
134
+ referenceBlock: BlockParameter,
135
+ blockHash: BlockHash,
136
+ ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
137
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
138
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
139
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
140
+ const referenceBlockNumber = await this.#resolveBlockNumber(referenceBlock);
141
+ if (referenceBlockNumber === BlockNumber.ZERO) {
142
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
143
+ return undefined;
144
+ }
145
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
146
+ const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
147
+ return pathAndIndex === undefined
148
+ ? undefined
149
+ : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
150
+ }
151
+
152
+ public async getNoteHashMembershipWitness(
153
+ referenceBlock: BlockParameter,
154
+ noteHash: Fr,
155
+ ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
156
+ const committedDb = await this.getWorldState(referenceBlock);
157
+ const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
158
+ MerkleTreeId.NOTE_HASH_TREE,
159
+ [noteHash],
160
+ );
161
+ return pathAndIndex === undefined
162
+ ? undefined
163
+ : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
164
+ }
165
+
166
+ public async getL1ToL2MessageMembershipWitness(
167
+ referenceBlock: BlockParameter,
168
+ l1ToL2Message: Fr,
169
+ ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
170
+ const db = await this.getWorldState(referenceBlock);
171
+ const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
172
+ if (!witness) {
173
+ return undefined;
174
+ }
175
+
176
+ // REFACTOR: Return a MembershipWitness object
177
+ return [witness.index, witness.path];
178
+ }
179
+
180
+ public getL1ToL2MessageIndex(l1ToL2Message: Fr): Promise<bigint | undefined> {
181
+ return this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
182
+ }
183
+
184
+ /**
185
+ * Returns all the L2 to L1 messages in an epoch (empty array if the epoch is not found). The public
186
+ * `AztecNodeService.getL2ToL1Messages` that delegates here is deprecated in favor of
187
+ * {@link getL2ToL1MembershipWitness}.
188
+ * @param epoch - The epoch at which to get the data.
189
+ */
190
+ public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
191
+ const blocks = await this.blockSource.getBlocks({ epoch, onlyCheckpointed: true });
192
+ const blocksInCheckpoints = chunkBy(blocks, block => block.header.globalVariables.slotNumber);
193
+ return blocksInCheckpoints.map(slotBlocks =>
194
+ slotBlocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
195
+ );
196
+ }
197
+
198
+ /**
199
+ * Returns the L2-to-L1 membership witness for a message in `txHash`. Passthrough to the
200
+ * archiver's locally-cached resolver — see {@link Archiver.getL2ToL1MembershipWitness}.
201
+ */
202
+ public getL2ToL1MembershipWitness(
203
+ txHash: TxHash,
204
+ message: Fr,
205
+ messageIndexInTx?: number,
206
+ ): Promise<L2ToL1MembershipWitness | undefined> {
207
+ return this.blockSource.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
208
+ }
209
+
210
+ public async getNullifierMembershipWitness(
211
+ referenceBlock: BlockParameter,
212
+ nullifier: Fr,
213
+ ): Promise<NullifierMembershipWitness | undefined> {
214
+ const db = await this.getWorldState(referenceBlock);
215
+ const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
216
+ if (!witness) {
217
+ return undefined;
218
+ }
219
+
220
+ const { index, path } = witness;
221
+ const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
222
+ if (!leafPreimage) {
223
+ return undefined;
224
+ }
225
+
226
+ return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
227
+ }
228
+
229
+ public async getLowNullifierMembershipWitness(
230
+ referenceBlock: BlockParameter,
231
+ nullifier: Fr,
232
+ ): Promise<NullifierMembershipWitness | undefined> {
233
+ const committedDb = await this.getWorldState(referenceBlock);
234
+ const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
235
+ if (!findResult) {
236
+ return undefined;
237
+ }
238
+ const { index, alreadyPresent } = findResult;
239
+ if (alreadyPresent) {
240
+ throw new Error(
241
+ `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
242
+ );
243
+ }
244
+ const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
245
+
246
+ const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
247
+ return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
248
+ }
249
+
250
+ async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
251
+ const committedDb = await this.getWorldState(referenceBlock);
252
+ const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
253
+ if (!lowLeafResult) {
254
+ return undefined;
255
+ } else {
256
+ const preimage = (await committedDb.getLeafPreimage(
257
+ MerkleTreeId.PUBLIC_DATA_TREE,
258
+ lowLeafResult.index,
259
+ )) as PublicDataTreeLeafPreimage;
260
+ const path = await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
261
+ return new PublicDataWitness(lowLeafResult.index, preimage, path);
262
+ }
263
+ }
264
+
265
+ public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
266
+ const committedDb = await this.getWorldState(referenceBlock);
267
+ const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
268
+
269
+ const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
270
+ if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
271
+ return Fr.ZERO;
272
+ }
273
+ const preimage = (await committedDb.getLeafPreimage(
274
+ MerkleTreeId.PUBLIC_DATA_TREE,
275
+ lowLeafResult.index,
276
+ )) as PublicDataTreeLeafPreimage;
277
+ return preimage.leaf.value;
278
+ }
279
+
280
+ /**
281
+ * Returns an instance of MerkleTreeOperations having first ensured the world state is synced to the requested
282
+ * block on the correct fork. Every query variant is resolved to a concrete (block number, block hash), which is
283
+ * threaded through both the sync and the snapshot read so a reorg that replaced the block at that height is
284
+ * detected rather than served silently. Transient failures — a prune landing between resolution and sync, or a
285
+ * fork flip caught at either the sync or the snapshot stage — are retried a few times, re-resolving the query
286
+ * against the updated chain each time; terminal failures — an unknown block hash at resolution, or a block whose
287
+ * history world state has pruned away — are thrown immediately.
288
+ * @param block - The block parameter (block number, block hash, or tag) at which to get the data.
289
+ * @returns An instance of a committed MerkleTreeOperations
290
+ */
291
+ public async getWorldState(block: BlockParameter) {
292
+ const query = normalizeBlockParameter(block);
293
+
294
+ for (let attempt = 1; ; attempt++) {
295
+ try {
296
+ return await this.#resolveWorldState(query);
297
+ } catch (err) {
298
+ if (attempt >= WORLD_STATE_SYNC_ATTEMPTS || !(err instanceof WorldStateSynchronizerError)) {
299
+ throw err;
300
+ }
301
+ this.log.verbose(`Retrying world state query after sync failure: ${err.message}`, {
302
+ attempt,
303
+ block: inspectBlockParameter(block),
304
+ });
305
+ await sleep(WORLD_STATE_SYNC_RETRY_DELAY_MS);
306
+ }
307
+ }
308
+ }
309
+
310
+ /**
311
+ * Resolves `query` to a concrete (block number, block hash), syncs world state to that exact fork, and returns
312
+ * the committed db (for `proposed` queries) or the fork-verified snapshot at the resolved block.
313
+ */
314
+ async #resolveWorldState(query: NormalizedBlockParameter) {
315
+ // User requests 'latest on the current fork', so the committed db is returned unverified
316
+ if ('tag' in query && query.tag === 'proposed') {
317
+ this.log.debug(`Using committed db for latest block`);
318
+ await this.worldStateSynchronizer.syncImmediate();
319
+ return this.worldStateSynchronizer.getCommitted();
320
+ }
321
+
322
+ // Resolve the query against the block source BEFORE syncing to a concrete (number, hash), and drive the sync to
323
+ // that exact fork. Resolving after the sync races the block source: the resolved tip can advance past what world
324
+ // state synced while the sync is in flight. Passing the hash makes the sync reorg-aware — it barriers until the
325
+ // archive-tree commit for that block has landed and verifies it matches the requested fork, throwing otherwise.
326
+ const { blockNumber, blockHash } = await this.#resolveBlockNumberAndHash(query);
327
+ const blockSyncedTo = await this.worldStateSynchronizer.syncImmediate(blockNumber, blockHash);
328
+
329
+ // The fork could flip between it returning and the snapshot being read, so getVerifiedSnapshot pins the
330
+ // returned view to the resolved fork (re-resolved by the retry loop on mismatch).
331
+ this.log.debug(`Using verified snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
332
+ return await this.worldStateSynchronizer.getVerifiedSnapshot(blockNumber, blockHash);
333
+ }
334
+
335
+ /** Resolves any {@link BlockParameter} variant to its concrete `(blockNumber, blockHash)` via the block source. */
336
+ async #resolveBlockNumberAndHash(
337
+ query: NormalizedBlockParameter,
338
+ ): Promise<{ blockNumber: BlockNumber; blockHash: BlockHash }> {
339
+ const blockData = await this.blockSource.getBlockData(query);
340
+ if (blockData === undefined) {
341
+ this.#throwOnUndefinedBlockData(query);
342
+ }
343
+ return { blockNumber: blockData.header.getBlockNumber(), blockHash: blockData.blockHash };
344
+ }
345
+
346
+ /** Resolves any {@link BlockParameter} variant to a concrete block number. */
347
+ async #resolveBlockNumber(block: BlockParameter): Promise<BlockNumber> {
348
+ const blockQuery = normalizeBlockParameter(block);
349
+ const blockNumber = await this.blockSource.getBlockNumber(blockQuery);
350
+ if (blockNumber === undefined) {
351
+ this.#throwOnUndefinedBlockData(blockQuery);
352
+ }
353
+ return blockNumber;
354
+ }
355
+
356
+ /**
357
+ * Hash and archive misses are terminal (an unknown block, likely a reorg); tag and number misses are transient —
358
+ * the block may have been pruned between the tag->number resolution and this data read, or may simply not have
359
+ * arrived yet — and surface as {@link WorldStateSynchronizerError} so the retry loop re-resolves against the
360
+ * current chain.
361
+ */
362
+ #throwOnUndefinedBlockData(query: NormalizedBlockParameter): never {
363
+ if ('hash' in query) {
364
+ throw new Error(
365
+ `Block hash ${query.hash.toString()} not found when resolving query. If the node API has been queried with anchor block hash possibly a reorg has occurred.`,
366
+ );
367
+ }
368
+ if ('archive' in query) {
369
+ throw new Error(`Block with archive ${query.archive.toString()} not found when resolving query.`);
370
+ }
371
+ throw new WorldStateSynchronizerError(`Block not found for ${inspectBlockParameter(query)} when resolving query.`);
372
+ }
373
+ }
@@ -0,0 +1,103 @@
1
+ # Sentinel
2
+
3
+ The Sentinel watches every committee member's behaviour each L2 slot, aggregates it into per-epoch performance once each epoch is fully observed, and emits inactivity slash payloads to the slasher.
4
+
5
+ ## Responsibilities
6
+
7
+ - Classify per-slot proposer/attestor behaviour from local node observations.
8
+ - Persist a sliding window of per-slot history per validator.
9
+ - Roll up that history into per-epoch performance after each epoch ends.
10
+ - Decide which validators have been inactive for `slashInactivityConsecutiveEpochThreshold` consecutive epochs and emit `WANT_TO_SLASH_EVENT` with `OffenseType.INACTIVITY`.
11
+ - Expose validator stats to RPC consumers (`getValidatorStats`, `computeStats`).
12
+
13
+ The sentinel is one of several watchers registered with the slasher; it does not vote or publish to L1 itself.
14
+
15
+ ## Inputs
16
+
17
+ | Source | What it provides |
18
+ |---|---|
19
+ | `EpochCache` | Slot/epoch helpers, committee + proposer for a slot, escape-hatch state |
20
+ | `L2BlockSource` (archiver) | Synced slot, `getCheckpoint({ slot })`, `getL2Tips()`, block headers |
21
+ | `P2PClient` | `getCheckpointAttestationsForSlot(slot, payloadHash)`, `hasBlockProposalsForSlot(slot)` |
22
+ | `CheckpointReexecutionTracker` | Local re-execution outcome for the proposal at each slot (`valid` / `invalid` / `unvalidated`) — populated by the validator client's `ProposalHandler` |
23
+ | L1-confirmed checkpoints | Fetched on demand per slot via `archiver.getCheckpoint({ slot })`, yielding the canonical attestor set |
24
+
25
+ ## Two cadences
26
+
27
+ `Sentinel.work()` runs every quarter L2 slot and drives two pipelines that operate independently:
28
+
29
+ ### 1. Per-slot recording (lag = 2 slots)
30
+
31
+ `processSlot(currentSlot - 2)` runs once per slot. The 2-slot lag gives P2P attestations time to settle and lets the archiver catch up. It calls `getSlotActivity(slot, epoch, proposer, committee)` and writes per-validator statuses to `SentinelStore.historyMap`. History is a sliding window of `sentinelHistoryLengthInEpochs * epochDuration` slots (default 24 epochs).
32
+
33
+ If `EpochCache.getCommittee(slot)` reports `isEscapeHatchOpen`, the slot is recorded as processed without writing any per-validator entries.
34
+
35
+ ### 2. Per-epoch evaluation (lag = `sentinelEpochEndBufferSlots` past the epoch's last slot)
36
+
37
+ `processEpochEnds(currentSlot)` checks whether any epoch is now fully observable and not yet evaluated. An epoch is eligible once both:
38
+
39
+ - the buffer has elapsed: `currentSlot − sentinelEpochEndBufferSlots ≥ lastSlotOfEpoch`, and
40
+ - per-slot recording has reached the epoch's last slot: `lastProcessedSlot ≥ lastSlotOfEpoch`.
41
+
42
+ When eligible, `handleEpochEnd(epoch)` aggregates the slot-level statuses for that epoch into per-validator `{missed, total}`, persists the result to `SentinelStore.epochMap` (default 2000-epoch window), and runs the inactivity check.
43
+
44
+ The aggregator catches up if multiple epochs become eligible at once (e.g. after a long backoff).
45
+
46
+ ## Six-case taxonomy
47
+
48
+ For each slot, the proposer is assigned one of six statuses, ranked highest-confidence first:
49
+
50
+ | # | Status | Trigger | Inactive party |
51
+ |---|---|---|---|
52
+ | 6 | `checkpoint-mined` | `archiver.getCheckpoint({ slot })` returns a checkpoint (one covering this slot has landed on L1) | Attestors who didn't attest |
53
+ | 5 | `checkpoint-valid` | `tracker.getOutcomeForSlot(slot) === 'valid'` | Attestors who didn't attest |
54
+ | 4 | `checkpoint-invalid` | `tracker.getOutcomeForSlot(slot) === 'invalid'` (re-executed and rejected) | Proposer |
55
+ | 3 | `checkpoint-unvalidated` | `tracker.getOutcomeForSlot(slot) === 'unvalidated'` (validation aborted: missing data, timeout, etc.) | Proposer |
56
+ | 2 | `checkpoint-missed` | `p2p.hasBlockProposalsForSlot(slot)` true (blocks seen but no checkpoint proposal observed) | Proposer |
57
+ | 1 | `blocks-missed` | None of the above (no block proposals observed) | Proposer |
58
+
59
+ Missing-attestor faults are only recorded in cases 5 and 6 — where the local node has positive evidence the checkpoint was valid or canonical. In cases 1–4 the proposer is at fault and no attestor penalty applies.
60
+
61
+ Each non-proposer committee member is tagged:
62
+
63
+ - `attestation-sent` — attestation seen on P2P (with valid signature) or in the L1 checkpoint's attestor set
64
+ - `attestation-missed` — only when proposer status is case 5 or 6 and the validator's attestation was not seen
65
+ - none — otherwise
66
+
67
+ ## Inactivity slashing
68
+
69
+ `handleEpochPerformance(epoch, performance)`:
70
+
71
+ 1. Filter validators where `missed / total ≥ slashInactivityTargetPercentage`.
72
+ 2. For each, call `checkPastInactivity` to require `slashInactivityConsecutiveEpochThreshold − 1` past epochs (from `SentinelStore.epochMap`) over the same threshold. Epochs where the validator was not on a committee are skipped, not counted against the streak.
73
+ 3. Emit a single `WANT_TO_SLASH_EVENT` with one `WantToSlashArgs` per qualifying validator.
74
+
75
+ `{missed, total}` only counts slots that had something happen (a proposal, an attestation, or a missed proposal opportunity). Slots where the validator was on the committee but no proposal occurred and they were not the proposer don't show up in either count — that prevents an offline validator from appearing as "5/10 missed" simply because half the epoch had no proposals.
76
+
77
+ ## Storage
78
+
79
+ `SentinelStore` is an LMDB-backed KV store with two maps:
80
+
81
+ - `historyMap` — validator address → serialized `[(slot, status)]` rolling window
82
+ - `epochMap` — validator address → serialized `[{epoch, missed, total}]` rolling window
83
+
84
+ `SCHEMA_VERSION` controls on-disk compatibility; bumping it wipes the store on next open. The encoded status numbers live in `SentinelStore.statusToNumber`/`statusFromNumber`.
85
+
86
+ ## Configuration
87
+
88
+ | Key | Env var | Default | Purpose |
89
+ |---|---|---|---|
90
+ | `sentinelEnabled` | `SENTINEL_ENABLED` | `false` | Master switch |
91
+ | `sentinelHistoryLengthInEpochs` | `SENTINEL_HISTORY_LENGTH_IN_EPOCHS` | `24` | Slot-history window, in epochs |
92
+ | `sentinelHistoricEpochPerformanceLengthInEpochs` | `SENTINEL_HISTORIC_EPOCH_PERFORMANCE_LENGTH_IN_EPOCHS` | `2000` | Per-epoch performance window |
93
+ | `sentinelEpochEndBufferSlots` | `SENTINEL_EPOCH_END_BUFFER_SLOTS` | `2` | Slots to wait past an epoch's last slot before evaluating it |
94
+
95
+ The sentinel also reads slashing thresholds and L1 chain identifiers from `SentinelRuntimeConfig` (see `sentinel.ts`).
96
+
97
+ ## Files
98
+
99
+ - `sentinel.ts` — main class
100
+ - `store.ts` — KV-backed persistence
101
+ - `config.ts` — `SentinelConfig` and env-var mappings
102
+ - `factory.ts` — `createSentinel` factory used by `AztecNodeService`
103
+ - `sentinel.test.ts` / `store.test.ts` — unit tests
@@ -0,0 +1,49 @@
1
+ import { type ConfigMappingsType, booleanConfigHelper, numberConfigHelper } from '@aztec-labs/foundation/config';
2
+
3
+ export type SentinelConfig = {
4
+ sentinelHistoryLengthInEpochs: number;
5
+ sentinelHistoricEpochPerformanceLengthInEpochs: number;
6
+ sentinelEnabled: boolean;
7
+ sentinelEpochEndBufferSlots: number;
8
+ };
9
+
10
+ export const sentinelConfigMappings: ConfigMappingsType<SentinelConfig> = {
11
+ sentinelHistoryLengthInEpochs: {
12
+ description: 'The number of L2 epochs kept of history for each validator for computing their stats.',
13
+ env: 'SENTINEL_HISTORY_LENGTH_IN_EPOCHS',
14
+ ...numberConfigHelper(24),
15
+ },
16
+ /**
17
+ * The number of L2 epochs kept of per-epoch performance history for each validator. End-of-epoch
18
+ * activity is recorded here and used to decide consecutive-epoch inactivity slashing.
19
+ * This value must be large enough so that we have epoch performance for every validator
20
+ * for at least slashInactivityConsecutiveEpochThreshold. Assuming this value is 3,
21
+ * and the committee size is 48, and we have 10k validators, then we pick 48 out of 10k each draw.
22
+ * For any fixed element, per-draw prob = 48/10000 = 0.0048.
23
+ * After n draws, count ~ Binomial(n, 0.0048). We want P(X >= 3).
24
+ * Results (exact binomial):
25
+ * - 90% chance: n = 1108
26
+ * - 95% chance: n = 1310
27
+ * - 99% chance: n = 1749
28
+ */
29
+ sentinelHistoricEpochPerformanceLengthInEpochs: {
30
+ description: 'The number of L2 epochs kept of per-epoch performance history for each validator.',
31
+ env: 'SENTINEL_HISTORIC_EPOCH_PERFORMANCE_LENGTH_IN_EPOCHS',
32
+ ...numberConfigHelper(2000),
33
+ },
34
+ sentinelEnabled: {
35
+ description: 'Whether the sentinel is enabled or not.',
36
+ env: 'SENTINEL_ENABLED',
37
+ ...booleanConfigHelper(false),
38
+ },
39
+ /**
40
+ * Number of L2 slots to wait after the end of an epoch before computing the epoch's performance.
41
+ * The buffer allows P2P attestations and the local archiver to settle. Higher values reduce the
42
+ * risk of misjudging late-arriving activity at the cost of delayed slashing.
43
+ */
44
+ sentinelEpochEndBufferSlots: {
45
+ description: 'Number of L2 slots after the end of an epoch before the sentinel evaluates it.',
46
+ env: 'SENTINEL_EPOCH_END_BUFFER_SLOTS',
47
+ ...numberConfigHelper(2),
48
+ },
49
+ };
@@ -0,0 +1,46 @@
1
+ import type { EpochCache } from '@aztec-labs/epoch-cache';
2
+ import { createLogger } from '@aztec-labs/foundation/log';
3
+ import { createStore } from '@aztec-labs/kv-store/lmdb-v2';
4
+ import type { P2PClient } from '@aztec-labs/p2p';
5
+ import type { L2BlockSource } from '@aztec-labs/stdlib/block';
6
+ import type { CheckpointReexecutionTracker } from '@aztec-labs/stdlib/checkpoint';
7
+ import type { ChainConfig } from '@aztec-labs/stdlib/config';
8
+ import type { SlasherConfig, ValidatorClientConfig } from '@aztec-labs/stdlib/interfaces/server';
9
+ import type { DataStoreConfig } from '@aztec-labs/stdlib/kv-store';
10
+
11
+ import type { SentinelConfig } from './config.js';
12
+ import { Sentinel } from './sentinel.js';
13
+ import { SentinelStore } from './store.js';
14
+
15
+ export async function createSentinel(
16
+ epochCache: EpochCache,
17
+ archiver: L2BlockSource,
18
+ p2p: P2PClient,
19
+ reexecutionTracker: CheckpointReexecutionTracker,
20
+ config: SentinelConfig &
21
+ DataStoreConfig &
22
+ SlasherConfig &
23
+ Pick<ChainConfig, 'l1ChainId' | 'rollupAddress'> &
24
+ Pick<ValidatorClientConfig, 'disableValidator'>,
25
+ logger = createLogger('node:sentinel'),
26
+ ): Promise<Sentinel | undefined> {
27
+ const runsValidator = !config.disableValidator;
28
+ if (!runsValidator && !config.sentinelEnabled) {
29
+ logger.verbose('Sentinel is disabled');
30
+ return undefined;
31
+ }
32
+ if (runsValidator) {
33
+ logger.info('Enabling sentinel since this node runs a validator');
34
+ } else {
35
+ logger.info('Enabling sentinel from SENTINEL_ENABLED configuration');
36
+ }
37
+
38
+ const kvStore = await createStore('sentinel', SentinelStore.SCHEMA_VERSION, config, logger.getBindings());
39
+ const storeHistoryLength = config.sentinelHistoryLengthInEpochs * epochCache.getL1Constants().epochDuration;
40
+ const storeHistoricEpochPerformanceLength = config.sentinelHistoricEpochPerformanceLengthInEpochs;
41
+ const sentinelStore = new SentinelStore(kvStore, {
42
+ historyLength: storeHistoryLength,
43
+ historicEpochPerformanceLength: storeHistoricEpochPerformanceLength,
44
+ });
45
+ return new Sentinel(epochCache, archiver, p2p, sentinelStore, reexecutionTracker, config, logger);
46
+ }
@@ -0,0 +1,8 @@
1
+ export { Sentinel } from './sentinel.js';
2
+
3
+ export type {
4
+ ValidatorsStats,
5
+ ValidatorStats,
6
+ ValidatorStatusHistory,
7
+ ValidatorStatusInSlot,
8
+ } from '@aztec-labs/stdlib/validators';