@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/config.ts
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type ConfigMappingsType,
|
|
3
|
+
booleanConfigHelper,
|
|
4
|
+
getConfigFromMappings,
|
|
5
|
+
getDefaultConfig,
|
|
6
|
+
numberConfigHelper,
|
|
7
|
+
} from '@aztec/foundation/config';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Configuration for the slashing protection service
|
|
11
|
+
*/
|
|
12
|
+
export interface SlashingProtectionConfig {
|
|
13
|
+
/** Whether slashing protection is enabled */
|
|
14
|
+
enabled: boolean;
|
|
15
|
+
/** Unique identifier for this node */
|
|
16
|
+
nodeId: string;
|
|
17
|
+
/** How long to wait between polls when a duty is being signed (ms) */
|
|
18
|
+
pollingIntervalMs: number;
|
|
19
|
+
/** Maximum time to wait for a duty being signed to complete (ms) */
|
|
20
|
+
signingTimeoutMs: number;
|
|
21
|
+
/** Maximum age of a stuck duty in ms */
|
|
22
|
+
maxStuckDutiesAgeMs: number;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export const slashingProtectionConfigMappings: ConfigMappingsType<SlashingProtectionConfig> = {
|
|
26
|
+
enabled: {
|
|
27
|
+
env: 'SLASHING_PROTECTION_ENABLED',
|
|
28
|
+
description: 'Whether slashing protection is enabled',
|
|
29
|
+
...booleanConfigHelper(true),
|
|
30
|
+
},
|
|
31
|
+
nodeId: {
|
|
32
|
+
env: 'SLASHING_PROTECTION_NODE_ID',
|
|
33
|
+
description: 'The unique identifier for this node',
|
|
34
|
+
defaultValue: '',
|
|
35
|
+
},
|
|
36
|
+
pollingIntervalMs: {
|
|
37
|
+
env: 'SLASHING_PROTECTION_POLLING_INTERVAL_MS',
|
|
38
|
+
description: 'The number of ms to wait between polls when a duty is being signed',
|
|
39
|
+
...numberConfigHelper(100),
|
|
40
|
+
},
|
|
41
|
+
signingTimeoutMs: {
|
|
42
|
+
env: 'SLASHING_PROTECTION_SIGNING_TIMEOUT_MS',
|
|
43
|
+
description: 'The maximum time to wait for a duty being signed to complete',
|
|
44
|
+
...numberConfigHelper(3_000),
|
|
45
|
+
},
|
|
46
|
+
maxStuckDutiesAgeMs: {
|
|
47
|
+
env: 'SLASHING_PROTECTION_MAX_STUCK_DUTIES_AGE_MS',
|
|
48
|
+
description: 'The maximum age of a stuck duty in ms',
|
|
49
|
+
// hard-coding at current 2 slot duration. This should be set by the validator on init
|
|
50
|
+
...numberConfigHelper(72_000),
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
export const defaultSlashingProtectionConfig: SlashingProtectionConfig = getDefaultConfig(
|
|
55
|
+
slashingProtectionConfigMappings,
|
|
56
|
+
);
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Configuration for creating an HA signer with PostgreSQL backend
|
|
60
|
+
*/
|
|
61
|
+
export interface CreateHASignerConfig extends SlashingProtectionConfig {
|
|
62
|
+
/**
|
|
63
|
+
* PostgreSQL connection string
|
|
64
|
+
* Format: postgresql://user:password@host:port/database
|
|
65
|
+
*/
|
|
66
|
+
databaseUrl: string;
|
|
67
|
+
/**
|
|
68
|
+
* PostgreSQL connection pool configuration
|
|
69
|
+
*/
|
|
70
|
+
/** Maximum number of clients in the pool (default: 10) */
|
|
71
|
+
poolMaxCount?: number;
|
|
72
|
+
/** Minimum number of clients in the pool (default: 0) */
|
|
73
|
+
poolMinCount?: number;
|
|
74
|
+
/** Idle timeout in milliseconds (default: 10000) */
|
|
75
|
+
poolIdleTimeoutMs?: number;
|
|
76
|
+
/** Connection timeout in milliseconds (default: 0, no timeout) */
|
|
77
|
+
poolConnectionTimeoutMs?: number;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export const createHASignerConfigMappings: ConfigMappingsType<CreateHASignerConfig> = {
|
|
81
|
+
...slashingProtectionConfigMappings,
|
|
82
|
+
databaseUrl: {
|
|
83
|
+
env: 'VALIDATOR_HA_DATABASE_URL',
|
|
84
|
+
description:
|
|
85
|
+
'PostgreSQL connection string for validator HA signer (format: postgresql://user:password@host:port/database)',
|
|
86
|
+
},
|
|
87
|
+
poolMaxCount: {
|
|
88
|
+
env: 'VALIDATOR_HA_POOL_MAX',
|
|
89
|
+
description: 'Maximum number of clients in the pool',
|
|
90
|
+
...numberConfigHelper(10),
|
|
91
|
+
},
|
|
92
|
+
poolMinCount: {
|
|
93
|
+
env: 'VALIDATOR_HA_POOL_MIN',
|
|
94
|
+
description: 'Minimum number of clients in the pool',
|
|
95
|
+
...numberConfigHelper(0),
|
|
96
|
+
},
|
|
97
|
+
poolIdleTimeoutMs: {
|
|
98
|
+
env: 'VALIDATOR_HA_POOL_IDLE_TIMEOUT_MS',
|
|
99
|
+
description: 'Idle timeout in milliseconds',
|
|
100
|
+
...numberConfigHelper(10_000),
|
|
101
|
+
},
|
|
102
|
+
poolConnectionTimeoutMs: {
|
|
103
|
+
env: 'VALIDATOR_HA_POOL_CONNECTION_TIMEOUT_MS',
|
|
104
|
+
description: 'Connection timeout in milliseconds (0 means no timeout)',
|
|
105
|
+
...numberConfigHelper(0),
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Returns the validator HA signer configuration from environment variables.
|
|
111
|
+
* Note: If an environment variable is not set, the default value is used.
|
|
112
|
+
* @returns The validator HA signer configuration.
|
|
113
|
+
*/
|
|
114
|
+
export function getConfigEnvVars(): CreateHASignerConfig {
|
|
115
|
+
return getConfigFromMappings<CreateHASignerConfig>(createHASignerConfigMappings);
|
|
116
|
+
}
|
package/src/db/index.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Initial schema for validator HA slashing protection
|
|
3
|
+
*
|
|
4
|
+
* This migration imports SQL from the schema.ts file to ensure a single source of truth.
|
|
5
|
+
*/
|
|
6
|
+
import type { MigrationBuilder } from 'node-pg-migrate';
|
|
7
|
+
|
|
8
|
+
import { DROP_SCHEMA_VERSION_TABLE, DROP_VALIDATOR_DUTIES_TABLE, SCHEMA_SETUP, SCHEMA_VERSION } from '../schema.js';
|
|
9
|
+
|
|
10
|
+
export function up(pgm: MigrationBuilder): void {
|
|
11
|
+
for (const statement of SCHEMA_SETUP) {
|
|
12
|
+
pgm.sql(statement);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
// Insert initial schema version
|
|
16
|
+
pgm.sql(`
|
|
17
|
+
INSERT INTO schema_version (version)
|
|
18
|
+
VALUES (${SCHEMA_VERSION})
|
|
19
|
+
ON CONFLICT (version) DO NOTHING;
|
|
20
|
+
`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function down(pgm: MigrationBuilder): void {
|
|
24
|
+
pgm.sql(DROP_VALIDATOR_DUTIES_TABLE);
|
|
25
|
+
pgm.sql(DROP_SCHEMA_VERSION_TABLE);
|
|
26
|
+
}
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PostgreSQL implementation of SlashingProtectionDatabase
|
|
3
|
+
*/
|
|
4
|
+
import { randomBytes } from '@aztec/foundation/crypto/random';
|
|
5
|
+
import { EthAddress } from '@aztec/foundation/eth-address';
|
|
6
|
+
import { type Logger, createLogger } from '@aztec/foundation/log';
|
|
7
|
+
|
|
8
|
+
import type { Pool, QueryResult } from 'pg';
|
|
9
|
+
|
|
10
|
+
import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
|
|
11
|
+
import {
|
|
12
|
+
CLEANUP_OWN_STUCK_DUTIES,
|
|
13
|
+
DELETE_DUTY,
|
|
14
|
+
INSERT_OR_GET_DUTY,
|
|
15
|
+
SCHEMA_VERSION,
|
|
16
|
+
UPDATE_DUTY_SIGNED,
|
|
17
|
+
} from './schema.js';
|
|
18
|
+
import type { CheckAndRecordParams, DutyRow, DutyType, InsertOrGetRow, ValidatorDutyRecord } from './types.js';
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* PostgreSQL implementation of the slashing protection database
|
|
22
|
+
*/
|
|
23
|
+
export class PostgresSlashingProtectionDatabase implements SlashingProtectionDatabase {
|
|
24
|
+
private readonly log: Logger;
|
|
25
|
+
|
|
26
|
+
constructor(private readonly pool: Pool) {
|
|
27
|
+
this.log = createLogger('slashing-protection:postgres');
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Verify that database migrations have been run and schema version matches.
|
|
32
|
+
* Should be called once at startup.
|
|
33
|
+
*
|
|
34
|
+
* @throws Error if migrations haven't been run or schema version is outdated
|
|
35
|
+
*/
|
|
36
|
+
async initialize(): Promise<void> {
|
|
37
|
+
let dbVersion: number;
|
|
38
|
+
|
|
39
|
+
try {
|
|
40
|
+
const result = await this.pool.query<{ version: number }>(
|
|
41
|
+
`SELECT version FROM schema_version ORDER BY version DESC LIMIT 1`,
|
|
42
|
+
);
|
|
43
|
+
|
|
44
|
+
if (result.rows.length === 0) {
|
|
45
|
+
throw new Error('No version found');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
dbVersion = result.rows[0].version;
|
|
49
|
+
} catch {
|
|
50
|
+
throw new Error(
|
|
51
|
+
'Database schema not initialized. Please run migrations first: aztec migrate up --database-url <url>',
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (dbVersion < SCHEMA_VERSION) {
|
|
56
|
+
throw new Error(
|
|
57
|
+
`Database schema version ${dbVersion} is outdated (expected ${SCHEMA_VERSION}). Please run migrations: aztec migrate up --database-url <url>`,
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
if (dbVersion > SCHEMA_VERSION) {
|
|
62
|
+
throw new Error(
|
|
63
|
+
`Database schema version ${dbVersion} is newer than expected (${SCHEMA_VERSION}). Please update your application.`,
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
this.log.info('Database schema verified', { version: dbVersion });
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* Atomically try to insert a new duty record, or get the existing one if present.
|
|
72
|
+
*
|
|
73
|
+
* @returns { isNew: true, record } if we successfully inserted and acquired the lock
|
|
74
|
+
* @returns { isNew: false, record } if a record already exists. lock_token is empty if the record already exists.
|
|
75
|
+
*/
|
|
76
|
+
async tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult> {
|
|
77
|
+
// create a token for ownership verification
|
|
78
|
+
const lockToken = randomBytes(16).toString('hex');
|
|
79
|
+
|
|
80
|
+
const result: QueryResult<InsertOrGetRow> = await this.pool.query(INSERT_OR_GET_DUTY, [
|
|
81
|
+
params.validatorAddress.toString(),
|
|
82
|
+
params.slot.toString(),
|
|
83
|
+
params.blockNumber.toString(),
|
|
84
|
+
params.dutyType,
|
|
85
|
+
params.messageHash,
|
|
86
|
+
params.nodeId,
|
|
87
|
+
lockToken,
|
|
88
|
+
]);
|
|
89
|
+
|
|
90
|
+
if (result.rows.length === 0) {
|
|
91
|
+
// This shouldn't happen - the query always returns either the inserted or existing row
|
|
92
|
+
throw new Error('INSERT_OR_GET_DUTY returned no rows');
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
const row = result.rows[0];
|
|
96
|
+
return {
|
|
97
|
+
isNew: row.is_new,
|
|
98
|
+
record: this.rowToRecord(row),
|
|
99
|
+
};
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Update a duty to 'signed' status with the signature.
|
|
104
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
105
|
+
*
|
|
106
|
+
* @returns true if the update succeeded, false if token didn't match or duty not found
|
|
107
|
+
*/
|
|
108
|
+
async updateDutySigned(
|
|
109
|
+
validatorAddress: EthAddress,
|
|
110
|
+
slot: bigint,
|
|
111
|
+
dutyType: DutyType,
|
|
112
|
+
signature: string,
|
|
113
|
+
lockToken: string,
|
|
114
|
+
): Promise<boolean> {
|
|
115
|
+
const result = await this.pool.query(UPDATE_DUTY_SIGNED, [
|
|
116
|
+
signature,
|
|
117
|
+
validatorAddress.toString(),
|
|
118
|
+
slot.toString(),
|
|
119
|
+
dutyType,
|
|
120
|
+
lockToken,
|
|
121
|
+
]);
|
|
122
|
+
|
|
123
|
+
if (result.rowCount === 0) {
|
|
124
|
+
this.log.warn('Failed to update duty to signed status: invalid token or duty not found', {
|
|
125
|
+
validatorAddress: validatorAddress.toString(),
|
|
126
|
+
slot: slot.toString(),
|
|
127
|
+
dutyType,
|
|
128
|
+
});
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
return true;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Delete a duty record.
|
|
136
|
+
* Only succeeds if the lockToken matches (caller must be the one who created the duty).
|
|
137
|
+
* Used when signing fails to allow another node/attempt to retry.
|
|
138
|
+
*
|
|
139
|
+
* @returns true if the delete succeeded, false if token didn't match or duty not found
|
|
140
|
+
*/
|
|
141
|
+
async deleteDuty(
|
|
142
|
+
validatorAddress: EthAddress,
|
|
143
|
+
slot: bigint,
|
|
144
|
+
dutyType: DutyType,
|
|
145
|
+
lockToken: string,
|
|
146
|
+
): Promise<boolean> {
|
|
147
|
+
const result = await this.pool.query(DELETE_DUTY, [
|
|
148
|
+
validatorAddress.toString(),
|
|
149
|
+
slot.toString(),
|
|
150
|
+
dutyType,
|
|
151
|
+
lockToken,
|
|
152
|
+
]);
|
|
153
|
+
|
|
154
|
+
if (result.rowCount === 0) {
|
|
155
|
+
this.log.warn('Failed to delete duty: invalid token or duty not found', {
|
|
156
|
+
validatorAddress: validatorAddress.toString(),
|
|
157
|
+
slot: slot.toString(),
|
|
158
|
+
dutyType,
|
|
159
|
+
});
|
|
160
|
+
return false;
|
|
161
|
+
}
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Convert a database row to a ValidatorDutyRecord
|
|
167
|
+
*/
|
|
168
|
+
private rowToRecord(row: DutyRow): ValidatorDutyRecord {
|
|
169
|
+
return {
|
|
170
|
+
validatorAddress: EthAddress.fromString(row.validator_address),
|
|
171
|
+
slot: BigInt(row.slot),
|
|
172
|
+
blockNumber: BigInt(row.block_number),
|
|
173
|
+
dutyType: row.duty_type,
|
|
174
|
+
status: row.status,
|
|
175
|
+
messageHash: row.message_hash,
|
|
176
|
+
signature: row.signature ?? undefined,
|
|
177
|
+
nodeId: row.node_id,
|
|
178
|
+
lockToken: row.lock_token,
|
|
179
|
+
startedAt: row.started_at,
|
|
180
|
+
completedAt: row.completed_at ?? undefined,
|
|
181
|
+
errorMessage: row.error_message ?? undefined,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Close the database connection pool
|
|
187
|
+
*/
|
|
188
|
+
async close(): Promise<void> {
|
|
189
|
+
await this.pool.end();
|
|
190
|
+
this.log.info('Database connection pool closed');
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* Cleanup own stuck duties
|
|
195
|
+
* @returns the number of duties cleaned up
|
|
196
|
+
*/
|
|
197
|
+
async cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
|
|
198
|
+
const cutoff = new Date(Date.now() - maxAgeMs);
|
|
199
|
+
const result = await this.pool.query(CLEANUP_OWN_STUCK_DUTIES, [nodeId, cutoff]);
|
|
200
|
+
return result.rowCount ?? 0;
|
|
201
|
+
}
|
|
202
|
+
}
|
package/src/db/schema.ts
ADDED
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SQL schema for the validator_duties table
|
|
3
|
+
*
|
|
4
|
+
* This table is used for distributed locking and slashing protection across multiple validator nodes.
|
|
5
|
+
* The PRIMARY KEY constraint ensures that only one node can acquire the lock for a given validator,
|
|
6
|
+
* slot, and duty type combination.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Current schema version
|
|
11
|
+
*/
|
|
12
|
+
export const SCHEMA_VERSION = 1;
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* SQL to create the validator_duties table
|
|
16
|
+
*/
|
|
17
|
+
export const CREATE_VALIDATOR_DUTIES_TABLE = `
|
|
18
|
+
CREATE TABLE IF NOT EXISTS validator_duties (
|
|
19
|
+
validator_address VARCHAR(42) NOT NULL,
|
|
20
|
+
slot BIGINT NOT NULL,
|
|
21
|
+
block_number BIGINT NOT NULL,
|
|
22
|
+
duty_type VARCHAR(30) NOT NULL CHECK (duty_type IN ('BLOCK_PROPOSAL', 'ATTESTATION', 'ATTESTATIONS_AND_SIGNERS')),
|
|
23
|
+
status VARCHAR(20) NOT NULL CHECK (status IN ('signing', 'signed', 'failed')),
|
|
24
|
+
message_hash VARCHAR(66) NOT NULL,
|
|
25
|
+
signature VARCHAR(132),
|
|
26
|
+
node_id VARCHAR(255) NOT NULL,
|
|
27
|
+
lock_token VARCHAR(64) NOT NULL,
|
|
28
|
+
started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
29
|
+
completed_at TIMESTAMP,
|
|
30
|
+
error_message TEXT,
|
|
31
|
+
|
|
32
|
+
PRIMARY KEY (validator_address, slot, duty_type),
|
|
33
|
+
CHECK (completed_at IS NULL OR completed_at >= started_at)
|
|
34
|
+
);
|
|
35
|
+
`;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* SQL to create index on status and started_at for cleanup queries
|
|
39
|
+
*/
|
|
40
|
+
export const CREATE_STATUS_INDEX = `
|
|
41
|
+
CREATE INDEX IF NOT EXISTS idx_validator_duties_status
|
|
42
|
+
ON validator_duties(status, started_at);
|
|
43
|
+
`;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* SQL to create index for querying duties by node
|
|
47
|
+
*/
|
|
48
|
+
export const CREATE_NODE_INDEX = `
|
|
49
|
+
CREATE INDEX IF NOT EXISTS idx_validator_duties_node
|
|
50
|
+
ON validator_duties(node_id, started_at);
|
|
51
|
+
`;
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* SQL to create the schema_version table for tracking migrations
|
|
55
|
+
*/
|
|
56
|
+
export const CREATE_SCHEMA_VERSION_TABLE = `
|
|
57
|
+
CREATE TABLE IF NOT EXISTS schema_version (
|
|
58
|
+
version INTEGER PRIMARY KEY,
|
|
59
|
+
applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
60
|
+
);
|
|
61
|
+
`;
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* SQL to initialize schema version
|
|
65
|
+
*/
|
|
66
|
+
export const INSERT_SCHEMA_VERSION = `
|
|
67
|
+
INSERT INTO schema_version (version)
|
|
68
|
+
VALUES ($1)
|
|
69
|
+
ON CONFLICT (version) DO NOTHING;
|
|
70
|
+
`;
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Complete schema setup - all statements in order
|
|
74
|
+
*/
|
|
75
|
+
export const SCHEMA_SETUP = [
|
|
76
|
+
CREATE_SCHEMA_VERSION_TABLE,
|
|
77
|
+
CREATE_VALIDATOR_DUTIES_TABLE,
|
|
78
|
+
CREATE_STATUS_INDEX,
|
|
79
|
+
CREATE_NODE_INDEX,
|
|
80
|
+
] as const;
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Query to get current schema version
|
|
84
|
+
*/
|
|
85
|
+
export const GET_SCHEMA_VERSION = `
|
|
86
|
+
SELECT version FROM schema_version ORDER BY version DESC LIMIT 1;
|
|
87
|
+
`;
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Atomic insert-or-get query.
|
|
91
|
+
* Tries to insert a new duty record. If a record already exists (conflict),
|
|
92
|
+
* returns the existing record instead.
|
|
93
|
+
*
|
|
94
|
+
* Returns the record with an `is_new` flag indicating whether we inserted or got existing.
|
|
95
|
+
*/
|
|
96
|
+
export const INSERT_OR_GET_DUTY = `
|
|
97
|
+
WITH inserted AS (
|
|
98
|
+
INSERT INTO validator_duties (
|
|
99
|
+
validator_address,
|
|
100
|
+
slot,
|
|
101
|
+
block_number,
|
|
102
|
+
duty_type,
|
|
103
|
+
status,
|
|
104
|
+
message_hash,
|
|
105
|
+
node_id,
|
|
106
|
+
lock_token,
|
|
107
|
+
started_at
|
|
108
|
+
) VALUES ($1, $2, $3, $4, 'signing', $5, $6, $7, CURRENT_TIMESTAMP)
|
|
109
|
+
ON CONFLICT (validator_address, slot, duty_type) DO NOTHING
|
|
110
|
+
RETURNING
|
|
111
|
+
validator_address,
|
|
112
|
+
slot,
|
|
113
|
+
block_number,
|
|
114
|
+
duty_type,
|
|
115
|
+
status,
|
|
116
|
+
message_hash,
|
|
117
|
+
signature,
|
|
118
|
+
node_id,
|
|
119
|
+
lock_token,
|
|
120
|
+
started_at,
|
|
121
|
+
completed_at,
|
|
122
|
+
error_message,
|
|
123
|
+
TRUE as is_new
|
|
124
|
+
)
|
|
125
|
+
SELECT * FROM inserted
|
|
126
|
+
UNION ALL
|
|
127
|
+
SELECT
|
|
128
|
+
validator_address,
|
|
129
|
+
slot,
|
|
130
|
+
block_number,
|
|
131
|
+
duty_type,
|
|
132
|
+
status,
|
|
133
|
+
message_hash,
|
|
134
|
+
signature,
|
|
135
|
+
node_id,
|
|
136
|
+
'' as lock_token,
|
|
137
|
+
started_at,
|
|
138
|
+
completed_at,
|
|
139
|
+
error_message,
|
|
140
|
+
FALSE as is_new
|
|
141
|
+
FROM validator_duties
|
|
142
|
+
WHERE validator_address = $1
|
|
143
|
+
AND slot = $2
|
|
144
|
+
AND duty_type = $4
|
|
145
|
+
AND NOT EXISTS (SELECT 1 FROM inserted);
|
|
146
|
+
`;
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Query to update a duty to 'signed' status
|
|
150
|
+
*/
|
|
151
|
+
export const UPDATE_DUTY_SIGNED = `
|
|
152
|
+
UPDATE validator_duties
|
|
153
|
+
SET status = 'signed',
|
|
154
|
+
signature = $1,
|
|
155
|
+
completed_at = CURRENT_TIMESTAMP
|
|
156
|
+
WHERE validator_address = $2
|
|
157
|
+
AND slot = $3
|
|
158
|
+
AND duty_type = $4
|
|
159
|
+
AND status = 'signing'
|
|
160
|
+
AND lock_token = $5;
|
|
161
|
+
`;
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* Query to delete a duty
|
|
165
|
+
* Only deletes if the lockToken matches
|
|
166
|
+
*/
|
|
167
|
+
export const DELETE_DUTY = `
|
|
168
|
+
DELETE FROM validator_duties
|
|
169
|
+
WHERE validator_address = $1
|
|
170
|
+
AND slot = $2
|
|
171
|
+
AND duty_type = $3
|
|
172
|
+
AND status = 'signing'
|
|
173
|
+
AND lock_token = $4;
|
|
174
|
+
`;
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Query to clean up old signed duties (for maintenance)
|
|
178
|
+
* Removes signed duties older than a specified timestamp
|
|
179
|
+
*/
|
|
180
|
+
export const CLEANUP_OLD_SIGNED_DUTIES = `
|
|
181
|
+
DELETE FROM validator_duties
|
|
182
|
+
WHERE status = 'signed'
|
|
183
|
+
AND completed_at < $1;
|
|
184
|
+
`;
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Query to clean up old duties (for maintenance)
|
|
188
|
+
* Removes duties older than a specified timestamp
|
|
189
|
+
*/
|
|
190
|
+
export const CLEANUP_OLD_DUTIES = `
|
|
191
|
+
DELETE FROM validator_duties
|
|
192
|
+
WHERE status IN ('signing', 'signed', 'failed')
|
|
193
|
+
AND started_at < $1;
|
|
194
|
+
`;
|
|
195
|
+
|
|
196
|
+
/**
|
|
197
|
+
* Query to cleanup own stuck duties
|
|
198
|
+
* Removes duties in 'signing' status for a specific node that are older than maxAgeMs
|
|
199
|
+
*/
|
|
200
|
+
export const CLEANUP_OWN_STUCK_DUTIES = `
|
|
201
|
+
DELETE FROM validator_duties
|
|
202
|
+
WHERE node_id = $1
|
|
203
|
+
AND status = 'signing'
|
|
204
|
+
AND started_at < $2;
|
|
205
|
+
`;
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* SQL to drop the validator_duties table
|
|
209
|
+
*/
|
|
210
|
+
export const DROP_VALIDATOR_DUTIES_TABLE = `DROP TABLE IF EXISTS validator_duties;`;
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* SQL to drop the schema_version table
|
|
214
|
+
*/
|
|
215
|
+
export const DROP_SCHEMA_VERSION_TABLE = `DROP TABLE IF EXISTS schema_version;`;
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Query to get stuck duties (for monitoring/alerting)
|
|
219
|
+
* Returns duties in 'signing' status that have been stuck for too long
|
|
220
|
+
*/
|
|
221
|
+
export const GET_STUCK_DUTIES = `
|
|
222
|
+
SELECT
|
|
223
|
+
validator_address,
|
|
224
|
+
slot,
|
|
225
|
+
block_number,
|
|
226
|
+
duty_type,
|
|
227
|
+
status,
|
|
228
|
+
message_hash,
|
|
229
|
+
node_id,
|
|
230
|
+
started_at,
|
|
231
|
+
EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - started_at)) as age_seconds
|
|
232
|
+
FROM validator_duties
|
|
233
|
+
WHERE status = 'signing'
|
|
234
|
+
AND started_at < $1
|
|
235
|
+
ORDER BY started_at ASC;
|
|
236
|
+
`;
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Test helpers for database setup
|
|
3
|
+
*/
|
|
4
|
+
import type { PGlite } from '@electric-sql/pglite';
|
|
5
|
+
|
|
6
|
+
import { INSERT_SCHEMA_VERSION, SCHEMA_SETUP, SCHEMA_VERSION } from './schema.js';
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Set up the database schema for testing.
|
|
10
|
+
* This runs the same SQL that migrations would apply.
|
|
11
|
+
*/
|
|
12
|
+
export async function setupTestSchema(pglite: PGlite): Promise<void> {
|
|
13
|
+
for (const statement of SCHEMA_SETUP) {
|
|
14
|
+
await pglite.query(statement);
|
|
15
|
+
}
|
|
16
|
+
await pglite.query(INSERT_SCHEMA_VERSION, [SCHEMA_VERSION]);
|
|
17
|
+
}
|