@aztec/validator-ha-signer 0.0.1-commit.3469e52 → 0.0.1-commit.3895657bc

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 (46) hide show
  1. package/README.md +10 -2
  2. package/dest/db/index.d.ts +2 -1
  3. package/dest/db/index.d.ts.map +1 -1
  4. package/dest/db/index.js +1 -0
  5. package/dest/db/lmdb.d.ts +66 -0
  6. package/dest/db/lmdb.d.ts.map +1 -0
  7. package/dest/db/lmdb.js +188 -0
  8. package/dest/db/postgres.d.ts +20 -4
  9. package/dest/db/postgres.d.ts.map +1 -1
  10. package/dest/db/postgres.js +44 -17
  11. package/dest/db/schema.d.ts +17 -10
  12. package/dest/db/schema.d.ts.map +1 -1
  13. package/dest/db/schema.js +39 -22
  14. package/dest/db/types.d.ts +43 -19
  15. package/dest/db/types.d.ts.map +1 -1
  16. package/dest/db/types.js +30 -15
  17. package/dest/factory.d.ts +22 -4
  18. package/dest/factory.d.ts.map +1 -1
  19. package/dest/factory.js +50 -5
  20. package/dest/metrics.d.ts +51 -0
  21. package/dest/metrics.d.ts.map +1 -0
  22. package/dest/metrics.js +103 -0
  23. package/dest/slashing_protection_service.d.ts +19 -6
  24. package/dest/slashing_protection_service.d.ts.map +1 -1
  25. package/dest/slashing_protection_service.js +55 -15
  26. package/dest/types.d.ts +32 -72
  27. package/dest/types.d.ts.map +1 -1
  28. package/dest/types.js +3 -20
  29. package/dest/validator_ha_signer.d.ts +15 -6
  30. package/dest/validator_ha_signer.d.ts.map +1 -1
  31. package/dest/validator_ha_signer.js +24 -11
  32. package/package.json +10 -5
  33. package/src/db/index.ts +1 -0
  34. package/src/db/lmdb.ts +264 -0
  35. package/src/db/postgres.ts +45 -12
  36. package/src/db/schema.ts +41 -22
  37. package/src/db/types.ts +67 -17
  38. package/src/factory.ts +61 -4
  39. package/src/metrics.ts +138 -0
  40. package/src/slashing_protection_service.ts +77 -19
  41. package/src/types.ts +50 -103
  42. package/src/validator_ha_signer.ts +41 -15
  43. package/dest/config.d.ts +0 -79
  44. package/dest/config.d.ts.map +0 -1
  45. package/dest/config.js +0 -73
  46. package/src/config.ts +0 -125
package/src/factory.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  /**
2
2
  * Factory functions for creating validator HA signers
3
3
  */
4
+ import { DateProvider } from '@aztec/foundation/timer';
5
+ import { createStore } from '@aztec/kv-store/lmdb-v2';
6
+ import type { LocalSignerConfig, ValidatorHASignerConfig } from '@aztec/stdlib/ha-signing';
7
+ import { getTelemetryClient } from '@aztec/telemetry-client';
8
+
4
9
  import { Pool } from 'pg';
5
10
 
6
- import type { ValidatorHASignerConfig } from './config.js';
11
+ import { LmdbSlashingProtectionDatabase } from './db/lmdb.js';
7
12
  import { PostgresSlashingProtectionDatabase } from './db/postgres.js';
8
- import type { CreateHASignerDeps, SlashingProtectionDatabase } from './types.js';
13
+ import { HASignerMetrics } from './metrics.js';
14
+ import type { CreateHASignerDeps, CreateLocalSignerWithProtectionDeps, SlashingProtectionDatabase } from './types.js';
9
15
  import { ValidatorHASigner } from './validator_ha_signer.js';
10
16
 
