@aztec/validator-ha-signer 0.0.1-commit.96bb3f7 → 0.0.1-commit.9d2bcf6d

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 (46) hide show
  1. package/README.md +42 -37
  2. package/dest/config.d.ts +71 -17
  3. package/dest/config.d.ts.map +1 -1
  4. package/dest/config.js +47 -19
  5. package/dest/db/postgres.d.ts +34 -5
  6. package/dest/db/postgres.d.ts.map +1 -1
  7. package/dest/db/postgres.js +80 -20
  8. package/dest/db/schema.d.ts +19 -9
  9. package/dest/db/schema.d.ts.map +1 -1
  10. package/dest/db/schema.js +46 -18
  11. package/dest/db/types.d.ts +81 -24
  12. package/dest/db/types.d.ts.map +1 -1
  13. package/dest/db/types.js +34 -0
  14. package/dest/errors.d.ts +9 -5
  15. package/dest/errors.d.ts.map +1 -1
  16. package/dest/errors.js +7 -4
  17. package/dest/factory.d.ts +6 -14
  18. package/dest/factory.d.ts.map +1 -1
  19. package/dest/factory.js +6 -11
  20. package/dest/migrations.d.ts +1 -1
  21. package/dest/migrations.d.ts.map +1 -1
  22. package/dest/migrations.js +13 -2
  23. package/dest/slashing_protection_service.d.ts +16 -6
  24. package/dest/slashing_protection_service.d.ts.map +1 -1
  25. package/dest/slashing_protection_service.js +58 -17
  26. package/dest/test/pglite_pool.d.ts +92 -0
  27. package/dest/test/pglite_pool.d.ts.map +1 -0
  28. package/dest/test/pglite_pool.js +210 -0
  29. package/dest/types.d.ts +91 -14
  30. package/dest/types.d.ts.map +1 -1
  31. package/dest/types.js +21 -1
  32. package/dest/validator_ha_signer.d.ts +10 -13
  33. package/dest/validator_ha_signer.d.ts.map +1 -1
  34. package/dest/validator_ha_signer.js +32 -31
  35. package/package.json +9 -8
  36. package/src/config.ts +83 -50
  37. package/src/db/postgres.ts +101 -19
  38. package/src/db/schema.ts +48 -18
  39. package/src/db/types.ts +111 -22
  40. package/src/errors.ts +7 -2
  41. package/src/factory.ts +8 -13
  42. package/src/migrations.ts +17 -1
  43. package/src/slashing_protection_service.ts +94 -23
  44. package/src/test/pglite_pool.ts +256 -0
  45. package/src/types.ts +140 -19
  46. package/src/validator_ha_signer.ts +39 -41
package/README.md CHANGED
@@ -9,39 +9,21 @@ Distributed locking and slashing protection for Aztec validators running in high
9
9
  - **Automatic Retry**: Failed signing attempts are cleared, allowing other nodes to retry
10
10
  - **PostgreSQL Backend**: Shared database for coordination across nodes
11
11
 
12
- ## Quick Start
12
+ ## Integration with Validator Client
13
13
 
14
- ### Option 1: Automatic Migrations (Simplest)
14
+ The HA signer is automatically integrated into the validator client when `VALIDATOR_HA_SIGNING_ENABLED=true` is set. The validator client will:
15
15
 
16
- ```typescript
17
- import { createHASigner } from '@aztec/validator-ha-signer/factory';
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
18
19
 
19
- // Migrations run automatically on startup
20
- const { signer, db } = await createHASigner({
21
- databaseUrl: process.env.DATABASE_URL,
22
- enabled: true,
23
- nodeId: 'validator-node-1',
24
- pollingIntervalMs: 100,
25
- signingTimeoutMs: 3000,
26
- });
20
+ No manual integration is required when using the validator client.
27
21
 
28
- // Start background cleanup tasks
29
- signer.start();
22
+ ## Manual Usage
30
23
 
31
- // Sign with protection
32
- const signature = await signer.signWithProtection(
33
- validatorAddress,
34
- messageHash,
35
- { slot: 100n, blockNumber: 50n, dutyType: 'BLOCK_PROPOSAL' },
36
- async root => localSigner.signMessage(root),
37
- );
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).
38
25
 
39
- // Cleanup on shutdown
40
- await signer.stop();
41
- await db.close();
42
- ```
43
-
44
- ### Option 2: Manual Migrations (Recommended for Production)
26
+ ### Basic Usage
45
27
 
