@aztec/validator-ha-signer 0.0.1-commit.ee80a48 → 0.0.1-commit.ef17749e1

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 +10 -2
  2. package/dest/db/index.d.ts +2 -1
  3. package/dest/db/index.d.ts.map +1 -1
  4. package/dest/db/index.js +1 -0
  5. package/dest/db/lmdb.d.ts +66 -0
  6. package/dest/db/lmdb.d.ts.map +1 -0
  7. package/dest/db/lmdb.js +188 -0
  8. package/dest/db/postgres.d.ts +18 -2
  9. package/dest/db/postgres.d.ts.map +1 -1
  10. package/dest/db/postgres.js +37 -16
  11. package/dest/db/schema.d.ts +13 -6
  12. package/dest/db/schema.d.ts.map +1 -1
  13. package/dest/db/schema.js +14 -5
  14. package/dest/db/types.d.ts +38 -19
  15. package/dest/db/types.d.ts.map +1 -1
  16. package/dest/db/types.js +30 -15
  17. package/dest/factory.d.ts +22 -4
  18. package/dest/factory.d.ts.map +1 -1
  19. package/dest/factory.js +50 -5
  20. package/dest/metrics.d.ts +51 -0
  21. package/dest/metrics.d.ts.map +1 -0
  22. package/dest/metrics.js +103 -0
  23. package/dest/slashing_protection_service.d.ts +19 -6
  24. package/dest/slashing_protection_service.d.ts.map +1 -1
  25. package/dest/slashing_protection_service.js +51 -11
  26. package/dest/types.d.ts +30 -70
  27. package/dest/types.d.ts.map +1 -1
  28. package/dest/types.js +3 -20
  29. package/dest/validator_ha_signer.d.ts +13 -5
  30. package/dest/validator_ha_signer.d.ts.map +1 -1
  31. package/dest/validator_ha_signer.js +18 -10
  32. package/package.json +10 -6
  33. package/src/db/index.ts +1 -0
  34. package/src/db/lmdb.ts +264 -0
  35. package/src/db/postgres.ts +38 -13
  36. package/src/db/schema.ts +16 -5
  37. package/src/db/types.ts +62 -17
  38. package/src/factory.ts +61 -4
  39. package/src/metrics.ts +138 -0
  40. package/src/slashing_protection_service.ts +66 -16
  41. package/src/types.ts +47 -104
  42. package/src/validator_ha_signer.ts +35 -14
  43. package/dest/config.d.ts +0 -96
  44. package/dest/config.d.ts.map +0 -1
  45. package/dest/config.js +0 -86
  46. package/src/config.ts +0 -141
