@aztec/slasher 0.0.1-commit.24de95ac

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 (82) hide show
  1. package/README.md +218 -0
  2. package/dest/config.d.ts +6 -0
  3. package/dest/config.d.ts.map +1 -0
  4. package/dest/config.js +134 -0
  5. package/dest/empire_slasher_client.d.ts +189 -0
  6. package/dest/empire_slasher_client.d.ts.map +1 -0
  7. package/dest/empire_slasher_client.js +572 -0
  8. package/dest/factory/create_facade.d.ts +15 -0
  9. package/dest/factory/create_facade.d.ts.map +1 -0
  10. package/dest/factory/create_facade.js +23 -0
  11. package/dest/factory/create_implementation.d.ts +17 -0
  12. package/dest/factory/create_implementation.d.ts.map +1 -0
  13. package/dest/factory/create_implementation.js +73 -0
  14. package/dest/factory/get_settings.d.ts +4 -0
  15. package/dest/factory/get_settings.d.ts.map +1 -0
  16. package/dest/factory/get_settings.js +36 -0
  17. package/dest/factory/index.d.ts +3 -0
  18. package/dest/factory/index.d.ts.map +1 -0
  19. package/dest/factory/index.js +2 -0
  20. package/dest/index.d.ts +11 -0
  21. package/dest/index.d.ts.map +1 -0
  22. package/dest/index.js +10 -0
  23. package/dest/null_slasher_client.d.ts +16 -0
  24. package/dest/null_slasher_client.d.ts.map +1 -0
  25. package/dest/null_slasher_client.js +33 -0
  26. package/dest/slash_offenses_collector.d.ts +45 -0
  27. package/dest/slash_offenses_collector.d.ts.map +1 -0
  28. package/dest/slash_offenses_collector.js +94 -0
  29. package/dest/slash_round_monitor.d.ts +29 -0
  30. package/dest/slash_round_monitor.d.ts.map +1 -0
  31. package/dest/slash_round_monitor.js +52 -0
  32. package/dest/slasher_client_facade.d.ts +43 -0
  33. package/dest/slasher_client_facade.d.ts.map +1 -0
  34. package/dest/slasher_client_facade.js +76 -0
  35. package/dest/slasher_client_interface.d.ts +38 -0
  36. package/dest/slasher_client_interface.d.ts.map +1 -0
  37. package/dest/slasher_client_interface.js +4 -0
  38. package/dest/stores/offenses_store.d.ts +37 -0
  39. package/dest/stores/offenses_store.d.ts.map +1 -0
  40. package/dest/stores/offenses_store.js +105 -0
  41. package/dest/stores/payloads_store.d.ts +29 -0
  42. package/dest/stores/payloads_store.d.ts.map +1 -0
  43. package/dest/stores/payloads_store.js +125 -0
  44. package/dest/stores/schema_version.d.ts +2 -0
  45. package/dest/stores/schema_version.d.ts.map +1 -0
  46. package/dest/stores/schema_version.js +1 -0
  47. package/dest/tally_slasher_client.d.ts +129 -0
  48. package/dest/tally_slasher_client.d.ts.map +1 -0
  49. package/dest/tally_slasher_client.js +349 -0
  50. package/dest/test/dummy_watcher.d.ts +11 -0
  51. package/dest/test/dummy_watcher.d.ts.map +1 -0
  52. package/dest/test/dummy_watcher.js +14 -0
  53. package/dest/watcher.d.ts +21 -0
  54. package/dest/watcher.d.ts.map +1 -0
  55. package/dest/watcher.js +1 -0
  56. package/dest/watchers/attestations_block_watcher.d.ts +33 -0
  57. package/dest/watchers/attestations_block_watcher.d.ts.map +1 -0
  58. package/dest/watchers/attestations_block_watcher.js +135 -0
  59. package/dest/watchers/epoch_prune_watcher.d.ts +37 -0
  60. package/dest/watchers/epoch_prune_watcher.d.ts.map +1 -0
  61. package/dest/watchers/epoch_prune_watcher.js +135 -0
  62. package/package.json +89 -0
  63. package/src/config.ts +157 -0
  64. package/src/empire_slasher_client.ts +656 -0
  65. package/src/factory/create_facade.ts +52 -0
  66. package/src/factory/create_implementation.ts +159 -0
  67. package/src/factory/get_settings.ts +58 -0
  68. package/src/factory/index.ts +2 -0
  69. package/src/index.ts +10 -0
  70. package/src/null_slasher_client.ts +40 -0
  71. package/src/slash_offenses_collector.ts +118 -0
  72. package/src/slash_round_monitor.ts +61 -0
  73. package/src/slasher_client_facade.ts +100 -0
  74. package/src/slasher_client_interface.ts +45 -0
  75. package/src/stores/offenses_store.ts +145 -0
  76. package/src/stores/payloads_store.ts +146 -0
  77. package/src/stores/schema_version.ts +1 -0
  78. package/src/tally_slasher_client.ts +436 -0
  79. package/src/test/dummy_watcher.ts +21 -0
  80. package/src/watcher.ts +27 -0
  81. package/src/watchers/attestations_block_watcher.ts +180 -0
  82. package/src/watchers/epoch_prune_watcher.ts +192 -0
