@aztec/validator-ha-signer 0.0.1-commit.a89ec08 → 0.0.1-commit.aa0c64f

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 (62) hide show
  1. package/README.md +2 -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 +4 -2
  15. package/dest/db/postgres.d.ts.map +1 -1
  16. package/dest/db/postgres.js +15 -13
  17. package/dest/db/schema.d.ts +6 -6
  18. package/dest/db/schema.d.ts.map +1 -1
  19. package/dest/db/schema.js +9 -4
  20. package/dest/db/types.d.ts +46 -21
  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 +28 -8
  27. package/dest/factory.d.ts.map +1 -1
  28. package/dest/factory.js +93 -22
  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 +15 -4
  33. package/dest/slashing_protection_service.d.ts.map +1 -1
  34. package/dest/slashing_protection_service.js +26 -12
  35. package/dest/types.d.ts +18 -70
  36. package/dest/types.d.ts.map +1 -1
  37. package/dest/types.js +4 -20
  38. package/dest/validator_ha_signer.d.ts +13 -4
  39. package/dest/validator_ha_signer.d.ts.map +1 -1
  40. package/dest/validator_ha_signer.js +48 -15
  41. package/package.json +11 -7
  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 +15 -11
  47. package/src/db/schema.ts +9 -4
  48. package/src/db/types.ts +66 -19
  49. package/src/errors.ts +21 -0
  50. package/src/factory.ts +123 -21
  51. package/src/metrics.ts +138 -0
  52. package/src/slashing_protection_service.ts +39 -13
  53. package/src/types.ts +38 -104
  54. package/src/validator_ha_signer.ts +78 -17
  55. package/dest/config.d.ts +0 -101
  56. package/dest/config.d.ts.map +0 -1
  57. package/dest/config.js +0 -92
  58. package/dest/db/in_memory.d.ts +0 -20
  59. package/dest/db/in_memory.d.ts.map +0 -1
  60. package/dest/db/in_memory.js +0 -73
  61. package/src/config.ts +0 -149
  62. package/src/db/in_memory.ts +0 -107
