@aztec-labs/slasher 6.0.0-nightly.20260829

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +232 -0
  2. package/dest/config.d.ts +6 -0
  3. package/dest/config.d.ts.map +1 -0
  4. package/dest/config.js +146 -0
  5. package/dest/factory/create_facade.d.ts +19 -0
  6. package/dest/factory/create_facade.d.ts.map +1 -0
  7. package/dest/factory/create_facade.js +49 -0
  8. package/dest/factory/create_implementation.d.ts +17 -0
  9. package/dest/factory/create_implementation.d.ts.map +1 -0
  10. package/dest/factory/create_implementation.js +25 -0
  11. package/dest/factory/get_settings.d.ts +4 -0
  12. package/dest/factory/get_settings.d.ts.map +1 -0
  13. package/dest/factory/get_settings.js +36 -0
  14. package/dest/factory/index.d.ts +3 -0
  15. package/dest/factory/index.d.ts.map +1 -0
  16. package/dest/factory/index.js +2 -0
  17. package/dest/generated/slasher-defaults.d.ts +21 -0
  18. package/dest/generated/slasher-defaults.d.ts.map +1 -0
  19. package/dest/generated/slasher-defaults.js +21 -0
  20. package/dest/index.d.ts +13 -0
  21. package/dest/index.d.ts.map +1 -0
  22. package/dest/index.js +12 -0
  23. package/dest/metrics.d.ts +23 -0
  24. package/dest/metrics.d.ts.map +1 -0
  25. package/dest/metrics.js +38 -0
  26. package/dest/null_slasher_client.d.ts +16 -0
  27. package/dest/null_slasher_client.d.ts.map +1 -0
  28. package/dest/null_slasher_client.js +30 -0
  29. package/dest/own_validator_slash_monitor.d.ts +66 -0
  30. package/dest/own_validator_slash_monitor.d.ts.map +1 -0
  31. package/dest/own_validator_slash_monitor.js +163 -0
  32. package/dest/slash_offenses_collector.d.ts +46 -0
  33. package/dest/slash_offenses_collector.d.ts.map +1 -0
  34. package/dest/slash_offenses_collector.js +114 -0
  35. package/dest/slash_round_monitor.d.ts +30 -0
  36. package/dest/slash_round_monitor.d.ts.map +1 -0
  37. package/dest/slash_round_monitor.js +52 -0
  38. package/dest/slasher_client.d.ts +118 -0
  39. package/dest/slasher_client.d.ts.map +1 -0
  40. package/dest/slasher_client.js +373 -0
  41. package/dest/slasher_client_facade.d.ts +44 -0
  42. package/dest/slasher_client_facade.d.ts.map +1 -0
  43. package/dest/slasher_client_facade.js +75 -0
  44. package/dest/slasher_client_interface.d.ts +25 -0
  45. package/dest/slasher_client_interface.d.ts.map +1 -0
  46. package/dest/slasher_client_interface.js +1 -0
  47. package/dest/stores/offenses_store.d.ts +37 -0
  48. package/dest/stores/offenses_store.d.ts.map +1 -0
  49. package/dest/stores/offenses_store.js +130 -0
  50. package/dest/stores/schema_version.d.ts +2 -0
  51. package/dest/stores/schema_version.d.ts.map +1 -0
  52. package/dest/stores/schema_version.js +1 -0
  53. package/dest/test/dummy_watcher.d.ts +11 -0
  54. package/dest/test/dummy_watcher.d.ts.map +1 -0
  55. package/dest/test/dummy_watcher.js +14 -0
  56. package/dest/watcher.d.ts +28 -0
  57. package/dest/watcher.d.ts.map +1 -0
  58. package/dest/watcher.js +2 -0
  59. package/dest/watchers/attestations_block_watcher.d.ts +47 -0
  60. package/dest/watchers/attestations_block_watcher.d.ts.map +1 -0
  61. package/dest/watchers/attestations_block_watcher.js +157 -0
  62. package/dest/watchers/attested_invalid_proposal_watcher.d.ts +42 -0
  63. package/dest/watchers/attested_invalid_proposal_watcher.d.ts.map +1 -0
  64. package/dest/watchers/attested_invalid_proposal_watcher.js +117 -0
  65. package/dest/watchers/broadcasted_invalid_checkpoint_proposal_watcher.d.ts +38 -0
  66. package/dest/watchers/broadcasted_invalid_checkpoint_proposal_watcher.d.ts.map +1 -0
  67. package/dest/watchers/broadcasted_invalid_checkpoint_proposal_watcher.js +138 -0
  68. package/dest/watchers/checkpoint_equivocation_watcher.d.ts +30 -0
  69. package/dest/watchers/checkpoint_equivocation_watcher.d.ts.map +1 -0
  70. package/dest/watchers/checkpoint_equivocation_watcher.js +69 -0
  71. package/dest/watchers/data_withholding_watcher.d.ts +69 -0
  72. package/dest/watchers/data_withholding_watcher.d.ts.map +1 -0
  73. package/dest/watchers/data_withholding_watcher.js +223 -0
  74. package/package.json +90 -0
  75. package/src/config.ts +177 -0
  76. package/src/factory/create_facade.ts +85 -0
  77. package/src/factory/create_implementation.ts +83 -0
  78. package/src/factory/get_settings.ts +58 -0
  79. package/src/factory/index.ts +2 -0
  80. package/src/generated/slasher-defaults.ts +23 -0
  81. package/src/index.ts +12 -0
  82. package/src/metrics.ts +58 -0
  83. package/src/null_slasher_client.ts +37 -0
  84. package/src/own_validator_slash_monitor.ts +183 -0
  85. package/src/slash_offenses_collector.ts +156 -0
  86. package/src/slash_round_monitor.ts +62 -0
  87. package/src/slasher_client.ts +477 -0
  88. package/src/slasher_client_facade.ts +99 -0
  89. package/src/slasher_client_interface.ts +31 -0
  90. package/src/stores/offenses_store.ts +173 -0
  91. package/src/stores/schema_version.ts +1 -0
  92. package/src/test/dummy_watcher.ts +20 -0
  93. package/src/watcher.ts +35 -0
  94. package/src/watchers/attestations_block_watcher.ts +199 -0
  95. package/src/watchers/attested_invalid_proposal_watcher.ts +167 -0
  96. package/src/watchers/broadcasted_invalid_checkpoint_proposal_watcher.ts +191 -0
  97. package/src/watchers/checkpoint_equivocation_watcher.ts +95 -0
  98. package/src/watchers/data_withholding_watcher.ts +256 -0
