@aztec/validator-ha-signer 0.0.1-commit.ee80a48 → 0.0.1-commit.f103f88

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 (54) 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 +189 -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 +18 -2
  15. package/dest/db/postgres.d.ts.map +1 -1
  16. package/dest/db/postgres.js +39 -16
  17. package/dest/db/schema.d.ts +16 -9
  18. package/dest/db/schema.d.ts.map +1 -1
  19. package/dest/db/schema.js +23 -9
  20. package/dest/db/types.d.ts +47 -22
  21. package/dest/db/types.d.ts.map +1 -1
  22. package/dest/db/types.js +31 -15
  23. package/dest/factory.d.ts +39 -4
  24. package/dest/factory.d.ts.map +1 -1
  25. package/dest/factory.js +75 -5
  26. package/dest/metrics.d.ts +51 -0
  27. package/dest/metrics.d.ts.map +1 -0
  28. package/dest/metrics.js +103 -0
  29. package/dest/slashing_protection_service.d.ts +19 -6
  30. package/dest/slashing_protection_service.d.ts.map +1 -1
  31. package/dest/slashing_protection_service.js +53 -13
  32. package/dest/types.d.ts +31 -70
  33. package/dest/types.d.ts.map +1 -1
  34. package/dest/types.js +4 -20
  35. package/dest/validator_ha_signer.d.ts +13 -5
  36. package/dest/validator_ha_signer.d.ts.map +1 -1
  37. package/dest/validator_ha_signer.js +20 -10
  38. package/package.json +10 -6
  39. package/src/db/index.ts +1 -0
  40. package/src/db/lmdb.ts +265 -0
  41. package/src/db/migrations/1_initial-schema.ts +35 -4
  42. package/src/db/migrations/2_add-checkpoint-number.ts +19 -0
  43. package/src/db/postgres.ts +40 -13
  44. package/src/db/schema.ts +25 -9
  45. package/src/db/types.ts +67 -20
  46. package/src/factory.ts +93 -4
  47. package/src/metrics.ts +138 -0
  48. package/src/slashing_protection_service.ts +68 -18
  49. package/src/types.ts +53 -104
  50. package/src/validator_ha_signer.ts +38 -14
  51. package/dest/config.d.ts +0 -96
  52. package/dest/config.d.ts.map +0 -1
  53. package/dest/config.js +0 -86
  54. package/src/config.ts +0 -141
@@ -5,9 +5,8 @@
5
5
  * This ensures that even with multiple validator nodes running, only one
6
6
  * node will sign for a given duty (slot + duty type).
7
7
  */ import { createLogger } from '@aztec/foundation/log';
8
- import { DutyType } from './db/types.js';
8
+ import { DutyType, getBlockNumberFromSigningContext, getCheckpointNumberFromSigningContext } from '@aztec/stdlib/ha-signing';
9
9
  import { SlashingProtectionService } from './slashing_protection_service.js';
