@aztec/validator-ha-signer 0.0.1-commit.ffe5b04ea → 0.0.1-commit.fff30aa

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 +2 -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/in_memory.d.ts +20 -0
  6. package/dest/db/in_memory.d.ts.map +1 -0
  7. package/dest/db/in_memory.js +73 -0
  8. package/dest/db/index.d.ts +1 -2
  9. package/dest/db/index.d.ts.map +1 -1
  10. package/dest/db/index.js +0 -1
  11. package/dest/db/postgres.d.ts +2 -4
  12. package/dest/db/postgres.d.ts.map +1 -1
  13. package/dest/db/postgres.js +13 -13
  14. package/dest/db/types.d.ts +18 -37
  15. package/dest/db/types.d.ts.map +1 -1
  16. package/dest/db/types.js +15 -30
  17. package/dest/factory.d.ts +13 -18
  18. package/dest/factory.d.ts.map +1 -1
  19. package/dest/factory.js +22 -42
  20. package/dest/slashing_protection_service.d.ts +3 -12
  21. package/dest/slashing_protection_service.d.ts.map +1 -1
  22. package/dest/slashing_protection_service.js +6 -17
  23. package/dest/types.d.ts +70 -17
  24. package/dest/types.d.ts.map +1 -1
  25. package/dest/types.js +20 -3
  26. package/dest/validator_ha_signer.d.ts +4 -12
  27. package/dest/validator_ha_signer.d.ts.map +1 -1
  28. package/dest/validator_ha_signer.js +8 -16
  29. package/package.json +6 -10
  30. package/src/config.ts +149 -0
  31. package/src/db/in_memory.ts +107 -0
  32. package/src/db/index.ts +0 -1
  33. package/src/db/postgres.ts +11 -13
  34. package/src/db/types.ts +16 -61
  35. package/src/factory.ts +28 -53
  36. package/src/slashing_protection_service.ts +7 -28
  37. package/src/types.ts +104 -32
  38. package/src/validator_ha_signer.ts +12 -33
  39. package/dest/db/lmdb.d.ts +0 -66
  40. package/dest/db/lmdb.d.ts.map +0 -1
  41. package/dest/db/lmdb.js +0 -188
  42. package/dest/metrics.d.ts +0 -51
  43. package/dest/metrics.d.ts.map +0 -1
  44. package/dest/metrics.js +0 -103
  45. package/src/db/lmdb.ts +0 -264
  46. package/src/metrics.ts +0 -138
@@ -7,8 +7,6 @@
7
7
  import { type Logger, createLogger } from '@aztec/foundation/log';
8
8
  import { RunningPromise } from '@aztec/foundation/promise';
9
9
  import { sleep } from '@aztec/foundation/sleep';
10
- import type { DateProvider } from '@aztec/foundation/timer';
11
- import type { BaseSignerConfig } from '@aztec/stdlib/ha-signing';
12
10
 
