@aztec/validator-ha-signer 4.0.0-nightly.20260116 → 4.0.0-nightly.20260118

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 (42) hide show
  1. package/README.md +42 -37
  2. package/dest/config.d.ts +49 -17
  3. package/dest/config.d.ts.map +1 -1
  4. package/dest/config.js +28 -19
  5. package/dest/db/postgres.d.ts +10 -3
  6. package/dest/db/postgres.d.ts.map +1 -1
  7. package/dest/db/postgres.js +50 -19
  8. package/dest/db/schema.d.ts +11 -7
  9. package/dest/db/schema.d.ts.map +1 -1
  10. package/dest/db/schema.js +19 -7
  11. package/dest/db/types.d.ts +75 -23
  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 +9 -3
  24. package/dest/slashing_protection_service.d.ts.map +1 -1
  25. package/dest/slashing_protection_service.js +21 -9
  26. package/dest/types.d.ts +78 -14
  27. package/dest/types.d.ts.map +1 -1
  28. package/dest/types.js +21 -1
  29. package/dest/validator_ha_signer.d.ts +7 -11
  30. package/dest/validator_ha_signer.d.ts.map +1 -1
  31. package/dest/validator_ha_signer.js +25 -29
  32. package/package.json +6 -5
  33. package/src/config.ts +59 -50
  34. package/src/db/postgres.ts +57 -17
  35. package/src/db/schema.ts +19 -7
  36. package/src/db/types.ts +105 -21
  37. package/src/errors.ts +7 -2
  38. package/src/factory.ts +8 -13
  39. package/src/migrations.ts +17 -1
  40. package/src/slashing_protection_service.ts +46 -12
  41. package/src/types.ts +116 -19
  42. package/src/validator_ha_signer.ts +32 -39
@@ -8,9 +8,15 @@ 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
10
 
11
- import { type CheckAndRecordParams, type DeleteDutyParams, DutyStatus, type RecordSuccessParams } from './db/types.js';
11
+ import {
12
+ type CheckAndRecordParams,
13
+ type DeleteDutyParams,
14
+ DutyStatus,
15
+ type RecordSuccessParams,
16
+ getBlockIndexFromDutyIdentifier,
17
+ } from './db/types.js';
12
18
  import { DutyAlreadySignedError, SlashingProtectionError } from './errors.js';
13
- import type { SlashingProtectionConfig, SlashingProtectionDatabase } from './types.js';
19
+ import type { SlashingProtectionDatabase, ValidatorHASignerConfig } from './types.js';
14
20
 
15
21
  /**
16
22
  * Slashing Protection Service
@@ -31,21 +37,24 @@ export class SlashingProtectionService {
31
37
  private readonly log: Logger;
32
38
  private readonly pollingIntervalMs: number;
33
39
  private readonly signingTimeoutMs: number;
40
+ private readonly maxStuckDutiesAgeMs: number;
34
41
 
35
42
  private cleanupRunningPromise: RunningPromise;
36
43
 
37
44
  constructor(
38
45
  private readonly db: SlashingProtectionDatabase,
39
- private readonly config: SlashingProtectionConfig,
46
+ private readonly config: ValidatorHASignerConfig,
40
47
  ) {
41
48
  this.log = createLogger('slashing-protection');
42
49
  this.pollingIntervalMs = config.pollingIntervalMs;
43
50
  this.signingTimeoutMs = config.signingTimeoutMs;
51
+ // Default to 144s (2x 72s Aztec slot duration) if not explicitly configured
52
+ this.maxStuckDutiesAgeMs = config.maxStuckDutiesAgeMs ?? 144_000;
44
53
 
45
54
  this.cleanupRunningPromise = new RunningPromise(
46
55
  this.cleanupStuckDuties.bind(this),
47
56
  this.log,
48
- this.config.maxStuckDutiesAgeMs,
57
+ this.maxStuckDutiesAgeMs,
49
58
  );
50
59
  }
51
60
 
@@ -98,9 +107,16 @@ export class SlashingProtectionService {
98
107
  existingNodeId: record.nodeId,
99
108
  attemptingNodeId: nodeId,
100
109
  });
101
- throw new SlashingProtectionError(slot, dutyType, record.messageHash, messageHash);
110
+ throw new SlashingProtectionError(
111
+ slot,
112
+ dutyType,
113
+ record.blockIndexWithinCheckpoint,
114
+ record.messageHash,
115
+ messageHash,
116
+ record.nodeId,
117
+ );
102
118
  }
103
- throw new DutyAlreadySignedError(slot, dutyType, record.nodeId);
119
+ throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, record.nodeId);
104
120
  } else if (record.status === DutyStatus.SIGNING) {
105
121
  // Another node is currently signing - check for timeout
106
122
  if (Date.now() - startTime > this.signingTimeoutMs) {
@@ -109,7 +125,7 @@ export class SlashingProtectionService {
109
125
  timeoutMs: this.signingTimeoutMs,
110
126
  signingNodeId: record.nodeId,
111
127
  });
112
- throw new DutyAlreadySignedError(slot, dutyType, 'unknown (timeout)');
128
+ throw new DutyAlreadySignedError(slot, dutyType, record.blockIndexWithinCheckpoint, 'unknown (timeout)');
113
129
  }
114
130
 
115
131
  // Wait and poll
@@ -134,8 +150,16 @@ export class SlashingProtectionService {
134
150
  */
