@aztec-labs/validator-ha-signer 6.0.0-nightly.20260829

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/README.md +195 -0
  2. package/dest/db/index.d.ts +5 -0
  3. package/dest/db/index.d.ts.map +1 -0
  4. package/dest/db/index.js +4 -0
  5. package/dest/db/lmdb.d.ts +70 -0
  6. package/dest/db/lmdb.d.ts.map +1 -0
  7. package/dest/db/lmdb.js +223 -0
  8. package/dest/db/migrations/1_initial-schema.d.ts +11 -0
  9. package/dest/db/migrations/1_initial-schema.d.ts.map +1 -0
  10. package/dest/db/migrations/1_initial-schema.js +50 -0
  11. package/dest/db/migrations/2_add-checkpoint-number.d.ts +7 -0
  12. package/dest/db/migrations/2_add-checkpoint-number.d.ts.map +1 -0
  13. package/dest/db/migrations/2_add-checkpoint-number.js +17 -0
  14. package/dest/db/postgres.d.ts +86 -0
  15. package/dest/db/postgres.d.ts.map +1 -0
  16. package/dest/db/postgres.js +210 -0
  17. package/dest/db/schema.d.ts +96 -0
  18. package/dest/db/schema.d.ts.map +1 -0
  19. package/dest/db/schema.js +235 -0
  20. package/dest/db/test_helper.d.ts +10 -0
  21. package/dest/db/test_helper.d.ts.map +1 -0
  22. package/dest/db/test_helper.js +14 -0
  23. package/dest/db/types.d.ts +191 -0
  24. package/dest/db/types.d.ts.map +1 -0
  25. package/dest/db/types.js +65 -0
  26. package/dest/errors.d.ts +47 -0
  27. package/dest/errors.d.ts.map +1 -0
  28. package/dest/errors.js +49 -0
  29. package/dest/factory.d.ts +75 -0
  30. package/dest/factory.d.ts.map +1 -0
  31. package/dest/factory.js +166 -0
  32. package/dest/metrics.d.ts +51 -0
  33. package/dest/metrics.d.ts.map +1 -0
  34. package/dest/metrics.js +103 -0
  35. package/dest/migrations.d.ts +15 -0
  36. package/dest/migrations.d.ts.map +1 -0
  37. package/dest/migrations.js +53 -0
  38. package/dest/slashing_protection_service.d.ts +95 -0
  39. package/dest/slashing_protection_service.d.ts.map +1 -0
  40. package/dest/slashing_protection_service.js +239 -0
  41. package/dest/test/pglite_pool.d.ts +92 -0
  42. package/dest/test/pglite_pool.d.ts.map +1 -0
  43. package/dest/test/pglite_pool.js +210 -0
  44. package/dest/types.d.ts +100 -0
  45. package/dest/types.d.ts.map +1 -0
  46. package/dest/types.js +5 -0
  47. package/dest/validator_ha_signer.d.ts +80 -0
  48. package/dest/validator_ha_signer.d.ts.map +1 -0
  49. package/dest/validator_ha_signer.js +165 -0
  50. package/package.json +109 -0
  51. package/src/db/index.ts +4 -0
  52. package/src/db/lmdb.ts +308 -0
  53. package/src/db/migrations/1_initial-schema.ts +57 -0
  54. package/src/db/migrations/2_add-checkpoint-number.ts +19 -0
  55. package/src/db/postgres.ts +285 -0
  56. package/src/db/schema.ts +272 -0
  57. package/src/db/test_helper.ts +17 -0
  58. package/src/db/types.ts +258 -0
  59. package/src/errors.ts +68 -0
  60. package/src/factory.ts +215 -0
  61. package/src/metrics.ts +138 -0
  62. package/src/migrations.ts +74 -0
  63. package/src/slashing_protection_service.ts +313 -0
  64. package/src/test/pglite_pool.ts +256 -0
  65. package/src/types.ts +159 -0
  66. package/src/validator_ha_signer.ts +223 -0
