@aztec/validator-ha-signer 0.0.1-commit.023c3e5

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 +79 -0
  3. package/dest/config.d.ts.map +1 -0
  4. package/dest/config.js +73 -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 +70 -0
  12. package/dest/db/postgres.d.ts.map +1 -0
  13. package/dest/db/postgres.js +181 -0
  14. package/dest/db/schema.d.ts +89 -0
  15. package/dest/db/schema.d.ts.map +1 -0
  16. package/dest/db/schema.js +213 -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 +161 -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 +80 -0
  33. package/dest/slashing_protection_service.d.ts.map +1 -0
  34. package/dest/slashing_protection_service.js +196 -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 +139 -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 +70 -0
  42. package/dest/validator_ha_signer.d.ts.map +1 -0
  43. package/dest/validator_ha_signer.js +127 -0
  44. package/package.json +105 -0
  45. package/src/config.ts +125 -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 +251 -0
  49. package/src/db/schema.ts +248 -0
  50. package/src/db/test_helper.ts +17 -0
  51. package/src/db/types.ts +201 -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 +250 -0
  56. package/src/test/pglite_pool.ts +256 -0
  57. package/src/types.ts +207 -0
  58. package/src/validator_ha_signer.ts +157 -0
@@ -0,0 +1,248 @@
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
+ validator_address VARCHAR(42) NOT NULL,
20
+ slot BIGINT NOT NULL,
21
+ block_number BIGINT NOT NULL,
22
+ block_index_within_checkpoint INTEGER NOT NULL DEFAULT 0,
23
+ duty_type VARCHAR(30) NOT NULL CHECK (duty_type IN ('BLOCK_PROPOSAL', 'CHECKPOINT_PROPOSAL', 'ATTESTATION', 'ATTESTATIONS_AND_SIGNERS', 'GOVERNANCE_VOTE', 'SLASHING_VOTE')),
24
+ status VARCHAR(20) NOT NULL CHECK (status IN ('signing', 'signed', 'failed')),
25
+ message_hash VARCHAR(66) NOT NULL,
26
+ signature VARCHAR(132),
27
+ node_id VARCHAR(255) NOT NULL,
28
+ lock_token VARCHAR(64) NOT NULL,
29
+ started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
30
+ completed_at TIMESTAMP,
31
+ error_message TEXT,
32
+
33
+ PRIMARY KEY (validator_address, slot, duty_type, block_index_within_checkpoint),
34
+ CHECK (completed_at IS NULL OR completed_at >= started_at)
35
+ );
36
+ `;
37
+
38
+ /**
39
+ * SQL to create index on status and started_at for cleanup queries
40
+ */
41
+ export const CREATE_STATUS_INDEX = `
42
+ CREATE INDEX IF NOT EXISTS idx_validator_duties_status
43
+ ON validator_duties(status, started_at);
44
+ `;
45
+
46
+ /**
47
+ * SQL to create index for querying duties by node
48
+ */
49
+ export const CREATE_NODE_INDEX = `
50
+ CREATE INDEX IF NOT EXISTS idx_validator_duties_node
51
+ ON validator_duties(node_id, started_at);
52
+ `;
53
+
54
+ /**
55
+ * SQL to create the schema_version table for tracking migrations
56
+ */
57
+ export const CREATE_SCHEMA_VERSION_TABLE = `
58
+ CREATE TABLE IF NOT EXISTS schema_version (
59
+ version INTEGER PRIMARY KEY,
60
+ applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
61
+ );
62
+ `;
63
+
64
+ /**
65
+ * SQL to initialize schema version
66
+ */
67
+ export const INSERT_SCHEMA_VERSION = `
68
+ INSERT INTO schema_version (version)
69
+ VALUES ($1)
70
+ ON CONFLICT (version) DO NOTHING;
71
+ `;
72
+
73
+ /**
74
+ * Complete schema setup - all statements in order
75
+ */
76
+ export const SCHEMA_SETUP = [
77
+ CREATE_SCHEMA_VERSION_TABLE,
78
+ CREATE_VALIDATOR_DUTIES_TABLE,
79
+ CREATE_STATUS_INDEX,
80
+ CREATE_NODE_INDEX,
81
+ ] as const;
82
+
83
+ /**
84
+ * Query to get current schema version
85
+ */
86
+ export const GET_SCHEMA_VERSION = `
87
+ SELECT version FROM schema_version ORDER BY version DESC LIMIT 1;
88
+ `;
89
+
90
+ /**
91
+ * Atomic insert-or-get query.
92
+ * Tries to insert a new duty record. If a record already exists (conflict),
93
+ * returns the existing record instead.
94
+ *
95
+ * Returns the record with an `is_new` flag indicating whether we inserted or got existing.
96
+ *
97
+ * Note: In high concurrency scenarios, if the INSERT conflicts and another transaction
98
+ * just committed the row, there's a small window where the SELECT might not see it yet.
99
+ * The application layer should retry if no rows are returned.
100
+ */
101
+ export const INSERT_OR_GET_DUTY = `
102
+ WITH inserted AS (
103
+ INSERT INTO validator_duties (
104
+ validator_address,
105
+ slot,
106
+ block_number,
107
+ block_index_within_checkpoint,
108
+ duty_type,
109
+ status,
110
+ message_hash,
111
+ node_id,
112
+ lock_token,
113
+ started_at
114
+ ) VALUES ($1, $2, $3, $4, $5, 'signing', $6, $7, $8, CURRENT_TIMESTAMP)
115
+ ON CONFLICT (validator_address, slot, duty_type, block_index_within_checkpoint) DO NOTHING
116
+ RETURNING
117
+ validator_address,
118
+ slot,
119
+ block_number,
120
+ block_index_within_checkpoint,
121
+ duty_type,
122
+ status,
123
+ message_hash,
124
+ signature,
125
+ node_id,
126
+ lock_token,
127
+ started_at,
128
+ completed_at,
129
+ error_message,
130
+ TRUE as is_new
131
+ )
132
+ SELECT * FROM inserted
133
+ UNION ALL
134
+ SELECT
135
+ validator_address,
136
+ slot,
137
+ block_number,
138
+ block_index_within_checkpoint,
139
+ duty_type,
140
+ status,
141
+ message_hash,
142
+ signature,
143
+ node_id,
144
+ '' as lock_token,
145
+ started_at,
146
+ completed_at,
147
+ error_message,
148
+ FALSE as is_new
149
+ FROM validator_duties
150
+ WHERE validator_address = $1
151
+ AND slot = $2
152
+ AND duty_type = $5
153
+ AND block_index_within_checkpoint = $4
154
+ AND NOT EXISTS (SELECT 1 FROM inserted);
155
+ `;
156
+
157
+ /**
158
+ * Query to update a duty to 'signed' status
159
+ */
160
+ export const UPDATE_DUTY_SIGNED = `
161
+ UPDATE validator_duties
162
+ SET status = 'signed',
163
+ signature = $1,
164
+ completed_at = CURRENT_TIMESTAMP
165
+ WHERE validator_address = $2
166
+ AND slot = $3
167
+ AND duty_type = $4
168
+ AND block_index_within_checkpoint = $5
169
+ AND status = 'signing'
170
+ AND lock_token = $6;
171
+ `;
172
+
173
+ /**
174
+ * Query to delete a duty
175
+ * Only deletes if the lockToken matches
176
+ */
177
+ export const DELETE_DUTY = `
178
+ DELETE FROM validator_duties
179
+ WHERE validator_address = $1
180
+ AND slot = $2
181
+ AND duty_type = $3
182
+ AND block_index_within_checkpoint = $4
183
+ AND status = 'signing'
184
+ AND lock_token = $5;
185
+ `;
186
+
187
+ /**
188
+ * Query to clean up old signed duties (for maintenance)
189
+ * Removes signed duties older than a specified timestamp
190
+ */
191
+ export const CLEANUP_OLD_SIGNED_DUTIES = `
192
+ DELETE FROM validator_duties
193
+ WHERE status = 'signed'
194
+ AND completed_at < $1;
195
+ `;
196
+
197
+ /**
198
+ * Query to clean up old duties (for maintenance)
199
+ * Removes duties older than a specified timestamp
200
+ */
201
+ export const CLEANUP_OLD_DUTIES = `
202
+ DELETE FROM validator_duties
203
+ WHERE status IN ('signing', 'signed', 'failed')
204
+ AND started_at < $1;
205
+ `;
206
+
207
+ /**
208
+ * Query to cleanup own stuck duties
209
+ * Removes duties in 'signing' status for a specific node that are older than maxAgeMs
210
+ */
211
+ export const CLEANUP_OWN_STUCK_DUTIES = `
212
+ DELETE FROM validator_duties
213
+ WHERE node_id = $1
214
+ AND status = 'signing'
215
+ AND started_at < $2;
216
+ `;
217
+
218
+ /**
219
+ * SQL to drop the validator_duties table
220
+ */
221
+ export const DROP_VALIDATOR_DUTIES_TABLE = `DROP TABLE IF EXISTS validator_duties;`;
222
+
223
+ /**
224
+ * SQL to drop the schema_version table
225
+ */
226
+ export const DROP_SCHEMA_VERSION_TABLE = `DROP TABLE IF EXISTS schema_version;`;
227
+
228
+ /**
229
+ * Query to get stuck duties (for monitoring/alerting)
230
+ * Returns duties in 'signing' status that have been stuck for too long
231
+ */
232
+ export const GET_STUCK_DUTIES = `
233
+ SELECT
234
+ validator_address,
235
+ slot,
236
+ block_number,
237
+ block_index_within_checkpoint,
238
+ duty_type,
239
+ status,
240
+ message_hash,
241
+ node_id,
242
+ started_at,
243
+ EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - started_at)) as age_seconds
244
+ FROM validator_duties
245
+ WHERE status = 'signing'
246
+ AND started_at < $1
247
+ ORDER BY started_at ASC;
248
+ `;
@@ -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
+ }
@@ -0,0 +1,201 @@
1
+ import type { BlockNumber, CheckpointNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import type { EthAddress } from '@aztec/foundation/eth-address';
3
+ import type { Signature } from '@aztec/foundation/eth-signature';
4
+
5
+ /**
6
+ * Row type from PostgreSQL query
7
+ */
8
+ export interface DutyRow {
9
+ validator_address: string;
10
+ slot: string;
11
+ block_number: string;
12
+ block_index_within_checkpoint: number;
13
+ duty_type: DutyType;
14
+ status: DutyStatus;
15
+ message_hash: string;
16
+ signature: string | null;
17
+ node_id: string;
18
+ lock_token: string;
19
+ started_at: Date;
20
+ completed_at: Date | null;
21
+ error_message: string | null;
22
+ }
23
+
24
+ /**
25
+ * Row type from INSERT_OR_GET_DUTY query (includes is_new flag)
26
+ */
27
+ export interface InsertOrGetRow extends DutyRow {
28
+ is_new: boolean;
29
+ }
30
+
31
+ /**
32
+ * Type of validator duty being performed
33
+ */
34
+ export enum DutyType {
35
+ BLOCK_PROPOSAL = 'BLOCK_PROPOSAL',
36
+ CHECKPOINT_PROPOSAL = 'CHECKPOINT_PROPOSAL',
37
+ ATTESTATION = 'ATTESTATION',
38
+ ATTESTATIONS_AND_SIGNERS = 'ATTESTATIONS_AND_SIGNERS',
39
+ GOVERNANCE_VOTE = 'GOVERNANCE_VOTE',
40
+ SLASHING_VOTE = 'SLASHING_VOTE',
41
+ AUTH_REQUEST = 'AUTH_REQUEST',
42
+ TXS = 'TXS',
43
+ }
44
+
45
+ /**
46
+ * Status of a duty in the database
47
+ */
48
+ export enum DutyStatus {
49
+ SIGNING = 'signing',
50
+ SIGNED = 'signed',
51
+ }
52
+
53
+ /**
54
+ * Record of a validator duty in the database
55
+ */
56
+ export interface ValidatorDutyRecord {
57
+ /** Ethereum address of the validator */
58
+ validatorAddress: EthAddress;
59
+ /** Slot number for this duty */
60
+ slot: SlotNumber;
61
+ /** Block number for this duty */
62
+ blockNumber: BlockNumber;
63
+ /** Block index within checkpoint (0, 1, 2... for block proposals, -1 for other duty types) */
64
+ blockIndexWithinCheckpoint: number;
65
+ /** Type of duty being performed */
66
+ dutyType: DutyType;
67
+ /** Current status of the duty */
68
+ status: DutyStatus;
69
+ /** The signing root (hash) for this duty */
70
+ messageHash: string;
71
+ /** The signature (populated after successful signing) */
72
+ signature?: string;
73
+ /** Unique identifier for the node that acquired the lock */
74
+ nodeId: string;
75
+ /** Secret token for verifying ownership of the duty lock */
76
+ lockToken: string;
77
+ /** When the duty signing was started */
78
+ startedAt: Date;
79
+ /** When the duty signing was completed (success or failure) */
80
+ completedAt?: Date;
81
+ /** Error message if status is 'failed' */
82
+ errorMessage?: string;
83
+ }
84
+
85
+ /**
86
+ * Duty identifier for block proposals.
87
+ * blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
88
+ */
89
+ export interface BlockProposalDutyIdentifier {
90
+ validatorAddress: EthAddress;
91
+ slot: SlotNumber;
92
+ /** Block index within checkpoint (0, 1, 2...). Required for block proposals. */
93
+ blockIndexWithinCheckpoint: IndexWithinCheckpoint;
94
+ dutyType: DutyType.BLOCK_PROPOSAL;
95
+ }
96
+
97
+ /**
98
+ * Duty identifier for non-block-proposal duties.
99
+ * blockIndexWithinCheckpoint is not applicable (internally stored as -1).
100
+ */
101
+ export interface OtherDutyIdentifier {
102
+ validatorAddress: EthAddress;
103
+ slot: SlotNumber;
104
+ dutyType:
105
+ | DutyType.CHECKPOINT_PROPOSAL
106
+ | DutyType.ATTESTATION
107
+ | DutyType.ATTESTATIONS_AND_SIGNERS
108
+ | DutyType.GOVERNANCE_VOTE
109
+ | DutyType.SLASHING_VOTE
110
+ | DutyType.AUTH_REQUEST
111
+ | DutyType.TXS;
112
+ }
113
+
114
+ /**
115
+ * Minimal info needed to identify a unique duty.
116
+ * Uses discriminated union to enforce type safety:
117
+ * - BLOCK_PROPOSAL duties MUST have blockIndexWithinCheckpoint >= 0
118
+ * - Other duty types do NOT have blockIndexWithinCheckpoint (internally -1)
119
+ */
120
+ export type DutyIdentifier = BlockProposalDutyIdentifier | OtherDutyIdentifier;
121
+
122
+ /**
123
+ * Validates and normalizes the block index for a duty.
124
+ * - BLOCK_PROPOSAL: validates blockIndexWithinCheckpoint is provided and >= 0
125
+ * - Other duty types: always returns -1
126
+ *
127
+ * @throws Error if BLOCK_PROPOSAL is missing blockIndexWithinCheckpoint or has invalid value
128
+ */
129
+ export function normalizeBlockIndex(dutyType: DutyType, blockIndexWithinCheckpoint: number | undefined): number {
130
+ if (dutyType === DutyType.BLOCK_PROPOSAL) {
131
+ if (blockIndexWithinCheckpoint === undefined) {
132
+ throw new Error('BLOCK_PROPOSAL duties require blockIndexWithinCheckpoint to be specified');
133
+ }
134
+ if (blockIndexWithinCheckpoint < 0) {
135
+ throw new Error(
136
+ `BLOCK_PROPOSAL duties require blockIndexWithinCheckpoint >= 0, got ${blockIndexWithinCheckpoint}`,
137
+ );
138
+ }
139
+ return blockIndexWithinCheckpoint;
140
+ }
141
+ // For all other duty types, always use -1
142
+ return -1;
143
+ }
144
+
145
+ /**
146
+ * Gets the block index from a DutyIdentifier.
147
+ * - BLOCK_PROPOSAL: returns the blockIndexWithinCheckpoint
148
+ * - Other duty types: returns -1
149
+ */
150
+ export function getBlockIndexFromDutyIdentifier(duty: DutyIdentifier): number {
151
+ if (duty.dutyType === DutyType.BLOCK_PROPOSAL) {
152
+ return duty.blockIndexWithinCheckpoint;
153
+ }
154
+ return -1;
155
+ }
156
+
157
+ /**
158
+ * Additional parameters for checking and recording a new duty
159
+ */
160
+ interface CheckAndRecordExtra {
161
+ /** Block number for this duty */
162
+ blockNumber: BlockNumber | CheckpointNumber;
163
+ /** The signing root (hash) for this duty */
164
+ messageHash: string;
165
+ /** Identifier for the node that acquired the lock */
166
+ nodeId: string;
167
+ }
168
+
169
+ /**
170
+ * Parameters for checking and recording a new duty.
171
+ * Uses intersection with DutyIdentifier to preserve the discriminated union.
172
+ */
173
+ export type CheckAndRecordParams = DutyIdentifier & CheckAndRecordExtra;
174
+
175
+ /**
176
+ * Additional parameters for recording a successful signing
177
+ */
178
+ interface RecordSuccessExtra {
179
+ signature: Signature;
180
+ nodeId: string;
181
+ lockToken: string;
182
+ }
183
+
184
+ /**
185
+ * Parameters for recording a successful signing.
186
+ * Uses intersection with DutyIdentifier to preserve the discriminated union.
187
+ */
188
+ export type RecordSuccessParams = DutyIdentifier & RecordSuccessExtra;
189
+
190
+ /**
191
+ * Additional parameters for deleting a duty
192
+ */
193
+ interface DeleteDutyExtra {
194
+ lockToken: string;
195
+ }
196
+
197
+ /**
198
+ * Parameters for deleting a duty.
199
+ * Uses intersection with DutyIdentifier to preserve the discriminated union.
200
+ */
201
+ export type DeleteDutyParams = DutyIdentifier & DeleteDutyExtra;
package/src/errors.ts ADDED
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Custom errors for the validator HA signer
3
+ */
4
+ import type { SlotNumber } from '@aztec/foundation/branded-types';
5
+
6
+ import type { DutyType } from './db/types.js';
7
+
8
+ /**
9
+ * Thrown when a duty has already been signed (by any node).
10
+ * This is expected behavior in an HA setup - all nodes try to sign,
11
+ * the first one wins, and subsequent attempts get this error.
12
+ */
13
+ export class DutyAlreadySignedError extends Error {
14
+ constructor(
15
+ public readonly slot: SlotNumber,
16
+ public readonly dutyType: DutyType,
17
+ public readonly blockIndexWithinCheckpoint: number,
18
+ public readonly signedByNode: string,
19
+ ) {
20
+ super(`Duty ${dutyType} for slot ${slot} already signed by node ${signedByNode}`);
21
+ this.name = 'DutyAlreadySignedError';
22
+ }
23
+ }
24
+
25
+ /**
26
+ * Thrown when attempting to sign data that conflicts with an already-signed duty.
27
+ * This means the same validator tried to sign DIFFERENT data for the same slot.
28
+ *
29
+ * This is expected in HA setups where nodes may build different blocks
30
+ * (e.g., different transaction ordering) - the protection prevents double-signing.
31
+ */
32
+ export class SlashingProtectionError extends Error {
33
+ constructor(
34
+ public readonly slot: SlotNumber,
35
+ public readonly dutyType: DutyType,
36
+ public readonly blockIndexWithinCheckpoint: number,
37
+ public readonly existingMessageHash: string,
38
+ public readonly attemptedMessageHash: string,
39
+ public readonly signedByNode: string,
40
+ ) {
41
+ super(
42
+ `Slashing protection: ${dutyType} for slot ${slot} was already signed with different data. ` +
43
+ `Existing: ${existingMessageHash.slice(0, 10)}..., Attempted: ${attemptedMessageHash.slice(0, 10)}...`,
44
+ );
45
+ this.name = 'SlashingProtectionError';
46
+ }
47
+ }
package/src/factory.ts ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Factory functions for creating validator HA signers
3
+ */
4
+ import { Pool } from 'pg';
5
+
6
+ import type { ValidatorHASignerConfig } from './config.js';
7
+ import { PostgresSlashingProtectionDatabase } from './db/postgres.js';
8
+ import type { CreateHASignerDeps, SlashingProtectionDatabase } from './types.js';
9
+ import { ValidatorHASigner } from './validator_ha_signer.js';
10
+
11
+ /**
12
+ * Create a validator HA signer with PostgreSQL backend
13
+ *
14
+ * After creating the signer, call `signer.start()` to begin background
15
+ * cleanup tasks. Call `signer.stop()` during graceful shutdown.
16
+ *
17
+ * Example with manual migrations (recommended for production):
18
+ * ```bash
19
+ * # Run migrations separately
20
+ * yarn migrate:up
21
+ * ```
22
+ *
23
+ * ```typescript
24
+ * const { signer, db } = await createHASigner({
25
+ * databaseUrl: process.env.DATABASE_URL,
26
+ * haSigningEnabled: true,
27
+ * nodeId: 'validator-node-1',
28
+ * pollingIntervalMs: 100,
29
+ * signingTimeoutMs: 3000,
30
+ * });
31
+ * signer.start(); // Start background cleanup
32
+ *
33
+ * // ... use signer ...
34
+ *
35
+ * await signer.stop(); // On shutdown
36
+ * ```
37
+ *
38
+ * Note: Migrations must be run separately using `aztec migrate-ha-db up` before
39
+ * creating the signer. The factory will verify the schema is initialized via `db.initialize()`.
40
+ *
41
+ * @param config - Configuration for the HA signer
42
+ * @param deps - Optional dependencies (e.g., for testing)
43
+ * @returns An object containing the signer and database instances
44
+ */
45
+ export async function createHASigner(
46
+ config: ValidatorHASignerConfig,
47
+ deps?: CreateHASignerDeps,
48
+ ): Promise<{
49
+ signer: ValidatorHASigner;
50
+ db: SlashingProtectionDatabase;
51
+ }> {
52
+ const { databaseUrl, poolMaxCount, poolMinCount, poolIdleTimeoutMs, poolConnectionTimeoutMs, ...signerConfig } =
53
+ config;
54
+
55
+ if (!databaseUrl) {
56
+ throw new Error('databaseUrl is required for createHASigner');
57
+ }
58
+ // Create connection pool (or use provided pool)
59
+ let pool: Pool;
60
+ if (!deps?.pool) {
61
+ pool = new Pool({
62
+ connectionString: databaseUrl,
63
+ max: poolMaxCount ?? 10,
64
+ min: poolMinCount ?? 0,
65
+ idleTimeoutMillis: poolIdleTimeoutMs ?? 10_000,
66
+ connectionTimeoutMillis: poolConnectionTimeoutMs ?? 0,
67
+ });
68
+ } else {
69
+ pool = deps.pool;
70
+ }
71
+
72
+ // Create database instance
73
+ const db = new PostgresSlashingProtectionDatabase(pool);
74
+
75
+ // Verify database schema is initialized and version matches
76
+ await db.initialize();
77
+
78
+ // Create signer
79
+ const signer = new ValidatorHASigner(db, { ...signerConfig, databaseUrl });
80
+
81
+ return { signer, db };
82
+ }
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Programmatic migration runner
3
+ */
4
+ import { createLogger } from '@aztec/foundation/log';
5
+
6
+ import { readdirSync } from 'fs';
7
+ import { runner } from 'node-pg-migrate';
8
+ import { dirname, join } from 'path';
9
+ import { fileURLToPath } from 'url';
10
+
11
+ const __filename = fileURLToPath(import.meta.url);
12
+ const __dirname = dirname(__filename);
13
+
14
+ export interface RunMigrationsOptions {
15
+ /** Migration direction ('up' to apply, 'down' to rollback). Defaults to 'up'. */
16
+ direction?: 'up' | 'down';
17
+ /** Enable verbose output. Defaults to false. */
18
+ verbose?: boolean;
19
+ }
20
+
21
+ /**
22
+ * Run database migrations programmatically
23
+ *
24
+ * @param databaseUrl - PostgreSQL connection string
25
+ * @param options - Migration options (direction, verbose)
26
+ * @returns Array of applied migration names
27
+ */
28
+ export async function runMigrations(databaseUrl: string, options: RunMigrationsOptions = {}): Promise<string[]> {
29
+ const direction = options.direction ?? 'up';
30
+ const verbose = options.verbose ?? false;
31
+
32
+ const log = createLogger('validator-ha-signer:migrations');
33
+
34
+ const migrationsDir = join(__dirname, 'db', 'migrations');
35
+
36
+ try {
37
+ log.info(`Running migrations ${direction}...`);
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
+
50
+ const appliedMigrations = await runner({
51
+ databaseUrl,
52
+ dir: migrationsDir,
53
+ direction,
54
+ migrationsTable: 'pgmigrations',
55
+ count: direction === 'down' ? 1 : Infinity,
56
+ verbose,
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$',
60
+ });
61
+
62
+ if (appliedMigrations.length === 0) {
63
+ log.info('No migrations to apply - schema is up to date');
64
+ } else {
65
+ log.info(`Applied ${appliedMigrations.length} migration(s)`, {
66
+ migrations: appliedMigrations.map(m => m.name),
67
+ });
68
+ }
69
+
70
+ return appliedMigrations.map(m => m.name);
71
+ } catch (error: any) {
72
+ log.error('Migration failed', error);
73
+ throw error;
74
+ }
75
+ }