11
17
  /**
@@ -23,7 +29,6 @@ import { ValidatorHASigner } from './validator_ha_signer.js';
23
29
  * ```typescript
24
30
  * const { signer, db } = await createHASigner({
25
31
  * databaseUrl: process.env.DATABASE_URL,
26
- * haSigningEnabled: true,
27
32
  * nodeId: 'validator-node-1',
28
33
  * pollingIntervalMs: 100,
29
34
  * signingTimeoutMs: 3000,
@@ -55,6 +60,10 @@ export async function createHASigner(
55
60
  if (!databaseUrl) {
56
61
  throw new Error('databaseUrl is required for createHASigner');
57
62
  }
63
+
64
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
65
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
66
+
58
67
  // Create connection pool (or use provided pool)
59
68
  let pool: Pool;
60
69
  if (!deps?.pool) {
@@ -75,8 +84,56 @@ export async function createHASigner(
75
84
  // Verify database schema is initialized and version matches
76
85
  await db.initialize();
77
86
 
87
+ // Create metrics
88
+ const metrics = new HASignerMetrics(telemetryClient, signerConfig.nodeId);
89
+
78
90
  // Create signer
79
- const signer = new ValidatorHASigner(db, { ...signerConfig, databaseUrl });
91
+ const signer = new ValidatorHASigner(db, signerConfig, { metrics, dateProvider });
92
+
93
+ return { signer, db };
94
+ }
95
+
96
+ /**
97
+ * Create a local (single-node) signing protection signer backed by LMDB.
98
+ *
99
+ * This provides double-signing protection for nodes that are NOT running in a
100
+ * high-availability (multi-node) setup. It prevents a proposer from sending two
101
+ * proposals for the same slot if the node crashes and restarts mid-proposal.
102
+ *
103
+ * When `config.dataDirectory` is set, the protection database is persisted to disk
104
+ * and survives crashes/restarts. When unset, an ephemeral in-memory store is
105
+ * used which protects within a single run but not across restarts.
106
+ *
107
+ * @param config - Local signer config
108
+ * @param deps - Optional dependencies (telemetry, date provider).
109
+ * @returns An object containing the signer and database instances.
110
+ */
111
+ export async function createLocalSignerWithProtection(
112
+ config: LocalSignerConfig,
113
+ deps?: CreateLocalSignerWithProtectionDeps,
114
+ ): Promise<{
115
+ signer: ValidatorHASigner;
116
+ db: SlashingProtectionDatabase;
117
+ }> {
118
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
119
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
120
+
121
+ const kvStore = await createStore('signing-protection', LmdbSlashingProtectionDatabase.SCHEMA_VERSION, {
122
+ dataDirectory: config.dataDirectory,
123
+ dataStoreMapSizeKb: config.signingProtectionMapSizeKb ?? config.dataStoreMapSizeKb,
124
+ l1Contracts: config.l1Contracts,
125
+ });
126
+
127
+ const db = new LmdbSlashingProtectionDatabase(kvStore, dateProvider);
128
+
129
+ const signerConfig = {
130
+ ...config,
131
+ nodeId: config.nodeId || 'local',
132
+ };
133
+
134
+ const metrics = new HASignerMetrics(telemetryClient, signerConfig.nodeId, 'LocalSigningProtectionMetrics');
135
+
136
+ const signer = new ValidatorHASigner(db, signerConfig, { metrics, dateProvider });
80
137
 
81
138
  return { signer, db };
82
139
  }
