@aztec/aztec-node 0.0.1-commit.42ee6df9b → 0.0.1-commit.431c48d

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 (75) hide show
  1. package/dest/aztec-node/block_response_helpers.d.ts +25 -0
  2. package/dest/aztec-node/block_response_helpers.d.ts.map +1 -0
  3. package/dest/aztec-node/block_response_helpers.js +112 -0
  4. package/dest/aztec-node/config.d.ts +16 -4
  5. package/dest/aztec-node/config.d.ts.map +1 -1
  6. package/dest/aztec-node/config.js +15 -5
  7. package/dest/aztec-node/node_public_calls_simulator.d.ts +90 -0
  8. package/dest/aztec-node/node_public_calls_simulator.d.ts.map +1 -0
  9. package/dest/aztec-node/node_public_calls_simulator.js +346 -0
  10. package/dest/aztec-node/public_data_overrides.d.ts +13 -0
  11. package/dest/aztec-node/public_data_overrides.d.ts.map +1 -0
  12. package/dest/aztec-node/public_data_overrides.js +21 -0
  13. package/dest/aztec-node/register_node_rpc_handlers.d.ts +11 -0
  14. package/dest/aztec-node/register_node_rpc_handlers.d.ts.map +1 -0
  15. package/dest/aztec-node/register_node_rpc_handlers.js +48 -0
  16. package/dest/aztec-node/server.d.ts +126 -133
  17. package/dest/aztec-node/server.d.ts.map +1 -1
  18. package/dest/aztec-node/server.js +400 -855
  19. package/dest/bin/index.js +31 -15
  20. package/dest/factory.d.ts +33 -0
  21. package/dest/factory.d.ts.map +1 -0
  22. package/dest/factory.js +523 -0
  23. package/dest/index.d.ts +3 -1
  24. package/dest/index.d.ts.map +1 -1
  25. package/dest/index.js +2 -0
  26. package/dest/modules/block_parameter.d.ts +25 -0
  27. package/dest/modules/block_parameter.d.ts.map +1 -0
  28. package/dest/modules/block_parameter.js +100 -0
  29. package/dest/modules/node_block_provider.d.ts +21 -0
  30. package/dest/modules/node_block_provider.d.ts.map +1 -0
  31. package/dest/modules/node_block_provider.js +114 -0
  32. package/dest/modules/node_tx_receipt.d.ts +24 -0
  33. package/dest/modules/node_tx_receipt.d.ts.map +1 -0
  34. package/dest/modules/node_tx_receipt.js +70 -0
  35. package/dest/modules/node_world_state_queries.d.ts +68 -0
  36. package/dest/modules/node_world_state_queries.d.ts.map +1 -0
  37. package/dest/modules/node_world_state_queries.js +272 -0
  38. package/dest/modules/unseen_block_hold_off.d.ts +52 -0
  39. package/dest/modules/unseen_block_hold_off.d.ts.map +1 -0
  40. package/dest/modules/unseen_block_hold_off.js +150 -0
  41. package/dest/sentinel/config.d.ts +3 -2
  42. package/dest/sentinel/config.d.ts.map +1 -1
  43. package/dest/sentinel/config.js +15 -5
  44. package/dest/sentinel/factory.d.ts +5 -3
  45. package/dest/sentinel/factory.d.ts.map +1 -1
  46. package/dest/sentinel/factory.js +12 -5
  47. package/dest/sentinel/sentinel.d.ts +145 -21
  48. package/dest/sentinel/sentinel.d.ts.map +1 -1
  49. package/dest/sentinel/sentinel.js +226 -104
  50. package/dest/sentinel/store.d.ts +8 -8
  51. package/dest/sentinel/store.d.ts.map +1 -1
  52. package/dest/sentinel/store.js +25 -17
  53. package/dest/test/index.d.ts +3 -3
  54. package/dest/test/index.d.ts.map +1 -1
  55. package/package.json +28 -26
  56. package/src/aztec-node/block_response_helpers.ts +161 -0
  57. package/src/aztec-node/config.ts +30 -7
  58. package/src/aztec-node/node_public_calls_simulator.ts +383 -0
  59. package/src/aztec-node/public_data_overrides.ts +35 -0
  60. package/src/aztec-node/register_node_rpc_handlers.ts +41 -0
  61. package/src/aztec-node/server.ts +528 -1100
  62. package/src/bin/index.ts +39 -16
  63. package/src/factory.ts +688 -0
  64. package/src/index.ts +2 -0
  65. package/src/modules/block_parameter.ts +93 -0
  66. package/src/modules/node_block_provider.ts +153 -0
  67. package/src/modules/node_tx_receipt.ts +115 -0
  68. package/src/modules/node_world_state_queries.ts +376 -0
  69. package/src/modules/unseen_block_hold_off.ts +199 -0
  70. package/src/sentinel/README.md +103 -0
  71. package/src/sentinel/config.ts +18 -6
  72. package/src/sentinel/factory.ts +21 -6
  73. package/src/sentinel/sentinel.ts +276 -129
  74. package/src/sentinel/store.ts +26 -18
  75. package/src/test/index.ts +2 -2