135
151
  async recordSuccess(params: RecordSuccessParams): Promise<boolean> {
136
152
  const { validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
137
-
138
- const success = await this.db.updateDutySigned(validatorAddress, slot, dutyType, signature.toString(), lockToken);
153
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
154
+
155
+ const success = await this.db.updateDutySigned(
156
+ validatorAddress,
157
+ slot,
158
+ dutyType,
159
+ signature.toString(),
160
+ lockToken,
161
+ blockIndexWithinCheckpoint,
162
+ );
139
163
 
140
164
  if (success) {
141
165
  this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
@@ -161,8 +185,9 @@ export class SlashingProtectionService {
161
185
  */
162
186
  async deleteDuty(params: DeleteDutyParams): Promise<boolean> {
163
187
  const { validatorAddress, slot, dutyType, lockToken } = params;
188
+ const blockIndexWithinCheckpoint = getBlockIndexFromDutyIdentifier(params);
164
189
 
165
- const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken);
190
+ const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken, blockIndexWithinCheckpoint);
166
191
 
167
192
  if (success) {
168
193
  this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
@@ -201,15 +226,24 @@ export class SlashingProtectionService {
201
226
  this.log.info('Slashing protection service stopped', { nodeId: this.config.nodeId });
202
227
  }
203
228
 
229
+ /**
230
+ * Close the database connection.
231
+ * Should be called after stop() during graceful shutdown.
232
+ */
233
+ async close() {
234
+ await this.db.close();
235
+ this.log.info('Slashing protection database connection closed');
236
+ }
237
+
204
238
  /**
205
239
  * Cleanup own stuck duties
206
240
  */
207
241
  private async cleanupStuckDuties() {
208
- const numDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.config.maxStuckDutiesAgeMs);
242
+ const numDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.maxStuckDutiesAgeMs);
209
243
  if (numDuties > 0) {
210
244
  this.log.info(`Cleaned up ${numDuties} stuck duties`, {
211
245
  nodeId: this.config.nodeId,
212
- maxStuckDutiesAgeMs: this.config.maxStuckDutiesAgeMs,
246
+ maxStuckDutiesAgeMs: this.maxStuckDutiesAgeMs,
213
247
  });
214
248
  }
215
249
  }
package/src/types.ts CHANGED
@@ -1,27 +1,31 @@
1
+ import { BlockNumber, type CheckpointNumber, type SlotNumber } from '@aztec/foundation/branded-types';
1
2
  import type { EthAddress } from '@aztec/foundation/eth-address';
2
3
 
3
4
  import type { Pool } from 'pg';
4
5
 
5
- import type { CreateHASignerConfig, SlashingProtectionConfig } from './config.js';
6
- import type {
7
- CheckAndRecordParams,
8
- DeleteDutyParams,
9
- DutyIdentifier,
6
+ import type { ValidatorHASignerConfig } from './config.js';
7
+ import {
8
+ type BlockProposalDutyIdentifier,
9
+ type CheckAndRecordParams,
10
+ type DeleteDutyParams,
11
+ type DutyIdentifier,
10
12
  DutyType,
11
- RecordSuccessParams,
12
- ValidatorDutyRecord,
13
+ type OtherDutyIdentifier,
14
+ type RecordSuccessParams,
15
+ type ValidatorDutyRecord,
13
16
  } from './db/types.js';
14
17
 
15
18
  export type {
19
+ BlockProposalDutyIdentifier,
16
20
  CheckAndRecordParams,
17
- CreateHASignerConfig,
18
21
  DeleteDutyParams,
19
22
  DutyIdentifier,
23
+ OtherDutyIdentifier,
20
24
  RecordSuccessParams,
21
- SlashingProtectionConfig,
22
25
  ValidatorDutyRecord,
26
+ ValidatorHASignerConfig,
23
27
  };
24
- export { DutyStatus, DutyType } from './db/types.js';
28
+ export { DutyStatus, DutyType, getBlockIndexFromDutyIdentifier, normalizeBlockIndex } from './db/types.js';
25
29
 
26
30
  /**
27
31
  * Result of tryInsertOrGetExisting operation
@@ -45,17 +49,97 @@ export interface CreateHASignerDeps {
45
49
  }
46
50
 
47
51
  /**
48
- * Context required for slashing protection during signing operations
52
+ * Base context for signing operations
49
53
  */
50
- export interface SigningContext {
54
+ interface BaseSigningContext {
51
55
  /** Slot number for this duty */
52
- slot: bigint;
53
- /** Block number for this duty */
54
- blockNumber: bigint;
55
- /** Type of duty being performed */
56
- dutyType: DutyType;
56
+ slot: SlotNumber;
57
+ /**
58
+ * Block or checkpoint number for this duty.
59
+ * For block proposals, this is the block number.
60
+ * For checkpoint proposals, this is the checkpoint number.
61
+ */
62
+ blockNumber: BlockNumber | CheckpointNumber;
63
+ }
64
+
65
+ /**
66
+ * Signing context for block proposals.
67
+ * blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
68
+ */
69
+ export interface BlockProposalSigningContext extends BaseSigningContext {
70
+ /** Block index within checkpoint (0, 1, 2...). Required for block proposals. */
71
+ blockIndexWithinCheckpoint: number;
72
+ dutyType: DutyType.BLOCK_PROPOSAL;
73
+ }
74
+
75
+ /**
76
+ * Signing context for non-block-proposal duties that require HA protection.
77
+ * blockIndexWithinCheckpoint is not applicable (internally always -1).
78
+ */
79
+ export interface OtherSigningContext extends BaseSigningContext {
80
+ dutyType: DutyType.CHECKPOINT_PROPOSAL | DutyType.ATTESTATION | DutyType.ATTESTATIONS_AND_SIGNERS;
81
+ }
82
+
83
+ /**
84
+ * Signing context for governance/slashing votes which only need slot for HA protection.
85
+ * blockNumber is not applicable (internally always 0).
86
+ */
87
+ export interface VoteSigningContext {
88
+ slot: SlotNumber;
89
+ dutyType: DutyType.GOVERNANCE_VOTE | DutyType.SLASHING_VOTE;
90
+ }
91
+
92
+ /**
93
+ * Signing context for duties which don't require slot/blockNumber
94
+ * as they don't need HA protection (AUTH_REQUEST, TXS).
95
+ */
96
+ export interface NoHAProtectionSigningContext {
97
+ dutyType: DutyType.AUTH_REQUEST | DutyType.TXS;
98
+ }
99
+
100
+ /**
101
+ * Signing contexts that require HA protection (excludes AUTH_REQUEST).
102
+ * Used by the HA signer's signWithProtection method.
103
+ */
104
+ export type HAProtectedSigningContext = BlockProposalSigningContext | OtherSigningContext | VoteSigningContext;
105
+
106
+ /**
107
+ * Type guard to check if a SigningContext requires HA protection.
108
+ * Returns true for contexts that need HA protection, false for AUTH_REQUEST and TXS.
109
+ */
110
+ export function isHAProtectedContext(context: SigningContext): context is HAProtectedSigningContext {
111
+ return context.dutyType !== DutyType.AUTH_REQUEST && context.dutyType !== DutyType.TXS;
112
+ }
113
+
114
+ /**
115
+ * Gets the block number from a signing context.
116
+ * - Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE): returns BlockNumber(0)
117
+ * - Other duties: returns the blockNumber from the context
118
+ */
119
+ export function getBlockNumberFromSigningContext(context: HAProtectedSigningContext): BlockNumber | CheckpointNumber {
120
+ // Check for duty types that have blockNumber
121
+ if (
122
+ context.dutyType === DutyType.BLOCK_PROPOSAL ||
123
+ context.dutyType === DutyType.CHECKPOINT_PROPOSAL ||
124
+ context.dutyType === DutyType.ATTESTATION ||
125
+ context.dutyType === DutyType.ATTESTATIONS_AND_SIGNERS
126
+ ) {
127
+ return context.blockNumber;
128
+ }
129
+ // Vote duties (GOVERNANCE_VOTE, SLASHING_VOTE) don't have blockNumber
130
+ return BlockNumber(0);
57
131
  }
58
132
 
133
+ /**
134
+ * Context required for slashing protection during signing operations.
135
+ * Uses discriminated union to enforce type safety:
136
+ * - BLOCK_PROPOSAL duties MUST have blockIndexWithinCheckpoint >= 0
137
+ * - Other duty types do NOT have blockIndexWithinCheckpoint (internally -1)
138
+ * - Vote duties only need slot (blockNumber is internally 0)
139
+ * - AUTH_REQUEST and TXS duties don't need slot/blockNumber (no HA protection needed)
140
+ */
141
+ export type SigningContext = HAProtectedSigningContext | NoHAProtectionSigningContext;
142
+
59
143
  /**
60
144
  * Database interface for slashing protection operations
61
145
  * This abstraction allows for different database implementations (PostgreSQL, SQLite, etc.)
@@ -82,10 +166,11 @@ export interface SlashingProtectionDatabase {
82
166
  */
83
167
  updateDutySigned(
84
168
  validatorAddress: EthAddress,
85
- slot: bigint,
169
+ slot: SlotNumber,
86
170
  dutyType: DutyType,
87
171
  signature: string,
88
172
  lockToken: string,
173
+ blockIndexWithinCheckpoint: number,
89
174
  ): Promise<boolean>;
90
175
 
91
176
  /**
@@ -95,11 +180,23 @@ export interface SlashingProtectionDatabase {
95
180
  *
96
181
  * @returns true if the delete succeeded, false if token didn't match or duty not found
97
182
  */
98
- deleteDuty(validatorAddress: EthAddress, slot: bigint, dutyType: DutyType, lockToken: string): Promise<boolean>;
183
+ deleteDuty(
184
+ validatorAddress: EthAddress,
185
+ slot: SlotNumber,
186
+ dutyType: DutyType,
187
+ lockToken: string,
188
+ blockIndexWithinCheckpoint: number,
189
+ ): Promise<boolean>;
99
190
 
100
191
  /**
101
192
  * Cleanup own stuck duties
102
193
  * @returns the number of duties cleaned up
103
194
  */
104
195
  cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
196
+
197
+ /**
198
+ * Close the database connection.
199
+ * Should be called during graceful shutdown.
200
+ */
201
+ close(): Promise<void>;
105
202
  }
@@ -10,9 +10,14 @@ import type { 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
12
 
13
- import type { CreateHASignerConfig } from './config.js';
13
+ import type { ValidatorHASignerConfig } from './config.js';
14
+ import { type DutyIdentifier, DutyType } from './db/types.js';
14
15
  import { SlashingProtectionService } from './slashing_protection_service.js';
15
- import type { SigningContext, SlashingProtectionDatabase } from './types.js';
16
+ import {
17
+ type HAProtectedSigningContext,
18
+ type SlashingProtectionDatabase,
19
+ getBlockNumberFromSigningContext,
20
+ } from './types.js';
16
21
 
17
22
  /**
18
23
  * Validator High Availability Signer
@@ -35,15 +40,15 @@ import type { SigningContext, SlashingProtectionDatabase } from './types.js';
35
40
  */
36
41
  export class ValidatorHASigner {
37
42
  private readonly log: Logger;
38
- private readonly slashingProtection: SlashingProtectionService | undefined;
43
+ private readonly slashingProtection: SlashingProtectionService;
39
44
 
40
45
  constructor(
41
46
  db: SlashingProtectionDatabase,
42
- private readonly config: CreateHASignerConfig,
47
+ private readonly config: ValidatorHASignerConfig,
43
48
  ) {
44
49
  this.log = createLogger('validator-ha-signer');
45
50
 
46
- if (!config.enabled) {
51
+ if (!config.haSigningEnabled) {
47
52
  // this shouldn't happen, the validator should use different signer for non-HA setups
48
53
  throw new Error('Validator HA Signer is not enabled in config');
49
54
  }
@@ -67,7 +72,7 @@ export class ValidatorHASigner {
67
72
  *
68
73
  * @param validatorAddress - The validator's Ethereum address
69
74
  * @param messageHash - The hash to be signed
70
- * @param context - The signing context (slot, block number, duty type)
75
+ * @param context - The signing context (HA-protected duty types only)
71
76
  * @param signFn - Function that performs the actual signing
72
77
  * @returns The signature
73
78
  *
@@ -77,29 +82,30 @@ export class ValidatorHASigner {
77
82
  async signWithProtection(
78
83
  validatorAddress: EthAddress,
79
84
  messageHash: Buffer32,
80
- context: SigningContext,
85
+ context: HAProtectedSigningContext,
81
86
  signFn: (messageHash: Buffer32) => Promise<Signature>,
82
87
  ): Promise<Signature> {
83
- // If slashing protection is disabled, just sign directly
84
- if (!this.slashingProtection) {
85
- this.log.info('Signing without slashing protection enabled', {
86
- validatorAddress: validatorAddress.toString(),
87
- nodeId: this.config.nodeId,
88
+ let dutyIdentifier: DutyIdentifier;
89
+ if (context.dutyType === DutyType.BLOCK_PROPOSAL) {
90
+ dutyIdentifier = {
91
+ validatorAddress,
92
+ slot: context.slot,
93
+ blockIndexWithinCheckpoint: context.blockIndexWithinCheckpoint,
88
94
  dutyType: context.dutyType,
95
+ };
96
+ } else {
97
+ dutyIdentifier = {
98
+ validatorAddress,
89
99
  slot: context.slot,
90
- blockNumber: context.blockNumber,
91
- });
92
- return await signFn(messageHash);
100
+ dutyType: context.dutyType,
101
+ };
93
102
  }
94
103
 
95
- const { slot, blockNumber, dutyType } = context;
96
-
97
104
  // Acquire lock and get the token for ownership verification
105
+ const blockNumber = getBlockNumberFromSigningContext(context);
98
106
  const lockToken = await this.slashingProtection.checkAndRecord({
99
- validatorAddress,
100
- slot,
107
+ ...dutyIdentifier,
101
108
  blockNumber,
102
- dutyType,
103
109
  messageHash: messageHash.toString(),
104
110
  nodeId: this.config.nodeId,
105
111
  });
@@ -110,20 +116,13 @@ export class ValidatorHASigner {
110
116
  signature = await signFn(messageHash);
111
117
  } catch (error: any) {
112
118
  // Delete duty to allow retry (only succeeds if we own the lock)
113
- await this.slashingProtection.deleteDuty({
114
- validatorAddress,
115
- slot,
116
- dutyType,
117
- lockToken,
118
- });
119
+ await this.slashingProtection.deleteDuty({ ...dutyIdentifier, lockToken });
119
120
  throw error;
120
121
  }
121
122
 
122
123
  // Record success (only succeeds if we own the lock)
123
124
  await this.slashingProtection.recordSuccess({
124
- validatorAddress,
125
- slot,
126
- dutyType,
125
+ ...dutyIdentifier,
127
126
  signature,
128
127
  nodeId: this.config.nodeId,
129
128
  lockToken,
@@ -132,13 +131,6 @@ export class ValidatorHASigner {
132
131
  return signature;
133
132
  }
134
133
 
135
- /**
136
- * Check if slashing protection is enabled
137
- */
138
- get isEnabled(): boolean {
139
- return this.slashingProtection !== undefined;
140
- }
141
-
142
134
  /**
143
135
  * Get the node ID for this signer
144
136
  */
@@ -151,14 +143,15 @@ export class ValidatorHASigner {
151
143
  * Should be called after construction and before signing operations.
152
144
  */
153
145
  start() {
154
- this.slashingProtection?.start();
146
+ this.slashingProtection.start();
155
147
  }
156
148
 
157
149
  /**
158
- * Stop the HA signer background tasks.
150
+ * Stop the HA signer background tasks and close database connection.
159
151
  * Should be called during graceful shutdown.
160
152
  */
161
153
  async stop() {
162
- await this.slashingProtection?.stop();
154
+ await this.slashingProtection.stop();
155
+ await this.slashingProtection.close();
163
156
  }
164
157
  }