@aztec/validator-ha-signer 0.0.1-commit.0208eb9

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 (58) hide show
  1. package/README.md +187 -0
  2. package/dest/config.d.ts +101 -0
  3. package/dest/config.d.ts.map +1 -0
  4. package/dest/config.js +92 -0
  5. package/dest/db/index.d.ts +4 -0
  6. package/dest/db/index.d.ts.map +1 -0
  7. package/dest/db/index.js +3 -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 +84 -0
  12. package/dest/db/postgres.d.ts.map +1 -0
  13. package/dest/db/postgres.js +210 -0
  14. package/dest/db/schema.d.ts +95 -0
  15. package/dest/db/schema.d.ts.map +1 -0
  16. package/dest/db/schema.js +229 -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 +166 -0
  21. package/dest/db/types.d.ts.map +1 -0
  22. package/dest/db/types.js +49 -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 +42 -0
  27. package/dest/factory.d.ts.map +1 -0
  28. package/dest/factory.js +70 -0
  29. package/dest/migrations.d.ts +15 -0
  30. package/dest/migrations.d.ts.map +1 -0
  31. package/dest/migrations.js +53 -0
  32. package/dest/slashing_protection_service.d.ts +84 -0
  33. package/dest/slashing_protection_service.d.ts.map +1 -0
  34. package/dest/slashing_protection_service.js +225 -0
  35. package/dest/test/pglite_pool.d.ts +92 -0
  36. package/dest/test/pglite_pool.d.ts.map +1 -0
  37. package/dest/test/pglite_pool.js +210 -0
  38. package/dest/types.d.ts +152 -0
  39. package/dest/types.d.ts.map +1 -0
  40. package/dest/types.js +21 -0
  41. package/dest/validator_ha_signer.d.ts +71 -0
  42. package/dest/validator_ha_signer.d.ts.map +1 -0
  43. package/dest/validator_ha_signer.js +132 -0
  44. package/package.json +106 -0
  45. package/src/config.ts +149 -0
  46. package/src/db/index.ts +3 -0
  47. package/src/db/migrations/1_initial-schema.ts +26 -0
  48. package/src/db/postgres.ts +284 -0
  49. package/src/db/schema.ts +266 -0
  50. package/src/db/test_helper.ts +17 -0
  51. package/src/db/types.ts +206 -0
  52. package/src/errors.ts +47 -0
  53. package/src/factory.ts +82 -0
  54. package/src/migrations.ts +75 -0
  55. package/src/slashing_protection_service.ts +287 -0
  56. package/src/test/pglite_pool.ts +256 -0
  57. package/src/types.ts +226 -0
  58. package/src/validator_ha_signer.ts +162 -0