10
- import { getBlockNumberFromSigningContext } from './types.js';
11
10
  /**
12
11
  * Validator High Availability Signer
13
12
  *
@@ -31,18 +30,21 @@ import { getBlockNumberFromSigningContext } from './types.js';
31
30
  log;
32
31
  slashingProtection;
33
32
  rollupAddress;
34
- constructor(db, config){
33
+ dateProvider;
34
+ metrics;
35
+ constructor(db, config, deps){
35
36
  this.config = config;
36
37
  this.log = createLogger('validator-ha-signer');
37
- if (!config.haSigningEnabled) {
38
- // this shouldn't happen, the validator should use different signer for non-HA setups
39
- throw new Error('Validator HA Signer is not enabled in config');
40
- }
38
+ this.metrics = deps.metrics;
39
+ this.dateProvider = deps.dateProvider;
41
40
  if (!config.nodeId || config.nodeId === '') {
42
41
  throw new Error('NODE_ID is required for high-availability setups');
43
42
  }
44
43
  this.rollupAddress = config.l1Contracts.rollupAddress;
45
- this.slashingProtection = new SlashingProtectionService(db, config);
44
+ this.slashingProtection = new SlashingProtectionService(db, config, {
45
+ metrics: deps.metrics,
46
+ dateProvider: deps.dateProvider
47
+ });
46
48
  this.log.info('Validator HA Signer initialized with slashing protection', {
47
49
  nodeId: config.nodeId,
48
50
  rollupAddress: this.rollupAddress.toString()
@@ -65,6 +67,8 @@ import { getBlockNumberFromSigningContext } from './types.js';
65
67
  * @throws DutyAlreadySignedError if the duty was already signed (expected in HA)
66
68
  * @throws SlashingProtectionError if attempting to sign different data for same slot (expected in HA)
67
69
  */ async signWithProtection(validatorAddress, messageHash, context, signFn) {
70
+ const startTime = this.dateProvider.now();
71
+ const dutyType = context.dutyType;
68
72
  let dutyIdentifier;
69
73
  if (context.dutyType === DutyType.BLOCK_PROPOSAL) {
70
74
  dutyIdentifier = {
@@ -83,10 +87,13 @@ import { getBlockNumberFromSigningContext } from './types.js';
83
87
  };
84
88
  }
85
89
  // Acquire lock and get the token for ownership verification
90
+ // DutyAlreadySignedError and SlashingProtectionError may be thrown here and are recorded in the service
86
91
  const blockNumber = getBlockNumberFromSigningContext(context);
92
+ const checkpointNumber = getCheckpointNumberFromSigningContext(context);
87
93
  const lockToken = await this.slashingProtection.checkAndRecord({
88
94
  ...dutyIdentifier,
89
95
  blockNumber,
96
+ checkpointNumber,
90
97
  messageHash: messageHash.toString(),
91
98
  nodeId: this.config.nodeId
92
99
  });
@@ -100,6 +107,7 @@ import { getBlockNumberFromSigningContext } from './types.js';
100
107
  ...dutyIdentifier,
101
108
  lockToken
102
109
  });
110
+ this.metrics.recordSigningError(dutyType);
103
111
  throw error;
104
112
  }
105
113
  // Record success (only succeeds if we own the lock)
@@ -109,6 +117,8 @@ import { getBlockNumberFromSigningContext } from './types.js';
109
117
  nodeId: this.config.nodeId,
110
118
  lockToken
111
119
  });
120
+ const duration = this.dateProvider.now() - startTime;
121
+ this.metrics.recordSigningSuccess(dutyType, duration);
112
122
  return signature;
113
123
  }