package/src/db/lmdb.ts ADDED
@@ -0,0 +1,264 @@
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/foundation/branded-types';
11
+ import { randomBytes } from '@aztec/foundation/crypto/random';
12
+ import { EthAddress } from '@aztec/foundation/eth-address';
13
+ import { type Logger, createLogger } from '@aztec/foundation/log';
14
+ import type { DateProvider } from '@aztec/foundation/timer';
15
+ import type { AztecAsyncKVStore, AztecAsyncMap } from '@aztec/kv-store';
16
+
17
+ import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
18
+ import {
19
+ type CheckAndRecordParams,
20
+ DutyStatus,
21
+ DutyType,
22
+ type StoredDutyRecord,
23
+ getBlockIndexFromDutyIdentifier,
24
+ recordFromFields,
25
+ } from './types.js';
26
+
27
+ function dutyKey(
28
+ rollupAddress: string,
29
+ validatorAddress: string,
30
+ slot: string,
31
+ dutyType: string,
32
+ blockIndexWithinCheckpoint: number,
33
+ ): string {
34
+ return `${rollupAddress}:${validatorAddress}:${slot}:${dutyType}:${blockIndexWithinCheckpoint}`;
35
+ }
36
+
37
+ /**
38
+ * LMDB-backed implementation of SlashingProtectionDatabase.
39
+ *
40
+ * Provides single-node double-signing protection that survives crashes and restarts.
41
+ * Does not provide cross-node coordination (that requires the PostgreSQL implementation).
42
+ */
43
+ export class LmdbSlashingProtectionDatabase implements SlashingProtectionDatabase {
44
+ public static readonly SCHEMA_VERSION = 1;
45
+
46
+ private readonly duties: AztecAsyncMap<string, StoredDutyRecord>;
47
+ private readonly log: Logger;
48
+
49
+ constructor(
50
+ private readonly store: AztecAsyncKVStore,
51
+ private readonly dateProvider: DateProvider,
52
+ ) {
53
+ this.log = createLogger('slashing-protection:lmdb');
54
+ this.duties = store.openMap<string, StoredDutyRecord>('signing-protection-duties');
55
+ }
56
+
57
+ /**
58
+ * Atomically try to insert a new duty record, or get the existing one if present.
59
+ *
60
+ * LMDB is single-writer so the read-then-write inside transactionAsync is naturally atomic.
61
+ */
62
+ public async tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult> {
63
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
64
+ const key = dutyKey(
65
+ params.rollupAddress.toString(),
66
+ params.validatorAddress.toString(),
67
+ params.slot.toString(),
68
+ params.dutyType,
69
+ blockIndexWithinCheckpoint,
70
+ );
71
+
72
+ const lockToken = randomBytes(16).toString('hex');
73
+ const now = this.dateProvider.now();
74
+
75
+ const result = await this.store.transactionAsync(async () => {
76
+ const existing = await this.duties.getAsync(key);
77
+ if (existing) {
78
+ return { isNew: false as const, record: { ...existing, lockToken: '' } };
79
+ }
80
+
81
+ const newRecord: StoredDutyRecord = {
82
+ rollupAddress: params.rollupAddress.toString(),
83
+ validatorAddress: params.validatorAddress.toString(),
84
+ slot: params.slot.toString(),
85
+ blockNumber: params.blockNumber.toString(),
86
+ blockIndexWithinCheckpoint,
87
+ dutyType: params.dutyType,
88
+ status: DutyStatus.SIGNING,
89
+ messageHash: params.messageHash,
90
+ nodeId: params.nodeId,
91
+ lockToken,
92
+ startedAtMs: now,
93
+ };
94
+ await this.duties.set(key, newRecord);
95
+ return { isNew: true as const, record: newRecord };
96
+ });
97
+
98
+ if (result.isNew) {
99
+ this.log.debug(`Acquired lock for duty ${params.dutyType} at slot ${params.slot}`, {
100
+ validatorAddress: params.validatorAddress.toString(),
101
+ nodeId: params.nodeId,
102
+ });
103
+ }
104
+
105
+ return { isNew: result.isNew, record: recordFromFields(result.record) };
106
+ }
107
+
108
+ /**
109
+ * Update a duty to 'signed' status with the signature.
110
+ * Only succeeds if the lockToken matches.
111
+ */
112
+ public updateDutySigned(
113
+ rollupAddress: EthAddress,
114
+ validatorAddress: EthAddress,
115
+ slot: SlotNumber,
116
+ dutyType: DutyType,
117
+ signature: string,
118
+ lockToken: string,
119
+ blockIndexWithinCheckpoint: number,
120
+ ): Promise<boolean> {
121
+ const key = dutyKey(
122
+ rollupAddress.toString(),
123
+ validatorAddress.toString(),
124
+ slot.toString(),
125
+ dutyType,
126
+ blockIndexWithinCheckpoint,
127
+ );
128
+
129
+ return this.store.transactionAsync(async () => {
130
+ const existing = await this.duties.getAsync(key);
131
+ if (!existing) {
132
+ this.log.warn('Failed to update duty to signed: duty not found', {
133
+ rollupAddress: rollupAddress.toString(),
134
+ validatorAddress: validatorAddress.toString(),
135
+ slot: slot.toString(),
136
+ dutyType,
137
+ blockIndexWithinCheckpoint,
138
+ });
139
+ return false;
140
+ }
141
+
142
+ if (existing.lockToken !== lockToken) {
143
+ this.log.warn('Failed to update duty to signed: invalid token', {
144
+ rollupAddress: rollupAddress.toString(),
145
+ validatorAddress: validatorAddress.toString(),
146
+ slot: slot.toString(),
147
+ dutyType,
148
+ blockIndexWithinCheckpoint,
149
+ });
150
+ return false;
151
+ }
152
+
153
+ await this.duties.set(key, {
154
+ ...existing,
155
+ status: DutyStatus.SIGNED,
156
+ signature,
157
+ completedAtMs: this.dateProvider.now(),
158
+ });
159
+
160
+ return true;
161
+ });
162
+ }
163
+
164
+ /**
165
+ * Delete a duty record.
166
+ * Only succeeds if the lockToken matches.
167
+ */
168
+ public deleteDuty(
169
+ rollupAddress: EthAddress,
170
+ validatorAddress: EthAddress,
171
+ slot: SlotNumber,
172
+ dutyType: DutyType,
173
+ lockToken: string,
174
+ blockIndexWithinCheckpoint: number,
175
+ ): Promise<boolean> {
176
+ const key = dutyKey(
177
+ rollupAddress.toString(),
178
+ validatorAddress.toString(),
179
+ slot.toString(),
180
+ dutyType,
181
+ blockIndexWithinCheckpoint,
182
+ );
183
+
184
+ return this.store.transactionAsync(async () => {
185
+ const existing = await this.duties.getAsync(key);
186
+ if (!existing || existing.lockToken !== lockToken) {
187
+ this.log.warn('Failed to delete duty: invalid token or duty not found', {
188
+ rollupAddress: rollupAddress.toString(),
189
+ validatorAddress: validatorAddress.toString(),
190
+ slot: slot.toString(),
191
+ dutyType,
192
+ blockIndexWithinCheckpoint,
193
+ });
194
+ return false;
195
+ }
196
+
197
+ await this.duties.delete(key);
198
+ return true;
199
+ });
200
+ }
201
+
202
+ /**
203
+ * Cleanup own stuck duties (SIGNING status older than maxAgeMs).
204
+ */
205
+ public cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
206
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
207
+
208
+ return this.store.transactionAsync(async () => {
209
+ const keysToDelete: string[] = [];
210
+ for await (const [key, record] of this.duties.entriesAsync()) {
211
+ if (record.nodeId === nodeId && record.status === DutyStatus.SIGNING && record.startedAtMs < cutoffMs) {
212
+ keysToDelete.push(key);
213
+ }
214
+ }
215
+ for (const key of keysToDelete) {
216
+ await this.duties.delete(key);
217
+ }
218
+ return keysToDelete.length;
219
+ });
220
+ }
221
+
222
+ /**
223
+ * Cleanup duties with outdated rollup address.
224
+ *
225
+ * This is always a no-op for the LMDB implementation: the underlying store is created via
226
+ * DatabaseVersionManager (in factory.ts), which already resets the entire data directory at
227
+ * startup whenever the rollup address changes.
228
+ */
229
+ public cleanupOutdatedRollupDuties(_currentRollupAddress: EthAddress): Promise<number> {
230
+ return Promise.resolve(0);
231
+ }
232
+
233
+ /**
234
+ * Cleanup old signed duties older than maxAgeMs.
235
+ */
236
+ public cleanupOldDuties(maxAgeMs: number): Promise<number> {
237
+ const cutoffMs = this.dateProvider.now() - maxAgeMs;
238
+
239
+ return this.store.transactionAsync(async () => {
240
+ const keysToDelete: string[] = [];
241
+ for await (const [key, record] of this.duties.entriesAsync()) {
242
+ if (
243
+ record.status === DutyStatus.SIGNED &&
244
+ record.completedAtMs !== undefined &&
245
+ record.completedAtMs < cutoffMs
246
+ ) {
247
+ keysToDelete.push(key);
248
+ }
249
+ }
250
+ for (const key of keysToDelete) {
251
+ await this.duties.delete(key);
252
+ }
253
+ return keysToDelete.length;
254
+ });
255
+ }
256
+
257
+ /**
258
+ * Close the underlying LMDB store.
259
+ */
260
+ public async close(): Promise<void> {
261
+ await this.store.close();
262
+ this.log.debug('LMDB slashing protection database closed');
263
+ }
264
+ }
@@ -1,7 +1,7 @@
1
1
  /**
2
2
  * PostgreSQL implementation of SlashingProtectionDatabase
3
3
  */
