@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.
- package/README.md +187 -0
- package/dest/config.d.ts +101 -0
- package/dest/config.d.ts.map +1 -0
- package/dest/config.js +92 -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 +84 -0
- package/dest/db/postgres.d.ts.map +1 -0
- package/dest/db/postgres.js +210 -0
- package/dest/db/schema.d.ts +95 -0
- package/dest/db/schema.d.ts.map +1 -0
- package/dest/db/schema.js +229 -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 +166 -0
- package/dest/db/types.d.ts.map +1 -0
- package/dest/db/types.js +49 -0
- package/dest/errors.d.ts +34 -0
- package/dest/errors.d.ts.map +1 -0
- package/dest/errors.js +34 -0
- package/dest/factory.d.ts +42 -0
- package/dest/factory.d.ts.map +1 -0
- package/dest/factory.js +70 -0
- package/dest/migrations.d.ts +15 -0
- package/dest/migrations.d.ts.map +1 -0
- package/dest/migrations.js +53 -0
- package/dest/slashing_protection_service.d.ts +84 -0
- package/dest/slashing_protection_service.d.ts.map +1 -0
- package/dest/slashing_protection_service.js +225 -0
- package/dest/test/pglite_pool.d.ts +92 -0
- package/dest/test/pglite_pool.d.ts.map +1 -0
- package/dest/test/pglite_pool.js +210 -0
- package/dest/types.d.ts +152 -0
- package/dest/types.d.ts.map +1 -0
- package/dest/types.js +21 -0
- package/dest/validator_ha_signer.d.ts +71 -0
- package/dest/validator_ha_signer.d.ts.map +1 -0
- package/dest/validator_ha_signer.js +132 -0
- package/package.json +106 -0
- package/src/config.ts +149 -0
- package/src/db/index.ts +3 -0
- package/src/db/migrations/1_initial-schema.ts +26 -0
- package/src/db/postgres.ts +284 -0
- package/src/db/schema.ts +266 -0
- package/src/db/test_helper.ts +17 -0
- package/src/db/types.ts +206 -0
- package/src/errors.ts +47 -0
- package/src/factory.ts +82 -0
- package/src/migrations.ts +75 -0
- package/src/slashing_protection_service.ts +287 -0
- package/src/test/pglite_pool.ts +256 -0
- package/src/types.ts +226 -0
- package/src/validator_ha_signer.ts +162 -0
package/src/db/types.ts
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
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
|
+
rollup_address: string;
|
|
10
|
+
validator_address: string;
|
|
11
|
+
slot: string;
|
|
12
|
+
block_number: string;
|
|
13
|
+
block_index_within_checkpoint: number;
|
|
14
|
+
duty_type: DutyType;
|
|
15
|
+
status: DutyStatus;
|
|
16
|
+
message_hash: string;
|
|
17
|
+
signature: string | null;
|
|
18
|
+
node_id: string;
|
|
19
|
+
lock_token: string;
|
|
20
|
+
started_at: Date;
|
|
21
|
+
completed_at: Date | null;
|
|
22
|
+
error_message: string | null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Row type from INSERT_OR_GET_DUTY query (includes is_new flag)
|
|
27
|
+
*/
|
|
28
|
+
export interface InsertOrGetRow extends DutyRow {
|
|
29
|
+
is_new: boolean;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Type of validator duty being performed
|
|
34
|
+
*/
|
|
35
|
+
export enum DutyType {
|
|
36
|
+
BLOCK_PROPOSAL = 'BLOCK_PROPOSAL',
|
|
37
|
+
CHECKPOINT_PROPOSAL = 'CHECKPOINT_PROPOSAL',
|
|
38
|
+
ATTESTATION = 'ATTESTATION',
|
|
39
|
+
ATTESTATIONS_AND_SIGNERS = 'ATTESTATIONS_AND_SIGNERS',
|
|
40
|
+
GOVERNANCE_VOTE = 'GOVERNANCE_VOTE',
|
|
41
|
+
SLASHING_VOTE = 'SLASHING_VOTE',
|
|
42
|
+
AUTH_REQUEST = 'AUTH_REQUEST',
|
|
43
|
+
TXS = 'TXS',
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Status of a duty in the database
|
|
48
|
+
*/
|
|
49
|
+
export enum DutyStatus {
|
|
50
|
+
SIGNING = 'signing',
|
|
51
|
+
SIGNED = 'signed',
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Record of a validator duty in the database
|
|
56
|
+
*/
|
|
57
|
+
export interface ValidatorDutyRecord {
|
|
58
|
+
/** Ethereum address of the rollup contract */
|
|
59
|
+
rollupAddress: EthAddress;
|
|
60
|
+
/** Ethereum address of the validator */
|
|
61
|
+
validatorAddress: EthAddress;
|
|
62
|
+
/** Slot number for this duty */
|
|
63
|
+
slot: SlotNumber;
|
|
64
|
+
/** Block number for this duty */
|
|
65
|
+
blockNumber: BlockNumber;
|
|
66
|
+
/** Block index within checkpoint (0, 1, 2... for block proposals, -1 for other duty types) */
|
|
67
|
+
blockIndexWithinCheckpoint: number;
|
|
68
|
+
/** Type of duty being performed */
|
|
69
|
+
dutyType: DutyType;
|
|
70
|
+
/** Current status of the duty */
|
|
71
|
+
status: DutyStatus;
|
|
72
|
+
/** The signing root (hash) for this duty */
|
|
73
|
+
messageHash: string;
|
|
74
|
+
/** The signature (populated after successful signing) */
|
|
75
|
+
signature?: string;
|
|
76
|
+
/** Unique identifier for the node that acquired the lock */
|
|
77
|
+
nodeId: string;
|
|
78
|
+
/** Secret token for verifying ownership of the duty lock */
|
|
79
|
+
lockToken: string;
|
|
80
|
+
/** When the duty signing was started */
|
|
81
|
+
startedAt: Date;
|
|
82
|
+
/** When the duty signing was completed (success or failure) */
|
|
83
|
+
completedAt?: Date;
|
|
84
|
+
/** Error message (currently unused) */
|
|
85
|
+
errorMessage?: string;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Duty identifier for block proposals.
|
|
90
|
+
* blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
|
|
91
|
+
*/
|
|
92
|
+
export interface BlockProposalDutyIdentifier {
|
|
93
|
+
rollupAddress: EthAddress;
|
|
94
|
+
validatorAddress: EthAddress;
|
|
95
|
+
slot: SlotNumber;
|
|
96
|
+
/** Block index within checkpoint (0, 1, 2...). Required for block proposals. */
|
|
97
|
+
blockIndexWithinCheckpoint: IndexWithinCheckpoint;
|
|
98
|
+
dutyType: DutyType.BLOCK_PROPOSAL;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Duty identifier for non-block-proposal duties.
|
|
103
|
+
* blockIndexWithinCheckpoint is not applicable (internally stored as -1).
|
|
104
|
+
*/
|
|
105
|
+
export interface OtherDutyIdentifier {
|
|
106
|
+
rollupAddress: EthAddress;
|
|
107
|
+
validatorAddress: EthAddress;
|
|
108
|
+
slot: SlotNumber;
|
|
109
|
+
dutyType:
|
|
110
|
+
| DutyType.CHECKPOINT_PROPOSAL
|
|
111
|
+
| DutyType.ATTESTATION
|
|
112
|
+
| DutyType.ATTESTATIONS_AND_SIGNERS
|
|
113
|
+
| DutyType.GOVERNANCE_VOTE
|
|
114
|
+
| DutyType.SLASHING_VOTE
|
|
115
|
+
| DutyType.AUTH_REQUEST
|
|
116
|
+
| DutyType.TXS;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Minimal info needed to identify a unique duty.
|
|
121
|
+
* Uses discriminated union to enforce type safety:
|
|
122
|
+
* - BLOCK_PROPOSAL duties MUST have blockIndexWithinCheckpoint >= 0
|
|
123
|
+
* - Other duty types do NOT have blockIndexWithinCheckpoint (internally -1)
|
|
124
|
+
*/
|
|
125
|
+
export type DutyIdentifier = BlockProposalDutyIdentifier | OtherDutyIdentifier;
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Validates and normalizes the block index for a duty.
|
|
129
|
+
* - BLOCK_PROPOSAL: validates blockIndexWithinCheckpoint is provided and >= 0
|
|
130
|
+
* - Other duty types: always returns -1
|
|
131
|
+
*
|
|
132
|
+
* @throws Error if BLOCK_PROPOSAL is missing blockIndexWithinCheckpoint or has invalid value
|
|
133
|
+
*/
|
|
134
|
+
export function normalizeBlockIndex(dutyType: DutyType, blockIndexWithinCheckpoint: number | undefined): number {
|
|
135
|
+
if (dutyType === DutyType.BLOCK_PROPOSAL) {
|
|
136
|
+
if (blockIndexWithinCheckpoint === undefined) {
|
|
137
|
+
throw new Error('BLOCK_PROPOSAL duties require blockIndexWithinCheckpoint to be specified');
|
|
138
|
+
}
|
|
139
|
+
if (blockIndexWithinCheckpoint < 0) {
|
|
140
|
+
throw new Error(
|
|
141
|
+
`BLOCK_PROPOSAL duties require blockIndexWithinCheckpoint >= 0, got ${blockIndexWithinCheckpoint}`,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
return blockIndexWithinCheckpoint;
|
|
145
|
+
}
|
|
146
|
+
// For all other duty types, always use -1
|
|
147
|
+
return -1;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Gets the block index from a DutyIdentifier.
|
|
152
|
+
* - BLOCK_PROPOSAL: returns the blockIndexWithinCheckpoint
|
|
153
|
+
* - Other duty types: returns -1
|
|
154
|
+
*/
|
|
155
|
+
export function getBlockIndexFromDutyIdentifier(duty: DutyIdentifier): number {
|
|
156
|
+
if (duty.dutyType === DutyType.BLOCK_PROPOSAL) {
|
|
157
|
+
return duty.blockIndexWithinCheckpoint;
|
|
158
|
+
}
|
|
159
|
+
return -1;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Additional parameters for checking and recording a new duty
|
|
164
|
+
*/
|
|
165
|
+
interface CheckAndRecordExtra {
|
|
166
|
+
/** Block number for this duty */
|
|
167
|
+
blockNumber: BlockNumber | CheckpointNumber;
|
|
168
|
+
/** The signing root (hash) for this duty */
|
|
169
|
+
messageHash: string;
|
|
170
|
+
/** Identifier for the node that acquired the lock */
|
|
171
|
+
nodeId: string;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Parameters for checking and recording a new duty.
|
|
176
|
+
* Uses intersection with DutyIdentifier to preserve the discriminated union.
|
|
177
|
+
*/
|
|
178
|
+
export type CheckAndRecordParams = DutyIdentifier & CheckAndRecordExtra;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Additional parameters for recording a successful signing
|
|
182
|
+
*/
|
|
183
|
+
interface RecordSuccessExtra {
|
|
184
|
+
signature: Signature;
|
|
185
|
+
nodeId: string;
|
|
186
|
+
lockToken: string;
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Parameters for recording a successful signing.
|
|
191
|
+
* Uses intersection with DutyIdentifier to preserve the discriminated union.
|
|
192
|
+
*/
|
|
193
|
+
export type RecordSuccessParams = DutyIdentifier & RecordSuccessExtra;
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Additional parameters for deleting a duty
|
|
197
|
+
*/
|
|
198
|
+
interface DeleteDutyExtra {
|
|
199
|
+
lockToken: string;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Parameters for deleting a duty.
|
|
204
|
+
* Uses intersection with DutyIdentifier to preserve the discriminated union.
|
|
205
|
+
*/
|
|
206
|
+
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
|
+
}
|
|
@@ -0,0 +1,287 @@
|
|
|
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 {
|
|
12
|
+
type CheckAndRecordParams,
|
|
13
|
+
type DeleteDutyParams,
|
|
14
|
+
DutyStatus,
|
|
15
|
+
type RecordSuccessParams,
|
|
16
|
+
getBlockIndexFromDutyIdentifier,
|
|
17
|
+
} from './db/types.js';
|
|
18
|
+
import { DutyAlreadySignedError, SlashingProtectionError } from './errors.js';
|
|
19
|
+
import type { SlashingProtectionDatabase, ValidatorHASignerConfig } from './types.js';
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Slashing Protection Service
|
|
23
|
+
*
|
|
24
|
+
* This service ensures that a validator only signs one block/attestation per slot,
|
|
25
|
+
* even when running multiple redundant nodes (HA setup).
|
|
26
|
+
*
|
|
27
|
+
* All nodes in the HA setup try to sign - the first one wins, others get
|
|
28
|
+
* DutyAlreadySignedError (normal) or SlashingProtectionError (if different data).
|
|
29
|
+
*
|
|
30
|
+
* Flow:
|
|
31
|
+
* 1. checkAndRecord() - Atomically try to acquire lock via tryInsertOrGetExisting
|
|
32
|
+
* 2. Caller performs the signing operation
|
|
33
|
+
* 3. recordSuccess() - Update to 'signed' status with signature
|
|
34
|
+
* OR deleteDuty() - Delete the record to allow retry
|
|
35
|
+
*/
|
|
36
|
+
export class SlashingProtectionService {
|
|
37
|
+
private readonly log: Logger;
|
|
38
|
+
private readonly pollingIntervalMs: number;
|
|
39
|
+
private readonly signingTimeoutMs: number;
|
|
40
|
+
private readonly maxStuckDutiesAgeMs: number;
|
|
41
|
+
|
|
42
|
+
private cleanupRunningPromise: RunningPromise;
|
|
43
|
+
private lastOldDutiesCleanupAtMs?: number;
|
|
44
|
+
|
|
45
|
+
constructor(
|
|
46
|
+
private readonly db: SlashingProtectionDatabase,
|
|
47
|
+
private readonly config: ValidatorHASignerConfig,
|
|
48
|
+
) {
|
|
49
|
+
this.log = createLogger('slashing-protection');
|
|
50
|
+
this.pollingIntervalMs = config.pollingIntervalMs;
|
|
51
|
+
this.signingTimeoutMs = config.signingTimeoutMs;
|
|
52
|
+
// Default to 144s (2x 72s Aztec slot duration) if not explicitly configured
|
|
53
|
+
this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? 144_000;
|
|
54
|
+
|
|
55
|
+
this.cleanupRunningPromise = new RunningPromise(this.cleanup.bind(this), this.log, this.maxStuckDutiesAgeMs);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Check if a duty can be performed and acquire the lock if so.
|
|
60
|
+
*
|
|
61
|
+
* This method uses an atomic insert-or-get operation.
|
|
62
|
+
* It will:
|
|
63
|
+
* 1. Try to insert a new record with 'signing' status
|
|
64
|
+
* 2. If insert succeeds, we acquired the lock - return the lockToken
|
|
65
|
+
* 3. If a record exists, handle based on status:
|
|
66
|
+
* - SIGNED: Throw appropriate error (already signed or slashing protection)
|
|
67
|
+
* - SIGNING: Wait and poll until status changes, then handle result
|
|
68
|
+
*
|
|
69
|
+
* @returns The lockToken that must be used for recordSuccess/deleteDuty
|
|
70
|
+
* @throws DutyAlreadySignedError if the duty was already completed
|
|
71
|
+
* @throws SlashingProtectionError if attempting to sign different data for same slot/duty
|
|
72
|
+
*/
|
|
73
|
+
async checkAndRecord(params: CheckAndRecordParams): Promise<string> {
|
|
74
|
+
const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
|
|
75
|
+
const startTime = Date.now();
|
|
76
|
+
|
|
77
|
+
this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
|
|
78
|
+
validatorAddress: validatorAddress.toString(),
|
|
79
|
+
nodeId,
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
while (true) {
|
|
83
|
+
// insert if not present, get existing if present
|
|
84
|
+
const { isNew, record } = await this.db.tryInsertOrGetExisting(params);
|
|
85
|
+
|
|
86
|
+
if (isNew) {
|
|
87
|
+
// We successfully acquired the lock
|
|
88
|
+
this.log.info(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
|
|
89
|
+
validatorAddress: validatorAddress.toString(),
|
|
90
|
+
nodeId,
|
|
91
|
+
});
|
|
92
|
+
return record.lockToken;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Record already exists - handle based on status
|
|
96
|
+
if (record.status === DutyStatus.SIGNED) {
|
|
97
|
+
// Duty was already signed - check if same or different data
|
|
98
|
+
if (record.messageHash !== messageHash) {
|
|
99
|
+
this.log.verbose(`Slashing protection triggered for duty ${dutyType} at slot ${slot}`, {
|
|
100
|
+
validatorAddress: validatorAddress.toString(),
|
|
101
|
+
existingMessageHash: record.messageHash,
|
|
102
|
+
attemptedMessageHash: messageHash,
|
|
103
|
+
existingNodeId: record.nodeId,
|
|
104
|
+
attemptingNodeId: nodeId,
|
|
105
|
+
});
|
|
106
|
+
throw new SlashingProtectionError(
|
|
107
|
+
slot,
|
|
108
|
+
dutyType,
|
|
109
|
+
record.blockIndexWithinCheckpoint,
|
|
110
|
+
record.messageHash,
|
|
111
|
+
messageHash,
|
|
112
|
+
record.nodeId,
|
|
113
|
+
);
|
|
114
|
+
}
|
|
115
|
+
throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
|
|
116
|
+
} else if (record.status === DutyStatus.SIGNING) {
|
|
117
|
+
// Another node is currently signing - check for timeout
|
|
118
|
+
if (Date.now() - startTime > this.signingTimeoutMs) {
|
|
119
|
+
this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
|
|
120
|
+
validatorAddress: validatorAddress.toString(),
|
|
121
|
+
timeoutMs: this.signingTimeoutMs,
|
|
122
|
+
signingNodeId: record.nodeId,
|
|
123
|
+
});
|
|
124
|
+
throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
// Wait and poll
|
|
128
|
+
this.log.debug(`Waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
|
|
129
|
+
validatorAddress: validatorAddress.toString(),
|
|
130
|
+
signingNodeId: record.nodeId,
|
|
131
|
+
});
|
|
132
|
+
await sleep(this.pollingIntervalMs);
|
|
133
|
+
// Loop continues - next iteration will check status again
|
|
134
|
+
} else {
|
|
135
|
+
throw new Error(`Unknown duty status: ${record.status}`);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Record a successful signing operation.
|
|
142
|
+
* Updates the duty status to 'signed' and stores the signature.
|
|
143
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
144
|
+
*
|
|
145
|
+
* @returns true if the update succeeded, false if token didn't match
|
|
146
|
+
*/
|
|
147
|
+
async recordSuccess(params: RecordSuccessParams): Promise<boolean> {
|
|
148
|
+
const { rollupAddress, validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
|
|
149
|
+
const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
|
|
150
|
+
|
|
151
|
+
const success = await this.db.updateDutySigned(
|
|
152
|
+
rollupAddress,
|
|
153
|
+
validatorAddress,
|
|
154
|
+
slot,
|
|
155
|
+
dutyType,
|
|
156
|
+
signature.toString(),
|
|
157
|
+
lockToken,
|
|
158
|
+
blockIndexWithinCheckpoint,
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
if (success) {
|
|
162
|
+
this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
|
|
163
|
+
validatorAddress: validatorAddress.toString(),
|
|
164
|
+
nodeId,
|
|
165
|
+
});
|
|
166
|
+
} else {
|
|
167
|
+
this.log.warn(`Failed to record successful signing for duty ${dutyType} at slot ${slot}: invalid token`, {
|
|
168
|
+
validatorAddress: validatorAddress.toString(),
|
|
169
|
+
nodeId,
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
return success;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Delete a duty record after a failed signing operation.
|
|
178
|
+
* Removes the record to allow another node/attempt to retry.
|
|
179
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
180
|
+
*
|
|
181
|
+
* @returns true if the delete succeeded, false if token didn't match
|
|
182
|
+
*/
|
|
183
|
+
async deleteDuty(params: DeleteDutyParams): Promise<boolean> {
|
|
184
|
+
const { rollupAddress, validatorAddress, slot, dutyType, lockToken } = params;
|
|
185
|
+
const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
|
|
186
|
+
|
|
187
|
+
const success = await this.db.deleteDuty(
|
|
188
|
+
rollupAddress,
|
|
189
|
+
validatorAddress,
|
|
190
|
+
slot,
|
|
191
|
+
dutyType,
|
|
192
|
+
lockToken,
|
|
193
|
+
blockIndexWithinCheckpoint,
|
|
194
|
+
);
|
|
195
|
+
|
|
196
|
+
if (success) {
|
|
197
|
+
this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
|
|
198
|
+
validatorAddress: validatorAddress.toString(),
|
|
199
|
+
});
|
|
200
|
+
} else {
|
|
201
|
+
this.log.warn(`Failed to delete duty ${dutyType} at slot ${slot}: invalid token`, {
|
|
202
|
+
validatorAddress: validatorAddress.toString(),
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
return success;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Get the node ID for this service
|
|
211
|
+
*/
|
|
212
|
+
get nodeId(): string {
|
|
213
|
+
return this.config.nodeId;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Start running tasks.
|
|
218
|
+
* Cleanup runs immediately on start to recover from any previous crashes.
|
|
219
|
+
*/
|
|
220
|
+
/**
|
|
221
|
+
* Start the background cleanup task.
|
|
222
|
+
* Also performs one-time cleanup of duties with outdated rollup addresses.
|
|
223
|
+
*/
|
|
224
|
+
async start() {
|
|
225
|
+
// One-time cleanup at startup: remove duties from previous rollup versions
|
|
226
|
+
const numOutdatedRollupDuties = await this.db.cleanupOutdatedRollupDuties(this.config.l1Contracts.rollupAddress);
|
|
227
|
+
if (numOutdatedRollupDuties > 0) {
|
|
228
|
+
this.log.info(`Cleaned up ${numOutdatedRollupDuties} duties with outdated rollup address at startup`, {
|
|
229
|
+
currentRollupAddress: this.config.l1Contracts.rollupAddress.toString(),
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
this.cleanupRunningPromise.start();
|
|
234
|
+
this.log.info('Slashing protection service started', { nodeId: this.config.nodeId });
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
/**
|
|
238
|
+
* Stop the background cleanup task.
|
|
239
|
+
*/
|
|
240
|
+
async stop() {
|
|
241
|
+
await this.cleanupRunningPromise.stop();
|
|
242
|
+
this.log.info('Slashing protection service stopped', { nodeId: this.config.nodeId });
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Close the database connection.
|
|
247
|
+
* Should be called after stop() during graceful shutdown.
|
|
248
|
+
*/
|
|
249
|
+
async close() {
|
|
250
|
+
await this.db.close();
|
|
251
|
+
this.log.info('Slashing protection database connection closed');
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* Periodic cleanup of stuck duties and optionally old signed duties.
|
|
256
|
+
* Runs in the background via RunningPromise.
|
|
257
|
+
*/
|
|
258
|
+
private async cleanup() {
|
|
259
|
+
// 1. Clean up stuck duties (our own node's duties that got stuck in 'signing' status)
|
|
260
|
+
const numStuckDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
|
|
261
|
+
if (numStuckDuties > 0) {
|
|
262
|
+
this.log.verbose(`Cleaned up ${numStuckDuties} stuck duties`, {
|
|
263
|
+
nodeId: this.config.nodeId,
|
|
264
|
+
maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs,
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
// 2. Clean up old signed duties if configured
|
|
269
|
+
// we shouldn't run this as often as stuck duty cleanup.
|
|
270
|
+
if (this.config.cleanupOldDutiesAfterHours !== undefined) {
|
|
271
|
+
const maxAgeMs = this.config.cleanupOldDutiesAfterHours * 60 * 60 * 1000;
|
|
272
|
+
const nowMs = Date.now();
|
|
273
|
+
const shouldRun =
|
|
274
|
+
this.lastOldDutiesCleanupAtMs === undefined || nowMs - this.lastOldDutiesCleanupAtMs >= maxAgeMs;
|
|
275
|
+
if (shouldRun) {
|
|
276
|
+
const numOldDuties = await this.db.cleanupOldDuties(maxAgeMs);
|
|
277
|
+
this.lastOldDutiesCleanupAtMs = nowMs;
|
|
278
|
+
if (numOldDuties > 0) {
|
|
279
|
+
this.log.verbose(`Cleaned up ${numOldDuties} old signed duties`, {
|
|
280
|
+
cleanupOldDutiesAfterHours: this.config.cleanupOldDutiesAfterHours,
|
|
281
|
+
maxAgeMs,
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
}
|