@aztec/validator-ha-signer 0.0.1-commit.0208eb9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/README.md +187 -0
  2. package/dest/config.d.ts +101 -0
  3. package/dest/config.d.ts.map +1 -0
  4. package/dest/config.js +92 -0
  5. package/dest/db/index.d.ts +4 -0
  6. package/dest/db/index.d.ts.map +1 -0
  7. package/dest/db/index.js +3 -0
  8. package/dest/db/migrations/1_initial-schema.d.ts +9 -0
  9. package/dest/db/migrations/1_initial-schema.d.ts.map +1 -0
  10. package/dest/db/migrations/1_initial-schema.js +20 -0
  11. package/dest/db/postgres.d.ts +84 -0
  12. package/dest/db/postgres.d.ts.map +1 -0
  13. package/dest/db/postgres.js +210 -0
  14. package/dest/db/schema.d.ts +95 -0
  15. package/dest/db/schema.d.ts.map +1 -0
  16. package/dest/db/schema.js +229 -0
  17. package/dest/db/test_helper.d.ts +10 -0
  18. package/dest/db/test_helper.d.ts.map +1 -0
  19. package/dest/db/test_helper.js +14 -0
  20. package/dest/db/types.d.ts +166 -0
  21. package/dest/db/types.d.ts.map +1 -0
  22. package/dest/db/types.js +49 -0
  23. package/dest/errors.d.ts +34 -0
  24. package/dest/errors.d.ts.map +1 -0
  25. package/dest/errors.js +34 -0
  26. package/dest/factory.d.ts +42 -0
  27. package/dest/factory.d.ts.map +1 -0
  28. package/dest/factory.js +70 -0
  29. package/dest/migrations.d.ts +15 -0
  30. package/dest/migrations.d.ts.map +1 -0
  31. package/dest/migrations.js +53 -0
  32. package/dest/slashing_protection_service.d.ts +84 -0
  33. package/dest/slashing_protection_service.d.ts.map +1 -0
  34. package/dest/slashing_protection_service.js +225 -0
  35. package/dest/test/pglite_pool.d.ts +92 -0
  36. package/dest/test/pglite_pool.d.ts.map +1 -0
  37. package/dest/test/pglite_pool.js +210 -0
  38. package/dest/types.d.ts +152 -0
  39. package/dest/types.d.ts.map +1 -0
  40. package/dest/types.js +21 -0
  41. package/dest/validator_ha_signer.d.ts +71 -0
  42. package/dest/validator_ha_signer.d.ts.map +1 -0
  43. package/dest/validator_ha_signer.js +132 -0
  44. package/package.json +106 -0
  45. package/src/config.ts +149 -0
  46. package/src/db/index.ts +3 -0
  47. package/src/db/migrations/1_initial-schema.ts +26 -0
  48. package/src/db/postgres.ts +284 -0
  49. package/src/db/schema.ts +266 -0
  50. package/src/db/test_helper.ts +17 -0
  51. package/src/db/types.ts +206 -0
  52. package/src/errors.ts +47 -0
  53. package/src/factory.ts +82 -0
  54. package/src/migrations.ts +75 -0
  55. package/src/slashing_protection_service.ts +287 -0
  56. package/src/test/pglite_pool.ts +256 -0
  57. package/src/types.ts +226 -0
  58. package/src/validator_ha_signer.ts +162 -0