@@ -0,0 +1,223 @@
1
+ import { CheckpointProposalHash, SlotNumber } from '@aztec-labs/foundation/branded-types';
2
+ import { compactArray, merge, pick } from '@aztec-labs/foundation/collection';
3
+ import { createLogger } from '@aztec-labs/foundation/log';
4
+ import { RunningPromise } from '@aztec-labs/foundation/promise';
5
+ import { getAttestationInfoFromPublishedCheckpoint } from '@aztec-labs/stdlib/block';
6
+ import { ConsensusPayload } from '@aztec-labs/stdlib/p2p';
7
+ import { OffenseType, getOffenseTypeName } from '@aztec-labs/stdlib/slashing';
8
+ import EventEmitter from 'node:events';
9
+ import { WANT_TO_SLASH_EVENT } from '../watcher.js';
10
+ const DataWithholdingWatcherConfigKeys = [
11
+ 'slashDataWithholdingPenalty',
12
+ 'slashDataWithholdingToleranceSlots'
13
+ ];
14
+ /**
15
+ * Detects data-withholding offenses by probing the local mempool for the txs in published
16
+ * checkpoints once they are old enough that an honest node should have collected them.
17
+ *
18
+ * Per AZIP-7: once `slashDataWithholdingToleranceSlots` full slots have elapsed after the
19
+ * checkpoint's slot — i.e. at `slotStart(checkpoint.slot + slashDataWithholdingToleranceSlots
20
+ * + 1)` — if any tx from the checkpoint's blocks is still missing locally, the checkpoint's
21
+ * attesters are considered at fault for not making the data available, and we emit a slash
22
+ * for them.
23
+ *
24
+ * The watcher ticks at quarter-eth-slot cadence (matching the Sentinel template). On boot it
25
+ * floors processing at the current slot — restart-time gaps are accepted and not back-filled,
26
+ * matching the Sentinel approach.
27
+ *
28
+ * Since the evidence for an offense is the absence of txs in the local pool, the probe is gated on
29
+ * p2p connectivity: while there are no connected peers, slots are skipped instead of probed, since
30
+ * missing txs then say nothing about the attesters. Nodes running with p2p disabled do not run this
31
+ * watcher at all.
32
+ */ export class DataWithholdingWatcher extends EventEmitter {
33
+ epochCache;
34
+ l2BlockSource;
35
+ txProvider;
36
+ p2p;
37
+ reexecutionTracker;
38
+ signatureContext;
39
+ log;
40
+ runningPromise;
41
+ initialSlot;
42
+ lastCheckedSlot;
43
+ config;
44
+ gossipDegraded;
45
+ constructor(epochCache, l2BlockSource, txProvider, p2p, reexecutionTracker, signatureContext, config, log = createLogger('data-withholding-watcher')){
46
+ super(), this.epochCache = epochCache, this.l2BlockSource = l2BlockSource, this.txProvider = txProvider, this.p2p = p2p, this.reexecutionTracker = reexecutionTracker, this.signatureContext = signatureContext, this.log = log, this.gossipDegraded = false;
47
+ this.config = pick(config, ...DataWithholdingWatcherConfigKeys);
48
+ const interval = epochCache.getL1Constants().ethereumSlotDuration * 1000 / 4;
49
+ this.runningPromise = new RunningPromise(this.work.bind(this), log, interval);
50
+ this.log.verbose(`DataWithholdingWatcher initialized`, this.config);
51
+ }
52
+ async start() {
53
+ // Floor processing at the archiver's synced slot rather than the wallclock — restart-time
54
+ // gaps before the archiver catches up are accepted and not back-filled. Falls back to the
55
+ // wallclock if the archiver isn't ready yet (cold start).
56
+ const syncedSlot = await this.l2BlockSource.getSyncedL2SlotNumber();
57
+ this.initialSlot = syncedSlot ?? this.epochCache.getSlotNow();
58
+ this.log.info(`Starting data-withholding watcher with initial slot ${this.initialSlot}`);
59
+ this.runningPromise.start();
60
+ }
61
+ stop() {
62
+ return this.runningPromise.stop();
63
+ }
64
+ updateConfig(config) {
65
+ this.config = merge(this.config, pick(config, ...DataWithholdingWatcherConfigKeys));
66
+ this.log.verbose('DataWithholdingWatcher config updated', this.config);
67
+ }
68
+ /**
69
+ * Runs every tick. Walks newly-eligible slots and probes their checkpoints for data
70
+ * availability; emits a DATA_WITHHOLDING slash for any checkpoint whose txs are missing.
71
+ */ async work() {
72
+ if (this.initialSlot === undefined) {
73
+ return;
74
+ }
75
+ // tolerance is the number of full slots that must elapse after the checkpoint's slot
76
+ // before we declare its data missing. For checkpoint slot S, we therefore process S
77
+ // only once we are in slot `S + tolerance + 1` or later. Drive this off the archiver's
78
+ // synced slot rather than the wallclock so we don't make claims about slots we haven't
79
+ // fully ingested yet (archiver may lag behind L1).
80
+ const tolerance = this.config.slashDataWithholdingToleranceSlots;
81
+ const currentSlot = await this.l2BlockSource.getSyncedL2SlotNumber() ?? this.epochCache.getSlotNow();
82
+ if (currentSlot <= tolerance) {
83
+ return;
84
+ }
85
+ const targetSlot = SlotNumber(currentSlot - tolerance - 1);
86
+ if (targetSlot <= this.initialSlot) {
87
+ return;
88
+ }
89
+ // Missing txs are only evidence of withholding if we could have received them. Slots probed
90
+ // while gossip is down are skipped for good rather than deferred: once peers return, txs from
91
+ // those checkpoints may already have been evicted from the pool as mined, so a late probe would
92
+ // still report them missing. An unknown must not turn into an offense. Note this deliberately
93
+ // ignores whether p2p is enabled: a node with no p2p stack sees even less than a peerless one.
94
+ const connectivity = await this.p2p.getP2PConnectivity();
95
+ if (connectivity.connectedPeers === 0) {
96
+ if (!this.gossipDegraded) {
97
+ this.gossipDegraded = true;
98
+ this.log.warn(`Skipping data-withholding checks while no peers are connected`, {
99
+ targetSlot,
100
+ lastCheckedSlot: this.lastCheckedSlot
101
+ });
102
+ }
103
+ this.lastCheckedSlot = targetSlot;
104
+ return;
105
+ }
106
+ if (this.gossipDegraded) {
107
+ this.gossipDegraded = false;
108
+ this.log.info(`Resuming data-withholding checks now that peers are connected`, {
109
+ targetSlot,
110
+ connectedPeers: connectivity.connectedPeers
111
+ });
112
+ }
113
+ const startSlot = this.lastCheckedSlot === undefined ? this.initialSlot : this.lastCheckedSlot;
114
+ for(let slot = SlotNumber(startSlot + 1); slot <= targetSlot; slot = SlotNumber(slot + 1)){
115
+ try {
116
+ await this.processSlot(slot);
117
+ } catch (err) {
118
+ this.log.error(`Error processing slot ${slot} for data-withholding check`, err, {
119
+ slot
120
+ });
121
+ }
122
+ this.lastCheckedSlot = slot;
123
+ }
124
+ }
125
+ /** Probes the checkpoint at the given slot, if any, and emits a slash on missing txs. */ async processSlot(slot) {
126
+ const published = await this.l2BlockSource.getCheckpoint({
127
+ slot
128
+ });
129
+ if (!published) {
130
+ this.log.trace(`No published checkpoint at slot ${slot}`, {
131
+ slot
132
+ });
133
+ return;
134
+ }
135
+ const checkpointNumber = published.checkpoint.number;
136
+ // Per-block tx-collection records (true | false | undefined) for every block in this
137
+ // published checkpoint. Captured by the validator's proposal handler at the moment of
138
+ // tx collection (i.e. by the *re-execution* deadline). Used as a positive short-circuit
139
+ // only: a `true` for every block means we know the data was available locally, so this
140
+ // checkpoint cannot be a data-withholding offense. A `false` does *not* trigger a slash
141
+ // on its own — the re-execution deadline is much earlier than the data-withholding
142
+ // tolerance window, so missing txs at that earlier deadline may still arrive in time.
143
+ // Anything other than all-true falls through to the mempool probe, which respects the
144
+ // tolerance window.
145
+ const collectionRecords = published.checkpoint.blocks.map((block, idx)=>this.reexecutionTracker.getTxsCollectedRecord(block.header.getSlot(), idx));
146
+ if (collectionRecords.every((r)=>r === true)) {
147
+ this.log.trace(`All blocks for checkpoint at slot ${slot} were collected locally; skipping`, {
148
+ slot,
149
+ checkpointNumber
150
+ });
151
+ return;
152
+ }
153
+ const txHashes = published.checkpoint.blocks.flatMap((block)=>block.body.txEffects.map((txEffect)=>txEffect.txHash));
154
+ if (txHashes.length === 0) {
155
+ this.log.trace(`Checkpoint at slot ${slot} has no txs`, {
156
+ slot
157
+ });
158
+ return;
159
+ }
160
+ const availability = await this.txProvider.hasTxs(txHashes);
161
+ const missingTxs = txHashes.filter((_, i)=>!availability[i]);
162
+ if (missingTxs.length === 0) {
163
+ this.log.trace(`All ${txHashes.length} txs available for checkpoint at slot ${slot}`, {
164
+ slot
165
+ });
166
+ return;
167
+ }
168
+ const attesters = await this.extractAttesters(published);
169
+ if (attesters.length === 0) {
170
+ this.log.warn(`Detected data withholding at slot ${slot} but no recoverable attesters`, {
171
+ slot,
172
+ checkpointNumber,
173
+ missingTxs: missingTxs.map((h)=>h.toString()),
174
+ records: collectionRecords
175
+ });
176
+ return;
177
+ }
178
+ this.log.info(`Detected data withholding offense at slot ${slot}`, {
179
+ slot,
180
+ checkpointNumber,
181
+ amount: this.config.slashDataWithholdingPenalty,
182
+ offenseType: getOffenseTypeName(OffenseType.DATA_WITHHOLDING),
183
+ missingTxs: missingTxs.map((h)=>h.toString()),
184
+ records: collectionRecords,
185
+ attesters: attesters.map((a)=>a.toString())
186
+ });
187
+ const args = attesters.map((validator)=>({
188
+ validator,
189
+ amount: this.config.slashDataWithholdingPenalty,
190
+ offenseType: OffenseType.DATA_WITHHOLDING,
191
+ epochOrSlot: BigInt(slot)
192
+ }));
193
+ this.emit(WANT_TO_SLASH_EVENT, args);
194
+ }
195
+ /**
196
+ * Returns the union of:
197
+ * 1. attesters whose signatures landed in the published checkpoint on L1, and
198
+ * 2. attesters we observed signing the same proposal on p2p (the proposer publishes as
199
+ * soon as it has hit committee quorum, so honest peer attestations that arrive after
200
+ * that point are dropped — but they still vouched for the data and
201
+ * should be slashed for withholding it).
202
+ *
203
+ *
204
+ * Exposed as protected so tests can substitute a deterministic recovery without having
205
+ * to construct real secp256k1 signatures.
206
+ */ async extractAttesters(published) {
207
+ const fromL1 = getAttestationInfoFromPublishedCheckpoint(published, this.signatureContext).filter((info)=>info.status === 'recovered-from-signature').map((info)=>info.address);
208
+ const slot = published.checkpoint.header.slotNumber;
209
+ const proposalPayloadHash = CheckpointProposalHash.fromBuffer(ConsensusPayload.fromCheckpoint(published.checkpoint, this.signatureContext).getPayloadHash());
210
+ const fromP2p = await this.p2p.getCheckpointAttestationsForSlot(slot, proposalPayloadHash).then((attestations)=>attestations.map((a)=>a.getSender()));
211
+ // Dedupe
212
+ const all = new Map();
213
+ for (const addr of compactArray([
214
+ ...fromL1,
215
+ ...fromP2p
216
+ ])){
217
+ all.set(addr.toString(), addr);
218
+ }
219
+ return [
220
+ ...all.values()
221
+ ];
222
+ }
223
+ }
package/package.json ADDED
@@ -0,0 +1,90 @@
1
+ {
2
+ "name": "@aztec-labs/slasher",
3
+ "version": "6.0.0-nightly.20260829",
4
+ "type": "module",
5
+ "exports": {
6
+ ".": "./dest/index.js",
7
+ "./config": "./dest/config.js"
8
+ },
9
+ "inherits": [
10
+ "../package.common.json",
11
+ "./package.local.json"
12
+ ],
13
+ "scripts": {
14
+ "build": "yarn clean && ../scripts/tsc.sh",
15
+ "build:dev": "../scripts/tsc.sh --watch",
16
+ "clean": "rm -rf ./dest .tsbuildinfo",
17
+ "bb": "node --no-warnings ./dest/bb/index.js",
18
+ "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}",
19
+ "generate": "./scripts/generate.sh"
20
+ },
21
+ "jest": {
22
+ "moduleNameMapper": {
23
+ "^(\\.{1,2}/.*)\\.[cm]?js$": "$1"
24
+ },
25
+ "testRegex": "./src/.*\\.test\\.(js|mjs|ts)$",
26
+ "rootDir": "./src",
27
+ "transform": {
28
+ "^.+\\.tsx?$": [
29
+ "@swc/jest",
30
+ {
31
+ "jsc": {
32
+ "parser": {
33
+ "syntax": "typescript",
34
+ "decorators": true
35
+ },
36
+ "transform": {
37
+ "decoratorVersion": "2022-03"
38
+ }
39
+ }
40
+ }
41
+ ]
42
+ },
43
+ "extensionsToTreatAsEsm": [
44
+ ".ts"
45
+ ],
46
+ "reporters": [
47
+ "default"
48
+ ],
49
+ "testTimeout": 120000,
50
+ "setupFiles": [
51
+ "../../foundation/src/jest/setup.mjs"
52
+ ],
53
+ "testEnvironment": "../../foundation/src/jest/env.mjs",
54
+ "setupFilesAfterEnv": [
55
+ "../../foundation/src/jest/setupAfterEnv.mjs"
56
+ ]
57
+ },
58
+ "dependencies": {
59
+ "@aztec-labs/epoch-cache": "6.0.0-nightly.20260829",
60
+ "@aztec-labs/ethereum": "6.0.0-nightly.20260829",
61
+ "@aztec-labs/foundation": "6.0.0-nightly.20260829",
62
+ "@aztec-labs/kv-store": "6.0.0-nightly.20260829",
63
+ "@aztec-labs/stdlib": "6.0.0-nightly.20260829",
64
+ "@aztec-labs/telemetry-client": "6.0.0-nightly.20260829",
65
+ "source-map-support": "^0.5.21",
66
+ "tslib": "^2.4.0",
67
+ "viem": "npm:@aztec/viem@2.38.2",
68
+ "zod": "^4"
69
+ },
70
+ "devDependencies": {
71
+ "@jest/globals": "^30.0.0",
72
+ "@types/jest": "^30.0.0",
73
+ "@types/node": "^22.15.17",
74
+ "@types/source-map-support": "^0.5.10",
75
+ "@typescript/native-preview": "7.0.0-dev.20260113.1",
76
+ "jest": "^30.0.0",
77
+ "jest-mock-extended": "^4.0.0",
78
+ "ts-node": "^10.9.1",
79
+ "typescript": "^5.3.3"
80
+ },
81
+ "files": [
82
+ "dest",
83
+ "src",
84
+ "!*.test.*"
85
+ ],
86
+ "types": "./dest/index.d.ts",
87
+ "engines": {
88
+ "node": ">=20.10"
89
+ }
90
+ }
package/src/config.ts ADDED
@@ -0,0 +1,177 @@
1
+ import type { ConfigMappingsType } from '@aztec-labs/foundation/config';
2
+ import {
3
+ bigintConfigHelper,
4
+ booleanConfigHelper,
5
+ floatConfigHelper,
6
+ numberConfigHelper,
7
+ } from '@aztec-labs/foundation/config';
8
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
9
+ import type { SlasherConfig } from '@aztec-labs/stdlib/interfaces/server';
10
+
11
+ import { slasherDefaultEnv } from './generated/slasher-defaults.js';
12
+
13
+ export type { SlasherConfig };
14
+
15
+ export const DefaultSlasherConfig: SlasherConfig = {
16
+ slashOverridePayload: undefined,
17
+ slashValidatorsAlways: [], // Empty by default
18
+ slashValidatorsNever: [], // Empty by default
19
+ slashDataWithholdingPenalty: BigInt(slasherDefaultEnv.SLASH_DATA_WITHHOLDING_PENALTY),
20
+ slashDataWithholdingToleranceSlots: slasherDefaultEnv.SLASH_DATA_WITHHOLDING_TOLERANCE_SLOTS,
21
+ slashInactivityTargetPercentage: slasherDefaultEnv.SLASH_INACTIVITY_TARGET_PERCENTAGE,
22
+ slashInactivityConsecutiveEpochThreshold: slasherDefaultEnv.SLASH_INACTIVITY_CONSECUTIVE_EPOCH_THRESHOLD,
23
+ slashBroadcastedInvalidBlockPenalty: BigInt(slasherDefaultEnv.SLASH_INVALID_BLOCK_PENALTY),
24
+ slashBroadcastedInvalidCheckpointProposalPenalty: BigInt(slasherDefaultEnv.SLASH_INVALID_CHECKPOINT_PROPOSAL_PENALTY),
25
+ slashDuplicateProposalPenalty: BigInt(slasherDefaultEnv.SLASH_DUPLICATE_PROPOSAL_PENALTY),
26
+ slashDuplicateAttestationPenalty: BigInt(slasherDefaultEnv.SLASH_DUPLICATE_ATTESTATION_PENALTY),
27
+ slashInactivityPenalty: BigInt(slasherDefaultEnv.SLASH_INACTIVITY_PENALTY),
28
+ slashProposeInvalidAttestationsPenalty: BigInt(slasherDefaultEnv.SLASH_PROPOSE_INVALID_ATTESTATIONS_PENALTY),
29
+ slashProposeDescendantOfCheckpointWithInvalidAttestationsPenalty: BigInt(
30
+ slasherDefaultEnv.SLASH_PROPOSE_DESCENDANT_OF_CHECKPOINT_WITH_INVALID_ATTESTATIONS_PENALTY,
31
+ ),
32
+ slashAttestInvalidCheckpointProposalPenalty: BigInt(
33
+ slasherDefaultEnv.SLASH_ATTEST_INVALID_CHECKPOINT_PROPOSAL_PENALTY,
34
+ ),
35
+ slashUnknownPenalty: BigInt(slasherDefaultEnv.SLASH_UNKNOWN_PENALTY),
36
+ slashOffenseExpirationRounds: slasherDefaultEnv.SLASH_OFFENSE_EXPIRATION_ROUNDS,
37
+ slashMaxPayloadSize: slasherDefaultEnv.SLASH_MAX_PAYLOAD_SIZE,
38
+ slashGracePeriodL2Slots: slasherDefaultEnv.SLASH_GRACE_PERIOD_L2_SLOTS,
39
+ slashExecuteRoundsLookBack: slasherDefaultEnv.SLASH_EXECUTE_ROUNDS_LOOK_BACK,
40
+ slashSelfAllowed: false,
41
+ };
42
+
43
+ export const slasherConfigMappings: ConfigMappingsType<SlasherConfig> = {
44
+ slashOverridePayload: {
45
+ env: 'SLASH_OVERRIDE_PAYLOAD',
46
+ description: 'An Ethereum address for a slash payload to vote for unconditionally.',
47
+ parseEnv: (val: string) => EthAddress.fromString(val),
48
+ defaultValue: DefaultSlasherConfig.slashOverridePayload,
49
+ },
50
+ slashValidatorsAlways: {
51
+ env: 'SLASH_VALIDATORS_ALWAYS',
52
+ description: 'Comma-separated list of validator addresses that should always be slashed.',
53
+ parseEnv: (val: string) =>
54
+ val
55
+ .split(',')
56
+ .map(addr => addr.trim())
57
+ .filter(addr => addr.length > 0)
58
+ .map(addr => EthAddress.fromString(addr)),
59
+ defaultValue: DefaultSlasherConfig.slashValidatorsAlways,
60
+ },
61
+ slashValidatorsNever: {
62
+ env: 'SLASH_VALIDATORS_NEVER',
63
+ description: 'Comma-separated list of validator addresses that should never be slashed.',
64
+ parseEnv: (val: string) =>
65
+ val
66
+ .split(',')
67
+ .map(addr => addr.trim())
68
+ .filter(addr => addr.length > 0)
69
+ .map(addr => EthAddress.fromString(addr)),
70
+ defaultValue: DefaultSlasherConfig.slashValidatorsNever,
71
+ },
72
+ slashDataWithholdingPenalty: {
73
+ env: 'SLASH_DATA_WITHHOLDING_PENALTY',
74
+ description: 'Penalty for data withholding (0 records offenses without slash votes).',
75
+ ...bigintConfigHelper(DefaultSlasherConfig.slashDataWithholdingPenalty),
76
+ },
77
+ slashDataWithholdingToleranceSlots: {
78
+ env: 'SLASH_DATA_WITHHOLDING_TOLERANCE_SLOTS',
79
+ description:
80
+ 'Number of full L2 slots that must elapse after a checkpoint slot before declaring its txs missing and slashing its attesters for data withholding.',
81
+ ...numberConfigHelper(DefaultSlasherConfig.slashDataWithholdingToleranceSlots),
82
+ },
83
+ slashBroadcastedInvalidBlockPenalty: {
84
+ env: 'SLASH_INVALID_BLOCK_PENALTY',
85
+ description: 'Penalty amount for slashing a validator for an invalid block proposed via p2p.',
86
+ ...bigintConfigHelper(DefaultSlasherConfig.slashBroadcastedInvalidBlockPenalty),
87
+ },
88
+ slashBroadcastedInvalidCheckpointProposalPenalty: {
89
+ env: 'SLASH_INVALID_CHECKPOINT_PROPOSAL_PENALTY',
90
+ description: 'Penalty amount for slashing a validator for an invalid checkpoint proposal proposed via p2p.',
91
+ ...bigintConfigHelper(DefaultSlasherConfig.slashBroadcastedInvalidCheckpointProposalPenalty),
92
+ },
93
+ slashDuplicateProposalPenalty: {
94
+ env: 'SLASH_DUPLICATE_PROPOSAL_PENALTY',
95
+ description: 'Penalty amount for slashing a validator for sending duplicate proposals.',
96
+ ...bigintConfigHelper(DefaultSlasherConfig.slashDuplicateProposalPenalty),
97
+ },
98
+ slashDuplicateAttestationPenalty: {
99
+ env: 'SLASH_DUPLICATE_ATTESTATION_PENALTY',
100
+ description:
101
+ 'Penalty amount for slashing a validator for signing attestations for different proposals at the same slot.',
102
+ ...bigintConfigHelper(DefaultSlasherConfig.slashDuplicateAttestationPenalty),
103
+ },
104
+ slashInactivityTargetPercentage: {
105
+ env: 'SLASH_INACTIVITY_TARGET_PERCENTAGE',
106
+ description:
107
+ 'Missed attestation percentage to trigger creation of inactivity slash payload (0, 1]. Must be greater than 0',
108
+ ...floatConfigHelper(DefaultSlasherConfig.slashInactivityTargetPercentage, v => {
109
+ if (v <= 0 || v > 1) {
110
+ throw new RangeError(`SLASH_INACTIVITY_TARGET_PERCENTAGE out of range. Expected (0, 1] got ${v}`);
111
+ }
112
+ }),
113
+ },
114
+ slashInactivityConsecutiveEpochThreshold: {
115
+ env: 'SLASH_INACTIVITY_CONSECUTIVE_EPOCH_THRESHOLD',
116
+ description: 'Number of consecutive epochs a validator must be inactive before slashing (minimum 1).',
117
+ ...numberConfigHelper(DefaultSlasherConfig.slashInactivityConsecutiveEpochThreshold),
118
+ parseEnv: (val: string) => {
119
+ const parsed = parseInt(val, 10);
120
+ if (parsed < 1) {
121
+ throw new RangeError(`SLASH_INACTIVITY_CONSECUTIVE_EPOCH_THRESHOLD must be at least 1 (got ${parsed})`);
122
+ }
123
+ return parsed;
124
+ },
125
+ },
126
+ slashInactivityPenalty: {
127
+ env: 'SLASH_INACTIVITY_PENALTY',
128
+ description: 'Penalty for an inactive validator (0 records offenses without slash votes).',
129
+ ...bigintConfigHelper(DefaultSlasherConfig.slashInactivityPenalty),
130
+ },
131
+ slashProposeInvalidAttestationsPenalty: {
132
+ env: 'SLASH_PROPOSE_INVALID_ATTESTATIONS_PENALTY',
133
+ description: 'Penalty for proposing invalid attestations (0 records offenses without slash votes).',
134
+ ...bigintConfigHelper(DefaultSlasherConfig.slashProposeInvalidAttestationsPenalty),
135
+ },
136
+ slashProposeDescendantOfCheckpointWithInvalidAttestationsPenalty: {
137
+ env: 'SLASH_PROPOSE_DESCENDANT_OF_CHECKPOINT_WITH_INVALID_ATTESTATIONS_PENALTY',
138
+ description:
139
+ 'Penalty for publishing a checkpoint building on an invalid checkpoint (0 records offenses without slash votes).',
140
+ ...bigintConfigHelper(DefaultSlasherConfig.slashProposeDescendantOfCheckpointWithInvalidAttestationsPenalty),
141
+ },
142
+ slashAttestInvalidCheckpointProposalPenalty: {
143
+ env: 'SLASH_ATTEST_INVALID_CHECKPOINT_PROPOSAL_PENALTY',
144
+ description: 'Penalty for attesting to an invalid checkpoint proposal (0 records offenses without slash votes).',
145
+ ...bigintConfigHelper(DefaultSlasherConfig.slashAttestInvalidCheckpointProposalPenalty),
146
+ },
147
+ slashUnknownPenalty: {
148
+ env: 'SLASH_UNKNOWN_PENALTY',
149
+ description: 'Penalty for an unknown offense (0 records offenses without slash votes).',
150
+ ...bigintConfigHelper(DefaultSlasherConfig.slashUnknownPenalty),
151
+ },
152
+ slashOffenseExpirationRounds: {
153
+ env: 'SLASH_OFFENSE_EXPIRATION_ROUNDS',
154
+ description: 'Number of rounds after which pending offenses expire.',
155
+ ...numberConfigHelper(DefaultSlasherConfig.slashOffenseExpirationRounds),
156
+ },
157
+ slashMaxPayloadSize: {
158
+ env: 'SLASH_MAX_PAYLOAD_SIZE',
159
+ description: 'Maximum number of offenses to include in a single slash payload.',
160
+ ...numberConfigHelper(DefaultSlasherConfig.slashMaxPayloadSize),
161
+ },
162
+ slashGracePeriodL2Slots: {
163
+ description:
164
+ 'Number of L2 slots after the network upgrade during which slashing offenses are ignored. The upgrade time is determined from the CanonicalRollupUpdated event.',
165
+ env: 'SLASH_GRACE_PERIOD_L2_SLOTS',
166
+ ...numberConfigHelper(DefaultSlasherConfig.slashGracePeriodL2Slots),
167
+ },
168
+ slashExecuteRoundsLookBack: {
169
+ env: 'SLASH_EXECUTE_ROUNDS_LOOK_BACK',
170
+ description: 'How many rounds to look back when searching for a round to execute.',
171
+ ...numberConfigHelper(DefaultSlasherConfig.slashExecuteRoundsLookBack),
172
+ },
173
+ slashSelfAllowed: {
174
+ description: 'Whether to allow slashes to own validators',
175
+ ...booleanConfigHelper(DefaultSlasherConfig.slashSelfAllowed),
176
+ },
177
+ };
@@ -0,0 +1,85 @@
1
+ import { EpochCache } from '@aztec-labs/epoch-cache';
2
+ import { RegistryContract, RollupContract } from '@aztec-labs/ethereum/contracts';
3
+ import type { L1ReaderConfig } from '@aztec-labs/ethereum/l1-reader';
4
+ import type { ViemClient } from '@aztec-labs/ethereum/types';
5
+ import { SlotNumber } from '@aztec-labs/foundation/branded-types';
6
+ import { unique } from '@aztec-labs/foundation/collection';
7
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
8
+ import { createLogger } from '@aztec-labs/foundation/log';
9
+ import { DateProvider } from '@aztec-labs/foundation/timer';
10
+ import { createStore } from '@aztec-labs/kv-store/lmdb-v2';
11
+ import { getSlotAtTimestamp } from '@aztec-labs/stdlib/epoch-helpers';
12
+ import type { SlasherConfig } from '@aztec-labs/stdlib/interfaces/server';
13
+ import type { DataStoreConfig } from '@aztec-labs/stdlib/kv-store';
14
+
15
+ import { SlasherClientFacade } from '../slasher_client_facade.js';
16
+ import type { SlasherClientInterface } from '../slasher_client_interface.js';
17
+ import { SCHEMA_VERSION } from '../stores/schema_version.js';
18
+ import type { Watcher } from '../watcher.js';
19
+
20
+ /** Creates a slasher client facade that updates itself whenever the rollup slasher changes */
21
+ export async function createSlasherFacade(
22
+ config: SlasherConfig & DataStoreConfig & { ethereumSlotDuration: number },
23
+ l1Contracts: Pick<L1ReaderConfig, 'rollupAddress' | 'registryAddress'>,
24
+ l1Client: ViemClient,
25
+ watchers: Watcher[],
26
+ dateProvider: DateProvider,
27
+ epochCache: EpochCache,
28
+ /**
29
+ * List of own validator addresses. Added to the slashValidatorNever list unless slashSelfAllowed is true, and used
30
+ * (independently of slashSelfAllowed) to warn and record metrics when they are targeted by onchain slashing.
31
+ */
32
+ validatorAddresses: EthAddress[] = [],
33
+ logger = createLogger('slasher'),
34
+ ): Promise<SlasherClientInterface> {
35
+ if (!l1Contracts.rollupAddress || l1Contracts.rollupAddress.equals(EthAddress.ZERO)) {
36
+ throw new Error('Cannot initialize SlasherClient without a Rollup address');
37
+ }
38
+
39
+ const kvStore = await createStore('slasher', SCHEMA_VERSION, config, logger.getBindings());
40
+ const rollup = new RollupContract(l1Client, l1Contracts.rollupAddress);
41
+
42
+ // Compute and cache the L2 slot at which the rollup was registered as canonical
43
+ const settingsMap = kvStore.openMap<string, number>('slasher-settings');
44
+ const cacheKey = `registeredSlot:${l1Contracts.rollupAddress}`;
45
+ let rollupRegisteredAtL2Slot = (await settingsMap.getAsync(cacheKey)) as SlotNumber | undefined;
46
+
47
+ if (rollupRegisteredAtL2Slot === undefined) {
48
+ const registry = new RegistryContract(l1Client, l1Contracts.registryAddress);
49
+ const l1StartBlock = await rollup.getL1StartBlock();
50
+ const registrationTimestamp = await registry.getCanonicalRollupRegistrationTimestamp(
51
+ l1Contracts.rollupAddress,
52
+ l1StartBlock,
53
+ );
54
+ if (registrationTimestamp !== undefined) {
55
+ const l1GenesisTime = await rollup.getL1GenesisTime();
56
+ const slotDuration = await rollup.getSlotDuration();
57
+ rollupRegisteredAtL2Slot = getSlotAtTimestamp(registrationTimestamp, {
58
+ l1GenesisTime,
59
+ slotDuration: Number(slotDuration),
60
+ });
61
+ } else {
62
+ rollupRegisteredAtL2Slot = SlotNumber(0);
63
+ }
64
+ await settingsMap.set(cacheKey, rollupRegisteredAtL2Slot);
65
+ logger.info(`Canonical rollup registered at L2 slot ${rollupRegisteredAtL2Slot}`);
66
+ }
67
+
68
+ const slashValidatorsNever = config.slashSelfAllowed
69
+ ? config.slashValidatorsNever
70
+ : unique([...config.slashValidatorsNever, ...validatorAddresses].map(a => a.toString())).map(EthAddress.fromString);
71
+ const updatedConfig = { ...config, slashValidatorsNever };
72
+
73
+ return new SlasherClientFacade(
74
+ updatedConfig,
75
+ rollup,
76
+ l1Client,
77
+ watchers,
78
+ epochCache,
79
+ dateProvider,
80
+ kvStore,
81
+ rollupRegisteredAtL2Slot,
82
+ validatorAddresses,
83
+ logger,
84
+ );
85
+ }
@@ -0,0 +1,83 @@
1
+ import { EpochCache } from '@aztec-labs/epoch-cache';
2
+ import { RollupContract, SlashingProposerContract } from '@aztec-labs/ethereum/contracts';
3
+ import type { ViemClient } from '@aztec-labs/ethereum/types';
4
+ import type { SlotNumber } from '@aztec-labs/foundation/branded-types';
5
+ import type { EthAddress } from '@aztec-labs/foundation/eth-address';
6
+ import { createLogger } from '@aztec-labs/foundation/log';
7
+ import { DateProvider } from '@aztec-labs/foundation/timer';
8
+ import { AztecLMDBStoreV2 } from '@aztec-labs/kv-store/lmdb-v2';
9
+ import type { SlasherConfig } from '@aztec-labs/stdlib/interfaces/server';
10
+ import type { DataStoreConfig } from '@aztec-labs/stdlib/kv-store';
11
+
12
+ import { NullSlasherClient } from '../null_slasher_client.js';
13
+ import { SlasherClient } from '../slasher_client.js';
14
+ import { SlasherOffensesStore } from '../stores/offenses_store.js';
15
+ import type { Watcher } from '../watcher.js';
16
+ import { getSlasherSettings } from './get_settings.js';
17
+
18
+ /** Creates a slasher client implementation based on the slasher proposer type in the rollup */
19
+ export async function createSlasherImplementation(
20
+ config: SlasherConfig & DataStoreConfig & { ethereumSlotDuration: number },
21
+ rollup: RollupContract,
22
+ l1Client: ViemClient,
23
+ watchers: Watcher[],
24
+ epochCache: EpochCache,
25
+ dateProvider: DateProvider,
26
+ kvStore: AztecLMDBStoreV2,
27
+ rollupRegisteredAtL2Slot: SlotNumber,
28
+ ownValidators: EthAddress[] = [],
29
+ logger = createLogger('slasher'),
30
+ ) {
31
+ const proposer = await rollup.getSlashingProposer();
32
+ if (!proposer) {
33
+ return new NullSlasherClient(config);
34
+ } else {
35
+ return createSlasher(
36
+ config,
37
+ rollup,
38
+ proposer,
39
+ watchers,
40
+ dateProvider,
41
+ epochCache,
42
+ kvStore,
43
+ rollupRegisteredAtL2Slot,
44
+ ownValidators,
45
+ logger,
46
+ );
47
+ }
48
+ }
49
+
50
+ async function createSlasher(
51
+ config: SlasherConfig & DataStoreConfig,
52
+ rollup: RollupContract,
53
+ slashingProposer: SlashingProposerContract,
54
+ watchers: Watcher[],
55
+ dateProvider: DateProvider,
56
+ epochCache: EpochCache,
57
+ kvStore: AztecLMDBStoreV2,
58
+ rollupRegisteredAtL2Slot: SlotNumber,
59
+ ownValidators: EthAddress[] = [],
60
+ logger = createLogger('slasher'),
61
+ ): Promise<SlasherClient> {
62
+ const settings = { ...(await getSlasherSettings(rollup, slashingProposer)), rollupRegisteredAtL2Slot };
63
+ const slasher = await rollup.getSlasherContract();
64
+
65
+ const offensesStore = new SlasherOffensesStore(kvStore, {
66
+ ...settings,
67
+ slashOffenseExpirationRounds: config.slashOffenseExpirationRounds,
68
+ });
69
+
70
+ return new SlasherClient(
71
+ config,
72
+ settings,
73
+ slashingProposer,
74
+ slasher!,
75
+ rollup,
76
+ watchers,
77
+ epochCache,
78
+ dateProvider,
79
+ offensesStore,
80
+ ownValidators,
81
+ logger,
82
+ );
83
+ }