@aztec/validator-ha-signer 0.0.1-commit.fffb133c → 0.0.1-private.3d175340d2

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 +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/factory.d.ts +39 -4
  24. package/dest/factory.d.ts.map +1 -1
  25. package/dest/factory.js +81 -7
  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 +57 -17
  32. package/dest/types.d.ts +33 -72
  33. package/dest/types.d.ts.map +1 -1
  34. package/dest/types.js +4 -20
  35. package/dest/validator_ha_signer.d.ts +15 -6
  36. package/dest/validator_ha_signer.d.ts.map +1 -1
  37. package/dest/validator_ha_signer.js +26 -11
  38. package/package.json +11 -6
  39. package/src/db/index.ts +1 -0
  40. package/src/db/lmdb.ts +308 -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 +47 -12
  44. package/src/db/schema.ts +47 -23
  45. package/src/db/types.ts +72 -20
  46. package/src/factory.ts +111 -6
  47. package/src/metrics.ts +138 -0
  48. package/src/slashing_protection_service.ts +79 -21
  49. package/src/types.ts +56 -103
  50. package/src/validator_ha_signer.ts +44 -15
  51. package/dest/config.d.ts +0 -79
  52. package/dest/config.d.ts.map +0 -1
  53. package/dest/config.js +0 -73
  54. package/src/config.ts +0 -125