package/src/metrics.ts ADDED
@@ -0,0 +1,138 @@
1
+ import {
2
+ Attributes,
3
+ type Histogram,
4
+ Metrics,
5
+ type TelemetryClient,
6
+ type UpDownCounter,
7
+ createUpDownCounterWithDefault,
8
+ } from '@aztec/telemetry-client';
9
+
10
+ export type HACleanupType = 'stuck' | 'old' | 'outdated_rollup';
11
+
12
+ /**
13
+ * Metrics for HA signer tracking signing operations, lock acquisition, and cleanup.
14
+ */
15
+ export class HASignerMetrics {
16
+ // Signing lifecycle metrics
17
+ private signingDuration: Histogram;
18
+ private signingSuccessCount: UpDownCounter;
19
+ private dutyAlreadySignedCount: UpDownCounter;
20
+ private slashingProtectionCount: UpDownCounter;
21
+ private signingErrorCount: UpDownCounter;
22
+
23
+ // Lock acquisition metrics
24
+ private lockAcquiredCount: UpDownCounter;
25
+
26
+ // Cleanup metrics
27
+ private cleanupStuckDutiesCount: UpDownCounter;
28
+ private cleanupOldDutiesCount: UpDownCounter;
29
+ private cleanupOutdatedRollupDutiesCount: UpDownCounter;
30
+
31
+ constructor(
32
+ client: TelemetryClient,
33
+ private nodeId: string,
34
+ name = 'HASignerMetrics',
35
+ ) {
36
+ const meter = client.getMeter(name);
37
+
38
+ // Signing lifecycle
39
+ this.signingDuration = meter.createHistogram(Metrics.HA_SIGNER_SIGNING_DURATION);
40
+ this.signingSuccessCount = createUpDownCounterWithDefault(meter, Metrics.HA_SIGNER_SIGNING_SUCCESS_COUNT);
41
+ this.dutyAlreadySignedCount = createUpDownCounterWithDefault(meter, Metrics.HA_SIGNER_DUTY_ALREADY_SIGNED_COUNT);
42
+ this.slashingProtectionCount = createUpDownCounterWithDefault(meter, Metrics.HA_SIGNER_SLASHING_PROTECTION_COUNT);
43
+ this.signingErrorCount = createUpDownCounterWithDefault(meter, Metrics.HA_SIGNER_SIGNING_ERROR_COUNT);
44
+
45
+ // Lock acquisition
46
+ this.lockAcquiredCount = createUpDownCounterWithDefault(meter, Metrics.HA_SIGNER_LOCK_ACQUIRED_COUNT);
47
+
48
+ // Cleanup
49
+ this.cleanupStuckDutiesCount = createUpDownCounterWithDefault(meter, Metrics.HA_SIGNER_CLEANUP_STUCK_DUTIES_COUNT);
50
+ this.cleanupOldDutiesCount = createUpDownCounterWithDefault(meter, Metrics.HA_SIGNER_CLEANUP_OLD_DUTIES_COUNT);
51
+ this.cleanupOutdatedRollupDutiesCount = createUpDownCounterWithDefault(
52
+ meter,
53
+ Metrics.HA_SIGNER_CLEANUP_OUTDATED_ROLLUP_DUTIES_COUNT,
54
+ );
55
+ }
56
+
57
+ /**
58
+ * Record a successful signing operation.
59
+ * @param dutyType - The type of duty signed
60
+ * @param durationMs - Duration from start of signWithProtection to completion
61
+ */
62
+ public recordSigningSuccess(dutyType: string, durationMs: number): void {
63
+ const attributes = {
64
+ [Attributes.HA_DUTY_TYPE]: dutyType,
65
+ [Attributes.HA_NODE_ID]: this.nodeId,
66
+ };
67
+ this.signingSuccessCount.add(1, attributes);
68
+ this.signingDuration.record(durationMs, attributes);
69
+ }
70
+
71
+ /**
72
+ * Record a DutyAlreadySignedError (expected in HA; another node signed first).
73
+ * @param dutyType - The type of duty
74
+ */
75
+ public recordDutyAlreadySigned(dutyType: string): void {
76
+ const attributes = {
77
+ [Attributes.HA_DUTY_TYPE]: dutyType,
78
+ [Attributes.HA_NODE_ID]: this.nodeId,
79
+ };
80
+ this.dutyAlreadySignedCount.add(1, attributes);
81
+ }
82
+
83
+ /**
84
+ * Record a SlashingProtectionError (attempted to sign different data for same duty).
85
+ * @param dutyType - The type of duty
86
+ */
87
+ public recordSlashingProtection(dutyType: string): void {
88
+ const attributes = {
89
+ [Attributes.HA_DUTY_TYPE]: dutyType,
90
+ [Attributes.HA_NODE_ID]: this.nodeId,
91
+ };
92
+ this.slashingProtectionCount.add(1, attributes);
93
+ }
94
+
95
+ /**
96
+ * Record a signing function failure (lock will be deleted for retry).
97
+ * @param dutyType - The type of duty
98
+ */
99
+ public recordSigningError(dutyType: string): void {
100
+ const attributes = {
101
+ [Attributes.HA_DUTY_TYPE]: dutyType,
102
+ [Attributes.HA_NODE_ID]: this.nodeId,
103
+ };
104
+ this.signingErrorCount.add(1, attributes);
105
+ }
106
+
107
+ /**
108
+ * Record lock acquisition.
109
+ * @param acquired - Whether a new lock was acquired (true) or existing record found (false)
110
+ */
111
+ public recordLockAcquire(acquired: boolean): void {
112
+ if (acquired) {
113
+ const attributes = {
114
+ [Attributes.HA_NODE_ID]: this.nodeId,
115
+ };
116
+ this.lockAcquiredCount.add(1, attributes);
117
+ }
118
+ }
119
+
120
+ /**
121
+ * Record cleanup metrics.
122
+ * @param type - Type of cleanup
123
+ * @param count - Number of duties cleaned up
124
+ */
125
+ public recordCleanup(type: HACleanupType, count: number): void {
126
+ const attributes = {
127
+ [Attributes.HA_NODE_ID]: this.nodeId,
128
+ };
129
+
130
+ if (type === 'stuck') {
131
+ this.cleanupStuckDutiesCount.add(count, attributes);
132
+ } else if (type === 'old') {
133
+ this.cleanupOldDutiesCount.add(count, attributes);
134
+ } else if (type === 'outdated_rollup') {
135
+ this.cleanupOutdatedRollupDutiesCount.add(count, attributes);
136
+ }
137
+ }
138
+ }
@@ -7,6 +7,8 @@
7
7
  import { type Logger, createLogger } from '@aztec/foundation/log';