package/src/db/types.ts CHANGED
@@ -1,6 +1,7 @@
1
- import type { BlockNumber, CheckpointNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
2
- import type { EthAddress } from '@aztec/foundation/eth-address';
1
+ import { BlockNumber, CheckpointNumber, type IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
3
  import type { Signature } from '@aztec/foundation/eth-signature';
4
+ import { DutyType } from '@aztec/stdlib/ha-signing';
4
5
 
5
6
  /**
6
7
  * Row type from PostgreSQL query
@@ -10,6 +11,7 @@ export interface DutyRow {
10
11
  validator_address: string;
11
12
  slot: string;
12
13
  block_number: string;
14
+ checkpoint_number: string;
13
15
  block_index_within_checkpoint: number;
14
16
  duty_type: DutyType;
15
17
  status: DutyStatus;
@@ -23,24 +25,35 @@ export interface DutyRow {
23
25
  }
24
26
 
25
27
  /**
26
- * Row type from INSERT_OR_GET_DUTY query (includes is_new flag)
28
+ * Plain-primitive representation of a duty record suitable for serialization
29
+ * (e.g. msgpackr for LMDB). All domain types are stored as their string/number
30
+ * equivalents. Timestamps are Unix milliseconds.
27
31
  */
28
- export interface InsertOrGetRow extends DutyRow {
29
- is_new: boolean;
32
+ export interface StoredDutyRecord {
33
+ rollupAddress: string;
34
+ validatorAddress: string;
35
+ slot: string;
36
+ blockNumber: string;
37
+ checkpointNumber: string;
38
+ blockIndexWithinCheckpoint: number;
39
+ dutyType: DutyType;
40
+ status: DutyStatus;
41
+ messageHash: string;
42
+ signature?: string;
43
+ nodeId: string;
44
+ lockToken: string;
45
+ /** Unix timestamp in milliseconds when signing started */
46
+ startedAtMs: number;
47
+ /** Unix timestamp in milliseconds when signing completed */
48
+ completedAtMs?: number;
49
+ errorMessage?: string;
30
50
  }
31
51
 
32
52
  /**
33
- * Type of validator duty being performed
53
+ * Row type from INSERT_OR_GET_DUTY query (includes is_new flag)
34
54
  */
35
- export enum DutyType {
36
- BLOCK_PROPOSAL = 'BLOCK_PROPOSAL',
37
- CHECKPOINT_PROPOSAL = 'CHECKPOINT_PROPOSAL',
38
- ATTESTATION = 'ATTESTATION',
39
- ATTESTATIONS_AND_SIGNERS = 'ATTESTATIONS_AND_SIGNERS',
40
- GOVERNANCE_VOTE = 'GOVERNANCE_VOTE',
41
- SLASHING_VOTE = 'SLASHING_VOTE',
42
- AUTH_REQUEST = 'AUTH_REQUEST',
43
- TXS = 'TXS',
55
+ export interface InsertOrGetRow extends DutyRow {
56
+ is_new: boolean;
44
57
  }
45
58
 
46
59
  /**
@@ -51,8 +64,12 @@ export enum DutyStatus {
51
64
  SIGNED = 'signed',
52
65
  }
53
66
 
67
+ // Re-export DutyType from stdlib
68
+ export { DutyType };
69
+
54
70
  /**
55
- * Record of a validator duty in the database
71
+ * Rich representation of a validator duty, with branded types and Date objects.
72
+ * This is the common output type returned by all SlashingProtectionDatabase implementations.
56
73
  */
57
74
  export interface ValidatorDutyRecord {
58
75
  /** Ethereum address of the rollup contract */
@@ -61,8 +78,10 @@ export interface ValidatorDutyRecord {
61
78
  validatorAddress: EthAddress;
62
79
  /** Slot number for this duty */
63
80
  slot: SlotNumber;
64
- /** Block number for this duty */
81
+ /** Block number for this duty (0 for non-block-proposal duties) */
65
82
  blockNumber: BlockNumber;
83
+ /** Checkpoint number for this duty (0 for attestation and vote duties) */
84
+ checkpointNumber: CheckpointNumber;
66
85
  /** Block index within checkpoint (0, 1, 2... for block proposals, -1 for other duty types) */
67
86
  blockIndexWithinCheckpoint: number;
68
87
  /** Type of duty being performed */
@@ -85,6 +104,32 @@ export interface ValidatorDutyRecord {
85
104
  errorMessage?: string;
86
105
  }
87
106
 
107
+ /**
108
+ * Convert a {@link StoredDutyRecord} (plain-primitive wire format) to a
109
+ * {@link ValidatorDutyRecord} (rich domain type).
110
+ *
111
+ * Shared by LMDB and any future non-Postgres backend implementations.
112
+ */
113
+ export function recordFromFields(stored: StoredDutyRecord): ValidatorDutyRecord {
114
+ return {
115
+ rollupAddress: EthAddress.fromString(stored.rollupAddress),
116
+ validatorAddress: EthAddress.fromString(stored.validatorAddress),
117
+ slot: SlotNumber.fromString(stored.slot),
118
+ blockNumber: BlockNumber.fromString(stored.blockNumber),
119
+ checkpointNumber: CheckpointNumber.fromString(stored.checkpointNumber),
120
+ blockIndexWithinCheckpoint: stored.blockIndexWithinCheckpoint,
121
+ dutyType: stored.dutyType,
122
+ status: stored.status,
123
+ messageHash: stored.messageHash,
124
+ signature: stored.signature,
125
+ nodeId: stored.nodeId,
126
+ lockToken: stored.lockToken,
127
+ startedAt: new Date(stored.startedAtMs),
128
+ completedAt: stored.completedAtMs !== undefined ? new Date(stored.completedAtMs) : undefined,
129
+ errorMessage: stored.errorMessage,
130
+ };
131
+ }
132
+
88
133
  /**
89
134
  * Duty identifier for block proposals.
90
135
  * blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
@@ -163,8 +208,10 @@ export function getBlockIndexFromDutyIdentifier(duty: DutyIdentifier): number {
163
208
  * Additional parameters for checking and recording a new duty
164
209
  */
165
210
  interface CheckAndRecordExtra {
166
- /** Block number for this duty */
167
- blockNumber: BlockNumber | CheckpointNumber;
211
+ /** Block number for this duty (0 for non-block-proposal duties) */
212
+ blockNumber: BlockNumber;
213
+ /** Checkpoint number for this duty (0 for attestation and vote duties) */
214
+ checkpointNumber: CheckpointNumber;
168
215
  /** The signing root (hash) for this duty */
169
216
  messageHash: string;
170
217
  /** Identifier for the node that acquired the lock */
package/src/errors.ts CHANGED
@@ -22,6 +22,27 @@ export class DutyAlreadySignedError extends Error {
22
22
  }
23
23
  }
24
24
 
25
+ /**
26
+ * Thrown when the slashing-protection record for an in-flight signing operation can no longer be
27
+ * updated because it is no longer owned by this node - for example, the stuck-duty cleanup loop
28
+ * deleted the SIGNING row while the remote signer was slow. The produced signature must be
29
+ * discarded rather than broadcast: with no protection record in place, a later attempt for the
30
+ * same duty with different data would sign freely, which is slashable equivocation.
31
+ */
32
+ export class SigningLockLostError extends Error {
33
+ constructor(
34
+ public readonly slot: SlotNumber,
35
+ public readonly dutyType: DutyType,
36
+ public readonly nodeId: string,
37
+ ) {
38
+ super(
39
+ `Slashing protection record for ${dutyType} at slot ${slot} was lost before signing completed ` +
40
+ `(node ${nodeId}); discarding signature`,
41
+ );
42
+ this.name = 'SigningLockLostError';
43
+ }
44
+ }
45
+
25
46
  /**
26
47
  * Thrown when attempting to sign data that conflicts with an already-signed duty.
27
48
  * This means the same validator tried to sign DIFFERENT data for the same slot.
package/src/factory.ts CHANGED
@@ -1,12 +1,18 @@
1
1
  /**
2
2
  * Factory functions for creating validator HA signers
3
3
  */
4
+ import { createLogger } from '@aztec/foundation/log';
5
+ import { DateProvider } from '@aztec/foundation/timer';
6
+ import { createStore } from '@aztec/kv-store/lmdb-v2';
7
+ import type { LocalSignerConfig, ValidatorHASignerConfig } from '@aztec/stdlib/ha-signing';
8
+ import { getTelemetryClient } from '@aztec/telemetry-client';
9
+
4
10
  import { Pool } from 'pg';
5
11
 
6
- import type { ValidatorHASignerConfig } from './config.js';
7
- import { InMemorySlashingProtectionDatabase } from './db/in_memory.js';
12
+ import { LmdbSlashingProtectionDatabase, migrateLmdbSlashingProtectionDatabase } from './db/lmdb.js';
8
13
  import { PostgresSlashingProtectionDatabase } from './db/postgres.js';
9
- import type { CreateHASignerDeps, SlashingProtectionDatabase } from './types.js';
14
+ import { HASignerMetrics } from './metrics.js';
15
+ import type { CreateHASignerDeps, CreateLocalSignerWithProtectionDeps, SlashingProtectionDatabase } from './types.js';
10
16
  import { ValidatorHASigner } from './validator_ha_signer.js';
11
17
 
12
18
  /**
@@ -24,10 +30,9 @@ import { ValidatorHASigner } from './validator_ha_signer.js';
24
30
  * ```typescript
25
31
  * const { signer, db } = await createHASigner({
26
32
  * databaseUrl: process.env.DATABASE_URL,
27
- * haSigningEnabled: true,
28
33
  * nodeId: 'validator-node-1',
29
34
  * pollingIntervalMs: 100,
30
- * signingTimeoutMs: 3000,
35
+ * peerSigningTimeoutMs: 3000,
31
36
  * });
32
37
  * signer.start(); // Start background cleanup
33
38
  *
@@ -53,14 +58,19 @@ export async function createHASigner(
53
58
  const { databaseUrl, poolMaxCount, poolMinCount, poolIdleTimeoutMs, poolConnectionTimeoutMs, ...signerConfig } =
54
59
  config;
55
60
 
56
- if (!databaseUrl) {
61
+ const databaseUrlValue = databaseUrl?.getValue();
62
+ if (!databaseUrlValue) {
57
63
  throw new Error('databaseUrl is required for createHASigner');
58
64
  }
65
+
66
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
67
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
68
+
59
69
  // Create connection pool (or use provided pool)
60
70
  let pool: Pool;
61
71
  if (!deps?.pool) {
62
72
  pool = new Pool({
63
- connectionString: databaseUrl,
73
+ connectionString: databaseUrlValue,
64
74
  max: poolMaxCount ?? 10,
65
75
  min: poolMinCount ?? 0,
66
76
  idleTimeoutMillis: poolIdleTimeoutMs ?? 10_000,
@@ -70,24 +80,120 @@ export async function createHASigner(
70
80
  pool = deps.pool;
71
81
  }
72
82
 
83
+ // pg re-emits idle-client errors (e.g. a Postgres restart severing an idle connection) on the
84
+ // pool. Without an 'error' listener, Node escalates these to an uncaughtException and crashes the
85
+ // process - taking down every HA replica sharing the DB at once. pg destroys and replaces the
86
+ // errored client itself, so logging is the only action needed. Log just message/code, never the
87
+ // raw error object (it can carry connection metadata).
88
+ const log = createLogger('validator-ha-signer:factory');
89
+ pool.on('error', (err: NodeJS.ErrnoException) => {
90
+ log.warn('Postgres pool error on idle client', { message: err.message, code: err.code });
91
+ });
92
+
73
93
  // Create database instance
74
94
  const db = new PostgresSlashingProtectionDatabase(pool);
75
95
 
76
96
  // Verify database schema is initialized and version matches
77
97
  await db.initialize();
78
98
 
99
+ // Create metrics
100
+ const metrics = new HASignerMetrics(telemetryClient, signerConfig.nodeId);
101
+
79
102
  // Create signer
80
- const signer = new ValidatorHASigner(db, { ...signerConfig, databaseUrl });
103
+ const signer = new ValidatorHASigner(db, signerConfig, { metrics, dateProvider });
104
+
105
+ return { signer, db };
106
+ }
107
+
108
+ /**
109
+ * Create a local (single-node) signing protection signer backed by LMDB.
110
+ *
111
+ * This provides double-signing protection for nodes that are NOT running in a
112
+ * high-availability (multi-node) setup. It prevents a proposer from sending two
113
+ * proposals for the same slot if the node crashes and restarts mid-proposal.
114
+ *
115
+ * `config.dataDirectory` is required so the protection database is persisted to disk and survives
116
+ * crashes/restarts. Booting without it throws, since an ephemeral store silently drops all
117
+ * double-signing protection across restarts. Set `config.allowEphemeralSigningProtection` to opt
118
+ * into the ephemeral store anyway (dev/test networks only) — a loud warning is logged in that case.
119
+ *
120
+ * @param config - Local signer config
121
+ * @param deps - Optional dependencies (telemetry, date provider).
122
+ * @returns An object containing the signer and database instances.
123
+ */
124
+ export async function createLocalSignerWithProtection(
125
+ config: LocalSignerConfig,
126
+ deps?: CreateLocalSignerWithProtectionDeps,
127
+ ): Promise<{
128
+ signer: ValidatorHASigner;
129
+ db: SlashingProtectionDatabase;
130
+ }> {
131
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
132
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
133
+
134
+ const log = createLogger('validator-ha-signer:factory');
135
+
136
+ if (!config.dataDirectory) {
137
+ if (!config.allowEphemeralSigningProtection) {
138
+ throw new Error(
139
+ 'Local signing protection requires a persistent data directory, but none was configured. ' +
140
+ 'Set DATA_DIRECTORY so double-signing protection survives restarts, or explicitly opt into an ' +
141
+ 'ephemeral store (dev/test only) with VALIDATOR_ALLOW_EPHEMERAL_SIGNING_PROTECTION=true.',
142
+ );
143
+ }
144
+ log.warn(
145
+ 'Local signing protection is running with an EPHEMERAL store: no data directory is configured. ' +
146
+ 'Double-signing protection will NOT survive a restart. This is unsafe for production validators.',
147
+ );
148
+ }
149
+
150
+ const kvStore = await createStore(
151
+ 'signing-protection',
152
+ LmdbSlashingProtectionDatabase.SCHEMA_VERSION,
153
+ {
154
+ dataDirectory: config.dataDirectory,
155
+ dataStoreMapSizeKb: config.signingProtectionMapSizeKb ?? config.dataStoreMapSizeKb,
156
+ rollupAddress: config.rollupAddress,
157
+ },
158
+ undefined,
159
+ {
160
+ onUpgrade: (dataDirectory, currentVersion, latestVersion) =>
161
+ migrateLmdbSlashingProtectionDatabase(
162
+ dataDirectory,
163
+ currentVersion,
164
+ latestVersion,
165
+ config.signingProtectionMapSizeKb ?? config.dataStoreMapSizeKb,
166
+ ),
167
+ schemaVersionMismatchPolicy: 'throw',
168
+ versionFileReadFailurePolicy: 'throw',
169
+ },
170
+ );
171
+
172
+ const db = new LmdbSlashingProtectionDatabase(kvStore, dateProvider);
173
+
174
+ const signerConfig = {
175
+ ...config,
176
+ nodeId: config.nodeId || 'local',
177
+ };
178
+
179
+ const metrics = new HASignerMetrics(telemetryClient, signerConfig.nodeId, 'LocalSigningProtectionMetrics');
180
+
181
+ const signer = new ValidatorHASigner(db, signerConfig, { metrics, dateProvider });
81
182
 
82
183
  return { signer, db };
83
184
  }
84
185
 
85
186
  /**
86
- * Create an in-memory SlashingProtectionDatabase that can be shared across
187
+ * Create an in-memory LMDB-backed SlashingProtectionDatabase that can be shared across
87
188
  * multiple validator nodes in the same process. Used for testing HA setups.
88
189
  */
89
- export function createSharedSlashingProtectionDb(): SlashingProtectionDatabase {
90
- return new InMemorySlashingProtectionDatabase();
190
+ export async function createSharedSlashingProtectionDb(
191
+ dateProvider: DateProvider = new DateProvider(),
192
+ ): Promise<SlashingProtectionDatabase> {
193
+ const kvStore = await createStore('shared-signing-protection', LmdbSlashingProtectionDatabase.SCHEMA_VERSION, {
194
+ dataStoreMapSizeKb: 1024 * 1024,
195
+ });
196
+ return new LmdbSlashingProtectionDatabase(kvStore, dateProvider);
91
197
  }
92
198
 
93
199
  /**
@@ -98,17 +204,13 @@ export function createSignerFromSharedDb(
98
204
  db: SlashingProtectionDatabase,
99
205
  config: Pick<
100
206
  ValidatorHASignerConfig,
101
- 'nodeId' | 'pollingIntervalMs' | 'signingTimeoutMs' | 'maxStuckDutiesAgeMs' | 'l1Contracts'
207
+ 'nodeId' | 'pollingIntervalMs' | 'peerSigningTimeoutMs' | 'maxStuckDutiesAgeMs' | 'rollupAddress'
102
208
  >,
209
+ deps?: CreateLocalSignerWithProtectionDeps,
103
210
  ): { signer: ValidatorHASigner; db: SlashingProtectionDatabase } {
104
- const signerConfig: ValidatorHASignerConfig = {
105
- haSigningEnabled: true,
106
- l1Contracts: config.l1Contracts,
107
- nodeId: config.nodeId || `shared-${Date.now()}`,
108
- pollingIntervalMs: config.pollingIntervalMs ?? 100,
109
- signingTimeoutMs: config.signingTimeoutMs ?? 3000,
110
- maxStuckDutiesAgeMs: config.maxStuckDutiesAgeMs,
111
- };
112
- const signer = new ValidatorHASigner(db, signerConfig);
211
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
212
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
213
+ const metrics = new HASignerMetrics(telemetryClient, config.nodeId, 'SharedSigningProtectionMetrics');
214
+ const signer = new ValidatorHASigner(db, config, { metrics, dateProvider });
113
215
  return { signer, db };
114
216
  }
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,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,23 +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;
43
57
  private lastOldDutiesCleanupAtMs?: number;
44
58
 
45
59
  constructor(
46
60
  private readonly db: SlashingProtectionDatabase,
47
- private readonly config: ValidatorHASignerConfig,
61
+ private readonly config: BaseSignerConfig,
62
+ deps: SlashingProtectionServiceDeps,
48
63
  ) {
49
64
  this.log = createLogger('slashing-protection');
50
65
  this.pollingIntervalMs = config.pollingIntervalMs;
51
- this.signingTimeoutMs = config.signingTimeoutMs;
52
- // Default to 144s (2x 72s Aztec slot duration) if not explicitly configured
53
- this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? 144_000;
66
+ this.peerSigningTimeoutMs = config.peerSigningTimeoutMs;
67
+ this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? DEFAULT_MAX_STUCK_DUTIES_AGE_MS;
54
68
 
55
69
  this.cleanupRunningPromise = new RunningPromise(this.cleanup.bind(this), this.log, this.maxStuckDutiesAgeMs);
70
+ this.metrics = deps.metrics;
71
+ this.dateProvider = deps.dateProvider;
56
72
  }
57
73
 
58
74
  /**
@@ -72,7 +88,7 @@ export class SlashingProtectionService {
72
88
  */
73
89
  async checkAndRecord(params: CheckAndRecordParams): Promise<string> {
74
90
  const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
75
- const startTime = Date.now();
91
+ const startTime = this.dateProvider.now();
76
92
 
77
93
  this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
78
94
  validatorAddress: validatorAddress.toString(),
@@ -89,6 +105,7 @@ export class SlashingProtectionService {
89
105
  validatorAddress: validatorAddress.toString(),
90
106
  nodeId,
91
107
  });
108
+ this.metrics.recordLockAcquire(true);
92
109
  return record.lockToken;
93
110
  }
94
111
 
@@ -103,6 +120,7 @@ export class SlashingProtectionService {
103
120
  existingNodeId: record.nodeId,
104
121
  attemptingNodeId: nodeId,
105
122
  });
123
+ this.metrics.recordSlashingProtection(dutyType);
106
124
  throw new SlashingProtectionError(
107
125
  slot,
108
126
  dutyType,
@@ -112,15 +130,17 @@ export class SlashingProtectionService {
112
130
  record.nodeId,
113
131
  );
114
132
  }
133
+ this.metrics.recordDutyAlreadySigned(dutyType);
115
134
  throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
116
135
  } else if (record.status === DutyStatus.SIGNING) {
117
136
  // Another node is currently signing - check for timeout
118
- if (Date.now() - startTime > this.signingTimeoutMs) {
137
+ if (this.dateProvider.now() - startTime > this.peerSigningTimeoutMs) {
119
138
  this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
120
139
  validatorAddress: validatorAddress.toString(),
121
- timeoutMs: this.signingTimeoutMs,
140
+ timeoutMs: this.peerSigningTimeoutMs,
122
141
  signingNodeId: record.nodeId,
123
142
  });
143
+ this.metrics.recordDutyAlreadySigned(dutyType);
124
144
  throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
125
145
  }
126
146
 
@@ -223,11 +243,12 @@ export class SlashingProtectionService {
223
243
  */
224
244
  async start() {
225
245
  // One-time cleanup at startup: remove duties from previous rollup versions
226
- const numOutdatedRollupDuties = await this.db.cleanupOutdatedRollupDuties(this.config.l1Contracts.rollupAddress);
246
+ const numOutdatedRollupDuties = await this.db.cleanupOutdatedRollupDuties(this.config.rollupAddress);
227
247
  if (numOutdatedRollupDuties > 0) {
228
248
  this.log.info(`Cleaned up ${numOutdatedRollupDuties} duties with outdated rollup address at startup`, {
229
- currentRollupAddress: this.config.l1Contracts.rollupAddress.toString(),
249
+ currentRollupAddress: this.config.rollupAddress.toString(),
230
250
  });
251
+ this.metrics.recordCleanup('outdated_rollup', numOutdatedRollupDuties);
231
252
  }
232
253
 
233
254
  this.cleanupRunningPromise.start();
@@ -256,20 +277,24 @@ export class SlashingProtectionService {
256
277
  * Runs in the background via RunningPromise.
257
278
  */
258
279
  private async cleanup() {
259
- // 1. Clean up stuck duties (our own node's duties that got stuck in 'signing' status)
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.
260
284
  const numStuckDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
261
285
  if (numStuckDuties > 0) {
262
286
  this.log.verbose(`Cleaned up ${numStuckDuties} stuck duties`, {
263
287
  nodeId: this.config.nodeId,
264
288
  maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs,
265
289
  });
290
+ this.metrics.recordCleanup('stuck', numStuckDuties);
266
291
  }
267
292
 
268
293
  // 2. Clean up old signed duties if configured
269
294
  // we shouldn't run this as often as stuck duty cleanup.
270
295
  if (this.config.cleanupOldDutiesAfterHours !== undefined) {
271
296
  const maxAgeMs = this.config.cleanupOldDutiesAfterHours * 60 * 60 * 1000;
272
- const nowMs = Date.now();
297
+ const nowMs = this.dateProvider.now();
273
298
  const shouldRun =
274
299
  this.lastOldDutiesCleanupAtMs === undefined || nowMs - this.lastOldDutiesCleanupAtMs >= maxAgeMs;
275
300
  if (shouldRun) {
@@ -280,6 +305,7 @@ export class SlashingProtectionService {
280
305
  cleanupOldDutiesAfterHours: this.config.cleanupOldDutiesAfterHours,
281
306
  maxAgeMs,
282
307
  });
308
+ this.metrics.recordCleanup('old', numOldDuties);
283
309
  }
284
310
  }
285
311
  }