@@ -0,0 +1,376 @@
1
+ import { ARCHIVE_HEIGHT, type L1_TO_L2_MSG_TREE_HEIGHT, type NOTE_HASH_TREE_HEIGHT } from '@aztec/constants';
2
+ import { BlockNumber, type CheckpointNumber, type EpochNumber } from '@aztec/foundation/branded-types';
3
+ import { chunkBy } from '@aztec/foundation/collection';
4
+ import { Fr } from '@aztec/foundation/curves/bn254';
5
+ import { type Logger, createLogger } from '@aztec/foundation/log';
6
+ import { sleep } from '@aztec/foundation/sleep';
7
+ import { MembershipWitness, type SiblingPath } from '@aztec/foundation/trees';
8
+ import type { AztecAddress } from '@aztec/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/stdlib/block';
17
+ import { computePublicDataTreeLeafSlot } from '@aztec/stdlib/hash';
18
+ import type { WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
19
+ import { InboxLeaf, type L1ToL2MessageSource, type L2ToL1MembershipWitness } from '@aztec/stdlib/messaging';
20
+ import {
21
+ MerkleTreeId,
22
+ type NullifierLeafPreimage,
23
+ NullifierMembershipWitness,
24
+ type PublicDataTreeLeafPreimage,
25
+ PublicDataWitness,
26
+ } from '@aztec/stdlib/trees';
27
+ import type { TxHash } from '@aztec/stdlib/tx';
28
+ import { WorldStateSynchronizerError } from '@aztec/world-state';
29
+
30
+ import { normalizeBlockParameter } from './block_parameter.js';
31
+ import type { UnseenBlockHoldOff, UnseenBlockHoldOffOptions } from './unseen_block_hold_off.js';
32
+
33
+ /** Attempts at resolving a query and syncing world state to it before giving up (see {@link NodeWorldStateQueries.getWorldState}). */
34
+ const WORLD_STATE_SYNC_ATTEMPTS = 3;
35
+
36
+ /** Delay between world-state sync attempts. */
37
+ const WORLD_STATE_SYNC_RETRY_DELAY_MS = 100;
38
+
39
+ /** Dependencies required to build a {@link NodeWorldStateQueries}. */
40
+ export interface NodeWorldStateQueriesDeps {
41
+ worldStateSynchronizer: WorldStateSynchronizer;
42
+ blockSource: L2BlockSource;
43
+ l1ToL2MessageSource: L1ToL2MessageSource;
44
+ holdOff: UnseenBlockHoldOff;
45
+ log?: Logger;
46
+ }
47
+
48
+ /**
49
+ * Serves the node's Merkle-tree and membership-witness queries against committed world-state at a
50
+ * requested block. Extracted from `AztecNodeService` so the block-resolution and reorg-aware sync logic
51
+ * can be unit-tested without standing up the whole node, and to keep `server.ts` smaller.
52
+ */
53
+ export class NodeWorldStateQueries {
54
+ private readonly worldStateSynchronizer: WorldStateSynchronizer;
55
+ private readonly blockSource: L2BlockSource;
56
+ private readonly l1ToL2MessageSource: L1ToL2MessageSource;
57
+ private readonly holdOff: UnseenBlockHoldOff;
58
+ private readonly log: Logger;
59
+
60
+ constructor(deps: NodeWorldStateQueriesDeps) {
61
+ this.worldStateSynchronizer = deps.worldStateSynchronizer;
62
+ this.blockSource = deps.blockSource;
63
+ this.l1ToL2MessageSource = deps.l1ToL2MessageSource;
64
+ this.holdOff = deps.holdOff;
65
+ this.log = deps.log ?? createLogger('node:world-state-queries');
66
+ }
67
+
68
+ public async findLeavesIndexes(
69
+ referenceBlock: BlockParameter,
70
+ treeId: MerkleTreeId,
71
+ leafValues: Fr[],
72
+ ): Promise<(DataInBlock<bigint> | undefined)[]> {
73
+ const committedDb = await this.getWorldState(referenceBlock);
74
+ const maybeIndices = await committedDb.findLeafIndices(
75
+ treeId,
76
+ leafValues.map(x => x.toBuffer()),
77
+ );
78
+ // Filter out undefined values to query block numbers only for found leaves
79
+ const definedIndices = maybeIndices.filter(x => x !== undefined);
80
+
81
+ // Now we find the block numbers for the defined indices
82
+ const blockNumbers = await committedDb.getBlockNumbersForLeafIndices(treeId, definedIndices);
83
+
84
+ // Build a map from leaf index to block number
85
+ const indexToBlockNumber = new Map<bigint, BlockNumber>();
86
+ for (let i = 0; i < definedIndices.length; i++) {
87
+ const blockNumber = blockNumbers[i];
88
+ if (blockNumber === undefined) {
89
+ throw new Error(
90
+ `Block number is undefined for leaf index ${definedIndices[i]} in tree ${MerkleTreeId[treeId]}`,
91
+ );
92
+ }
93
+ indexToBlockNumber.set(definedIndices[i], blockNumber);
94
+ }
95
+
96
+ // Get unique block numbers in order to optimize num calls to getLeafValue function.
97
+ const uniqueBlockNumbers = [...new Set(indexToBlockNumber.values())];
98
+
99
+ // Now we obtain the block hashes from the archive tree (block number = leaf index in archive tree).
100
+ const blockHashes = await Promise.all(
101
+ uniqueBlockNumbers.map(blockNumber => {
102
+ return committedDb.getLeafValue(MerkleTreeId.ARCHIVE, BigInt(blockNumber));
103
+ }),
104
+ );
105
+
106
+ // Build a map from block number to block hash
107
+ const blockNumberToHash = new Map<BlockNumber, BlockHash>();
108
+ for (let i = 0; i < uniqueBlockNumbers.length; i++) {
109
+ const blockHash = blockHashes[i];
110
+ if (blockHash === undefined) {
111
+ throw new Error(`Block hash is undefined for block number ${uniqueBlockNumbers[i]}`);
112
+ }
113
+ blockNumberToHash.set(uniqueBlockNumbers[i], blockHash);
114
+ }
115
+
116
+ // Create DataInBlock objects by combining indices, blockNumbers and blockHashes and return them.
117
+ return maybeIndices.map(index => {
118
+ if (index === undefined) {
119
+ return undefined;
120
+ }
121
+ const blockNumber = indexToBlockNumber.get(index);
122
+ if (blockNumber === undefined) {
123
+ throw new Error(`Block number not found for leaf index ${index} in tree ${MerkleTreeId[treeId]}`);
124
+ }
125
+ const l2BlockHash = blockNumberToHash.get(blockNumber);
126
+ if (l2BlockHash === undefined) {
127
+ throw new Error(`Block hash not found for block number ${blockNumber}`);
128
+ }
129
+ return {
130
+ l2BlockNumber: blockNumber,
131
+ l2BlockHash,
132
+ data: index,
133
+ };
134
+ });
135
+ }
136
+
137
+ public async getBlockHashMembershipWitness(
138
+ referenceBlock: BlockParameter,
139
+ blockHash: BlockHash,
140
+ ): Promise<MembershipWitness<typeof ARCHIVE_HEIGHT> | undefined> {
141
+ // The Noir circuit checks the archive membership proof against `anchor_block_header.last_archive.root`,
142
+ // which is the archive tree root BEFORE the anchor block was added (i.e. the state after block N-1).
143
+ // So we need the world state at block N-1, not block N, to produce a sibling path matching that root.
144
+ const { blockNumber: referenceBlockNumber } = await this.#resolveBlockNumberAndHash(
145
+ normalizeBlockParameter(referenceBlock),
146
+ );
147
+ if (referenceBlockNumber === BlockNumber.ZERO) {
148
+ // Block 0 (the initial block) has an empty archive, so no membership witness can exist.
149
+ return undefined;
150
+ }
151
+ const committedDb = await this.getWorldState(BlockNumber(referenceBlockNumber - 1));
152
+ const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.ARCHIVE>(MerkleTreeId.ARCHIVE, [blockHash]);
153
+ return pathAndIndex === undefined
154
+ ? undefined
155
+ : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
156
+ }
157
+
158
+ public async getNoteHashMembershipWitness(
159
+ referenceBlock: BlockParameter,
160
+ noteHash: Fr,
161
+ ): Promise<MembershipWitness<typeof NOTE_HASH_TREE_HEIGHT> | undefined> {
162
+ const committedDb = await this.getWorldState(referenceBlock);
163
+ const [pathAndIndex] = await committedDb.findSiblingPaths<MerkleTreeId.NOTE_HASH_TREE>(
164
+ MerkleTreeId.NOTE_HASH_TREE,
165
+ [noteHash],
166
+ );
167
+ return pathAndIndex === undefined
168
+ ? undefined
169
+ : MembershipWitness.fromSiblingPath(pathAndIndex.index, pathAndIndex.path);
170
+ }
171
+
172
+ public async getL1ToL2MessageMembershipWitness(
173
+ referenceBlock: BlockParameter,
174
+ l1ToL2Message: Fr,
175
+ ): Promise<[bigint, SiblingPath<typeof L1_TO_L2_MSG_TREE_HEIGHT>] | undefined> {
176
+ const db = await this.getWorldState(referenceBlock);
177
+ const [witness] = await db.findSiblingPaths(MerkleTreeId.L1_TO_L2_MESSAGE_TREE, [l1ToL2Message]);
178
+ if (!witness) {
179
+ return undefined;
180
+ }
181
+
182
+ // REFACTOR: Return a MembershipWitness object
183
+ return [witness.index, witness.path];
184
+ }
185
+
186
+ public async getL1ToL2MessageCheckpoint(l1ToL2Message: Fr): Promise<CheckpointNumber | undefined> {
187
+ const messageIndex = await this.l1ToL2MessageSource.getL1ToL2MessageIndex(l1ToL2Message);
188
+ return messageIndex !== undefined ? InboxLeaf.checkpointNumberFromIndex(messageIndex) : undefined;
189
+ }
190
+
191
+ /**
192
+ * Returns all the L2 to L1 messages in an epoch (empty array if the epoch is not found). The public
193
+ * `AztecNodeService.getL2ToL1Messages` that delegates here is deprecated in favor of
194
+ * {@link getL2ToL1MembershipWitness}.
195
+ * @param epoch - The epoch at which to get the data.
196
+ */
197
+ public async getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]> {
198
+ const blocks = await this.blockSource.getBlocks({ epoch, onlyCheckpointed: true });
199
+ const blocksInCheckpoints = chunkBy(blocks, block => block.header.globalVariables.slotNumber);
200
+ return blocksInCheckpoints.map(slotBlocks =>
201
+ slotBlocks.map(block => block.body.txEffects.map(txEffect => txEffect.l2ToL1Msgs)),
202
+ );
203
+ }
204
+
205
+ /**
206
+ * Returns the L2-to-L1 membership witness for a message in `txHash`. Passthrough to the
207
+ * archiver's locally-cached resolver — see {@link Archiver.getL2ToL1MembershipWitness}.
208
+ */
209
+ public getL2ToL1MembershipWitness(
210
+ txHash: TxHash,
211
+ message: Fr,
212
+ messageIndexInTx?: number,
213
+ ): Promise<L2ToL1MembershipWitness | undefined> {
214
+ return this.blockSource.getL2ToL1MembershipWitness(txHash, message, messageIndexInTx);
215
+ }
216
+
217
+ public async getNullifierMembershipWitness(
218
+ referenceBlock: BlockParameter,
219
+ nullifier: Fr,
220
+ ): Promise<NullifierMembershipWitness | undefined> {
221
+ const db = await this.getWorldState(referenceBlock);
222
+ const [witness] = await db.findSiblingPaths(MerkleTreeId.NULLIFIER_TREE, [nullifier.toBuffer()]);
223
+ if (!witness) {
224
+ return undefined;
225
+ }
226
+
227
+ const { index, path } = witness;
228
+ const leafPreimage = await db.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index);
229
+ if (!leafPreimage) {
230
+ return undefined;
231
+ }
232
+
233
+ return new NullifierMembershipWitness(index, leafPreimage as NullifierLeafPreimage, path);
234
+ }
235
+
236
+ public async getLowNullifierMembershipWitness(
237
+ referenceBlock: BlockParameter,
238
+ nullifier: Fr,
239
+ ): Promise<NullifierMembershipWitness | undefined> {
240
+ const committedDb = await this.getWorldState(referenceBlock);
241
+ const findResult = await committedDb.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt());
242
+ if (!findResult) {
243
+ return undefined;
244
+ }
245
+ const { index, alreadyPresent } = findResult;
246
+ if (alreadyPresent) {
247
+ throw new Error(
248
+ `Cannot prove nullifier non-inclusion: nullifier ${nullifier.toBigInt()} already exists in the tree`,
249
+ );
250
+ }
251
+ const preimageData = (await committedDb.getLeafPreimage(MerkleTreeId.NULLIFIER_TREE, index))!;
252
+
253
+ const siblingPath = await committedDb.getSiblingPath(MerkleTreeId.NULLIFIER_TREE, BigInt(index));
254
+ return new NullifierMembershipWitness(BigInt(index), preimageData as NullifierLeafPreimage, siblingPath);
255
+ }
256
+
257
+ async getPublicDataWitness(referenceBlock: BlockParameter, leafSlot: Fr): Promise<PublicDataWitness | undefined> {
258
+ const committedDb = await this.getWorldState(referenceBlock);
259
+ const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
260
+ if (!lowLeafResult) {
261
+ return undefined;
262
+ } else {
263
+ const preimage = (await committedDb.getLeafPreimage(
264
+ MerkleTreeId.PUBLIC_DATA_TREE,
265
+ lowLeafResult.index,
266
+ )) as PublicDataTreeLeafPreimage;
267
+ const path = await committedDb.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, lowLeafResult.index);
268
+ return new PublicDataWitness(lowLeafResult.index, preimage, path);
269
+ }
270
+ }
271
+
272
+ public async getPublicStorageAt(referenceBlock: BlockParameter, contract: AztecAddress, slot: Fr): Promise<Fr> {
273
+ const committedDb = await this.getWorldState(referenceBlock);
274
+ const leafSlot = await computePublicDataTreeLeafSlot(contract, slot);
275
+
276
+ const lowLeafResult = await committedDb.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot.toBigInt());
277
+ if (!lowLeafResult || !lowLeafResult.alreadyPresent) {
278
+ return Fr.ZERO;
279
+ }
280
+ const preimage = (await committedDb.getLeafPreimage(
281
+ MerkleTreeId.PUBLIC_DATA_TREE,
282
+ lowLeafResult.index,
283
+ )) as PublicDataTreeLeafPreimage;
284
+ return preimage.leaf.value;
285
+ }
286
+
287
+ /**
288
+ * Returns an instance of MerkleTreeOperations having first ensured the world state is synced to the requested
289
+ * block on the correct fork. Every query variant is resolved to a concrete (block number, block hash), which is
290
+ * threaded through both the sync and the snapshot read so a reorg that replaced the block at that height is
291
+ * detected rather than served silently. Transient sync failures — a prune landing between resolution and sync, or
292
+ * a fork flip caught at either the sync or the snapshot stage — are retried a few times, re-resolving the query
293
+ * against the updated chain each time; terminal failures — a query that resolves to no block, or a block whose
294
+ * history world state has pruned away — are thrown immediately.
295
+ * @param block - The block parameter (block number, block hash, or tag) at which to get the data.
296
+ * @returns An instance of a committed MerkleTreeOperations
297
+ */
298
+ public async getWorldState(block: BlockParameter) {
299
+ const query = normalizeBlockParameter(block);
300
+
301
+ // User requests 'latest on the current fork', so the committed db is returned unverified
302
+ if ('tag' in query && query.tag === 'proposed') {
303
+ this.log.debug(`Using committed db for latest block`);
304
+ await this.worldStateSynchronizer.syncImmediate();
305
+ return this.worldStateSynchronizer.getCommitted();
306
+ }
307
+
308
+ // Resolve the query against the block source BEFORE syncing, so the sync can be driven to a concrete
309
+ // (number, hash). Resolving after the sync races the block source: the resolved tip can advance past what world
310
+ // state synced while the sync is in flight. Resolving here rather than inside the retry loop also keeps a
311
+ // retry from re-entering the hold-off, which would multiply the wait a client experiences by the attempt count.
312
+ let resolved = await this.#resolveBlockNumberAndHash(query);
313
+
314
+ for (let attempt = 1; ; attempt++) {
315
+ try {
316
+ return await this.#resolveWorldState(resolved);
317
+ } catch (err) {
318
+ if (attempt >= WORLD_STATE_SYNC_ATTEMPTS || !(err instanceof WorldStateSynchronizerError)) {
319
+ throw err;
320
+ }
321
+ this.log.verbose(`Retrying world state query after sync failure: ${err.message}`, {
322
+ attempt,
323
+ block: inspectBlockParameter(block),
324
+ });
325
+ await sleep(WORLD_STATE_SYNC_RETRY_DELAY_MS);
326
+ resolved = await this.#resolveBlockNumberAndHash(query, { holdOff: false });
327
+ }
328
+ }
329
+ }
330
+
331
+ /**
332
+ * Syncs world state to the resolved fork and returns the fork-verified snapshot at that block. Passing the hash
333
+ * makes the sync reorg-aware — it barriers until the archive-tree commit for that block has landed and verifies
334
+ * it matches the requested fork, throwing otherwise.
335
+ */
336
+ async #resolveWorldState({ blockNumber, blockHash }: { blockNumber: BlockNumber; blockHash: BlockHash }) {
337
+ const blockSyncedTo = await this.worldStateSynchronizer.syncImmediate(blockNumber, blockHash);
338
+
339
+ // The fork could flip between it returning and the snapshot being read, so getVerifiedSnapshot pins the
340
+ // returned view to the resolved fork (re-resolved by the retry loop on mismatch).
341
+ this.log.debug(`Using verified snapshot for block ${blockNumber}, world state synced upto ${blockSyncedTo}`);
342
+ return await this.worldStateSynchronizer.getVerifiedSnapshot(blockNumber, blockHash);
343
+ }
344
+
345
+ /**
346
+ * Resolves any {@link BlockParameter} variant to its concrete `(blockNumber, blockHash)`, holding the query
347
+ * briefly (unless the caller opts out) when it references a block the node is about to see.
348
+ */
349
+ async #resolveBlockNumberAndHash(
350
+ query: NormalizedBlockParameter,
351
+ opts: UnseenBlockHoldOffOptions = {},
352
+ ): Promise<{ blockNumber: BlockNumber; blockHash: BlockHash }> {
353
+ const blockData = await this.holdOff.getBlockData(query, opts);
354
+ if (blockData === undefined) {
355
+ this.#throwOnUndefinedBlockData(query);
356
+ }
357
+ return { blockNumber: blockData.header.getBlockNumber(), blockHash: blockData.blockHash };
358
+ }
359
+
360
+ /**
361
+ * Hash and archive misses report an unknown block (likely a reorg); tag and number misses report a transient
362
+ * condition — the block may have been pruned, or may simply not have arrived yet — and are distinguished to the
363
+ * caller as a {@link WorldStateSynchronizerError}.
364
+ */
365
+ #throwOnUndefinedBlockData(query: NormalizedBlockParameter): never {
366
+ if ('hash' in query) {
367
+ throw new Error(
368
+ `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.`,
369
+ );
370
+ }
371
+ if ('archive' in query) {
372
+ throw new Error(`Block with archive ${query.archive.toString()} not found when resolving query.`);
373
+ }
374
+ throw new WorldStateSynchronizerError(`Block not found for ${inspectBlockParameter(query)} when resolving query.`);
375
+ }
376
+ }
@@ -0,0 +1,199 @@
1
+ import { type Logger, createLogger } from '@aztec/foundation/log';
2
+ import { InterruptibleSleep } from '@aztec/foundation/sleep';
3
+ import { Timer } from '@aztec/foundation/timer';
4
+ import {
5
+ type BlockData,
6
+ type BlockHash,
7
+ type L2Block,
8
+ type L2BlockSource,
9
+ type L2BlockSourceEventEmitter,
10
+ L2BlockSourceEvents,
11
+ type NormalizedBlockParameter,
12
+ getBlockSourceEmitter,
13
+ inspectBlockParameter,
14
+ } from '@aztec/stdlib/block';
15
+
16
+ /**
17
+ * Longest a held request sleeps before re-reading the block source anyway. Held requests are woken by the source
18
+ * reporting an update, so this only bounds how long one waits when it misses the update that added its block: the
19
+ * source can commit between a request's read and its sleep, and a request that is not sleeping yet is not woken.
20
+ */
21
+ const MAX_SLEEP_MS = 1000;
22
+
23
+ /** Max requests held simultaneously. Beyond this, misses fail fast as if the hold-off were disabled. */
24
+ export const MAX_CONCURRENT_HOLDS = 100;
25
+
26
+ /** Wait budgets for {@link UnseenBlockHoldOff}, in milliseconds. Zero (or negative) disables a budget. */
27
+ export type UnseenBlockHoldOffConfig = {
28
+ /** Budget for a query anchored on the block number right after the node's proposed tip. */
29
+ byNumberWaitMs: number;
30
+ /** Budget for a query anchored on a block hash or archive root the node does not know. */
31
+ byHashWaitMs: number;
32
+ };
33
+
34
+ /** Options for a single {@link UnseenBlockHoldOff} query. */
35
+ export type UnseenBlockHoldOffOptions = {
36
+ /** Set to false to resolve without ever waiting (used by callers that already spent their budget). */
37
+ holdOff?: boolean;
38
+ };
39
+
40
+ /**
41
+ * Resolves RPC block anchors against the block source, briefly holding a request whose anchor the node is about to
42
+ * see instead of failing it immediately.
43
+ *
44
+ * Behind a load balancer a client can sync to block N+1 through one node and then anchor follow-up queries against
45
+ * another node that is still at block N. Failing those queries aborts a whole client flow over a skew that resolves
46
+ * in under a block time, so a miss on an anchor that plausibly lies just ahead of the tip is retried for a bounded
47
+ * budget. Everything else — a tag, a number far past the tip, a budget of zero, or too many requests already held —
48
+ * resolves exactly as the bare block source would.
49
+ *
50
+ * Held requests do not poll at a rate of their own choosing: they all sleep on one wake-up that the block source
51
+ * triggers when it reports it moved, so the source is read when there is something new to read and, failing that, at
52
+ * most once per {@link MAX_SLEEP_MS}. A source that reports no updates cannot wake them, so it never holds anything
53
+ * off.
54
+ */
55
+ export class UnseenBlockHoldOff {
56
+ private activeHolds = 0;
57
+ private readonly log: Logger;
58
+ /** Shared by every held request; interrupted on a source update. Undefined for a source that reports none. */
59
+ private readonly wakeup: InterruptibleSleep | undefined;
60
+
61
+ constructor(
62
+ private readonly blockSource: L2BlockSource | L2BlockSourceEventEmitter,
63
+ private readonly config: UnseenBlockHoldOffConfig,
64
+ log?: Logger,
65
+ ) {
66
+ this.log = log ?? createLogger('node:unseen-block-hold-off');
67
+ const emitter = getBlockSourceEmitter(blockSource);
68
+ if (emitter === undefined) {
69
+ this.log.verbose(`Block source reports no updates, queries for unseen blocks will not be held off`);
70
+ } else {
71
+ const wakeup = new InterruptibleSleep();
72
+ this.wakeup = wakeup;
73
+ emitter.on(L2BlockSourceEvents.L2BlockSourceUpdated, () => wakeup.interrupt());
74
+ }
75
+ }
76
+
77
+ /** Number of requests currently held waiting for their anchor block. Exposed for tests and diagnostics. */
78
+ public get holds(): number {
79
+ return this.activeHolds;
80
+ }
81
+
82
+ /**
83
+ * Resolves `query` to block metadata, holding off briefly when it references a block the node is about to see.
84
+ * Returns undefined on a miss, so callers keep whatever behavior they had before (throwing or returning
85
+ * undefined) — the hold-off only delays that outcome.
86
+ */
87
+ public getBlockData(
88
+ query: NormalizedBlockParameter,
89
+ opts: UnseenBlockHoldOffOptions = {},
90
+ ): Promise<BlockData | undefined> {
91
+ return this.#readWithHoldOff(query, q => this.blockSource.getBlockData(q), opts);
92
+ }
93
+
94
+ /** Resolves `query` to a full block with its transactions, holding off as {@link getBlockData} does. */
95
+ public getBlock(query: NormalizedBlockParameter, opts: UnseenBlockHoldOffOptions = {}): Promise<L2Block | undefined> {
96
+ return this.#readWithHoldOff(query, q => this.blockSource.getBlock(q), opts);
97
+ }
98
+
99
+ /**
100
+ * Reads `query` through `read`, and on a miss waits for the block it names before reading once more. Subject to the
101
+ * concurrent-hold cap: once it is saturated a miss resolves without waiting, as it would with the hold-off
102
+ * disabled.
103
+ */
104
+ async #readWithHoldOff<T>(
105
+ query: NormalizedBlockParameter,
106
+ read: (query: NormalizedBlockParameter) => Promise<T | undefined>,
107
+ opts: UnseenBlockHoldOffOptions,
108
+ ): Promise<T | undefined> {
109
+ const value = await read(query);
110
+ if (value !== undefined || opts.holdOff === false) {
111
+ return value;
112
+ }
113
+ const arrived = await this.#waitForBlock(query, await this.#resolveWaitBudgetMs(query));
114
+ return arrived ? await read(query) : undefined;
115
+ }
116
+
117
+ /**
118
+ * Waits for the block `query` names to show up on the block source, for at most `waitMs`, and reports whether it
119
+ * did. Returns false without waiting when the source reports no updates, when the budget is empty, or when the
120
+ * concurrent-hold cap is saturated, so a miss fails as fast as it would with the hold-off disabled.
121
+ *
122
+ * Arrival is checked on block metadata rather than through the caller's read, so a held request costs a metadata
123
+ * read per wake-up whatever it asked for: a held `getBlock` would otherwise reconstruct a whole block with its
124
+ * transactions on every wake-up only to find it is not the one it is waiting for.
125
+ *
126
+ * A budget is approximate: the deadline is only re-checked after a sleep, so the actual wait can exceed it by the
127
+ * read's own latency.
128
+ */
129
+ async #waitForBlock(query: NormalizedBlockParameter, waitMs: number): Promise<boolean> {
130
+ const wakeup = this.wakeup;
131
+ if (wakeup === undefined || !Number.isFinite(waitMs) || waitMs <= 0) {
132
+ return false;
133
+ }
134
+ const blockParameter = inspectBlockParameter(query);
135
+ if (this.activeHolds >= MAX_CONCURRENT_HOLDS) {
136
+ this.log.verbose(`Not holding off query for unseen block, too many requests already held`, {
137
+ blockParameter,
138
+ holds: this.activeHolds,
139
+ });
140
+ return false;
141
+ }
142
+
143
+ this.activeHolds++;
144
+ const timer = new Timer();
145
+ try {
146
+ this.log.verbose(`Holding off query for unseen block`, { blockParameter, waitMs, holds: this.activeHolds });
147
+ while (timer.ms() < waitMs) {
148
+ await wakeup.sleep(Math.min(waitMs - timer.ms(), MAX_SLEEP_MS));
149
+ const data = await this.blockSource.getBlockData(query);
150
+ if (data !== undefined) {
151
+ this.log.verbose(`Unseen block arrived after ${timer.ms()}ms`, {
152
+ blockParameter,
153
+ blockNumber: data.header.getBlockNumber(),
154
+ elapsedMs: timer.ms(),
155
+ });
156
+ return true;
157
+ }
158
+ }
159
+ this.log.verbose(`Gave up waiting for unseen block after ${timer.ms()}ms`, {
160
+ blockParameter,
161
+ waitMs,
162
+ elapsedMs: timer.ms(),
163
+ });
164
+ return false;
165
+ } finally {
166
+ this.activeHolds--;
167
+ }
168
+ }
169
+
170
+ /**
171
+ * Budget for waiting on a missing anchor, decided once on entry rather than per wake-up. A tag always resolves
172
+ * against the current tip, so a tag miss is never a skew. A number is only worth waiting on when it is the very
173
+ * next block: further ahead the client is not merely one block in front, and at or below the tip the block was
174
+ * pruned or reorged away. A hash or archive root carries no height, so "one ahead" and "reorged away" are
175
+ * indistinguishable and both get the shorter hash budget.
176
+ *
177
+ * The genesis block hash is the one hash never worth waiting on: a client anchors on it before it has synced any
178
+ * block (as a PXE does for its first tagged-log queries), and the block is synthetic, so a source that does not
179
+ * answer for it now never will.
180
+ */
181
+ async #resolveWaitBudgetMs(query: NormalizedBlockParameter): Promise<number> {
182
+ if ('tag' in query) {
183
+ return 0;
184
+ }
185
+ if ('number' in query) {
186
+ const tip = await this.blockSource.getBlockNumber();
187
+ return query.number === tip + 1 ? this.config.byNumberWaitMs : 0;
188
+ }
189
+ if ('hash' in query && this.#isGenesisBlockHash(query.hash)) {
190
+ return 0;
191
+ }
192
+ return this.config.byHashWaitMs;
193
+ }
194
+
195
+ /** True when `hash` names the synthetic genesis block, which never arrives and so is never waited for. */
196
+ #isGenesisBlockHash(hash: BlockHash): boolean {
197
+ return hash.equals(this.blockSource.getGenesisBlockHash());
198
+ }
199
+ }
@@ -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