13
11
  import {
14
12
  type CheckAndRecordParams,
@@ -18,13 +16,7 @@ import {
18
16
  getBlockIndexFromDutyIdentifier,
19
17
  } from './db/types.js';
20
18
  import { DutyAlreadySignedError, SlashingProtectionError } from './errors.js';
21
- import type { HASignerMetrics } from './metrics.js';
22
- import type { SlashingProtectionDatabase } from './types.js';
23
-
24
- export interface SlashingProtectionServiceDeps {
25
- metrics: HASignerMetrics;
26
- dateProvider: DateProvider;
27
- }
19
+ import type { SlashingProtectionDatabase, ValidatorHASignerConfig } from './types.js';
28
20
 
29
21
  /**
30
22
  * Slashing Protection Service
@@ -47,16 +39,12 @@ export class SlashingProtectionService {
47
39
  private readonly signingTimeoutMs: number;
48
40
  private readonly maxStuckDutiesAgeMs: number;
49
41
 
50
- private readonly metrics: HASignerMetrics;
51
- private readonly dateProvider: DateProvider;
52
-
53
42
  private cleanupRunningPromise: RunningPromise;
54
43
  private lastOldDutiesCleanupAtMs?: number;
55
44
 
56
45
  constructor(
57
46
  private readonly db: SlashingProtectionDatabase,
58
- private readonly config: BaseSignerConfig,
59
- deps: SlashingProtectionServiceDeps,
47
+ private readonly config: ValidatorHASignerConfig,
60
48
  ) {
61
49
  this.log = createLogger('slashing-protection');
62
50
  this.pollingIntervalMs = config.pollingIntervalMs;
@@ -65,8 +53,6 @@ export class SlashingProtectionService {
65
53
  this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? 144_000;
66
54
 
67
55
  this.cleanupRunningPromise = new RunningPromise(this.cleanup.bind(this), this.log, this.maxStuckDutiesAgeMs);
68
- this.metrics = deps.metrics;
69
- this.dateProvider = deps.dateProvider;
70
56
  }
71
57
 
72
58
  /**
@@ -86,7 +72,7 @@ export class SlashingProtectionService {
86
72
  */
87
73
  async checkAndRecord(params: CheckAndRecordParams): Promise<string> {
88
74
  const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
89
- const startTime = this.dateProvider.now();
75
+ const startTime = Date.now();
90
76
 
91
77
  this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
92
78
  validatorAddress: validatorAddress.toString(),
@@ -99,11 +85,10 @@ export class SlashingProtectionService {
99
85
 
100
86
  if (isNew) {
101
87
  // We successfully acquired the lock
102
- this.log.info(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
88
+ this.log.verbose(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
103
89
  validatorAddress: validatorAddress.toString(),
104
90
  nodeId,
105
91
  });
106
- this.metrics.recordLockAcquire(true);
107
92
  return record.lockToken;
108
93
  }
109
94
 
@@ -118,7 +103,6 @@ export class SlashingProtectionService {
118
103
  existingNodeId: record.nodeId,
119
104
  attemptingNodeId: nodeId,
120
105
  });
121
- this.metrics.recordSlashingProtection(dutyType);
122
106
  throw new SlashingProtectionError(
123
107
  slot,
124
108
  dutyType,
@@ -128,17 +112,15 @@ export class SlashingProtectionService {
128
112
  record.nodeId,
129
113
  );
130
114
  }
131
- this.metrics.recordDutyAlreadySigned(dutyType);
132
115
  throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
133
116
  } else if (record.status === DutyStatus.SIGNING) {
134
117
  // Another node is currently signing - check for timeout
135
- if (this.dateProvider.now() - startTime > this.signingTimeoutMs) {
118
+ if (Date.now() - startTime > this.signingTimeoutMs) {
136
119
  this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
137
120
  validatorAddress: validatorAddress.toString(),
138
121
  timeoutMs: this.signingTimeoutMs,
139
122
  signingNodeId: record.nodeId,
140
123
  });
141
- this.metrics.recordDutyAlreadySigned(dutyType);
142
124
  throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
143
125
  }
144
126
 
@@ -177,7 +159,7 @@ export class SlashingProtectionService {
177
159
  );
178
160
 
179
161
  if (success) {
180
- this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
162
+ this.log.verbose(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
181
163
  validatorAddress: validatorAddress.toString(),
182
164
  nodeId,
183
165
  });
@@ -246,7 +228,6 @@ export class SlashingProtectionService {
246
228
  this.log.info(`Cleaned up ${numOutdatedRollupDuties} duties with outdated rollup address at startup`, {
247
229
  currentRollupAddress: this.config.l1Contracts.rollupAddress.toString(),
248
230
  });
249
- this.metrics.recordCleanup('outdated_rollup', numOutdatedRollupDuties);
250
231
  }
251
232
 
252
233
  this.cleanupRunningPromise.start();
@@ -282,14 +263,13 @@ export class SlashingProtectionService {
282
263
  nodeId: this.config.nodeId,
283
264
  maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs,
284
265
  });
285
- this.metrics.recordCleanup('stuck', numStuckDuties);
286
266
  }
287
267
 
288
268
  // 2. Clean up old signed duties if configured
289
269
  // we shouldn't run this as often as stuck duty cleanup.
