@aztec/validator-ha-signer 0.0.1-commit.a072138 → 0.0.1-commit.a5db02d

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 (58) hide show
  1. package/README.md +12 -4
  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 +70 -0
  6. package/dest/db/lmdb.d.ts.map +1 -0
  7. package/dest/db/lmdb.js +223 -0
  8. package/dest/db/migrations/1_initial-schema.d.ts +4 -2
  9. package/dest/db/migrations/1_initial-schema.d.ts.map +1 -1
  10. package/dest/db/migrations/1_initial-schema.js +34 -4
  11. package/dest/db/migrations/2_add-checkpoint-number.d.ts +7 -0
  12. package/dest/db/migrations/2_add-checkpoint-number.d.ts.map +1 -0
  13. package/dest/db/migrations/2_add-checkpoint-number.js +17 -0
  14. package/dest/db/postgres.d.ts +20 -4
  15. package/dest/db/postgres.d.ts.map +1 -1
  16. package/dest/db/postgres.js +46 -17
  17. package/dest/db/schema.d.ts +18 -11
  18. package/dest/db/schema.d.ts.map +1 -1
  19. package/dest/db/schema.js +45 -23
  20. package/dest/db/types.d.ts +52 -22
  21. package/dest/db/types.d.ts.map +1 -1
  22. package/dest/db/types.js +31 -15
  23. package/dest/errors.d.ts +14 -1
  24. package/dest/errors.d.ts.map +1 -1
  25. package/dest/errors.js +15 -0
  26. package/dest/factory.d.ts +38 -5
  27. package/dest/factory.d.ts.map +1 -1
  28. package/dest/factory.js +104 -8
  29. package/dest/metrics.d.ts +51 -0
  30. package/dest/metrics.d.ts.map +1 -0
  31. package/dest/metrics.js +103 -0
  32. package/dest/slashing_protection_service.d.ts +22 -7
  33. package/dest/slashing_protection_service.d.ts.map +1 -1
  34. package/dest/slashing_protection_service.js +65 -22
  35. package/dest/types.d.ts +33 -72
  36. package/dest/types.d.ts.map +1 -1
  37. package/dest/types.js +4 -20
  38. package/dest/validator_ha_signer.d.ts +16 -6
  39. package/dest/validator_ha_signer.d.ts.map +1 -1
  40. package/dest/validator_ha_signer.js +54 -16
  41. package/package.json +11 -6
  42. package/src/db/index.ts +1 -0
  43. package/src/db/lmdb.ts +308 -0
  44. package/src/db/migrations/1_initial-schema.ts +35 -4
  45. package/src/db/migrations/2_add-checkpoint-number.ts +19 -0
  46. package/src/db/postgres.ts +47 -12
  47. package/src/db/schema.ts +47 -23
  48. package/src/db/types.ts +72 -20
  49. package/src/errors.ts +21 -0
  50. package/src/factory.ts +141 -7
  51. package/src/metrics.ts +138 -0
  52. package/src/slashing_protection_service.ts +90 -27
  53. package/src/types.ts +56 -103
  54. package/src/validator_ha_signer.ts +85 -19
  55. package/dest/config.d.ts +0 -79
  56. package/dest/config.d.ts.map +0 -1
  57. package/dest/config.js +0 -73
  58. package/src/config.ts +0 -125
@@ -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,16 @@ 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
+ }
28
+
29
+ /** Default max age (ms) of a stuck SIGNING duty before cleanup reclaims it: 2x the 72s Aztec slot duration. */
30
+ export const DEFAULT_MAX_STUCK_DUTIES_AGE_MS = 144_000;
20
31
 