@@ -0,0 +1,436 @@
1
+ import { EthAddress } from '@aztec/aztec.js/addresses';
2
+ import type { EpochCache } from '@aztec/epoch-cache';
3
+ import { RollupContract, SlasherContract, TallySlashingProposerContract } from '@aztec/ethereum/contracts';
4
+ import { maxBigint } from '@aztec/foundation/bigint';
5
+ import { compactArray, partition, times } from '@aztec/foundation/collection';
6
+ import { createLogger } from '@aztec/foundation/log';
7
+ import { sleep } from '@aztec/foundation/sleep';
8
+ import type { DateProvider } from '@aztec/foundation/timer';
9
+ import type { Prettify } from '@aztec/foundation/types';
10
+ import type { SlasherConfig } from '@aztec/stdlib/interfaces/server';
11
+ import {
12
+ type Offense,
13
+ OffenseType,
14
+ type ProposerSlashAction,
15
+ type ProposerSlashActionProvider,
16
+ type SlashPayloadRound,
17
+ getEpochsForRound,
18
+ getSlashConsensusVotesFromOffenses,
19
+ } from '@aztec/stdlib/slashing';
20
+
21
+ import type { Hex } from 'viem';
22
+
23
+ import {
24
+ SlashOffensesCollector,
25
+ type SlashOffensesCollectorConfig,
26
+ type SlashOffensesCollectorSettings,
27
+ } from './slash_offenses_collector.js';
28
+ import { SlashRoundMonitor, type SlashRoundMonitorSettings } from './slash_round_monitor.js';
29
+ import type { SlasherClientInterface } from './slasher_client_interface.js';
30
+ import type { SlasherOffensesStore } from './stores/offenses_store.js';
31
+ import type { Watcher } from './watcher.js';
32
+
33
+ /** Settings used in the tally slasher client, loaded from the L1 contracts during initialization */
34
+ export type TallySlasherSettings = Prettify<
35
+ SlashRoundMonitorSettings &
36
+ SlashOffensesCollectorSettings & {
37
+ slashingLifetimeInRounds: number;
38
+ slashingExecutionDelayInRounds: number;
39
+ slashingRoundSizeInEpochs: number;
40
+ slashingOffsetInRounds: number;
41
+ slashingQuorumSize: number;
42
+ slashingAmounts: [bigint, bigint, bigint];
43
+ /** Committee size for block proposal */
44
+ targetCommitteeSize: number;
45
+ }
46
+ >;
47
+
48
+ export type TallySlasherClientConfig = SlashOffensesCollectorConfig &
49
+ Pick<SlasherConfig, 'slashValidatorsAlways' | 'slashValidatorsNever' | 'slashExecuteRoundsLookBack'>;
50
+
51
+ /**
52
+ * The Tally Slasher client is responsible for managing slashable offenses using
53
+ * the consensus-based slashing model where proposers vote on individual validator offenses.
54
+ *
55
+ * The client subscribes to several slash watchers that emit offenses and tracks them. When the slasher is the
56
+ * proposer, it votes for which validators from past epochs should be slashed based on collected offenses.
57
+ * Voting is handled by the sequencer publisher, the slasher client does not interact with L1 directly.
58
+ * The client also monitors rounds and executes slashing when rounds become executable after reaching quorum.
59
+ *
60
+ * Voting and offense collection
61
+ * - Time is divided into rounds (ROUND_SIZE slots each). During each round, block proposers can submit votes
62
+ * indicating which validators from SLASH_OFFSET_IN_ROUNDS rounds ago should be slashed.
63
+ * - Votes are encoded as bytes where each validator's vote is represented by 2 bits indicating the slash amount (0-3 slash units)
64
+ * for the validator in the committee being slashed.
65
+ * - When gathering offenses for round N, the system looks at offenses from round N-2 (where 2 is the hardcoded
66
+ * offset), giving time to detect offenses and vote on them in a later round.
67
+ * - Each offense carries an epoch or block identifier to differentiate multiple offenses by the same validator.
68
+ *
69
+ * Quorum and execution
70
+ * - After a round ends, there is an execution delay period for review so the VETOER in the Slasher can veto
71
+ * if needed.
72
+ * - Once the delay passes, anyone can call executeRound() to tally votes and execute slashing.
73
+ * - Validators that reach the quorum threshold are slashed. A vote for slashing N units is also considered
74
+ * a vote for slashing N-1, N-2, ..., 1 units. The system slashes for the largest amount that reaches quorum.
75
+ * - The client monitors executable rounds and triggers execution when appropriate.
76
+ *
77
+ * Differences from Empire model
78
+ * - No fixed slash payloads - votes are for individual validator offenses encoded in bytes
79
+ * - The L1 contract determines which offenses reach quorum rather than nodes agreeing on a payload
80
+ * - Proposers vote directly on which validators to slash and by how much
81
+ * - Uses a slash offset to vote on validators from past rounds (e.g., round N votes on round N-2)
82
+ */
83
+ export class TallySlasherClient implements ProposerSlashActionProvider, SlasherClientInterface {
84
+ protected unwatchCallbacks: (() => void)[] = [];
85
+ protected roundMonitor: SlashRoundMonitor;
86
+ protected offensesCollector: SlashOffensesCollector;
87
+
88
+ constructor(
89
+ private config: TallySlasherClientConfig,
90
+ private settings: TallySlasherSettings,
91
+ private tallySlashingProposer: TallySlashingProposerContract,
92
+ private slasher: SlasherContract,
93
+ private rollup: RollupContract,
94
+ watchers: Watcher[],
95
+ private epochCache: EpochCache,
96
+ private dateProvider: DateProvider,
97
+ private offensesStore: SlasherOffensesStore,
98
+ private log = createLogger('slasher:consensus'),
99
+ ) {
100
+ this.roundMonitor = new SlashRoundMonitor(settings, dateProvider);
101
+ this.offensesCollector = new SlashOffensesCollector(config, settings, watchers, offensesStore);
102
+ }
103
+
104
+ public async start() {
105
+ this.log.debug('Starting Tally Slasher client...');
106
+
107
+ this.roundMonitor.start();
108
+ await this.offensesCollector.start();
109
+
110
+ // Listen for RoundExecuted events
111
+ this.unwatchCallbacks.push(
112
+ this.tallySlashingProposer.listenToRoundExecuted(
113
+ ({ round, slashCount, l1BlockHash }) =>
114
+ void this.handleRoundExecuted(round, slashCount, l1BlockHash).catch(err =>
115
+ this.log.error('Error handling round executed', err),
116
+ ),
117
+ ),
118
+ );
119
+
120
+ // Check for round changes
121
+ this.unwatchCallbacks.push(this.roundMonitor.listenToNewRound(round => this.handleNewRound(round)));
122
+
123
+ this.log.info(`Started tally slasher client`);
124
+ return Promise.resolve();
125
+ }
126
+
127
+ /**
128
+ * Stop the tally slasher client
129
+ */
130
+ public async stop() {
131
+ this.log.debug('Stopping Tally Slasher client...');
132
+
133
+ for (const unwatchCallback of this.unwatchCallbacks) {
134
+ unwatchCallback();
135
+ }
136
+
137
+ this.roundMonitor.stop();
138
+ await this.offensesCollector.stop();
139
+
140
+ // Sleeping to sidestep viem issue with unwatching events
141
+ await sleep(2000);
142
+ this.log.info('Tally Slasher client stopped');
143
+ }
144
+
145
+ /** Returns the current config */
146
+ public getConfig(): SlasherConfig {
147
+ return this.config as SlasherConfig;
148
+ }
149
+
150
+ /** Update the config of the slasher client */
151
+ public updateConfig(config: Partial<SlasherConfig>) {
152
+ this.config = { ...this.config, ...config };
153
+ }
154
+
155
+ /** Triggered on a time basis when we enter a new slashing round. Clears expired offenses. */
156
+ protected async handleNewRound(round: bigint) {
157
+ this.log.info(`Starting new tally slashing round ${round}`);
158
+ await this.offensesCollector.handleNewRound(round);
159
+ }
160
+
161
+ /** Called when we see a RoundExecuted event on the TallySlashingProposer (just for logging). */
162
+ protected async handleRoundExecuted(round: bigint, slashCount: bigint, l1BlockHash: Hex) {
163
+ const slashes = await this.rollup.getSlashEvents(l1BlockHash);
164
+ this.log.info(`Slashing round ${round} has been executed with ${slashCount} slashes`, { slashes });
165
+ }
166
+
167
+ /**
168
+ * Get the actions the proposer should take for slashing
169
+ * @param slotNumber - The current slot number
170
+ * @returns The actions to take
171
+ */
172
+ public async getProposerActions(slotNumber: bigint): Promise<ProposerSlashAction[]> {
173
+ const [executeAction, voteAction] = await Promise.all([
174
+ this.getExecuteSlashAction(slotNumber),
175
+ this.getVoteOffensesAction(slotNumber),
176
+ ]);
177
+
178
+ return compactArray<ProposerSlashAction>([executeAction, voteAction]);
179
+ }
180
+
181
+ /**
182
+ * Returns an execute slash action if there are any rounds ready to be executed.
183
+ * Returns the oldest slash action if there are multiple rounds pending execution.
184
+ */
185
+ protected async getExecuteSlashAction(slotNumber: bigint): Promise<ProposerSlashAction | undefined> {
186
+ const { round: currentRound } = this.roundMonitor.getRoundForSlot(slotNumber);
187
+ const slashingExecutionDelayInRounds = BigInt(this.settings.slashingExecutionDelayInRounds);
188
+ const executableRound = currentRound - slashingExecutionDelayInRounds - 1n;
189
+ const lookBack = BigInt(this.config.slashExecuteRoundsLookBack);
190
+ const slashingLifetimeInRounds = BigInt(this.settings.slashingLifetimeInRounds);
191
+
192
+ // Compute the oldest executable round considering both lookBack and lifetimeInRounds
193
+ // A round is only executable if currentRound <= round + lifetimeInRounds
194
+ // So the oldest round we can execute is: currentRound - lifetimeInRounds
195
+ const oldestByLifetime = maxBigint(0n, currentRound - slashingLifetimeInRounds);
196
+ const oldestByLookBack = maxBigint(0n, executableRound - lookBack);
197
+ const oldestExecutableRound = maxBigint(oldestByLifetime, oldestByLookBack);
198
+
199
+ // Check if slashing is enabled at all
200
+ if (!(await this.slasher.isSlashingEnabled())) {
201
+ this.log.warn(`Slashing is disabled in the Slasher contract (skipping execution)`);
202
+ return undefined;
203
+ }
204
+
205
+ this.log.debug(`Checking slashing rounds ${oldestExecutableRound} to ${executableRound} to execute`, {
206
+ slotNumber,
207
+ currentRound,
208
+ oldestExecutableRound,
209
+ oldestByLifetime,
210
+ oldestByLookBack,
211
+ executableRound,
212
+ slashingExecutionDelayInRounds,
213
+ lookBack,
214
+ slashingLifetimeInRounds,
215
+ });
216
+
217
+ // Iterate over all rounds, starting from the oldest, until we find one that is executable
218
+ for (let roundToCheck = oldestExecutableRound; roundToCheck <= executableRound; roundToCheck++) {
219
+ const action = await this.tryGetRoundExecuteAction(roundToCheck, slotNumber);
220
+ if (action) {
221
+ return action;
222
+ }
223
+ }
224
+
225
+ // And return nothing if none are found
226
+ return undefined;
227
+ }
228
+
229
+ /**
230
+ * Checks if a given round is executable and returns an execute-slash action for it if so.
231
+ * Assumes round number has already been checked against lifetime and execution delay.
232
+ * @param executableRound - The round to check for execution
233
+ */
234
+ private async tryGetRoundExecuteAction(
235
+ executableRound: bigint,
236
+ slotNumber: bigint,
237
+ ): Promise<ProposerSlashAction | undefined> {
238
+ let logData: Record<string, unknown> = { executableRound, slotNumber };
239
+ this.log.debug(`Testing if slashing round ${executableRound} is executable`, logData);
240
+
241
+ try {
242
+ const roundInfo = await this.tallySlashingProposer.getRound(executableRound);
243
+ logData = { ...logData, roundInfo };
244
+ if (roundInfo.isExecuted) {
245
+ this.log.verbose(`Round ${executableRound} has already been executed`, logData);
246
+ return undefined;
247
+ } else if (roundInfo.voteCount === 0n) {
248
+ this.log.debug(`Round ${executableRound} received no votes`, logData);
249
+ return undefined;
250
+ } else if (roundInfo.voteCount < this.settings.slashingQuorumSize) {
251
+ this.log.verbose(`Round ${executableRound} does not have enough votes to execute`, logData);
252
+ return undefined;
253
+ }
254
+
255
+ // Check if round is ready to execute at the given slot
256
+ const isReadyToExecute = await this.tallySlashingProposer.isRoundReadyToExecute(executableRound, slotNumber);
257
+ if (!isReadyToExecute) {
258
+ this.log.warn(
259
+ `Round ${executableRound} is not ready to execute at slot ${slotNumber} according to contract check`,
260
+ logData,
261
+ );
262
+ return undefined;
263
+ }
264
+
265
+ // Check if the round yields any slashing at all
266
+ const { actions: slashActions, committees } = await this.tallySlashingProposer.getTally(executableRound);
267
+ if (slashActions.length === 0) {
268
+ this.log.verbose(`Round ${executableRound} does not resolve in any slashing`, logData);
269
+ return undefined;
270
+ }
271
+
272
+ // Check if the slash payload is vetoed
273
+ const payload = await this.tallySlashingProposer.getPayload(executableRound);
274
+ const isVetoed = await this.slasher.isPayloadVetoed(payload.address);
275
+ if (isVetoed) {
276
+ this.log.warn(`Round ${executableRound} payload is vetoed (skipping execution)`, {
277
+ payloadAddress: payload.address.toString(),
278
+ ...logData,
279
+ });
280
+ return undefined;
281
+ }
282
+
283
+ this.log.info(`Round ${executableRound} is ready to execute with ${slashActions.length} slashes`, {
284
+ slashActions,
285
+ payloadAddress: payload.address.toString(),
286
+ ...logData,
287
+ });
288
+
289
+ // We only need to post committees that are actually slashed
290
+ const slashedCommittees = committees.map(c =>
291
+ c.some(validator => slashActions.some(action => action.validator.equals(validator))) ? c : [],
292
+ );
293
+ this.log.debug(`Collected ${committees.length} committees for executing round ${executableRound}`, {
294
+ slashedCommittees,
295
+ ...logData,
296
+ });
297
+ return { type: 'execute-slash', round: executableRound, committees: slashedCommittees };
298
+ } catch (error) {
299
+ this.log.error(`Error checking round to execute ${executableRound}`, error);
300
+ return undefined;
301
+ }
302
+ }
303
+
304
+ /** Returns a vote action based on offenses from the target round (with offset applied) */
305
+ protected async getVoteOffensesAction(slotNumber: bigint): Promise<ProposerSlashAction | undefined> {
306
+ // Compute what round we are in based on the slot number and what round will be slashed
307
+ const { round: currentRound } = this.roundMonitor.getRoundForSlot(slotNumber);
308
+ const slashedRound = this.getSlashedRound(currentRound);
309
+ if (slashedRound < 0n) {
310
+ return undefined;
311
+ }
312
+
313
+ // Compute offenses to slash, by loading the offenses for this round, adding synthetic offenses
314
+ // for validators that should always be slashed, and removing the ones that should never be slashed.
315
+ const offensesForRound = await this.gatherOffensesForRound(currentRound);
316
+ const offensesFromAlwaysSlash = (this.config.slashValidatorsAlways ?? []).map(validator => ({
317
+ validator,
318
+ amount: this.settings.slashingAmounts[2],
319
+ offenseType: OffenseType.UNKNOWN,
320
+ }));
321
+ const [offensesToForgive, offensesToSlash] = partition([...offensesForRound, ...offensesFromAlwaysSlash], offense =>
322
+ this.config.slashValidatorsNever?.some(v => v.equals(offense.validator)),
323
+ );
324
+
325
+ if (offensesFromAlwaysSlash.length > 0) {
326
+ this.log.verbose(`Slashing ${offensesFromAlwaysSlash.length} validators due to always-slash config`, {
327
+ slotNumber,
328
+ currentRound,
329
+ slashedRound,
330
+ offensesToForgive,
331
+ slashValidatorsAlways: this.config.slashValidatorsAlways,
332
+ });
333
+ }
334
+
335
+ if (offensesToForgive.length > 0) {
336
+ this.log.verbose(`Skipping slashing of ${offensesToForgive.length} offenses`, {
337
+ slotNumber,
338
+ currentRound,
339
+ slashedRound,
340
+ offensesToForgive,
341
+ slashValidatorsNever: this.config.slashValidatorsNever,
342
+ });
343
+ }
344
+
345
+ if (offensesToSlash.length === 0) {
346
+ this.log.debug(`No offenses to slash for round ${slashedRound}`, { currentRound, slotNumber, slashedRound });
347
+ return undefined;
348
+ }
349
+
350
+ this.log.info(`Voting to slash ${offensesToSlash.length} offenses`, {
351
+ slotNumber,
352
+ currentRound,
353
+ slashedRound,
354
+ offensesToSlash,
355
+ });
356
+
357
+ const committees = await this.collectCommitteesActiveDuringRound(slashedRound);
358
+ const epochsForCommittees = getEpochsForRound(slashedRound, this.settings);
359
+ const votes = getSlashConsensusVotesFromOffenses(offensesToSlash, committees, epochsForCommittees, this.settings);
360
+ if (votes.every(v => v === 0)) {
361
+ this.log.warn(`Computed votes for offenses are all zero. Skipping vote.`, {
362
+ slotNumber,
363
+ currentRound,
364
+ slashedRound,
365
+ offensesToSlash,
366
+ committees,
367
+ });
368
+ return undefined;
369
+ }
370
+
371
+ this.log.debug(`Computed votes for slashing ${offensesToSlash.length} offenses`, {
372
+ slashedRound,
373
+ currentRound,
374
+ votes,
375
+ committees,
376
+ settings: this.settings,
377
+ });
378
+
379
+ return {
380
+ type: 'vote-offenses',
381
+ round: currentRound,
382
+ votes,
383
+ committees,
384
+ };
385
+ }
386
+
387
+ /** Returns the committees that were active during the timespan of a given round */
388
+ private collectCommitteesActiveDuringRound(round: bigint): Promise<EthAddress[][]> {
389
+ const epochsToSlash = getEpochsForRound(round, this.settings);
390
+ const emptyCommittee = times(Number(this.settings.targetCommitteeSize), () => EthAddress.ZERO);
391
+ return Promise.all(
392
+ epochsToSlash.map(epoch => this.epochCache.getCommitteeForEpoch(epoch).then(c => c.committee ?? emptyCommittee)),
393
+ );
394
+ }
395
+
396
+ /**
397
+ * Get slash payloads is NOT SUPPORTED in tally model
398
+ * @throws Error indicating this operation is not supported
399
+ */
400
+ public getSlashPayloads(): Promise<SlashPayloadRound[]> {
401
+ return Promise.reject(new Error('Tally slashing model does not support slash payloads'));
402
+ }
403
+
404
+ /**
405
+ * Gather offenses to be slashed on a given round.
406
+ * In tally slashing, round N slashes validators from round N - slashOffsetInRounds.
407
+ * @param round - The round to get offenses for, defaults to current round
408
+ * @returns Array of pending offenses for the round with offset applied
409
+ */
410
+ public async gatherOffensesForRound(round?: bigint): Promise<Offense[]> {
411
+ const targetRound = this.getSlashedRound(round);
412
+ if (targetRound < 0n) {
413
+ return [];
414
+ }
415
+
416
+ return await this.offensesStore.getOffensesForRound(targetRound);
417
+ }
418
+
419
+ /** Returns all pending offenses stored */
420
+ public getPendingOffenses(): Promise<Offense[]> {
421
+ return this.offensesStore.getPendingOffenses();
422
+ }
423
+
424
+ /**
425
+ * Returns the round to be slashed given the current round by applying the slash offset.
426
+ * During round N, we cannot slash the validators from the epochs of the same round, since the round is not over,
427
+ * and besides we would be asking the current validators to vote to slash themselves. So during round N we look at the
428
+ * epochs spanned during round N - SLASH_OFFSET_IN_ROUNDS. This offset means that the epochs we slash are complete,
429
+ * and also gives nodes time to detect any misbehavior (eg slashing for prunes requires the proof submission window to
430
+ * pass).
431
+ */
432
+ private getSlashedRound(round?: bigint) {
433
+ round ??= this.roundMonitor.getCurrentRound().round;
434
+ return round - BigInt(this.settings.slashingOffsetInRounds);
435
+ }
436
+ }
@@ -0,0 +1,21 @@
1
+ import type { SlasherConfig } from '@aztec/stdlib/interfaces/server';
2
+
3
+ import EventEmitter from 'node:events';
4
+
5
+ import { WANT_TO_SLASH_EVENT, type WantToSlashArgs, type Watcher, type WatcherEmitter } from '../watcher.js';
6
+
7
+ export class DummyWatcher extends (EventEmitter as new () => WatcherEmitter) implements Watcher {
8
+ public updateConfig(_config: Partial<SlasherConfig>) {}
9
+
10
+ public start() {
11
+ return Promise.resolve();
12
+ }
13
+
14
+ public stop() {
15
+ return Promise.resolve();
16
+ }
17
+
18
+ public triggerSlash(args: WantToSlashArgs[]) {
19
+ this.emit(WANT_TO_SLASH_EVENT, args);
20
+ }
21
+ }
package/src/watcher.ts ADDED
@@ -0,0 +1,27 @@
1
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
+ import type { TypedEventEmitter } from '@aztec/foundation/types';
3
+ import { OffenseType } from '@aztec/stdlib/slashing';
4
+
5
+ import type { SlasherConfig } from './config.js';
6
+
7
+ export const WANT_TO_SLASH_EVENT = 'want-to-slash' as const;
8
+
9
+ export interface WantToSlashArgs {
10
+ validator: EthAddress;
11
+ amount: bigint;
12
+ offenseType: OffenseType;
13
+ epochOrSlot: bigint; // Epoch number for epoch-based offenses, block number for block-based
14
+ }
15
+
16
+ // Event map for specific, known events of a watcher
17
+ export interface WatcherEventMap {
18
+ [WANT_TO_SLASH_EVENT]: (args: WantToSlashArgs[]) => void;
19
+ }
20
+
21
+ export type WatcherEmitter = TypedEventEmitter<WatcherEventMap>;
22
+
23
+ export type Watcher = WatcherEmitter & {
24
+ start?: () => Promise<void>;
25
+ stop?: () => Promise<void>;
26
+ updateConfig: (config: Partial<SlasherConfig>) => void;
27
+ };
@@ -0,0 +1,180 @@
1
+ import { EpochCache } from '@aztec/epoch-cache';
2
+ import { merge, pick } from '@aztec/foundation/collection';
3
+ import { type Logger, createLogger } from '@aztec/foundation/log';
4
+ import {
5
+ type InvalidBlockDetectedEvent,
6
+ type L2BlockInfo,
7
+ type L2BlockSourceEventEmitter,
8
+ L2BlockSourceEvents,
9
+ type ValidateBlockNegativeResult,
10
+ } from '@aztec/stdlib/block';
11
+ import { OffenseType } from '@aztec/stdlib/slashing';
12
+
13
+ import EventEmitter from 'node:events';
14
+
15
+ import type { SlasherConfig } from '../config.js';
16
+ import { WANT_TO_SLASH_EVENT, type WantToSlashArgs, type Watcher, type WatcherEmitter } from '../watcher.js';
17
+
18
+ const AttestationsBlockWatcherConfigKeys = [
19
+ 'slashAttestDescendantOfInvalidPenalty',
20
+ 'slashProposeInvalidAttestationsPenalty',
21
+ ] as const;
22
+
23
+ type AttestationsBlockWatcherConfig = Pick<SlasherConfig, (typeof AttestationsBlockWatcherConfigKeys)[number]>;
24
+
25
+ /**
26
+ * This watcher is responsible for detecting invalid blocks and creating slashing arguments for offenders.
27
+ * An invalid block is one that doesn't have enough attestations or has incorrect attestations.
28
+ * The proposer of an invalid block should be slashed.
29
+ * If there's another block consecutive to the invalid one, its proposer and attestors should also be slashed.
30
+ */
31
+ export class AttestationsBlockWatcher extends (EventEmitter as new () => WatcherEmitter) implements Watcher {
32
+ private log: Logger = createLogger('attestations-block-watcher');
33
+
34
+ // Only keep track of the last N invalid blocks
35
+ private maxInvalidBlocks = 100;
36
+
37
+ // All invalid archive roots seen
38
+ private invalidArchiveRoots: Set<string> = new Set();
39
+
40
+ private config: AttestationsBlockWatcherConfig;
41
+
42
+ private boundHandleInvalidBlock = (event: InvalidBlockDetectedEvent) => {
43
+ try {
44
+ this.handleInvalidBlock(event);
45
+ } catch (err) {
46
+ this.log.error('Error handling invalid block', err, {
47
+ ...event.validationResult,
48
+ reason: event.validationResult.reason,
49
+ });
50
+ }
51
+ };
52
+
53
+ constructor(
54
+ private l2BlockSource: L2BlockSourceEventEmitter,
55
+ private epochCache: EpochCache,
56
+ config: AttestationsBlockWatcherConfig,
57
+ ) {
58
+ super();
59
+ this.config = pick(config, ...AttestationsBlockWatcherConfigKeys);
60
+ this.log.info('AttestationsBlockWatcher initialized');
61
+ }
62
+
63
+ public updateConfig(newConfig: Partial<AttestationsBlockWatcherConfig>) {
64
+ this.config = merge(this.config, pick(newConfig, ...AttestationsBlockWatcherConfigKeys));
65
+ this.log.verbose('AttestationsBlockWatcher config updated', this.config);
66
+ }
67
+
68
+ public start() {
69
+ this.l2BlockSource.on(L2BlockSourceEvents.InvalidAttestationsBlockDetected, this.boundHandleInvalidBlock);
70
+ return Promise.resolve();
71
+ }
72
+
73
+ public stop() {
74
+ this.l2BlockSource.removeListener(
75
+ L2BlockSourceEvents.InvalidAttestationsBlockDetected,
76
+ this.boundHandleInvalidBlock,
77
+ );
78
+ return Promise.resolve();
79
+ }
80
+
81
+ private handleInvalidBlock(event: InvalidBlockDetectedEvent): void {
82
+ const { validationResult } = event;
83
+ const block = validationResult.block;
84
+
85
+ // Check if we already have processed this block, archiver may emit the same event multiple times
86
+ if (this.invalidArchiveRoots.has(block.archive.toString())) {
87
+ this.log.trace(`Already processed invalid block ${block.blockNumber}`);
88
+ return;
89
+ }
90
+
91
+ this.log.verbose(`Detected invalid block ${block.blockNumber}`, {
92
+ ...block,
93
+ reason: validationResult.valid === false ? validationResult.reason : 'unknown',
94
+ });
95
+
96
+ // Store the invalid block
97
+ this.addInvalidBlock(event.validationResult.block);
98
+
99
+ // Slash the proposer of the invalid block
100
+ this.slashProposer(event.validationResult);
101
+
102
+ // Check if the parent of this block is invalid as well, if so, we will slash its attestors as well
103
+ this.slashAttestorsOnAncestorInvalid(event.validationResult);
104
+ }
105
+
106
+ private slashAttestorsOnAncestorInvalid(validationResult: ValidateBlockNegativeResult) {
107
+ const block = validationResult.block;
108
+
109
+ const parentArchive = block.lastArchive.toString();
110
+ if (this.invalidArchiveRoots.has(parentArchive)) {
111
+ const attestors = validationResult.attestors;
112
+ this.log.info(`Want to slash attestors of block ${block.blockNumber} built on invalid block`, {
113
+ ...block,
114
+ ...attestors,
115
+ parentArchive,
116
+ });
117
+
118
+ this.emit(
119
+ WANT_TO_SLASH_EVENT,
120
+ attestors.map(attestor => ({
121
+ validator: attestor,
122
+ amount: this.config.slashAttestDescendantOfInvalidPenalty,
123
+ offenseType: OffenseType.ATTESTED_DESCENDANT_OF_INVALID,
124
+ epochOrSlot: BigInt(block.slotNumber),
125
+ })),
126
+ );
127
+ }
128
+ }
129
+
130
+ private slashProposer(validationResult: ValidateBlockNegativeResult) {
131
+ const { reason, block } = validationResult;
132
+ const blockNumber = block.blockNumber;
133
+ const slot = BigInt(block.slotNumber);
134
+ const proposer = this.epochCache.getProposerFromEpochCommittee(validationResult, slot);
135
+
136
+ if (!proposer) {
137
+ this.log.warn(`No proposer found for block ${blockNumber} at slot ${slot}`);
138
+ return;
139
+ }
140
+
141
+ const offense = this.getOffenseFromInvalidationReason(reason);
142
+ const amount = this.config.slashProposeInvalidAttestationsPenalty;
143
+ const args: WantToSlashArgs = {
144
+ validator: proposer,
145
+ amount,
146
+ offenseType: offense,
147
+ epochOrSlot: slot,
148
+ };
149
+
150
+ this.log.info(`Want to slash proposer of block ${blockNumber} due to ${reason}`, {
151
+ ...block,
152
+ ...args,
153
+ });
154
+
155
+ this.emit(WANT_TO_SLASH_EVENT, [args]);
156
+ }
157
+
158
+ private getOffenseFromInvalidationReason(reason: ValidateBlockNegativeResult['reason']): OffenseType {
159
+ switch (reason) {
160
+ case 'invalid-attestation':
161
+ return OffenseType.PROPOSED_INCORRECT_ATTESTATIONS;
162
+ case 'insufficient-attestations':
163
+ return OffenseType.PROPOSED_INSUFFICIENT_ATTESTATIONS;
164
+ default: {
165
+ const _: never = reason;
166
+ return OffenseType.UNKNOWN;
167
+ }
168
+ }
169
+ }
170
+
171
+ private addInvalidBlock(block: L2BlockInfo) {
172
+ this.invalidArchiveRoots.add(block.archive.toString());
173
+
174
+ // Prune old entries if we exceed the maximum
175
+ if (this.invalidArchiveRoots.size > this.maxInvalidBlocks) {
176
+ const oldestKey = this.invalidArchiveRoots.keys().next().value!;
177
+ this.invalidArchiveRoots.delete(oldestKey);
178
+ }
179
+ }
180
+ }