290
270
  if (this.config.cleanupOldDutiesAfterHours !== undefined) {
291
271
  const maxAgeMs = this.config.cleanupOldDutiesAfterHours * 60 * 60 * 1000;
292
- const nowMs = this.dateProvider.now();
272
+ const nowMs = Date.now();
293
273
  const shouldRun =
294
274
  this.lastOldDutiesCleanupAtMs === undefined || nowMs - this.lastOldDutiesCleanupAtMs >= maxAgeMs;
295
275
  if (shouldRun) {
@@ -300,7 +280,6 @@ export class SlashingProtectionService {
300
280
  cleanupOldDutiesAfterHours: this.config.cleanupOldDutiesAfterHours,
301
281
  maxAgeMs,
302
282
  });
303
- this.metrics.recordCleanup('old', numOldDuties);
304
283
  }
305
284
  }
306
285
  }
package/src/types.ts CHANGED
@@ -1,27 +1,24 @@
1
- import { SlotNumber } from '@aztec/foundation/branded-types';
2
- import type { EthAddress } from '@aztec/foundation/eth-address';
3
- import { DateProvider } from '@aztec/foundation/timer';
4
1
  import {
5
- DutyType,
6
- type HAProtectedSigningContext,
7
- type SigningContext,
8
- type ValidatorHASignerConfig,
9
- getBlockNumberFromSigningContext as getBlockNumberFromSigningContextFromStdlib,
10
- isHAProtectedContext,
11
- } from '@aztec/stdlib/ha-signing';
12
- import type { TelemetryClient } from '@aztec/telemetry-client';
2
+ BlockNumber,
3
+ type CheckpointNumber,
4
+ type IndexWithinCheckpoint,
5
+ type SlotNumber,
6
+ } from '@aztec/foundation/branded-types';
7
+ import type { EthAddress } from '@aztec/foundation/eth-address';
13
8
 
14
9
  import type { Pool } from 'pg';
15
10
 