8
8
  import { RunningPromise } from '@aztec/foundation/promise';
9
9
  import { sleep } from '@aztec/foundation/sleep';
10
+ import type { DateProvider } from '@aztec/foundation/timer';
11
+ import type { BaseSignerConfig } from '@aztec/stdlib/ha-signing';
10
12
 
11
13
  import {
12
14
  type CheckAndRecordParams,
@@ -16,7 +18,13 @@ import {
16
18
  getBlockIndexFromDutyIdentifier,
17
19
  } from './db/types.js';
18
20
  import { DutyAlreadySignedError, SlashingProtectionError } from './errors.js';
19
- import type { SlashingProtectionDatabase, ValidatorHASignerConfig } from './types.js';
21
+ import type { HASignerMetrics } from './metrics.js';
22
+ import type { SlashingProtectionDatabase } from './types.js';
23
+
24
+ export interface SlashingProtectionServiceDeps {
25
+ metrics: HASignerMetrics;
26
+ dateProvider: DateProvider;
27
+ }
20
28
 
21
29
  /**
22
30
  * Slashing Protection Service
@@ -39,11 +47,16 @@ export class SlashingProtectionService {
39
47
  private readonly signingTimeoutMs: number;
40
48
  private readonly maxStuckDutiesAgeMs: number;
41
49
 
50
+ private readonly metrics: HASignerMetrics;
51
+ private readonly dateProvider: DateProvider;
52
+
42
53
  private cleanupRunningPromise: RunningPromise;
54
+ private lastOldDutiesCleanupAtMs?: number;
43
55
 
44
56
  constructor(
45
57
  private readonly db: SlashingProtectionDatabase,
46
- private readonly config: ValidatorHASignerConfig,
58
+ private readonly config: BaseSignerConfig,
59
+ deps: SlashingProtectionServiceDeps,
47
60
  ) {
48
61
  this.log = createLogger('slashing-protection');
49
62
  this.pollingIntervalMs = config.pollingIntervalMs;
@@ -51,11 +64,9 @@ export class SlashingProtectionService {
51
64
  // Default to 144s (2x 72s Aztec slot duration) if not explicitly configured
52
65
  this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? 144_000;
53
66
 
54
- this.cleanupRunningPromise = new RunningPromise(
55
- this.cleanupStuckDuties.bind(this),
56
- this.log,
57
- this.maxStuckDutiesAgeMs,
58
- );
67
+ this.cleanupRunningPromise = new RunningPromise(this.cleanup.bind(this), this.log, this.maxStuckDutiesAgeMs);
68
+ this.metrics = deps.metrics;
69
+ this.dateProvider = deps.dateProvider;
59
70
  }
60
71
 
61
72
  /**
@@ -67,7 +78,6 @@ export class SlashingProtectionService {
67
78
  * 2. If insert succeeds, we acquired the lock - return the lockToken
68
79
  * 3. If a record exists, handle based on status:
69
80
  * - SIGNED: Throw appropriate error (already signed or slashing protection)
70
- * - FAILED: Delete the failed record
71
81
  * - SIGNING: Wait and poll until status changes, then handle result
72
82
  *
73
83
  * @returns The lockToken that must be used for recordSuccess/deleteDuty
@@ -76,7 +86,7 @@ export class SlashingProtectionService {
76
86
  */
77
87
  async checkAndRecord(params: CheckAndRecordParams): Promise<string> {
78
88
  const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
79
- const startTime = Date.now();
89
+ const startTime = this.dateProvider.now();
80
90
 
81
91
  this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
82
92
  validatorAddress: validatorAddress.toString(),
@@ -93,6 +103,7 @@ export class SlashingProtectionService {
93
103
  validatorAddress: validatorAddress.toString(),
94
104
  nodeId,
95
105
  });
106
+ this.metrics.recordLockAcquire(true);
96
107
  return record.lockToken;
97
108
  }