package/README.md ADDED
@@ -0,0 +1,187 @@
1
+ # Validator HA Signer
2
+
3
+ Distributed locking and slashing protection for Aztec validators running in high-availability configurations.
4
+
5
+ ## Features
6
+
7
+ - **Distributed Locking**: Prevents multiple validator nodes from signing the same duty
8
+ - **Slashing Protection**: Blocks attempts to sign conflicting data for the same slot
9
+ - **Automatic Retry**: Failed signing attempts are cleared, allowing other nodes to retry
10
+ - **PostgreSQL Backend**: Shared database for coordination across nodes
11
+
12
+ ## Integration with Validator Client
13
+
14
+ The HA signer is automatically integrated into the validator client when `VALIDATOR_HA_SIGNING_ENABLED=true` is set. The validator client will:
15
+
16
+ 1. Create the HA signer using `createHASigner()` from the factory
17
+ 2. Wrap the base keystore with `HAKeyStore` to provide HA-protected signing
18
+ 3. Automatically start/stop the signer lifecycle
19
+
20
+ No manual integration is required when using the validator client.
21
+
22
+ ## Manual Usage
23
+
24
+ For advanced use cases or testing, you can use the HA signer directly. **Note**: Database migrations must be run separately before creating the signer (see [Database Migrations](#database-migrations) below).
25
+
26
+ ### Basic Usage
27
+
28
+ ```bash
29
+ # 1. Run migrations separately (once per deployment)
30
+ aztec migrate-ha-db up --database-url postgresql://user:pass@host:port/db
31
+ ```
32
+
33
+ ```typescript
34
+ // 2. Create signer (migrations already applied)
35
+ import { createHASigner } from '@aztec/validator-ha-signer/factory';
36
+
37
+ const { signer, db } = await createHASigner({
38
+ databaseUrl: process.env.DATABASE_URL,
39
+ haSigningEnabled: true,
40
+ nodeId: 'validator-node-1',
41
+ pollingIntervalMs: 100,
42
+ signingTimeoutMs: 3000,
43
+ });
44
+
45
+ // Start background cleanup tasks
46
+ signer.start();
47
+
48
+ // Sign with protection
49
+ const signature = await signer.signWithProtection(
50
+ validatorAddress,
51
+ messageHash,
52
+ { slot: 100n, blockNumber: 50n, blockIndexWithinCheckpoint: 0, dutyType: 'BLOCK_PROPOSAL' },
53
+ async root => localSigner.signMessage(root),
54
+ );
55
+
56
+ // On shutdown
57
+ await signer.stop();
58
+ await db.close();
59
+ ```
60
+
61
+ ### Advanced: Custom Connection Pool
62
+
63
+ If you need custom pool configuration (e.g., max connections, idle timeout) or want to share a connection pool across multiple components:
64
+
65
+ > **Note**: You still need to run migrations separately before using this approach.
66
+ > See [Database Migrations](#database-migrations) below.
67
+
68
+ ```typescript
69
+ import { PostgresSlashingProtectionDatabase } from '@aztec/validator-ha-signer/db';
70
+ import { ValidatorHASigner } from '@aztec/validator-ha-signer/validator-ha-signer';
71
+
72
+ import { Pool } from 'pg';
73
+
74
+ // Custom pool configuration
75
+ const pool = new Pool({
76
+ connectionString: process.env.DATABASE_URL,
77
+ max: 20, // Maximum connections
78
+ idleTimeoutMillis: 30000,
79
+ });
80
+ const db = new PostgresSlashingProtectionDatabase(pool);
81
+ await db.initialize();
82
+
83
+ const signer = new ValidatorHASigner(db, {
84
+ haSigningEnabled: true,
85
+ nodeId: 'validator-node-1',
86
+ pollingIntervalMs: 100,
87
+ signingTimeoutMs: 3000,
88
+ maxStuckDutiesAgeMs: 144000,
89
+ });
90
+
91
+ // Start background cleanup tasks
92
+ signer.start();
93
+
94
+ // On shutdown
95
+ await signer.stop();
96
+ await pool.end(); // You manage the pool lifecycle
97
+ ```
98
+
99
+ ## Configuration
100
+
101
+ Set via environment variables or config object:
102
+
103
+ - `VALIDATOR_HA_DATABASE_URL`: PostgreSQL connection string (e.g., `postgresql://user:pass@host:port/db`)
104
+ - `VALIDATOR_HA_SIGNING_ENABLED`: Whether HA signing / slashing protection is enabled (default: false)
105
+ - `VALIDATOR_HA_NODE_ID`: Unique identifier for this validator node (required when enabled)
106
+ - `VALIDATOR_HA_POLLING_INTERVAL_MS`: How often to check duty status (default: 100)
107
+ - `VALIDATOR_HA_SIGNING_TIMEOUT_MS`: Max wait for in-progress signing (default: 3000)
108
+ - `VALIDATOR_HA_MAX_STUCK_DUTIES_AGE_MS`: Max age of stuck duties before cleanup (default: 2 \* aztecSlotDuration)
109
+ - `VALIDATOR_HA_POOL_MAX`: Maximum number of connections in the pool (default: 10)
110
+ - `VALIDATOR_HA_POOL_MIN`: Minimum number of connections in the pool (default: 0)
111
+ - `VALIDATOR_HA_POOL_IDLE_TIMEOUT_MS`: Idle timeout for pool connections (default: 10000)
112
+ - `VALIDATOR_HA_POOL_CONNECTION_TIMEOUT_MS`: Connection timeout (default: 0, no timeout)
113
+
114
+ ## Database Migrations
115
+
116
+ This package uses `node-pg-migrate` for database schema management.
117
+
118
+ ### Migration Commands
119
+
120
+ ```bash
121
+ # Run pending migrations
122
+ aztec migrate-ha-db up --database-url postgresql://...
123
+
124
+ # Rollback last migration
125
+ aztec migrate-ha-db down --database-url postgresql://...
126
+ ```
127
+
128
+ ### Creating New Migrations
129
+
130
+ ```bash
131
+ # Generate a new migration file
132
+ npx node-pg-migrate create my-migration-name
133
+ ```
134
+
135
+ ### Production Deployment
136
+
137
+ Run migrations before starting your application:
138
+
139
+ ```yaml
140
+ # Kubernetes example
141
+ apiVersion: batch/v1
142
+ kind: Job
143
+ metadata:
144
+ name: validator-db-migrate
145
+ spec:
146
+ template:
147
+ spec:
148
+ containers:
149
+ - name: migrate
150
+ image: aztecprotocol/aztec:<image_tag>
151
+ command: ['node', '--no-warnings', '/usr/src/yarn-project/aztec/dest/bin/index.js', 'migrate-ha-db', 'up']
152
+ env:
153
+ - name: DATABASE_URL
154
+ valueFrom:
155
+ secretKeyRef:
156
+ name: db-secret
157
+ key: url
158
+ restartPolicy: OnFailure
159
+ ```
160
+
161
+ ## How It Works
162
+
163
+ When multiple validator nodes attempt to sign:
164
+
165
+ 1. First node acquires lock and signs
166
+ 2. Other nodes receive `DutyAlreadySignedError` (expected)
167
+ 3. If different data detected: `SlashingProtectionError` (prevents slashing)
168
+ 4. Failed attempts are auto-cleaned, allowing retry
169
+
170
+ ### Signing Context
171
+
172
+ All signing operations require a `SigningContext` that includes:
173
+
174
+ - `slot`: The slot number
175
+ - `blockNumber`: The block number within the checkpoint
176
+ - `blockIndexWithinCheckpoint`: The index of the block within the checkpoint (use `-1` for N/A contexts)
177
+ - `dutyType`: The type of duty (e.g., `BLOCK_PROPOSAL`, `CHECKPOINT_ATTESTATION`, `AUTH_REQUEST`)
178
+
179
+ Note: `AUTH_REQUEST` duties bypass HA protection since signing multiple times is safe for authentication requests.
180
+
181
+ ## Development
182
+
183
+ ```bash
184
+ yarn build # Build package
185
+ yarn test # Run tests
186
+ yarn clean # Clean build artifacts
187
+ ```
@@ -0,0 +1,101 @@
1
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
2
+ import { type ConfigMappingsType } from '@aztec/foundation/config';
3
+ import { EthAddress } from '@aztec/foundation/eth-address';
4
+ import { z } from 'zod';
5
+ /**
6
+ * Configuration for the Validator HA Signer
7
+ *
8
+ * This config is used for distributed locking and slashing protection
9
+ * when running multiple validator nodes in a high-availability setup.
10
+ */
11
+ export interface ValidatorHASignerConfig {
12
+ /** Whether HA signing / slashing protection is enabled */
13
+ haSigningEnabled: boolean;
14
+ /** L1 contract addresses (rollup address required) */
15
+ l1Contracts: Pick<L1ContractAddresses, 'rollupAddress'>;
16
+ /** Unique identifier for this node */
17
+ nodeId: string;
18
+ /** How long to wait between polls when a duty is being signed (ms) */
19
+ pollingIntervalMs: number;
20
+ /** Maximum time to wait for a duty being signed to complete (ms) */
21
+ signingTimeoutMs: number;
22
+ /** Maximum age of a stuck duty in ms (defaults to 2x hardcoded Aztec slot duration if not set) */
23
+ maxStuckDutiesAgeMs?: number;
24
+ /** Optional: clean up old duties after this many hours (disabled if not set) */
25
+ cleanupOldDutiesAfterHours?: number;
26
+ /**
27
+ * PostgreSQL connection string
28
+ * Format: postgresql://user:password@host:port/database
29
+ */
30
+ databaseUrl?: string;
31
+ /**
32
+ * PostgreSQL connection pool configuration
33
+ */
34
+ /** Maximum number of clients in the pool (default: 10) */
35
+ poolMaxCount?: number;
36
+ /** Minimum number of clients in the pool (default: 0) */
37
+ poolMinCount?: number;
38
+ /** Idle timeout in milliseconds (default: 10000) */
39
+ poolIdleTimeoutMs?: number;
40
+ /** Connection timeout in milliseconds (default: 0, no timeout) */
41
+ poolConnectionTimeoutMs?: number;
42
+ }
43
+ export declare const validatorHASignerConfigMappings: ConfigMappingsType<ValidatorHASignerConfig>;
44
+ export declare const defaultValidatorHASignerConfig: ValidatorHASignerConfig;
45
+ /**
46
+ * Returns the validator HA signer configuration from environment variables.
47
+ * Note: If an environment variable is not set, the default value is used.
48
+ * @returns The validator HA signer configuration.
49
+ */
50
+ export declare function getConfigEnvVars(): ValidatorHASignerConfig;
51
+ export declare const ValidatorHASignerConfigSchema: z.ZodObject<{
52
+ haSigningEnabled: z.ZodBoolean;
53
+ l1Contracts: z.ZodObject<{
54
+ rollupAddress: z.ZodType<EthAddress, z.ZodTypeDef, EthAddress>;
55
+ }, "strip", z.ZodTypeAny, {
56
+ rollupAddress: EthAddress;
57
+ }, {
58
+ rollupAddress: EthAddress;
59
+ }>;
60
+ nodeId: z.ZodString;
61
+ pollingIntervalMs: z.ZodNumber;
62
+ signingTimeoutMs: z.ZodNumber;
63
+ maxStuckDutiesAgeMs: z.ZodOptional<z.ZodNumber>;
64
+ cleanupOldDutiesAfterHours: z.ZodOptional<z.ZodNumber>;
65
+ databaseUrl: z.ZodOptional<z.ZodString>;
66
+ poolMaxCount: z.ZodOptional<z.ZodNumber>;
67
+ poolMinCount: z.ZodOptional<z.ZodNumber>;
68
+ poolIdleTimeoutMs: z.ZodOptional<z.ZodNumber>;
69
+ poolConnectionTimeoutMs: z.ZodOptional<z.ZodNumber>;
70
+ }, "strip", z.ZodTypeAny, {
71
+ haSigningEnabled: boolean;
72
+ l1Contracts: {
73
+ rollupAddress: EthAddress;
74
+ };
75
+ nodeId: string;
76
+ pollingIntervalMs: number;
77
+ signingTimeoutMs: number;
78
+ maxStuckDutiesAgeMs?: number | undefined;
79
+ cleanupOldDutiesAfterHours?: number | undefined;
80
+ databaseUrl?: string | undefined;
81
+ poolMaxCount?: number | undefined;
82
+ poolMinCount?: number | undefined;
83
+ poolIdleTimeoutMs?: number | undefined;
84
+ poolConnectionTimeoutMs?: number | undefined;
85
+ }, {
86
+ haSigningEnabled: boolean;
87
+ l1Contracts: {
88
+ rollupAddress: EthAddress;
89
+ };
90
+ nodeId: string;
91
+ pollingIntervalMs: number;
92
+ signingTimeoutMs: number;
93
+ maxStuckDutiesAgeMs?: number | undefined;
94
+ cleanupOldDutiesAfterHours?: number | undefined;
95
+ databaseUrl?: string | undefined;
96
+ poolMaxCount?: number | undefined;
97
+ poolMinCount?: number | undefined;
98
+ poolIdleTimeoutMs?: number | undefined;
99
+ poolConnectionTimeoutMs?: number | undefined;
100
+ }>;
101
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sS0FBSyxFQUFFLG1CQUFtQixFQUFFLE1BQU0sdUNBQXVDLENBQUM7QUFDakYsT0FBTyxFQUNMLEtBQUssa0JBQWtCLEVBTXhCLE1BQU0sMEJBQTBCLENBQUM7QUFDbEMsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFN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AC;AAEF,eAAO,MAAM,8BAA8B,EAAE,uBAE5C,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,uBAAuB,CAE1D;AAED,eAAO,MAAM,6BAA6B;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAeE,CAAC"}
package/dest/config.js ADDED
@@ -0,0 +1,92 @@
1
+ import { booleanConfigHelper, getConfigFromMappings, getDefaultConfig, numberConfigHelper, optionalNumberConfigHelper } from '@aztec/foundation/config';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import { z } from 'zod';
4
+ export const validatorHASignerConfigMappings = {
5
+ haSigningEnabled: {
6
+ env: 'VALIDATOR_HA_SIGNING_ENABLED',
7
+ description: 'Whether HA signing / slashing protection is enabled',
8
+ ...booleanConfigHelper(false)
9
+ },
10
+ l1Contracts: {
11
+ description: 'L1 contract addresses (rollup address required)',
12
+ nested: {
13
+ rollupAddress: {
14
+ description: 'The Ethereum address of the rollup contract (must be set programmatically)',
15
+ parseEnv: (val)=>EthAddress.fromString(val)
16
+ }
17
+ }
18
+ },
19
+ nodeId: {
20
+ env: 'VALIDATOR_HA_NODE_ID',
21
+ description: 'The unique identifier for this node',
22
+ defaultValue: ''
23
+ },
24
+ pollingIntervalMs: {
25
+ env: 'VALIDATOR_HA_POLLING_INTERVAL_MS',
26
+ description: 'The number of ms to wait between polls when a duty is being signed',
27
+ ...numberConfigHelper(100)
28
+ },
29
+ signingTimeoutMs: {
30
+ env: 'VALIDATOR_HA_SIGNING_TIMEOUT_MS',
31
+ description: 'The maximum time to wait for a duty being signed to complete',
32
+ ...numberConfigHelper(3_000)
33
+ },
34
+ maxStuckDutiesAgeMs: {
35
+ env: 'VALIDATOR_HA_MAX_STUCK_DUTIES_AGE_MS',
36
+ description: 'The maximum age of a stuck duty in ms (defaults to 2x Aztec slot duration)',
37
+ ...optionalNumberConfigHelper()
38
+ },
39
+ cleanupOldDutiesAfterHours: {
40
+ env: 'VALIDATOR_HA_OLD_DUTIES_MAX_AGE_H',
41
+ description: 'Optional: clean up old duties after this many hours (disabled if not set)',
42
+ ...optionalNumberConfigHelper()
43
+ },
44
+ databaseUrl: {
45
+ env: 'VALIDATOR_HA_DATABASE_URL',
46
+ description: 'PostgreSQL connection string for validator HA signer (format: postgresql://user:password@host:port/database)'
47
+ },
48
+ poolMaxCount: {
49
+ env: 'VALIDATOR_HA_POOL_MAX',
50
+ description: 'Maximum number of clients in the pool',
51
+ ...numberConfigHelper(10)
52
+ },
53
+ poolMinCount: {
54
+ env: 'VALIDATOR_HA_POOL_MIN',
55
+ description: 'Minimum number of clients in the pool',
56
+ ...numberConfigHelper(0)
57
+ },
58
+ poolIdleTimeoutMs: {
59
+ env: 'VALIDATOR_HA_POOL_IDLE_TIMEOUT_MS',
60
+ description: 'Idle timeout in milliseconds',
61
+ ...numberConfigHelper(10_000)
62
+ },
63
+ poolConnectionTimeoutMs: {
64
+ env: 'VALIDATOR_HA_POOL_CONNECTION_TIMEOUT_MS',
65
+ description: 'Connection timeout in milliseconds (0 means no timeout)',
66
+ ...numberConfigHelper(0)
67
+ }
68
+ };
69
+ export const defaultValidatorHASignerConfig = getDefaultConfig(validatorHASignerConfigMappings);
70
+ /**
71
+ * Returns the validator HA signer configuration from environment variables.
72
+ * Note: If an environment variable is not set, the default value is used.
73
+ * @returns The validator HA signer configuration.
74
+ */ export function getConfigEnvVars() {
75
+ return getConfigFromMappings(validatorHASignerConfigMappings);
76
+ }
77
+ export const ValidatorHASignerConfigSchema = z.object({
78
+ haSigningEnabled: z.boolean(),
79
+ l1Contracts: z.object({
80
+ rollupAddress: z.instanceof(EthAddress)
81
+ }),
82
+ nodeId: z.string(),
83
+ pollingIntervalMs: z.number().min(0),
84
+ signingTimeoutMs: z.number().min(0),
85
+ maxStuckDutiesAgeMs: z.number().min(0).optional(),
86
+ cleanupOldDutiesAfterHours: z.number().min(0).optional(),
87
+ databaseUrl: z.string().optional(),
88
+ poolMaxCount: z.number().min(0).optional(),
89
+ poolMinCount: z.number().min(0).optional(),
90
+ poolIdleTimeoutMs: z.number().min(0).optional(),
91
+ poolConnectionTimeoutMs: z.number().min(0).optional()
92
+ });
@@ -0,0 +1,4 @@
1
+ export * from './types.js';
2
+ export * from './schema.js';
3
+ export * from './postgres.js';
4
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kYi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxjQUFjLFlBQVksQ0FBQztBQUMzQixjQUFjLGFBQWEsQ0FBQztBQUM1QixjQUFjLGVBQWUsQ0FBQyJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/db/index.ts"],"names":[],"mappings":"AAAA,cAAc,YAAY,CAAC;AAC3B,cAAc,aAAa,CAAC;AAC5B,cAAc,eAAe,CAAC"}
@@ -0,0 +1,3 @@
1
+ export * from './types.js';
2
+ export * from './schema.js';
3
+ export * from './postgres.js';
@@ -0,0 +1,9 @@
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
+ export declare function up(pgm: MigrationBuilder): void;
8
+ export declare function down(pgm: MigrationBuilder): void;
9
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMV9pbml0aWFsLXNjaGVtYS5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2RiL21pZ3JhdGlvbnMvMV9pbml0aWFsLXNjaGVtYS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7OztHQUlHO0FBQ0gsT0FBTyxLQUFLLEVBQUUsZ0JBQWdCLEVBQUUsTUFBTSxpQkFBaUIsQ0FBQztBQUl4RCx3QkFBZ0IsRUFBRSxDQUFDLEdBQUcsRUFBRSxnQkFBZ0IsR0FBRyxJQUFJLENBVzlDO0FBRUQsd0JBQWdCLElBQUksQ0FBQyxHQUFHLEVBQUUsZ0JBQWdCLEdBQUcsSUFBSSxDQUdoRCJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"1_initial-schema.d.ts","sourceRoot":"","sources":["../../../src/db/migrations/1_initial-schema.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAIxD,wBAAgB,EAAE,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI,CAW9C;AAED,wBAAgB,IAAI,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI,CAGhD"}
@@ -0,0 +1,20 @@
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
+ */ import { DROP_SCHEMA_VERSION_TABLE, DROP_VALIDATOR_DUTIES_TABLE, SCHEMA_SETUP, SCHEMA_VERSION } from '../schema.js';
6
+ export function up(pgm) {
7
+ for (const statement of SCHEMA_SETUP){
8
+ pgm.sql(statement);
9
+ }
10
+ // Insert initial schema version
11
+ pgm.sql(`
12
+ INSERT INTO schema_version (version)
13
+ VALUES (${SCHEMA_VERSION})
14
+ ON CONFLICT (version) DO NOTHING;
15
+ `);
16
+ }
17
+ export function down(pgm) {
18
+ pgm.sql(DROP_VALIDATOR_DUTIES_TABLE);
19
+ pgm.sql(DROP_SCHEMA_VERSION_TABLE);
20
+ }
@@ -0,0 +1,84 @@
1
+ /**
2
+ * PostgreSQL implementation of SlashingProtectionDatabase
3
+ */
4
+ import { SlotNumber } from '@aztec/foundation/branded-types';
5
+ import { EthAddress } from '@aztec/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
+ */
59
+ private rowToRecord;
60
+ /**
61
+ * Close the database connection pool
62
+ */
63
+ close(): Promise<void>;
64
+ /**
65
+ * Cleanup own stuck duties
66
+ * @returns the number of duties cleaned up
67
+ */
68
+ cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
69
+ /**
70
+ * Cleanup duties with outdated rollup address.
71
+ * Removes all duties where the rollup address doesn't match the current one.
72
+ * Used after a rollup upgrade to clean up duties for the old rollup.
73
+ * @returns the number of duties cleaned up
74
+ */
75
+ cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number>;
76
+ /**
77
+ * Cleanup old signed duties.
78
+ * Removes only signed duties older than the specified age.
79
+ * Does not remove 'signing' duties as they may be in progress.
80
+ * @returns the number of duties cleaned up
81
+ */
82
+ cleanupOldDuties(maxAgeMs: number): Promise<number>;
83
+ }
84
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicG9zdGdyZXMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kYi9wb3N0Z3Jlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7R0FFRztBQUNILE9BQU8sRUFBZSxVQUFVLEVBQUUsTUFBTSxpQ0FBaUMsQ0FBQztBQUUxRSxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0sK0JBQStCLENBQUM7QUFJM0QsT0FBTyxLQUFLLEVBQUUsV0FBVyxFQUFFLGNBQWMsRUFBRSxNQUFNLElBQUksQ0FBQztBQUV0RCxPQUFPLEtBQUssRUFBRSwwQkFBMEIsRUFBRSxvQkFBb0IsRUFBRSxNQUFNLGFBQWEsQ0FBQztBQVVwRixPQUFPLEtBQUssRUFBRSxvQkFBb0IsRUFBVyxRQUFRL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