@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,42 @@
1
+ import type { ValidatorHASignerConfig } from './config.js';
2
+ import type { CreateHASignerDeps, SlashingProtectionDatabase } from './types.js';
3
+ import { ValidatorHASigner } from './validator_ha_signer.js';
4
+ /**
5
+ * Create a validator HA signer with PostgreSQL backend
6
+ *
7
+ * After creating the signer, call `signer.start()` to begin background
8
+ * cleanup tasks. Call `signer.stop()` during graceful shutdown.
9
+ *
10
+ * Example with manual migrations (recommended for production):
11
+ * ```bash
12
+ * # Run migrations separately
13
+ * yarn migrate:up
14
+ * ```
15
+ *
16
+ * ```typescript
17
+ * const { signer, db } = await createHASigner({
18
+ * databaseUrl: process.env.DATABASE_URL,
19
+ * haSigningEnabled: true,
20
+ * nodeId: 'validator-node-1',
21
+ * pollingIntervalMs: 100,
22
+ * signingTimeoutMs: 3000,
23
+ * });
24
+ * signer.start(); // Start background cleanup
25
+ *
26
+ * // ... use signer ...
27
+ *
28
+ * await signer.stop(); // On shutdown
29
+ * ```
30
+ *
31
+ * Note: Migrations must be run separately using `aztec migrate-ha-db up` before
32
+ * creating the signer. The factory will verify the schema is initialized via `db.initialize()`.
33
+ *
34
+ * @param config - Configuration for the HA signer
35
+ * @param deps - Optional dependencies (e.g., for testing)
36
+ * @returns An object containing the signer and database instances
37
+ */
38
+ export declare function createHASigner(config: ValidatorHASignerConfig, deps?: CreateHASignerDeps): Promise<{
39
+ signer: ValidatorHASigner;
40
+ db: SlashingProtectionDatabase;
41
+ }>;
42
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZmFjdG9yeS5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL2ZhY3RvcnkudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBS0EsT0FBTyxLQUFLLEVBQUUsdUJBQXVCLEVBQUUsTUFBTSxhQUFhLENBQUM7QUFFM0QsT0FBTyxLQUFLLEVBQUUsa0JBQWtCLEVBQUUsMEJBQTBCLEVBQUUsTUFBTSxZQUFZLENBQUM7QUFDakYsT0FBTyxFQUFFLGlCQUFpQixFQUFFLE1BQU0sMEJBQTBCLENBQUM7QUFFN0Q7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7OztHQWlDRztBQUNILHdCQUFzQixjQUFjLENBQ2xDLE1BQU0sRUFBRSx1QkFBdUIsRUFDL0IsSUFBSSxDQUFDLEVBQUUsa0JBQWtCLEdBQ3hCLE9BQU8sQ0FBQztJQUNULE1BQU0sRUFBRSxpQkFBaUIsQ0FBQztJQUMxQixFQUFFLEVBQUUsMEJBQTBCLENBQUM7Q0FDaEMsQ0FBQyxDQStCRCJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"factory.d.ts","sourceRoot":"","sources":["../src/factory.ts"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,aAAa,CAAC;AAE3D,OAAO,KAAK,EAAE,kBAAkB,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AACjF,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAsB,cAAc,CAClC,MAAM,EAAE,uBAAuB,EAC/B,IAAI,CAAC,EAAE,kBAAkB,GACxB,OAAO,CAAC;IACT,MAAM,EAAE,iBAAiB,CAAC;IAC1B,EAAE,EAAE,0BAA0B,CAAC;CAChC,CAAC,CA+BD"}
@@ -0,0 +1,70 @@
1
+ /**
2
+ * Factory functions for creating validator HA signers
3
+ */ import { Pool } from 'pg';
4
+ import { PostgresSlashingProtectionDatabase } from './db/postgres.js';
5
+ import { ValidatorHASigner } from './validator_ha_signer.js';
6
+ /**
7
+ * Create a validator HA signer with PostgreSQL backend
8
+ *
9
+ * After creating the signer, call `signer.start()` to begin background
10
+ * cleanup tasks. Call `signer.stop()` during graceful shutdown.
11
+ *
12
+ * Example with manual migrations (recommended for production):
13
+ * ```bash
14
+ * # Run migrations separately
15
+ * yarn migrate:up
16
+ * ```
17
+ *
18
+ * ```typescript
19
+ * const { signer, db } = await createHASigner({
20
+ * databaseUrl: process.env.DATABASE_URL,
21
+ * haSigningEnabled: true,
22
+ * nodeId: 'validator-node-1',
23
+ * pollingIntervalMs: 100,
24
+ * signingTimeoutMs: 3000,
25
+ * });
26
+ * signer.start(); // Start background cleanup
27
+ *
28
+ * // ... use signer ...
29
+ *
30
+ * await signer.stop(); // On shutdown
31
+ * ```
32
+ *
33
+ * Note: Migrations must be run separately using `aztec migrate-ha-db up` before
34
+ * creating the signer. The factory will verify the schema is initialized via `db.initialize()`.
35
+ *
36
+ * @param config - Configuration for the HA signer
37
+ * @param deps - Optional dependencies (e.g., for testing)
38
+ * @returns An object containing the signer and database instances
39
+ */ export async function createHASigner(config, deps) {
40
+ const { databaseUrl, poolMaxCount, poolMinCount, poolIdleTimeoutMs, poolConnectionTimeoutMs, ...signerConfig } = config;
41
+ if (!databaseUrl) {
42
+ throw new Error('databaseUrl is required for createHASigner');
43
+ }
44
+ // Create connection pool (or use provided pool)
45
+ let pool;
46
+ if (!deps?.pool) {
47
+ pool = new Pool({
48
+ connectionString: databaseUrl,
49
+ max: poolMaxCount ?? 10,
50
+ min: poolMinCount ?? 0,
51
+ idleTimeoutMillis: poolIdleTimeoutMs ?? 10_000,
52
+ connectionTimeoutMillis: poolConnectionTimeoutMs ?? 0
53
+ });
54
+ } else {
55
+ pool = deps.pool;
56
+ }
57
+ // Create database instance
58
+ const db = new PostgresSlashingProtectionDatabase(pool);
59
+ // Verify database schema is initialized and version matches
60
+ await db.initialize();
61
+ // Create signer
62
+ const signer = new ValidatorHASigner(db, {
63
+ ...signerConfig,
64
+ databaseUrl
65
+ });
66
+ return {
67
+ signer,
68
+ db
69
+ };
70
+ }
@@ -0,0 +1,15 @@
1
+ export interface RunMigrationsOptions {
2
+ /** Migration direction ('up' to apply, 'down' to rollback). Defaults to 'up'. */
3
+ direction?: 'up' | 'down';
4
+ /** Enable verbose output. Defaults to false. */
5
+ verbose?: boolean;
6
+ }
7
+ /**
8
+ * Run database migrations programmatically
9
+ *
10
+ * @param databaseUrl - PostgreSQL connection string
11
+ * @param options - Migration options (direction, verbose)
12
+ * @returns Array of applied migration names
13
+ */
14
+ export declare function runMigrations(databaseUrl: string, options?: RunMigrationsOptions): Promise<string[]>;
15
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWlncmF0aW9ucy5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL21pZ3JhdGlvbnMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBYUEsTUFBTSxXQUFXLG9CQUFvQjtJQUNuQyxpRkFBaUY7SUFDakYsU0FBUyxDQUFDLEVBQUUsSUFBSSxHQUFHLE1BQU0sQ0FBQztJQUMxQixnREFBZ0Q7SUFDaEQsT0FBTyxDQUFDLEVBQUUsT0FBTyxDQUFDO0NBQ25CO0FBRUQ7Ozs7OztHQU1HO0FBQ0gsd0JBQXNCLGFBQWEsQ0FBQyxXQUFXLEVBQUUsTUFBTSxFQUFFLE9BQU8sR0FBRSxvQkFBeUIsR0FBRyxPQUFPLENBQUMsTUFBTSxFQUFFLENBQUMsQ0ErQzlHIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"migrations.d.ts","sourceRoot":"","sources":["../src/migrations.ts"],"names":[],"mappings":"AAaA,MAAM,WAAW,oBAAoB;IACnC,iFAAiF;IACjF,SAAS,CAAC,EAAE,IAAI,GAAG,MAAM,CAAC;IAC1B,gDAAgD;IAChD,OAAO,CAAC,EAAE,OAAO,CAAC;CACnB;AAED;;;;;;GAMG;AACH,wBAAsB,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,OAAO,GAAE,oBAAyB,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CA+C9G"}
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Programmatic migration runner
3
+ */ import { createLogger } from '@aztec/foundation/log';
4
+ import { readdirSync } from 'fs';
5
+ import { runner } from 'node-pg-migrate';
6
+ import { dirname, join } from 'path';
7
+ import { fileURLToPath } from 'url';
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+ /**
11
+ * Run database migrations programmatically
12
+ *
13
+ * @param databaseUrl - PostgreSQL connection string
14
+ * @param options - Migration options (direction, verbose)
15
+ * @returns Array of applied migration names
16
+ */ export async function runMigrations(databaseUrl, options = {}) {
17
+ const direction = options.direction ?? 'up';
18
+ const verbose = options.verbose ?? false;
19
+ const log = createLogger('validator-ha-signer:migrations');
20
+ const migrationsDir = join(__dirname, 'db', 'migrations');
21
+ try {
22
+ log.info(`Running migrations ${direction}...`);
23
+ // Filter out .d.ts and .d.ts.map files - node-pg-migrate only needs .js files
24
+ const migrationFiles = readdirSync(migrationsDir);
25
+ const jsMigrationFiles = migrationFiles.filter((file)=>file.endsWith('.js') && !file.endsWith('.d.ts') && !file.endsWith('.d.ts.map'));
26
+ if (jsMigrationFiles.length === 0) {
27
+ log.info('No migration files found');
28
+ return [];
29
+ }
30
+ const appliedMigrations = await runner({
31
+ databaseUrl,
32
+ dir: migrationsDir,
33
+ direction,
34
+ migrationsTable: 'pgmigrations',
35
+ count: direction === 'down' ? 1 : Infinity,
36
+ verbose,
37
+ log: (msg)=>verbose ? log.info(msg) : log.debug(msg),
38
+ // Ignore TypeScript declaration files - node-pg-migrate will try to import them otherwise
39
+ ignorePattern: '.*\\.d\\.(ts|js)$|.*\\.d\\.ts\\.map$'
40
+ });
41
+ if (appliedMigrations.length === 0) {
42
+ log.info('No migrations to apply - schema is up to date');
43
+ } else {
44
+ log.info(`Applied ${appliedMigrations.length} migration(s)`, {
45
+ migrations: appliedMigrations.map((m)=>m.name)
46
+ });
47
+ }
48
+ return appliedMigrations.map((m)=>m.name);
49
+ } catch (error) {
50
+ log.error('Migration failed', error);
51
+ throw error;
52
+ }
53
+ }
@@ -0,0 +1,80 @@
1
+ import { type CheckAndRecordParams, type DeleteDutyParams, type RecordSuccessParams } from './db/types.js';
2
+ import type { SlashingProtectionDatabase, ValidatorHASignerConfig } from './types.js';
3
+ /**
4
+ * Slashing Protection Service
5
+ *
6
+ * This service ensures that a validator only signs one block/attestation per slot,
7
+ * even when running multiple redundant nodes (HA setup).
8
+ *
9
+ * All nodes in the HA setup try to sign - the first one wins, others get
10
+ * DutyAlreadySignedError (normal) or SlashingProtectionError (if different data).
11
+ *
12
+ * Flow:
13
+ * 1. checkAndRecord() - Atomically try to acquire lock via tryInsertOrGetExisting
14
+ * 2. Caller performs the signing operation
15
+ * 3. recordSuccess() - Update to 'signed' status with signature
16
+ * OR deleteDuty() - Delete the record to allow retry
17
+ */
18
+ export declare class SlashingProtectionService {
19
+ private readonly db;
20
+ private readonly config;
21
+ private readonly log;
22
+ private readonly pollingIntervalMs;
23
+ private readonly signingTimeoutMs;
24
+ private readonly maxStuckDutiesAgeMs;
25
+ private cleanupRunningPromise;
26
+ constructor(db: SlashingProtectionDatabase, config: ValidatorHASignerConfig);
27
+ /**
28
+ * Check if a duty can be performed and acquire the lock if so.
29
+ *
30
+ * This method uses an atomic insert-or-get operation.
31
+ * It will:
32
+ * 1. Try to insert a new record with 'signing' status
33
+ * 2. If insert succeeds, we acquired the lock - return the lockToken
34
+ * 3. If a record exists, handle based on status:
35
+ * - SIGNED: Throw appropriate error (already signed or slashing protection)
36
+ * - FAILED: Delete the failed record
37
+ * - SIGNING: Wait and poll until status changes, then handle result
38
+ *
39
+ * @returns The lockToken that must be used for recordSuccess/deleteDuty
40
+ * @throws DutyAlreadySignedError if the duty was already completed
41
+ * @throws SlashingProtectionError if attempting to sign different data for same slot/duty
42
+ */
43
+ checkAndRecord(params: CheckAndRecordParams): Promise<string>;
44
+ /**
45
+ * Record a successful signing operation.
46
+ * Updates the duty status to 'signed' and stores the signature.
47
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
48
+ *
49
+ * @returns true if the update succeeded, false if token didn't match
50
+ */
51
+ recordSuccess(params: RecordSuccessParams): Promise<boolean>;
52
+ /**
53
+ * Delete a duty record after a failed signing operation.
54
+ * Removes the record to allow another node/attempt to retry.
55
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
56
+ *
57
+ * @returns true if the delete succeeded, false if token didn't match
58
+ */
59
+ deleteDuty(params: DeleteDutyParams): Promise<boolean>;
60
+ /**
61
+ * Get the node ID for this service
62
+ */
63
+ get nodeId(): string;
64
+ /**
65
+ * Start running tasks.
66
+ * Cleanup runs immediately on start to recover from any previous crashes.
67
+ */
68
+ start(): void;
69
+ /**
70
+ * Stop the background cleanup task.
71
+ */
72
+ stop(): Promise<void>;
73
+ /**
74
+ * Close the database connection.
75
+ * Should be called after stop() during graceful shutdown.
76
+ */
77
+ close(): Promise<void>;
78
+ private cleanupStuckDuties;
79
+ }
80
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2xhc2hpbmdfcHJvdGVjdGlvbl9zZXJ2aWNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvc2xhc2hpbmdfcHJvdGVjdGlvbl9zZXJ2aWNlLnRz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;IACH,KAAK,SAGJ;IAED;;OAEG;IACG,IAAI,kBAGT;IAED;;;OAGG;IACG,KAAK,kBAGV;YAKa,kBAAkB;CASjC"}
@@ -0,0 +1,196 @@
1
+ /**
2
+ * Slashing Protection Service
3
+ *
4
+ * Provides distributed locking and slashing protection for validator duties.
5
+ * Uses an external database to coordinate across multiple validator nodes.
6
+ */ import { createLogger } from '@aztec/foundation/log';
7
+ import { RunningPromise } from '@aztec/foundation/promise';
8
+ import { sleep } from '@aztec/foundation/sleep';
9
+ import { DutyStatus, getBlockIndexFromDutyIdentifier } from './db/types.js';
10
+ import { DutyAlreadySignedError, SlashingProtectionError } from './errors.js';
11
+ /**
12
+ * Slashing Protection Service
13
+ *
14
+ * This service ensures that a validator only signs one block/attestation per slot,
15
+ * even when running multiple redundant nodes (HA setup).
16
+ *
17
+ * All nodes in the HA setup try to sign - the first one wins, others get
18
+ * DutyAlreadySignedError (normal) or SlashingProtectionError (if different data).
19
+ *
20
+ * Flow:
21
+ * 1. checkAndRecord() - Atomically try to acquire lock via tryInsertOrGetExisting
22
+ * 2. Caller performs the signing operation
23
+ * 3. recordSuccess() - Update to 'signed' status with signature
24
+ * OR deleteDuty() - Delete the record to allow retry
25
+ */ export class SlashingProtectionService {
26
+ db;
27
+ config;
28
+ log;
29
+ pollingIntervalMs;
30
+ signingTimeoutMs;
31
+ maxStuckDutiesAgeMs;
32
+ cleanupRunningPromise;
33
+ constructor(db, config){
34
+ this.db = db;
35
+ this.config = config;
36
+ this.log = createLogger('slashing-protection');
37
+ this.pollingIntervalMs = config.pollingIntervalMs;
38
+ this.signingTimeoutMs = config.signingTimeoutMs;
39
+ // Default to 144s (2x 72s Aztec slot duration) if not explicitly configured
40
+ this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? 144_000;
41
+ this.cleanupRunningPromise = new RunningPromise(this.cleanupStuckDuties.bind(this), this.log, this.maxStuckDutiesAgeMs);
42
+ }
43
+ /**
44
+ * Check if a duty can be performed and acquire the lock if so.
45
+ *
46
+ * This method uses an atomic insert-or-get operation.
47
+ * It will:
48
+ * 1. Try to insert a new record with 'signing' status
49
+ * 2. If insert succeeds, we acquired the lock - return the lockToken
50
+ * 3. If a record exists, handle based on status:
51
+ * - SIGNED: Throw appropriate error (already signed or slashing protection)
52
+ * - FAILED: Delete the failed record
53
+ * - SIGNING: Wait and poll until status changes, then handle result
54
+ *
55
+ * @returns The lockToken that must be used for recordSuccess/deleteDuty
56
+ * @throws DutyAlreadySignedError if the duty was already completed
57
+ * @throws SlashingProtectionError if attempting to sign different data for same slot/duty
58
+ */ async checkAndRecord(params) {
59
+ const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
60
+ const startTime = Date.now();
61
+ this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
62
+ validatorAddress: validatorAddress.toString(),
63
+ nodeId
64
+ });
65
+ while(true){
66
+ // insert if not present, get existing if present
67
+ const { isNew, record } = await this.db.tryInsertOrGetExisting(params);
68
+ if (isNew) {
69
+ // We successfully acquired the lock
70
+ this.log.info(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
71
+ validatorAddress: validatorAddress.toString(),
72
+ nodeId
73
+ });
74
+ return record.lockToken;
75
+ }
76
+ // Record already exists - handle based on status
77
+ if (record.status === DutyStatus.SIGNED) {
78
+ // Duty was already signed - check if same or different data
79
+ if (record.messageHash !== messageHash) {
80
+ this.log.verbose(`Slashing protection triggered for duty ${dutyType} at slot ${slot}`, {
81
+ validatorAddress: validatorAddress.toString(),
82
+ existingMessageHash: record.messageHash,
83
+ attemptedMessageHash: messageHash,
84
+ existingNodeId: record.nodeId,
85
+ attemptingNodeId: nodeId
86
+ });
87
+ throw new SlashingProtectionError(slot, dutyType, record.blockIndexWithinCheckpoint, record.messageHash, messageHash, record.nodeId);
88
+ }
89
+ throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
90
+ } else if (record.status === DutyStatus.SIGNING) {
91
+ // Another node is currently signing - check for timeout
92
+ if (Date.now() - startTime > this.signingTimeoutMs) {
93
+ this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
94
+ validatorAddress: validatorAddress.toString(),
95
+ timeoutMs: this.signingTimeoutMs,
96
+ signingNodeId: record.nodeId
97
+ });
98
+ throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
99
+ }
100
+ // Wait and poll
101
+ this.log.debug(`Waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
102
+ validatorAddress: validatorAddress.toString(),
103
+ signingNodeId: record.nodeId
104
+ });
105
+ await sleep(this.pollingIntervalMs);
106
+ // Loop continues - next iteration will check status again
107
+ } else {
108
+ throw new Error(`Unknown duty status: ${record.status}`);
109
+ }
110
+ }
111
+ }
112
+ /**
113
+ * Record a successful signing operation.
114
+ * Updates the duty status to 'signed' and stores the signature.
115
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
116
+ *
117
+ * @returns true if the update succeeded, false if token didn't match
118
+ */ async recordSuccess(params) {
119
+ const { validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
120
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
121
+ const success = await this.db.updateDutySigned(validatorAddress, slot, dutyType, signature.toString(), lockToken, blockIndexWithinCheckpoint);
122
+ if (success) {
123
+ this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
124
+ validatorAddress: validatorAddress.toString(),
125
+ nodeId
126
+ });
127
+ } else {
128
+ this.log.warn(`Failed to record successful signing for duty ${dutyType} at slot ${slot}: invalid token`, {
129
+ validatorAddress: validatorAddress.toString(),
130
+ nodeId
131
+ });
132
+ }
133
+ return success;
134
+ }
135
+ /**
136
+ * Delete a duty record after a failed signing operation.
137
+ * Removes the record to allow another node/attempt to retry.
138
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
139
+ *
140
+ * @returns true if the delete succeeded, false if token didn't match
141
+ */ async deleteDuty(params) {
142
+ const { validatorAddress, slot, dutyType, lockToken } = params;
143
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
144
+ const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint);
145
+ if (success) {
146
+ this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
147
+ validatorAddress: validatorAddress.toString()
148
+ });
149
+ } else {
150
+ this.log.warn(`Failed to delete duty ${dutyType} at slot ${slot}: invalid token`, {
151
+ validatorAddress: validatorAddress.toString()
152
+ });
153
+ }
154
+ return success;
155
+ }
156
+ /**
157
+ * Get the node ID for this service
158
+ */ get nodeId() {
159
+ return this.config.nodeId;
160
+ }
161
+ /**
162
+ * Start running tasks.
163
+ * Cleanup runs immediately on start to recover from any previous crashes.
164
+ */ start() {
165
+ this.cleanupRunningPromise.start();
166
+ this.log.info('Slashing protection service started', {
167
+ nodeId: this.config.nodeId
168
+ });
169
+ }
170
+ /**
171
+ * Stop the background cleanup task.
172
+ */ async stop() {
173
+ await this.cleanupRunningPromise.stop();
174
+ this.log.info('Slashing protection service stopped', {
175
+ nodeId: this.config.nodeId
176
+ });
177
+ }
178
+ /**
179
+ * Close the database connection.
180
+ * Should be called after stop() during graceful shutdown.
181
+ */ async close() {
182
+ await this.db.close();
183
+ this.log.info('Slashing protection database connection closed');
184
+ }
185
+ /**
186
+ * Cleanup own stuck duties
187
+ */ async cleanupStuckDuties() {
188
+ const numDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
189
+ if (numDuties > 0) {
190
+ this.log.info(`Cleaned up ${numDuties} stuck duties`, {
191
+ nodeId: this.config.nodeId,
192
+ maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs
193
+ });
194
+ }
195
+ }
196
+ }
@@ -0,0 +1,92 @@
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
+ export interface PoolConfig {
18
+ pglite: PGliteInterface;
19
+ max?: number;
20
+ min?: number;
21
+ }
22
+ interface ClientConfig {
23
+ pglite: PGliteInterface;
24
+ host?: string;
25
+ port?: number;
26
+ ssl?: boolean;
27
+ }
28
+ export declare class Client extends EventEmitter {
29
+ protected pglite: PGliteInterface;
30
+ protected _connected: boolean;
31
+ readonly host: string;
32
+ readonly port: number;
33
+ readonly ssl: boolean;
34
+ readonly connection: object;
35
+ readonly copyFrom: () => Writable;
36
+ readonly copyTo: () => Readable;
37
+ readonly pauseDrain: () => void;
38
+ readonly resumeDrain: () => void;
39
+ readonly escapeLiteral: (str: string) => string;
40
+ readonly escapeIdentifier: (str: string) => string;
41
+ readonly setTypeParser: () => void;
42
+ readonly getTypeParser: () => (value: string) => unknown;
43
+ constructor(config: ClientConfig);
44
+ connect(): Promise<void>;
45
+ end(): Promise<void>;
46
+ query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>>;
47
+ protected convertPGliteResult<R extends QueryResultRow>(result: {
48
+ rows: R[];
49
+ fields: Array<{
50
+ name: string;
51
+ dataTypeID: number;
52
+ }>;
53
+ affectedRows?: number;
54
+ }): QueryResult<R>;
55
+ get connected(): boolean;
56
+ }
57
+ export declare class Pool extends EventEmitter {
58
+ private clients;
59
+ private availableClients;
60
+ private waitingQueue;
61
+ private _ended;
62
+ private pglite;
63
+ private _config;
64
+ readonly expiredCount = 0;
65
+ readonly options: PoolConfig;
66
+ constructor(config: PoolConfig);
67
+ get totalCount(): number;
68
+ get idleCount(): number;
69
+ get waitingCount(): number;
70
+ get ending(): boolean;
71
+ get ended(): boolean;
72
+ connect(): Promise<PoolClient>;
73
+ query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>>;
74
+ releaseClient(client: PoolClient): void;
75
+ end(): Promise<void>;
76
+ }
77
+ export declare class PoolClient extends Client {
78
+ private pool;
79
+ private _released;
80
+ private _inUse;
81
+ private _userReleased;
82
+ constructor(pglite: PGliteInterface, pool: Pool);
83
+ query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>>;
84
+ release(): void;
85
+ end(): Promise<void>;
86
+ _markInUse(): void;
87
+ _markAvailable(): void;
88
+ _markReleased(): void;
89
+ get connected(): boolean;
90
+ }
91
+ export {};
92
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicGdsaXRlX3Bvb2wuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy90ZXN0L3BnbGl0ZV9wb29sLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7Ozs7OztHQVdHO0FBQ0gsT0FBTyxLQUFLLEVBQUUsZUFBZSxFQUFFLE1BQU0sc0JBQXNCLENBQUM7QUFDNUQsT0FBTyxFQUFFLFlBQVksRUFBRSxNQUFNLFFBQVEsQ0FBQztBQUN0QyxPQUFPLEtBQUssRUFBRSxXQUFXLEVBQUUsY0FBYyxFQUFFLE1BQU0sSUFBSSxDQUFDO0FBQ3RELE9BQU8sRUFBRSxRQUFRLEVBQUUsUUFBUSxFQUFFLE1BQU0sUUFBUSxDQUFDO0FBRTVDLE1BQU0sV0FBVyxVQUFVO0lBQ3pCLE1BQU0sRUFBRSxlQUFlLENBQUM7SUFDeEIsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDO0lBQ2IsR0FBRyxDQUFDLEVBQUUsTUFBTS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