98
109
 
@@ -107,6 +118,7 @@ export class SlashingProtectionService {
107
118
  existingNodeId: record.nodeId,
108
119
  attemptingNodeId: nodeId,
109
120
  });
121
+ this.metrics.recordSlashingProtection(dutyType);
110
122
  throw new SlashingProtectionError(
111
123
  slot,
112
124
  dutyType,
@@ -116,15 +128,17 @@ export class SlashingProtectionService {
116
128
  record.nodeId,
117
129
  );
118
130
  }
131
+ this.metrics.recordDutyAlreadySigned(dutyType);
119
132
  throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
120
133
  } else if (record.status === DutyStatus.SIGNING) {
121
134
  // Another node is currently signing - check for timeout
122
- if (Date.now() - startTime > this.signingTimeoutMs) {
135
+ if (this.dateProvider.now() - startTime > this.signingTimeoutMs) {
123
136
  this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
124
137
  validatorAddress: validatorAddress.toString(),
125
138
  timeoutMs: this.signingTimeoutMs,
126
139
  signingNodeId: record.nodeId,
127
140
  });
141
+ this.metrics.recordDutyAlreadySigned(dutyType);
128
142
  throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
129
143
  }
130
144
 
@@ -149,10 +163,11 @@ export class SlashingProtectionService {
149
163
  * @returns true if the update succeeded, false if token didn't match
150
164
  */
151
165
  async recordSuccess(params: RecordSuccessParams): Promise<boolean> {
152
- const { validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
166
+ const { rollupAddress, validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
153
167
  const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
154
168
 
155
169
  const success = await this.db.updateDutySigned(
170
+ rollupAddress,
156
171
  validatorAddress,
157
172
  slot,
158
173
  dutyType,
@@ -184,10 +199,17 @@ export class SlashingProtectionService {
184
199
  * @returns true if the delete succeeded, false if token didn't match
185
200
  */
186
201
  async deleteDuty(params: DeleteDutyParams): Promise<boolean> {
187
- const { validatorAddress, slot, dutyType, lockToken } = params;
202
+ const { rollupAddress, validatorAddress, slot, dutyType, lockToken } = params;
188
203
  const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
189
204
 
190
- const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint);
205
+ const success = await this.db.deleteDuty(
206
+ rollupAddress,
207
+ validatorAddress,
208
+ slot,
209
+ dutyType,
210
+ lockToken,
211
+ blockIndexWithinCheckpoint,
212
+ );
191
213
 
192
214
  if (success) {
193
215
  this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
@@ -213,7 +235,20 @@ export class SlashingProtectionService {
213
235
  * Start running tasks.
214
236
  * Cleanup runs immediately on start to recover from any previous crashes.
215
237
  */
216
- start() {
238
+ /**
239
+ * Start the background cleanup task.
240
+ * Also performs one-time cleanup of duties with outdated rollup addresses.
241
+ */
242
+ async start() {
243
+ // One-time cleanup at startup: remove duties from previous rollup versions
244
+ const numOutdatedRollupDuties = await this.db.cleanupOutdatedRollupDuties(this.config.l1Contracts.rollupAddress);
245
+ if (numOutdatedRollupDuties > 0) {
246
+ this.log.info(`Cleaned up ${numOutdatedRollupDuties} duties with outdated rollup address at startup`, {
247
+ currentRollupAddress: this.config.l1Contracts.rollupAddress.toString(),
248
+ });
249
+ this.metrics.recordCleanup('outdated_rollup', numOutdatedRollupDuties);
250
+ }
251
+
217
252
  this.cleanupRunningPromise.start();
218
253
  this.log.info('Slashing protection service started', { nodeId: this.config.nodeId });
219
254
  }
@@ -236,15 +271,38 @@ export class SlashingProtectionService {
236
271
  }
237
272
 
238
273
  /**
239
- * Cleanup own stuck duties
274
+ * Periodic cleanup of stuck duties and optionally old signed duties.
275
+ * Runs in the background via RunningPromise.
240
276
  */
241
- private async cleanupStuckDuties() {
242
- const numDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
243
- if (numDuties > 0) {
244
- this.log.info(`Cleaned up ${numDuties} stuck duties`, {
277
+ private async cleanup() {
278
+ // 1. Clean up stuck duties (our own node's duties that got stuck in 'signing' status)
279
+ const numStuckDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
280
+ if (numStuckDuties > 0) {
281
+ this.log.verbose(`Cleaned up ${numStuckDuties} stuck duties`, {
245
282
  nodeId: this.config.nodeId,
246
283
  maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs,
247
284
  });
285
+ this.metrics.recordCleanup('stuck', numStuckDuties);
286
+ }
287
+
288
+ // 2. Clean up old signed duties if configured
289
+ // we shouldn't run this as often as stuck duty cleanup.
290
+ if (this.config.cleanupOldDutiesAfterHours !== undefined) {
291
+ const maxAgeMs = this.config.cleanupOldDutiesAfterHours * 60 * 60 * 1000;
292
+ const nowMs = this.dateProvider.now();
293
+ const shouldRun =
294
+ this.lastOldDutiesCleanupAtMs === undefined || nowMs - this.lastOldDutiesCleanupAtMs >= maxAgeMs;
295
+ if (shouldRun) {
296
+ const numOldDuties = await this.db.cleanupOldDuties(maxAgeMs);
297
+ this.lastOldDutiesCleanupAtMs = nowMs;
298
+ if (numOldDuties > 0) {
299
+ this.log.verbose(`Cleaned up ${numOldDuties} old signed duties`, {
300
+ cleanupOldDutiesAfterHours: this.config.cleanupOldDutiesAfterHours,
301
+ maxAgeMs,
302
+ });
303
+ this.metrics.recordCleanup('old', numOldDuties);
304
+ }
305
+ }
248
306
  }
249
307
  }
250
308
  }
package/src/types.ts CHANGED
@@ -1,23 +1,27 @@
1
- import {
2
- BlockNumber,
3
- type CheckpointNumber,
4
- type IndexWithinCheckpoint,
5
- type SlotNumber,
6
- } from '@aztec/foundation/branded-types';
1
+ import { SlotNumber } from '@aztec/foundation/branded-types';
7
2
  import type { EthAddress } from '@aztec/foundation/eth-address';
3
+ import { DateProvider } from '@aztec/foundation/timer';
4
+ import {
5
+ DutyType,
6
+ type HAProtectedSigningContext,
7
+ type SigningContext,
8
+ type ValidatorHASignerConfig,
9
+ getBlockNumberFromSigningContext as getBlockNumberFromSigningContextFromStdlib,
10
+ isHAProtectedContext,
11
+ } from '@aztec/stdlib/ha-signing';
12
+ import type { TelemetryClient } from '@aztec/telemetry-client';
8
13
 
9
14
  import type { Pool } from 'pg';
10
15
 
11
- import type { ValidatorHASignerConfig } from './config.js';
12
- import {
13
- type BlockProposalDutyIdentifier,
14
- type CheckAndRecordParams,
15
- type DeleteDutyParams,
16
- type DutyIdentifier,
17
- DutyType,
18
- type OtherDutyIdentifier,
19
- type RecordSuccessParams,
20
- type ValidatorDutyRecord,
16
+ import type {
17
+ BlockProposalDutyIdentifier,
18
+ CheckAndRecordParams,
19
+ DeleteDutyParams,
20
+ DutyIdentifier,
21
+ DutyRow,
22
+ OtherDutyIdentifier,
23
+ RecordSuccessParams,
24
+ ValidatorDutyRecord,
21
25
  } from './db/types.js';
22
26
 
23
27
  export type {
@@ -25,12 +29,17 @@ export type {
25
29
  CheckAndRecordParams,
26
30
  DeleteDutyParams,
27
31
  DutyIdentifier,
32
+ DutyRow,
33
+ HAProtectedSigningContext,
28
34
  OtherDutyIdentifier,
29
35
  RecordSuccessParams,
36
+ SigningContext,
30
37
  ValidatorDutyRecord,
31
38
  ValidatorHASignerConfig,
32
39
  };
33
40
  export { DutyStatus, DutyType, getBlockIndexFromDutyIdentifier, normalizeBlockIndex } from './db/types.js';
41
+ export { isHAProtectedContext };
42
+ export { getBlockNumberFromSigningContextFromStdlib as getBlockNumberFromSigningContext };
34
43
 
35
44
  /**
36
45
  * Result of tryInsertOrGetExisting operation
@@ -51,99 +60,20 @@ export interface CreateHASignerDeps {
51
60
  * If provided, databaseUrl and poolConfig are ignored
52
61
  */
53
62
  pool?: Pool;
54
- }
55
-
56
- /**
57
- * Base context for signing operations
58
- */
59
- interface BaseSigningContext {
60
- /** Slot number for this duty */
61
- slot: SlotNumber;
62
63
  /**
63
- * Block or checkpoint number for this duty.
64
- * For block proposals, this is the block number.
65
- * For checkpoint proposals, this is the checkpoint number.
64
+ * Optional telemetry client for metrics
66
65
  */
67
- blockNumber: BlockNumber | CheckpointNumber;
68
- }
69
-
70
- /**
71
- * Signing context for block proposals.
72
- * blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
73
- */
74
- export interface BlockProposalSigningContext extends BaseSigningContext {
75
- /** Block index within checkpoint (0, 1, 2...). Required for block proposals. */
76
- blockIndexWithinCheckpoint: IndexWithinCheckpoint;
77
- dutyType: DutyType.BLOCK_PROPOSAL;
78
- }
79
-
80
- /**
81
- * Signing context for non-block-proposal duties that require HA protection.
82
- * blockIndexWithinCheckpoint is not applicable (internally always -1).
83
- */
84
- export interface OtherSigningContext extends BaseSigningContext {
85
- dutyType: DutyType.CHECKPOINT_PROPOSAL | DutyType.ATTESTATION | DutyType.ATTESTATIONS_AND_SIGNERS;
86
- }
87
-
88
- /**
89
- * Signing context for governance/slashing votes which only need slot for HA protection.
90
- * blockNumber is not applicable (internally always 0).
91
- */
92
- export interface VoteSigningContext {
93
- slot: SlotNumber;
94
- dutyType: DutyType.GOVERNANCE_VOTE | DutyType.SLASHING_VOTE;
95
- }
96
-
97
- /**
98
- * Signing context for duties which don't require slot/blockNumber
99
- * as they don't need HA protection (AUTH_REQUEST, TXS).
100
- */
101
- export interface NoHAProtectionSigningContext {
102
- dutyType: DutyType.AUTH_REQUEST | DutyType.TXS;
103
- }
104
-
105
- /**
106
- * Signing contexts that require HA protection (excludes AUTH_REQUEST).
107
- * Used by the HA signer's signWithProtection method.
108
- */
109
- export type HAProtectedSigningContext = BlockProposalSigningContext | OtherSigningContext | VoteSigningContext;
110
-
111
- /**
112
- * Type guard to check if a SigningContext requires HA protection.
113
- * Returns true for contexts that need HA protection, false for AUTH_REQUEST and TXS.
114
- */
115
- export function isHAProtectedContext(context: SigningContext): context is HAProtectedSigningContext {
116
- return context.dutyType !== DutyType.AUTH_REQUEST && context.dutyType !== DutyType.TXS;
117
- }
118
-
119
- /**
120
- * Gets the block number from a signing context.
121
- * - Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE): returns BlockNumber(0)
122
- * - Other duties: returns the blockNumber from the context
123
- */
124
- export function getBlockNumberFromSigningContext(context: HAProtectedSigningContext): BlockNumber | CheckpointNumber {
125
- // Check for duty types that have blockNumber
126
- if (
127
- context.dutyType === DutyType.BLOCK_PROPOSAL ||
128
- context.dutyType === DutyType.CHECKPOINT_PROPOSAL ||
129
- context.dutyType === DutyType.ATTESTATION ||
130
- context.dutyType === DutyType.ATTESTATIONS_AND_SIGNERS
131
- ) {
132
- return context.blockNumber;
133
- }
134
- // Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE) don't have blockNumber
135
- return BlockNumber(0);
66
+ telemetryClient?: TelemetryClient;
67
+ /**
68
+ * Optional date provider for timestamps
69
+ */
70
+ dateProvider?: DateProvider;
136
71
  }
137
72
 
138
73
  /**
139
- * Context required for slashing protection during signing operations.
140
- * Uses discriminated union to enforce type safety:
141
- * - BLOCK_PROPOSAL duties MUST have blockIndexWithinCheckpoint >= 0
142
- * - Other duty types do NOT have blockIndexWithinCheckpoint (internally -1)
143
- * - Vote duties only need slot (blockNumber is internally 0)
144
- * - AUTH_REQUEST and TXS duties don't need slot/blockNumber (no HA protection needed)
74
+ * deps for creating a local signing protection signer
145
75
  */
146
- export type SigningContext = HAProtectedSigningContext | NoHAProtectionSigningContext;
76
+ export type CreateLocalSignerWithProtectionDeps = Omit<CreateHASignerDeps, 'pool'>;
147
77
 
148
78
  /**
149
79
  * Database interface for slashing protection operations
@@ -170,6 +100,7 @@ export interface SlashingProtectionDatabase {
170
100
  * @returns true if the update succeeded, false if token didn't match or duty not found
171
101
  */
172
102
  updateDutySigned(
103
+ rollupAddress: EthAddress,
173
104
  validatorAddress: EthAddress,
174
105
  slot: SlotNumber,
175
106
  dutyType: DutyType,
@@ -186,6 +117,7 @@ export interface SlashingProtectionDatabase {
186
117
  * @returns true if the delete succeeded, false if token didn't match or duty not found
187
118
  */
188
119
  deleteDuty(
120
+ rollupAddress: EthAddress,
189
121
  validatorAddress: EthAddress,
190
122
  slot: SlotNumber,
191
123
  dutyType: DutyType,
@@ -199,6 +131,21 @@ export interface SlashingProtectionDatabase {
199
131
  */
200
132
  cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
201
133
 
134
+ /**
135
+ * Cleanup duties with outdated rollup address.
136
+ * Removes all duties where the rollup address doesn't match the current one.
137
+ * Used after a rollup upgrade to clean up duties for the old rollup.
138
+ * @returns the number of duties cleaned up
139
+ */
140
+ cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number>;
141
+
142
+ /**
143
+ * Cleanup old signed duties.
144
+ * Removes only signed duties older than the specified age.
145
+ * @returns the number of duties cleaned up
146
+ */
147
+ cleanupOldDuties(maxAgeMs: number): Promise<number>;
148
+
202
149
  /**
203
150
  * Close the database connection.
204
151
  * Should be called during graceful shutdown.