4
- import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
4
+ import { SlotNumber } from '@aztec/foundation/branded-types';
5
5
  import { randomBytes } from '@aztec/foundation/crypto/random';
6
6
  import { EthAddress } from '@aztec/foundation/eth-address';
7
7
  import { type Logger, createLogger } from '@aztec/foundation/log';
@@ -11,6 +11,8 @@ import type { QueryResult, QueryResultRow } from 'pg';
11
11
 
12
12
  import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
13
13
  import {
14
+ CLEANUP_OLD_DUTIES,
15
+ CLEANUP_OUTDATED_ROLLUP_DUTIES,
14
16
  CLEANUP_OWN_STUCK_DUTIES,
15
17
  DELETE_DUTY,
16
18
  INSERT_OR_GET_DUTY,
@@ -18,7 +20,7 @@ import {
18
20
  UPDATE_DUTY_SIGNED,
19
21
  } from './schema.js';
20
22
  import type { CheckAndRecordParams, DutyRow, DutyType, InsertOrGetRow, ValidatorDutyRecord } from './types.js';
21
- import { getBlockIndexFromDutyIdentifier } from './types.js';
23
+ import { getBlockIndexFromDutyIdentifier, recordFromFields } from './types.js';
22
24
 
23
25
  /**
24
26
  * Minimal pool interface for database operations.
@@ -218,14 +220,16 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
218
220
  }
219
221
 
220
222
  /**
221
- * Convert a database row to a ValidatorDutyRecord
223
+ * Convert a database row to a ValidatorDutyRecord.
224
+ * Maps snake_case column names to StoredDutyRecord (camelCase, ms timestamps),
225
+ * then delegates to the shared recordFromFields() converter.
222
226
  */
223
227
  private rowToRecord(row: DutyRow): ValidatorDutyRecord {
224
- return {
225
- rollupAddress: EthAddress.fromString(row.rollup_address),
226
- validatorAddress: EthAddress.fromString(row.validator_address),
227
- slot: SlotNumber.fromString(row.slot),
228
- blockNumber: BlockNumber.fromString(row.block_number),
228
+ return recordFromFields({
229
+ rollupAddress: row.rollup_address,
230
+ validatorAddress: row.validator_address,
231
+ slot: row.slot,
232
+ blockNumber: row.block_number,
229
233
  blockIndexWithinCheckpoint: row.block_index_within_checkpoint,
230
234
  dutyType: row.duty_type,
231
235
  status: row.status,
@@ -233,10 +237,10 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
233
237
  signature: row.signature ?? undefined,
234
238
  nodeId: row.node_id,
235
239
  lockToken: row.lock_token,
236
- startedAt: row.started_at,
237
- completedAt: row.completed_at ?? undefined,
240
+ startedAtMs: row.started_at.getTime(),
241
+ completedAtMs: row.completed_at?.getTime(),
238
242
  errorMessage: row.error_message ?? undefined,
239
- };
243
+ });
240
244
  }
241
245
 
242
246
  /**
@@ -252,8 +256,29 @@ export class PostgresSlashingProtectionDatabase implements SlashingProtectionDat
252
256
  * @returns the number of duties cleaned up
253
257
  */
254
258
  async cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number> {
255
- const cutoff = new Date(Date.now() - maxAgeMs);
256
- const result = await this.pool.query(CLEANUP_OWN_STUCK_DUTIES, [nodeId, cutoff]);
259
+ const result = await this.pool.query(CLEANUP_OWN_STUCK_DUTIES, [nodeId, maxAgeMs]);
260
+ return result.rowCount ?? 0;
261
+ }
262
+
263
+ /**
264
+ * Cleanup duties with outdated rollup address.
265
+ * Removes all duties where the rollup address doesn't match the current one.
266
+ * Used after a rollup upgrade to clean up duties for the old rollup.
267
+ * @returns the number of duties cleaned up
268
+ */
269
+ async cleanupOutdatedRollupDuties(currentRollupAddress: EthAddress): Promise<number> {
270
+ const result = await this.pool.query(CLEANUP_OUTDATED_ROLLUP_DUTIES, [currentRollupAddress.toString()]);
271
+ return result.rowCount ?? 0;
272
+ }
273
+
274
+ /**
275
+ * Cleanup old signed duties.
276
+ * Removes only signed duties older than the specified age.
277
+ * Does not remove 'signing' duties as they may be in progress.
278
+ * @returns the number of duties cleaned up
279
+ */
280
+ async cleanupOldDuties(maxAgeMs: number): Promise<number> {
281
+ const result = await this.pool.query(CLEANUP_OLD_DUTIES, [maxAgeMs]);
257
282
  return result.rowCount ?? 0;
258
283
  }
259
284
  }
