@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,349 @@
1
+ import { EthAddress } from '@aztec/aztec.js/addresses';
2
+ import { maxBigint } from '@aztec/foundation/bigint';
3
+ import { compactArray, partition, times } from '@aztec/foundation/collection';
4
+ import { createLogger } from '@aztec/foundation/log';
5
+ import { sleep } from '@aztec/foundation/sleep';
6
+ import { OffenseType, getEpochsForRound, getSlashConsensusVotesFromOffenses } from '@aztec/stdlib/slashing';
7
+ import { SlashOffensesCollector } from './slash_offenses_collector.js';
8
+ import { SlashRoundMonitor } from './slash_round_monitor.js';
9
+ /**
10
+ * The Tally Slasher client is responsible for managing slashable offenses using
11
+ * the consensus-based slashing model where proposers vote on individual validator offenses.
12
+ *
13
+ * The client subscribes to several slash watchers that emit offenses and tracks them. When the slasher is the
14
+ * proposer, it votes for which validators from past epochs should be slashed based on collected offenses.
15
+ * Voting is handled by the sequencer publisher, the slasher client does not interact with L1 directly.
16
+ * The client also monitors rounds and executes slashing when rounds become executable after reaching quorum.
17
+ *
18
+ * Voting and offense collection
19
+ * - Time is divided into rounds (ROUND_SIZE slots each). During each round, block proposers can submit votes
20
+ * indicating which validators from SLASH_OFFSET_IN_ROUNDS rounds ago should be slashed.
21
+ * - Votes are encoded as bytes where each validator's vote is represented by 2 bits indicating the slash amount (0-3 slash units)
22
+ * for the validator in the committee being slashed.
23
+ * - When gathering offenses for round N, the system looks at offenses from round N-2 (where 2 is the hardcoded
24
+ * offset), giving time to detect offenses and vote on them in a later round.
25
+ * - Each offense carries an epoch or block identifier to differentiate multiple offenses by the same validator.
26
+ *
27
+ * Quorum and execution
28
+ * - After a round ends, there is an execution delay period for review so the VETOER in the Slasher can veto
29
+ * if needed.
30
+ * - Once the delay passes, anyone can call executeRound() to tally votes and execute slashing.
31
+ * - Validators that reach the quorum threshold are slashed. A vote for slashing N units is also considered
32
+ * a vote for slashing N-1, N-2, ..., 1 units. The system slashes for the largest amount that reaches quorum.
33
+ * - The client monitors executable rounds and triggers execution when appropriate.
34
+ *
35
+ * Differences from Empire model
36
+ * - No fixed slash payloads - votes are for individual validator offenses encoded in bytes
37
+ * - The L1 contract determines which offenses reach quorum rather than nodes agreeing on a payload
38
+ * - Proposers vote directly on which validators to slash and by how much
39
+ * - Uses a slash offset to vote on validators from past rounds (e.g., round N votes on round N-2)
40
+ */ export class TallySlasherClient {
41
+ config;
42
+ settings;
43
+ tallySlashingProposer;
44
+ slasher;
45
+ rollup;
46
+ epochCache;
47
+ dateProvider;
48
+ offensesStore;
49
+ log;
50
+ unwatchCallbacks;
51
+ roundMonitor;
52
+ offensesCollector;
53
+ constructor(config, settings, tallySlashingProposer, slasher, rollup, watchers, epochCache, dateProvider, offensesStore, log = createLogger('slasher:consensus')){
54
+ this.config = config;
55
+ this.settings = settings;
56
+ this.tallySlashingProposer = tallySlashingProposer;
57
+ this.slasher = slasher;
58
+ this.rollup = rollup;
59
+ this.epochCache = epochCache;
60
+ this.dateProvider = dateProvider;
61
+ this.offensesStore = offensesStore;
62
+ this.log = log;
63
+ this.unwatchCallbacks = [];
64
+ this.roundMonitor = new SlashRoundMonitor(settings, dateProvider);
65
+ this.offensesCollector = new SlashOffensesCollector(config, settings, watchers, offensesStore);
66
+ }
67
+ async start() {
68
+ this.log.debug('Starting Tally Slasher client...');
69
+ this.roundMonitor.start();
70
+ await this.offensesCollector.start();
71
+ // Listen for RoundExecuted events
72
+ this.unwatchCallbacks.push(this.tallySlashingProposer.listenToRoundExecuted(({ round, slashCount, l1BlockHash })=>void this.handleRoundExecuted(round, slashCount, l1BlockHash).catch((err)=>this.log.error('Error handling round executed', err))));
73
+ // Check for round changes
74
+ this.unwatchCallbacks.push(this.roundMonitor.listenToNewRound((round)=>this.handleNewRound(round)));
75
+ this.log.info(`Started tally slasher client`);
76
+ return Promise.resolve();
77
+ }
78
+ /**
79
+ * Stop the tally slasher client
80
+ */ async stop() {
81
+ this.log.debug('Stopping Tally Slasher client...');
82
+ for (const unwatchCallback of this.unwatchCallbacks){
83
+ unwatchCallback();
84
+ }
85
+ this.roundMonitor.stop();
86
+ await this.offensesCollector.stop();
87
+ // Sleeping to sidestep viem issue with unwatching events
88
+ await sleep(2000);
89
+ this.log.info('Tally Slasher client stopped');
90
+ }
91
+ /** Returns the current config */ getConfig() {
92
+ return this.config;
93
+ }
94
+ /** Update the config of the slasher client */ updateConfig(config) {
95
+ this.config = {
96
+ ...this.config,
97
+ ...config
98
+ };
99
+ }
100
+ /** Triggered on a time basis when we enter a new slashing round. Clears expired offenses. */ async handleNewRound(round) {
101
+ this.log.info(`Starting new tally slashing round ${round}`);
102
+ await this.offensesCollector.handleNewRound(round);
103
+ }
104
+ /** Called when we see a RoundExecuted event on the TallySlashingProposer (just for logging). */ async handleRoundExecuted(round, slashCount, l1BlockHash) {
105
+ const slashes = await this.rollup.getSlashEvents(l1BlockHash);
106
+ this.log.info(`Slashing round ${round} has been executed with ${slashCount} slashes`, {
107
+ slashes
108
+ });
109
+ }
110
+ /**
111
+ * Get the actions the proposer should take for slashing
112
+ * @param slotNumber - The current slot number
113
+ * @returns The actions to take
114
+ */ async getProposerActions(slotNumber) {
115
+ const [executeAction, voteAction] = await Promise.all([
116
+ this.getExecuteSlashAction(slotNumber),
117
+ this.getVoteOffensesAction(slotNumber)
118
+ ]);
119
+ return compactArray([
120
+ executeAction,
121
+ voteAction
122
+ ]);
123
+ }
124
+ /**
125
+ * Returns an execute slash action if there are any rounds ready to be executed.
126
+ * Returns the oldest slash action if there are multiple rounds pending execution.
127
+ */ async getExecuteSlashAction(slotNumber) {
128
+ const { round: currentRound } = this.roundMonitor.getRoundForSlot(slotNumber);
129
+ const slashingExecutionDelayInRounds = BigInt(this.settings.slashingExecutionDelayInRounds);
130
+ const executableRound = currentRound - slashingExecutionDelayInRounds - 1n;
131
+ const lookBack = BigInt(this.config.slashExecuteRoundsLookBack);
132
+ const slashingLifetimeInRounds = BigInt(this.settings.slashingLifetimeInRounds);
133
+ // Compute the oldest executable round considering both lookBack and lifetimeInRounds
134
+ // A round is only executable if currentRound <= round + lifetimeInRounds
135
+ // So the oldest round we can execute is: currentRound - lifetimeInRounds
136
+ const oldestByLifetime = maxBigint(0n, currentRound - slashingLifetimeInRounds);
137
+ const oldestByLookBack = maxBigint(0n, executableRound - lookBack);
138
+ const oldestExecutableRound = maxBigint(oldestByLifetime, oldestByLookBack);
139
+ // Check if slashing is enabled at all
140
+ if (!await this.slasher.isSlashingEnabled()) {
141
+ this.log.warn(`Slashing is disabled in the Slasher contract (skipping execution)`);
142
+ return undefined;
143
+ }
144
+ this.log.debug(`Checking slashing rounds ${oldestExecutableRound} to ${executableRound} to execute`, {
145
+ slotNumber,
146
+ currentRound,
147
+ oldestExecutableRound,
148
+ oldestByLifetime,
149
+ oldestByLookBack,
150
+ executableRound,
151
+ slashingExecutionDelayInRounds,
152
+ lookBack,
153
+ slashingLifetimeInRounds
154
+ });
155
+ // Iterate over all rounds, starting from the oldest, until we find one that is executable
156
+ for(let roundToCheck = oldestExecutableRound; roundToCheck <= executableRound; roundToCheck++){
157
+ const action = await this.tryGetRoundExecuteAction(roundToCheck, slotNumber);
158
+ if (action) {
159
+ return action;
160
+ }
161
+ }
162
+ // And return nothing if none are found
163
+ return undefined;
164
+ }
165
+ /**
166
+ * Checks if a given round is executable and returns an execute-slash action for it if so.
167
+ * Assumes round number has already been checked against lifetime and execution delay.
168
+ * @param executableRound - The round to check for execution
169
+ */ async tryGetRoundExecuteAction(executableRound, slotNumber) {
170
+ let logData = {
171
+ executableRound,
172
+ slotNumber
173
+ };
174
+ this.log.debug(`Testing if slashing round ${executableRound} is executable`, logData);
175
+ try {
176
+ const roundInfo = await this.tallySlashingProposer.getRound(executableRound);
177
+ logData = {
178
+ ...logData,
179
+ roundInfo
180
+ };
181
+ if (roundInfo.isExecuted) {
182
+ this.log.verbose(`Round ${executableRound} has already been executed`, logData);
183
+ return undefined;
184
+ } else if (roundInfo.voteCount === 0n) {
185
+ this.log.debug(`Round ${executableRound} received no votes`, logData);
186
+ return undefined;
187
+ } else if (roundInfo.voteCount < this.settings.slashingQuorumSize) {
188
+ this.log.verbose(`Round ${executableRound} does not have enough votes to execute`, logData);
189
+ return undefined;
190
+ }
191
+ // Check if round is ready to execute at the given slot
192
+ const isReadyToExecute = await this.tallySlashingProposer.isRoundReadyToExecute(executableRound, slotNumber);
193
+ if (!isReadyToExecute) {
194
+ this.log.warn(`Round ${executableRound} is not ready to execute at slot ${slotNumber} according to contract check`, logData);
195
+ return undefined;
196
+ }
197
+ // Check if the round yields any slashing at all
198
+ const { actions: slashActions, committees } = await this.tallySlashingProposer.getTally(executableRound);
199
+ if (slashActions.length === 0) {
200
+ this.log.verbose(`Round ${executableRound} does not resolve in any slashing`, logData);
201
+ return undefined;
202
+ }
203
+ // Check if the slash payload is vetoed
204
+ const payload = await this.tallySlashingProposer.getPayload(executableRound);
205
+ const isVetoed = await this.slasher.isPayloadVetoed(payload.address);
206
+ if (isVetoed) {
207
+ this.log.warn(`Round ${executableRound} payload is vetoed (skipping execution)`, {
208
+ payloadAddress: payload.address.toString(),
209
+ ...logData
210
+ });
211
+ return undefined;
212
+ }
213
+ this.log.info(`Round ${executableRound} is ready to execute with ${slashActions.length} slashes`, {
214
+ slashActions,
215
+ payloadAddress: payload.address.toString(),
216
+ ...logData
217
+ });
218
+ // We only need to post committees that are actually slashed
219
+ const slashedCommittees = committees.map((c)=>c.some((validator)=>slashActions.some((action)=>action.validator.equals(validator))) ? c : []);
220
+ this.log.debug(`Collected ${committees.length} committees for executing round ${executableRound}`, {
221
+ slashedCommittees,
222
+ ...logData
223
+ });
224
+ return {
225
+ type: 'execute-slash',
226
+ round: executableRound,
227
+ committees: slashedCommittees
228
+ };
229
+ } catch (error) {
230
+ this.log.error(`Error checking round to execute ${executableRound}`, error);
231
+ return undefined;
232
+ }
233
+ }
234
+ /** Returns a vote action based on offenses from the target round (with offset applied) */ async getVoteOffensesAction(slotNumber) {
235
+ // Compute what round we are in based on the slot number and what round will be slashed
236
+ const { round: currentRound } = this.roundMonitor.getRoundForSlot(slotNumber);
237
+ const slashedRound = this.getSlashedRound(currentRound);
238
+ if (slashedRound < 0n) {
239
+ return undefined;
240
+ }
241
+ // Compute offenses to slash, by loading the offenses for this round, adding synthetic offenses
242
+ // for validators that should always be slashed, and removing the ones that should never be slashed.
243
+ const offensesForRound = await this.gatherOffensesForRound(currentRound);
244
+ const offensesFromAlwaysSlash = (this.config.slashValidatorsAlways ?? []).map((validator)=>({
245
+ validator,
246
+ amount: this.settings.slashingAmounts[2],
247
+ offenseType: OffenseType.UNKNOWN
248
+ }));
249
+ const [offensesToForgive, offensesToSlash] = partition([
250
+ ...offensesForRound,
251
+ ...offensesFromAlwaysSlash
252
+ ], (offense)=>this.config.slashValidatorsNever?.some((v)=>v.equals(offense.validator)));
253
+ if (offensesFromAlwaysSlash.length > 0) {
254
+ this.log.verbose(`Slashing ${offensesFromAlwaysSlash.length} validators due to always-slash config`, {
255
+ slotNumber,
256
+ currentRound,
257
+ slashedRound,
258
+ offensesToForgive,
259
+ slashValidatorsAlways: this.config.slashValidatorsAlways
260
+ });
261
+ }
262
+ if (offensesToForgive.length > 0) {
263
+ this.log.verbose(`Skipping slashing of ${offensesToForgive.length} offenses`, {
264
+ slotNumber,
265
+ currentRound,
266
+ slashedRound,
267
+ offensesToForgive,
268
+ slashValidatorsNever: this.config.slashValidatorsNever
269
+ });
270
+ }
271
+ if (offensesToSlash.length === 0) {
272
+ this.log.debug(`No offenses to slash for round ${slashedRound}`, {
273
+ currentRound,
274
+ slotNumber,
275
+ slashedRound
276
+ });
277
+ return undefined;
278
+ }
279
+ this.log.info(`Voting to slash ${offensesToSlash.length} offenses`, {
280
+ slotNumber,
281
+ currentRound,
282
+ slashedRound,
283
+ offensesToSlash
284
+ });
285
+ const committees = await this.collectCommitteesActiveDuringRound(slashedRound);
286
+ const epochsForCommittees = getEpochsForRound(slashedRound, this.settings);
287
+ const votes = getSlashConsensusVotesFromOffenses(offensesToSlash, committees, epochsForCommittees, this.settings);
288
+ if (votes.every((v)=>v === 0)) {
289
+ this.log.warn(`Computed votes for offenses are all zero. Skipping vote.`, {
290
+ slotNumber,
291
+ currentRound,
292
+ slashedRound,
293
+ offensesToSlash,
294
+ committees
295
+ });
296
+ return undefined;
297
+ }
298
+ this.log.debug(`Computed votes for slashing ${offensesToSlash.length} offenses`, {
299
+ slashedRound,
300
+ currentRound,
301
+ votes,
302
+ committees,
303
+ settings: this.settings
304
+ });
305
+ return {
306
+ type: 'vote-offenses',
307
+ round: currentRound,
308
+ votes,
309
+ committees
310
+ };
311
+ }
312
+ /** Returns the committees that were active during the timespan of a given round */ collectCommitteesActiveDuringRound(round) {
313
+ const epochsToSlash = getEpochsForRound(round, this.settings);
314
+ const emptyCommittee = times(Number(this.settings.targetCommitteeSize), ()=>EthAddress.ZERO);
315
+ return Promise.all(epochsToSlash.map((epoch)=>this.epochCache.getCommitteeForEpoch(epoch).then((c)=>c.committee ?? emptyCommittee)));
316
+ }
317
+ /**
318
+ * Get slash payloads is NOT SUPPORTED in tally model
319
+ * @throws Error indicating this operation is not supported
320
+ */ getSlashPayloads() {
321
+ return Promise.reject(new Error('Tally slashing model does not support slash payloads'));
322
+ }
323
+ /**
324
+ * Gather offenses to be slashed on a given round.
325
+ * In tally slashing, round N slashes validators from round N - slashOffsetInRounds.
326
+ * @param round - The round to get offenses for, defaults to current round
327
+ * @returns Array of pending offenses for the round with offset applied
328
+ */ async gatherOffensesForRound(round) {
329
+ const targetRound = this.getSlashedRound(round);
330
+ if (targetRound < 0n) {
331
+ return [];
332
+ }
333
+ return await this.offensesStore.getOffensesForRound(targetRound);
334
+ }
335
+ /** Returns all pending offenses stored */ getPendingOffenses() {
336
+ return this.offensesStore.getPendingOffenses();
337
+ }
338
+ /**
339
+ * Returns the round to be slashed given the current round by applying the slash offset.
340
+ * During round N, we cannot slash the validators from the epochs of the same round, since the round is not over,
341
+ * and besides we would be asking the current validators to vote to slash themselves. So during round N we look at the
342
+ * epochs spanned during round N - SLASH_OFFSET_IN_ROUNDS. This offset means that the epochs we slash are complete,
343
+ * and also gives nodes time to detect any misbehavior (eg slashing for prunes requires the proof submission window to
344
+ * pass).
345
+ */ getSlashedRound(round) {
346
+ round ??= this.roundMonitor.getCurrentRound().round;
347
+ return round - BigInt(this.settings.slashingOffsetInRounds);
348
+ }
349
+ }
@@ -0,0 +1,11 @@
1
+ import type { SlasherConfig } from '@aztec/stdlib/interfaces/server';
2
+ import { type WantToSlashArgs, type Watcher, type WatcherEmitter } from '../watcher.js';
3
+ declare const DummyWatcher_base: new () => WatcherEmitter;
4
+ export declare class DummyWatcher extends DummyWatcher_base implements Watcher {
5
+ updateConfig(_config: Partial<SlasherConfig>): void;
6
+ start(): Promise<void>;
7
+ stop(): Promise<void>;
8
+ triggerSlash(args: WantToSlashArgs[]): void;
9
+ }
10
+ export {};
11
+ //# sourceMappingURL=dummy_watcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dummy_watcher.d.ts","sourceRoot":"","sources":["../../src/test/dummy_watcher.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iCAAiC,CAAC;AAIrE,OAAO,EAAuB,KAAK,eAAe,EAAE,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;iCAE1D,UAAU,cAAc;AAA3E,qBAAa,YAAa,SAAQ,iBAA2C,YAAW,OAAO;IACtF,YAAY,CAAC,OAAO,EAAE,OAAO,CAAC,aAAa,CAAC;IAE5C,KAAK;IAIL,IAAI;IAIJ,YAAY,CAAC,IAAI,EAAE,eAAe,EAAE;CAG5C"}
@@ -0,0 +1,14 @@
1
+ import EventEmitter from 'node:events';
2
+ import { WANT_TO_SLASH_EVENT } from '../watcher.js';
3
+ export class DummyWatcher extends EventEmitter {
4
+ updateConfig(_config) {}
5
+ start() {
6
+ return Promise.resolve();
7
+ }
8
+ stop() {
9
+ return Promise.resolve();
10
+ }
11
+ triggerSlash(args) {
12
+ this.emit(WANT_TO_SLASH_EVENT, args);
13
+ }
14
+ }
@@ -0,0 +1,21 @@
1
+ import { EthAddress } from '@aztec/foundation/eth-address';
2
+ import type { TypedEventEmitter } from '@aztec/foundation/types';
3
+ import { OffenseType } from '@aztec/stdlib/slashing';
4
+ import type { SlasherConfig } from './config.js';
5
+ export declare const WANT_TO_SLASH_EVENT: "want-to-slash";
6
+ export interface WantToSlashArgs {
7
+ validator: EthAddress;
8
+ amount: bigint;
9
+ offenseType: OffenseType;
10
+ epochOrSlot: bigint;
11
+ }
12
+ export interface WatcherEventMap {
13
+ [WANT_TO_SLASH_EVENT]: (args: WantToSlashArgs[]) => void;
14
+ }
15
+ export type WatcherEmitter = TypedEventEmitter<WatcherEventMap>;
16
+ export type Watcher = WatcherEmitter & {
17
+ start?: () => Promise<void>;
18
+ stop?: () => Promise<void>;
19
+ updateConfig: (config: Partial<SlasherConfig>) => void;
20
+ };
21
+ //# sourceMappingURL=watcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"watcher.d.ts","sourceRoot":"","sources":["../src/watcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,+BAA+B,CAAC;AAC3D,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AACjE,OAAO,EAAE,WAAW,EAAE,MAAM,wBAAwB,CAAC;AAErD,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,aAAa,CAAC;AAEjD,eAAO,MAAM,mBAAmB,EAAG,eAAwB,CAAC;AAE5D,MAAM,WAAW,eAAe;IAC9B,SAAS,EAAE,UAAU,CAAC;IACtB,MAAM,EAAE,MAAM,CAAC;IACf,WAAW,EAAE,WAAW,CAAC;IACzB,WAAW,EAAE,MAAM,CAAC;CACrB;AAGD,MAAM,WAAW,eAAe;IAC9B,CAAC,mBAAmB,CAAC,EAAE,CAAC,IAAI,EAAE,eAAe,EAAE,KAAK,IAAI,CAAC;CAC1D;AAED,MAAM,MAAM,cAAc,GAAG,iBAAiB,CAAC,eAAe,CAAC,CAAC;AAEhE,MAAM,MAAM,OAAO,GAAG,cAAc,GAAG;IACrC,KAAK,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC5B,IAAI,CAAC,EAAE,MAAM,OAAO,CAAC,IAAI,CAAC,CAAC;IAC3B,YAAY,EAAE,CAAC,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC,KAAK,IAAI,CAAC;CACxD,CAAC"}
@@ -0,0 +1 @@
1
+ export const WANT_TO_SLASH_EVENT = 'want-to-slash';
@@ -0,0 +1,33 @@
1
+ import { EpochCache } from '@aztec/epoch-cache';
2
+ import { type L2BlockSourceEventEmitter } from '@aztec/stdlib/block';
3
+ import type { SlasherConfig } from '../config.js';
4
+ import { type Watcher, type WatcherEmitter } from '../watcher.js';
5
+ declare const AttestationsBlockWatcherConfigKeys: readonly ["slashAttestDescendantOfInvalidPenalty", "slashProposeInvalidAttestationsPenalty"];
6
+ type AttestationsBlockWatcherConfig = Pick<SlasherConfig, (typeof AttestationsBlockWatcherConfigKeys)[number]>;
7
+ declare const AttestationsBlockWatcher_base: new () => WatcherEmitter;
8
+ /**
9
+ * This watcher is responsible for detecting invalid blocks and creating slashing arguments for offenders.
10
+ * An invalid block is one that doesn't have enough attestations or has incorrect attestations.
11
+ * The proposer of an invalid block should be slashed.
12
+ * If there's another block consecutive to the invalid one, its proposer and attestors should also be slashed.
13
+ */
14
+ export declare class AttestationsBlockWatcher extends AttestationsBlockWatcher_base implements Watcher {
15
+ private l2BlockSource;
16
+ private epochCache;
17
+ private log;
18
+ private maxInvalidBlocks;
19
+ private invalidArchiveRoots;
20
+ private config;
21
+ private boundHandleInvalidBlock;
22
+ constructor(l2BlockSource: L2BlockSourceEventEmitter, epochCache: EpochCache, config: AttestationsBlockWatcherConfig);
23
+ updateConfig(newConfig: Partial<AttestationsBlockWatcherConfig>): void;
24
+ start(): Promise<void>;
25
+ stop(): Promise<void>;
26
+ private handleInvalidBlock;
27
+ private slashAttestorsOnAncestorInvalid;
28
+ private slashProposer;
29
+ private getOffenseFromInvalidationReason;
30
+ private addInvalidBlock;
31
+ }
32
+ export {};
33
+ //# sourceMappingURL=attestations_block_watcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"attestations_block_watcher.d.ts","sourceRoot":"","sources":["../../src/watchers/attestations_block_watcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGhD,OAAO,EAGL,KAAK,yBAAyB,EAG/B,MAAM,qBAAqB,CAAC;AAK7B,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AAClD,OAAO,EAA6C,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAE7G,QAAA,MAAM,kCAAkC,8FAG9B,CAAC;AAEX,KAAK,8BAA8B,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC,OAAO,kCAAkC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;6CAQhD,UAAU,cAAc;AANvF;;;;;GAKG;AACH,qBAAa,wBAAyB,SAAQ,6BAA2C,YAAW,OAAO;IAuBvG,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,UAAU;IAvBpB,OAAO,CAAC,GAAG,CAAsD;IAGjE,OAAO,CAAC,gBAAgB,CAAO;IAG/B,OAAO,CAAC,mBAAmB,CAA0B;IAErD,OAAO,CAAC,MAAM,CAAiC;IAE/C,OAAO,CAAC,uBAAuB,CAS7B;gBAGQ,aAAa,EAAE,yBAAyB,EACxC,UAAU,EAAE,UAAU,EAC9B,MAAM,EAAE,8BAA8B;IAOjC,YAAY,CAAC,SAAS,EAAE,OAAO,CAAC,8BAA8B,CAAC;IAK/D,KAAK;IAKL,IAAI;IAQX,OAAO,CAAC,kBAAkB;IAyB1B,OAAO,CAAC,+BAA+B;IAwBvC,OAAO,CAAC,aAAa;IA4BrB,OAAO,CAAC,gCAAgC;IAaxC,OAAO,CAAC,eAAe;CASxB"}
@@ -0,0 +1,135 @@
1
+ import { merge, pick } from '@aztec/foundation/collection';
2
+ import { createLogger } from '@aztec/foundation/log';
3
+ import { L2BlockSourceEvents } from '@aztec/stdlib/block';
4
+ import { OffenseType } from '@aztec/stdlib/slashing';
5
+ import EventEmitter from 'node:events';
6
+ import { WANT_TO_SLASH_EVENT } from '../watcher.js';
7
+ const AttestationsBlockWatcherConfigKeys = [
8
+ 'slashAttestDescendantOfInvalidPenalty',
9
+ 'slashProposeInvalidAttestationsPenalty'
10
+ ];
11
+ /**
12
+ * This watcher is responsible for detecting invalid blocks and creating slashing arguments for offenders.
13
+ * An invalid block is one that doesn't have enough attestations or has incorrect attestations.
14
+ * The proposer of an invalid block should be slashed.
15
+ * If there's another block consecutive to the invalid one, its proposer and attestors should also be slashed.
16
+ */ export class AttestationsBlockWatcher extends EventEmitter {
17
+ l2BlockSource;
18
+ epochCache;
19
+ log;
20
+ // Only keep track of the last N invalid blocks
21
+ maxInvalidBlocks;
22
+ // All invalid archive roots seen
23
+ invalidArchiveRoots;
24
+ config;
25
+ boundHandleInvalidBlock;
26
+ constructor(l2BlockSource, epochCache, config){
27
+ super(), this.l2BlockSource = l2BlockSource, this.epochCache = epochCache, this.log = createLogger('attestations-block-watcher'), this.maxInvalidBlocks = 100, this.invalidArchiveRoots = new Set(), this.boundHandleInvalidBlock = (event)=>{
28
+ try {
29
+ this.handleInvalidBlock(event);
30
+ } catch (err) {
31
+ this.log.error('Error handling invalid block', err, {
32
+ ...event.validationResult,
33
+ reason: event.validationResult.reason
34
+ });
35
+ }
36
+ };
37
+ this.config = pick(config, ...AttestationsBlockWatcherConfigKeys);
38
+ this.log.info('AttestationsBlockWatcher initialized');
39
+ }
40
+ updateConfig(newConfig) {
41
+ this.config = merge(this.config, pick(newConfig, ...AttestationsBlockWatcherConfigKeys));
42
+ this.log.verbose('AttestationsBlockWatcher config updated', this.config);
43
+ }
44
+ start() {
45
+ this.l2BlockSource.on(L2BlockSourceEvents.InvalidAttestationsBlockDetected, this.boundHandleInvalidBlock);
46
+ return Promise.resolve();
47
+ }
48
+ stop() {
49
+ this.l2BlockSource.removeListener(L2BlockSourceEvents.InvalidAttestationsBlockDetected, this.boundHandleInvalidBlock);
50
+ return Promise.resolve();
51
+ }
52
+ handleInvalidBlock(event) {
53
+ const { validationResult } = event;
54
+ const block = validationResult.block;
55
+ // Check if we already have processed this block, archiver may emit the same event multiple times
56
+ if (this.invalidArchiveRoots.has(block.archive.toString())) {
57
+ this.log.trace(`Already processed invalid block ${block.blockNumber}`);
58
+ return;
59
+ }
60
+ this.log.verbose(`Detected invalid block ${block.blockNumber}`, {
61
+ ...block,
62
+ reason: validationResult.valid === false ? validationResult.reason : 'unknown'
63
+ });
64
+ // Store the invalid block
65
+ this.addInvalidBlock(event.validationResult.block);
66
+ // Slash the proposer of the invalid block
67
+ this.slashProposer(event.validationResult);
68
+ // Check if the parent of this block is invalid as well, if so, we will slash its attestors as well
69
+ this.slashAttestorsOnAncestorInvalid(event.validationResult);
70
+ }
71
+ slashAttestorsOnAncestorInvalid(validationResult) {
72
+ const block = validationResult.block;
73
+ const parentArchive = block.lastArchive.toString();
74
+ if (this.invalidArchiveRoots.has(parentArchive)) {
75
+ const attestors = validationResult.attestors;
76
+ this.log.info(`Want to slash attestors of block ${block.blockNumber} built on invalid block`, {
77
+ ...block,
78
+ ...attestors,
79
+ parentArchive
80
+ });
81
+ this.emit(WANT_TO_SLASH_EVENT, attestors.map((attestor)=>({
82
+ validator: attestor,
83
+ amount: this.config.slashAttestDescendantOfInvalidPenalty,
84
+ offenseType: OffenseType.ATTESTED_DESCENDANT_OF_INVALID,
85
+ epochOrSlot: BigInt(block.slotNumber)
86
+ })));
87
+ }
88
+ }
89
+ slashProposer(validationResult) {
90
+ const { reason, block } = validationResult;
91
+ const blockNumber = block.blockNumber;
92
+ const slot = BigInt(block.slotNumber);
93
+ const proposer = this.epochCache.getProposerFromEpochCommittee(validationResult, slot);
94
+ if (!proposer) {
95
+ this.log.warn(`No proposer found for block ${blockNumber} at slot ${slot}`);
96
+ return;
97
+ }
98
+ const offense = this.getOffenseFromInvalidationReason(reason);
99
+ const amount = this.config.slashProposeInvalidAttestationsPenalty;
100
+ const args = {
101
+ validator: proposer,
102
+ amount,
103
+ offenseType: offense,
104
+ epochOrSlot: slot
105
+ };
106
+ this.log.info(`Want to slash proposer of block ${blockNumber} due to ${reason}`, {
107
+ ...block,
108
+ ...args
109
+ });
110
+ this.emit(WANT_TO_SLASH_EVENT, [
111
+ args
112
+ ]);
113
+ }
114
+ getOffenseFromInvalidationReason(reason) {
115
+ switch(reason){
116
+ case 'invalid-attestation':
117
+ return OffenseType.PROPOSED_INCORRECT_ATTESTATIONS;
118
+ case 'insufficient-attestations':
119
+ return OffenseType.PROPOSED_INSUFFICIENT_ATTESTATIONS;
120
+ default:
121
+ {
122
+ const _ = reason;
123
+ return OffenseType.UNKNOWN;
124
+ }
125
+ }
126
+ }
127
+ addInvalidBlock(block) {
128
+ this.invalidArchiveRoots.add(block.archive.toString());
129
+ // Prune old entries if we exceed the maximum
130
+ if (this.invalidArchiveRoots.size > this.maxInvalidBlocks) {
131
+ const oldestKey = this.invalidArchiveRoots.keys().next().value;
132
+ this.invalidArchiveRoots.delete(oldestKey);
133
+ }
134
+ }
135
+ }
@@ -0,0 +1,37 @@
1
+ import { EpochCache } from '@aztec/epoch-cache';
2
+ import { L2Block, type L2BlockSourceEventEmitter } from '@aztec/stdlib/block';
3
+ import type { IFullNodeBlockBuilder, ITxProvider, MerkleTreeWriteOperations, SlasherConfig } from '@aztec/stdlib/interfaces/server';
4
+ import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
5
+ import { type Watcher, type WatcherEmitter } from '../watcher.js';
6
+ declare const EpochPruneWatcherPenaltiesConfigKeys: readonly ["slashPrunePenalty", "slashDataWithholdingPenalty"];
7
+ type EpochPruneWatcherPenalties = Pick<SlasherConfig, (typeof EpochPruneWatcherPenaltiesConfigKeys)[number]>;
8
+ declare const EpochPruneWatcher_base: new () => WatcherEmitter;
9
+ /**
10
+ * This watcher is responsible for detecting chain prunes and creating slashing arguments for the committee.
11
+ * It only wants to slash if:
12
+ * - the transactions are not available
13
+ * - OR the archive roots match when re-building all the blocks in the epoch (i.e. the epoch *could* have been proven)
14
+ */
15
+ export declare class EpochPruneWatcher extends EpochPruneWatcher_base implements Watcher {
16
+ private l2BlockSource;
17
+ private l1ToL2MessageSource;
18
+ private epochCache;
19
+ private txProvider;
20
+ private blockBuilder;
21
+ private log;
22
+ private boundHandlePruneL2Blocks;
23
+ private penalties;
24
+ constructor(l2BlockSource: L2BlockSourceEventEmitter, l1ToL2MessageSource: L1ToL2MessageSource, epochCache: EpochCache, txProvider: Pick<ITxProvider, 'getAvailableTxs'>, blockBuilder: IFullNodeBlockBuilder, penalties: EpochPruneWatcherPenalties);
25
+ start(): Promise<void>;
26
+ stop(): Promise<void>;
27
+ updateConfig(config: Partial<SlasherConfig>): void;
28
+ private handlePruneL2Blocks;
29
+ private emitSlashForEpoch;
30
+ private processPruneL2Blocks;
31
+ validateBlocks(blocks: L2Block[]): Promise<void>;
32
+ validateBlock(blockFromL1: L2Block, fork: MerkleTreeWriteOperations): Promise<void>;
33
+ private getValidatorsForEpoch;
34
+ private validatorsToSlashingArgs;
35
+ }
36
+ export {};
37
+ //# sourceMappingURL=epoch_prune_watcher.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"epoch_prune_watcher.d.ts","sourceRoot":"","sources":["../../src/watchers/epoch_prune_watcher.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAGhD,OAAO,EAEL,OAAO,EAEP,KAAK,yBAAyB,EAE/B,MAAM,qBAAqB,CAAC;AAE7B,OAAO,KAAK,EACV,qBAAqB,EACrB,WAAW,EACX,yBAAyB,EACzB,aAAa,EACd,MAAM,iCAAiC,CAAC;AACzC,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,yBAAyB,CAAC;AAWnE,OAAO,EAA6C,KAAK,OAAO,EAAE,KAAK,cAAc,EAAE,MAAM,eAAe,CAAC;AAE7G,QAAA,MAAM,oCAAoC,+DAAgE,CAAC;AAE3G,KAAK,0BAA0B,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC,OAAO,oCAAoC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC;sCAQrD,UAAU,cAAc;AANhF;;;;;GAKG;AACH,qBAAa,iBAAkB,SAAQ,sBAA2C,YAAW,OAAO;IAShG,OAAO,CAAC,aAAa;IACrB,OAAO,CAAC,mBAAmB;IAC3B,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,UAAU;IAClB,OAAO,CAAC,YAAY;IAZtB,OAAO,CAAC,GAAG,CAA+C;IAG1D,OAAO,CAAC,wBAAwB,CAAuC;IAEvE,OAAO,CAAC,SAAS,CAA6B;gBAGpC,aAAa,EAAE,yBAAyB,EACxC,mBAAmB,EAAE,mBAAmB,EACxC,UAAU,EAAE,UAAU,EACtB,UAAU,EAAE,IAAI,CAAC,WAAW,EAAE,iBAAiB,CAAC,EAChD,YAAY,EAAE,qBAAqB,EAC3C,SAAS,EAAE,0BAA0B;IAShC,KAAK;IAKL,IAAI;IAKJ,YAAY,CAAC,MAAM,EAAE,OAAO,CAAC,aAAa,CAAC,GAAG,IAAI;IAKzD,OAAO,CAAC,mBAAmB;YAOb,iBAAiB;YAWjB,oBAAoB;IAwBrB,cAAc,CAAC,MAAM,EAAE,OAAO,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAchD,aAAa,CAAC,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC;YAgClF,qBAAqB;IASnC,OAAO,CAAC,wBAAwB;CAgBjC"}