@aztec/validator-ha-signer 4.0.0-nightly.20260110
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.
- package/README.md +182 -0
- package/dest/config.d.ts +47 -0
- package/dest/config.d.ts.map +1 -0
- package/dest/config.js +64 -0
- package/dest/db/index.d.ts +4 -0
- package/dest/db/index.d.ts.map +1 -0
- package/dest/db/index.js +3 -0
- package/dest/db/migrations/1_initial-schema.d.ts +9 -0
- package/dest/db/migrations/1_initial-schema.d.ts.map +1 -0
- package/dest/db/migrations/1_initial-schema.js +20 -0
- package/dest/db/postgres.d.ts +55 -0
- package/dest/db/postgres.d.ts.map +1 -0
- package/dest/db/postgres.js +150 -0
- package/dest/db/schema.d.ts +85 -0
- package/dest/db/schema.d.ts.map +1 -0
- package/dest/db/schema.js +201 -0
- package/dest/db/test_helper.d.ts +10 -0
- package/dest/db/test_helper.d.ts.map +1 -0
- package/dest/db/test_helper.js +14 -0
- package/dest/db/types.d.ts +109 -0
- package/dest/db/types.d.ts.map +1 -0
- package/dest/db/types.js +15 -0
- package/dest/errors.d.ts +30 -0
- package/dest/errors.d.ts.map +1 -0
- package/dest/errors.js +31 -0
- package/dest/factory.d.ts +50 -0
- package/dest/factory.d.ts.map +1 -0
- package/dest/factory.js +75 -0
- package/dest/migrations.d.ts +15 -0
- package/dest/migrations.d.ts.map +1 -0
- package/dest/migrations.js +42 -0
- package/dest/slashing_protection_service.d.ts +74 -0
- package/dest/slashing_protection_service.d.ts.map +1 -0
- package/dest/slashing_protection_service.js +184 -0
- package/dest/types.d.ts +75 -0
- package/dest/types.d.ts.map +1 -0
- package/dest/types.js +1 -0
- package/dest/validator_ha_signer.d.ts +74 -0
- package/dest/validator_ha_signer.d.ts.map +1 -0
- package/dest/validator_ha_signer.js +131 -0
- package/package.json +105 -0
- package/src/config.ts +116 -0
- package/src/db/index.ts +3 -0
- package/src/db/migrations/1_initial-schema.ts +26 -0
- package/src/db/postgres.ts +202 -0
- package/src/db/schema.ts +236 -0
- package/src/db/test_helper.ts +17 -0
- package/src/db/types.ts +117 -0
- package/src/errors.ts +42 -0
- package/src/factory.ts +87 -0
- package/src/migrations.ts +59 -0
- package/src/slashing_protection_service.ts +216 -0
- package/src/types.ts +105 -0
- package/src/validator_ha_signer.ts +164 -0
package/src/db/types.ts
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import type { EthAddress } from '@aztec/foundation/eth-address';
|
|
2
|
+
import type { Signature } from '@aztec/foundation/eth-signature';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Row type from PostgreSQL query
|
|
6
|
+
*/
|
|
7
|
+
export interface DutyRow {
|
|
8
|
+
validator_address: string;
|
|
9
|
+
slot: string;
|
|
10
|
+
block_number: string;
|
|
11
|
+
duty_type: DutyType;
|
|
12
|
+
status: DutyStatus;
|
|
13
|
+
message_hash: string;
|
|
14
|
+
signature: string | null;
|
|
15
|
+
node_id: string;
|
|
16
|
+
lock_token: string;
|
|
17
|
+
started_at: Date;
|
|
18
|
+
completed_at: Date | null;
|
|
19
|
+
error_message: string | null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Row type from INSERT_OR_GET_DUTY query (includes is_new flag)
|
|
24
|
+
*/
|
|
25
|
+
export interface InsertOrGetRow extends DutyRow {
|
|
26
|
+
is_new: boolean;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Type of validator duty being performed
|
|
31
|
+
*/
|
|
32
|
+
export enum DutyType {
|
|
33
|
+
BLOCK_PROPOSAL = 'BLOCK_PROPOSAL',
|
|
34
|
+
ATTESTATION = 'ATTESTATION',
|
|
35
|
+
ATTESTATIONS_AND_SIGNERS = 'ATTESTATIONS_AND_SIGNERS',
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* Status of a duty in the database
|
|
40
|
+
*/
|
|
41
|
+
export enum DutyStatus {
|
|
42
|
+
SIGNING = 'signing',
|
|
43
|
+
SIGNED = 'signed',
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Record of a validator duty in the database
|
|
48
|
+
*/
|
|
49
|
+
export interface ValidatorDutyRecord {
|
|
50
|
+
/** Ethereum address of the validator */
|
|
51
|
+
validatorAddress: EthAddress;
|
|
52
|
+
/** Slot number for this duty */
|
|
53
|
+
slot: bigint;
|
|
54
|
+
/** Block number for this duty */
|
|
55
|
+
blockNumber: bigint;
|
|
56
|
+
/** Type of duty being performed */
|
|
57
|
+
dutyType: DutyType;
|
|
58
|
+
/** Current status of the duty */
|
|
59
|
+
status: DutyStatus;
|
|
60
|
+
/** The signing root (hash) for this duty */
|
|
61
|
+
messageHash: string;
|
|
62
|
+
/** The signature (populated after successful signing) */
|
|
63
|
+
signature?: string;
|
|
64
|
+
/** Unique identifier for the node that acquired the lock */
|
|
65
|
+
nodeId: string;
|
|
66
|
+
/** Secret token for verifying ownership of the duty lock */
|
|
67
|
+
lockToken: string;
|
|
68
|
+
/** When the duty signing was started */
|
|
69
|
+
startedAt: Date;
|
|
70
|
+
/** When the duty signing was completed (success or failure) */
|
|
71
|
+
completedAt?: Date;
|
|
72
|
+
/** Error message if status is 'failed' */
|
|
73
|
+
errorMessage?: string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Minimal info needed to identify a unique duty
|
|
78
|
+
*/
|
|
79
|
+
export interface DutyIdentifier {
|
|
80
|
+
validatorAddress: EthAddress;
|
|
81
|
+
slot: bigint;
|
|
82
|
+
dutyType: DutyType;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Parameters for checking and recording a new duty
|
|
87
|
+
*/
|
|
88
|
+
export interface CheckAndRecordParams {
|
|
89
|
+
validatorAddress: EthAddress;
|
|
90
|
+
slot: bigint;
|
|
91
|
+
blockNumber: bigint;
|
|
92
|
+
dutyType: DutyType;
|
|
93
|
+
messageHash: string;
|
|
94
|
+
nodeId: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Parameters for recording a successful signing
|
|
99
|
+
*/
|
|
100
|
+
export interface RecordSuccessParams {
|
|
101
|
+
validatorAddress: EthAddress;
|
|
102
|
+
slot: bigint;
|
|
103
|
+
dutyType: DutyType;
|
|
104
|
+
signature: Signature;
|
|
105
|
+
nodeId: string;
|
|
106
|
+
lockToken: string;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Parameters for deleting a duty
|
|
111
|
+
*/
|
|
112
|
+
export interface DeleteDutyParams {
|
|
113
|
+
validatorAddress: EthAddress;
|
|
114
|
+
slot: bigint;
|
|
115
|
+
dutyType: DutyType;
|
|
116
|
+
lockToken: string;
|
|
117
|
+
}
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom errors for the validator HA signer
|
|
3
|
+
*/
|
|
4
|
+
import type { DutyType } from './db/types.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Thrown when a duty has already been signed (by any node).
|
|
8
|
+
* This is expected behavior in an HA setup - all nodes try to sign,
|
|
9
|
+
* the first one wins, and subsequent attempts get this error.
|
|
10
|
+
*/
|
|
11
|
+
export class DutyAlreadySignedError extends Error {
|
|
12
|
+
constructor(
|
|
13
|
+
public readonly slot: bigint,
|
|
14
|
+
public readonly dutyType: DutyType,
|
|
15
|
+
public readonly signedByNode: string,
|
|
16
|
+
) {
|
|
17
|
+
super(`Duty ${dutyType} for slot ${slot} already signed by node ${signedByNode}`);
|
|
18
|
+
this.name = 'DutyAlreadySignedError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Thrown when attempting to sign data that conflicts with an already-signed duty.
|
|
24
|
+
* This means the same validator tried to sign DIFFERENT data for the same slot.
|
|
25
|
+
*
|
|
26
|
+
* This is expected in HA setups where nodes may build different blocks
|
|
27
|
+
* (e.g., different transaction ordering) - the protection prevents double-signing.
|
|
28
|
+
*/
|
|
29
|
+
export class SlashingProtectionError extends Error {
|
|
30
|
+
constructor(
|
|
31
|
+
public readonly slot: bigint,
|
|
32
|
+
public readonly dutyType: DutyType,
|
|
33
|
+
public readonly existingMessageHash: string,
|
|
34
|
+
public readonly attemptedMessageHash: string,
|
|
35
|
+
) {
|
|
36
|
+
super(
|
|
37
|
+
`Slashing protection: ${dutyType} for slot ${slot} was already signed with different data. ` +
|
|
38
|
+
`Existing: ${existingMessageHash.slice(0, 10)}..., Attempted: ${attemptedMessageHash.slice(0, 10)}...`,
|
|
39
|
+
);
|
|
40
|
+
this.name = 'SlashingProtectionError';
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/factory.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Factory functions for creating validator HA signers
|
|
3
|
+
*/
|
|
4
|
+
import { Pool } from 'pg';
|
|
5
|
+
|
|
6
|
+
import type { CreateHASignerConfig } 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
|
+
* enabled: 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
|
+
* Example with automatic migrations (simpler for dev/testing):
|
|
39
|
+
* ```typescript
|
|
40
|
+
* const { signer, db } = await createHASigner({
|
|
41
|
+
* databaseUrl: process.env.DATABASE_URL,
|
|
42
|
+
* enabled: true,
|
|
43
|
+
* nodeId: 'validator-node-1',
|
|
44
|
+
* runMigrations: true, // Auto-run migrations on startup
|
|
45
|
+
* });
|
|
46
|
+
* signer.start();
|
|
47
|
+
* ```
|
|
48
|
+
*
|
|
49
|
+
* @param config - Configuration for the HA signer
|
|
50
|
+
* @param deps - Optional dependencies (e.g., for testing)
|
|
51
|
+
* @returns An object containing the signer and database instances
|
|
52
|
+
*/
|
|
53
|
+
export async function createHASigner(
|
|
54
|
+
config: CreateHASignerConfig,
|
|
55
|
+
deps?: CreateHASignerDeps,
|
|
56
|
+
): Promise<{
|
|
57
|
+
signer: ValidatorHASigner;
|
|
58
|
+
db: SlashingProtectionDatabase;
|
|
59
|
+
}> {
|
|
60
|
+
const { databaseUrl, poolMaxCount, poolMinCount, poolIdleTimeoutMs, poolConnectionTimeoutMs, ...signerConfig } =
|
|
61
|
+
config;
|
|
62
|
+
|
|
63
|
+
// Create connection pool (or use provided pool)
|
|
64
|
+
let pool: Pool;
|
|
65
|
+
if (!deps?.pool) {
|
|
66
|
+
pool = new Pool({
|
|
67
|
+
connectionString: databaseUrl,
|
|
68
|
+
max: poolMaxCount ?? 10,
|
|
69
|
+
min: poolMinCount ?? 0,
|
|
70
|
+
idleTimeoutMillis: poolIdleTimeoutMs ?? 10_000,
|
|
71
|
+
connectionTimeoutMillis: poolConnectionTimeoutMs ?? 0,
|
|
72
|
+
});
|
|
73
|
+
} else {
|
|
74
|
+
pool = deps.pool;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Create database instance
|
|
78
|
+
const db = new PostgresSlashingProtectionDatabase(pool);
|
|
79
|
+
|
|
80
|
+
// Verify database schema is initialized and version matches
|
|
81
|
+
await db.initialize();
|
|
82
|
+
|
|
83
|
+
// Create signer
|
|
84
|
+
const signer = new ValidatorHASigner(db, { ...signerConfig, databaseUrl });
|
|
85
|
+
|
|
86
|
+
return { signer, db };
|
|
87
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Programmatic migration runner
|
|
3
|
+
*/
|
|
4
|
+
import { createLogger } from '@aztec/foundation/log';
|
|
5
|
+
|
|
6
|
+
import { runner } from 'node-pg-migrate';
|
|
7
|
+
import { dirname, join } from 'path';
|
|
8
|
+
import { fileURLToPath } from 'url';
|
|
9
|
+
|
|
10
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
11
|
+
const __dirname = dirname(__filename);
|
|
12
|
+
|
|
13
|
+
export interface RunMigrationsOptions {
|
|
14
|
+
/** Migration direction ('up' to apply, 'down' to rollback). Defaults to 'up'. */
|
|
15
|
+
direction?: 'up' | 'down';
|
|
16
|
+
/** Enable verbose output. Defaults to false. */
|
|
17
|
+
verbose?: boolean;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Run database migrations programmatically
|
|
22
|
+
*
|
|
23
|
+
* @param databaseUrl - PostgreSQL connection string
|
|
24
|
+
* @param options - Migration options (direction, verbose)
|
|
25
|
+
* @returns Array of applied migration names
|
|
26
|
+
*/
|
|
27
|
+
export async function runMigrations(databaseUrl: string, options: RunMigrationsOptions = {}): Promise<string[]> {
|
|
28
|
+
const direction = options.direction ?? 'up';
|
|
29
|
+
const verbose = options.verbose ?? false;
|
|
30
|
+
|
|
31
|
+
const log = createLogger('validator-ha-signer:migrations');
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
log.info(`Running migrations ${direction}...`);
|
|
35
|
+
|
|
36
|
+
const appliedMigrations = await runner({
|
|
37
|
+
databaseUrl,
|
|
38
|
+
dir: join(__dirname, 'db', 'migrations'),
|
|
39
|
+
direction,
|
|
40
|
+
migrationsTable: 'pgmigrations',
|
|
41
|
+
count: direction === 'down' ? 1 : Infinity,
|
|
42
|
+
verbose,
|
|
43
|
+
log: msg => (verbose ? log.info(msg) : log.debug(msg)),
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
if (appliedMigrations.length === 0) {
|
|
47
|
+
log.info('No migrations to apply - schema is up to date');
|
|
48
|
+
} else {
|
|
49
|
+
log.info(`Applied ${appliedMigrations.length} migration(s)`, {
|
|
50
|
+
migrations: appliedMigrations.map(m => m.name),
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return appliedMigrations.map(m => m.name);
|
|
55
|
+
} catch (error: any) {
|
|
56
|
+
log.error('Migration failed', error);
|
|
57
|
+
throw error;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,216 @@
|
|
|
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
|
+
*/
|
|
7
|
+
import { type Logger, createLogger } from '@aztec/foundation/log';
|
|
8
|
+
import { RunningPromise } from '@aztec/foundation/promise';
|
|
9
|
+
import { sleep } from '@aztec/foundation/sleep';
|
|
10
|
+
|
|
11
|
+
import { type CheckAndRecordParams, type DeleteDutyParams, DutyStatus, type RecordSuccessParams } from './db/types.js';
|
|
12
|
+
import { DutyAlreadySignedError, SlashingProtectionError } from './errors.js';
|
|
13
|
+
import type { SlashingProtectionConfig, SlashingProtectionDatabase } from './types.js';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Slashing Protection Service
|
|
17
|
+
*
|
|
18
|
+
* This service ensures that a validator only signs one block/attestation per slot,
|
|
19
|
+
* even when running multiple redundant nodes (HA setup).
|
|
20
|
+
*
|
|
21
|
+
* All nodes in the HA setup try to sign - the first one wins, others get
|
|
22
|
+
* DutyAlreadySignedError (normal) or SlashingProtectionError (if different data).
|
|
23
|
+
*
|
|
24
|
+
* Flow:
|
|
25
|
+
* 1. checkAndRecord() - Atomically try to acquire lock via tryInsertOrGetExisting
|
|
26
|
+
* 2. Caller performs the signing operation
|
|
27
|
+
* 3. recordSuccess() - Update to 'signed' status with signature
|
|
28
|
+
* OR deleteDuty() - Delete the record to allow retry
|
|
29
|
+
*/
|
|
30
|
+
export class SlashingProtectionService {
|
|
31
|
+
private readonly log: Logger;
|
|
32
|
+
private readonly pollingIntervalMs: number;
|
|
33
|
+
private readonly signingTimeoutMs: number;
|
|
34
|
+
|
|
35
|
+
private cleanupRunningPromise: RunningPromise;
|
|
36
|
+
|
|
37
|
+
constructor(
|
|
38
|
+
private readonly db: SlashingProtectionDatabase,
|
|
39
|
+
private readonly config: SlashingProtectionConfig,
|
|
40
|
+
) {
|
|
41
|
+
this.log = createLogger('slashing-protection');
|
|
42
|
+
this.pollingIntervalMs = config.pollingIntervalMs;
|
|
43
|
+
this.signingTimeoutMs = config.signingTimeoutMs;
|
|
44
|
+
|
|
45
|
+
this.cleanupRunningPromise = new RunningPromise(
|
|
46
|
+
this.cleanupStuckDuties.bind(this),
|
|
47
|
+
this.log,
|
|
48
|
+
this.config.maxStuckDutiesAgeMs,
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Check if a duty can be performed and acquire the lock if so.
|
|
54
|
+
*
|
|
55
|
+
* This method uses an atomic insert-or-get operation.
|
|
56
|
+
* It will:
|
|
57
|
+
* 1. Try to insert a new record with 'signing' status
|
|
58
|
+
* 2. If insert succeeds, we acquired the lock - return the lockToken
|
|
59
|
+
* 3. If a record exists, handle based on status:
|
|
60
|
+
* - SIGNED: Throw appropriate error (already signed or slashing protection)
|
|
61
|
+
* - FAILED: Delete the failed record
|
|
62
|
+
* - SIGNING: Wait and poll until status changes, then handle result
|
|
63
|
+
*
|
|
64
|
+
* @returns The lockToken that must be used for recordSuccess/deleteDuty
|
|
65
|
+
* @throws DutyAlreadySignedError if the duty was already completed
|
|
66
|
+
* @throws SlashingProtectionError if attempting to sign different data for same slot/duty
|
|
67
|
+
*/
|
|
68
|
+
async checkAndRecord(params: CheckAndRecordParams): Promise<string> {
|
|
69
|
+
const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
|
|
70
|
+
const startTime = Date.now();
|
|
71
|
+
|
|
72
|
+
this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
|
|
73
|
+
validatorAddress: validatorAddress.toString(),
|
|
74
|
+
nodeId,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
while (true) {
|
|
78
|
+
// insert if not present, get existing if present
|
|
79
|
+
const { isNew, record } = await this.db.tryInsertOrGetExisting(params);
|
|
80
|
+
|
|
81
|
+
if (isNew) {
|
|
82
|
+
// We successfully acquired the lock
|
|
83
|
+
this.log.info(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
|
|
84
|
+
validatorAddress: validatorAddress.toString(),
|
|
85
|
+
nodeId,
|
|
86
|
+
});
|
|
87
|
+
return record.lockToken;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Record already exists - handle based on status
|
|
91
|
+
if (record.status === DutyStatus.SIGNED) {
|
|
92
|
+
// Duty was already signed - check if same or different data
|
|
93
|
+
if (record.messageHash !== messageHash) {
|
|
94
|
+
this.log.verbose(`Slashing protection triggered for duty ${dutyType} at slot ${slot}`, {
|
|
95
|
+
validatorAddress: validatorAddress.toString(),
|
|
96
|
+
existingMessageHash: record.messageHash,
|
|
97
|
+
attemptedMessageHash: messageHash,
|
|
98
|
+
existingNodeId: record.nodeId,
|
|
99
|
+
attemptingNodeId: nodeId,
|
|
100
|
+
});
|
|
101
|
+
throw new SlashingProtectionError(slot, dutyType, record.messageHash, messageHash);
|
|
102
|
+
}
|
|
103
|
+
throw new DutyAlreadySignedError(slot, dutyType, record.nodeId);
|
|
104
|
+
} else if (record.status === DutyStatus.SIGNING) {
|
|
105
|
+
// Another node is currently signing - check for timeout
|
|
106
|
+
if (Date.now() - startTime > this.signingTimeoutMs) {
|
|
107
|
+
this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
|
|
108
|
+
validatorAddress: validatorAddress.toString(),
|
|
109
|
+
timeoutMs: this.signingTimeoutMs,
|
|
110
|
+
signingNodeId: record.nodeId,
|
|
111
|
+
});
|
|
112
|
+
throw new DutyAlreadySignedError(slot, dutyType, 'unknown (timeout)');
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Wait and poll
|
|
116
|
+
this.log.debug(`Waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
|
|
117
|
+
validatorAddress: validatorAddress.toString(),
|
|
118
|
+
signingNodeId: record.nodeId,
|
|
119
|
+
});
|
|
120
|
+
await sleep(this.pollingIntervalMs);
|
|
121
|
+
// Loop continues - next iteration will check status again
|
|
122
|
+
} else {
|
|
123
|
+
throw new Error(`Unknown duty status: ${record.status}`);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Record a successful signing operation.
|
|
130
|
+
* Updates the duty status to 'signed' and stores the signature.
|
|
131
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
132
|
+
*
|
|
133
|
+
* @returns true if the update succeeded, false if token didn't match
|
|
134
|
+
*/
|
|
135
|
+
async recordSuccess(params: RecordSuccessParams): Promise<boolean> {
|
|
136
|
+
const { validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
|
|
137
|
+
|
|
138
|
+
const success = await this.db.updateDutySigned(validatorAddress, slot, dutyType, signature.toString(), lockToken);
|
|
139
|
+
|
|
140
|
+
if (success) {
|
|
141
|
+
this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
|
|
142
|
+
validatorAddress: validatorAddress.toString(),
|
|
143
|
+
nodeId,
|
|
144
|
+
});
|
|
145
|
+
} else {
|
|
146
|
+
this.log.warn(`Failed to record successful signing for duty ${dutyType} at slot ${slot}: invalid token`, {
|
|
147
|
+
validatorAddress: validatorAddress.toString(),
|
|
148
|
+
nodeId,
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return success;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Delete a duty record after a failed signing operation.
|
|
157
|
+
* Removes the record to allow another node/attempt to retry.
|
|
158
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
159
|
+
*
|
|
160
|
+
* @returns true if the delete succeeded, false if token didn't match
|
|
161
|
+
*/
|
|
162
|
+
async deleteDuty(params: DeleteDutyParams): Promise<boolean> {
|
|
163
|
+
const { validatorAddress, slot, dutyType, lockToken } = params;
|
|
164
|
+
|
|
165
|
+
const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken);
|
|
166
|
+
|
|
167
|
+
if (success) {
|
|
168
|
+
this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
|
|
169
|
+
validatorAddress: validatorAddress.toString(),
|
|
170
|
+
});
|
|
171
|
+
} else {
|
|
172
|
+
this.log.warn(`Failed to delete duty ${dutyType} at slot ${slot}: invalid token`, {
|
|
173
|
+
validatorAddress: validatorAddress.toString(),
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
return success;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Get the node ID for this service
|
|
182
|
+
*/
|
|
183
|
+
get nodeId(): string {
|
|
184
|
+
return this.config.nodeId;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Start running tasks.
|
|
189
|
+
* Cleanup runs immediately on start to recover from any previous crashes.
|
|
190
|
+
*/
|
|
191
|
+
start() {
|
|
192
|
+
this.cleanupRunningPromise.start();
|
|
193
|
+
this.log.info('Slashing protection service started', { nodeId: this.config.nodeId });
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Stop the background cleanup task.
|
|
198
|
+
*/
|
|
199
|
+
async stop() {
|
|
200
|
+
await this.cleanupRunningPromise.stop();
|
|
201
|
+
this.log.info('Slashing protection service stopped', { nodeId: this.config.nodeId });
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
/**
|
|
205
|
+
* Cleanup own stuck duties
|
|
206
|
+
*/
|
|
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`, {
|
|
211
|
+
nodeId: this.config.nodeId,
|
|
212
|
+
maxStuckDutiesAgeMs: this.config.maxStuckDutiesAgeMs,
|
|
213
|
+
});
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import type { EthAddress } from '@aztec/foundation/eth-address';
|
|
2
|
+
|
|
3
|
+
import type { Pool } from 'pg';
|
|
4
|
+
|
|
5
|
+
import type { CreateHASignerConfig, SlashingProtectionConfig } from './config.js';
|
|
6
|
+
import type {
|
|
7
|
+
CheckAndRecordParams,
|
|
8
|
+
DeleteDutyParams,
|
|
9
|
+
DutyIdentifier,
|
|
10
|
+
DutyType,
|
|
11
|
+
RecordSuccessParams,
|
|
12
|
+
ValidatorDutyRecord,
|
|
13
|
+
} from './db/types.js';
|
|
14
|
+
|
|
15
|
+
export type {
|
|
16
|
+
CheckAndRecordParams,
|
|
17
|
+
CreateHASignerConfig,
|
|
18
|
+
DeleteDutyParams,
|
|
19
|
+
DutyIdentifier,
|
|
20
|
+
RecordSuccessParams,
|
|
21
|
+
SlashingProtectionConfig,
|
|
22
|
+
ValidatorDutyRecord,
|
|
23
|
+
};
|
|
24
|
+
export { DutyStatus, DutyType } from './db/types.js';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Result of tryInsertOrGetExisting operation
|
|
28
|
+
*/
|
|
29
|
+
export interface TryInsertOrGetResult {
|
|
30
|
+
/** True if we inserted a new record, false if we got an existing record */
|
|
31
|
+
isNew: boolean;
|
|
32
|
+
/** The record (either newly inserted or existing) */
|
|
33
|
+
record: ValidatorDutyRecord;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* deps for creating an HA signer
|
|
38
|
+
*/
|
|
39
|
+
export interface CreateHASignerDeps {
|
|
40
|
+
/**
|
|
41
|
+
* Optional PostgreSQL connection pool
|
|
42
|
+
* If provided, databaseUrl and poolConfig are ignored
|
|
43
|
+
*/
|
|
44
|
+
pool?: Pool;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Context required for slashing protection during signing operations
|
|
49
|
+
*/
|
|
50
|
+
export interface SigningContext {
|
|
51
|
+
/** 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;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Database interface for slashing protection operations
|
|
61
|
+
* This abstraction allows for different database implementations (PostgreSQL, SQLite, etc.)
|
|
62
|
+
*
|
|
63
|
+
* The interface is designed around 3 core operations:
|
|
64
|
+
* 1. tryInsertOrGetExisting - Atomically insert or get existing record (eliminates race conditions)
|
|
65
|
+
* 2. updateDutySigned - Update to signed status on success
|
|
66
|
+
* 3. deleteDuty - Delete a duty record on failure
|
|
67
|
+
*/
|
|
68
|
+
export interface SlashingProtectionDatabase {
|
|
69
|
+
/**
|
|
70
|
+
* Atomically try to insert a new duty record, or get the existing one if present.
|
|
71
|
+
*
|
|
72
|
+
* @returns { isNew: true, record } if we successfully inserted and acquired the lock
|
|
73
|
+
* @returns { isNew: false, record } if a record already exists (caller should handle based on status)
|
|
74
|
+
*/
|
|
75
|
+
tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult>;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Update a duty to 'signed' status with the signature.
|
|
79
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
80
|
+
*
|
|
81
|
+
* @returns true if the update succeeded, false if token didn't match or duty not found
|
|
82
|
+
*/
|
|
83
|
+
updateDutySigned(
|
|
84
|
+
validatorAddress: EthAddress,
|
|
85
|
+
slot: bigint,
|
|
86
|
+
dutyType: DutyType,
|
|
87
|
+
signature: string,
|
|
88
|
+
lockToken: string,
|
|
89
|
+
): Promise<boolean>;
|
|
90
|
+
|
|
91
|
+
/**
|
|
92
|
+
* Delete a duty record.
|
|
93
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
94
|
+
* Used when signing fails to allow another node/attempt to retry.
|
|
95
|
+
*
|
|
96
|
+
* @returns true if the delete succeeded, false if token didn't match or duty not found
|
|
97
|
+
*/
|
|
98
|
+
deleteDuty(validatorAddress: EthAddress, slot: bigint, dutyType: DutyType, lockToken: string): Promise<boolean>;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Cleanup own stuck duties
|
|
102
|
+
* @returns the number of duties cleaned up
|
|
103
|
+
*/
|
|
104
|
+
cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
|
|
105
|
+
}
|