21
32
  /**
22
33
  * Slashing Protection Service
@@ -36,26 +47,28 @@ import type { SlashingProtectionDatabase, ValidatorHASignerConfig } from './type
36
47
  export class SlashingProtectionService {
37
48
  private readonly log: Logger;
38
49
  private readonly pollingIntervalMs: number;
39
- private readonly signingTimeoutMs: number;
50
+ private readonly peerSigningTimeoutMs: number;
40
51
  private readonly maxStuckDutiesAgeMs: number;
41
52
 
53
+ private readonly metrics: HASignerMetrics;
54
+ private readonly dateProvider: DateProvider;
55
+
42
56
  private cleanupRunningPromise: RunningPromise;
57
+ private lastOldDutiesCleanupAtMs?: number;
43
58
 
44
59
  constructor(
45
60
  private readonly db: SlashingProtectionDatabase,
46
- private readonly config: ValidatorHASignerConfig,
61
+ private readonly config: BaseSignerConfig,
62
+ deps: SlashingProtectionServiceDeps,
47
63
  ) {
48
64
  this.log = createLogger('slashing-protection');
49
65
  this.pollingIntervalMs = config.pollingIntervalMs;
50
- this.signingTimeoutMs = config.signingTimeoutMs;
51
- // Default to 144s (2x 72s Aztec slot duration) if not explicitly configured
52
- this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? 144_000;
53
-
54
- this.cleanupRunningPromise = new RunningPromise(
55
- this.cleanupStuckDuties.bind(this),
56
- this.log,
57
- this.maxStuckDutiesAgeMs,
58
- );
66
+ this.peerSigningTimeoutMs = config.peerSigningTimeoutMs;
67
+ this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? DEFAULT_MAX_STUCK_DUTIES_AGE_MS;
68
+
69
+ this.cleanupRunningPromise = new RunningPromise(this.cleanup.bind(this), this.log, this.maxStuckDutiesAgeMs);
70
+ this.metrics = deps.metrics;
71
+ this.dateProvider = deps.dateProvider;
59
72
  }
60
73
 
61
74
  /**
@@ -67,7 +80,6 @@ export class SlashingProtectionService {
67
80
  * 2. If insert succeeds, we acquired the lock - return the lockToken
68
81
  * 3. If a record exists, handle based on status:
69
82
  * - SIGNED: Throw appropriate error (already signed or slashing protection)
70
- * - FAILED: Delete the failed record
71
83
  * - SIGNING: Wait and poll until status changes, then handle result
72
84
  *
73
85
  * @returns The lockToken that must be used for recordSuccess/deleteDuty
@@ -76,7 +88,7 @@ export class SlashingProtectionService {
76
88
  */
77
89
  async checkAndRecord(params: CheckAndRecordParams): Promise<string> {
78
90
  const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
79
- const startTime = Date.now();
91
+ const startTime = this.dateProvider.now();
80
92
 
81
93
  this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
82
94
  validatorAddress: validatorAddress.toString(),
@@ -89,10 +101,11 @@ export class SlashingProtectionService {
89
101
 
90
102
  if (isNew) {
91
103
  // We successfully acquired the lock
92
- this.log.info(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
104
+ this.log.verbose(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
93
105
  validatorAddress: validatorAddress.toString(),
94
106
  nodeId,
95
107
  });
108
+ this.metrics.recordLockAcquire(true);
96
109
  return record.lockToken;
97
110
  }
98
111
 
@@ -107,6 +120,7 @@ export class SlashingProtectionService {
107
120
  existingNodeId: record.nodeId,
108
121
  attemptingNodeId: nodeId,
109
122
  });
123
+ this.metrics.recordSlashingProtection(dutyType);
110
124
  throw new SlashingProtectionError(
111
125
  slot,
112
126
  dutyType,
@@ -116,15 +130,17 @@ export class SlashingProtectionService {
116
130
  record.nodeId,
117
131
  );
118
132
  }
133
+ this.metrics.recordDutyAlreadySigned(dutyType);
119
134
  throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
120
135
  } else if (record.status === DutyStatus.SIGNING) {
121
136
  // Another node is currently signing - check for timeout
122
- if (Date.now() - startTime > this.signingTimeoutMs) {
137
+ if (this.dateProvider.now() - startTime > this.peerSigningTimeoutMs) {
123
138
  this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
124
139
  validatorAddress: validatorAddress.toString(),
125
- timeoutMs: this.signingTimeoutMs,
140
+ timeoutMs: this.peerSigningTimeoutMs,
126
141
  signingNodeId: record.nodeId,
127
142
  });
143
+ this.metrics.recordDutyAlreadySigned(dutyType);
128
144
  throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
129
145
  }
