@aztec/validator-ha-signer 0.0.1-commit.001888fc

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 +195 -0
  2. package/dest/db/index.d.ts +5 -0
  3. package/dest/db/index.d.ts.map +1 -0
  4. package/dest/db/index.js +4 -0
  5. package/dest/db/lmdb.d.ts +66 -0
  6. package/dest/db/lmdb.d.ts.map +1 -0
  7. package/dest/db/lmdb.js +188 -0
  8. package/dest/db/migrations/1_initial-schema.d.ts +9 -0
  9. package/dest/db/migrations/1_initial-schema.d.ts.map +1 -0
  10. package/dest/db/migrations/1_initial-schema.js +20 -0
  11. package/dest/db/postgres.d.ts +86 -0
  12. package/dest/db/postgres.d.ts.map +1 -0
  13. package/dest/db/postgres.js +208 -0
  14. package/dest/db/schema.d.ts +96 -0
  15. package/dest/db/schema.d.ts.map +1 -0
  16. package/dest/db/schema.js +230 -0
  17. package/dest/db/test_helper.d.ts +10 -0
  18. package/dest/db/test_helper.d.ts.map +1 -0
  19. package/dest/db/test_helper.js +14 -0
  20. package/dest/db/types.d.ts +185 -0
  21. package/dest/db/types.d.ts.map +1 -0
  22. package/dest/db/types.js +64 -0
  23. package/dest/errors.d.ts +34 -0
  24. package/dest/errors.d.ts.map +1 -0
  25. package/dest/errors.js +34 -0
  26. package/dest/factory.d.ts +60 -0
  27. package/dest/factory.d.ts.map +1 -0
  28. package/dest/factory.js +115 -0
  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/migrations.d.ts +15 -0
  33. package/dest/migrations.d.ts.map +1 -0
  34. package/dest/migrations.js +53 -0
  35. package/dest/slashing_protection_service.d.ts +93 -0
  36. package/dest/slashing_protection_service.d.ts.map +1 -0
  37. package/dest/slashing_protection_service.js +236 -0
  38. package/dest/test/pglite_pool.d.ts +92 -0
  39. package/dest/test/pglite_pool.d.ts.map +1 -0
  40. package/dest/test/pglite_pool.js +210 -0
  41. package/dest/types.d.ts +99 -0
  42. package/dest/types.d.ts.map +1 -0
  43. package/dest/types.js +4 -0
  44. package/dest/validator_ha_signer.d.ts +79 -0
  45. package/dest/validator_ha_signer.d.ts.map +1 -0
  46. package/dest/validator_ha_signer.js +140 -0
  47. package/package.json +110 -0
  48. package/src/db/index.ts +4 -0
  49. package/src/db/lmdb.ts +264 -0
  50. package/src/db/migrations/1_initial-schema.ts +26 -0
  51. package/src/db/postgres.ts +284 -0
  52. package/src/db/schema.ts +267 -0
  53. package/src/db/test_helper.ts +17 -0
  54. package/src/db/types.ts +251 -0
  55. package/src/errors.ts +47 -0
  56. package/src/factory.ts +139 -0
  57. package/src/metrics.ts +138 -0
  58. package/src/migrations.ts +75 -0
  59. package/src/slashing_protection_service.ts +308 -0
  60. package/src/test/pglite_pool.ts +256 -0
  61. package/src/types.ts +154 -0
  62. package/src/validator_ha_signer.ts +183 -0
