@aztec/validator-ha-signer 0.0.1-commit.96bb3f7 → 0.0.1-commit.9d2bcf6d

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 (46) hide show
  1. package/README.md +42 -37
  2. package/dest/config.d.ts +71 -17
  3. package/dest/config.d.ts.map +1 -1
  4. package/dest/config.js +47 -19
  5. package/dest/db/postgres.d.ts +34 -5
  6. package/dest/db/postgres.d.ts.map +1 -1
  7. package/dest/db/postgres.js +80 -20
  8. package/dest/db/schema.d.ts +19 -9
  9. package/dest/db/schema.d.ts.map +1 -1
  10. package/dest/db/schema.js +46 -18
  11. package/dest/db/types.d.ts +81 -24
  12. package/dest/db/types.d.ts.map +1 -1
  13. package/dest/db/types.js +34 -0
  14. package/dest/errors.d.ts +9 -5
  15. package/dest/errors.d.ts.map +1 -1
  16. package/dest/errors.js +7 -4
  17. package/dest/factory.d.ts +6 -14
  18. package/dest/factory.d.ts.map +1 -1
  19. package/dest/factory.js +6 -11
  20. package/dest/migrations.d.ts +1 -1
  21. package/dest/migrations.d.ts.map +1 -1
  22. package/dest/migrations.js +13 -2
  23. package/dest/slashing_protection_service.d.ts +16 -6
  24. package/dest/slashing_protection_service.d.ts.map +1 -1
  25. package/dest/slashing_protection_service.js +58 -17
  26. package/dest/test/pglite_pool.d.ts +92 -0
  27. package/dest/test/pglite_pool.d.ts.map +1 -0
  28. package/dest/test/pglite_pool.js +210 -0
  29. package/dest/types.d.ts +91 -14
  30. package/dest/types.d.ts.map +1 -1
  31. package/dest/types.js +21 -1
  32. package/dest/validator_ha_signer.d.ts +10 -13
  33. package/dest/validator_ha_signer.d.ts.map +1 -1
  34. package/dest/validator_ha_signer.js +32 -31
  35. package/package.json +9 -8
  36. package/src/config.ts +83 -50
  37. package/src/db/postgres.ts +101 -19
  38. package/src/db/schema.ts +48 -18
  39. package/src/db/types.ts +111 -22
  40. package/src/errors.ts +7 -2
  41. package/src/factory.ts +8 -13
  42. package/src/migrations.ts +17 -1
  43. package/src/slashing_protection_service.ts +94 -23
  44. package/src/test/pglite_pool.ts +256 -0
  45. package/src/types.ts +140 -19
  46. package/src/validator_ha_signer.ts +39 -41
package/src/migrations.ts CHANGED
@@ -3,6 +3,7 @@
3
3
  */
4
4
  import { createLogger } from '@aztec/foundation/log';
5
5
 
6
+ import { readdirSync } from 'fs';
6
7
  import { runner } from 'node-pg-migrate';
7
8
  import { dirname, join } from 'path';
8
9
  import { fileURLToPath } from 'url';