@@ -0,0 +1,86 @@
1
+ /**
2
+ * PostgreSQL implementation of SlashingProtectionDatabase
3
+ */
4
+ import { SlotNumber } from '@aztec-labs/foundation/branded-types';
5
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
6
+ import type { QueryResult, QueryResultRow } from 'pg';
7
+ import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
8
+ import type { CheckAndRecordParams, DutyType } from './types.js';
9
+ /**
10
+ * Minimal pool interface for database operations.
11
+ * Both pg.Pool and test adapters (e.g., PGlite) satisfy this interface.
12
+ */
13
+ export interface QueryablePool {
14
+ query<R extends QueryResultRow = any>(text: string, values?: any[]): Promise<QueryResult<R>>;
15
+ end(): Promise<void>;
16
+ }
17
+ /**
18
+ * PostgreSQL implementation of the slashing protection database
19
+ */
20
+ export declare class PostgresSlashingProtectionDatabase implements SlashingProtectionDatabase {
21
+ private readonly pool;
22
+ private readonly log;
23
+ constructor(pool: QueryablePool);
24
+ /**
25
+ * Verify that database migrations have been run and schema version matches.
26
+ * Should be called once at startup.
27
+ *
28
+ * @throws Error if migrations haven't been run or schema version is outdated
29
+ */
30
+ initialize(): Promise<void>;
31
+ /**
32
+ * Atomically try to insert a new duty record, or get the existing one if present.
33
+ *
34
+ * @returns { isNew: true, record } if we successfully inserted and acquired the lock
35
+ * @returns { isNew: false, record } if a record already exists. lock_token is empty if the record already exists.
36
+ *
37
+ * Retries if no rows are returned, which can happen under high concurrency
38
+ * when another transaction just committed the row but it's not yet visible.
39
+ */
40
+ tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult>;
41
+ /**
42
+ * Update a duty to 'signed' status with the signature.
43
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
44
+ *
45
+ * @returns true if the update succeeded, false if token didn't match or duty not found
46
+ */
47
+ updateDutySigned(rollupAddress: EthAddress, validatorAddress: EthAddress, slot: SlotNumber, dutyType: DutyType, signature: string, lockToken: string, blockIndexWithinCheckpoint: number): Promise<boolean>;
48
+ /**
49
+ * Delete a duty record.
50
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
51
+ * Used when signing fails to allow another node/attempt to retry.
52
+ *
53
+ * @returns true if the delete succeeded, false if token didn't match or duty not found
54
+ */
55
+ deleteDuty(rollupAddress: EthAddress, validatorAddress: EthAddress, slot: SlotNumber, dutyType: DutyType, lockToken: string, blockIndexWithinCheckpoint: number): Promise<boolean>;
56
+ /**
57
+ * Convert a database row to a ValidatorDutyRecord.
58
+ * Maps snake_case column names to StoredDutyRecord (camelCase, ms timestamps),
59
+ * then delegates to the shared recordFromFields() converter.
60
+ */
61
+ private rowToRecord;
62
+ /**
63
+ * Close the database connection pool
64
+ */
65
+ close(): Promise<void>;
66
+ /**
67
+ * Cleanup own stuck duties
68
+ * @returns the number of duties cleaned up
69
+ */
70
+ cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
71
+ /**
72
+ * Cleanup duties with outdated rollup address.
73
+ * Removes all duties where the rollup address doesn't match the current one.
74
+ * Used after a rollup upgrade to clean up duties for the old rollup.
75
+ * @returns the number of duties cleaned up
76
+ */
77
+ cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number>;
78
+ /**
79
+ * Cleanup old signed duties.
80
+ * Removes only signed duties older than the specified age.
81
+ * Does not remove 'signing' duties as they may be in progress.
82
+ * @returns the number of duties cleaned up
83
+ */
84
+ cleanupOldDuties(maxAgeMs: number): Promise<number>;
85
+ }
86
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicG9zdGdyZXMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kYi9wb3N0Z3Jlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7R0FFRztBQUNILE9BQU8sRUFBRSxVQUFVLEVBQUUsTUFBTSxzQ0FBc0MsQ0FBQztBQUVsRSxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0sb0NBQW9DLENBQUM7QUFHaEUsT0FBTyxLQUFLLEVBQUUsV0FBVyxFQUFFLGNBQWMsRUFBRSxNQUFNLElBQUksQ0FBQztBQUV0RCxPQUFPLEtBQUssRUFBRSwwQkFBMEIsRUFBRSxvQkFBb0IsRUFBRSxNQUFNLGFBQWEsQ0FBQztBQVVwRixPQUFPLEtBQUssRUFBRSxvQkFBb0IsRUFBVyxRQUFRLEVBQXVDLE1BQU0sWUFBWSxDQUFDO0FBRy9HOzs7R0FHRztBQUNILE1BQU0sV0FBVyxhQUFhO0lBQzVCLEtBQUssQ0FBQyxDQUFDLFNBQVMsY0FBYyxHQUFHLEdBQUcsRUFBRSxJQUFJLEVBQUUsTUFBTSxFQUFFLE1BQU0s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+ /**
2
+ * PostgreSQL implementation of SlashingProtectionDatabase
3
+ */ import { randomBytes } from '@aztec-labs/foundation/crypto/random';
4
+ import { createLogger } from '@aztec-labs/foundation/log';
5
+ import { makeBackoff, retry } from '@aztec-labs/foundation/retry';
6
+ import { CLEANUP_OLD_DUTIES, CLEANUP_OUTDATED_ROLLUP_DUTIES, CLEANUP_OWN_STUCK_DUTIES, DELETE_DUTY, INSERT_OR_GET_DUTY, SCHEMA_VERSION, UPDATE_DUTY_SIGNED } from './schema.js';
7
+ import { getBlockIndexFromDutyIdentifier, recordFromFields } from './types.js';
8
+ /**
9
+ * PostgreSQL implementation of the slashing protection database
10
+ */ export class PostgresSlashingProtectionDatabase {
11
+ pool;
12
+ log;
13
+ constructor(pool){
14
+ this.pool = pool;
15
+ this.log = createLogger('slashing-protection:postgres');
16
+ }
17
+ /**
18
+ * Verify that database migrations have been run and schema version matches.
19
+ * Should be called once at startup.
20
+ *
21
+ * @throws Error if migrations haven't been run or schema version is outdated
22
+ */ async initialize() {
23
+ let dbVersion;
24
+ try {
25
+ const result = await this.pool.query(`SELECT version FROM schema_version ORDER BY version DESC LIMIT 1`);
26
+ if (result.rows.length === 0) {
27
+ throw new Error('No version found');
28
+ }
29
+ dbVersion = result.rows[0].version;
30
+ } catch {
31
+ throw new Error('Database schema not initialized. Please run migrations first: aztec migrate-ha-db up --database-url <url>');
32
+ }
33
+ if (dbVersion < SCHEMA_VERSION) {
34
+ throw new Error(`Database schema version ${dbVersion} is outdated (expected ${SCHEMA_VERSION}). Please run migrations: aztec migrate-ha-db up --database-url <url>`);
35
+ }
36
+ if (dbVersion > SCHEMA_VERSION) {
37
+ throw new Error(`Database schema version ${dbVersion} is newer than expected (${SCHEMA_VERSION}). Please update your application.`);
38
+ }
39
+ this.log.info('Database schema verified', {
40
+ version: dbVersion
41
+ });
42
+ }
43
+ /**
44
+ * Atomically try to insert a new duty record, or get the existing one if present.
45
+ *
46
+ * @returns { isNew: true, record } if we successfully inserted and acquired the lock
47
+ * @returns { isNew: false, record } if a record already exists. lock_token is empty if the record already exists.
48
+ *
49
+ * Retries if no rows are returned, which can happen under high concurrency
50
+ * when another transaction just committed the row but it's not yet visible.
51
+ */ async tryInsertOrGetExisting(params) {
52
+ // create a token for ownership verification
53
+ const lockToken = randomBytes(16).toString('hex');
54
+ // Use fast retries with custom backoff: 10ms, 20ms, 30ms (then stop)
55
+ const fastBackoff = makeBackoff([
56
+ 0.01,
57
+ 0.02,
58
+ 0.03
59
+ ]);
60
+ // Get the normalized block index using type-safe helper
61
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
62
+ const result = await retry(async ()=>{
63
+ const queryResult = await this.pool.query(INSERT_OR_GET_DUTY, [
64
+ params.rollupAddress.toString(),
65
+ params.validatorAddress.toString(),
66
+ params.slot.toString(),
67
+ params.blockNumber.toString(),
68
+ params.checkpointNumber.toString(),
69
+ blockIndexWithinCheckpoint,
70
+ params.dutyType,
71
+ params.messageHash,
72
+ params.nodeId,
73
+ lockToken
74
+ ]);
75
+ // Throw error if no rows to trigger retry
76
+ if (queryResult.rows.length === 0) {
77
+ throw new Error('INSERT_OR_GET_DUTY returned no rows');
78
+ }
79
+ return queryResult;
80
+ }, `INSERT_OR_GET_DUTY for node ${params.nodeId}`, fastBackoff, this.log, true);
81
+ if (result.rows.length === 0) {
82
+ // this should never happen as the retry function should throw if it still fails after retries
83
+ throw new Error('INSERT_OR_GET_DUTY returned no rows after retries');
84
+ }
85
+ if (result.rows.length > 1) {
86
+ // this should never happen if database constraints are correct (PRIMARY KEY should prevent duplicates)
87
+ throw new Error(`INSERT_OR_GET_DUTY returned ${result.rows.length} rows (expected exactly 1).`);
88
+ }
89
+ const row = result.rows[0];
90
+ return {
91
+ isNew: row.is_new,
92
+ record: this.rowToRecord(row)
93
+ };
94
+ }
95
+ /**
96
+ * Update a duty to 'signed' status with the signature.
97
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
98
+ *
99
+ * @returns true if the update succeeded, false if token didn't match or duty not found
100
+ */ async updateDutySigned(rollupAddress, validatorAddress, slot, dutyType, signature, lockToken, blockIndexWithinCheckpoint) {
101
+ const result = await this.pool.query(UPDATE_DUTY_SIGNED, [
102
+ signature,
103
+ rollupAddress.toString(),
104
+ validatorAddress.toString(),
105
+ slot.toString(),
106
+ dutyType,
107
+ blockIndexWithinCheckpoint,
108
+ lockToken
109
+ ]);
110
+ if (result.rowCount === 0) {
111
+ this.log.warn('Failed to update duty to signed status: invalid token or duty not found', {
112
+ rollupAddress: rollupAddress.toString(),
113
+ validatorAddress: validatorAddress.toString(),
114
+ slot: slot.toString(),
115
+ dutyType,
116
+ blockIndexWithinCheckpoint
117
+ });
118
+ return false;
119
+ }
120
+ return true;
121
+ }
122
+ /**
123
+ * Delete a duty record.
124
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
125
+ * Used when signing fails to allow another node/attempt to retry.
126
+ *
127
+ * @returns true if the delete succeeded, false if token didn't match or duty not found
128
+ */ async deleteDuty(rollupAddress, validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint) {
129
+ const result = await this.pool.query(DELETE_DUTY, [
130
+ rollupAddress.toString(),
131
+ validatorAddress.toString(),
132
+ slot.toString(),
133
+ dutyType,
134
+ blockIndexWithinCheckpoint,
135
+ lockToken
136
+ ]);
137
+ if (result.rowCount === 0) {
138
+ this.log.warn('Failed to delete duty: invalid token or duty not found', {
139
+ rollupAddress: rollupAddress.toString(),
140
+ validatorAddress: validatorAddress.toString(),
141
+ slot: slot.toString(),
142
+ dutyType,
143
+ blockIndexWithinCheckpoint
144
+ });
145
+ return false;
146
+ }
147
+ return true;
148
+ }
149
+ /**
150
+ * Convert a database row to a ValidatorDutyRecord.
151
+ * Maps snake_case column names to StoredDutyRecord (camelCase, ms timestamps),
152
+ * then delegates to the shared recordFromFields() converter.
153
+ */ rowToRecord(row) {
154
+ return recordFromFields({
155
+ rollupAddress: row.rollup_address,
156
+ validatorAddress: row.validator_address,
157
+ slot: row.slot,
158
+ blockNumber: row.block_number,
159
+ checkpointNumber: row.checkpoint_number,
160
+ blockIndexWithinCheckpoint: row.block_index_within_checkpoint,
161
+ dutyType: row.duty_type,
162
+ status: row.status,
163
+ messageHash: row.message_hash,
164
+ signature: row.signature ?? undefined,
165
+ nodeId: row.node_id,
166
+ lockToken: row.lock_token,
167
+ startedAtMs: row.started_at.getTime(),
168
+ completedAtMs: row.completed_at?.getTime(),
169
+ errorMessage: row.error_message ?? undefined
170
+ });
171
+ }
172
+ /**
173
+ * Close the database connection pool
174
+ */ async close() {
175
+ await this.pool.end();
176
+ this.log.info('Database connection pool closed');
177
+ }
178
+ /**
179
+ * Cleanup own stuck duties
180
+ * @returns the number of duties cleaned up
181
+ */ async cleanupOwnStuckDuties(nodeId, maxAgeMs) {
182
+ const result = await this.pool.query(CLEANUP_OWN_STUCK_DUTIES, [
183
+ nodeId,
184
+ maxAgeMs
185
+ ]);
186
+ return result.rowCount ?? 0;
187
+ }
188
+ /**
189
+ * Cleanup duties with outdated rollup address.
190
+ * Removes all duties where the rollup address doesn't match the current one.
191
+ * Used after a rollup upgrade to clean up duties for the old rollup.
192
+ * @returns the number of duties cleaned up
193
+ */ async cleanupOutdatedRollupDuties(currentRollupAddress) {
194
+ const result = await this.pool.query(CLEANUP_OUTDATED_ROLLUP_DUTIES, [
195
+ currentRollupAddress.toString()
196
+ ]);
197
+ return result.rowCount ?? 0;
198
+ }
199
+ /**
200
+ * Cleanup old signed duties.
201
+ * Removes only signed duties older than the specified age.
202
+ * Does not remove 'signing' duties as they may be in progress.
203
+ * @returns the number of duties cleaned up
204
+ */ async cleanupOldDuties(maxAgeMs) {
205
+ const result = await this.pool.query(CLEANUP_OLD_DUTIES, [
206
+ maxAgeMs
207
+ ]);
208
+ return result.rowCount ?? 0;
209
+ }
210
+ }
@@ -0,0 +1,96 @@
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
+ * Current schema version
10
+ */
11
+ export declare const SCHEMA_VERSION = 2;
12
+ /**
13
+ * SQL to create the validator_duties table
14
+ */
15
+ export declare const CREATE_VALIDATOR_DUTIES_TABLE = "\nCREATE TABLE IF NOT EXISTS validator_duties (\n rollup_address VARCHAR(42) NOT NULL,\n validator_address VARCHAR(42) NOT NULL,\n slot BIGINT NOT NULL,\n block_number BIGINT NOT NULL,\n checkpoint_number BIGINT NOT NULL DEFAULT 0,\n block_index_within_checkpoint INTEGER NOT NULL DEFAULT 0,\n duty_type VARCHAR(30) NOT NULL CHECK (duty_type IN ('BLOCK_PROPOSAL', 'CHECKPOINT_PROPOSAL', 'ATTESTATION', 'ATTESTATIONS_AND_SIGNERS', 'GOVERNANCE_VOTE', 'SLASHING_VOTE')),\n status VARCHAR(20) NOT NULL CHECK (status IN ('signing', 'signed')),\n message_hash VARCHAR(66) NOT NULL,\n signature VARCHAR(132),\n node_id VARCHAR(255) NOT NULL,\n lock_token VARCHAR(64) NOT NULL,\n started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n completed_at TIMESTAMP,\n error_message TEXT,\n\n PRIMARY KEY (rollup_address, validator_address, slot, duty_type, block_index_within_checkpoint),\n CHECK (completed_at IS NULL OR completed_at >= started_at)\n);\n";
16
+ /**
17
+ * SQL to create index on status and started_at for cleanup queries
18
+ */
19
+ export declare const CREATE_STATUS_INDEX = "\nCREATE INDEX IF NOT EXISTS idx_validator_duties_status\nON validator_duties(status, started_at);\n";
20
+ /**
21
+ * SQL to create index for querying duties by node
22
+ */
23
+ export declare const CREATE_NODE_INDEX = "\nCREATE INDEX IF NOT EXISTS idx_validator_duties_node\nON validator_duties(node_id, started_at);\n";
24
+ /**
25
+ * SQL to create the schema_version table for tracking migrations
26
+ */
27
+ export declare const CREATE_SCHEMA_VERSION_TABLE = "\nCREATE TABLE IF NOT EXISTS schema_version (\n version INTEGER PRIMARY KEY,\n applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\n);\n";
28
+ /**
29
+ * SQL to initialize schema version
30
+ */
31
+ export declare const INSERT_SCHEMA_VERSION = "\nINSERT INTO schema_version (version)\nVALUES ($1)\nON CONFLICT (version) DO NOTHING;\n";
32
+ /**
33
+ * Complete schema setup - all statements in order
34
+ */
35
+ export declare const SCHEMA_SETUP: readonly ["\nCREATE TABLE IF NOT EXISTS schema_version (\n version INTEGER PRIMARY KEY,\n applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP\n);\n", "\nCREATE TABLE IF NOT EXISTS validator_duties (\n rollup_address VARCHAR(42) NOT NULL,\n validator_address VARCHAR(42) NOT NULL,\n slot BIGINT NOT NULL,\n block_number BIGINT NOT NULL,\n checkpoint_number BIGINT NOT NULL DEFAULT 0,\n block_index_within_checkpoint INTEGER NOT NULL DEFAULT 0,\n duty_type VARCHAR(30) NOT NULL CHECK (duty_type IN ('BLOCK_PROPOSAL', 'CHECKPOINT_PROPOSAL', 'ATTESTATION', 'ATTESTATIONS_AND_SIGNERS', 'GOVERNANCE_VOTE', 'SLASHING_VOTE')),\n status VARCHAR(20) NOT NULL CHECK (status IN ('signing', 'signed')),\n message_hash VARCHAR(66) NOT NULL,\n signature VARCHAR(132),\n node_id VARCHAR(255) NOT NULL,\n lock_token VARCHAR(64) NOT NULL,\n started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n completed_at TIMESTAMP,\n error_message TEXT,\n\n PRIMARY KEY (rollup_address, validator_address, slot, duty_type, block_index_within_checkpoint),\n CHECK (completed_at IS NULL OR completed_at >= started_at)\n);\n", "\nCREATE INDEX IF NOT EXISTS idx_validator_duties_status\nON validator_duties(status, started_at);\n", "\nCREATE INDEX IF NOT EXISTS idx_validator_duties_node\nON validator_duties(node_id, started_at);\n"];
36
+ /**
37
+ * Query to get current schema version
38
+ */
39
+ export declare const GET_SCHEMA_VERSION = "\nSELECT version FROM schema_version ORDER BY version DESC LIMIT 1;\n";
40
+ /**
41
+ * Atomic insert-or-get query.
42
+ * Tries to insert a new duty record. If a record already exists (conflict),
43
+ * returns the existing record instead.
44
+ *
45
+ * Returns the record with an `is_new` flag indicating whether we inserted or got existing.
46
+ *
47
+ * Note: In high concurrency scenarios, if the INSERT conflicts and another transaction
48
+ * just committed the row, there's a small window where the SELECT might not see it yet.
49
+ * The application layer should retry if no rows are returned.
50
+ */
51
+ export declare const INSERT_OR_GET_DUTY = "\nWITH inserted AS (\n INSERT INTO validator_duties (\n rollup_address,\n validator_address,\n slot,\n block_number,\n checkpoint_number,\n block_index_within_checkpoint,\n duty_type,\n status,\n message_hash,\n node_id,\n lock_token,\n started_at\n ) VALUES ($1, $2, $3, $4, $5, $6, $7, 'signing', $8, $9, $10, CURRENT_TIMESTAMP)\n ON CONFLICT (rollup_address, validator_address, slot, duty_type, block_index_within_checkpoint) DO NOTHING\n RETURNING\n rollup_address,\n validator_address,\n slot,\n block_number,\n checkpoint_number,\n block_index_within_checkpoint,\n duty_type,\n status,\n message_hash,\n signature,\n node_id,\n lock_token,\n started_at,\n completed_at,\n error_message,\n TRUE as is_new\n)\nSELECT * FROM inserted\nUNION ALL\nSELECT\n rollup_address,\n validator_address,\n slot,\n block_number,\n checkpoint_number,\n block_index_within_checkpoint,\n duty_type,\n status,\n message_hash,\n signature,\n node_id,\n '' as lock_token,\n started_at,\n completed_at,\n error_message,\n FALSE as is_new\nFROM validator_duties\nWHERE rollup_address = $1\n AND validator_address = $2\n AND slot = $3\n AND duty_type = $7\n AND block_index_within_checkpoint = $6\n AND NOT EXISTS (SELECT 1 FROM inserted);\n";
52
+ /**
53
+ * Query to update a duty to 'signed' status
54
+ */
55
+ export declare const UPDATE_DUTY_SIGNED = "\nUPDATE validator_duties\nSET status = 'signed',\n signature = $1,\n completed_at = CURRENT_TIMESTAMP\nWHERE rollup_address = $2\n AND validator_address = $3\n AND slot = $4\n AND duty_type = $5\n AND block_index_within_checkpoint = $6\n AND status = 'signing'\n AND lock_token = $7;\n";
56
+ /**
57
+ * Query to delete a duty
58
+ * Only deletes if the lockToken matches
59
+ */
60
+ export declare const DELETE_DUTY = "\nDELETE FROM validator_duties\nWHERE rollup_address = $1\n AND validator_address = $2\n AND slot = $3\n AND duty_type = $4\n AND block_index_within_checkpoint = $5\n AND status = 'signing'\n AND lock_token = $6;\n";
61
+ /**
62
+ * Query to clean up old signed duties (for maintenance)
63
+ * Removes signed duties older than a specified timestamp
64
+ */
65
+ export declare const CLEANUP_OLD_SIGNED_DUTIES = "\nDELETE FROM validator_duties\nWHERE status = 'signed'\n AND completed_at < $1;\n";
66
+ /**
67
+ * Query to clean up old duties (for maintenance)
68
+ * Removes SIGNED duties older than a specified age (in milliseconds)
69
+ */
70
+ export declare const CLEANUP_OLD_DUTIES = "\nDELETE FROM validator_duties\nWHERE status = 'signed'\n AND started_at < CURRENT_TIMESTAMP - ($1 || ' milliseconds')::INTERVAL;\n";
71
+ /**
72
+ * Query to cleanup own stuck duties
73
+ * Removes duties in 'signing' status for a specific node that are older than maxAgeMs
74
+ * Uses DB's CURRENT_TIMESTAMP to avoid clock skew issues between nodes
75
+ */
76
+ export declare const CLEANUP_OWN_STUCK_DUTIES = "\nDELETE FROM validator_duties\nWHERE node_id = $1\n AND status = 'signing'\n AND started_at < CURRENT_TIMESTAMP - ($2 || ' milliseconds')::INTERVAL;\n";
77
+ /**
78
+ * Query to cleanup duties with outdated rollup address
79
+ * Removes all duties where the rollup address doesn't match the current one
80
+ * Used after a rollup upgrade to clean up duties for the old rollup
81
+ */
82
+ export declare const CLEANUP_OUTDATED_ROLLUP_DUTIES = "\nDELETE FROM validator_duties\nWHERE rollup_address != $1;\n";
83
+ /**
84
+ * SQL to drop the validator_duties table
85
+ */
86
+ export declare const DROP_VALIDATOR_DUTIES_TABLE = "DROP TABLE IF EXISTS validator_duties;";
87
+ /**
88
+ * SQL to drop the schema_version table
89
+ */
90
+ export declare const DROP_SCHEMA_VERSION_TABLE = "DROP TABLE IF EXISTS schema_version;";
91
+ /**
92
+ * Query to get stuck duties (for monitoring/alerting)
93
+ * Returns duties in 'signing' status that have been stuck for too long
94
+ */
95
+ export declare const GET_STUCK_DUTIES = "\nSELECT\n rollup_address,\n validator_address,\n slot,\n block_number,\n checkpoint_number,\n block_index_within_checkpoint,\n duty_type,\n status,\n message_hash,\n node_id,\n started_at,\n EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - started_at)) as age_seconds\nFROM validator_duties\nWHERE status = 'signing'\n AND started_at < $1\nORDER BY started_at ASC;\n";
96
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NoZW1hLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvZGIvc2NoZW1hLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7R0FNRztBQUVIOztHQUVHO0FBQ0gsZUFBTyxNQUFNLGNBQWMsSUFBSSxDQUFDO0FBRWhDOztHQUVHO0FBQ0gsZUFBTyxNQUFNLDZCQUE2QixzOEJBcUJ6QyxDQUFDO0FBRUY7O0dBRUc7QUFDSCxlQUFPLE1BQU0sbUJBQW1CLHlHQUcvQixDQUFDO0FBRUY7O0dBRUc7QUFDSCxlQUFPLE1BQU0saUJBQWlCLHdHQUc3QixDQUFDO0FBRUY7O0dBRUc7QUFDSCxlQUFPLE1BQU0sMkJBQTJCLG1KQUt2QyxDQUFDO0FBRUY7O0dBRUc7QUFDSCxlQUFPLE1BQU0scUJBQXFCLDZGQUlqQyxDQUFDO0FBRUY7O0dBRUc7QUFDSCxlQUFPLE1BQU0sWUFBWSxpekNBS2YsQ0FBQztBQUVYOztHQUVHO0FBQ0gsZUFBTyxNQUFNLGtCQUFrQiwwRUFFOUIsQ0FBQztBQUVGOzs7Ozs7Ozs7O0dBVUc7QUFDSCxlQUFPLE1BQU0sa0JBQWtCLHd6Q0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kBAAkB,wzCA6D9B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,kBAAkB,+SAY9B,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,WAAW,iOASvB,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,yBAAyB,wFAIrC,CAAC;AAEF;;;GAGG;AACH,eAAO,MAAM,kBAAkB,yIAI9B,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,wBAAwB,8JAKpC,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,8BAA8B,kEAG1C,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,2BAA2B,2CAA2C,CAAC;AAEpF;;GAEG;AACH,eAAO,MAAM,yBAAyB,yCAAyC,CAAC;AAEhF;;;GAGG;AACH,eAAO,MAAM,gBAAgB,wXAkB5B,CAAC"}
@@ -0,0 +1,235 @@
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
+ * Current schema version
9
+ */ export const SCHEMA_VERSION = 2;
10
+ /**
11
+ * SQL to create the validator_duties table
12
+ */ export const CREATE_VALIDATOR_DUTIES_TABLE = `
13
+ CREATE TABLE IF NOT EXISTS validator_duties (
14
+ rollup_address VARCHAR(42) NOT NULL,
15
+ validator_address VARCHAR(42) NOT NULL,
16
+ slot BIGINT NOT NULL,
17
+ block_number BIGINT NOT NULL,
18
+ checkpoint_number BIGINT NOT NULL DEFAULT 0,
19
+ block_index_within_checkpoint INTEGER NOT NULL DEFAULT 0,
20
+ duty_type VARCHAR(30) NOT NULL CHECK (duty_type IN ('BLOCK_PROPOSAL', 'CHECKPOINT_PROPOSAL', 'ATTESTATION', 'ATTESTATIONS_AND_SIGNERS', 'GOVERNANCE_VOTE', 'SLASHING_VOTE')),
21
+ status VARCHAR(20) NOT NULL CHECK (status IN ('signing', 'signed')),
22
+ message_hash VARCHAR(66) NOT NULL,
23
+ signature VARCHAR(132),
24
+ node_id VARCHAR(255) NOT NULL,
25
+ lock_token VARCHAR(64) NOT NULL,
26
+ started_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
27
+ completed_at TIMESTAMP,
28
+ error_message TEXT,
29
+
30
+ PRIMARY KEY (rollup_address, validator_address, slot, duty_type, block_index_within_checkpoint),
31
+ CHECK (completed_at IS NULL OR completed_at >= started_at)
32
+ );
33
+ `;
34
+ /**
35
+ * SQL to create index on status and started_at for cleanup queries
36
+ */ export const CREATE_STATUS_INDEX = `
37
+ CREATE INDEX IF NOT EXISTS idx_validator_duties_status
38
+ ON validator_duties(status, started_at);
39
+ `;
40
+ /**
41
+ * SQL to create index for querying duties by node
42
+ */ export const CREATE_NODE_INDEX = `
43
+ CREATE INDEX IF NOT EXISTS idx_validator_duties_node
44
+ ON validator_duties(node_id, started_at);
45
+ `;
46
+ /**
47
+ * SQL to create the schema_version table for tracking migrations
48
+ */ export const CREATE_SCHEMA_VERSION_TABLE = `
49
+ CREATE TABLE IF NOT EXISTS schema_version (
50
+ version INTEGER PRIMARY KEY,
51
+ applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
52
+ );
53
+ `;
54
+ /**
55
+ * SQL to initialize schema version
56
+ */ export const INSERT_SCHEMA_VERSION = `
57
+ INSERT INTO schema_version (version)
58
+ VALUES ($1)
59
+ ON CONFLICT (version) DO NOTHING;
60
+ `;
61
+ /**
62
+ * Complete schema setup - all statements in order
63
+ */ export const SCHEMA_SETUP = [
64
+ CREATE_SCHEMA_VERSION_TABLE,
65
+ CREATE_VALIDATOR_DUTIES_TABLE,
66
+ CREATE_STATUS_INDEX,
67
+ CREATE_NODE_INDEX
68
+ ];
69
+ /**
70
+ * Query to get current schema version
71
+ */ export const GET_SCHEMA_VERSION = `
72
+ SELECT version FROM schema_version ORDER BY version DESC LIMIT 1;
73
+ `;
74
+ /**
75
+ * Atomic insert-or-get query.
76
+ * Tries to insert a new duty record. If a record already exists (conflict),
77
+ * returns the existing record instead.
78
+ *
79
+ * Returns the record with an `is_new` flag indicating whether we inserted or got existing.
80
+ *
81
+ * Note: In high concurrency scenarios, if the INSERT conflicts and another transaction
82
+ * just committed the row, there's a small window where the SELECT might not see it yet.
83
+ * The application layer should retry if no rows are returned.
84
+ */ export const INSERT_OR_GET_DUTY = `
85
+ WITH inserted AS (
86
+ INSERT INTO validator_duties (
87
+ rollup_address,
88
+ validator_address,
89
+ slot,
90
+ block_number,
91
+ checkpoint_number,
92
+ block_index_within_checkpoint,
93
+ duty_type,
94
+ status,
95
+ message_hash,
96
+ node_id,
97
+ lock_token,
98
+ started_at
99
+ ) VALUES ($1, $2, $3, $4, $5, $6, $7, 'signing', $8, $9, $10, CURRENT_TIMESTAMP)
100
+ ON CONFLICT (rollup_address, validator_address, slot, duty_type, block_index_within_checkpoint) DO NOTHING
101
+ RETURNING
102
+ rollup_address,
103
+ validator_address,
104
+ slot,
105
+ block_number,
106
+ checkpoint_number,
107
+ block_index_within_checkpoint,
108
+ duty_type,
109
+ status,
110
+ message_hash,
111
+ signature,
112
+ node_id,
113
+ lock_token,
114
+ started_at,
115
+ completed_at,
116
+ error_message,
117
+ TRUE as is_new
118
+ )
119
+ SELECT * FROM inserted
120
+ UNION ALL
121
+ SELECT
122
+ rollup_address,
123
+ validator_address,
124
+ slot,
125
+ block_number,
126
+ checkpoint_number,
127
+ block_index_within_checkpoint,
128
+ duty_type,
129
+ status,
130
+ message_hash,
131
+ signature,
132
+ node_id,
133
+ '' as lock_token,
134
+ started_at,
135
+ completed_at,
136
+ error_message,
137
+ FALSE as is_new
138
+ FROM validator_duties
139
+ WHERE rollup_address = $1
140
+ AND validator_address = $2
141
+ AND slot = $3
142
+ AND duty_type = $7
143
+ AND block_index_within_checkpoint = $6
144
+ AND NOT EXISTS (SELECT 1 FROM inserted);
145
+ `;
146
+ /**
147
+ * Query to update a duty to 'signed' status
148
+ */ export const UPDATE_DUTY_SIGNED = `
149
+ UPDATE validator_duties
150
+ SET status = 'signed',
151
+ signature = $1,
152
+ completed_at = CURRENT_TIMESTAMP
153
+ WHERE rollup_address = $2
154
+ AND validator_address = $3
155
+ AND slot = $4
156
+ AND duty_type = $5
157
+ AND block_index_within_checkpoint = $6
158
+ AND status = 'signing'
159
+ AND lock_token = $7;
160
+ `;
161
+ /**
162
+ * Query to delete a duty
163
+ * Only deletes if the lockToken matches
164
+ */ export const DELETE_DUTY = `
165
+ DELETE FROM validator_duties
166
+ WHERE rollup_address = $1
167
+ AND validator_address = $2
168
+ AND slot = $3
169
+ AND duty_type = $4
170
+ AND block_index_within_checkpoint = $5
171
+ AND status = 'signing'
172
+ AND lock_token = $6;
173
+ `;
174
+ /**
175
+ * Query to clean up old signed duties (for maintenance)
176
+ * Removes signed duties older than a specified timestamp
177
+ */ export const CLEANUP_OLD_SIGNED_DUTIES = `
178
+ DELETE FROM validator_duties
179
+ WHERE status = 'signed'
180
+ AND completed_at < $1;
181
+ `;
182
+ /**
183
+ * Query to clean up old duties (for maintenance)
184
+ * Removes SIGNED duties older than a specified age (in milliseconds)
185
+ */ export const CLEANUP_OLD_DUTIES = `
186
+ DELETE FROM validator_duties
187
+ WHERE status = 'signed'
188
+ AND started_at < CURRENT_TIMESTAMP - ($1 || ' milliseconds')::INTERVAL;
189
+ `;
190
+ /**
191
+ * Query to cleanup own stuck duties
192
+ * Removes duties in 'signing' status for a specific node that are older than maxAgeMs
193
+ * Uses DB's CURRENT_TIMESTAMP to avoid clock skew issues between nodes
194
+ */ export const CLEANUP_OWN_STUCK_DUTIES = `
195
+ DELETE FROM validator_duties
196
+ WHERE node_id = $1
197
+ AND status = 'signing'
198
+ AND started_at < CURRENT_TIMESTAMP - ($2 || ' milliseconds')::INTERVAL;
199
+ `;
200
+ /**
201
+ * Query to cleanup duties with outdated rollup address
202
+ * Removes all duties where the rollup address doesn't match the current one
203
+ * Used after a rollup upgrade to clean up duties for the old rollup
204
+ */ export const CLEANUP_OUTDATED_ROLLUP_DUTIES = `
205
+ DELETE FROM validator_duties
206
+ WHERE rollup_address != $1;
207
+ `;
208
+ /**
209
+ * SQL to drop the validator_duties table
210
+ */ export const DROP_VALIDATOR_DUTIES_TABLE = `DROP TABLE IF EXISTS validator_duties;`;
211
+ /**
212
+ * SQL to drop the schema_version table
213
+ */ export const DROP_SCHEMA_VERSION_TABLE = `DROP TABLE IF EXISTS schema_version;`;
214
+ /**
215
+ * Query to get stuck duties (for monitoring/alerting)
216
+ * Returns duties in 'signing' status that have been stuck for too long
217
+ */ export const GET_STUCK_DUTIES = `
218
+ SELECT
219
+ rollup_address,
220
+ validator_address,
221
+ slot,
222
+ block_number,
223
+ checkpoint_number,
224
+ block_index_within_checkpoint,
225
+ duty_type,
226
+ status,
227
+ message_hash,
228
+ node_id,
229
+ started_at,
230
+ EXTRACT(EPOCH FROM (CURRENT_TIMESTAMP - started_at)) as age_seconds
231
+ FROM validator_duties
232
+ WHERE status = 'signing'
233
+ AND started_at < $1
234
+ ORDER BY started_at ASC;
235
+ `;
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Test helpers for database setup
3
+ */
4
+ import type { PGlite } from '@electric-sql/pglite';
5
+ /**
6
+ * Set up the database schema for testing.
7
+ * This runs the same SQL that migrations would apply.
8
+ */
9
+ export declare function setupTestSchema(pglite: PGlite): Promise<void>;
10
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVzdF9oZWxwZXIuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kYi90ZXN0X2hlbHBlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7R0FFRztBQUNILE9BQU8sS0FBSyxFQUFFLE1BQU0sRUFBRSxNQUFNLHNCQUFzQixDQUFDO0FBSW5EOzs7R0FHRztBQUNILHdCQUFzQixlQUFlLENBQUMsTUFBTSxFQUFFLE1BQU0sR0FBRyxPQUFPLENBQUMsSUFBSSxDQUFDLENBS25FIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"test_helper.d.ts","sourceRoot":"","sources":["../../src/db/test_helper.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,sBAAsB,CAAC;AAInD;;;GAGG;AACH,wBAAsB,eAAe,CAAC,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAKnE"}