package/src/db/lmdb.ts ADDED
@@ -0,0 +1,264 @@
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 = 1;
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
+ blockIndexWithinCheckpoint,
87
+ dutyType: params.dutyType,
88
+ status: DutyStatus.SIGNING,
89
+ messageHash: params.messageHash,
90
+ nodeId: params.nodeId,
91
+ lockToken,
92
+ startedAtMs: now,
93
+ };
94
+ await this.duties.set(key, newRecord);
95
+ return { isNew: true as const, record: newRecord };
96
+ });
97
+
98
+ if (result.isNew) {
99
+ this.log.debug(`Acquired lock for duty ${params.dutyType} at slot ${params.slot}`, {
100
+ validatorAddress: params.validatorAddress.toString(),
101
+ nodeId: params.nodeId,
102
+ });
103
+ }
104
+
105
+ return { isNew: result.isNew, record: recordFromFields(result.record) };
106
+ }
107
+
108
+ /**
109
+ * Update a duty to 'signed' status with the signature.
110
+ * Only succeeds if the lockToken matches.
111
+ */
112
+ public updateDutySigned(
113
+ rollupAddress: EthAddress,
114
+ validatorAddress: EthAddress,
115
+ slot: SlotNumber,
116
+ dutyType: DutyType,
117
+ signature: string,
118
+ lockToken: string,
119
+ blockIndexWithinCheckpoint: number,
120
+ ): Promise<boolean> {
121
+ const key = dutyKey(
122
+ rollupAddress.toString(),
123
+ validatorAddress.toString(),
124
+ slot.toString(),
125
+ dutyType,
126
+ blockIndexWithinCheckpoint,
127
+ );
128
+
129
+ return this.store.transactionAsync(async () => {
130
+ const existing = await this.duties.getAsync(key);
131
+ if (!existing) {
132
+ this.log.warn('Failed to update duty to signed: duty not found', {
133
+ rollupAddress: rollupAddress.toString(),
134
+ validatorAddress: validatorAddress.toString(),
135
+ slot: slot.toString(),
136
+ dutyType,
137
+ blockIndexWithinCheckpoint,
138
+ });
139
+ return false;
140
+ }
141
+
142
+ if (existing.lockToken !== lockToken) {
143
+ this.log.warn('Failed to update duty to signed: invalid token', {
144
+ rollupAddress: rollupAddress.toString(),
145
+ validatorAddress: validatorAddress.toString(),
146
+ slot: slot.toString(),
147
+ dutyType,
148
+ blockIndexWithinCheckpoint,
149
+ });
150
+ return false;
151
+ }
152
+
153
+ await this.duties.set(key, {
154
+ ...existing,
155
+ status: DutyStatus.SIGNED,
156
+ signature,
157
+ completedAtMs: this.dateProvider.now(),
158
+ });
159
+
160
+ return true;
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Delete a duty record.
166
+ * Only succeeds if the lockToken matches.
167
+ */
168
+ public deleteDuty(
169
+ rollupAddress: EthAddress,
170
+ validatorAddress: EthAddress,
171
+ slot: SlotNumber,
172
+ dutyType: DutyType,
173
+ lockToken: string,
174
+ blockIndexWithinCheckpoint: number,
175
+ ): Promise<boolean> {
176
+ const key = dutyKey(
177
+ rollupAddress.toString(),
178
+ validatorAddress.toString(),
179
+ slot.toString(),
180
+ dutyType,
181
+ blockIndexWithinCheckpoint,
182
+ );
183
+
184
+ return this.store.transactionAsync(async () => {
185
+ const existing = await this.duties.getAsync(key);
186
+ if (!existing || existing.lockToken !== lockToken) {
187
+ this.log.warn('Failed to delete duty: invalid token or duty not found', {
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.delete(key);
198
+ return true;
199
+ });
200
+ }
201
+
202
+ /**
203
+ * Cleanup own stuck duties (SIGNING status older than maxAgeMs).
204
+ */
205
+ public cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
206
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
207
+
208
+ return this.store.transactionAsync(async () => {
209
+ const keysToDelete: string[] = [];
210
+ for await (const [key, record] of this.duties.entriesAsync()) {
211
+ if (record.nodeId === nodeId && record.status === DutyStatus.SIGNING && record.startedAtMs < cutoffMs) {
212
+ keysToDelete.push(key);
213
+ }
214
+ }
215
+ for (const key of keysToDelete) {
216
+ await this.duties.delete(key);
217
+ }
218
+ return keysToDelete.length;
219
+ });
220
+ }
221
+
222
+ /**
223
+ * Cleanup duties with outdated rollup address.
224
+ *
225
+ * This is always a no-op for the LMDB implementation: the underlying store is created via
226
+ * DatabaseVersionManager (in factory.ts), which already resets the entire data directory at
227
+ * startup whenever the rollup address changes.
228
+ */
229
+ public cleanupOutdatedRollupDuties(_currentRollupAddress: EthAddress): Promise<number> {
230
+ return Promise.resolve(0);
231
+ }
232
+
233
+ /**
234
+ * Cleanup old signed duties older than maxAgeMs.
235
+ */
236
+ public cleanupOldDuties(maxAgeMs: number): Promise<number> {
237
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
238
+
239
+ return this.store.transactionAsync(async () => {
240
+ const keysToDelete: string[] = [];
241
+ for await (const [key, record] of this.duties.entriesAsync()) {
242
+ if (
243
+ record.status === DutyStatus.SIGNED &&
244
+ record.completedAtMs !== undefined &&
245
+ record.completedAtMs < cutoffMs
246
+ ) {
247
+ keysToDelete.push(key);
248
+ }
249
+ }
250
+ for (const key of keysToDelete) {
251
+ await this.duties.delete(key);
252
+ }
253
+ return keysToDelete.length;
254
+ });
255
+ }
256
+
257
+ /**
258
+ * Close the underlying LMDB store.
259
+ */
260
+ public async close(): Promise<void> {
261
+ await this.store.close();
262
+ this.log.debug('LMDB slashing protection database closed');
263
+ }
264
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Initial schema for validator HA slashing protection
3
+ *
4
+ * This migration imports SQL from the schema.ts file to ensure a single source of truth.
5
+ */
6
+ import type { MigrationBuilder } from 'node-pg-migrate';
7
+
8
+ import { DROP_SCHEMA_VERSION_TABLE, DROP_VALIDATOR_DUTIES_TABLE, SCHEMA_SETUP, SCHEMA_VERSION } from '../schema.js';
9
+
10
+ export function up(pgm: MigrationBuilder): void {
11
+ for (const statement of SCHEMA_SETUP) {
12
+ pgm.sql(statement);
13
+ }
14
+
15
+ // Insert initial schema version
16
+ pgm.sql(`
17
+ INSERT INTO schema_version (version)
18
+ VALUES (${SCHEMA_VERSION})
19
+ ON CONFLICT (version) DO NOTHING;
20
+ `);
21
+ }
22
+
23
+ export function down(pgm: MigrationBuilder): void {
24
+ pgm.sql(DROP_VALIDATOR_DUTIES_TABLE);
25
+ pgm.sql(DROP_SCHEMA_VERSION_TABLE);
26
+ }
@@ -0,0 +1,284 @@
1
+ /**
2
+ * PostgreSQL implementation of SlashingProtectionDatabase
3
+ */
4
+ import { SlotNumber } from '@aztec/foundation/branded-types';
5
+ import { randomBytes } from '@aztec/foundation/crypto/random';
6
+ import { EthAddress } from '@aztec/foundation/eth-address';
7
+ import { type Logger, createLogger } from '@aztec/foundation/log';
8
+ import { makeBackoff, retry } from '@aztec/foundation/retry';
9
+
10
+ import type { QueryResult, QueryResultRow } from 'pg';
11
+
12
+ import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
13
+ import {
14
+ CLEANUP_OLD_DUTIES,
15
+ CLEANUP_OUTDATED_ROLLUP_DUTIES,
16
+ CLEANUP_OWN_STUCK_DUTIES,
17
+ DELETE_DUTY,
18
+ INSERT_OR_GET_DUTY,
19
+ SCHEMA_VERSION,
20
+ UPDATE_DUTY_SIGNED,
21
+ } from './schema.js';
22
+ import type { CheckAndRecordParams, DutyRow, DutyType, InsertOrGetRow, ValidatorDutyRecord } from './types.js';
23
+ import { getBlockIndexFromDutyIdentifier, recordFromFields } from './types.js';
24
+
25
+ /**
26
+ * Minimal pool interface for database operations.
27
+ * Both pg.Pool and test adapters (e.g., PGlite) satisfy this interface.
28
+ */
29
+ export interface QueryablePool {
30
+ query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>>;
31
+ end(): Promise<void>;
32
+ }
33
+
34
+ /**
35
+ * PostgreSQL implementation of the slashing protection database
36
+ */
37
+ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDatabase {
38
+ private readonly log: Logger;
39
+
40
+ constructor(private readonly pool: QueryablePool) {
41
+ this.log = createLogger('slashing-protection:postgres');
42
+ }
43
+
44
+ /**
45
+ * Verify that database migrations have been run and schema version matches.
46
+ * Should be called once at startup.
47
+ *
48
+ * @throws Error if migrations haven't been run or schema version is outdated
49
+ */
50
+ async initialize(): Promise<void> {
51
+ let dbVersion: number;
52
+
53
+ try {
54
+ const result = await this.pool.query<{ version: number }>(
55
+ `SELECT version FROM schema_version ORDER BY version DESC LIMIT 1`,
56
+ );
57
+
58
+ if (result.rows.length === 0) {
59
+ throw new Error('No version found');
60
+ }
61
+
62
+ dbVersion = result.rows[0].version;
63
+ } catch {
64
+ throw new Error(
65
+ 'Database schema not initialized. Please run migrations first: aztec migrate-ha-db up --database-url <url>',
66
+ );
67
+ }
68
+
69
+ if (dbVersion < SCHEMA_VERSION) {
70
+ throw new Error(
71
+ `Database schema version ${dbVersion} is outdated (expected ${SCHEMA_VERSION}). Please run migrations: aztec migrate-ha-db up --database-url <url>`,
72
+ );
73
+ }
74
+
75
+ if (dbVersion > SCHEMA_VERSION) {
76
+ throw new Error(
77
+ `Database schema version ${dbVersion} is newer than expected (${SCHEMA_VERSION}). Please update your application.`,
78
+ );
79
+ }
80
+
81
+ this.log.info('Database schema verified', { version: dbVersion });
82
+ }
83
+
84
+ /**
85
+ * Atomically try to insert a new duty record, or get the existing one if present.
86
+ *
87
+ * @returns { isNew: true, record } if we successfully inserted and acquired the lock
88
+ * @returns { isNew: false, record } if a record already exists. lock_token is empty if the record already exists.
89
+ *
90
+ * Retries if no rows are returned, which can happen under high concurrency
91
+ * when another transaction just committed the row but it's not yet visible.
92
+ */
93
+ async tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult> {
94
+ // create a token for ownership verification
95
+ const lockToken = randomBytes(16).toString('hex');
96
+
97
+ // Use fast retries with custom backoff: 10ms, 20ms, 30ms (then stop)
98
+ const fastBackoff = makeBackoff([0.01, 0.02, 0.03]);
99
+
100
+ // Get the normalized block index using type-safe helper
101
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
102
+
103
+ const result = await retry<QueryResult<InsertOrGetRow>>(
104
+ async () => {
105
+ const queryResult: QueryResult<InsertOrGetRow> = await this.pool.query(INSERT_OR_GET_DUTY, [
106
+ params.rollupAddress.toString(),
107
+ params.validatorAddress.toString(),
108
+ params.slot.toString(),
109
+ params.blockNumber.toString(),
110
+ blockIndexWithinCheckpoint,
111
+ params.dutyType,
112
+ params.messageHash,
113
+ params.nodeId,
114
+ lockToken,
115
+ ]);
116
+
117
+ // Throw error if no rows to trigger retry
118
+ if (queryResult.rows.length === 0) {
119
+ throw new Error('INSERT_OR_GET_DUTY returned no rows');
120
+ }
121
+
122
+ return queryResult;
123
+ },
124
+ `INSERT_OR_GET_DUTY for node ${params.nodeId}`,
125
+ fastBackoff,
126
+ this.log,
127
+ true,
128
+ );
129
+
130
+ if (result.rows.length === 0) {
131
+ // this should never happen as the retry function should throw if it still fails after retries
132
+ throw new Error('INSERT_OR_GET_DUTY returned no rows after retries');
133
+ }
134
+
135
+ if (result.rows.length > 1) {
136
+ // this should never happen if database constraints are correct (PRIMARY KEY should prevent duplicates)
137
+ throw new Error(`INSERT_OR_GET_DUTY returned ${result.rows.length} rows (expected exactly 1).`);
138
+ }
139
+
140
+ const row = result.rows[0];
141
+ return {
142
+ isNew: row.is_new,
143
+ record: this.rowToRecord(row),
144
+ };
145
+ }
146
+
147
+ /**
148
+ * Update a duty to 'signed' status with the signature.
149
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
150
+ *
151
+ * @returns true if the update succeeded, false if token didn't match or duty not found
152
+ */
153
+ async updateDutySigned(
154
+ rollupAddress: EthAddress,
155
+ validatorAddress: EthAddress,
156
+ slot: SlotNumber,
157
+ dutyType: DutyType,
158
+ signature: string,
159
+ lockToken: string,
160
+ blockIndexWithinCheckpoint: number,
161
+ ): Promise<boolean> {
162
+ const result = await this.pool.query(UPDATE_DUTY_SIGNED, [
163
+ signature,
164
+ rollupAddress.toString(),
165
+ validatorAddress.toString(),
166
+ slot.toString(),
167
+ dutyType,
168
+ blockIndexWithinCheckpoint,
169
+ lockToken,
170
+ ]);
171
+
172
+ if (result.rowCount === 0) {
173
+ this.log.warn('Failed to update duty to signed status: invalid token or duty not found', {
174
+ rollupAddress: rollupAddress.toString(),
175
+ validatorAddress: validatorAddress.toString(),
176
+ slot: slot.toString(),
177
+ dutyType,
178
+ blockIndexWithinCheckpoint,
179
+ });
180
+ return false;
181
+ }
182
+ return true;
183
+ }
184
+
185
+ /**
186
+ * Delete a duty record.
187
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
188
+ * Used when signing fails to allow another node/attempt to retry.
189
+ *
190
+ * @returns true if the delete succeeded, false if token didn't match or duty not found
191
+ */
192
+ async deleteDuty(
193
+ rollupAddress: EthAddress,
194
+ validatorAddress: EthAddress,
195
+ slot: SlotNumber,
196
+ dutyType: DutyType,
197
+ lockToken: string,
198
+ blockIndexWithinCheckpoint: number,
199
+ ): Promise<boolean> {
200
+ const result = await this.pool.query(DELETE_DUTY, [
201
+ rollupAddress.toString(),
202
+ validatorAddress.toString(),
203
+ slot.toString(),
204
+ dutyType,
205
+ blockIndexWithinCheckpoint,
206
+ lockToken,
207
+ ]);
208
+
209
+ if (result.rowCount === 0) {
210
+ this.log.warn('Failed to delete duty: invalid token or duty not found', {
211
+ rollupAddress: rollupAddress.toString(),
212
+ validatorAddress: validatorAddress.toString(),
213
+ slot: slot.toString(),
214
+ dutyType,
215
+ blockIndexWithinCheckpoint,
216
+ });
217
+ return false;
218
+ }
219
+ return true;
220
+ }
221
+
222
+ /**
223
+ * Convert a database row to a ValidatorDutyRecord.
224
+ * Maps snake_case column names to StoredDutyRecord (camelCase, ms timestamps),
225
+ * then delegates to the shared recordFromFields() converter.
226
+ */
227
+ private rowToRecord(row: DutyRow): ValidatorDutyRecord {
228
+ return recordFromFields({
229
+ rollupAddress: row.rollup_address,
230
+ validatorAddress: row.validator_address,
231
+ slot: row.slot,
232
+ blockNumber: row.block_number,
233
+ blockIndexWithinCheckpoint: row.block_index_within_checkpoint,
234
+ dutyType: row.duty_type,
235
+ status: row.status,
236
+ messageHash: row.message_hash,
237
+ signature: row.signature ?? undefined,
238
+ nodeId: row.node_id,
239
+ lockToken: row.lock_token,
240
+ startedAtMs: row.started_at.getTime(),
241
+ completedAtMs: row.completed_at?.getTime(),
242
+ errorMessage: row.error_message ?? undefined,
243
+ });
244
+ }
245
+
246
+ /**
247
+ * Close the database connection pool
248
+ */
249
+ async close(): Promise<void> {
250
+ await this.pool.end();
251
+ this.log.info('Database connection pool closed');
252
+ }
253
+
254
+ /**
255
+ * Cleanup own stuck duties
256
+ * @returns the number of duties cleaned up
257
+ */
258
+ async cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
259
+ const result = await this.pool.query(CLEANUP_OWN_STUCK_DUTIES, [nodeId, maxAgeMs]);
260
+ return result.rowCount ?? 0;
261
+ }
262
+
263
+ /**
264
+ * Cleanup duties with outdated rollup address.
265
+ * Removes all duties where the rollup address doesn't match the current one.
266
+ * Used after a rollup upgrade to clean up duties for the old rollup.
267
+ * @returns the number of duties cleaned up
268
+ */
269
+ async cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number> {
270
+ const result = await this.pool.query(CLEANUP_OUTDATED_ROLLUP_DUTIES, [currentRollupAddress.toString()]);
271
+ return result.rowCount ?? 0;
272
+ }
273
+
274
+ /**
275
+ * Cleanup old signed duties.
276
+ * Removes only signed duties older than the specified age.
277
+ * Does not remove 'signing' duties as they may be in progress.
278
+ * @returns the number of duties cleaned up
279
+ */
280
+ async cleanupOldDuties(maxAgeMs: number): Promise<number> {
281
+ const result = await this.pool.query(CLEANUP_OLD_DUTIES, [maxAgeMs]);
282
+ return result.rowCount ?? 0;
283
+ }
284
+ }