16
- import type {
17
- BlockProposalDutyIdentifier,
18
- CheckAndRecordParams,
19
- DeleteDutyParams,
20
- DutyIdentifier,
21
- DutyRow,
22
- OtherDutyIdentifier,
23
- RecordSuccessParams,
24
- ValidatorDutyRecord,
11
+ import type { ValidatorHASignerConfig } from './config.js';
12
+ import {
13
+ type BlockProposalDutyIdentifier,
14
+ type CheckAndRecordParams,
15
+ type DeleteDutyParams,
16
+ type DutyIdentifier,
17
+ type DutyRow,
18
+ DutyType,
19
+ type OtherDutyIdentifier,
20
+ type RecordSuccessParams,
21
+ type ValidatorDutyRecord,
25
22
  } from './db/types.js';
26
23
 
27
24
  export type {
@@ -30,16 +27,12 @@ export type {
30
27
  DeleteDutyParams,
31
28
  DutyIdentifier,
32
29
  DutyRow,
33
- HAProtectedSigningContext,
34
30
  OtherDutyIdentifier,
35
31
  RecordSuccessParams,
36
- SigningContext,
37
32
  ValidatorDutyRecord,
38
33
  ValidatorHASignerConfig,
39
34
  };
40
35
  export { DutyStatus, DutyType, getBlockIndexFromDutyIdentifier, normalizeBlockIndex } from './db/types.js';
41
- export { isHAProtectedContext };
42
- export { getBlockNumberFromSigningContextFromStdlib as getBlockNumberFromSigningContext };
43
36
 
44
37
  /**
45
38
  * Result of tryInsertOrGetExisting operation
@@ -60,20 +53,99 @@ export interface CreateHASignerDeps {
60
53
  * If provided, databaseUrl and poolConfig are ignored
61
54
  */
62
55
  pool?: Pool;
56
+ }
57
+
58
+ /**
59
+ * Base context for signing operations
60
+ */
61
+ interface BaseSigningContext {
62
+ /** Slot number for this duty */
63
+ slot: SlotNumber;
63
64
  /**
64
- * Optional telemetry client for metrics
65
- */
66
- telemetryClient?: TelemetryClient;
67
- /**
68
- * Optional date provider for timestamps
65
+ * Block or checkpoint number for this duty.
66
+ * For block proposals, this is the block number.
67
+ * For checkpoint proposals, this is the checkpoint number.
69
68
  */
70
- dateProvider?: DateProvider;
69
+ blockNumber: BlockNumber | CheckpointNumber;
70
+ }
71
+
72
+ /**
73
+ * Signing context for block proposals.
74
+ * blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
75
+ */
76
+ export interface BlockProposalSigningContext extends BaseSigningContext {
77
+ /** Block index within checkpoint (0, 1, 2...). Required for block proposals. */
78
+ blockIndexWithinCheckpoint: IndexWithinCheckpoint;
79
+ dutyType: DutyType.BLOCK_PROPOSAL;
80
+ }
81
+
82
+ /**
83
+ * Signing context for non-block-proposal duties that require HA protection.
84
+ * blockIndexWithinCheckpoint is not applicable (internally always -1).
85
+ */
86
+ export interface OtherSigningContext extends BaseSigningContext {
87
+ dutyType: DutyType.CHECKPOINT_PROPOSAL | DutyType.ATTESTATION | DutyType.ATTESTATIONS_AND_SIGNERS;
88
+ }
89
+
90
+ /**
91
+ * Signing context for governance/slashing votes which only need slot for HA protection.
92
+ * blockNumber is not applicable (internally always 0).
93
+ */
94
+ export interface VoteSigningContext {
95
+ slot: SlotNumber;
96
+ dutyType: DutyType.GOVERNANCE_VOTE | DutyType.SLASHING_VOTE;
97
+ }
98
+
99
+ /**
100
+ * Signing context for duties which don't require slot/blockNumber
101
+ * as they don't need HA protection (AUTH_REQUEST, TXS).
102
+ */
103
+ export interface NoHAProtectionSigningContext {
104
+ dutyType: DutyType.AUTH_REQUEST | DutyType.TXS;
105
+ }
106
+
107
+ /**
108
+ * Signing contexts that require HA protection (excludes AUTH_REQUEST).
109
+ * Used by the HA signer's signWithProtection method.
110
+ */
111
+ export type HAProtectedSigningContext = BlockProposalSigningContext | OtherSigningContext | VoteSigningContext;
112
+
113
+ /**
114
+ * Type guard to check if a SigningContext requires HA protection.
115
+ * Returns true for contexts that need HA protection, false for AUTH_REQUEST and TXS.
116
+ */
117
+ export function isHAProtectedContext(context: SigningContext): context is HAProtectedSigningContext {
118
+ return context.dutyType !== DutyType.AUTH_REQUEST && context.dutyType !== DutyType.TXS;
119
+ }
120
+
121
+ /**
122
+ * Gets the block number from a signing context.
123
+ * - Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE): returns BlockNumber(0)
124
+ * - Other duties: returns the blockNumber from the context
125
+ */
126
+ export function getBlockNumberFromSigningContext(context: HAProtectedSigningContext): BlockNumber | CheckpointNumber {
127
+ // Check for duty types that have blockNumber
128
+ if (
129
+ context.dutyType === DutyType.BLOCK_PROPOSAL ||
130
+ context.dutyType === DutyType.CHECKPOINT_PROPOSAL ||
131
+ context.dutyType === DutyType.ATTESTATION ||
132
+ context.dutyType === DutyType.ATTESTATIONS_AND_SIGNERS
133
+ ) {
134
+ return context.blockNumber;
135
+ }
136
+ // Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE) don't have blockNumber
137
+ return BlockNumber(0);
71
138
  }
72
139
 
73
140
  /**
74
- * deps for creating a local signing protection signer
141
+ * Context required for slashing protection during signing operations.
142
+ * Uses discriminated union to enforce type safety:
143
+ * - BLOCK_PROPOSAL duties MUST have blockIndexWithinCheckpoint >= 0
144
+ * - Other duty types do NOT have blockIndexWithinCheckpoint (internally -1)
145
+ * - Vote duties only need slot (blockNumber is internally 0)
146
+ * - AUTH_REQUEST and TXS duties don't need slot/blockNumber (no HA protection needed)
75
147
  */
76
- export type CreateLocalSignerWithProtectionDeps = Omit<CreateHASignerDeps, 'pool'>;
148
+ export type SigningContext = HAProtectedSigningContext | NoHAProtectionSigningContext;
77
149
 
78
150
  /**
79
151
  * Database interface for slashing protection operations
@@ -9,23 +9,15 @@ import type { Buffer32 } from '@aztec/foundation/buffer';
9
9
  import { EthAddress } from '@aztec/foundation/eth-address';
10
10
  import type { Signature } from '@aztec/foundation/eth-signature';
11
11
  import { type Logger, createLogger } from '@aztec/foundation/log';
12
- import type { DateProvider } from '@aztec/foundation/timer';
12
+
13
+ import type { ValidatorHASignerConfig } from './config.js';
14
+ import { type DutyIdentifier, DutyType } from './db/types.js';
15
+ import { SlashingProtectionService } from './slashing_protection_service.js';
13
16
  import {
14
- type BaseSignerConfig,
15
- DutyType,
16
17
  type HAProtectedSigningContext,
18
+ type SlashingProtectionDatabase,
17
19
  getBlockNumberFromSigningContext,
18
- } from '@aztec/stdlib/ha-signing';
19
-
20
- import type { DutyIdentifier } from './db/types.js';
21
- import type { HASignerMetrics } from './metrics.js';
22
- import { SlashingProtectionService } from './slashing_protection_service.js';
23
- import type { SlashingProtectionDatabase } from './types.js';
24
-
25
- export interface ValidatorHASignerDeps {
26
- metrics: HASignerMetrics;
27
- dateProvider: DateProvider;
28
- }
20
+ } from './types.js';
29
21
 
30
22
  /**
31
23
  * Validator High Availability Signer
@@ -51,27 +43,22 @@ export class ValidatorHASigner {
51
43
  private readonly slashingProtection: SlashingProtectionService;
52
44
  private readonly rollupAddress: EthAddress;
53
45
 
54
- private readonly dateProvider: DateProvider;
55
- private readonly metrics: HASignerMetrics;
56
-
57
46
  constructor(
58
47
  db: SlashingProtectionDatabase,
59
- private readonly config: BaseSignerConfig,
60
- deps: ValidatorHASignerDeps,
48
+ private readonly config: ValidatorHASignerConfig,
61
49
  ) {
62
50
  this.log = createLogger('validator-ha-signer');
63
51
 
64
- this.metrics = deps.metrics;
65
- this.dateProvider = deps.dateProvider;
52
+ if (!config.haSigningEnabled) {
53
+ // this shouldn't happen, the validator should use different signer for non-HA setups
54
+ throw new Error('Validator HA Signer is not enabled in config');
55
+ }
66
56
 
67
57
  if (!config.nodeId || config.nodeId === '') {
68
58
  throw new Error('NODE_ID is required for high-availability setups');
69
59
  }
70
60
  this.rollupAddress = config.l1Contracts.rollupAddress;
71
- this.slashingProtection = new SlashingProtectionService(db, config, {
72
- metrics: deps.metrics,
73
- dateProvider: deps.dateProvider,
74
- });
61
+ this.slashingProtection = new SlashingProtectionService(db, config);
75
62
  this.log.info('Validator HA Signer initialized with slashing protection', {
76
63
  nodeId: config.nodeId,
77
64
  rollupAddress: this.rollupAddress.toString(),
@@ -101,9 +88,6 @@ export class ValidatorHASigner {
101
88
  context: HAProtectedSigningContext,
102
89
  signFn: (messageHash: Buffer32) => Promise<Signature>,
103
90
  ): Promise<Signature> {
104
- const startTime = this.dateProvider.now();
105
- const dutyType = context.dutyType;
106
-
107
91
  let dutyIdentifier: DutyIdentifier;
108
92
  if (context.dutyType === DutyType.BLOCK_PROPOSAL) {
109
93
  dutyIdentifier = {
@@ -123,7 +107,6 @@ export class ValidatorHASigner {
123
107
  }
124
108
 
125
109
  // Acquire lock and get the token for ownership verification
126
- // DutyAlreadySignedError and SlashingProtectionError may be thrown here and are recorded in the service
127
110
  const blockNumber = getBlockNumberFromSigningContext(context);
128
111
  const lockToken = await this.slashingProtection.checkAndRecord({
129
112
  ...dutyIdentifier,
@@ -139,7 +122,6 @@ export class ValidatorHASigner {
139
122
  } catch (error: any) {
140
123
  // Delete duty to allow retry (only succeeds if we own the lock)
141
124
  await this.slashingProtection.deleteDuty({ ...dutyIdentifier, lockToken });
142
- this.metrics.recordSigningError(dutyType);
143
125
  throw error;
144
126
  }
145
127
 
@@ -151,9 +133,6 @@ export class ValidatorHASigner {
151
133
  lockToken,
152
134
  });
153
135
 
154
- const duration = this.dateProvider.now() - startTime;
155
- this.metrics.recordSigningSuccess(dutyType, duration);
156
-
157
136
  return signature;
158
137
  }
159
138
 
package/dest/db/lmdb.d.ts DELETED
@@ -1,66 +0,0 @@
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 { EthAddress } from '@aztec/foundation/eth-address';
12
- import type { DateProvider } from '@aztec/foundation/timer';
13
- import type { AztecAsyncKVStore } from '@aztec/kv-store';
14
- import type { SlashingProtectionDatabase, TryInsertOrGetResult } from '../types.js';
15
- import { type CheckAndRecordParams, DutyType } from './types.js';
16
- /**
17
- * LMDB-backed implementation of SlashingProtectionDatabase.
18
- *
19
- * Provides single-node double-signing protection that survives crashes and restarts.
20
- * Does not provide cross-node coordination (that requires the PostgreSQL implementation).
21
- */
22
- export declare class LmdbSlashingProtectionDatabase implements SlashingProtectionDatabase {
23
- private readonly store;
24
- private readonly dateProvider;
25
- static readonly SCHEMA_VERSION = 1;
26
- private readonly duties;
27
- private readonly log;
28
- constructor(store: AztecAsyncKVStore, dateProvider: DateProvider);
29
- /**
30
- * Atomically try to insert a new duty record, or get the existing one if present.
31
- *
32
- * LMDB is single-writer so the read-then-write inside transactionAsync is naturally atomic.
33
- */
34
- tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult>;
35
- /**
36
- * Update a duty to 'signed' status with the signature.
37
- * Only succeeds if the lockToken matches.
38
- */
39
- updateDutySigned(rollupAddress: EthAddress, validatorAddress: EthAddress, slot: SlotNumber, dutyType: DutyType, signature: string, lockToken: string, blockIndexWithinCheckpoint: number): Promise<boolean>;
40
- /**
41
- * Delete a duty record.
42
- * Only succeeds if the lockToken matches.
43
- */
44
- deleteDuty(rollupAddress: EthAddress, validatorAddress: EthAddress, slot: SlotNumber, dutyType: DutyType, lockToken: string, blockIndexWithinCheckpoint: number): Promise<boolean>;
45
- /**
46
- * Cleanup own stuck duties (SIGNING status older than maxAgeMs).
47
- */
48
- cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
49
- /**
50
- * Cleanup duties with outdated rollup address.
51
- *
52
- * This is always a no-op for the LMDB implementation: the underlying store is created via
53
- * DatabaseVersionManager (in factory.ts), which already resets the entire data directory at
54
- * startup whenever the rollup address changes.
55
- */
56
- cleanupOutdatedRollupDuties(_currentRollupAddress: EthAddress): Promise<number>;
57
- /**
58
- * Cleanup old signed duties older than maxAgeMs.
59
- */
60
- cleanupOldDuties(maxAgeMs: number): Promise<number>;
61
- /**
62
- * Close the underlying LMDB store.
63
- */
64
- close(): Promise<void>;
65
- }
66
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG1kYi5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vc3JjL2RiL2xtZGIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7Ozs7O0dBUUc7QUFDSCxPQUFPLEVBQUUsVUFBVSxFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFFN0QsT0FBTyxFQUFFLFVBQVUsRUFBRSxNQUFNLCtCQUErQixDQUFDO0FBRTNELE9BQU8sS0FBSyxFQUFFLFlBQVksRUFBRSxNQUFNLHlCQUF5QixDQUFDO0FBQzVELE9BQU8sS0FBSyxFQUFFLGlCQUFpQixFQUFpQixNQUFNLGlCQUFpQixDQUFDO0FBRXhFLE9BQU8sS0FBSyxFQUFFLDBCQUEwQixFQUFFLG9CQUFvQixFQUFFLE1BQU0sYUFBYSxDQUFDO0FBQ3BGLE9BQU8sRUFDTCxLQUFLLG9CQUFvQixFQUV6QixRQUFRLEVBSVQsTUFBTSxZQUFZLENBQUM7QUFZcEI7Ozs7O0dBS0c7QUFDSCxxQkFBYSw4QkFBK0IsWUFBVywwQkFBMEI7SUFPN0UsT0FBTyxDQUFDLFFBQVEsQ0FBQyx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,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"}
package/dest/db/lmdb.js DELETED
@@ -1,188 +0,0 @@
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/foundation/crypto/random';
10
- import { createLogger } from '@aztec/foundation/log';
11
- import { DutyStatus, getBlockIndexFromDutyIdentifier, recordFromFields } from './types.js';
12
- function dutyKey(rollupAddress, validatorAddress, slot, dutyType, blockIndexWithinCheckpoint) {
13
- return `${rollupAddress}:${validatorAddress}:${slot}:${dutyType}:${blockIndexWithinCheckpoint}`;
14
- }
15
- /**
16
- * LMDB-backed implementation of SlashingProtectionDatabase.
17
- *
18
- * Provides single-node double-signing protection that survives crashes and restarts.
19
- * Does not provide cross-node coordination (that requires the PostgreSQL implementation).
20
- */ export class LmdbSlashingProtectionDatabase {
21
- store;
22
- dateProvider;
23
- static SCHEMA_VERSION = 1;
24
- duties;
25
- log;
26
- constructor(store, dateProvider){
27
- this.store = store;
28
- this.dateProvider = dateProvider;
29
- this.log = createLogger('slashing-protection:lmdb');
30
- this.duties = store.openMap('signing-protection-duties');
31
- }
32
- /**
33
- * Atomically try to insert a new duty record, or get the existing one if present.
34
- *
35
- * LMDB is single-writer so the read-then-write inside transactionAsync is naturally atomic.
36
- */ async tryInsertOrGetExisting(params) {
37
- const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
38
- const key = dutyKey(params.rollupAddress.toString(), params.validatorAddress.toString(), params.slot.toString(), params.dutyType, blockIndexWithinCheckpoint);
39
- const lockToken = randomBytes(16).toString('hex');
40
- const now = this.dateProvider.now();
41
- const result = await this.store.transactionAsync(async ()=>{
42
- const existing = await this.duties.getAsync(key);
43
- if (existing) {
44
- return {
45
- isNew: false,
46
- record: {
47
- ...existing,
48
- lockToken: ''
49
- }
50
- };
51
- }
52
- const newRecord = {
53
- rollupAddress: params.rollupAddress.toString(),
54
- validatorAddress: params.validatorAddress.toString(),
55
- slot: params.slot.toString(),
56
- blockNumber: params.blockNumber.toString(),
57
- blockIndexWithinCheckpoint,
58
- dutyType: params.dutyType,
59
- status: DutyStatus.SIGNING,
60
- messageHash: params.messageHash,
61
- nodeId: params.nodeId,
62
- lockToken,
63
- startedAtMs: now
64
- };
65
- await this.duties.set(key, newRecord);
66
- return {
67
- isNew: true,
68
- record: newRecord
69
- };
70
- });
71
- if (result.isNew) {
72
- this.log.debug(`Acquired lock for duty ${params.dutyType} at slot ${params.slot}`, {
73
- validatorAddress: params.validatorAddress.toString(),
74
- nodeId: params.nodeId
75
- });
76
- }
77
- return {
78
- isNew: result.isNew,
79
- record: recordFromFields(result.record)
80
- };
81
- }
82
- /**
83
- * Update a duty to 'signed' status with the signature.
84
- * Only succeeds if the lockToken matches.
85
- */ updateDutySigned(rollupAddress, validatorAddress, slot, dutyType, signature, lockToken, blockIndexWithinCheckpoint) {
86
- const key = dutyKey(rollupAddress.toString(), validatorAddress.toString(), slot.toString(), dutyType, blockIndexWithinCheckpoint);
87
- return this.store.transactionAsync(async ()=>{
88
- const existing = await this.duties.getAsync(key);
89
- if (!existing) {
90
- this.log.warn('Failed to update duty to signed: duty not found', {
91
- rollupAddress: rollupAddress.toString(),
92
- validatorAddress: validatorAddress.toString(),
93
- slot: slot.toString(),
94
- dutyType,
95
- blockIndexWithinCheckpoint
96
- });
97
- return false;
98
- }
99
- if (existing.lockToken !== lockToken) {
100
- this.log.warn('Failed to update duty to signed: invalid token', {
101
- rollupAddress: rollupAddress.toString(),
102
- validatorAddress: validatorAddress.toString(),
103
- slot: slot.toString(),
104
- dutyType,
105
- blockIndexWithinCheckpoint
106
- });
107
- return false;
108
- }
109
- await this.duties.set(key, {
110
- ...existing,
111
- status: DutyStatus.SIGNED,
112
- signature,
113
- completedAtMs: this.dateProvider.now()
114
- });
115
- return true;
116
- });
117
- }
118
- /**
119
- * Delete a duty record.
120
- * Only succeeds if the lockToken matches.
121
- */ deleteDuty(rollupAddress, validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint) {
122
- const key = dutyKey(rollupAddress.toString(), validatorAddress.toString(), slot.toString(), dutyType, blockIndexWithinCheckpoint);
123
- return this.store.transactionAsync(async ()=>{
124
- const existing = await this.duties.getAsync(key);
125
- if (!existing || existing.lockToken !== lockToken) {
126
- this.log.warn('Failed to delete duty: invalid token or duty not found', {
127
- rollupAddress: rollupAddress.toString(),
128
- validatorAddress: validatorAddress.toString(),
129
- slot: slot.toString(),
130
- dutyType,
131
- blockIndexWithinCheckpoint
132
- });
133
- return false;
134
- }
135
- await this.duties.delete(key);
136
- return true;
137
- });
138
- }
139
- /**
140
- * Cleanup own stuck duties (SIGNING status older than maxAgeMs).
141
- */ cleanupOwnStuckDuties(nodeId, maxAgeMs) {
142
- const cutoffMs = this.dateProvider.now() - maxAgeMs;
143
- return this.store.transactionAsync(async ()=>{
144
- const keysToDelete = [];
145
- for await (const [key, record] of this.duties.entriesAsync()){
146
- if (record.nodeId === nodeId && record.status === DutyStatus.SIGNING && record.startedAtMs < cutoffMs) {
147
- keysToDelete.push(key);
148
- }
149
- }
150
- for (const key of keysToDelete){
151
- await this.duties.delete(key);
152
- }
153
- return keysToDelete.length;
154
- });
155
- }
156
- /**
157
- * Cleanup duties with outdated rollup address.
158
- *
159
- * This is always a no-op for the LMDB implementation: the underlying store is created via
160
- * DatabaseVersionManager (in factory.ts), which already resets the entire data directory at
161
- * startup whenever the rollup address changes.
162
- */ cleanupOutdatedRollupDuties(_currentRollupAddress) {
163
- return Promise.resolve(0);
164
- }
165
- /**
166
- * Cleanup old signed duties older than maxAgeMs.
167
- */ cleanupOldDuties(maxAgeMs) {
168
- const cutoffMs = this.dateProvider.now() - maxAgeMs;
169
- return this.store.transactionAsync(async ()=>{
170
- const keysToDelete = [];
171
- for await (const [key, record] of this.duties.entriesAsync()){
172
- if (record.status === DutyStatus.SIGNED && record.completedAtMs !== undefined && record.completedAtMs < cutoffMs) {
173
- keysToDelete.push(key);
174
- }
175
- }
176
- for (const key of keysToDelete){
177
- await this.duties.delete(key);
178
- }
179
- return keysToDelete.length;
180
- });
181
- }
182
- /**
183
- * Close the underlying LMDB store.
184
- */ async close() {
185
- await this.store.close();
186
- this.log.debug('LMDB slashing protection database closed');
187
- }
188
- }