@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.
- package/README.md +187 -0
- package/dest/config.d.ts +79 -0
- package/dest/config.d.ts.map +1 -0
- package/dest/config.js +73 -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 +70 -0
- package/dest/db/postgres.d.ts.map +1 -0
- package/dest/db/postgres.js +181 -0
- package/dest/db/schema.d.ts +89 -0
- package/dest/db/schema.d.ts.map +1 -0
- package/dest/db/schema.js +213 -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 +161 -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 +80 -0
- package/dest/slashing_protection_service.d.ts.map +1 -0
- package/dest/slashing_protection_service.js +196 -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 +139 -0
- package/dest/types.d.ts.map +1 -0
- package/dest/types.js +21 -0
- package/dest/validator_ha_signer.d.ts +70 -0
- package/dest/validator_ha_signer.d.ts.map +1 -0
- package/dest/validator_ha_signer.js +127 -0
- package/package.json +105 -0
- package/src/config.ts +125 -0
- package/src/db/index.ts +3 -0
- package/src/db/migrations/1_initial-schema.ts +26 -0
- package/src/db/postgres.ts +251 -0
- package/src/db/schema.ts +248 -0
- package/src/db/test_helper.ts +17 -0
- package/src/db/types.ts +201 -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 +250 -0
- package/src/test/pglite_pool.ts +256 -0
- package/src/types.ts +207 -0
- package/src/validator_ha_signer.ts +157 -0
|
@@ -0,0 +1,250 @@
|
|
|
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
|
+
|
|
44
|
+
constructor(
|
|
45
|
+
private readonly db: SlashingProtectionDatabase,
|
|
46
|
+
private readonly config: ValidatorHASignerConfig,
|
|
47
|
+
) {
|
|
48
|
+
this.log = createLogger('slashing-protection');
|
|
49
|
+
this.pollingIntervalMs = config.pollingIntervalMs;
|
|
50
|
+
this.signingTimeoutMs = config.signingTimeoutMs;
|
|
51
|
+
// Default to 144s (2x 72s Aztec slot duration) if not explicitly configured
|
|
52
|
+
this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? 144_000;
|
|
53
|
+
|
|
54
|
+
this.cleanupRunningPromise = new RunningPromise(
|
|
55
|
+
this.cleanupStuckDuties.bind(this),
|
|
56
|
+
this.log,
|
|
57
|
+
this.maxStuckDutiesAgeMs,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Check if a duty can be performed and acquire the lock if so.
|
|
63
|
+
*
|
|
64
|
+
* This method uses an atomic insert-or-get operation.
|
|
65
|
+
* It will:
|
|
66
|
+
* 1. Try to insert a new record with 'signing' status
|
|
67
|
+
* 2. If insert succeeds, we acquired the lock - return the lockToken
|
|
68
|
+
* 3. If a record exists, handle based on status:
|
|
69
|
+
* - SIGNED: Throw appropriate error (already signed or slashing protection)
|
|
70
|
+
* - FAILED: Delete the failed record
|
|
71
|
+
* - SIGNING: Wait and poll until status changes, then handle result
|
|
72
|
+
*
|
|
73
|
+
* @returns The lockToken that must be used for recordSuccess/deleteDuty
|
|
74
|
+
* @throws DutyAlreadySignedError if the duty was already completed
|
|
75
|
+
* @throws SlashingProtectionError if attempting to sign different data for same slot/duty
|
|
76
|
+
*/
|
|
77
|
+
async checkAndRecord(params: CheckAndRecordParams): Promise<string> {
|
|
78
|
+
const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
|
|
79
|
+
const startTime = Date.now();
|
|
80
|
+
|
|
81
|
+
this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
|
|
82
|
+
validatorAddress: validatorAddress.toString(),
|
|
83
|
+
nodeId,
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
while (true) {
|
|
87
|
+
// insert if not present, get existing if present
|
|
88
|
+
const { isNew, record } = await this.db.tryInsertOrGetExisting(params);
|
|
89
|
+
|
|
90
|
+
if (isNew) {
|
|
91
|
+
// We successfully acquired the lock
|
|
92
|
+
this.log.info(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
|
|
93
|
+
validatorAddress: validatorAddress.toString(),
|
|
94
|
+
nodeId,
|
|
95
|
+
});
|
|
96
|
+
return record.lockToken;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// Record already exists - handle based on status
|
|
100
|
+
if (record.status === DutyStatus.SIGNED) {
|
|
101
|
+
// Duty was already signed - check if same or different data
|
|
102
|
+
if (record.messageHash !== messageHash) {
|
|
103
|
+
this.log.verbose(`Slashing protection triggered for duty ${dutyType} at slot ${slot}`, {
|
|
104
|
+
validatorAddress: validatorAddress.toString(),
|
|
105
|
+
existingMessageHash: record.messageHash,
|
|
106
|
+
attemptedMessageHash: messageHash,
|
|
107
|
+
existingNodeId: record.nodeId,
|
|
108
|
+
attemptingNodeId: nodeId,
|
|
109
|
+
});
|
|
110
|
+
throw new SlashingProtectionError(
|
|
111
|
+
slot,
|
|
112
|
+
dutyType,
|
|
113
|
+
record.blockIndexWithinCheckpoint,
|
|
114
|
+
record.messageHash,
|
|
115
|
+
messageHash,
|
|
116
|
+
record.nodeId,
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
|
|
120
|
+
} else if (record.status === DutyStatus.SIGNING) {
|
|
121
|
+
// Another node is currently signing - check for timeout
|
|
122
|
+
if (Date.now() - startTime > this.signingTimeoutMs) {
|
|
123
|
+
this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
|
|
124
|
+
validatorAddress: validatorAddress.toString(),
|
|
125
|
+
timeoutMs: this.signingTimeoutMs,
|
|
126
|
+
signingNodeId: record.nodeId,
|
|
127
|
+
});
|
|
128
|
+
throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Wait and poll
|
|
132
|
+
this.log.debug(`Waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
|
|
133
|
+
validatorAddress: validatorAddress.toString(),
|
|
134
|
+
signingNodeId: record.nodeId,
|
|
135
|
+
});
|
|
136
|
+
await sleep(this.pollingIntervalMs);
|
|
137
|
+
// Loop continues - next iteration will check status again
|
|
138
|
+
} else {
|
|
139
|
+
throw new Error(`Unknown duty status: ${record.status}`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* Record a successful signing operation.
|
|
146
|
+
* Updates the duty status to 'signed' and stores the signature.
|
|
147
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
148
|
+
*
|
|
149
|
+
* @returns true if the update succeeded, false if token didn't match
|
|
150
|
+
*/
|
|
151
|
+
async recordSuccess(params: RecordSuccessParams): Promise<boolean> {
|
|
152
|
+
const { validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
|
|
153
|
+
const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
|
|
154
|
+
|
|
155
|
+
const success = await this.db.updateDutySigned(
|
|
156
|
+
validatorAddress,
|
|
157
|
+
slot,
|
|
158
|
+
dutyType,
|
|
159
|
+
signature.toString(),
|
|
160
|
+
lockToken,
|
|
161
|
+
blockIndexWithinCheckpoint,
|
|
162
|
+
);
|
|
163
|
+
|
|
164
|
+
if (success) {
|
|
165
|
+
this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
|
|
166
|
+
validatorAddress: validatorAddress.toString(),
|
|
167
|
+
nodeId,
|
|
168
|
+
});
|
|
169
|
+
} else {
|
|
170
|
+
this.log.warn(`Failed to record successful signing for duty ${dutyType} at slot ${slot}: invalid token`, {
|
|
171
|
+
validatorAddress: validatorAddress.toString(),
|
|
172
|
+
nodeId,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
return success;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Delete a duty record after a failed signing operation.
|
|
181
|
+
* Removes the record to allow another node/attempt to retry.
|
|
182
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
183
|
+
*
|
|
184
|
+
* @returns true if the delete succeeded, false if token didn't match
|
|
185
|
+
*/
|
|
186
|
+
async deleteDuty(params: DeleteDutyParams): Promise<boolean> {
|
|
187
|
+
const { validatorAddress, slot, dutyType, lockToken } = params;
|
|
188
|
+
const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
|
|
189
|
+
|
|
190
|
+
const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint);
|
|
191
|
+
|
|
192
|
+
if (success) {
|
|
193
|
+
this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
|
|
194
|
+
validatorAddress: validatorAddress.toString(),
|
|
195
|
+
});
|
|
196
|
+
} else {
|
|
197
|
+
this.log.warn(`Failed to delete duty ${dutyType} at slot ${slot}: invalid token`, {
|
|
198
|
+
validatorAddress: validatorAddress.toString(),
|
|
199
|
+
});
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
return success;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Get the node ID for this service
|
|
207
|
+
*/
|
|
208
|
+
get nodeId(): string {
|
|
209
|
+
return this.config.nodeId;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Start running tasks.
|
|
214
|
+
* Cleanup runs immediately on start to recover from any previous crashes.
|
|
215
|
+
*/
|
|
216
|
+
start() {
|
|
217
|
+
this.cleanupRunningPromise.start();
|
|
218
|
+
this.log.info('Slashing protection service started', { nodeId: this.config.nodeId });
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* Stop the background cleanup task.
|
|
223
|
+
*/
|
|
224
|
+
async stop() {
|
|
225
|
+
await this.cleanupRunningPromise.stop();
|
|
226
|
+
this.log.info('Slashing protection service stopped', { nodeId: this.config.nodeId });
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Close the database connection.
|
|
231
|
+
* Should be called after stop() during graceful shutdown.
|
|
232
|
+
*/
|
|
233
|
+
async close() {
|
|
234
|
+
await this.db.close();
|
|
235
|
+
this.log.info('Slashing protection database connection closed');
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Cleanup own stuck duties
|
|
240
|
+
*/
|
|
241
|
+
private async cleanupStuckDuties() {
|
|
242
|
+
const numDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
|
|
243
|
+
if (numDuties > 0) {
|
|
244
|
+
this.log.info(`Cleaned up ${numDuties} stuck duties`, {
|
|
245
|
+
nodeId: this.config.nodeId,
|
|
246
|
+
maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs,
|
|
247
|
+
});
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
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
|
+
|
|
18
|
+
export interface PoolConfig {
|
|
19
|
+
pglite: PGliteInterface;
|
|
20
|
+
max?: number;
|
|
21
|
+
min?: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface ClientConfig {
|
|
25
|
+
pglite: PGliteInterface;
|
|
26
|
+
host?: string;
|
|
27
|
+
port?: number;
|
|
28
|
+
ssl?: boolean;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export class Client extends EventEmitter {
|
|
32
|
+
protected pglite: PGliteInterface;
|
|
33
|
+
protected _connected = false;
|
|
34
|
+
readonly host: string;
|
|
35
|
+
readonly port: number;
|
|
36
|
+
readonly ssl: boolean;
|
|
37
|
+
readonly connection: object;
|
|
38
|
+
|
|
39
|
+
// Stub implementations for pg compatibility
|
|
40
|
+
readonly copyFrom = (): Writable => new Writable();
|
|
41
|
+
readonly copyTo = (): Readable => new Readable();
|
|
42
|
+
readonly pauseDrain = (): void => {};
|
|
43
|
+
readonly resumeDrain = (): void => {};
|
|
44
|
+
readonly escapeLiteral = (str: string): string => `'${str.replace(/'/g, "''")}'`;
|
|
45
|
+
readonly escapeIdentifier = (str: string): string => `"${str.replace(/"/g, '""')}"`;
|
|
46
|
+
readonly setTypeParser = (): void => {};
|
|
47
|
+
readonly getTypeParser = (): ((value: string) => unknown) => (value: string) => value;
|
|
48
|
+
|
|
49
|
+
constructor(config: ClientConfig) {
|
|
50
|
+
super();
|
|
51
|
+
this.pglite = config.pglite;
|
|
52
|
+
this.host = config.host || 'localhost';
|
|
53
|
+
this.port = config.port || 5432;
|
|
54
|
+
this.ssl = typeof config.ssl === 'boolean' ? config.ssl : !!config.ssl;
|
|
55
|
+
this.connection = {};
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
connect(): Promise<void> {
|
|
59
|
+
if (this._connected) {
|
|
60
|
+
return Promise.resolve();
|
|
61
|
+
}
|
|
62
|
+
this._connected = true;
|
|
63
|
+
this.emit('connect');
|
|
64
|
+
return Promise.resolve();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
end(): Promise<void> {
|
|
68
|
+
if (!this._connected) {
|
|
69
|
+
return Promise.resolve();
|
|
70
|
+
}
|
|
71
|
+
this._connected = false;
|
|
72
|
+
this.emit('end');
|
|
73
|
+
return Promise.resolve();
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
async query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>> {
|
|
77
|
+
if (!this._connected) {
|
|
78
|
+
throw new Error('Client is not connected');
|
|
79
|
+
}
|
|
80
|
+
const result = await this.pglite.query<R>(text, values);
|
|
81
|
+
return this.convertPGliteResult(result);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
protected convertPGliteResult<R extends QueryResultRow>(result: {
|
|
85
|
+
rows: R[];
|
|
86
|
+
fields: Array<{ name: string; dataTypeID: number }>;
|
|
87
|
+
affectedRows?: number;
|
|
88
|
+
}): QueryResult<R> {
|
|
89
|
+
return {
|
|
90
|
+
command: '',
|
|
91
|
+
rowCount: 'affectedRows' in result ? (result.affectedRows ?? 0) : result.rows.length,
|
|
92
|
+
oid: 0,
|
|
93
|
+
fields: result.fields.map(field => ({
|
|
94
|
+
name: field.name,
|
|
95
|
+
tableID: 0,
|
|
96
|
+
columnID: 0,
|
|
97
|
+
dataTypeID: field.dataTypeID,
|
|
98
|
+
dataTypeSize: -1,
|
|
99
|
+
dataTypeModifier: -1,
|
|
100
|
+
format: 'text',
|
|
101
|
+
})),
|
|
102
|
+
rows: result.rows,
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
get connected(): boolean {
|
|
107
|
+
return this._connected;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export class Pool extends EventEmitter {
|
|
112
|
+
private clients: PoolClient[] = [];
|
|
113
|
+
private availableClients: PoolClient[] = [];
|
|
114
|
+
private waitingQueue: Array<(client: PoolClient) => void> = [];
|
|
115
|
+
private _ended = false;
|
|
116
|
+
private pglite: PGliteInterface;
|
|
117
|
+
private _config: PoolConfig;
|
|
118
|
+
|
|
119
|
+
readonly expiredCount = 0;
|
|
120
|
+
readonly options: PoolConfig;
|
|
121
|
+
|
|
122
|
+
constructor(config: PoolConfig) {
|
|
123
|
+
super();
|
|
124
|
+
this._config = { max: 10, min: 0, ...config };
|
|
125
|
+
this.pglite = config.pglite;
|
|
126
|
+
this.options = config;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
get totalCount(): number {
|
|
130
|
+
return this.clients.length;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
get idleCount(): number {
|
|
134
|
+
return this.availableClients.length;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
get waitingCount(): number {
|
|
138
|
+
return this.waitingQueue.length;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
get ending(): boolean {
|
|
142
|
+
return this._ended;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
get ended(): boolean {
|
|
146
|
+
return this._ended;
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
connect(): Promise<PoolClient> {
|
|
150
|
+
if (this._ended) {
|
|
151
|
+
return Promise.reject(new Error('Pool is ended'));
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
if (this.availableClients.length > 0) {
|
|
155
|
+
const client = this.availableClients.pop()!;
|
|
156
|
+
client._markInUse();
|
|
157
|
+
return Promise.resolve(client);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (this.clients.length < (this._config.max || 10)) {
|
|
161
|
+
const client = new PoolClient(this.pglite, this);
|
|
162
|
+
this.clients.push(client);
|
|
163
|
+
return Promise.resolve(client);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
return new Promise(resolve => {
|
|
167
|
+
this.waitingQueue.push(resolve);
|
|
168
|
+
});
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
async query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>> {
|
|
172
|
+
const client = await this.connect();
|
|
173
|
+
try {
|
|
174
|
+
return await client.query<R>(text, values);
|
|
175
|
+
} finally {
|
|
176
|
+
client.release();
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
releaseClient(client: PoolClient): void {
|
|
181
|
+
const index = this.clients.indexOf(client);
|
|
182
|
+
if (index !== -1) {
|
|
183
|
+
client._markAvailable();
|
|
184
|
+
if (this.waitingQueue.length > 0) {
|
|
185
|
+
const resolve = this.waitingQueue.shift()!;
|
|
186
|
+
client._markInUse();
|
|
187
|
+
resolve(client);
|
|
188
|
+
} else {
|
|
189
|
+
this.availableClients.push(client);
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
end(): Promise<void> {
|
|
195
|
+
this._ended = true;
|
|
196
|
+
this.clients.forEach(client => client._markReleased());
|
|
197
|
+
this.clients = [];
|
|
198
|
+
this.availableClients = [];
|
|
199
|
+
this.emit('end');
|
|
200
|
+
return Promise.resolve();
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export class PoolClient extends Client {
|
|
205
|
+
private pool: Pool;
|
|
206
|
+
private _released = false;
|
|
207
|
+
private _inUse = true;
|
|
208
|
+
private _userReleased = false;
|
|
209
|
+
|
|
210
|
+
constructor(pglite: PGliteInterface, pool: Pool) {
|
|
211
|
+
super({ pglite });
|
|
212
|
+
this.pool = pool;
|
|
213
|
+
this._connected = true;
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
override async query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>> {
|
|
217
|
+
if (this._userReleased && !this._inUse) {
|
|
218
|
+
throw new Error('Client has been released back to the pool');
|
|
219
|
+
}
|
|
220
|
+
const result = await this.pglite.query<R>(text, values);
|
|
221
|
+
return this.convertPGliteResult(result);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
release(): void {
|
|
225
|
+
if (this._released || this._userReleased) {
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
this._userReleased = true;
|
|
229
|
+
this.pool.releaseClient(this);
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
override end(): Promise<void> {
|
|
233
|
+
this.release();
|
|
234
|
+
return Promise.resolve();
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
_markInUse(): void {
|
|
238
|
+
this._inUse = true;
|
|
239
|
+
this._userReleased = false;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
_markAvailable(): void {
|
|
243
|
+
this._inUse = false;
|
|
244
|
+
this._userReleased = false;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
_markReleased(): void {
|
|
248
|
+
this._released = true;
|
|
249
|
+
this._inUse = false;
|
|
250
|
+
this._userReleased = true;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
override get connected(): boolean {
|
|
254
|
+
return this._connected && !this._released;
|
|
255
|
+
}
|
|
256
|
+
}
|
package/src/types.ts
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BlockNumber,
|
|
3
|
+
type CheckpointNumber,
|
|
4
|
+
type IndexWithinCheckpoint,
|
|
5
|
+
type SlotNumber,
|
|
6
|
+
} from '@aztec/foundation/branded-types';
|
|
7
|
+
import type { EthAddress } from '@aztec/foundation/eth-address';
|
|
8
|
+
|
|
9
|
+
import type { Pool } from 'pg';
|
|
10
|
+
|
|
11
|
+
import type { ValidatorHASignerConfig } from './config.js';
|
|
12
|
+
import {
|
|
13
|
+
type BlockProposalDutyIdentifier,
|
|
14
|
+
type CheckAndRecordParams,
|
|
15
|
+
type DeleteDutyParams,
|
|
16
|
+
type DutyIdentifier,
|
|
17
|
+
DutyType,
|
|
18
|
+
type OtherDutyIdentifier,
|
|
19
|
+
type RecordSuccessParams,
|
|
20
|
+
type ValidatorDutyRecord,
|
|
21
|
+
} from './db/types.js';
|
|
22
|
+
|
|
23
|
+
export type {
|
|
24
|
+
BlockProposalDutyIdentifier,
|
|
25
|
+
CheckAndRecordParams,
|
|
26
|
+
DeleteDutyParams,
|
|
27
|
+
DutyIdentifier,
|
|
28
|
+
OtherDutyIdentifier,
|
|
29
|
+
RecordSuccessParams,
|
|
30
|
+
ValidatorDutyRecord,
|
|
31
|
+
ValidatorHASignerConfig,
|
|
32
|
+
};
|
|
33
|
+
export { DutyStatus, DutyType, getBlockIndexFromDutyIdentifier, normalizeBlockIndex } from './db/types.js';
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Result of tryInsertOrGetExisting operation
|
|
37
|
+
*/
|
|
38
|
+
export interface TryInsertOrGetResult {
|
|
39
|
+
/** True if we inserted a new record, false if we got an existing record */
|
|
40
|
+
isNew: boolean;
|
|
41
|
+
/** The record (either newly inserted or existing) */
|
|
42
|
+
record: ValidatorDutyRecord;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* deps for creating an HA signer
|
|
47
|
+
*/
|
|
48
|
+
export interface CreateHASignerDeps {
|
|
49
|
+
/**
|
|
50
|
+
* Optional PostgreSQL connection pool
|
|
51
|
+
* If provided, databaseUrl and poolConfig are ignored
|
|
52
|
+
*/
|
|
53
|
+
pool?: Pool;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Base context for signing operations
|
|
58
|
+
*/
|
|
59
|
+
interface BaseSigningContext {
|
|
60
|
+
/** Slot number for this duty */
|
|
61
|
+
slot: SlotNumber;
|
|
62
|
+
/**
|
|
63
|
+
* Block or checkpoint number for this duty.
|
|
64
|
+
* For block proposals, this is the block number.
|
|
65
|
+
* For checkpoint proposals, this is the checkpoint number.
|
|
66
|
+
*/
|
|
67
|
+
blockNumber: BlockNumber | CheckpointNumber;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Signing context for block proposals.
|
|
72
|
+
* blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
|
|
73
|
+
*/
|
|
74
|
+
export interface BlockProposalSigningContext extends BaseSigningContext {
|
|
75
|
+
/** Block index within checkpoint (0, 1, 2...). Required for block proposals. */
|
|
76
|
+
blockIndexWithinCheckpoint: IndexWithinCheckpoint;
|
|
77
|
+
dutyType: DutyType.BLOCK_PROPOSAL;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Signing context for non-block-proposal duties that require HA protection.
|
|
82
|
+
* blockIndexWithinCheckpoint is not applicable (internally always -1).
|
|
83
|
+
*/
|
|
84
|
+
export interface OtherSigningContext extends BaseSigningContext {
|
|
85
|
+
dutyType: DutyType.CHECKPOINT_PROPOSAL | DutyType.ATTESTATION | DutyType.ATTESTATIONS_AND_SIGNERS;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Signing context for governance/slashing votes which only need slot for HA protection.
|
|
90
|
+
* blockNumber is not applicable (internally always 0).
|
|
91
|
+
*/
|
|
92
|
+
export interface VoteSigningContext {
|
|
93
|
+
slot: SlotNumber;
|
|
94
|
+
dutyType: DutyType.GOVERNANCE_VOTE | DutyType.SLASHING_VOTE;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* Signing context for duties which don't require slot/blockNumber
|
|
99
|
+
* as they don't need HA protection (AUTH_REQUEST, TXS).
|
|
100
|
+
*/
|
|
101
|
+
export interface NoHAProtectionSigningContext {
|
|
102
|
+
dutyType: DutyType.AUTH_REQUEST | DutyType.TXS;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Signing contexts that require HA protection (excludes AUTH_REQUEST).
|
|
107
|
+
* Used by the HA signer's signWithProtection method.
|
|
108
|
+
*/
|
|
109
|
+
export type HAProtectedSigningContext = BlockProposalSigningContext | OtherSigningContext | VoteSigningContext;
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Type guard to check if a SigningContext requires HA protection.
|
|
113
|
+
* Returns true for contexts that need HA protection, false for AUTH_REQUEST and TXS.
|
|
114
|
+
*/
|
|
115
|
+
export function isHAProtectedContext(context: SigningContext): context is HAProtectedSigningContext {
|
|
116
|
+
return context.dutyType !== DutyType.AUTH_REQUEST && context.dutyType !== DutyType.TXS;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Gets the block number from a signing context.
|
|
121
|
+
* - Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE): returns BlockNumber(0)
|
|
122
|
+
* - Other duties: returns the blockNumber from the context
|
|
123
|
+
*/
|
|
124
|
+
export function getBlockNumberFromSigningContext(context: HAProtectedSigningContext): BlockNumber | CheckpointNumber {
|
|
125
|
+
// Check for duty types that have blockNumber
|
|
126
|
+
if (
|
|
127
|
+
context.dutyType === DutyType.BLOCK_PROPOSAL ||
|
|
128
|
+
context.dutyType === DutyType.CHECKPOINT_PROPOSAL ||
|
|
129
|
+
context.dutyType === DutyType.ATTESTATION ||
|
|
130
|
+
context.dutyType === DutyType.ATTESTATIONS_AND_SIGNERS
|
|
131
|
+
) {
|
|
132
|
+
return context.blockNumber;
|
|
133
|
+
}
|
|
134
|
+
// Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE) don't have blockNumber
|
|
135
|
+
return BlockNumber(0);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Context required for slashing protection during signing operations.
|
|
140
|
+
* Uses discriminated union to enforce type safety:
|
|
141
|
+
* - BLOCK_PROPOSAL duties MUST have blockIndexWithinCheckpoint >= 0
|
|
142
|
+
* - Other duty types do NOT have blockIndexWithinCheckpoint (internally -1)
|
|
143
|
+
* - Vote duties only need slot (blockNumber is internally 0)
|
|
144
|
+
* - AUTH_REQUEST and TXS duties don't need slot/blockNumber (no HA protection needed)
|
|
145
|
+
*/
|
|
146
|
+
export type SigningContext = HAProtectedSigningContext | NoHAProtectionSigningContext;
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Database interface for slashing protection operations
|
|
150
|
+
* This abstraction allows for different database implementations (PostgreSQL, SQLite, etc.)
|
|
151
|
+
*
|
|
152
|
+
* The interface is designed around 3 core operations:
|
|
153
|
+
* 1. tryInsertOrGetExisting - Atomically insert or get existing record (eliminates race conditions)
|
|
154
|
+
* 2. updateDutySigned - Update to signed status on success
|
|
155
|
+
* 3. deleteDuty - Delete a duty record on failure
|
|
156
|
+
*/
|
|
157
|
+
export interface SlashingProtectionDatabase {
|
|
158
|
+
/**
|
|
159
|
+
* Atomically try to insert a new duty record, or get the existing one if present.
|
|
160
|
+
*
|
|
161
|
+
* @returns { isNew: true, record } if we successfully inserted and acquired the lock
|
|
162
|
+
* @returns { isNew: false, record } if a record already exists (caller should handle based on status)
|
|
163
|
+
*/
|
|
164
|
+
tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult>;
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Update a duty to 'signed' status with the signature.
|
|
168
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
169
|
+
*
|
|
170
|
+
* @returns true if the update succeeded, false if token didn't match or duty not found
|
|
171
|
+
*/
|
|
172
|
+
updateDutySigned(
|
|
173
|
+
validatorAddress: EthAddress,
|
|
174
|
+
slot: SlotNumber,
|
|
175
|
+
dutyType: DutyType,
|
|
176
|
+
signature: string,
|
|
177
|
+
lockToken: string,
|
|
178
|
+
blockIndexWithinCheckpoint: number,
|
|
179
|
+
): Promise<boolean>;
|
|
180
|
+
|
|
181
|
+
/**
|
|
182
|
+
* Delete a duty record.
|
|
183
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
184
|
+
* Used when signing fails to allow another node/attempt to retry.
|
|
185
|
+
*
|
|
186
|
+
* @returns true if the delete succeeded, false if token didn't match or duty not found
|
|
187
|
+
*/
|
|
188
|
+
deleteDuty(
|
|
189
|
+
validatorAddress: EthAddress,
|
|
190
|
+
slot: SlotNumber,
|
|
191
|
+
dutyType: DutyType,
|
|
192
|
+
lockToken: string,
|
|
193
|
+
blockIndexWithinCheckpoint: number,
|
|
194
|
+
): Promise<boolean>;
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Cleanup own stuck duties
|
|
198
|
+
* @returns the number of duties cleaned up
|
|
199
|
+
*/
|
|
200
|
+
cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Close the database connection.
|
|
204
|
+
* Should be called during graceful shutdown.
|
|
205
|
+
*/
|
|
206
|
+
close(): Promise<void>;
|
|
207
|
+
}
|