46
28
  ```bash
47
29
  # 1. Run migrations separately (once per deployment)
@@ -54,7 +36,7 @@ import { createHASigner } from '@aztec/validator-ha-signer/factory';
54
36
 
55
37
  const { signer, db } = await createHASigner({
56
38
  databaseUrl: process.env.DATABASE_URL,
57
- enabled: true,
39
+ haSigningEnabled: true,
58
40
  nodeId: 'validator-node-1',
59
41
  pollingIntervalMs: 100,
60
42
  signingTimeoutMs: 3000,
@@ -63,6 +45,14 @@ const { signer, db } = await createHASigner({
63
45
  // Start background cleanup tasks
64
46
  signer.start();
65
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
+
66
56
  // On shutdown
67
57
  await signer.stop();
68
58
  await db.close();
@@ -73,7 +63,7 @@ await db.close();
73
63
  If you need custom pool configuration (e.g., max connections, idle timeout) or want to share a connection pool across multiple components:
74
64
 
75
65
  > **Note**: You still need to run migrations separately before using this approach.
76
- > See [Option 2](#option-2-manual-migrations-recommended-for-production) above.
66
+ > See [Database Migrations](#database-migrations) below.
77
67
 
78
68
  ```typescript
79
69
  import { PostgresSlashingProtectionDatabase } from '@aztec/validator-ha-signer/db';
@@ -91,11 +81,11 @@ const db = new PostgresSlashingProtectionDatabase(pool);
91
81
  await db.initialize();
92
82
 
93
83
  const signer = new ValidatorHASigner(db, {
94
- enabled: true,
84
+ haSigningEnabled: true,
95
85
  nodeId: 'validator-node-1',
96
86
  pollingIntervalMs: 100,
97
87
  signingTimeoutMs: 3000,
98
- maxStuckDutiesAgeMs: 72000,
88
+ maxStuckDutiesAgeMs: 144000,
99
89
  });
100
90
 
101
91
  // Start background cleanup tasks
@@ -111,11 +101,15 @@ await pool.end(); // You manage the pool lifecycle
111
101
  Set via environment variables or config object:
112
102
 
113
103
  - `VALIDATOR_HA_DATABASE_URL`: PostgreSQL connection string (e.g., `postgresql://user:pass@host:port/db`)
114
- - `SLASHING_PROTECTION_ENABLED`: Whether slashing protection is enabled (default: true)
115
- - `SLASHING_PROTECTION_NODE_ID`: Unique identifier for this validator node
116
- - `SLASHING_PROTECTION_POLLING_INTERVAL_MS`: How often to check duty status (default: 100)
117
- - `SLASHING_PROTECTION_SIGNING_TIMEOUT_MS`: Max wait for in-progress signing (default: 3000)
118
- - `SLASHING_PROTECTION_MAX_STUCK_DUTIES_AGE_MS`: Max age of stuck duties before cleanup (default: 72000)
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)
119
113
 
120
114
  ## Database Migrations
121
115
 
@@ -170,9 +164,20 @@ When multiple validator nodes attempt to sign:
170
164
 
171
165
  1. First node acquires lock and signs
172
166
  2. Other nodes receive `DutyAlreadySignedError` (expected)
173
- 3. If different data detected: `SlashingProtectionError` (likely for block builder signing)
167
+ 3. If different data detected: `SlashingProtectionError` (prevents slashing)
174
168
  4. Failed attempts are auto-cleaned, allowing retry
175
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
+
176
181
  ## Development
177
182
 