114
124
  /**
@@ -119,8 +129,8 @@ import { getBlockNumberFromSigningContext } from './types.js';
119
129
  /**
120
130
  * Start the HA signer background tasks (cleanup of stuck duties).
121
131
  * Should be called after construction and before signing operations.
122
- */ start() {
123
- this.slashingProtection.start();
132
+ */ async start() {
133
+ await this.slashingProtection.start();
124
134
  }
125
135
  /**
126
136
  * Stop the HA signer background tasks and close database connection.
package/package.json CHANGED
@@ -1,24 +1,25 @@
1
1
  {
2
2
  "name": "@aztec/validator-ha-signer",
3
- "version": "0.0.1-commit.ee80a48",
3
+ "version": "0.0.1-commit.f103f88",
4
4
  "type": "module",
5
5
  "exports": {
6
- "./config": "./dest/config.js",
7
6
  "./db": "./dest/db/index.js",
8
7
  "./errors": "./dest/errors.js",
9
8
  "./factory": "./dest/factory.js",
9
+ "./metrics": "./dest/metrics.js",
10
10
  "./migrations": "./dest/migrations.js",
11
11
  "./slashing-protection-service": "./dest/slashing_protection_service.js",
12
12
  "./types": "./dest/types.js",
13
13
  "./validator-ha-signer": "./dest/validator_ha_signer.js",
14
- "./test": "./dest/test/pglite_pool.js"
14
+ "./test": "./dest/test/pglite_pool.js",
15
+ "./db/lmdb": "./dest/db/lmdb.js"
15
16
  },
16
17
  "typedocOptions": {
17
18
  "entryPoints": [
18
- "./src/config.ts",
19
19
  "./src/db/index.ts",
20
20
  "./src/errors.ts",
21
21
  "./src/factory.ts",
22
+ "./src/metrics.ts",
22
23
  "./src/migrations.ts",
23
24
  "./src/slashing_protection_service.ts",
24
25
  "./src/types.ts",
@@ -74,8 +75,11 @@
74
75
  ]
75
76
  },
76
77
  "dependencies": {
77
- "@aztec/ethereum": "0.0.1-commit.ee80a48",
78
- "@aztec/foundation": "0.0.1-commit.ee80a48",
78
+ "@aztec/ethereum": "0.0.1-commit.f103f88",
79
+ "@aztec/foundation": "0.0.1-commit.f103f88",
80
+ "@aztec/kv-store": "0.0.1-commit.f103f88",
81
+ "@aztec/stdlib": "0.0.1-commit.f103f88",
82
+ "@aztec/telemetry-client": "0.0.1-commit.f103f88",
79
83
  "node-pg-migrate": "^8.0.4",
80
84
  "pg": "^8.11.3",
81
85
  "tslib": "^2.4.0",
package/src/db/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from './types.js';
2
2
  export * from './schema.js';
3
3
  export * from './postgres.js';
4
+ export * from './lmdb.js';
package/src/db/lmdb.ts ADDED
@@ -0,0 +1,265 @@
1
+ /**
2
+ * LMDB implementation of SlashingProtectionDatabase
3
+ *
4
+ * Provides local (single-node) double-signing protection using LMDB as the backend.
5
+ * Suitable for nodes that do NOT run in a high-availability multi-node setup.
6
+ *
7
+ * The LMDB store is single-writer, making setIfNotExists inherently atomic.
8
+ * This means we get crash-restart protection without needing an external database.
9
+ */
10
+ import { SlotNumber } from '@aztec/foundation/branded-types';
11
+ import { randomBytes } from '@aztec/foundation/crypto/random';
12
+ import { EthAddress } from '@aztec/foundation/eth-address';
13
+ import { type Logger, createLogger } from '@aztec/foundation/log';
14
+ import type { DateProvider } from '@aztec/foundation/timer';
15
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
16
+
17
+ import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
18
+ import {
19
+ type CheckAndRecordParams,
20
+ DutyStatus,
21
+ DutyType,
22
+ type StoredDutyRecord,
23
+ getBlockIndexFromDutyIdentifier,
24
+ recordFromFields,
25
+ } from './types.js';
26
+
27
+ function dutyKey(
28
+ rollupAddress: string,
29
+ validatorAddress: string,
30
+ slot: string,
31
+ dutyType: string,
32
+ blockIndexWithinCheckpoint: number,
33
+ ): string {
34
+ return `${rollupAddress}:${validatorAddress}:${slot}:${dutyType}:${blockIndexWithinCheckpoint}`;
35
+ }
36
+
37
+ /**
38
+ * LMDB-backed implementation of SlashingProtectionDatabase.
39
+ *
40
+ * Provides single-node double-signing protection that survives crashes and restarts.
41
+ * Does not provide cross-node coordination (that requires the PostgreSQL implementation).
42
+ */
43
+ export class LmdbSlashingProtectionDatabase implements SlashingProtectionDatabase {
44
+ public static readonly SCHEMA_VERSION = 2;
45
+
46
+ private readonly duties: AztecAsyncMap<string, StoredDutyRecord>;
47
+ private readonly log: Logger;
48
+
49
+ constructor(
50
+ private readonly store: AztecAsyncKVStore,
51
+ private readonly dateProvider: DateProvider,
52
+ ) {
53
+ this.log = createLogger('slashing-protection:lmdb');
54
+ this.duties = store.openMap<string, StoredDutyRecord>('signing-protection-duties');
55
+ }
56
+
57
+ /**
58
+ * Atomically try to insert a new duty record, or get the existing one if present.
59
+ *
60
+ * LMDB is single-writer so the read-then-write inside transactionAsync is naturally atomic.
61
+ */
62
+ public async tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult> {
63
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
64
+ const key = dutyKey(
65
+ params.rollupAddress.toString(),
66
+ params.validatorAddress.toString(),
67
+ params.slot.toString(),
68
+ params.dutyType,
69
+ blockIndexWithinCheckpoint,
70
+ );
71
+
72
+ const lockToken = randomBytes(16).toString('hex');
73
+ const now = this.dateProvider.now();
74
+
75
+ const result = await this.store.transactionAsync(async () => {
76
+ const existing = await this.duties.getAsync(key);
77
+ if (existing) {
78
+ return { isNew: false as const, record: { ...existing, lockToken: '' } };
79
+ }
80
+
81
+ const newRecord: StoredDutyRecord = {
82
+ rollupAddress: params.rollupAddress.toString(),
83
+ validatorAddress: params.validatorAddress.toString(),
84
+ slot: params.slot.toString(),
85
+ blockNumber: params.blockNumber.toString(),
86
+ checkpointNumber: params.checkpointNumber.toString(),
87
+ blockIndexWithinCheckpoint,
88
+ dutyType: params.dutyType,
89
+ status: DutyStatus.SIGNING,
90
+ messageHash: params.messageHash,
91
+ nodeId: params.nodeId,
92
+ lockToken,
93
+ startedAtMs: now,
94
+ };
95
+ await this.duties.set(key, newRecord);
96
+ return { isNew: true as const, record: newRecord };
97
+ });
98
+
99
+ if (result.isNew) {
100
+ this.log.debug(`Acquired lock for duty ${params.dutyType} at slot ${params.slot}`, {
101
+ validatorAddress: params.validatorAddress.toString(),
102
+ nodeId: params.nodeId,
103
+ });
104
+ }
105
+
106
+ return { isNew: result.isNew, record: recordFromFields(result.record) };
107
+ }
108
+
109
+ /**
110
+ * Update a duty to 'signed' status with the signature.
111
+ * Only succeeds if the lockToken matches.
112
+ */
113
+ public updateDutySigned(
114
+ rollupAddress: EthAddress,
115
+ validatorAddress: EthAddress,
116
+ slot: SlotNumber,
117
+ dutyType: DutyType,
118
+ signature: string,
119
+ lockToken: string,
120
+ blockIndexWithinCheckpoint: number,
121
+ ): Promise<boolean> {
122
+ const key = dutyKey(
123
+ rollupAddress.toString(),
124
+ validatorAddress.toString(),
125
+ slot.toString(),
126
+ dutyType,
127
+ blockIndexWithinCheckpoint,
128
+ );
129
+
130
+ return this.store.transactionAsync(async () => {
131
+ const existing = await this.duties.getAsync(key);
132
+ if (!existing) {
133
+ this.log.warn('Failed to update duty to signed: duty not found', {
134
+ rollupAddress: rollupAddress.toString(),
135
+ validatorAddress: validatorAddress.toString(),
136
+ slot: slot.toString(),
137
+ dutyType,
138
+ blockIndexWithinCheckpoint,
139
+ });
140
+ return false;
141
+ }
142
+
143
+ if (existing.lockToken !== lockToken) {
144
+ this.log.warn('Failed to update duty to signed: invalid token', {
145
+ rollupAddress: rollupAddress.toString(),
146
+ validatorAddress: validatorAddress.toString(),
147
+ slot: slot.toString(),
148
+ dutyType,
149
+ blockIndexWithinCheckpoint,
150
+ });
151
+ return false;
152
+ }
153
+
154
+ await this.duties.set(key, {
155
+ ...existing,
156
+ status: DutyStatus.SIGNED,
157
+ signature,
158
+ completedAtMs: this.dateProvider.now(),
159
+ });
160
+
161
+ return true;
162
+ });
163
+ }
164
+
165
+ /**
166
+ * Delete a duty record.
167
+ * Only succeeds if the lockToken matches.
168
+ */
169
+ public deleteDuty(
170
+ rollupAddress: EthAddress,
171
+ validatorAddress: EthAddress,
172
+ slot: SlotNumber,
173
+ dutyType: DutyType,
174
+ lockToken: string,
175
+ blockIndexWithinCheckpoint: number,
176
+ ): Promise<boolean> {
177
+ const key = dutyKey(
178
+ rollupAddress.toString(),
179
+ validatorAddress.toString(),
180
+ slot.toString(),
181
+ dutyType,
182
+ blockIndexWithinCheckpoint,
183
+ );
184
+
185
+ return this.store.transactionAsync(async () => {
186
+ const existing = await this.duties.getAsync(key);
187
+ if (!existing || existing.lockToken !== lockToken) {
188
+ this.log.warn('Failed to delete duty: invalid token or duty not found', {
189
+ rollupAddress: rollupAddress.toString(),
190
+ validatorAddress: validatorAddress.toString(),
191
+ slot: slot.toString(),
192
+ dutyType,
193
+ blockIndexWithinCheckpoint,
194
+ });
195
+ return false;
196
+ }
197
+
198
+ await this.duties.delete(key);
199
+ return true;
200
+ });
201
+ }
202
+
203
+ /**
204
+ * Cleanup own stuck duties (SIGNING status older than maxAgeMs).
205
+ */
206
+ public cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
207
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
208
+
209
+ return this.store.transactionAsync(async () => {
210
+ const keysToDelete: string[] = [];
211
+ for await (const [key, record] of this.duties.entriesAsync()) {
212
+ if (record.nodeId === nodeId && record.status === DutyStatus.SIGNING && record.startedAtMs < cutoffMs) {
213
+ keysToDelete.push(key);
214
+ }
215
+ }
216
+ for (const key of keysToDelete) {
217
+ await this.duties.delete(key);
218
+ }
219
+ return keysToDelete.length;
220
+ });
221
+ }
222
+
223
+ /**
224
+ * Cleanup duties with outdated rollup address.
225
+ *
226
+ * This is always a no-op for the LMDB implementation: the underlying store is created via
227
+ * DatabaseVersionManager (in factory.ts), which already resets the entire data directory at
228
+ * startup whenever the rollup address changes.
229
+ */
230
+ public cleanupOutdatedRollupDuties(_currentRollupAddress: EthAddress): Promise<number> {
231
+ return Promise.resolve(0);
232
+ }
233
+
234
+ /**
235
+ * Cleanup old signed duties older than maxAgeMs.
236
+ */
237
+ public cleanupOldDuties(maxAgeMs: number): Promise<number> {
238
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
239
+
240
+ return this.store.transactionAsync(async () => {
241
+ const keysToDelete: string[] = [];
242
+ for await (const [key, record] of this.duties.entriesAsync()) {
243
+ if (
244
+ record.status === DutyStatus.SIGNED &&
245
+ record.completedAtMs !== undefined &&
246
+ record.completedAtMs < cutoffMs
247
+ ) {
248
+ keysToDelete.push(key);
249
+ }
250
+ }
251
+ for (const key of keysToDelete) {
252
+ await this.duties.delete(key);
253
+ }
254
+ return keysToDelete.length;
255
+ });
256
+ }
257
+
258
+ /**
259
+ * Close the underlying LMDB store.
260
+ */
261
+ public async close(): Promise<void> {
262
+ await this.store.close();
263
+ this.log.debug('LMDB slashing protection database closed');
264
+ }
265
+ }
@@ -1,21 +1,52 @@
1
1
  /**
2
2
  * Initial schema for validator HA slashing protection
3
3
  *
4
- * This migration imports SQL from the schema.ts file to ensure a single source of truth.
4
+ * Note: this migration contains a fixed snapshot of the schema at the time it was created.
5
+ * It must NOT import from schema.ts, which evolves over time and would cause this migration
6
+ * to produce different results on fresh runs vs. re-runs.
5
7
  */