package/src/db/lmdb.ts ADDED
@@ -0,0 +1,308 @@
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
+ import { openStoreAt } from '@aztec/kv-store/lmdb-v2';
17
+
18
+ import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
19
+ import {
20
+ type CheckAndRecordParams,
21
+ DutyStatus,
22
+ DutyType,
23
+ type StoredDutyRecord,
24
+ getBlockIndexFromDutyIdentifier,
25
+ recordFromFields,
26
+ } from './types.js';
27
+
28
+ const DUTIES_MAP_NAME = 'signing-protection-duties';
29
+ const LEGACY_CHECKPOINT_NUMBER = '0';
30
+
31
+ type StoredDutyRecordV1 = Omit<StoredDutyRecord, 'checkpointNumber'> & { checkpointNumber?: undefined };
32
+ type MigratableStoredDutyRecord = StoredDutyRecord | StoredDutyRecordV1;
33
+
34
+ function needsCheckpointNumberMigration(record: MigratableStoredDutyRecord): record is StoredDutyRecordV1 {
35
+ return record.checkpointNumber === undefined;
36
+ }
37
+
38
+ /**
39
+ * Migrates local slashing-protection duties from schema 1 to schema 2.
40
+ */
41
+ export async function migrateLmdbSlashingProtectionDatabase(
42
+ dataDirectory: string,
43
+ currentVersion: number,
44
+ latestVersion: number,
45
+ dbMapSizeKb?: number,
46
+ ): Promise<void> {
47
+ if (currentVersion !== 1 || latestVersion !== LmdbSlashingProtectionDatabase.SCHEMA_VERSION) {
48
+ throw new Error(`Unsupported LMDB slashing-protection migration ${currentVersion} -> ${latestVersion}`);
49
+ }
50
+
51
+ const store = await openStoreAt(dataDirectory, dbMapSizeKb);
52
+ try {
53
+ const duties = store.openMap<string, MigratableStoredDutyRecord>(DUTIES_MAP_NAME);
54
+ const migratedRecords: { key: string; value: StoredDutyRecord }[] = [];
55
+
56
+ for await (const [key, record] of duties.entriesAsync()) {
57
+ if (needsCheckpointNumberMigration(record)) {
58
+ migratedRecords.push({ key, value: { ...record, checkpointNumber: LEGACY_CHECKPOINT_NUMBER } });
59
+ }
60
+ }
61
+
62
+ if (migratedRecords.length > 0) {
63
+ await duties.setMany(migratedRecords);
64
+ }
65
+ } finally {
66
+ await store.close();
67
+ }
68
+ }
69
+
70
+ function dutyKey(
71
+ rollupAddress: string,
72
+ validatorAddress: string,
73
+ slot: string,
74
+ dutyType: string,
75
+ blockIndexWithinCheckpoint: number,
76
+ ): string {
77
+ return `${rollupAddress}:${validatorAddress}:${slot}:${dutyType}:${blockIndexWithinCheckpoint}`;
78
+ }
79
+
80
+ /**
81
+ * LMDB-backed implementation of SlashingProtectionDatabase.
82
+ *
83
+ * Provides single-node double-signing protection that survives crashes and restarts.
84
+ * Does not provide cross-node coordination (that requires the PostgreSQL implementation).
85
+ */
86
+ export class LmdbSlashingProtectionDatabase implements SlashingProtectionDatabase {
87
+ public static readonly SCHEMA_VERSION = 2;
88
+
89
+ private readonly duties: AztecAsyncMap<string, StoredDutyRecord>;
90
+ private readonly log: Logger;
91
+
92
+ constructor(
93
+ private readonly store: AztecAsyncKVStore,
94
+ private readonly dateProvider: DateProvider,
95
+ ) {
96
+ this.log = createLogger('slashing-protection:lmdb');
97
+ this.duties = store.openMap<string, StoredDutyRecord>(DUTIES_MAP_NAME);
98
+ }
99
+
100
+ /**
101
+ * Atomically try to insert a new duty record, or get the existing one if present.
102
+ *
103
+ * LMDB is single-writer so the read-then-write inside transactionAsync is naturally atomic.
104
+ */
105
+ public async tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult> {
106
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
107
+ const key = dutyKey(
108
+ params.rollupAddress.toString(),
109
+ params.validatorAddress.toString(),
110
+ params.slot.toString(),
111
+ params.dutyType,
112
+ blockIndexWithinCheckpoint,
113
+ );
114
+
115
+ const lockToken = randomBytes(16).toString('hex');
116
+ const now = this.dateProvider.now();
117
+
118
+ const result = await this.store.transactionAsync(async () => {
119
+ const existing = await this.duties.getAsync(key);
120
+ if (existing) {
121
+ return { isNew: false as const, record: { ...existing, lockToken: '' } };
122
+ }
123
+
124
+ const newRecord: StoredDutyRecord = {
125
+ rollupAddress: params.rollupAddress.toString(),
126
+ validatorAddress: params.validatorAddress.toString(),
127
+ slot: params.slot.toString(),
128
+ blockNumber: params.blockNumber.toString(),
129
+ checkpointNumber: params.checkpointNumber.toString(),
130
+ blockIndexWithinCheckpoint,
131
+ dutyType: params.dutyType,
132
+ status: DutyStatus.SIGNING,
133
+ messageHash: params.messageHash,
134
+ nodeId: params.nodeId,
135
+ lockToken,
136
+ startedAtMs: now,
137
+ };
138
+ await this.duties.set(key, newRecord);
139
+ return { isNew: true as const, record: newRecord };
140
+ });
141
+
142
+ if (result.isNew) {
143
+ this.log.debug(`Acquired lock for duty ${params.dutyType} at slot ${params.slot}`, {
144
+ validatorAddress: params.validatorAddress.toString(),
145
+ nodeId: params.nodeId,
146
+ });
147
+ }
148
+
149
+ return { isNew: result.isNew, record: recordFromFields(result.record) };
150
+ }
151
+
152
+ /**
153
+ * Update a duty to 'signed' status with the signature.
154
+ * Only succeeds if the lockToken matches.
155
+ */
156
+ public updateDutySigned(
157
+ rollupAddress: EthAddress,
158
+ validatorAddress: EthAddress,
159
+ slot: SlotNumber,
160
+ dutyType: DutyType,
161
+ signature: string,
162
+ lockToken: string,
163
+ blockIndexWithinCheckpoint: number,
164
+ ): Promise<boolean> {
165
+ const key = dutyKey(
166
+ rollupAddress.toString(),
167
+ validatorAddress.toString(),
168
+ slot.toString(),
169
+ dutyType,
170
+ blockIndexWithinCheckpoint,
171
+ );
172
+
173
+ return this.store.transactionAsync(async () => {
174
+ const existing = await this.duties.getAsync(key);
175
+ if (!existing) {
176
+ this.log.warn('Failed to update duty to signed: duty not found', {
177
+ rollupAddress: rollupAddress.toString(),
178
+ validatorAddress: validatorAddress.toString(),
179
+ slot: slot.toString(),
180
+ dutyType,
181
+ blockIndexWithinCheckpoint,
182
+ });
183
+ return false;
184
+ }
185
+
186
+ if (existing.lockToken !== lockToken) {
187
+ this.log.warn('Failed to update duty to signed: invalid token', {
188
+ rollupAddress: rollupAddress.toString(),
189
+ validatorAddress: validatorAddress.toString(),
190
+ slot: slot.toString(),
191
+ dutyType,
192
+ blockIndexWithinCheckpoint,
193
+ });
194
+ return false;
195
+ }
196
+
197
+ await this.duties.set(key, {
198
+ ...existing,
199
+ status: DutyStatus.SIGNED,
200
+ signature,
201
+ completedAtMs: this.dateProvider.now(),
202
+ });
203
+
204
+ return true;
205
+ });
206
+ }
207
+
208
+ /**
209
+ * Delete a duty record.
210
+ * Only succeeds if the lockToken matches.
211
+ */
212
+ public deleteDuty(
213
+ rollupAddress: EthAddress,
214
+ validatorAddress: EthAddress,
215
+ slot: SlotNumber,
216
+ dutyType: DutyType,
217
+ lockToken: string,
218
+ blockIndexWithinCheckpoint: number,
219
+ ): Promise<boolean> {
220
+ const key = dutyKey(
221
+ rollupAddress.toString(),
222
+ validatorAddress.toString(),
223
+ slot.toString(),
224
+ dutyType,
225
+ blockIndexWithinCheckpoint,
226
+ );
227
+
228
+ return this.store.transactionAsync(async () => {
229
+ const existing = await this.duties.getAsync(key);
230
+ if (!existing || existing.lockToken !== lockToken) {
231
+ this.log.warn('Failed to delete duty: invalid token or duty not found', {
232
+ rollupAddress: rollupAddress.toString(),
233
+ validatorAddress: validatorAddress.toString(),
234
+ slot: slot.toString(),
235
+ dutyType,
236
+ blockIndexWithinCheckpoint,
237
+ });
238
+ return false;
239
+ }
240
+
241
+ await this.duties.delete(key);
242
+ return true;
243
+ });
244
+ }
245
+
246
+ /**
247
+ * Cleanup own stuck duties (SIGNING status older than maxAgeMs).
248
+ */
249
+ public cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
250
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
251
+
252
+ return this.store.transactionAsync(async () => {
253
+ const keysToDelete: string[] = [];
254
+ for await (const [key, record] of this.duties.entriesAsync()) {
255
+ if (record.nodeId === nodeId && record.status === DutyStatus.SIGNING && record.startedAtMs < cutoffMs) {
256
+ keysToDelete.push(key);
257
+ }
258
+ }
259
+ for (const key of keysToDelete) {
260
+ await this.duties.delete(key);
261
+ }
262
+ return keysToDelete.length;
263
+ });
264
+ }
265
+
266
+ /**
267
+ * Cleanup duties with outdated rollup address.
268
+ *
269
+ * This is always a no-op for the LMDB implementation: the underlying store is created via
270
+ * DatabaseVersionManager (in factory.ts), which already resets the entire data directory at
271
+ * startup whenever the rollup address changes.
272
+ */
273
+ public cleanupOutdatedRollupDuties(_currentRollupAddress: EthAddress): Promise<number> {
274
+ return Promise.resolve(0);
275
+ }
276
+
277
+ /**
278
+ * Cleanup old signed duties older than maxAgeMs.
279
+ */
280
+ public cleanupOldDuties(maxAgeMs: number): Promise<number> {
281
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
282
+
283
+ return this.store.transactionAsync(async () => {
284
+ const keysToDelete: string[] = [];
285
+ for await (const [key, record] of this.duties.entriesAsync()) {
286
+ if (
287
+ record.status === DutyStatus.SIGNED &&
288
+ record.completedAtMs !== undefined &&
289
+ record.completedAtMs < cutoffMs
290
+ ) {
291
+ keysToDelete.push(key);
292
+ }
293
+ }
294
+ for (const key of keysToDelete) {
295
+ await this.duties.delete(key);
296
+ }
297
+ return keysToDelete.length;
298
+ });
299
+ }
300
+
301
+ /**
302
+ * Close the underlying LMDB store.
303
+ */
304
+ public async close(): Promise<void> {
305
+ await this.store.close();
306
+ this.log.debug('LMDB slashing protection database closed');
307
+ }
308
+ }
@@ -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.
@@ -101,9 +103,11 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
101
103
  const result = await retry<QueryResult<InsertOrGetRow>>(
102
104
  async () => {
103
105
  const queryResult: QueryResult<InsertOrGetRow> = await this.pool.query(INSERT_OR_GET_DUTY, [
106
+ params.rollupAddress.toString(),
104
107
  params.validatorAddress.toString(),
105
108
  params.slot.toString(),
106
109
  params.blockNumber.toString(),
110
+ params.checkpointNumber.toString(),
107
111
  blockIndexWithinCheckpoint,
108
112
  params.dutyType,
109
113
  params.messageHash,
@@ -148,6 +152,7 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
148
152
  * @returns true if the update succeeded, false if token didn't match or duty not found
149
153
  */
150
154
  async updateDutySigned(
155
+ rollupAddress: EthAddress,
151
156
  validatorAddress: EthAddress,
152
157
  slot: SlotNumber,
153
158
  dutyType: DutyType,
@@ -157,6 +162,7 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
157
162
  ): Promise<boolean> {
158
163
  const result = await this.pool.query(UPDATE_DUTY_SIGNED, [
159
164
  signature,
165
+ rollupAddress.toString(),
160
166
  validatorAddress.toString(),
161
167
  slot.toString(),
162
168
  dutyType,
@@ -166,6 +172,7 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
166
172
 
167
173
  if (result.rowCount === 0) {
168
174
  this.log.warn('Failed to update duty to signed status: invalid token or duty not found', {
175
+ rollupAddress: rollupAddress.toString(),
169
176
  validatorAddress: validatorAddress.toString(),
170
177
  slot: slot.toString(),
171
178
  dutyType,
@@ -184,6 +191,7 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
184
191
  * @returns true if the delete succeeded, false if token didn't match or duty not found
185
192
  */
186
193
  async deleteDuty(
194
+ rollupAddress: EthAddress,
187
195
  validatorAddress: EthAddress,
188
196
  slot: SlotNumber,
189
197
  dutyType: DutyType,
@@ -191,6 +199,7 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
191
199
  blockIndexWithinCheckpoint: number,
192
200
  ): Promise<boolean> {
193
201
  const result = await this.pool.query(DELETE_DUTY, [
202
+ rollupAddress.toString(),
194
203
  validatorAddress.toString(),
195
204
  slot.toString(),
196
205
  dutyType,
@@ -200,6 +209,7 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
200
209
 
201
210
  if (result.rowCount === 0) {
202
211
  this.log.warn('Failed to delete duty: invalid token or duty not found', {
212
+ rollupAddress: rollupAddress.toString(),
203
213
  validatorAddress: validatorAddress.toString(),
204
214
  slot: slot.toString(),
205
215
  dutyType,
@@ -211,13 +221,17 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
211
221
  }
212
222
 
213
223
  /**
214
- * 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.
215
227
  */
216
228
  private rowToRecord(row: DutyRow): ValidatorDutyRecord {
217
- return {
218
- validatorAddress: EthAddress.fromString(row.validator_address),
219
- slot: SlotNumber.fromString(row.slot),
220
- 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,
221
235
  blockIndexWithinCheckpoint: row.block_index_within_checkpoint,
222
236
  dutyType: row.duty_type,
223
237
  status: row.status,
@@ -225,10 +239,10 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
225
239
  signature: row.signature ?? undefined,
226
240
  nodeId: row.node_id,
227
241
  lockToken: row.lock_token,
228
- startedAt: row.started_at,
229
- completedAt: row.completed_at ?? undefined,
242
+ startedAtMs: row.started_at.getTime(),
243
+ completedAtMs: row.completed_at?.getTime(),
230
244
  errorMessage: row.error_message ?? undefined,
231
- };
245
+ });
232
246
  }
233
247
 
234
248
  /**
@@ -244,8 +258,29 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
244
258
  * @returns the number of duties cleaned up
245
259
  */
246
260
  async cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
247
- const cutoff = new Date(Date.now() - maxAgeMs);
248
- 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]);
249
284
  return result.rowCount ?? 0;
250
285
  }
251
286
  }