@aztec/aztec-node 0.82.2 → 0.82.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ export { Sentinel } from './sentinel.js';
2
+
3
+ export type {
4
+ ValidatorsStats,
5
+ ValidatorStats,
6
+ ValidatorStatusHistory,
7
+ ValidatorStatusInSlot,
8
+ } from '@aztec/stdlib/validators';
@@ -0,0 +1,280 @@
1
+ import type { EpochCache } from '@aztec/epoch-cache';
2
+ import { countWhile } from '@aztec/foundation/collection';
3
+ import { EthAddress } from '@aztec/foundation/eth-address';
4
+ import { createLogger } from '@aztec/foundation/log';
5
+ import { RunningPromise } from '@aztec/foundation/running-promise';
6
+ import { L2TipsMemoryStore, type L2TipsStore } from '@aztec/kv-store/stores';
7
+ import type { P2PClient } from '@aztec/p2p';
8
+ import {
9
+ type L2BlockSource,
10
+ L2BlockStream,
11
+ type L2BlockStreamEvent,
12
+ type L2BlockStreamEventHandler,
13
+ } from '@aztec/stdlib/block';
14
+ import { getTimestampForSlot } from '@aztec/stdlib/epoch-helpers';
15
+ import type {
16
+ ValidatorStats,
17
+ ValidatorStatusHistory,
18
+ ValidatorStatusInSlot,
19
+ ValidatorStatusType,
20
+ ValidatorsStats,
21
+ } from '@aztec/stdlib/validators';
22
+
23
+ import { SentinelStore } from './store.js';
24
+
25
+ export class Sentinel implements L2BlockStreamEventHandler {
26
+ protected runningPromise: RunningPromise;
27
+ protected blockStream!: L2BlockStream;
28
+ protected l2TipsStore: L2TipsStore;
29
+
30
+ protected initialSlot: bigint | undefined;
31
+ protected lastProcessedSlot: bigint | undefined;
32
+ protected slotNumberToArchive: Map<bigint, string> = new Map();
33
+
34
+ constructor(
35
+ protected epochCache: EpochCache,
36
+ protected archiver: L2BlockSource,
37
+ protected p2p: P2PClient,
38
+ protected store: SentinelStore,
39
+ protected logger = createLogger('node:sentinel'),
40
+ ) {
41
+ this.l2TipsStore = new L2TipsMemoryStore();
42
+ const interval = (epochCache.getL1Constants().ethereumSlotDuration * 1000) / 4;
43
+ this.runningPromise = new RunningPromise(this.work.bind(this), logger, interval);
44
+ }
45
+
46
+ public async start() {
47
+ await this.init();
48
+ this.runningPromise.start();
49
+ }
50
+
51
+ /** Loads initial slot and initializes blockstream. We will not process anything at or before the initial slot. */
52
+ protected async init() {
53
+ this.initialSlot = this.epochCache.getEpochAndSlotNow().slot;
54
+ const startingBlock = await this.archiver.getBlockNumber();
55
+ this.blockStream = new L2BlockStream(this.archiver, this.l2TipsStore, this, this.logger, { startingBlock });
56
+ }
57
+
58
+ public stop() {
59
+ return this.runningPromise.stop();
60
+ }
61
+
62
+ public async handleBlockStreamEvent(event: L2BlockStreamEvent): Promise<void> {
63
+ await this.l2TipsStore.handleBlockStreamEvent(event);
64
+ if (event.type === 'blocks-added') {
65
+ // Store mapping from slot to archive
66
+ for (const block of event.blocks) {
67
+ this.slotNumberToArchive.set(block.block.header.getSlot(), block.block.archive.root.toString());
68
+ }
69
+
70
+ // Prune the archive map to only keep at most N entries
71
+ const historyLength = this.store.getHistoryLength();
72
+ if (this.slotNumberToArchive.size > historyLength) {
73
+ const toDelete = Array.from(this.slotNumberToArchive.keys())
74
+ .sort((a, b) => Number(a - b))
75
+ .slice(0, this.slotNumberToArchive.size - historyLength);
76
+ for (const key of toDelete) {
77
+ this.slotNumberToArchive.delete(key);
78
+ }
79
+ }
80
+ }
81
+ }
82
+
83
+ /**
84
+ * Process data for two L2 slots ago.
85
+ * Note that we do not process historical data, since we rely on p2p data for processing,
86
+ * and we don't have that data if we were offline during the period.
87
+ */
88
+ public async work() {
89
+ const { slot: currentSlot } = this.epochCache.getEpochAndSlotNow();
90
+ try {
91
+ // Manually sync the block stream to ensure we have the latest data.
92
+ // Note we never `start` the blockstream, so it loops at the same pace as we do.
93
+ await this.blockStream.sync();
94
+
95
+ // Check if we are ready to process data for two L2 slots ago.
96
+ const targetSlot = await this.isReadyToProcess(currentSlot);
97
+
98
+ // And process it if we are.
99
+ if (targetSlot !== false) {
100
+ await this.processSlot(targetSlot);
101
+ }
102
+ } catch (err) {
103
+ this.logger.error(`Failed to process slot ${currentSlot}`, err);
104
+ }
105
+ }
106
+
107
+ /**
108
+ * Check if we are ready to process data for two L2 slots ago, so we allow plenty of time for p2p to process all in-flight attestations.
109
+ * We also don't move past the archiver last synced L2 slot, as we don't want to process data that is not yet available.
110
+ * Last, we check the p2p is synced with the archiver, so it has pulled all attestations from it.
111
+ */
112
+ protected async isReadyToProcess(currentSlot: bigint) {
113
+ const targetSlot = currentSlot - 2n;
114
+ if (this.lastProcessedSlot && this.lastProcessedSlot >= targetSlot) {
115
+ this.logger.trace(`Already processed slot ${targetSlot}`, { lastProcessedSlot: this.lastProcessedSlot });
116
+ return false;
117
+ }
118
+
119
+ if (this.initialSlot === undefined) {
120
+ this.logger.error(`Initial slot not loaded.`);
121
+ return false;
122
+ }
123
+
124
+ if (targetSlot <= this.initialSlot) {
125
+ this.logger.debug(`Refusing to process slot ${targetSlot} given initial slot ${this.initialSlot}`);
126
+ return false;
127
+ }
128
+
129
+ const archiverSlot = await this.archiver.getL2SlotNumber();
130
+ if (archiverSlot < targetSlot) {
131
+ this.logger.debug(`Waiting for archiver to sync with L2 slot ${targetSlot}`, { archiverSlot, targetSlot });
132
+ return false;
133
+ }
134
+
135
+ const archiverLastBlockHash = await this.l2TipsStore.getL2Tips().then(tip => tip.latest.hash);
136
+ const p2pLastBlockHash = await this.p2p.getL2Tips().then(tips => tips.latest.hash);
137
+ const isP2pSynced = archiverLastBlockHash === p2pLastBlockHash;
138
+ if (!isP2pSynced) {
139
+ this.logger.debug(`Waiting for P2P client to sync with archiver`, { archiverLastBlockHash, p2pLastBlockHash });
140
+ return false;
141
+ }
142
+
143
+ return targetSlot;
144
+ }
145
+
146
+ /**
147
+ * Gathers committee and proposer data for a given slot, computes slot stats,
148
+ * and updates overall stats.
149
+ */
150
+ protected async processSlot(slot: bigint) {
151
+ const { epoch, seed, committee } = await this.epochCache.getCommittee(slot);
152
+ if (committee.length === 0) {
153
+ this.logger.warn(`No committee found for slot ${slot} at epoch ${epoch}`);
154
+ this.lastProcessedSlot = slot;
155
+ return;
156
+ }
157
+ const proposerIndex = this.epochCache.computeProposerIndex(slot, epoch, seed, BigInt(committee.length));
158
+ const proposer = committee[Number(proposerIndex)];
159
+ const stats = await this.getSlotActivity(slot, epoch, proposer, committee);
160
+ this.logger.verbose(`Updating L2 slot ${slot} observed activity`, stats);
161
+ await this.updateValidators(slot, stats);
162
+ this.lastProcessedSlot = slot;
163
+ }
164
+
165
+ /** Computes activity for a given slot. */
166
+ protected async getSlotActivity(slot: bigint, epoch: bigint, proposer: EthAddress, committee: EthAddress[]) {
167
+ this.logger.debug(`Computing stats for slot ${slot} at epoch ${epoch}`, { slot, epoch, proposer, committee });
168
+
169
+ // Check if there is an L2 block in L1 for this L2 slot
170
+
171
+ // Here we get all attestations for the block mined at the given slot,
172
+ // or all attestations for all proposals in the slot if no block was mined.
173
+ const archive = this.slotNumberToArchive.get(slot);
174
+ const attested = await this.p2p.getAttestationsForSlot(slot, archive);
175
+ const attestors = new Set(await Promise.all(attested.map(a => a.getSender().then(a => a.toString()))));
176
+
177
+ // We assume that there was a block proposal if at least one of the validators attested to it.
178
+ // It could be the case that every single validator failed, and we could differentiate it by having
179
+ // this node re-execute every block proposal it sees and storing it in the attestation pool.
180
+ // But we'll leave that corner case out to reduce pressure on the node.
181
+ const blockStatus = archive ? 'mined' : attestors.size > 0 ? 'proposed' : 'missed';
182
+ this.logger.debug(`Block for slot ${slot} was ${blockStatus}`, { archive, slot });
183
+
184
+ // Get attestors that failed their duties for this block, but only if there was a block proposed
185
+ const missedAttestors = new Set(
186
+ blockStatus === 'missed'
187
+ ? []
188
+ : committee.filter(v => !attestors.has(v.toString()) && !proposer.equals(v)).map(v => v.toString()),
189
+ );
190
+
191
+ this.logger.debug(`Retrieved ${attestors.size} attestors out of ${committee.length} for slot ${slot}`, {
192
+ blockStatus,
193
+ proposer: proposer.toString(),
194
+ archive,
195
+ slot,
196
+ attestors: [...attestors],
197
+ missedAttestors: [...missedAttestors],
198
+ committee: committee.map(c => c.toString()),
199
+ });
200
+
201
+ // Compute the status for each validator in the committee
202
+ const statusFor = (who: `0x${string}`): ValidatorStatusInSlot | undefined => {
203
+ if (who === proposer.toString()) {
204
+ return `block-${blockStatus}`;
205
+ } else if (attestors.has(who)) {
206
+ return 'attestation-sent';
207
+ } else if (missedAttestors.has(who)) {
208
+ return 'attestation-missed';
209
+ } else {
210
+ return undefined;
211
+ }
212
+ };
213
+
214
+ return Object.fromEntries(committee.map(v => v.toString()).map(who => [who, statusFor(who)]));
215
+ }
216
+
217
+ /** Push the status for each slot for each validator. */
218
+ protected updateValidators(slot: bigint, stats: Record<`0x${string}`, ValidatorStatusInSlot | undefined>) {
219
+ return this.store.updateValidators(slot, stats);
220
+ }
221
+
222
+ /** Computes stats to be returned based on stored data. */
223
+ public async computeStats(): Promise<ValidatorsStats> {
224
+ const histories = await this.store.getHistories();
225
+ const slotNow = this.epochCache.getEpochAndSlotNow().slot;
226
+ const fromSlot = (this.lastProcessedSlot ?? slotNow) - BigInt(this.store.getHistoryLength());
227
+ const result: Record<`0x${string}`, ValidatorStats> = {};
228
+ for (const [address, history] of Object.entries(histories)) {
229
+ const validatorAddress = address as `0x${string}`;
230
+ result[validatorAddress] = this.computeStatsForValidator(validatorAddress, history, fromSlot);
231
+ }
232
+ return {
233
+ stats: result,
234
+ lastProcessedSlot: this.lastProcessedSlot,
235
+ initialSlot: this.initialSlot,
236
+ slotWindow: this.store.getHistoryLength(),
237
+ };
238
+ }
239
+
240
+ protected computeStatsForValidator(
241
+ address: `0x${string}`,
242
+ allHistory: ValidatorStatusHistory,
243
+ fromSlot?: bigint,
244
+ ): ValidatorStats {
245
+ const history = fromSlot ? allHistory.filter(h => h.slot >= fromSlot) : allHistory;
246
+ return {
247
+ address: EthAddress.fromString(address),
248
+ lastProposal: this.computeFromSlot(
249
+ history.filter(h => h.status === 'block-proposed' || h.status === 'block-mined').at(-1)?.slot,
250
+ ),
251
+ lastAttestation: this.computeFromSlot(history.filter(h => h.status === 'attestation-sent').at(-1)?.slot),
252
+ totalSlots: history.length,
253
+ missedProposals: this.computeMissed(history, 'block', 'block-missed'),
254
+ missedAttestations: this.computeMissed(history, 'attestation', 'attestation-missed'),
255
+ history,
256
+ };
257
+ }
258
+
259
+ protected computeMissed(
260
+ history: ValidatorStatusHistory,
261
+ computeOverPrefix: ValidatorStatusType,
262
+ filter: ValidatorStatusInSlot,
263
+ ) {
264
+ const relevantHistory = history.filter(h => h.status.startsWith(computeOverPrefix));
265
+ const filteredHistory = relevantHistory.filter(h => h.status === filter);
266
+ return {
267
+ currentStreak: countWhile([...relevantHistory].reverse(), h => h.status === filter),
268
+ rate: filteredHistory.length / relevantHistory.length,
269
+ count: filteredHistory.length,
270
+ };
271
+ }
272
+
273
+ protected computeFromSlot(slot: bigint | undefined) {
274
+ if (slot === undefined) {
275
+ return undefined;
276
+ }
277
+ const timestamp = getTimestampForSlot(slot, this.epochCache.getL1Constants());
278
+ return { timestamp, slot, date: new Date(Number(timestamp) * 1000).toISOString() };
279
+ }
280
+ }
@@ -0,0 +1,103 @@
1
+ import { BufferReader, numToUInt8, numToUInt32BE, serializeToBuffer } from '@aztec/foundation/serialize';
2
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
3
+ import type { ValidatorStatusHistory, ValidatorStatusInSlot } from '@aztec/stdlib/validators';
4
+
5
+ export class SentinelStore {
6
+ public static readonly SCHEMA_VERSION = 1;
7
+
8
+ private readonly map: AztecAsyncMap<`0x${string}`, Buffer>;
9
+
10
+ constructor(private store: AztecAsyncKVStore, private config: { historyLength: number }) {
11
+ this.map = store.openMap('sentinel-validator-status');
12
+ }
13
+
14
+ public getHistoryLength() {
15
+ return this.config.historyLength;
16
+ }
17
+
18
+ public async updateValidators(slot: bigint, statuses: Record<`0x${string}`, ValidatorStatusInSlot | undefined>) {
19
+ await this.store.transactionAsync(async () => {
20
+ for (const [who, status] of Object.entries(statuses)) {
21
+ if (status) {
22
+ await this.pushValidatorStatusForSlot(who as `0x${string}`, slot, status);
23
+ }
24
+ }
25
+ });
26
+ }
27
+
28
+ private async pushValidatorStatusForSlot(
29
+ who: `0x${string}`,
30
+ slot: bigint,
31
+ status: 'block-mined' | 'block-proposed' | 'block-missed' | 'attestation-sent' | 'attestation-missed',
32
+ ) {
33
+ const currentHistory = (await this.getHistory(who)) ?? [];
34
+ const newHistory = [...currentHistory, { slot, status }].slice(-this.config.historyLength);
35
+ await this.map.set(who, this.serializeHistory(newHistory));
36
+ }
37
+
38
+ public async getHistories(): Promise<Record<`0x${string}`, ValidatorStatusHistory>> {
39
+ const histories: Record<`0x${string}`, ValidatorStatusHistory> = {};
40
+ for await (const [address, history] of this.map.entriesAsync()) {
41
+ histories[address] = this.deserializeHistory(history);
42
+ }
43
+ return histories;
44
+ }
45
+
46
+ private async getHistory(address: `0x${string}`): Promise<ValidatorStatusHistory | undefined> {
47
+ const data = await this.map.getAsync(address);
48
+ return data && this.deserializeHistory(data);
49
+ }
50
+
51
+ private serializeHistory(history: ValidatorStatusHistory): Buffer {
52
+ return serializeToBuffer(
53
+ history.map(h => [numToUInt32BE(Number(h.slot)), numToUInt8(this.statusToNumber(h.status))]),
54
+ );
55
+ }
56
+
57
+ private deserializeHistory(buffer: Buffer): ValidatorStatusHistory {
58
+ const reader = new BufferReader(buffer);
59
+ const history: ValidatorStatusHistory = [];
60
+ while (!reader.isEmpty()) {
61
+ const slot = BigInt(reader.readNumber());
62
+ const status = this.statusFromNumber(reader.readUInt8());
63
+ history.push({ slot, status });
64
+ }
65
+ return history;
66
+ }
67
+
68
+ private statusToNumber(status: ValidatorStatusInSlot): number {
69
+ switch (status) {
70
+ case 'block-mined':
71
+ return 1;
72
+ case 'block-proposed':
73
+ return 2;
74
+ case 'block-missed':
75
+ return 3;
76
+ case 'attestation-sent':
77
+ return 4;
78
+ case 'attestation-missed':
79
+ return 5;
80
+ default: {
81
+ const _exhaustive: never = status;
82
+ throw new Error(`Unknown status: ${status}`);
83
+ }
84
+ }
85
+ }
86
+
87
+ private statusFromNumber(status: number): ValidatorStatusInSlot {
88
+ switch (status) {
89
+ case 1:
90
+ return 'block-mined';
91
+ case 2:
92
+ return 'block-proposed';
93
+ case 3:
94
+ return 'block-missed';
95
+ case 4:
96
+ return 'attestation-sent';
97
+ case 5:
98
+ return 'attestation-missed';
99
+ default:
100
+ throw new Error(`Unknown status: ${status}`);
101
+ }
102
+ }
103
+ }