@@ -30,17 +31,32 @@ export async function runMigrations(databaseUrl: string, options: RunMigrationsO
30
31
 
31
32
  const log = createLogger('validator-ha-signer:migrations');
32
33
 
34
+ const migrationsDir = join(__dirname, 'db', 'migrations');
35
+
33
36
  try {
34
37
  log.info(`Running migrations ${direction}...`);
35
38
 
39
+ // Filter out .d.ts and .d.ts.map files - node-pg-migrate only needs .js files
40
+ const migrationFiles = readdirSync(migrationsDir);
41
+ const jsMigrationFiles = migrationFiles.filter(
42
+ file => file.endsWith('.js') && !file.endsWith('.d.ts') && !file.endsWith('.d.ts.map'),
43
+ );
44
+
45
+ if (jsMigrationFiles.length === 0) {
46
+ log.info('No migration files found');
47
+ return [];
48
+ }
49
+
36
50
  const appliedMigrations = await runner({
37
51
  databaseUrl,
38
- dir: join(__dirname, 'db', 'migrations'),
52
+ dir: migrationsDir,
39
53
  direction,
40
54
  migrationsTable: 'pgmigrations',
41
55
  count: direction === 'down' ? 1 : Infinity,
42
56
  verbose,
43
57
  log: msg => (verbose ? log.info(msg) : log.debug(msg)),
58
+ // Ignore TypeScript declaration files - node-pg-migrate will try to import them otherwise
59
+ ignorePattern: '.*\\.d\\.(ts|js)$|.*\\.d\\.ts\\.map$',
44
60
  });
45
61
 
46
62
  if (appliedMigrations.length === 0) {
@@ -8,9 +8,15 @@ 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
10
 
11
- import { type CheckAndRecordParams, type DeleteDutyParams, DutyStatus, type RecordSuccessParams } from './db/types.js';
11
+ import {
12
+ type CheckAndRecordParams,
13
+ type DeleteDutyParams,
14
+ DutyStatus,
15
+ type RecordSuccessParams,
16
+ getBlockIndexFromDutyIdentifier,
17
+ } from './db/types.js';
12
18
  import { DutyAlreadySignedError, SlashingProtectionError } from './errors.js';
13
- import type { SlashingProtectionConfig, SlashingProtectionDatabase } from './types.js';
19
+ import type { SlashingProtectionDatabase, ValidatorHASignerConfig } from './types.js';
14
20
 
15
21
  /**
16
22
  * Slashing Protection Service
@@ -31,22 +37,22 @@ export class SlashingProtectionService {
31
37
  private readonly log: Logger;
32
38
  private readonly pollingIntervalMs: number;
33
39
  private readonly signingTimeoutMs: number;
40
+ private readonly maxStuckDutiesAgeMs: number;
34
41
 
35
42
  private cleanupRunningPromise: RunningPromise;
43
+ private lastOldDutiesCleanupAtMs?: number;
36
44
 
37
45
  constructor(
38
46
  private readonly db: SlashingProtectionDatabase,
39
- private readonly config: SlashingProtectionConfig,
47
+ private readonly config: ValidatorHASignerConfig,
40
48
  ) {
41
49
  this.log = createLogger('slashing-protection');
42
50
  this.pollingIntervalMs = config.pollingIntervalMs;
43
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;
44
54
 
45
- this.cleanupRunningPromise = new RunningPromise(
46
- this.cleanupStuckDuties.bind(this),
47
- this.log,
48
- this.config.maxStuckDutiesAgeMs,
49
- );
55
+ this.cleanupRunningPromise = new RunningPromise(this.cleanup.bind(this), this.log, this.maxStuckDutiesAgeMs);
50
56
  }
51
57
 
52
58
  /**
@@ -58,7 +64,6 @@ export class SlashingProtectionService {
58
64
  * 2. If insert succeeds, we acquired the lock - return the lockToken
59
65
  * 3. If a record exists, handle based on status:
60
66
  * - SIGNED: Throw appropriate error (already signed or slashing protection)
61
- * - FAILED: Delete the failed record
62
67
  * - SIGNING: Wait and poll until status changes, then handle result
63
68
  *
64
69
  * @returns The lockToken that must be used for recordSuccess/deleteDuty
@@ -98,9 +103,16 @@ export class SlashingProtectionService {
98
103
  existingNodeId: record.nodeId,
99
104
  attemptingNodeId: nodeId,
100
105
  });
101
- throw new SlashingProtectionError(slot, dutyType, record.messageHash, messageHash);
106
+ throw new SlashingProtectionError(
107
+ slot,
108
+ dutyType,
109
+ record.blockIndexWithinCheckpoint,
110
+ record.messageHash,
111
+ messageHash,
112
+ record.nodeId,
113
+ );
102
114
  }
103
- throw new DutyAlreadySignedError(slot, dutyType, record.nodeId);
115
+ throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
104
116
  } else if (record.status === DutyStatus.SIGNING) {
105
117
  // Another node is currently signing - check for timeout
106
118
  if (Date.now() - startTime > this.signingTimeoutMs) {
@@ -109,7 +121,7 @@ export class SlashingProtectionService {
109
121
  timeoutMs: this.signingTimeoutMs,
110
122
  signingNodeId: record.nodeId,
111
123
  });
112
- throw new DutyAlreadySignedError(slot, dutyType, 'unknown (timeout)');
124
+ throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
113
125
  }
114
126
 
115
127
  // Wait and poll
@@ -133,9 +145,18 @@ export class SlashingProtectionService {
133
145
  * @returns true if the update succeeded, false if token didn't match
134
146
  */
135
147
  async recordSuccess(params: RecordSuccessParams): Promise<boolean> {
136
- const { validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
148
+ const { rollupAddress, validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
149
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
137
150
 
138
- const success = await this.db.updateDutySigned(validatorAddress, slot, dutyType, signature.toString(), lockToken);
151
+ const success = await this.db.updateDutySigned(
152
+ rollupAddress,
153
+ validatorAddress,
154
+ slot,
155
+ dutyType,
156
+ signature.toString(),
157
+ lockToken,
158
+ blockIndexWithinCheckpoint,
159
+ );
139
160
 
140
161
  if (success) {
141
162
  this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
@@ -160,9 +181,17 @@ export class SlashingProtectionService {
160
181
  * @returns true if the delete succeeded, false if token didn't match
161
182
  */
162
183
  async deleteDuty(params: DeleteDutyParams): Promise<boolean> {
163
- const { validatorAddress, slot, dutyType, lockToken } = params;
184
+ const { rollupAddress, validatorAddress, slot, dutyType, lockToken } = params;
185
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
164
186
 
165
- const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken);
187
+ const success = await this.db.deleteDuty(
188
+ rollupAddress,
189
+ validatorAddress,
190
+ slot,
191
+ dutyType,
192
+ lockToken,
193
+ blockIndexWithinCheckpoint,
194
+ );
166
195
 
167
196
  if (success) {
168
197
  this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
@@ -188,7 +217,19 @@ export class SlashingProtectionService {
188
217
  * Start running tasks.
189
218
  * Cleanup runs immediately on start to recover from any previous crashes.
190
219
  */
191
- start() {
220
+ /**
221
+ * Start the background cleanup task.
222
+ * Also performs one-time cleanup of duties with outdated rollup addresses.
223
+ */
224
+ async start() {
225
+ // One-time cleanup at startup: remove duties from previous rollup versions
226
+ const numOutdatedRollupDuties = await this.db.cleanupOutdatedRollupDuties(this.config.l1Contracts.rollupAddress);
227
+ if (numOutdatedRollupDuties > 0) {
228
+ this.log.info(`Cleaned up ${numOutdatedRollupDuties} duties with outdated rollup address at startup`, {
229
+ currentRollupAddress: this.config.l1Contracts.rollupAddress.toString(),
230
+ });
231
+ }
232
+
192
233
  this.cleanupRunningPromise.start();
193
234
  this.log.info('Slashing protection service started', { nodeId: this.config.nodeId });
194
235
  }
@@ -202,15 +243,45 @@ export class SlashingProtectionService {
202
243
  }
203
244
 
204
245
  /**
205
- * Cleanup own stuck duties
246
+ * Close the database connection.
247
+ * Should be called after stop() during graceful shutdown.
206
248
  */
207
- private async cleanupStuckDuties() {
208
- const numDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.config.maxStuckDutiesAgeMs);
209
- if (numDuties > 0) {
210
- this.log.info(`Cleaned up ${numDuties} stuck duties`, {
249
+ async close() {
250
+ await this.db.close();
251
+ this.log.info('Slashing protection database connection closed');
252
+ }
253
+
254
+ /**
255
+ * Periodic cleanup of stuck duties and optionally old signed duties.
256
+ * Runs in the background via RunningPromise.
257
+ */
258
+ private async cleanup() {
259
+ // 1. Clean up stuck duties (our own node's duties that got stuck in 'signing' status)
260
+ const numStuckDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
261
+ if (numStuckDuties > 0) {
262
+ this.log.verbose(`Cleaned up ${numStuckDuties} stuck duties`, {
211
263
  nodeId: this.config.nodeId,
212
- maxStuckDutiesAgeMs: this.config.maxStuckDutiesAgeMs,
264
+ maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs,
213
265
  });
214
266
  }
267
+
268
+ // 2. Clean up old signed duties if configured
269
+ // we shouldn't run this as often as stuck duty cleanup.
270
+ if (this.config.cleanupOldDutiesAfterHours !== undefined) {
271
+ const maxAgeMs = this.config.cleanupOldDutiesAfterHours * 60 * 60 * 1000;
272
+ const nowMs = Date.now();
273
+ const shouldRun =
274
+ this.lastOldDutiesCleanupAtMs === undefined || nowMs - this.lastOldDutiesCleanupAtMs >= maxAgeMs;
275
+ if (shouldRun) {
276
+ const numOldDuties = await this.db.cleanupOldDuties(maxAgeMs);
277
+ this.lastOldDutiesCleanupAtMs = nowMs;
278
+ if (numOldDuties > 0) {
279
+ this.log.verbose(`Cleaned up ${numOldDuties} old signed duties`, {
280
+ cleanupOldDutiesAfterHours: this.config.cleanupOldDutiesAfterHours,
281
+ maxAgeMs,
282
+ });
283
+ }
284
+ }
285
+ }
215
286
  }
216
287
  }
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Vendored pg-compatible Pool/Client wrapper for PGlite.
3
+ *
4
+ * Copied from @middle-management/pglite-pg-adapter v0.0.3
5
+ * https://www.npmjs.com/package/@middle-management/pglite-pg-adapter
6
+ *
7
+ * Modifications:
8
+ * - Converted to ESM and TypeScript
9
+ * - Uses PGliteInterface instead of PGlite class to avoid TypeScript
10
+ * type mismatches from ESM/CJS dual package resolution with private fields
11
+ * - Simplified rowCount calculation to handle CTEs properly
12
+ */
13
+ import type { PGliteInterface } from '@electric-sql/pglite';
14
+ import { EventEmitter } from 'events';
15
+ import type { QueryResult, QueryResultRow } from 'pg';
16
+ import { Readable, Writable } from 'stream';
17
+
18
+ export interface PoolConfig {
19
+ pglite: PGliteInterface;
20
+ max?: number;
21
+ min?: number;
22
+ }
23
+
24
+ interface ClientConfig {
25
+ pglite: PGliteInterface;
26
+ host?: string;
27
+ port?: number;
28
+ ssl?: boolean;
29
+ }
30
+
31
+ export class Client extends EventEmitter {
32
+ protected pglite: PGliteInterface;
33
+ protected _connected = false;
34
+ readonly host: string;
35
+ readonly port: number;
36
+ readonly ssl: boolean;
37
+ readonly connection: object;
38
+
39
+ // Stub implementations for pg compatibility
40
+ readonly copyFrom = (): Writable => new Writable();
41
+ readonly copyTo = (): Readable => new Readable();
42
+ readonly pauseDrain = (): void => {};
43
+ readonly resumeDrain = (): void => {};
44
+ readonly escapeLiteral = (str: string): string => `'${str.replace(/'/g, "''")}'`;
45
+ readonly escapeIdentifier = (str: string): string => `"${str.replace(/"/g, '""')}"`;
46
+ readonly setTypeParser = (): void => {};
47
+ readonly getTypeParser = (): ((value: string) => unknown) => (value: string) => value;
48
+
49
+ constructor(config: ClientConfig) {
50
+ super();
51
+ this.pglite = config.pglite;
52
+ this.host = config.host || 'localhost';
53
+ this.port = config.port || 5432;
54
+ this.ssl = typeof config.ssl === 'boolean' ? config.ssl : !!config.ssl;
55
+ this.connection = {};
56
+ }
57
+
58
+ connect(): Promise<void> {
59
+ if (this._connected) {
60
+ return Promise.resolve();
61
+ }
62
+ this._connected = true;
63
+ this.emit('connect');
64
+ return Promise.resolve();
65
+ }
66
+
67
+ end(): Promise<void> {
68
+ if (!this._connected) {
69
+ return Promise.resolve();
70
+ }
71
+ this._connected = false;
72
+ this.emit('end');
73
+ return Promise.resolve();
74
+ }
75
+
76
+ async query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>> {
77
+ if (!this._connected) {
78
+ throw new Error('Client is not connected');
79
+ }
80
+ const result = await this.pglite.query<R>(text, values);
81
+ return this.convertPGliteResult(result);
82
+ }
83
+
84
+ protected convertPGliteResult<R extends QueryResultRow>(result: {
85
+ rows: R[];
86
+ fields: Array<{ name: string; dataTypeID: number }>;
87
+ affectedRows?: number;
88
+ }): QueryResult<R> {
89
+ return {
90
+ command: '',
91
+ rowCount: 'affectedRows' in result ? (result.affectedRows ?? 0) : result.rows.length,
92
+ oid: 0,
93
+ fields: result.fields.map(field => ({
94
+ name: field.name,
95
+ tableID: 0,
96
+ columnID: 0,
97
+ dataTypeID: field.dataTypeID,
98
+ dataTypeSize: -1,
99
+ dataTypeModifier: -1,
100
+ format: 'text',
101
+ })),
102
+ rows: result.rows,
103
+ };
104
+ }
105
+
106
+ get connected(): boolean {
107
+ return this._connected;
108
+ }
109
+ }
110
+
111
+ export class Pool extends EventEmitter {
112
+ private clients: PoolClient[] = [];
113
+ private availableClients: PoolClient[] = [];
114
+ private waitingQueue: Array<(client: PoolClient) => void> = [];
115
+ private _ended = false;
116
+ private pglite: PGliteInterface;
117
+ private _config: PoolConfig;
118
+
119
+ readonly expiredCount = 0;
120
+ readonly options: PoolConfig;
121
+
122
+ constructor(config: PoolConfig) {
123
+ super();
124
+ this._config = { max: 10, min: 0, ...config };
125
+ this.pglite = config.pglite;
126
+ this.options = config;
127
+ }
128
+
129
+ get totalCount(): number {
130
+ return this.clients.length;
131
+ }
132
+
133
+ get idleCount(): number {
134
+ return this.availableClients.length;
135
+ }
136
+
137
+ get waitingCount(): number {
138
+ return this.waitingQueue.length;
139
+ }
140
+
141
+ get ending(): boolean {
142
+ return this._ended;
143
+ }
144
+
145
+ get ended(): boolean {
146
+ return this._ended;
147
+ }
148
+
149
+ connect(): Promise<PoolClient> {
150
+ if (this._ended) {
151
+ return Promise.reject(new Error('Pool is ended'));
152
+ }
153
+
154
+ if (this.availableClients.length > 0) {
155
+ const client = this.availableClients.pop()!;
156
+ client._markInUse();
157
+ return Promise.resolve(client);
158
+ }
159
+
160
+ if (this.clients.length < (this._config.max || 10)) {
161
+ const client = new PoolClient(this.pglite, this);
162
+ this.clients.push(client);
163
+ return Promise.resolve(client);
164
+ }
165
+
166
+ return new Promise(resolve => {
167
+ this.waitingQueue.push(resolve);
168
+ });
169
+ }
170
+
171
+ async query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>> {
172
+ const client = await this.connect();
173
+ try {
174
+ return await client.query<R>(text, values);
175
+ } finally {
176
+ client.release();
177
+ }
178
+ }
179
+
180
+ releaseClient(client: PoolClient): void {
181
+ const index = this.clients.indexOf(client);
182
+ if (index !== -1) {
183
+ client._markAvailable();
184
+ if (this.waitingQueue.length > 0) {
185
+ const resolve = this.waitingQueue.shift()!;
186
+ client._markInUse();
187
+ resolve(client);
188
+ } else {
189
+ this.availableClients.push(client);
190
+ }
191
+ }
192
+ }
193
+
194
+ end(): Promise<void> {
195
+ this._ended = true;
196
+ this.clients.forEach(client => client._markReleased());
197
+ this.clients = [];
198
+ this.availableClients = [];
199
+ this.emit('end');
200
+ return Promise.resolve();
201
+ }
202
+ }
203
+
204
+ export class PoolClient extends Client {
205
+ private pool: Pool;
206
+ private _released = false;
207
+ private _inUse = true;
208
+ private _userReleased = false;
209
+
210
+ constructor(pglite: PGliteInterface, pool: Pool) {
211
+ super({ pglite });
212
+ this.pool = pool;
213
+ this._connected = true;
214
+ }
215
+
216
+ override async query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>> {
217
+ if (this._userReleased && !this._inUse) {
218
+ throw new Error('Client has been released back to the pool');
219
+ }
220
+ const result = await this.pglite.query<R>(text, values);
221
+ return this.convertPGliteResult(result);
222
+ }
223
+
224
+ release(): void {
225
+ if (this._released || this._userReleased) {
226
+ return;
227
+ }
228
+ this._userReleased = true;
229
+ this.pool.releaseClient(this);
230
+ }
231
+
232
+ override end(): Promise<void> {
233
+ this.release();
234
+ return Promise.resolve();
235
+ }
236
+
237
+ _markInUse(): void {
238
+ this._inUse = true;
239
+ this._userReleased = false;
240
+ }
241
+
242
+ _markAvailable(): void {
243
+ this._inUse = false;
244
+ this._userReleased = false;
245
+ }
246
+
247
+ _markReleased(): void {
248
+ this._released = true;
249
+ this._inUse = false;
250
+ this._userReleased = true;
251
+ }
252
+
253
+ override get connected(): boolean {
254
+ return this._connected && !this._released;
255
+ }
256
+ }
package/src/types.ts CHANGED
@@ -1,27 +1,38 @@
1
+ import {
2
+ BlockNumber,
3
+ type CheckpointNumber,
4
+ type IndexWithinCheckpoint,
5
+ type SlotNumber,
6
+ } from '@aztec/foundation/branded-types';
1
7
  import type { EthAddress } from '@aztec/foundation/eth-address';
2
8
 
3
9
  import type { Pool } from 'pg';
4
10
 
5
- import type { CreateHASignerConfig, SlashingProtectionConfig } from './config.js';
6
- import type {
7
- CheckAndRecordParams,
8
- DeleteDutyParams,
9
- DutyIdentifier,
11
+ import type { ValidatorHASignerConfig } from './config.js';
12
+ import {
13
+ type BlockProposalDutyIdentifier,
14
+ type CheckAndRecordParams,
15
+ type DeleteDutyParams,
16
+ type DutyIdentifier,
17
+ type DutyRow,
10
18
  DutyType,
11
- RecordSuccessParams,
12
- ValidatorDutyRecord,
19
+ type OtherDutyIdentifier,
20
+ type RecordSuccessParams,
21
+ type ValidatorDutyRecord,
13
22
  } from './db/types.js';
14
23
 
15
24
  export type {
25
+ BlockProposalDutyIdentifier,
16
26
  CheckAndRecordParams,
17
- CreateHASignerConfig,
18
27
  DeleteDutyParams,
19
28
  DutyIdentifier,
29
+ DutyRow,
30
+ OtherDutyIdentifier,
20
31
  RecordSuccessParams,
21
- SlashingProtectionConfig,
22
32
  ValidatorDutyRecord,
33
+ ValidatorHASignerConfig,
23
34
  };
24
- export { DutyStatus, DutyType } from './db/types.js';
35
+ export { DutyStatus, DutyType, getBlockIndexFromDutyIdentifier, normalizeBlockIndex } from './db/types.js';
25
36
 
26
37
  /**
27
38
  * Result of tryInsertOrGetExisting operation
@@ -45,17 +56,97 @@ export interface CreateHASignerDeps {
45
56
  }
46
57
 
47
58
  /**
48
- * Context required for slashing protection during signing operations
59
+ * Base context for signing operations
49
60
  */
50
- export interface SigningContext {
61
+ interface BaseSigningContext {
51
62
  /** Slot number for this duty */
52
- slot: bigint;
53
- /** Block number for this duty */
54
- blockNumber: bigint;
55
- /** Type of duty being performed */
56
- dutyType: DutyType;
63
+ slot: SlotNumber;
64
+ /**
65
+ * Block or checkpoint number for this duty.
66
+ * For block proposals, this is the block number.
67
+ * For checkpoint proposals, this is the checkpoint number.
68
+ */
69
+ blockNumber: BlockNumber | CheckpointNumber;
70
+ }
71
+
72
+ /**
73
+ * Signing context for block proposals.
74
+ * blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
75
+ */
76
+ export interface BlockProposalSigningContext extends BaseSigningContext {
77
+ /** Block index within checkpoint (0, 1, 2...). Required for block proposals. */
78
+ blockIndexWithinCheckpoint: IndexWithinCheckpoint;
79
+ dutyType: DutyType.BLOCK_PROPOSAL;
80
+ }
81
+
82
+ /**
83
+ * Signing context for non-block-proposal duties that require HA protection.
84
+ * blockIndexWithinCheckpoint is not applicable (internally always -1).
85
+ */
86
+ export interface OtherSigningContext extends BaseSigningContext {
87
+ dutyType: DutyType.CHECKPOINT_PROPOSAL | DutyType.ATTESTATION | DutyType.ATTESTATIONS_AND_SIGNERS;
88
+ }
89
+
90
+ /**
91
+ * Signing context for governance/slashing votes which only need slot for HA protection.
92
+ * blockNumber is not applicable (internally always 0).
93
+ */
94
+ export interface VoteSigningContext {
95
+ slot: SlotNumber;
96
+ dutyType: DutyType.GOVERNANCE_VOTE | DutyType.SLASHING_VOTE;
97
+ }
98
+
99
+ /**
100
+ * Signing context for duties which don't require slot/blockNumber
101
+ * as they don't need HA protection (AUTH_REQUEST, TXS).
102
+ */
103
+ export interface NoHAProtectionSigningContext {
104
+ dutyType: DutyType.AUTH_REQUEST | DutyType.TXS;
105
+ }
106
+
107
+ /**
108
+ * Signing contexts that require HA protection (excludes AUTH_REQUEST).
109
+ * Used by the HA signer's signWithProtection method.
110
+ */
111
+ export type HAProtectedSigningContext = BlockProposalSigningContext | OtherSigningContext | VoteSigningContext;
112
+
113
+ /**
114
+ * Type guard to check if a SigningContext requires HA protection.
115
+ * Returns true for contexts that need HA protection, false for AUTH_REQUEST and TXS.
116
+ */
117
+ export function isHAProtectedContext(context: SigningContext): context is HAProtectedSigningContext {
118
+ return context.dutyType !== DutyType.AUTH_REQUEST && context.dutyType !== DutyType.TXS;
57
119
  }
58
120
 
121
+ /**
122
+ * Gets the block number from a signing context.
123
+ * - Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE): returns BlockNumber(0)
124
+ * - Other duties: returns the blockNumber from the context
125
+ */
126
+ export function getBlockNumberFromSigningContext(context: HAProtectedSigningContext): BlockNumber | CheckpointNumber {
127
+ // Check for duty types that have blockNumber
128
+ if (
129
+ context.dutyType === DutyType.BLOCK_PROPOSAL ||
130
+ context.dutyType === DutyType.CHECKPOINT_PROPOSAL ||
131
+ context.dutyType === DutyType.ATTESTATION ||
132
+ context.dutyType === DutyType.ATTESTATIONS_AND_SIGNERS
133
+ ) {
134
+ return context.blockNumber;
135
+ }
136
+ // Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE) don't have blockNumber
137
+ return BlockNumber(0);
138
+ }
139
+
140
+ /**
141
+ * Context required for slashing protection during signing operations.
142
+ * Uses discriminated union to enforce type safety:
143
+ * - BLOCK_PROPOSAL duties MUST have blockIndexWithinCheckpoint >= 0
144
+ * - Other duty types do NOT have blockIndexWithinCheckpoint (internally -1)
145
+ * - Vote duties only need slot (blockNumber is internally 0)
146
+ * - AUTH_REQUEST and TXS duties don't need slot/blockNumber (no HA protection needed)
147
+ */
148
+ export type SigningContext = HAProtectedSigningContext | NoHAProtectionSigningContext;
149
+
59
150
  /**
60
151
  * Database interface for slashing protection operations
61
152
  * This abstraction allows for different database implementations (PostgreSQL, SQLite, etc.)
@@ -81,11 +172,13 @@ export interface SlashingProtectionDatabase {
81
172
  * @returns true if the update succeeded, false if token didn't match or duty not found
82
173
  */
83
174
  updateDutySigned(
175
+ rollupAddress: EthAddress,
84
176
  validatorAddress: EthAddress,
85
- slot: bigint,
177
+ slot: SlotNumber,
86
178
  dutyType: DutyType,
87
179
  signature: string,
88
180
  lockToken: string,
181
+ blockIndexWithinCheckpoint: number,
89
182
  ): Promise<boolean>;
90
183
 
91
184
  /**
@@ -95,11 +188,39 @@ export interface SlashingProtectionDatabase {
95
188
  *
96
189
  * @returns true if the delete succeeded, false if token didn't match or duty not found
97
190
  */
98
- deleteDuty(validatorAddress: EthAddress, slot: bigint, dutyType: DutyType, lockToken: string): Promise<boolean>;
191
+ deleteDuty(
192
+ rollupAddress: EthAddress,
193
+ validatorAddress: EthAddress,
194
+ slot: SlotNumber,
195
+ dutyType: DutyType,
196
+ lockToken: string,
197
+ blockIndexWithinCheckpoint: number,
198
+ ): Promise<boolean>;
99
199
 
100
200
  /**
101
201
  * Cleanup own stuck duties
102
202
  * @returns the number of duties cleaned up
103
203
  */
104
204
  cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
205
+
206
+ /**
207
+ * Cleanup duties with outdated rollup address.
208
+ * Removes all duties where the rollup address doesn't match the current one.
209
+ * Used after a rollup upgrade to clean up duties for the old rollup.
210
+ * @returns the number of duties cleaned up
211
+ */
212
+ cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number>;
213
+
214
+ /**
215
+ * Cleanup old signed duties.
216
+ * Removes only signed duties older than the specified age.
217
+ * @returns the number of duties cleaned up
218
+ */
219
+ cleanupOldDuties(maxAgeMs: number): Promise<number>;
220
+
221
+ /**
222
+ * Close the database connection.
223
+ * Should be called during graceful shutdown.
224
+ */
225
+ close(): Promise<void>;
105
226
  }