6
8
  import type { MigrationBuilder } from 'node-pg-migrate';
7
9
 
8
- import { DROP_SCHEMA_VERSION_TABLE, DROP_VALIDATOR_DUTIES_TABLE, SCHEMA_SETUP, SCHEMA_VERSION } from '../schema.js';
10
+ import { DROP_SCHEMA_VERSION_TABLE, DROP_VALIDATOR_DUTIES_TABLE } from '../schema.js';
11
+
12
+ // Snapshot of the initial schema — does NOT include checkpoint_number (added in migration 2).
13
+ const INITIAL_SCHEMA_SETUP = [
14
+ `CREATE TABLE IF NOT EXISTS schema_version (
15
+ version INTEGER PRIMARY KEY,
16
+ applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
17
+ );`,
18
+ `CREATE TABLE IF NOT EXISTS validator_duties (
19
+ rollup_address VARCHAR(42) NOT NULL,
20
+ validator_address VARCHAR(42) NOT NULL,
21
+ slot BIGINT NOT NULL,
22
+ block_number BIGINT NOT NULL,
23
+ block_index_within_checkpoint INTEGER NOT NULL DEFAULT 0,
24
+ duty_type VARCHAR(30) NOT NULL CHECK (duty_type IN ('BLOCK_PROPOSAL', 'CHECKPOINT_PROPOSAL', 'ATTESTATION', 'ATTESTATIONS_AND_SIGNERS', 'GOVERNANCE_VOTE', 'SLASHING_VOTE')),
25
+ status VARCHAR(20) NOT NULL CHECK (status IN ('signing', 'signed')),
26
+ message_hash VARCHAR(66) NOT NULL,
27
+ signature VARCHAR(132),
28
+ node_id VARCHAR(255) NOT NULL,
29
+ lock_token VARCHAR(64) NOT NULL,
30
+ started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
31
+ completed_at TIMESTAMP,
32
+ error_message TEXT,
33
+
34
+ PRIMARY KEY (rollup_address, validator_address, slot, duty_type, block_index_within_checkpoint),
35
+ CHECK (completed_at IS NULL OR completed_at >= started_at)
36
+ );`,
37
+ `CREATE INDEX IF NOT EXISTS idx_validator_duties_status ON validator_duties(status, started_at);`,
38
+ `CREATE INDEX IF NOT EXISTS idx_validator_duties_node ON validator_duties(node_id, started_at);`,
39
+ ] as const;
9
40
 