178
183
  ```bash
package/dest/config.d.ts CHANGED
@@ -1,30 +1,33 @@
1
+ import type { L1ContractAddresses } from '@aztec/ethereum/l1-contract-addresses';
1
2
  import { type ConfigMappingsType } from '@aztec/foundation/config';
3
+ import { EthAddress } from '@aztec/foundation/eth-address';
4
+ import { z } from 'zod';
2
5
  /**
3
- * Configuration for the slashing protection service
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.
4
10
  */
5
- export interface SlashingProtectionConfig {
6
- /** Whether slashing protection is enabled */
7
- enabled: boolean;
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'>;
8
16
  /** Unique identifier for this node */
9
17
  nodeId: string;
10
18
  /** How long to wait between polls when a duty is being signed (ms) */
11
19
  pollingIntervalMs: number;
12
20
  /** Maximum time to wait for a duty being signed to complete (ms) */
13
21
  signingTimeoutMs: number;
14
- /** Maximum age of a stuck duty in ms */
15
- maxStuckDutiesAgeMs: number;
16
- }
17
- export declare const slashingProtectionConfigMappings: ConfigMappingsType<SlashingProtectionConfig>;
18
- export declare const defaultSlashingProtectionConfig: SlashingProtectionConfig;
19
- /**
20
- * Configuration for creating an HA signer with PostgreSQL backend
21
- */
22
- export interface CreateHASignerConfig extends SlashingProtectionConfig {
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;
23
26
  /**
24
27
  * PostgreSQL connection string
25
28
  * Format: postgresql://user:password@host:port/database
26
29
  */
27
- databaseUrl: string;
30
+ databaseUrl?: string;
28
31
  /**
29
32
  * PostgreSQL connection pool configuration
30
33
  */
@@ -37,11 +40,62 @@ export interface CreateHASignerConfig extends SlashingProtectionConfig {
37
40
  /** Connection timeout in milliseconds (default: 0, no timeout) */
38
41
  poolConnectionTimeoutMs?: number;
39
42
  }
40
- export declare const createHASignerConfigMappings: ConfigMappingsType<CreateHASignerConfig>;
43
+ export declare const validatorHASignerConfigMappings: ConfigMappingsType<ValidatorHASignerConfig>;
44
+ export declare const defaultValidatorHASignerConfig: ValidatorHASignerConfig;
41
45
  /**
42
46
  * Returns the validator HA signer configuration from environment variables.
43
47
  * Note: If an environment variable is not set, the default value is used.
44
48
  * @returns The validator HA signer configuration.
45
49
  */
46
- export declare function getConfigEnvVars(): CreateHASignerConfig;
47
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFDTCxLQUFLLGtCQUFrQixFQUt4QixNQUFNLDBCQUEwQixDQUFDO0FBRWxDOztHQUVHO0FBQ0gsTUFBTSxXQUFXLHdCQUF3QjtJQUN2Qyw2Q0FBNkM7SUFDN0MsT0FBTyxFQUFFLE9BQU8sQ0FBQztJQUNqQixzQ0FBc0M7SUFDdEMsTUFBTSxFQUFFLE1BQU0sQ0FBQztJQUNmLHNFQUFzRTtJQUN0RSxpQkFBaUIsRUFBRSxNQUFNLENBQUM7SUFDMUIsb0VBQW9FO0lBQ3BFLGdCQUFnQixFQUFFLE1BQU0sQ0FBQztJQUN6Qix3Q0FBd0M7SUFDeEMsbUJBQW1CLEVBQUUsTUFBTSxDQUFDO0NBQzdCO0FBRUQsZUFBTyxNQUFNLGdDQUFnQyxFQUFFLGtCQUFrQixDQUFDLHdCQUF3QixDQTJCekYsQ0FBQztBQUVGLGVBQU8sTUFBTSwrQkFBK0IsRUFBRSx3QkFFN0MsQ0FBQztBQUVGOztHQUVHO0FBQ0gsTUFBTSxXQUFXLG9CQUFxQixTQUFRLHdCQUF3QjtJQUNwRTs7O09BR0c7SUFDSCxXQUFXLEVBQUUsTUFBTSxDQUFDO0lBQ3BCOztPQUVHO0lBQ0gsMERBQTBEO0lBQzFELFlBQVksQ0FBQyxFQUFFLE1BQU0sQ0FBQztJQUN0Qix5REFBeUQ7SUFDekQsWUFBWSxDQUFDLEVBQUUsTUFBTSxDQUFDO0lBQ3RCLG9EQUFvRDtJQUNwRCxpQkFBaUIsQ0FBQyxFQUFFLE1BQU0sQ0FBQztJQUMzQixrRUFBa0U7SUFDbEUsdUJBQXVCLENBQUMsRUFBRSxNQUFNLENBQUM7Q0FDbEM7QUFFRCxlQUFPLE1BQU0sNEJBQTRCLEVBQUUsa0JBQWtCLENBQUMsb0JBQW9CLENBMkJqRixDQUFDO0FBRUY7Ozs7R0FJRztBQUNILHdCQUFnQixnQkFBZ0IsSUFBSSxvQkFBb0IsQ0FFdkQifQ==
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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sS0FBSyxFQUFFLG1CQUFtQixFQUFFLE1BQU0sdUNBQXVDLENBQUM7QUFDakYsT0FBTyxFQUNMLEtBQUssa0JBQWtCLEVBTXhCLE1BQU0sMEJBQTBCLENBQUM7QUFDbE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@@ -1,35 +1,46 @@
1
- import { booleanConfigHelper, getConfigFromMappings, getDefaultConfig, numberConfigHelper } from '@aztec/foundation/config';
2
- export const slashingProtectionConfigMappings = {
3
- enabled: {
4
- env: 'SLASHING_PROTECTION_ENABLED',
5
- description: 'Whether slashing protection is enabled',
6
- ...booleanConfigHelper(true)
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
+ }
7
18
  },
8
19
  nodeId: {
9
- env: 'SLASHING_PROTECTION_NODE_ID',
20
+ env: 'VALIDATOR_HA_NODE_ID',
10
21
  description: 'The unique identifier for this node',
11
22
  defaultValue: ''
12
23
  },
13
24
  pollingIntervalMs: {
14
- env: 'SLASHING_PROTECTION_POLLING_INTERVAL_MS',
25
+ env: 'VALIDATOR_HA_POLLING_INTERVAL_MS',
15
26
  description: 'The number of ms to wait between polls when a duty is being signed',
16
27
  ...numberConfigHelper(100)
17
28
  },
18
29
  signingTimeoutMs: {
19
- env: 'SLASHING_PROTECTION_SIGNING_TIMEOUT_MS',
30
+ env: 'VALIDATOR_HA_SIGNING_TIMEOUT_MS',
20
31
  description: 'The maximum time to wait for a duty being signed to complete',
21
32
  ...numberConfigHelper(3_000)
22
33
  },
23
34
  maxStuckDutiesAgeMs: {
24
- env: 'SLASHING_PROTECTION_MAX_STUCK_DUTIES_AGE_MS',
25
- description: 'The maximum age of a stuck duty in ms',
26
- // hard-coding at current 2 slot duration. This should be set by the validator on init
27
- ...numberConfigHelper(72_000)
28
- }
29
- };
30
- export const defaultSlashingProtectionConfig = getDefaultConfig(slashingProtectionConfigMappings);
31
- export const createHASignerConfigMappings = {
32
- ...slashingProtectionConfigMappings,
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
+ },
33
44
  databaseUrl: {
34
45
  env: 'VALIDATOR_HA_DATABASE_URL',
35
46
  description: 'PostgreSQL connection string for validator HA signer (format: postgresql://user:password@host:port/database)'
@@ -55,10 +66,27 @@ export const createHASignerConfigMappings = {
55
66
  ...numberConfigHelper(0)
56
67
  }
57
68
  };
69
+ export const defaultValidatorHASignerConfig = getDefaultConfig(validatorHASignerConfigMappings);
58
70
  /**
59
71
  * Returns the validator HA signer configuration from environment variables.
60
72
  * Note: If an environment variable is not set, the default value is used.
61
73
  * @returns The validator HA signer configuration.
62
74
  */ export function getConfigEnvVars() {
63
- return getConfigFromMappings(createHASignerConfigMappings);
75
+ return getConfigFromMappings(validatorHASignerConfigMappings);
64
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
+ });
@@ -1,14 +1,26 @@
1
+ /**
2
+ * PostgreSQL implementation of SlashingProtectionDatabase
3
+ */
4
+ import { SlotNumber } from '@aztec/foundation/branded-types';
1
5
  import { EthAddress } from '@aztec/foundation/eth-address';
2
- import type { Pool } from 'pg';
6
+ import type { QueryResult, QueryResultRow } from 'pg';
3
7
  import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
4
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
+ }
5
17
  /**
6
18
  * PostgreSQL implementation of the slashing protection database
7
19
  */
8
20
  export declare class PostgresSlashingProtectionDatabase implements SlashingProtectionDatabase {
9
21
  private readonly pool;
10
22
  private readonly log;
11
- constructor(pool: Pool);
23
+ constructor(pool: QueryablePool);
12
24
  /**
13
25
  * Verify that database migrations have been run and schema version matches.
14
26
  * Should be called once at startup.
@@ -21,6 +33,9 @@ export declare class PostgresSlashingProtectionDatabase implements SlashingProte
21
33
  *
22
34
  * @returns { isNew: true, record } if we successfully inserted and acquired the lock
23
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.
24
39
  */
25
40
  tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult>;
26
41
  /**
@@ -29,7 +44,7 @@ export declare class PostgresSlashingProtectionDatabase implements SlashingProte
29
44
  *
30
45
  * @returns true if the update succeeded, false if token didn't match or duty not found
31
46
  */
32
- updateDutySigned(validatorAddress: EthAddress, slot: bigint, dutyType: DutyType, signature: string, lockToken: string): Promise<boolean>;
47
+ updateDutySigned(rollupAddress: EthAddress, validatorAddress: EthAddress, slot: SlotNumber, dutyType: DutyType, signature: string, lockToken: string, blockIndexWithinCheckpoint: number): Promise<boolean>;
33
48
  /**
34
49
  * Delete a duty record.
35
50
  * Only succeeds if the lockToken matches (caller must be the one who created the duty).
@@ -37,7 +52,7 @@ export declare class PostgresSlashingProtectionDatabase implements SlashingProte
37
52
  *
38
53
  * @returns true if the delete succeeded, false if token didn't match or duty not found
39
54
  */
40
- deleteDuty(validatorAddress: EthAddress, slot: bigint, dutyType: DutyType, lockToken: string): Promise<boolean>;
55
+ deleteDuty(rollupAddress: EthAddress, validatorAddress: EthAddress, slot: SlotNumber, dutyType: DutyType, lockToken: string, blockIndexWithinCheckpoint: number): Promise<boolean>;
41
56
  /**
42
57
  * Convert a database row to a ValidatorDutyRecord
43
58
  */
@@ -51,5 +66,19 @@ export declare class PostgresSlashingProtectionDatabase implements SlashingProte
51
66
  * @returns the number of duties cleaned up
52
67
  */
53
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>;
54
83
  }
55
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicG9zdGdyZXMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kYi9wb3N0Z3Jlcy50cyJdLCJuYW1l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ztec/foundation/crypto/random';
3
+ */ import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
+ import { randomBytes } from '@aztec/foundation/crypto/random';
4
5
  import { EthAddress } from '@aztec/foundation/eth-address';
5
6
  import { createLogger } from '@aztec/foundation/log';
6
- import { CLEANUP_OWN_STUCK_DUTIES, DELETE_DUTY, INSERT_OR_GET_DUTY, SCHEMA_VERSION, UPDATE_DUTY_SIGNED } from './schema.js';
7
+ import { makeBackoff, retry } from '@aztec/foundation/retry';
8
+ 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';
9
+ import { getBlockIndexFromDutyIdentifier } from './types.js';
7
10
  /**
8
11
  * PostgreSQL implementation of the slashing protection database
9
12
  */ export class PostgresSlashingProtectionDatabase {
@@ -27,10 +30,10 @@ import { CLEANUP_OWN_STUCK_DUTIES, DELETE_DUTY, INSERT_OR_GET_DUTY, SCHEMA_VERSI
27
30
  }
28
31
  dbVersion = result.rows[0].version;
29
32
  } catch {
30
- throw new Error('Database schema not initialized. Please run migrations first: aztec migrate up --database-url <url>');
33
+ throw new Error('Database schema not initialized. Please run migrations first: aztec migrate-ha-db up --database-url <url>');
31
34
  }
32
35
  if (dbVersion < SCHEMA_VERSION) {
33
- throw new Error(`Database schema version ${dbVersion} is outdated (expected ${SCHEMA_VERSION}). Please run migrations: aztec migrate up --database-url <url>`);
36
+ throw new Error(`Database schema version ${dbVersion} is outdated (expected ${SCHEMA_VERSION}). Please run migrations: aztec migrate-ha-db up --database-url <url>`);
34
37
  }
35
38
  if (dbVersion > SCHEMA_VERSION) {
36
39
  throw new Error(`Database schema version ${dbVersion} is newer than expected (${SCHEMA_VERSION}). Please update your application.`);
@@ -44,21 +47,45 @@ import { CLEANUP_OWN_STUCK_DUTIES, DELETE_DUTY, INSERT_OR_GET_DUTY, SCHEMA_VERSI
44
47
  *
45
48
  * @returns { isNew: true, record } if we successfully inserted and acquired the lock
46
49
  * @returns { isNew: false, record } if a record already exists. lock_token is empty if the record already exists.
50
+ *
51
+ * Retries if no rows are returned, which can happen under high concurrency
52
+ * when another transaction just committed the row but it's not yet visible.
47
53
  */ async tryInsertOrGetExisting(params) {
48
54
  // create a token for ownership verification
49
55
  const lockToken = randomBytes(16).toString('hex');
50
- const result = await this.pool.query(INSERT_OR_GET_DUTY, [
51
- params.validatorAddress.toString(),
52
- params.slot.toString(),
53
- params.blockNumber.toString(),
54
- params.dutyType,
55
- params.messageHash,
56
- params.nodeId,
57
- lockToken
56
+ // Use fast retries with custom backoff: 10ms, 20ms, 30ms (then stop)
57
+ const fastBackoff = makeBackoff([
58
+ 0.01,
59
+ 0.02,
60
+ 0.03
58
61
  ]);
62
+ // Get the normalized block index using type-safe helper
63
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
64
+ const result = await retry(async ()=>{
65
+ const queryResult = await this.pool.query(INSERT_OR_GET_DUTY, [
66
+ params.rollupAddress.toString(),
67
+ params.validatorAddress.toString(),
68
+ params.slot.toString(),
69
+ params.blockNumber.toString(),
70
+ blockIndexWithinCheckpoint,
71
+ params.dutyType,
72
+ params.messageHash,
73
+ params.nodeId,
74
+ lockToken
75
+ ]);
76
+ // Throw error if no rows to trigger retry
77
+ if (queryResult.rows.length === 0) {
78
+ throw new Error('INSERT_OR_GET_DUTY returned no rows');
79
+ }
80
+ return queryResult;
81
+ }, `INSERT_OR_GET_DUTY for node ${params.nodeId}`, fastBackoff, this.log, true);
59
82
  if (result.rows.length === 0) {
60
- // This shouldn't happen - the query always returns either the inserted or existing row
61
- throw new Error('INSERT_OR_GET_DUTY returned no rows');
83
+ // this should never happen as the retry function should throw if it still fails after retries
84
+ throw new Error('INSERT_OR_GET_DUTY returned no rows after retries');
85
+ }
86
+ if (result.rows.length > 1) {
87
+ // this should never happen if database constraints are correct (PRIMARY KEY should prevent duplicates)
88
+ throw new Error(`INSERT_OR_GET_DUTY returned ${result.rows.length} rows (expected exactly 1).`);
62
89
  }
63
90
  const row = result.rows[0];
64
91
  return {
@@ -71,19 +98,23 @@ import { CLEANUP_OWN_STUCK_DUTIES, DELETE_DUTY, INSERT_OR_GET_DUTY, SCHEMA_VERSI
71
98
  * Only succeeds if the lockToken matches (caller must be the one who created the duty).
72
99
  *
73
100
  * @returns true if the update succeeded, false if token didn't match or duty not found
74
- */ async updateDutySigned(validatorAddress, slot, dutyType, signature, lockToken) {
101
+ */ async updateDutySigned(rollupAddress, validatorAddress, slot, dutyType, signature, lockToken, blockIndexWithinCheckpoint) {
75
102
  const result = await this.pool.query(UPDATE_DUTY_SIGNED, [
76
103
  signature,
104
+ rollupAddress.toString(),
77
105
  validatorAddress.toString(),
78
106
  slot.toString(),
79
107
  dutyType,
108
+ blockIndexWithinCheckpoint,
80
109
  lockToken
81
110
  ]);
82
111
  if (result.rowCount === 0) {
83
112
  this.log.warn('Failed to update duty to signed status: invalid token or duty not found', {
113
+ rollupAddress: rollupAddress.toString(),
84
114
  validatorAddress: validatorAddress.toString(),
85
115
  slot: slot.toString(),
86
- dutyType
116
+ dutyType,
117
+ blockIndexWithinCheckpoint
87
118
  });
88
119
  return false;
89
120
  }
@@ -95,18 +126,22 @@ import { CLEANUP_OWN_STUCK_DUTIES, DELETE_DUTY, INSERT_OR_GET_DUTY, SCHEMA_VERSI
95
126
  * Used when signing fails to allow another node/attempt to retry.
96
127
  *
97
128
  * @returns true if the delete succeeded, false if token didn't match or duty not found
98
- */ async deleteDuty(validatorAddress, slot, dutyType, lockToken) {
129
+ */ async deleteDuty(rollupAddress, validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint) {
99
130
  const result = await this.pool.query(DELETE_DUTY, [
131
+ rollupAddress.toString(),
100
132
  validatorAddress.toString(),
101
133
  slot.toString(),
102
134
  dutyType,
135
+ blockIndexWithinCheckpoint,
103
136
  lockToken
104
137
  ]);
105
138
  if (result.rowCount === 0) {
106
139
  this.log.warn('Failed to delete duty: invalid token or duty not found', {
140
+ rollupAddress: rollupAddress.toString(),
107
141
  validatorAddress: validatorAddress.toString(),
108
142
  slot: slot.toString(),
109
- dutyType
143
+ dutyType,
144
+ blockIndexWithinCheckpoint
110
145
  });
111
146
  return false;
112
147
  }
@@ -116,9 +151,11 @@ import { CLEANUP_OWN_STUCK_DUTIES, DELETE_DUTY, INSERT_OR_GET_DUTY, SCHEMA_VERSI
116
151
  * Convert a database row to a ValidatorDutyRecord
117
152
  */ rowToRecord(row) {
118
153
  return {
154
+ rollupAddress: EthAddress.fromString(row.rollup_address),
119
155
  validatorAddress: EthAddress.fromString(row.validator_address),
120
- slot: BigInt(row.slot),
121
- blockNumber: BigInt(row.block_number),
156
+ slot: SlotNumber.fromString(row.slot),
157
+ blockNumber: BlockNumber.fromString(row.block_number),
158
+ blockIndexWithinCheckpoint: row.block_index_within_checkpoint,
122
159
  dutyType: row.duty_type,
123
160
  status: row.status,
124
161
  messageHash: row.message_hash,
@@ -147,4 +184,27 @@ import { CLEANUP_OWN_STUCK_DUTIES, DELETE_DUTY, INSERT_OR_GET_DUTY, SCHEMA_VERSI
147
184
  ]);
148
185
  return result.rowCount ?? 0;
149
186
  }
187
+ /**
188
+ * Cleanup duties with outdated rollup address.
189
+ * Removes all duties where the rollup address doesn't match the current one.
190
+ * Used after a rollup upgrade to clean up duties for the old rollup.
191
+ * @returns the number of duties cleaned up
192
+ */ async cleanupOutdatedRollupDuties(currentRollupAddress) {
193
+ const result = await this.pool.query(CLEANUP_OUTDATED_ROLLUP_DUTIES, [
194
+ currentRollupAddress.toString()
195
+ ]);
196
+ return result.rowCount ?? 0;
197
+ }
198
+ /**
199
+ * Cleanup old signed duties.
200
+ * Removes only signed duties older than the specified age.
201
+ * Does not remove 'signing' duties as they may be in progress.
202
+ * @returns the number of duties cleaned up
203
+ */ async cleanupOldDuties(maxAgeMs) {
204
+ const cutoff = new Date(Date.now() - maxAgeMs);
205
+ const result = await this.pool.query(CLEANUP_OLD_DUTIES, [
206
+ cutoff
207
+ ]);
208
+ return result.rowCount ?? 0;
209
+ }
150
210
  }