@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
package/README.md ADDED
@@ -0,0 +1,195 @@
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-labs/validator-ha-signer/factory';
36
+
37
+ const { signer, db } = await createHASigner({
38
+ databaseUrl: process.env.DATABASE_URL,
39
+ nodeId: 'validator-node-1',
40
+ pollingIntervalMs: 100,
41
+ peerSigningTimeoutMs: 3000,
42
+ });
43
+
44
+ // Start background cleanup tasks
45
+ signer.start();
46
+
47
+ // Sign with protection
48
+ const signature = await signer.signWithProtection(
49
+ validatorAddress,
50
+ messageHash,
51
+ { slot: 100n, blockNumber: 50n, blockIndexWithinCheckpoint: 0, dutyType: 'BLOCK_PROPOSAL' },
52
+ async root => localSigner.signMessage(root),
53
+ );
54
+
55
+ // On shutdown
56
+ await signer.stop();
57
+ await db.close();
58
+ ```
59
+
60
+ ### Advanced: Custom Connection Pool
61
+
62
+ If you need custom pool configuration (e.g., max connections, idle timeout) or want to share a connection pool across multiple components:
63
+
64
+ > **Note**: You still need to run migrations separately before using this approach.
65
+ > See [Database Migrations](#database-migrations) below.
66
+
67
+ ```typescript
68
+ import { PostgresSlashingProtectionDatabase } from '@aztec-labs/validator-ha-signer/db';
69
+ import { ValidatorHASigner } from '@aztec-labs/validator-ha-signer/validator-ha-signer';
70
+
71
+ import { Pool } from 'pg';
72
+
73
+ // Custom pool configuration
74
+ const pool = new Pool({
75
+ connectionString: process.env.DATABASE_URL,
76
+ max: 20, // Maximum connections
77
+ idleTimeoutMillis: 30000,
78
+ });
79
+ const db = new PostgresSlashingProtectionDatabase(pool);
80
+ await db.initialize();
81
+
82
+ const signer = new ValidatorHASigner(db, {
83
+ nodeId: 'validator-node-1',
84
+ pollingIntervalMs: 100,
85
+ peerSigningTimeoutMs: 3000,
86
+ maxStuckDutiesAgeMs: 144000,
87
+ });
88
+
89
+ // Start background cleanup tasks
90
+ signer.start();
91
+
92
+ // On shutdown
93
+ await signer.stop();
94
+ await pool.end(); // You manage the pool lifecycle
95
+ ```
96
+
97
+ ## Configuration
98
+
99
+ Set via environment variables or config object:
100
+
101
+ - `VALIDATOR_HA_DATABASE_URL`: PostgreSQL connection string (e.g., `postgresql://user:pass@host:port/db`)
102
+ - `VALIDATOR_HA_SIGNING_ENABLED`: Whether HA signing / slashing protection is enabled (default: false)
103
+ - `VALIDATOR_HA_NODE_ID`: Unique identifier for this validator node (required when enabled)
104
+ - `VALIDATOR_HA_POLLING_INTERVAL_MS`: How often to check duty status (default: 100)
105
+ - `VALIDATOR_HA_SIGNING_TIMEOUT_MS`: Max wait for in-progress signing (default: 3000)
106
+ - `VALIDATOR_HA_MAX_STUCK_DUTIES_AGE_MS`: Max age of stuck duties before cleanup (default: 2 \* aztecSlotDuration)
107
+ - `VALIDATOR_HA_POOL_MAX`: Maximum number of connections in the pool (default: 10)
108
+ - `VALIDATOR_HA_POOL_MIN`: Minimum number of connections in the pool (default: 0)
109
+ - `VALIDATOR_HA_POOL_IDLE_TIMEOUT_MS`: Idle timeout for pool connections (default: 10000)
110
+ - `VALIDATOR_HA_POOL_CONNECTION_TIMEOUT_MS`: Connection timeout (default: 0, no timeout)
111
+
112
+ ## Database Migrations
113
+
114
+ This package uses `node-pg-migrate` for database schema management.
115
+
116
+ ### Migration Commands
117
+
118
+ ```bash
119
+ # Run pending migrations
120
+ aztec migrate-ha-db up --database-url postgresql://...
121
+
122
+ # Rollback last migration
123
+ aztec migrate-ha-db down --database-url postgresql://...
124
+ ```
125
+
126
+ ### Creating New Migrations
127
+
128
+ ```bash
129
+ # Generate a new migration file
130
+ npx node-pg-migrate create my-migration-name
131
+ ```
132
+
133
+ ### Production Deployment
134
+
135
+ Run migrations before starting your application:
136
+
137
+ ```yaml
138
+ # Kubernetes example
139
+ apiVersion: batch/v1
140
+ kind: Job
141
+ metadata:
142
+ name: validator-db-migrate
143
+ spec:
144
+ template:
145
+ spec:
146
+ containers:
147
+ - name: migrate
148
+ image: azteclabs/aztec:<image_tag>
149
+ command: ['node', '--no-warnings', '/usr/src/yarn-project/aztec/dest/bin/index.js', 'migrate-ha-db', 'up']
150
+ env:
151
+ - name: DATABASE_URL
152
+ valueFrom:
153
+ secretKeyRef:
154
+ name: db-secret
155
+ key: url
156
+ restartPolicy: OnFailure
157
+ ```
158
+
159
+ ## How It Works
160
+
161
+ When multiple validator nodes attempt to sign:
162
+
163
+ 1. First node acquires lock and signs
164
+ 2. Other nodes receive `DutyAlreadySignedError` (expected)
165
+ 3. If different data detected: `SlashingProtectionError` (prevents slashing)
166
+ 4. Failed attempts are auto-cleaned, allowing retry
167
+
168
+ ### Signing Context
169
+
170
+ All signing operations require a `SigningContext` that includes:
171
+
172
+ - `slot`: The slot number
173
+ - `blockNumber`: The block number within the checkpoint
174
+ - `blockIndexWithinCheckpoint`: The index of the block within the checkpoint (use `-1` for N/A contexts)
175
+ - `dutyType`: The type of duty (e.g., `BLOCK_PROPOSAL`, `CHECKPOINT_ATTESTATION`, `AUTH_REQUEST`)
176
+
177
+ Note: `AUTH_REQUEST` duties bypass HA protection since signing multiple times is safe for authentication requests.
178
+
179
+ ## Important Limitations
180
+
181
+ ### Database Isolation Per Rollup Version
182
+
183
+ **You cannot use the same database to provide slashing protection for validator nodes running on different rollup versions** (e.g., current rollup and old rollup simultaneously).
184
+
185
+ When the HA signer performs background cleanup via `cleanupOutdatedRollupDuties()`, it removes all duties where the rollup address doesn't match the current rollup address. If two validators running on different rollup versions share the same database, they will delete each other's duties during cleanup.
186
+
187
+ **Solution**: Use separate databases for validators running on different rollup versions. Each rollup version requires its own isolated slashing protection database.
188
+
189
+ ## Development
190
+
191
+ ```bash
192
+ yarn build # Build package
193
+ yarn test # Run tests
194
+ yarn clean # Clean build artifacts
195
+ ```
@@ -0,0 +1,5 @@
1
+ export * from './types.js';
2
+ export * from './schema.js';
3
+ export * from './postgres.js';
4
+ export * from './lmdb.js';
5
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kYi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxjQUFjLFlBQVksQ0FBQztBQUMzQixjQUFjLGFBQWEsQ0FBQztBQUM1QixjQUFjLGVBQWUsQ0FBQztBQUM5QixjQUFjLFdBQVcsQ0FBQyJ9
@@ -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;AAC9B,cAAc,WAAW,CAAC"}
@@ -0,0 +1,4 @@
1
+ export * from './types.js';
2
+ export * from './schema.js';
3
+ export * from './postgres.js';
4
+ export * from './lmdb.js';
@@ -0,0 +1,70 @@
1
+ /**
2
+ * LMDB implementation of SlashingProtectionDatabase
3
+ *
4
+ * Provides local (single-node) double-signing protection using LMDB as the backend.
5
+ * Suitable for nodes that do NOT run in a high-availability multi-node setup.
6
+ *
7
+ * The LMDB store is single-writer, making setIfNotExists inherently atomic.
8
+ * This means we get crash-restart protection without needing an external database.
9
+ */
10
+ import { SlotNumber } from '@aztec-labs/foundation/branded-types';
11
+ import { EthAddress } from '@aztec-labs/foundation/eth-address';
12
+ import type { DateProvider } from '@aztec-labs/foundation/timer';
13
+ import type { AztecAsyncKVStore } from '@aztec-labs/kv-store';
14
+ import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
15
+ import { type CheckAndRecordParams, DutyType } from './types.js';
16
+ /**
17
+ * Migrates local slashing-protection duties from schema 1 to schema 2.
18
+ */
19
+ export declare function migrateLmdbSlashingProtectionDatabase(dataDirectory: string, currentVersion: number, latestVersion: number, dbMapSizeKb?: number): Promise<void>;
20
+ /**
21
+ * LMDB-backed implementation of SlashingProtectionDatabase.
22
+ *
23
+ * Provides single-node double-signing protection that survives crashes and restarts.
24
+ * Does not provide cross-node coordination (that requires the PostgreSQL implementation).
25
+ */
26
+ export declare class LmdbSlashingProtectionDatabase implements SlashingProtectionDatabase {
27
+ private readonly store;
28
+ private readonly dateProvider;
29
+ static readonly SCHEMA_VERSION = 2;
30
+ private readonly duties;
31
+ private readonly log;
32
+ constructor(store: AztecAsyncKVStore, dateProvider: DateProvider);
33
+ /**
34
+ * Atomically try to insert a new duty record, or get the existing one if present.
35
+ *
36
+ * LMDB is single-writer so the read-then-write inside transactionAsync is naturally atomic.
37
+ */
38
+ tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult>;
39
+ /**
40
+ * Update a duty to 'signed' status with the signature.
41
+ * Only succeeds if the lockToken matches.
42
+ */
43
+ updateDutySigned(rollupAddress: EthAddress, validatorAddress: EthAddress, slot: SlotNumber, dutyType: DutyType, signature: string, lockToken: string, blockIndexWithinCheckpoint: number): Promise<boolean>;
44
+ /**
45
+ * Delete a duty record.
46
+ * Only succeeds if the lockToken matches.
47
+ */
48
+ deleteDuty(rollupAddress: EthAddress, validatorAddress: EthAddress, slot: SlotNumber, dutyType: DutyType, lockToken: string, blockIndexWithinCheckpoint: number): Promise<boolean>;
49
+ /**
50
+ * Cleanup own stuck duties (SIGNING status older than maxAgeMs).
51
+ */
52
+ cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
53
+ /**
54
+ * Cleanup duties with outdated rollup address.
55
+ *
56
+ * This is always a no-op for the LMDB implementation: the underlying store is created via
57
+ * DatabaseVersionManager (in factory.ts), which already resets the entire data directory at
58
+ * startup whenever the rollup address changes.
59
+ */
60
+ cleanupOutdatedRollupDuties(_currentRollupAddress: EthAddress): Promise<number>;
61
+ /**
62
+ * Cleanup old signed duties older than maxAgeMs.
63
+ */
64
+ cleanupOldDuties(maxAgeMs: number): Promise<number>;
65
+ /**
66
+ * Close the underlying LMDB store.
67
+ */
68
+ close(): Promise<void>;
69
+ }
70
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG1kYi5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2RiL2xtZGIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7O0dBUUc7QUFDSCxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0sc0NBQXNDLENBQUM7QUFFbEUsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLG9DQUFvQyxDQUFDO0FBRWhFLE9BQU8sS0FBSyxFQUFFLFlBQVksRUFBRSxNQUFNLDhCQUE4QixDQUFDO0FBQ2pFLE9BQU8sS0FBSyxFQUFFLGlCQUFpQixFQUFpQixNQUFNLHNCQUFzQixDQUFDO0FBRzdFLE9BQU8sS0FBSyxFQUFFLDBCQUEwQixFQUFFLG9CQUFvQixFQUFFLE1BQU0sYUFBYSxDQUFDO0FBQ3BGLE9BQU8sRUFDTCxLQUFLLG9CQUFvQixFQUV6QixRQUFRLEVBSVQsTUFBTSxZQUFZLENBQUM7QUFZcEI7O0dBRUc7QUFDSCx3QkFBc0IscUNBQXFDLENBQ3pELGFBQWEsRUFBRSxNQUFNLEVBQ3JCLGNBQWMsRUFBRSxNQUFNLEVBQ3RCLGFBQWEsRUFBRSxNQUFNLEVBQ3JCLFdBQVcsQ0FBQyxFQUFFLE1BQU0sR0FDbkIsT0FBTyxDQUFDLElBQUksQ0FBQyxDQXNCZjtBQVlEOzs7OztHQUtHO0FBQ0gscUJBQWEsOEJBQStCLFlBQVcsMEJBQTBCO0lBTzdFLE9BQU8sQ0FBQyxRQUFR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BAAiB,EACxB,YAAY,EAAE,YAAY,EAI5C;IAED;;;;OAIG;IACU,sBAAsB,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CA6C/F;IAED;;;OAGG;IACI,gBAAgB,CACrB,aAAa,EAAE,UAAU,EACzB,gBAAgB,EAAE,UAAU,EAC5B,IAAI,EAAE,UAAU,EAChB,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,EACjB,0BAA0B,EAAE,MAAM,GACjC,OAAO,CAAC,OAAO,CAAC,CA0ClB;IAED;;;OAGG;IACI,UAAU,CACf,aAAa,EAAE,UAAU,EACzB,gBAAgB,EAAE,UAAU,EAC5B,IAAI,EAAE,UAAU,EAChB,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,EACjB,0BAA0B,EAAE,MAAM,GACjC,OAAO,CAAC,OAAO,CAAC,CAyBlB;IAED;;OAEG;IACI,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAe9E;IAED;;;;;;OAMG;IACI,2BAA2B,CAAC,qBAAqB,EAAE,UAAU,GAAG,OAAO,CAAC,MAAM,CAAC,CAErF;IAED;;OAEG;IACI,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAmBzD;IAED;;OAEG;IACU,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAGlC;CACF"}
@@ -0,0 +1,223 @@
1
+ /**
2
+ * LMDB implementation of SlashingProtectionDatabase
3
+ *
4
+ * Provides local (single-node) double-signing protection using LMDB as the backend.
5
+ * Suitable for nodes that do NOT run in a high-availability multi-node setup.
6
+ *
7
+ * The LMDB store is single-writer, making setIfNotExists inherently atomic.
8
+ * This means we get crash-restart protection without needing an external database.
9
+ */ import { randomBytes } from '@aztec-labs/foundation/crypto/random';
10
+ import { createLogger } from '@aztec-labs/foundation/log';
11
+ import { openStoreAt } from '@aztec-labs/kv-store/lmdb-v2';
12
+ import { DutyStatus, getBlockIndexFromDutyIdentifier, recordFromFields } from './types.js';
13
+ const DUTIES_MAP_NAME = 'signing-protection-duties';
14
+ const LEGACY_CHECKPOINT_NUMBER = '0';
15
+ function needsCheckpointNumberMigration(record) {
16
+ return record.checkpointNumber === undefined;
17
+ }
18
+ /**
19
+ * Migrates local slashing-protection duties from schema 1 to schema 2.
20
+ */ export async function migrateLmdbSlashingProtectionDatabase(dataDirectory, currentVersion, latestVersion, dbMapSizeKb) {
21
+ if (currentVersion !== 1 || latestVersion !== LmdbSlashingProtectionDatabase.SCHEMA_VERSION) {
22
+ throw new Error(`Unsupported LMDB slashing-protection migration ${currentVersion} -> ${latestVersion}`);
23
+ }
24
+ const store = await openStoreAt(dataDirectory, dbMapSizeKb);
25
+ try {
26
+ const duties = store.openMap(DUTIES_MAP_NAME);
27
+ const migratedRecords = [];
28
+ for await (const [key, record] of duties.entriesAsync()){
29
+ if (needsCheckpointNumberMigration(record)) {
30
+ migratedRecords.push({
31
+ key,
32
+ value: {
33
+ ...record,
34
+ checkpointNumber: LEGACY_CHECKPOINT_NUMBER
35
+ }
36
+ });
37
+ }
38
+ }
39
+ if (migratedRecords.length > 0) {
40
+ await duties.setMany(migratedRecords);
41
+ }
42
+ } finally{
43
+ await store.close();
44
+ }
45
+ }
46
+ function dutyKey(rollupAddress, validatorAddress, slot, dutyType, blockIndexWithinCheckpoint) {
47
+ return `${rollupAddress}:${validatorAddress}:${slot}:${dutyType}:${blockIndexWithinCheckpoint}`;
48
+ }
49
+ /**
50
+ * LMDB-backed implementation of SlashingProtectionDatabase.
51
+ *
52
+ * Provides single-node double-signing protection that survives crashes and restarts.
53
+ * Does not provide cross-node coordination (that requires the PostgreSQL implementation).
54
+ */ export class LmdbSlashingProtectionDatabase {
55
+ store;
56
+ dateProvider;
57
+ static SCHEMA_VERSION = 2;
58
+ duties;
59
+ log;
60
+ constructor(store, dateProvider){
61
+ this.store = store;
62
+ this.dateProvider = dateProvider;
63
+ this.log = createLogger('slashing-protection:lmdb');
64
+ this.duties = store.openMap(DUTIES_MAP_NAME);
65
+ }
66
+ /**
67
+ * Atomically try to insert a new duty record, or get the existing one if present.
68
+ *
69
+ * LMDB is single-writer so the read-then-write inside transactionAsync is naturally atomic.
70
+ */ async tryInsertOrGetExisting(params) {
71
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
72
+ const key = dutyKey(params.rollupAddress.toString(), params.validatorAddress.toString(), params.slot.toString(), params.dutyType, blockIndexWithinCheckpoint);
73
+ const lockToken = randomBytes(16).toString('hex');
74
+ const now = this.dateProvider.now();
75
+ const result = await this.store.transactionAsync(async ()=>{
76
+ const existing = await this.duties.getAsync(key);
77
+ if (existing) {
78
+ return {
79
+ isNew: false,
80
+ record: {
81
+ ...existing,
82
+ lockToken: ''
83
+ }
84
+ };
85
+ }
86
+ const newRecord = {
87
+ rollupAddress: params.rollupAddress.toString(),
88
+ validatorAddress: params.validatorAddress.toString(),
89
+ slot: params.slot.toString(),
90
+ blockNumber: params.blockNumber.toString(),
91
+ checkpointNumber: params.checkpointNumber.toString(),
92
+ blockIndexWithinCheckpoint,
93
+ dutyType: params.dutyType,
94
+ status: DutyStatus.SIGNING,
95
+ messageHash: params.messageHash,
96
+ nodeId: params.nodeId,
97
+ lockToken,
98
+ startedAtMs: now
99
+ };
100
+ await this.duties.set(key, newRecord);
101
+ return {
102
+ isNew: true,
103
+ record: newRecord
104
+ };
105
+ });
106
+ if (result.isNew) {
107
+ this.log.debug(`Acquired lock for duty ${params.dutyType} at slot ${params.slot}`, {
108
+ validatorAddress: params.validatorAddress.toString(),
109
+ nodeId: params.nodeId
110
+ });
111
+ }
112
+ return {
113
+ isNew: result.isNew,
114
+ record: recordFromFields(result.record)
115
+ };
116
+ }
117
+ /**
118
+ * Update a duty to 'signed' status with the signature.
119
+ * Only succeeds if the lockToken matches.
120
+ */ updateDutySigned(rollupAddress, validatorAddress, slot, dutyType, signature, lockToken, blockIndexWithinCheckpoint) {
121
+ const key = dutyKey(rollupAddress.toString(), validatorAddress.toString(), slot.toString(), dutyType, blockIndexWithinCheckpoint);
122
+ return this.store.transactionAsync(async ()=>{
123
+ const existing = await this.duties.getAsync(key);
124
+ if (!existing) {
125
+ this.log.warn('Failed to update duty to signed: duty not found', {
126
+ rollupAddress: rollupAddress.toString(),
127
+ validatorAddress: validatorAddress.toString(),
128
+ slot: slot.toString(),
129
+ dutyType,
130
+ blockIndexWithinCheckpoint
131
+ });
132
+ return false;
133
+ }
134
+ if (existing.lockToken !== lockToken) {
135
+ this.log.warn('Failed to update duty to signed: invalid token', {
136
+ rollupAddress: rollupAddress.toString(),
137
+ validatorAddress: validatorAddress.toString(),
138
+ slot: slot.toString(),
139
+ dutyType,
140
+ blockIndexWithinCheckpoint
141
+ });
142
+ return false;
143
+ }
144
+ await this.duties.set(key, {
145
+ ...existing,
146
+ status: DutyStatus.SIGNED,
147
+ signature,
148
+ completedAtMs: this.dateProvider.now()
149
+ });
150
+ return true;
151
+ });
152
+ }
153
+ /**
154
+ * Delete a duty record.
155
+ * Only succeeds if the lockToken matches.
156
+ */ deleteDuty(rollupAddress, validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint) {
157
+ const key = dutyKey(rollupAddress.toString(), validatorAddress.toString(), slot.toString(), dutyType, blockIndexWithinCheckpoint);
158
+ return this.store.transactionAsync(async ()=>{
159
+ const existing = await this.duties.getAsync(key);
160
+ if (!existing || existing.lockToken !== lockToken) {
161
+ this.log.warn('Failed to delete duty: invalid token or duty not found', {
162
+ rollupAddress: rollupAddress.toString(),
163
+ validatorAddress: validatorAddress.toString(),
164
+ slot: slot.toString(),
165
+ dutyType,
166
+ blockIndexWithinCheckpoint
167
+ });
168
+ return false;
169
+ }
170
+ await this.duties.delete(key);
171
+ return true;
172
+ });
173
+ }
174
+ /**
175
+ * Cleanup own stuck duties (SIGNING status older than maxAgeMs).
176
+ */ cleanupOwnStuckDuties(nodeId, maxAgeMs) {
177
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
178
+ return this.store.transactionAsync(async ()=>{
179
+ const keysToDelete = [];
180
+ for await (const [key, record] of this.duties.entriesAsync()){
181
+ if (record.nodeId === nodeId && record.status === DutyStatus.SIGNING && record.startedAtMs < cutoffMs) {
182
+ keysToDelete.push(key);
183
+ }
184
+ }
185
+ for (const key of keysToDelete){
186
+ await this.duties.delete(key);
187
+ }
188
+ return keysToDelete.length;
189
+ });
190
+ }
191
+ /**
192
+ * Cleanup duties with outdated rollup address.
193
+ *
194
+ * This is always a no-op for the LMDB implementation: the underlying store is created via
195
+ * DatabaseVersionManager (in factory.ts), which already resets the entire data directory at
196
+ * startup whenever the rollup address changes.
197
+ */ cleanupOutdatedRollupDuties(_currentRollupAddress) {
198
+ return Promise.resolve(0);
199
+ }
200
+ /**
201
+ * Cleanup old signed duties older than maxAgeMs.
202
+ */ cleanupOldDuties(maxAgeMs) {
203
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
204
+ return this.store.transactionAsync(async ()=>{
205
+ const keysToDelete = [];
206
+ for await (const [key, record] of this.duties.entriesAsync()){
207
+ if (record.status === DutyStatus.SIGNED && record.completedAtMs !== undefined && record.completedAtMs < cutoffMs) {
208
+ keysToDelete.push(key);
209
+ }
210
+ }
211
+ for (const key of keysToDelete){
212
+ await this.duties.delete(key);
213
+ }
214
+ return keysToDelete.length;
215
+ });
216
+ }
217
+ /**
218
+ * Close the underlying LMDB store.
219
+ */ async close() {
220
+ await this.store.close();
221
+ this.log.debug('LMDB slashing protection database closed');
222
+ }
223
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Initial schema for validator HA slashing protection
3
+ *
4
+ * Note: this migration contains a fixed snapshot of the schema at the time it was created.
5
+ * It must NOT import from schema.ts, which evolves over time and would cause this migration
6
+ * to produce different results on fresh runs vs. re-runs.
7
+ */
8
+ import type { MigrationBuilder } from 'node-pg-migrate';
9
+ export declare function up(pgm: MigrationBuilder): void;
10
+ export declare function down(pgm: MigrationBuilder): void;
11
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMV9pbml0aWFsLXNjaGVtYS5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vc3JjL2RiL21pZ3JhdGlvbnMvMV9pbml0aWFsLXNjaGVtYS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQTs7Ozs7O0dBTUc7QUFDSCxPQUFPLEtBQUssRUFBRSxnQkFBZ0IsRUFBRSxNQUFNLGlCQUFpQixDQUFDO0FBaUN4RCx3QkFBZ0IsRUFBRSxDQUFDLEdBQUcsRUFBRSxnQkFBZ0IsR0FBRyxJQUFJLENBVzlDO0FBRUQsd0JBQWdCLElBQUksQ0FBQyxHQUFHLEVBQUUsZ0JBQWdCLEdBQUcsSUFBSSxDQUdoRCJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"1_initial-schema.d.ts","sourceRoot":"","sources":["../../../src/db/migrations/1_initial-schema.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAiCxD,wBAAgB,EAAE,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI,CAW9C;AAED,wBAAgB,IAAI,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI,CAGhD"}
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Initial schema for validator HA slashing protection
3
+ *
4
+ * Note: this migration contains a fixed snapshot of the schema at the time it was created.
5
+ * It must NOT import from schema.ts, which evolves over time and would cause this migration
6
+ * to produce different results on fresh runs vs. re-runs.
7
+ */ import { DROP_SCHEMA_VERSION_TABLE, DROP_VALIDATOR_DUTIES_TABLE } from '../schema.js';
8
+ // Snapshot of the initial schema — does NOT include checkpoint_number (added in migration 2).
9
+ const INITIAL_SCHEMA_SETUP = [
10
+ `CREATE TABLE IF NOT EXISTS schema_version (
11
+ version INTEGER PRIMARY KEY,
12
+ applied_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
13
+ );`,
14
+ `CREATE TABLE IF NOT EXISTS validator_duties (
15
+ rollup_address VARCHAR(42) NOT NULL,
16
+ validator_address VARCHAR(42) NOT NULL,
17
+ slot BIGINT NOT NULL,
18
+ block_number BIGINT NOT NULL,
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
+ `CREATE INDEX IF NOT EXISTS idx_validator_duties_status ON validator_duties(status, started_at);`,
34
+ `CREATE INDEX IF NOT EXISTS idx_validator_duties_node ON validator_duties(node_id, started_at);`
35
+ ];
36
+ export function up(pgm) {
37
+ for (const statement of INITIAL_SCHEMA_SETUP){
38
+ pgm.sql(statement);
39
+ }
40
+ // Insert initial schema version
41
+ pgm.sql(`
42
+ INSERT INTO schema_version (version)
43
+ VALUES (1)
44
+ ON CONFLICT (version) DO NOTHING;
45
+ `);
46
+ }
47
+ export function down(pgm) {
48
+ pgm.sql(DROP_VALIDATOR_DUTIES_TABLE);
49
+ pgm.sql(DROP_SCHEMA_VERSION_TABLE);
50
+ }
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Add checkpoint_number column to validator_duties table
3
+ */
4
+ import type { MigrationBuilder } from 'node-pg-migrate';
5
+ export declare function up(pgm: MigrationBuilder): void;
6
+ export declare function down(pgm: MigrationBuilder): void;
7
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMl9hZGQtY2hlY2twb2ludC1udW1iZXIuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uL3NyYy9kYi9taWdyYXRpb25zLzJfYWRkLWNoZWNrcG9pbnQtbnVtYmVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBQ0gsT0FBTyxLQUFLLEVBQUUsZ0JBQWdCLEVBQUUsTUFBTSxpQkFBaUIsQ0FBQztBQUV4RCx3QkFBZ0IsRUFBRSxDQUFDLEdBQUcsRUFBRSxnQkFBZ0IsR0FBRyxJQUFJLENBTzlDO0FBRUQsd0JBQWdCLElBQUksQ0FBQyxHQUFHLEVBQUUsZ0JBQWdCLEdBQUcsSUFBSSxDQUloRCJ9
@@ -0,0 +1 @@
1
+ {"version":3,"file":"2_add-checkpoint-number.d.ts","sourceRoot":"","sources":["../../../src/db/migrations/2_add-checkpoint-number.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD,wBAAgB,EAAE,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI,CAO9C;AAED,wBAAgB,IAAI,CAAC,GAAG,EAAE,gBAAgB,GAAG,IAAI,CAIhD"}
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Add checkpoint_number column to validator_duties table
3
+ */ export function up(pgm) {
4
+ pgm.addColumn('validator_duties', {
5
+ // eslint-disable-next-line camelcase
6
+ checkpoint_number: {
7
+ type: 'bigint',
8
+ notNull: true,
9
+ default: 0
10
+ }
11
+ });
12
+ pgm.sql(`UPDATE schema_version SET version = 2 WHERE version = 1`);
13
+ }
14
+ export function down(pgm) {
15
+ pgm.dropColumn('validator_duties', 'checkpoint_number');
16
+ pgm.sql(`UPDATE schema_version SET version = 1 WHERE version = 2`);
17
+ }