130
146
 
@@ -149,10 +165,11 @@ export class SlashingProtectionService {
149
165
  * @returns true if the update succeeded, false if token didn't match
150
166
  */
151
167
  async recordSuccess(params: RecordSuccessParams): Promise<boolean> {
152
- const { validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
168
+ const { rollupAddress, validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
153
169
  const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
154
170
 
155
171
  const success = await this.db.updateDutySigned(
172
+ rollupAddress,
156
173
  validatorAddress,
157
174
  slot,
158
175
  dutyType,
@@ -162,7 +179,7 @@ export class SlashingProtectionService {
162
179
  );
163
180
 
164
181
  if (success) {
165
- this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
182
+ this.log.verbose(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
166
183
  validatorAddress: validatorAddress.toString(),
167
184
  nodeId,
168
185
  });
@@ -184,10 +201,17 @@ export class SlashingProtectionService {
184
201
  * @returns true if the delete succeeded, false if token didn't match
185
202
  */
186
203
  async deleteDuty(params: DeleteDutyParams): Promise<boolean> {
187
- const { validatorAddress, slot, dutyType, lockToken } = params;
204
+ const { rollupAddress, validatorAddress, slot, dutyType, lockToken } = params;
188
205
  const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
189
206
 
190
- const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint);
207
+ const success = await this.db.deleteDuty(
208
+ rollupAddress,
209
+ validatorAddress,
210
+ slot,
211
+ dutyType,
212
+ lockToken,
213
+ blockIndexWithinCheckpoint,
214
+ );
191
215
 
192
216
  if (success) {
193
217
  this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
@@ -213,7 +237,20 @@ export class SlashingProtectionService {
213
237
  * Start running tasks.
214
238
  * Cleanup runs immediately on start to recover from any previous crashes.
215
239
  */
216
- start() {
240
+ /**
241
+ * Start the background cleanup task.
242
+ * Also performs one-time cleanup of duties with outdated rollup addresses.
243
+ */
244
+ async start() {
245
+ // One-time cleanup at startup: remove duties from previous rollup versions
246
+ const numOutdatedRollupDuties = await this.db.cleanupOutdatedRollupDuties(this.config.rollupAddress);
247
+ if (numOutdatedRollupDuties > 0) {
248
+ this.log.info(`Cleaned up ${numOutdatedRollupDuties} duties with outdated rollup address at startup`, {
249
+ currentRollupAddress: this.config.rollupAddress.toString(),
250
+ });
251
+ this.metrics.recordCleanup('outdated_rollup', numOutdatedRollupDuties);
252
+ }
253
+
217
254
  this.cleanupRunningPromise.start();
218
255
  this.log.info('Slashing protection service started', { nodeId: this.config.nodeId });
219
256
  }
@@ -236,15 +273,41 @@ export class SlashingProtectionService {
236
273
  }
237
274
 
238
275
  /**
239
- * Cleanup own stuck duties
276
+ * Periodic cleanup of stuck duties and optionally old signed duties.
277
+ * Runs in the background via RunningPromise.
240
278
  */
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`, {
279
+ private async cleanup() {
280
+ // 1. Clean up stuck duties (our own node's duties that got stuck in 'signing' status).
281
+ // This cannot race an in-flight signing: every signing operation is hard-bounded by a timeout
282
+ // clamped below maxStuckDutiesAgeMs / 2 (see ValidatorHASigner), so a live SIGNING row is
283
+ // always released long before it can be considered stuck.
284
+ const numStuckDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
285
+ if (numStuckDuties > 0) {
286
+ this.log.verbose(`Cleaned up ${numStuckDuties} stuck duties`, {
245
287
  nodeId: this.config.nodeId,
246
288
  maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs,
247
289
  });
290
+ this.metrics.recordCleanup('stuck', numStuckDuties);
291
+ }
292
+
293
+ // 2. Clean up old signed duties if configured
294
+ // we shouldn't run this as often as stuck duty cleanup.
295
+ if (this.config.cleanupOldDutiesAfterHours !== undefined) {
296
+ const maxAgeMs = this.config.cleanupOldDutiesAfterHours * 60 * 60 * 1000;
297
+ const nowMs = this.dateProvider.now();
298
+ const shouldRun =
299
+ this.lastOldDutiesCleanupAtMs === undefined || nowMs - this.lastOldDutiesCleanupAtMs >= maxAgeMs;
300
+ if (shouldRun) {
301
+ const numOldDuties = await this.db.cleanupOldDuties(maxAgeMs);
302
+ this.lastOldDutiesCleanupAtMs = nowMs;
303
+ if (numOldDuties > 0) {
304
+ this.log.verbose(`Cleaned up ${numOldDuties} old signed duties`, {
305
+ cleanupOldDutiesAfterHours: this.config.cleanupOldDutiesAfterHours,
306
+ maxAgeMs,
307
+ });
308
+ this.metrics.recordCleanup('old', numOldDuties);
309
+ }
310
+ }
248
311
  }
249
312
  }
250
313
  }
package/src/types.ts CHANGED
@@ -1,36 +1,51 @@
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
+ type AttestationSigningContext,
6
+ type CheckpointProposalSigningContext,
7
+ DutyType,
8
+ type HAProtectedSigningContext,
9
+ type SigningContext,
10
+ type ValidatorHASignerConfig,
11
+ getBlockNumberFromSigningContext as getBlockNumberFromSigningContextFromStdlib,
12
+ getCheckpointNumberFromSigningContext as getCheckpointNumberFromSigningContextFromStdlib,
13
+ isHAProtectedContext,
14
+ } from '@aztec/stdlib/ha-signing';
15
+ import type { TelemetryClient } from '@aztec/telemetry-client';
8
16
 
9
17
  import type { Pool } from 'pg';
10
18
 
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,
19
+ import type {
20
+ BlockProposalDutyIdentifier,
21
+ CheckAndRecordParams,
22
+ DeleteDutyParams,
23
+ DutyIdentifier,
24
+ DutyRow,
25
+ OtherDutyIdentifier,
26
+ RecordSuccessParams,
27
+ ValidatorDutyRecord,
21
28
  } from './db/types.js';
22
29
 
23
30
  export type {
31
+ AttestationSigningContext,
24
32
  BlockProposalDutyIdentifier,
25
33
  CheckAndRecordParams,
34
+ CheckpointProposalSigningContext,
26
35
  DeleteDutyParams,
27
36
  DutyIdentifier,
37
+ DutyRow,
38
+ HAProtectedSigningContext,
28
39
  OtherDutyIdentifier,
29
40
  RecordSuccessParams,
41
+ SigningContext,
30
42
  ValidatorDutyRecord,
31
43
  ValidatorHASignerConfig,
32
44
  };
33
45
  export { DutyStatus, DutyType, getBlockIndexFromDutyIdentifier, normalizeBlockIndex } from './db/types.js';
46
+ export { isHAProtectedContext };
47
+ export { getBlockNumberFromSigningContextFromStdlib as getBlockNumberFromSigningContext };
48
+ export { getCheckpointNumberFromSigningContextFromStdlib as getCheckpointNumberFromSigningContext };
34
49
 
35
50
  /**
36
51
  * Result of tryInsertOrGetExisting operation
@@ -51,99 +66,20 @@ export interface CreateHASignerDeps {
51
66
  * If provided, databaseUrl and poolConfig are ignored
52
67
  */
53
68
  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
69
  /**
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.
70
+ * Optional telemetry client for metrics
66
71
  */
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);
72
+ telemetryClient?: TelemetryClient;
73
+ /**
74
+ * Optional date provider for timestamps
75
+ */
76
+ dateProvider?: DateProvider;
136
77
  }
137
78
 
138
79
  /**
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)
80
+ * deps for creating a local signing protection signer
145
81
  */
146
- export type SigningContext = HAProtectedSigningContext | NoHAProtectionSigningContext;
82
+ export type CreateLocalSignerWithProtectionDeps = Omit<CreateHASignerDeps, 'pool'>;
147
83
 
148
84
  /**
149
85
  * Database interface for slashing protection operations
@@ -170,6 +106,7 @@ export interface SlashingProtectionDatabase {
170
106
  * @returns true if the update succeeded, false if token didn't match or duty not found
171
107
  */
172
108
  updateDutySigned(
109
+ rollupAddress: EthAddress,
173
110
  validatorAddress: EthAddress,
174
111
  slot: SlotNumber,
175
112
  dutyType: DutyType,
@@ -186,6 +123,7 @@ export interface SlashingProtectionDatabase {
186
123
  * @returns true if the delete succeeded, false if token didn't match or duty not found
187
124
  */
188
125
  deleteDuty(
126
+ rollupAddress: EthAddress,
189
127
  validatorAddress: EthAddress,
190
128
  slot: SlotNumber,
191
129
  dutyType: DutyType,
@@ -199,6 +137,21 @@ export interface SlashingProtectionDatabase {
199
137
  */
200
138
  cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
201
139
 
140
+ /**
141
+ * Cleanup duties with outdated rollup address.
142
+ * Removes all duties where the rollup address doesn't match the current one.
143
+ * Used after a rollup upgrade to clean up duties for the old rollup.
144
+ * @returns the number of duties cleaned up
145
+ */
146
+ cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number>;
147
+
148
+ /**
149
+ * Cleanup old signed duties.
150
+ * Removes only signed duties older than the specified age.
151
+ * @returns the number of duties cleaned up
152
+ */
153
+ cleanupOldDuties(maxAgeMs: number): Promise<number>;
154
+
202
155
  /**
203
156
  * Close the database connection.
204
157
  * Should be called during graceful shutdown.
@@ -6,18 +6,31 @@
6
6
  * node will sign for a given duty (slot + duty type).
7
7
  */
8
8
  import type { Buffer32 } from '@aztec/foundation/buffer';
9
- import type { EthAddress } from '@aztec/foundation/eth-address';
9
+ import { EthAddress } from '@aztec/foundation/eth-address';
10
10
  import type { Signature } from '@aztec/foundation/eth-signature';
11
11
  import { type Logger, createLogger } from '@aztec/foundation/log';
12
-
13
- import type { ValidatorHASignerConfig } from './config.js';
14
- import { type DutyIdentifier, DutyType } from './db/types.js';
15
- import { SlashingProtectionService } from './slashing_protection_service.js';
12
+ import { type DateProvider, executeTimeout } from '@aztec/foundation/timer';
16
13
  import {
14
+ type BaseSignerConfig,
15
+ DutyType,
17
16
  type HAProtectedSigningContext,
18
- type SlashingProtectionDatabase,
19
17
  getBlockNumberFromSigningContext,
20
- } from './types.js';
18
+ getCheckpointNumberFromSigningContext,
19
+ } from '@aztec/stdlib/ha-signing';
20
+
21
+ import type { DutyIdentifier } from './db/types.js';
22
+ import { SigningLockLostError } from './errors.js';
23
+ import type { HASignerMetrics } from './metrics.js';
24
+ import { DEFAULT_MAX_STUCK_DUTIES_AGE_MS, SlashingProtectionService } from './slashing_protection_service.js';
25
+ import type { SlashingProtectionDatabase } from './types.js';
26
+
27
+ export interface ValidatorHASignerDeps {
28
+ metrics: HASignerMetrics;
29
+ dateProvider: DateProvider;
30
+ }
31
+
32
+ /** Default hard timeout (ms) for a single signer call when not configured. */
33
+ const DEFAULT_SIGNER_CALL_TIMEOUT_MS = 30_000;
21
34
 
22
35
  /**
23
36
  * Validator High Availability Signer
@@ -41,24 +54,47 @@ import {
41
54
  export class ValidatorHASigner {
42
55
  private readonly log: Logger;
43
56
  private readonly slashingProtection: SlashingProtectionService;
57
+ private readonly rollupAddress: EthAddress;
58
+
59
+ private readonly dateProvider: DateProvider;
60
+ private readonly metrics: HASignerMetrics;
61
+ private readonly signerCallTimeoutMs: number;
44
62
 
45
63
  constructor(
46
64
  db: SlashingProtectionDatabase,
47
- private readonly config: ValidatorHASignerConfig,
65
+ private readonly config: BaseSignerConfig,
66
+ deps: ValidatorHASignerDeps,
48
67
  ) {
49
68
  this.log = createLogger('validator-ha-signer');
50
69
 
51
- if (!config.haSigningEnabled) {
52
- // this shouldn't happen, the validator should use different signer for non-HA setups
53
- throw new Error('Validator HA Signer is not enabled in config');
54
- }
70
+ this.metrics = deps.metrics;
71
+ this.dateProvider = deps.dateProvider;
72
+
73
+ // Clamp the signer-call timeout below half the stuck-duty max age. This maintains the
74
+ // invariant that an in-flight signing always times out and releases its SIGNING row well before
75
+ // stuck-duty cleanup could consider it stuck, so cleanup can never delete a live duty (only
76
+ // signWithProtection writes SIGNING rows, and every path through it is bounded by this timeout).
77
+ // If timers misbehave anyway, the recordSuccess-returns-false throw is the backstop: the duty
78
+ // fails instead of broadcasting an unprotected signature.
79
+ const maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? DEFAULT_MAX_STUCK_DUTIES_AGE_MS;
80
+ this.signerCallTimeoutMs = Math.min(
81
+ config.signerCallTimeoutMs ?? DEFAULT_SIGNER_CALL_TIMEOUT_MS,
82
+ maxStuckDutiesAgeMs / 2,
83
+ );
55
84
 
56
85
  if (!config.nodeId || config.nodeId === '') {
57
86
  throw new Error('NODE_ID is required for high-availability setups');
58
87
  }
59
- this.slashingProtection = new SlashingProtectionService(db, config);
88
+ this.rollupAddress = config.rollupAddress;
89
+ this.slashingProtection = new SlashingProtectionService(db, config, {
90
+ metrics: deps.metrics,
91
+ dateProvider: deps.dateProvider,
92
+ });
93
+
60
94
  this.log.info('Validator HA Signer initialized with slashing protection', {
61
95
  nodeId: config.nodeId,
96
+ rollupAddress: this.rollupAddress.toString(),
97
+ signerCallTimeoutMs: this.signerCallTimeoutMs,
62
98
  });
63
99
  }
64
100
 
@@ -85,9 +121,13 @@ export class ValidatorHASigner {
85
121
  context: HAProtectedSigningContext,
86
122
  signFn: (messageHash: Buffer32) => Promise<Signature>,
87
123
  ): Promise<Signature> {
124
+ const startTime = this.dateProvider.now();
125
+ const dutyType = context.dutyType;
126
+
88
127
  let dutyIdentifier: DutyIdentifier;
89
128
  if (context.dutyType === DutyType.BLOCK_PROPOSAL) {
90
129
  dutyIdentifier = {
130
+ rollupAddress: this.rollupAddress,
91
131
  validatorAddress,
92
132
  slot: context.slot,
93
133
  blockIndexWithinCheckpoint: context.blockIndexWithinCheckpoint,
@@ -95,6 +135,7 @@ export class ValidatorHASigner {
95
135
  };
96
136
  } else {
97
137
  dutyIdentifier = {
138
+ rollupAddress: this.rollupAddress,
98
139
  validatorAddress,
99
140
  slot: context.slot,
100
141
  dutyType: context.dutyType,
@@ -102,31 +143,56 @@ export class ValidatorHASigner {
102
143
  }
103
144
 
104
145
  // Acquire lock and get the token for ownership verification
146
+ // DutyAlreadySignedError and SlashingProtectionError may be thrown here and are recorded in the service
105
147
  const blockNumber = getBlockNumberFromSigningContext(context);
148
+ const checkpointNumber = getCheckpointNumberFromSigningContext(context);
106
149
  const lockToken = await this.slashingProtection.checkAndRecord({
107
150
  ...dutyIdentifier,
108
151
  blockNumber,
152
+ checkpointNumber,
109
153
  messageHash: messageHash.toString(),
110
154
  nodeId: this.config.nodeId,
111
155
  });
112
156
 
113
- // Perform signing
157
+ // Perform signing under a hard timeout. If the signer hangs, executeTimeout aborts and rejects;
158
+ // the orphaned signFn promise resolving later is discarded (never broadcast). A timeout takes the
159
+ // same failure path as any signing error: release the lock so the duty can be retried safely.
114
160
  let signature: Signature;
115
161
  try {
116
- signature = await signFn(messageHash);
162
+ signature = await executeTimeout(
163
+ () => signFn(messageHash),
164
+ this.signerCallTimeoutMs,
165
+ () =>
166
+ new Error(
167
+ `Signing operation for ${dutyType} at slot ${context.slot} timed out after ` +
168
+ `${this.signerCallTimeoutMs}ms`,
169
+ ),
170
+ );
117
171
  } catch (error: any) {
118
172
  // Delete duty to allow retry (only succeeds if we own the lock)
119
173
  await this.slashingProtection.deleteDuty({ ...dutyIdentifier, lockToken });
174
+ this.metrics.recordSigningError(dutyType);
120
175
  throw error;
121
176
  }
122
177
 
123
- // Record success (only succeeds if we own the lock)
124
- await this.slashingProtection.recordSuccess({
178
+ // Record success (only succeeds if we still own the lock).
179
+ // A false result means our SIGNING row is gone or no longer ours (e.g. deleted by stuck-duty
180
+ // cleanup while signing was slow). We must not broadcast this signature: without a protection
181
+ // record, a later attempt for the same duty with different data would sign freely (slashable).
182
+ // Do not delete the duty here - we no longer own it, and another node may legitimately hold it.
183
+ const recorded = await this.slashingProtection.recordSuccess({
125
184
  ...dutyIdentifier,
126
185
  signature,
127
186
  nodeId: this.config.nodeId,
128
187
  lockToken,
129
188
  });
189
+ if (!recorded) {
190
+ this.metrics.recordSigningError(dutyType);
191
+ throw new SigningLockLostError(context.slot, dutyType, this.config.nodeId);
192
+ }
193
+
194
+ const duration = this.dateProvider.now() - startTime;
195
+ this.metrics.recordSigningSuccess(dutyType, duration);
130
196
 
131
197
  return signature;
132
198
  }
@@ -142,8 +208,8 @@ export class ValidatorHASigner {
142
208
  * Start the HA signer background tasks (cleanup of stuck duties).
143
209
  * Should be called after construction and before signing operations.
144
210
  */
145
- start() {
146
- this.slashingProtection.start();
211
+ async start() {
212
+ await this.slashingProtection.start();
147
213
  }
148
214
 
149
215
  /**