10
41
  export function up(pgm: MigrationBuilder): void {
11
- for (const statement of SCHEMA_SETUP) {
42
+ for (const statement of INITIAL_SCHEMA_SETUP) {
12
43
  pgm.sql(statement);
13
44
  }
14
45
 
15
46
  // Insert initial schema version
16
47
  pgm.sql(`
17
48
  INSERT INTO schema_version (version)
18
- VALUES (${SCHEMA_VERSION})
49
+ VALUES (1)
19
50
  ON CONFLICT (version) DO NOTHING;
20
51
  `);
21
52
  }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Add checkpoint_number column to validator_duties table
3
+ */
4
+ import type { MigrationBuilder } from 'node-pg-migrate';
5
+
6
+ export function up(pgm: MigrationBuilder): void {
7
+ pgm.addColumn('validator_duties', {
8
+ // eslint-disable-next-line camelcase
9
+ checkpoint_number: { type: 'bigint', notNull: true, default: 0 },
10
+ });
11
+
12
+ pgm.sql(`UPDATE schema_version SET version = 2 WHERE version = 1`);
13
+ }
14
+
15
+ export function down(pgm: MigrationBuilder): void {
16
+ pgm.dropColumn('validator_duties', 'checkpoint_number');
17
+
18
+ pgm.sql(`UPDATE schema_version SET version = 1 WHERE version = 2`);
19
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * PostgreSQL implementation of SlashingProtectionDatabase
3
3
  */
4
- import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
+ import { SlotNumber } from '@aztec/foundation/branded-types';
5
5
  import { randomBytes } from '@aztec/foundation/crypto/random';
6
6
  import { EthAddress } from '@aztec/foundation/eth-address';
7
7
  import { type Logger, createLogger } from '@aztec/foundation/log';
@@ -11,6 +11,8 @@ import type { QueryResult, QueryResultRow } from 'pg';
11
11
 
12
12
  import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
13
13
  import {
14
+ CLEANUP_OLD_DUTIES,
15
+ CLEANUP_OUTDATED_ROLLUP_DUTIES,
14
16
  CLEANUP_OWN_STUCK_DUTIES,
15
17
  DELETE_DUTY,
16
18
  INSERT_OR_GET_DUTY,
@@ -18,7 +20,7 @@ import {
18
20
  UPDATE_DUTY_SIGNED,
19
21
  } from './schema.js';
20
22
  import type { CheckAndRecordParams, DutyRow, DutyType, InsertOrGetRow, ValidatorDutyRecord } from './types.js';
21
- import { getBlockIndexFromDutyIdentifier } from './types.js';
23
+ import { getBlockIndexFromDutyIdentifier, recordFromFields } from './types.js';
22
24
 
23
25
  /**
24
26
  * Minimal pool interface for database operations.
@@ -105,6 +107,7 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
105
107
  params.validatorAddress.toString(),
106
108
  params.slot.toString(),
107
109
  params.blockNumber.toString(),
110
+ params.checkpointNumber.toString(),
108
111
  blockIndexWithinCheckpoint,
109
112
  params.dutyType,
110
113
  params.messageHash,
@@ -218,14 +221,17 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
218
221
  }
219
222
 
220
223
  /**
221
- * Convert a database row to a ValidatorDutyRecord
224
+ * Convert a database row to a ValidatorDutyRecord.
225
+ * Maps snake_case column names to StoredDutyRecord (camelCase, ms timestamps),
226
+ * then delegates to the shared recordFromFields() converter.
222
227
  */
223
228
  private rowToRecord(row: DutyRow): ValidatorDutyRecord {
224
- return {
225
- rollupAddress: EthAddress.fromString(row.rollup_address),
226
- validatorAddress: EthAddress.fromString(row.validator_address),
227
- slot: SlotNumber.fromString(row.slot),
228
- blockNumber: BlockNumber.fromString(row.block_number),
229
+ return recordFromFields({
230
+ rollupAddress: row.rollup_address,
231
+ validatorAddress: row.validator_address,
232
+ slot: row.slot,
233
+ blockNumber: row.block_number,
234
+ checkpointNumber: row.checkpoint_number,
229
235
  blockIndexWithinCheckpoint: row.block_index_within_checkpoint,
230
236
  dutyType: row.duty_type,
231
237
  status: row.status,
@@ -233,10 +239,10 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
233
239
  signature: row.signature ?? undefined,
234
240
  nodeId: row.node_id,
235
241
  lockToken: row.lock_token,
236
- startedAt: row.started_at,
237
- completedAt: row.completed_at ?? undefined,
242
+ startedAtMs: row.started_at.getTime(),
243
+ completedAtMs: row.completed_at?.getTime(),
238
244
  errorMessage: row.error_message ?? undefined,
239
- };
245
+ });
240
246
  }
241
247
 
242
248
  /**
@@ -252,8 +258,29 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
252
258
  * @returns the number of duties cleaned up
253
259
  */
254
260
  async cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
255
- const cutoff = new Date(Date.now() - maxAgeMs);
256
- const result = await this.pool.query(CLEANUP_OWN_STUCK_DUTIES, [nodeId, cutoff]);
261
+ const result = await this.pool.query(CLEANUP_OWN_STUCK_DUTIES, [nodeId, maxAgeMs]);
262
+ return result.rowCount ?? 0;
263
+ }
264
+
265
+ /**
266
+ * Cleanup duties with outdated rollup address.
267
+ * Removes all duties where the rollup address doesn't match the current one.
268
+ * Used after a rollup upgrade to clean up duties for the old rollup.
269
+ * @returns the number of duties cleaned up
270
+ */
271
+ async cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number> {
272
+ const result = await this.pool.query(CLEANUP_OUTDATED_ROLLUP_DUTIES, [currentRollupAddress.toString()]);
273
+ return result.rowCount ?? 0;
274
+ }
275
+
276
+ /**
277
+ * Cleanup old signed duties.
278
+ * Removes only signed duties older than the specified age.
279
+ * Does not remove 'signing' duties as they may be in progress.
280
+ * @returns the number of duties cleaned up
281
+ */
282
+ async cleanupOldDuties(maxAgeMs: number): Promise<number> {
283
+ const result = await this.pool.query(CLEANUP_OLD_DUTIES, [maxAgeMs]);
257
284
  return result.rowCount ?? 0;
258
285
  }
259
286
  }