package/src/db/schema.ts CHANGED
@@ -22,7 +22,7 @@ CREATE TABLE IF NOT EXISTS validator_duties (
22
22
  block_number BIGINT NOT NULL,
23
23
  block_index_within_checkpoint INTEGER NOT NULL DEFAULT 0,
24
24
  duty_type VARCHAR(30) NOT NULL CHECK (duty_type IN ('BLOCK_PROPOSAL', 'CHECKPOINT_PROPOSAL', 'ATTESTATION', 'ATTESTATIONS_AND_SIGNERS', 'GOVERNANCE_VOTE', 'SLASHING_VOTE')),
25
- status VARCHAR(20) NOT NULL CHECK (status IN ('signing', 'signed', 'failed')),
25
+ status VARCHAR(20) NOT NULL CHECK (status IN ('signing', 'signed')),
26
26
  message_hash VARCHAR(66) NOT NULL,
27
27
  signature VARCHAR(132),
28
28
  node_id VARCHAR(255) NOT NULL,
@@ -203,23 +203,34 @@ WHERE status = 'signed'
203
203
 
204
204
  /**
205
205
  * Query to clean up old duties (for maintenance)
206
- * Removes duties older than a specified timestamp
206
+ * Removes SIGNED duties older than a specified age (in milliseconds)
207
207
  */
208
208
  export const CLEANUP_OLD_DUTIES = `
209
209
  DELETE FROM validator_duties
210
- WHERE status IN ('signing', 'signed', 'failed')
211
- AND started_at < $1;
210
+ WHERE status = 'signed'
211
+ AND started_at < CURRENT_TIMESTAMP - ($1 || ' milliseconds')::INTERVAL;
212
212
  `;
213
213
 
214
214
  /**
215
215
  * Query to cleanup own stuck duties
216
216
  * Removes duties in 'signing' status for a specific node that are older than maxAgeMs
217
+ * Uses DB's CURRENT_TIMESTAMP to avoid clock skew issues between nodes
217
218
  */
218
219
  export const CLEANUP_OWN_STUCK_DUTIES = `
219
220
  DELETE FROM validator_duties
220
221
  WHERE node_id = $1
221
222
  AND status = 'signing'
222
- AND started_at < $2;
223
+ AND started_at < CURRENT_TIMESTAMP - ($2 || ' milliseconds')::INTERVAL;
224
+ `;
225
+
226
+ /**
227
+ * Query to cleanup duties with outdated rollup address
228
+ * Removes all duties where the rollup address doesn't match the current one
229
+ * Used after a rollup upgrade to clean up duties for the old rollup
230
+ */
231
+ export const CLEANUP_OUTDATED_ROLLUP_DUTIES = `
232
+ DELETE FROM validator_duties
233
+ WHERE rollup_address != $1;
223
234
  `;
224
235
 
225
236
  /**
package/src/db/types.ts CHANGED
@@ -1,6 +1,12 @@
1
- import type { BlockNumber, CheckpointNumber, IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
2
- import type { EthAddress } from '@aztec/foundation/eth-address';
1
+ import {
2
+ BlockNumber,
3
+ type CheckpointNumber,
4
+ type IndexWithinCheckpoint,
5
+ SlotNumber,
6
+ } from '@aztec/foundation/branded-types';
7
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
8
  import type { Signature } from '@aztec/foundation/eth-signature';
9
+ import { DutyType } from '@aztec/stdlib/ha-signing';
4
10
 
5
11
  /**
6
12
  * Row type from PostgreSQL query
@@ -23,24 +29,34 @@ export interface DutyRow {
23
29
  }
24
30
 
25
31
  /**
26
- * Row type from INSERT_OR_GET_DUTY query (includes is_new flag)
32
+ * Plain-primitive representation of a duty record suitable for serialization
33
+ * (e.g. msgpackr for LMDB). All domain types are stored as their string/number
34
+ * equivalents. Timestamps are Unix milliseconds.
27
35
  */
28
- export interface InsertOrGetRow extends DutyRow {
29
- is_new: boolean;
36
+ export interface StoredDutyRecord {
37
+ rollupAddress: string;
38
+ validatorAddress: string;
39
+ slot: string;
40
+ blockNumber: string;
41
+ blockIndexWithinCheckpoint: number;
42
+ dutyType: DutyType;
43
+ status: DutyStatus;
44
+ messageHash: string;
45
+ signature?: string;
46
+ nodeId: string;
47
+ lockToken: string;
48
+ /** Unix timestamp in milliseconds when signing started */
49
+ startedAtMs: number;
50
+ /** Unix timestamp in milliseconds when signing completed */
51
+ completedAtMs?: number;
52
+ errorMessage?: string;
30
53
  }
31
54
 
32
55
  /**
33
- * Type of validator duty being performed
56
+ * Row type from INSERT_OR_GET_DUTY query (includes is_new flag)
34
57
  */
35
- export enum DutyType {
36
- BLOCK_PROPOSAL = 'BLOCK_PROPOSAL',
37
- CHECKPOINT_PROPOSAL = 'CHECKPOINT_PROPOSAL',
38
- ATTESTATION = 'ATTESTATION',
39
- ATTESTATIONS_AND_SIGNERS = 'ATTESTATIONS_AND_SIGNERS',
40
- GOVERNANCE_VOTE = 'GOVERNANCE_VOTE',
41
- SLASHING_VOTE = 'SLASHING_VOTE',
42
- AUTH_REQUEST = 'AUTH_REQUEST',
43
- TXS = 'TXS',
58
+ export interface InsertOrGetRow extends DutyRow {
59
+ is_new: boolean;
44
60
  }
45
61
 
46
62
  /**
@@ -51,8 +67,12 @@ export enum DutyStatus {
51
67
  SIGNED = 'signed',
52
68
  }
53
69
 
70
+ // Re-export DutyType from stdlib
71
+ export { DutyType };
72
+
54
73
  /**
55
- * Record of a validator duty in the database
74
+ * Rich representation of a validator duty, with branded types and Date objects.
75
+ * This is the common output type returned by all SlashingProtectionDatabase implementations.
56
76
  */
57
77
  export interface ValidatorDutyRecord {
58
78
  /** Ethereum address of the rollup contract */
@@ -81,10 +101,35 @@ export interface ValidatorDutyRecord {
81
101
  startedAt: Date;
82
102
  /** When the duty signing was completed (success or failure) */
83
103
  completedAt?: Date;
84
- /** Error message if status is 'failed' */
104
+ /** Error message (currently unused) */
85
105
  errorMessage?: string;
86
106
  }
87
107
 
108
+ /**
109
+ * Convert a {@link StoredDutyRecord} (plain-primitive wire format) to a
110
+ * {@link ValidatorDutyRecord} (rich domain type).
111
+ *
112
+ * Shared by LMDB and any future non-Postgres backend implementations.
113
+ */
114
+ export function recordFromFields(stored: StoredDutyRecord): ValidatorDutyRecord {
115
+ return {
116
+ rollupAddress: EthAddress.fromString(stored.rollupAddress),
117
+ validatorAddress: EthAddress.fromString(stored.validatorAddress),
118
+ slot: SlotNumber.fromString(stored.slot),
119
+ blockNumber: BlockNumber.fromString(stored.blockNumber),
120
+ blockIndexWithinCheckpoint: stored.blockIndexWithinCheckpoint,
121
+ dutyType: stored.dutyType,
122
+ status: stored.status,
123
+ messageHash: stored.messageHash,
124
+ signature: stored.signature,
125
+ nodeId: stored.nodeId,
126
+ lockToken: stored.lockToken,
127
+ startedAt: new Date(stored.startedAtMs),
128
+ completedAt: stored.completedAtMs !== undefined ? new Date(stored.completedAtMs) : undefined,
129
+ errorMessage: stored.errorMessage,
130
+ };
131
+ }
132
+
88
133
  /**
89
134
  * Duty identifier for block proposals.
90
135
  * blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
package/src/factory.ts CHANGED
@@ -1,11 +1,17 @@
1
1
  /**
2
2
  * Factory functions for creating validator HA signers
3
3
  */
4
+ import { DateProvider } from '@aztec/foundation/timer';
5
+ import { createStore } from '@aztec/kv-store/lmdb-v2';
6
+ import type { LocalSignerConfig, ValidatorHASignerConfig } from '@aztec/stdlib/ha-signing';
7
+ import { getTelemetryClient } from '@aztec/telemetry-client';
8
+
4
9
  import { Pool } from 'pg';
5
10
 
6
- import type { ValidatorHASignerConfig } from './config.js';
11
+ import { LmdbSlashingProtectionDatabase } from './db/lmdb.js';
7
12
  import { PostgresSlashingProtectionDatabase } from './db/postgres.js';
8
- import type { CreateHASignerDeps, SlashingProtectionDatabase } from './types.js';
13
+ import { HASignerMetrics } from './metrics.js';
14
+ import type { CreateHASignerDeps, CreateLocalSignerWithProtectionDeps, SlashingProtectionDatabase } from './types.js';
9
15
  import { ValidatorHASigner } from './validator_ha_signer.js';
10
16
 
11
17
  /**
@@ -23,7 +29,6 @@ import { ValidatorHASigner } from './validator_ha_signer.js';
23
29
  * ```typescript
24
30
  * const { signer, db } = await createHASigner({
25
31
  * databaseUrl: process.env.DATABASE_URL,
26
- * haSigningEnabled: true,
27
32
  * nodeId: 'validator-node-1',
28
33
  * pollingIntervalMs: 100,
29
34
  * signingTimeoutMs: 3000,
@@ -55,6 +60,10 @@ export async function createHASigner(
55
60
  if (!databaseUrl) {
56
61
  throw new Error('databaseUrl is required for createHASigner');
57
62
  }
63
+
64
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
65
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
66
+
58
67
  // Create connection pool (or use provided pool)
59
68
  let pool: Pool;
60
69
  if (!deps?.pool) {
@@ -75,8 +84,56 @@ export async function createHASigner(
75
84
  // Verify database schema is initialized and version matches
76
85
  await db.initialize();
77
86
 
87
+ // Create metrics
88
+ const metrics = new HASignerMetrics(telemetryClient, signerConfig.nodeId);
89
+
78
90
  // Create signer
79
- const signer = new ValidatorHASigner(db, { ...signerConfig, databaseUrl });
91
+ const signer = new ValidatorHASigner(db, signerConfig, { metrics, dateProvider });
92
+
93
+ return { signer, db };
94
+ }
95
+
96
+ /**
97
+ * Create a local (single-node) signing protection signer backed by LMDB.
98
+ *
99
+ * This provides double-signing protection for nodes that are NOT running in a
100
+ * high-availability (multi-node) setup. It prevents a proposer from sending two
101
+ * proposals for the same slot if the node crashes and restarts mid-proposal.
102
+ *
103
+ * When `config.dataDirectory` is set, the protection database is persisted to disk
104
+ * and survives crashes/restarts. When unset, an ephemeral in-memory store is
105
+ * used which protects within a single run but not across restarts.
106
+ *
107
+ * @param config - Local signer config
108
+ * @param deps - Optional dependencies (telemetry, date provider).
109
+ * @returns An object containing the signer and database instances.
110
+ */
111
+ export async function createLocalSignerWithProtection(
112
+ config: LocalSignerConfig,
113
+ deps?: CreateLocalSignerWithProtectionDeps,
114
+ ): Promise<{
115
+ signer: ValidatorHASigner;
116
+ db: SlashingProtectionDatabase;
117
+ }> {
118
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
119
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
120
+
121
+ const kvStore = await createStore('signing-protection', LmdbSlashingProtectionDatabase.SCHEMA_VERSION, {
122
+ dataDirectory: config.dataDirectory,
123
+ dataStoreMapSizeKb: config.signingProtectionMapSizeKb ?? config.dataStoreMapSizeKb,
124
+ l1Contracts: config.l1Contracts,
125
+ });
126
+
127
+ const db = new LmdbSlashingProtectionDatabase(kvStore, dateProvider);
128
+
129
+ const signerConfig = {
130
+ ...config,
131
+ nodeId: config.nodeId || 'local',
132
+ };
133
+
134
+ const metrics = new HASignerMetrics(telemetryClient, signerConfig.nodeId, 'LocalSigningProtectionMetrics');
135
+
136
+ const signer = new ValidatorHASigner(db, signerConfig, { metrics, dateProvider });
80
137
 
81
138
  return { signer, db };
82
139
  }