@@ -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 { BlockNumber, 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 } 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
+ */
225
+ private rowToRecord(row: DutyRow): ValidatorDutyRecord {
226
+ return {
227
+ rollupAddress: EthAddress.fromString(row.rollup_address),
228
+ validatorAddress: EthAddress.fromString(row.validator_address),
229
+ slot: SlotNumber.fromString(row.slot),
230
+ blockNumber: BlockNumber.fromString(row.block_number),
231
+ blockIndexWithinCheckpoint: row.block_index_within_checkpoint,
232
+ dutyType: row.duty_type,
233
+ status: row.status,
234
+ messageHash: row.message_hash,
235
+ signature: row.signature ?? undefined,
236
+ nodeId: row.node_id,
237
+ lockToken: row.lock_token,
238
+ startedAt: row.started_at,
239
+ completedAt: row.completed_at ?? undefined,
240
+ errorMessage: row.error_message ?? undefined,
241
+ };
242
+ }
243
+
244
+ /**
245
+ * Close the database connection pool
246
+ */
247
+ async close(): Promise<void> {
248
+ await this.pool.end();
249
+ this.log.info('Database connection pool closed');
250
+ }
251
+
252
+ /**
253
+ * Cleanup own stuck duties
254
+ * @returns the number of duties cleaned up
255
+ */
256
+ async cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
257
+ const cutoff = new Date(Date.now() - maxAgeMs);
258
+ const result = await this.pool.query(CLEANUP_OWN_STUCK_DUTIES, [nodeId, cutoff]);
259
+ return result.rowCount ?? 0;
260
+ }
261
+
262
+ /**
263
+ * Cleanup duties with outdated rollup address.
264
+ * Removes all duties where the rollup address doesn't match the current one.
265
+ * Used after a rollup upgrade to clean up duties for the old rollup.
266
+ * @returns the number of duties cleaned up
267
+ */
268
+ async cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number> {
269
+ const result = await this.pool.query(CLEANUP_OUTDATED_ROLLUP_DUTIES, [currentRollupAddress.toString()]);
270
+ return result.rowCount ?? 0;
271
+ }
272
+
273
+ /**
274
+ * Cleanup old signed duties.
275
+ * Removes only signed duties older than the specified age.
276
+ * Does not remove 'signing' duties as they may be in progress.
277
+ * @returns the number of duties cleaned up
278
+ */
279
+ async cleanupOldDuties(maxAgeMs: number): Promise<number> {
280
+ const cutoff = new Date(Date.now() - maxAgeMs);
281
+ const result = await this.pool.query(CLEANUP_OLD_DUTIES, [cutoff]);
282
+ return result.rowCount ?? 0;
283
+ }
284
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * SQL schema for the validator_duties table
3
+ *
4
+ * This table is used for distributed locking and slashing protection across multiple validator nodes.
5
+ * The PRIMARY KEY constraint ensures that only one node can acquire the lock for a given validator,
6
+ * slot, and duty type combination.
7
+ */
8
+
9
+ /**
10
+ * Current schema version
11
+ */
12
+ export const SCHEMA_VERSION = 1;
13
+
14
+ /**
15
+ * SQL to create the validator_duties table
16
+ */
17
+ export const CREATE_VALIDATOR_DUTIES_TABLE = `
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
+ `;
38
+
39
+ /**
40
+ * SQL to create index on status and started_at for cleanup queries
41
+ */
42
+ export const CREATE_STATUS_INDEX = `
43
+ CREATE INDEX IF NOT EXISTS idx_validator_duties_status
44
+ ON validator_duties(status, started_at);
45
+ `;
46
+
47
+ /**
48
+ * SQL to create index for querying duties by node
49
+ */
50
+ export const CREATE_NODE_INDEX = `
51
+ CREATE INDEX IF NOT EXISTS idx_validator_duties_node
52
+ ON validator_duties(node_id, started_at);
53
+ `;
54
+
55
+ /**
56
+ * SQL to create the schema_version table for tracking migrations
57
+ */
58
+ export const CREATE_SCHEMA_VERSION_TABLE = `
59
+ CREATE TABLE IF NOT EXISTS schema_version (
60
+ version INTEGER PRIMARY KEY,
61
+ applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
62
+ );
63
+ `;
64
+
65
+ /**
66
+ * SQL to initialize schema version
67
+ */
68
+ export const INSERT_SCHEMA_VERSION = `
69
+ INSERT INTO schema_version (version)
70
+ VALUES ($1)
71
+ ON CONFLICT (version) DO NOTHING;
72
+ `;
73
+
74
+ /**
75
+ * Complete schema setup - all statements in order
76
+ */
77
+ export const SCHEMA_SETUP = [
78
+ CREATE_SCHEMA_VERSION_TABLE,
79
+ CREATE_VALIDATOR_DUTIES_TABLE,
80
+ CREATE_STATUS_INDEX,
81
+ CREATE_NODE_INDEX,
82
+ ] as const;
83
+
84
+ /**
85
+ * Query to get current schema version
86
+ */
87
+ export const GET_SCHEMA_VERSION = `
88
+ SELECT version FROM schema_version ORDER BY version DESC LIMIT 1;
89
+ `;
90
+
91
+ /**
92
+ * Atomic insert-or-get query.
93
+ * Tries to insert a new duty record. If a record already exists (conflict),
94
+ * returns the existing record instead.
95
+ *
96
+ * Returns the record with an `is_new` flag indicating whether we inserted or got existing.
97
+ *
98
+ * Note: In high concurrency scenarios, if the INSERT conflicts and another transaction
99
+ * just committed the row, there's a small window where the SELECT might not see it yet.
100
+ * The application layer should retry if no rows are returned.
101
+ */
102
+ export const INSERT_OR_GET_DUTY = `
103
+ WITH inserted AS (
104
+ INSERT INTO validator_duties (
105
+ rollup_address,
106
+ validator_address,
107
+ slot,
108
+ block_number,
109
+ block_index_within_checkpoint,
110
+ duty_type,
111
+ status,
112
+ message_hash,
113
+ node_id,
114
+ lock_token,
115
+ started_at
116
+ ) VALUES ($1, $2, $3, $4, $5, $6, 'signing', $7, $8, $9, CURRENT_TIMESTAMP)
117
+ ON CONFLICT (rollup_address, validator_address, slot, duty_type, block_index_within_checkpoint) DO NOTHING
118
+ RETURNING
119
+ rollup_address,
120
+ validator_address,
121
+ slot,
122
+ block_number,
123
+ block_index_within_checkpoint,
124
+ duty_type,
125
+ status,
126
+ message_hash,
127
+ signature,
128
+ node_id,
129
+ lock_token,
130
+ started_at,
131
+ completed_at,
132
+ error_message,
133
+ TRUE as is_new
134
+ )
135
+ SELECT * FROM inserted
136
+ UNION ALL
137
+ SELECT
138
+ rollup_address,
139
+ validator_address,
140
+ slot,
141
+ block_number,
142
+ block_index_within_checkpoint,
143
+ duty_type,
144
+ status,
145
+ message_hash,
146
+ signature,
147
+ node_id,
148
+ '' as lock_token,
149
+ started_at,
150
+ completed_at,
151
+ error_message,
152
+ FALSE as is_new
153
+ FROM validator_duties
154
+ WHERE rollup_address = $1
155
+ AND validator_address = $2
156
+ AND slot = $3
157
+ AND duty_type = $6
158
+ AND block_index_within_checkpoint = $5
159
+ AND NOT EXISTS (SELECT 1 FROM inserted);
160
+ `;
161
+
162
+ /**
163
+ * Query to update a duty to 'signed' status
164
+ */
165
+ export const UPDATE_DUTY_SIGNED = `
166
+ UPDATE validator_duties
167
+ SET status = 'signed',
168
+ signature = $1,
169
+ completed_at = CURRENT_TIMESTAMP
170
+ WHERE rollup_address = $2
171
+ AND validator_address = $3
172
+ AND slot = $4
173
+ AND duty_type = $5
174
+ AND block_index_within_checkpoint = $6
175
+ AND status = 'signing'
176
+ AND lock_token = $7;
177
+ `;
178
+
179
+ /**
180
+ * Query to delete a duty
181
+ * Only deletes if the lockToken matches
182
+ */
183
+ export const DELETE_DUTY = `
184
+ DELETE FROM validator_duties
185
+ WHERE rollup_address = $1
186
+ AND validator_address = $2
187
+ AND slot = $3
188
+ AND duty_type = $4
189
+ AND block_index_within_checkpoint = $5
190
+ AND status = 'signing'
191
+ AND lock_token = $6;
192
+ `;
193
+
194
+ /**
195
+ * Query to clean up old signed duties (for maintenance)
196
+ * Removes signed duties older than a specified timestamp
197
+ */
198
+ export const CLEANUP_OLD_SIGNED_DUTIES = `
199
+ DELETE FROM validator_duties
200
+ WHERE status = 'signed'
201
+ AND completed_at < $1;
202
+ `;
203
+
204
+ /**
205
+ * Query to clean up old duties (for maintenance)
206
+ * Removes SIGNED duties older than a specified timestamp
207
+ */
208
+ export const CLEANUP_OLD_DUTIES = `
209
+ DELETE FROM validator_duties
210
+ WHERE status = 'signed'
211
+ AND started_at < $1;
212
+ `;
213
+
214
+ /**
215
+ * Query to cleanup own stuck duties
216
+ * Removes duties in 'signing' status for a specific node that are older than maxAgeMs
217
+ */
218
+ export const CLEANUP_OWN_STUCK_DUTIES = `
219
+ DELETE FROM validator_duties
220
+ WHERE node_id = $1
221
+ AND status = 'signing'
222
+ AND started_at < $2;
223
+ `;
224
+
225
+ /**
226
+ * Query to cleanup duties with outdated rollup address
227
+ * Removes all duties where the rollup address doesn't match the current one
228
+ * Used after a rollup upgrade to clean up duties for the old rollup
229
+ */
230
+ export const CLEANUP_OUTDATED_ROLLUP_DUTIES = `
231
+ DELETE FROM validator_duties
232
+ WHERE rollup_address != $1;
233
+ `;
234
+
235
+ /**
236
+ * SQL to drop the validator_duties table
237
+ */
238
+ export const DROP_VALIDATOR_DUTIES_TABLE = `DROP TABLE IF EXISTS validator_duties;`;
239
+
240
+ /**
241
+ * SQL to drop the schema_version table
242
+ */
243
+ export const DROP_SCHEMA_VERSION_TABLE = `DROP TABLE IF EXISTS schema_version;`;
244
+
245
+ /**
246
+ * Query to get stuck duties (for monitoring/alerting)
247
+ * Returns duties in 'signing' status that have been stuck for too long
248
+ */
249
+ export const GET_STUCK_DUTIES = `
250
+ SELECT
251
+ rollup_address,
252
+ validator_address,
253
+ slot,
254
+ block_number,
255
+ block_index_within_checkpoint,
256
+ duty_type,
257
+ status,
258
+ message_hash,
259
+ node_id,
260
+ started_at,
261
+ EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - started_at)) as age_seconds
262
+ FROM validator_duties
263
+ WHERE status = 'signing'
264
+ AND started_at < $1
265
+ ORDER BY started_at ASC;
266
+ `;
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Test helpers for database setup
3
+ */
4
+ import type { PGlite } from '@electric-sql/pglite';
5
+
6
+ import { INSERT_SCHEMA_VERSION, SCHEMA_SETUP, SCHEMA_VERSION } from './schema.js';
7
+
8
+ /**
9
+ * Set up the database schema for testing.
10
+ * This runs the same SQL that migrations would apply.
11
+ */
12
+ export async function setupTestSchema(pglite: PGlite): Promise<void> {
13
+ for (const statement of SCHEMA_SETUP) {
14
+ await pglite.query(statement);
15
+ }
16
+ await pglite.query(INSERT_SCHEMA_VERSION, [SCHEMA_VERSION]);
17
+ }