@aztec/validator-ha-signer 4.0.0-nightly.20260110

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 (54) hide show
  1. package/README.md +182 -0
  2. package/dest/config.d.ts +47 -0
  3. package/dest/config.d.ts.map +1 -0
  4. package/dest/config.js +64 -0
  5. package/dest/db/index.d.ts +4 -0
  6. package/dest/db/index.d.ts.map +1 -0
  7. package/dest/db/index.js +3 -0
  8. package/dest/db/migrations/1_initial-schema.d.ts +9 -0
  9. package/dest/db/migrations/1_initial-schema.d.ts.map +1 -0
  10. package/dest/db/migrations/1_initial-schema.js +20 -0
  11. package/dest/db/postgres.d.ts +55 -0
  12. package/dest/db/postgres.d.ts.map +1 -0
  13. package/dest/db/postgres.js +150 -0
  14. package/dest/db/schema.d.ts +85 -0
  15. package/dest/db/schema.d.ts.map +1 -0
  16. package/dest/db/schema.js +201 -0
  17. package/dest/db/test_helper.d.ts +10 -0
  18. package/dest/db/test_helper.d.ts.map +1 -0
  19. package/dest/db/test_helper.js +14 -0
  20. package/dest/db/types.d.ts +109 -0
  21. package/dest/db/types.d.ts.map +1 -0
  22. package/dest/db/types.js +15 -0
  23. package/dest/errors.d.ts +30 -0
  24. package/dest/errors.d.ts.map +1 -0
  25. package/dest/errors.js +31 -0
  26. package/dest/factory.d.ts +50 -0
  27. package/dest/factory.d.ts.map +1 -0
  28. package/dest/factory.js +75 -0
  29. package/dest/migrations.d.ts +15 -0
  30. package/dest/migrations.d.ts.map +1 -0
  31. package/dest/migrations.js +42 -0
  32. package/dest/slashing_protection_service.d.ts +74 -0
  33. package/dest/slashing_protection_service.d.ts.map +1 -0
  34. package/dest/slashing_protection_service.js +184 -0
  35. package/dest/types.d.ts +75 -0
  36. package/dest/types.d.ts.map +1 -0
  37. package/dest/types.js +1 -0
  38. package/dest/validator_ha_signer.d.ts +74 -0
  39. package/dest/validator_ha_signer.d.ts.map +1 -0
  40. package/dest/validator_ha_signer.js +131 -0
  41. package/package.json +105 -0
  42. package/src/config.ts +116 -0
  43. package/src/db/index.ts +3 -0
  44. package/src/db/migrations/1_initial-schema.ts +26 -0
  45. package/src/db/postgres.ts +202 -0
  46. package/src/db/schema.ts +236 -0
  47. package/src/db/test_helper.ts +17 -0
  48. package/src/db/types.ts +117 -0
  49. package/src/errors.ts +42 -0
  50. package/src/factory.ts +87 -0
  51. package/src/migrations.ts +59 -0
  52. package/src/slashing_protection_service.ts +216 -0
  53. package/src/types.ts +105 -0
  54. package/src/validator_ha_signer.ts +164 -0
@@ -0,0 +1,74 @@
1
+ import { type CheckAndRecordParams, type DeleteDutyParams, type RecordSuccessParams } from './db/types.js';
2
+ import type { SlashingProtectionConfig, SlashingProtectionDatabase } from './types.js';
3
+ /**
4
+ * Slashing Protection Service
5
+ *
6
+ * This service ensures that a validator only signs one block/attestation per slot,
7
+ * even when running multiple redundant nodes (HA setup).
8
+ *
9
+ * All nodes in the HA setup try to sign - the first one wins, others get
10
+ * DutyAlreadySignedError (normal) or SlashingProtectionError (if different data).
11
+ *
12
+ * Flow:
13
+ * 1. checkAndRecord() - Atomically try to acquire lock via tryInsertOrGetExisting
14
+ * 2. Caller performs the signing operation
15
+ * 3. recordSuccess() - Update to 'signed' status with signature
16
+ * OR deleteDuty() - Delete the record to allow retry
17
+ */
18
+ export declare class SlashingProtectionService {
19
+ private readonly db;
20
+ private readonly config;
21
+ private readonly log;
22
+ private readonly pollingIntervalMs;
23
+ private readonly signingTimeoutMs;
24
+ private cleanupRunningPromise;
25
+ constructor(db: SlashingProtectionDatabase, config: SlashingProtectionConfig);
26
+ /**
27
+ * Check if a duty can be performed and acquire the lock if so.
28
+ *
29
+ * This method uses an atomic insert-or-get operation.
30
+ * It will:
31
+ * 1. Try to insert a new record with 'signing' status
32
+ * 2. If insert succeeds, we acquired the lock - return the lockToken
33
+ * 3. If a record exists, handle based on status:
34
+ * - SIGNED: Throw appropriate error (already signed or slashing protection)
35
+ * - FAILED: Delete the failed record
36
+ * - SIGNING: Wait and poll until status changes, then handle result
37
+ *
38
+ * @returns The lockToken that must be used for recordSuccess/deleteDuty
39
+ * @throws DutyAlreadySignedError if the duty was already completed
40
+ * @throws SlashingProtectionError if attempting to sign different data for same slot/duty
41
+ */
42
+ checkAndRecord(params: CheckAndRecordParams): Promise<string>;
43
+ /**
44
+ * Record a successful signing operation.
45
+ * Updates the duty status to 'signed' and stores the signature.
46
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
47
+ *
48
+ * @returns true if the update succeeded, false if token didn't match
49
+ */
50
+ recordSuccess(params: RecordSuccessParams): Promise<boolean>;
51
+ /**
52
+ * Delete a duty record after a failed signing operation.
53
+ * Removes the record to allow another node/attempt to retry.
54
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
55
+ *
56
+ * @returns true if the delete succeeded, false if token didn't match
57
+ */
58
+ deleteDuty(params: DeleteDutyParams): Promise<boolean>;
59
+ /**
60
+ * Get the node ID for this service
61
+ */
62
+ get nodeId(): string;
63
+ /**
64
+ * Start running tasks.
65
+ * Cleanup runs immediately on start to recover from any previous crashes.
66
+ */
67
+ start(): void;
68
+ /**
69
+ * Stop the background cleanup task.
70
+ */
71
+ stop(): Promise<void>;
72
+ private cleanupStuckDuties;
73
+ }
74
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2xhc2hpbmdfcHJvdGVjdGlvbl9zZXJ2aWNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvc2xhc2hpbmdfcHJvdGVjdGlvbl9zZXJ2aWNlLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQVVBLE9BQU8sRUFBRSxLQUFLLG9CQUFvQixFQUFFLEtBQUssZ0JBQWdCLEVBQWMsS0FBSyxtQkFBbUIsRUFBRSxNQUFNLGVBQWUsQ0FBQztBQUV2SCxPQUFPLEtBQUssRUFBRSx3QkFBd0IsRUFBRSwwQkFBMEIsRUF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AK,gBAAgB,EAAc,KAAK,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAEvH,OAAO,KAAK,EAAE,wBAAwB,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AAEvF;;;;;;;;;;;;;;GAcG;AACH,qBAAa,yBAAyB;IAQlC,OAAO,CAAC,QAAQ,CAAC,EAAE;IACnB,OAAO,CAAC,QAAQ,CAAC,MAAM;IARzB,OAAO,CAAC,QAAQ,CAAC,GAAG,CAAS;IAC7B,OAAO,CAAC,QAAQ,CAAC,iBAAiB,CAAS;IAC3C,OAAO,CAAC,QAAQ,CAAC,gBAAgB,CAAS;IAE1C,OAAO,CAAC,qBAAqB,CAAiB;IAE9C,YACmB,EAAE,EAAE,0BAA0B,EAC9B,MAAM,EAAE,wBAAwB,EAWlD;IAED;;;;;;;;;;;;;;;OAeG;IACG,cAAc,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,MAAM,CAAC,CA0DlE;IAED;;;;;;OAMG;IACG,aAAa,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,OAAO,CAAC,CAkBjE;IAED;;;;;;OAMG;IACG,UAAU,CAAC,MAAM,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAgB3D;IAED;;OAEG;IACH,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED;;;OAGG;IACH,KAAK,SAGJ;IAED;;OAEG;IACG,IAAI,kBAGT;YAKa,kBAAkB;CASjC"}
@@ -0,0 +1,184 @@
1
+ /**
2
+ * Slashing Protection Service
3
+ *
4
+ * Provides distributed locking and slashing protection for validator duties.
5
+ * Uses an external database to coordinate across multiple validator nodes.
6
+ */ import { createLogger } from '@aztec/foundation/log';
7
+ import { RunningPromise } from '@aztec/foundation/promise';
8
+ import { sleep } from '@aztec/foundation/sleep';
9
+ import { DutyStatus } from './db/types.js';
10
+ import { DutyAlreadySignedError, SlashingProtectionError } from './errors.js';
11
+ /**
12
+ * Slashing Protection Service
13
+ *
14
+ * This service ensures that a validator only signs one block/attestation per slot,
15
+ * even when running multiple redundant nodes (HA setup).
16
+ *
17
+ * All nodes in the HA setup try to sign - the first one wins, others get
18
+ * DutyAlreadySignedError (normal) or SlashingProtectionError (if different data).
19
+ *
20
+ * Flow:
21
+ * 1. checkAndRecord() - Atomically try to acquire lock via tryInsertOrGetExisting
22
+ * 2. Caller performs the signing operation
23
+ * 3. recordSuccess() - Update to 'signed' status with signature
24
+ * OR deleteDuty() - Delete the record to allow retry
25
+ */ export class SlashingProtectionService {
26
+ db;
27
+ config;
28
+ log;
29
+ pollingIntervalMs;
30
+ signingTimeoutMs;
31
+ cleanupRunningPromise;
32
+ constructor(db, config){
33
+ this.db = db;
34
+ this.config = config;
35
+ this.log = createLogger('slashing-protection');
36
+ this.pollingIntervalMs = config.pollingIntervalMs;
37
+ this.signingTimeoutMs = config.signingTimeoutMs;
38
+ this.cleanupRunningPromise = new RunningPromise(this.cleanupStuckDuties.bind(this), this.log, this.config.maxStuckDutiesAgeMs);
39
+ }
40
+ /**
41
+ * Check if a duty can be performed and acquire the lock if so.
42
+ *
43
+ * This method uses an atomic insert-or-get operation.
44
+ * It will:
45
+ * 1. Try to insert a new record with 'signing' status
46
+ * 2. If insert succeeds, we acquired the lock - return the lockToken
47
+ * 3. If a record exists, handle based on status:
48
+ * - SIGNED: Throw appropriate error (already signed or slashing protection)
49
+ * - FAILED: Delete the failed record
50
+ * - SIGNING: Wait and poll until status changes, then handle result
51
+ *
52
+ * @returns The lockToken that must be used for recordSuccess/deleteDuty
53
+ * @throws DutyAlreadySignedError if the duty was already completed
54
+ * @throws SlashingProtectionError if attempting to sign different data for same slot/duty
55
+ */ async checkAndRecord(params) {
56
+ const { validatorAddress, slot, dutyType, messageHash, nodeId } = params;
57
+ const startTime = Date.now();
58
+ this.log.debug(`Checking duty: ${dutyType} for slot ${slot}`, {
59
+ validatorAddress: validatorAddress.toString(),
60
+ nodeId
61
+ });
62
+ while(true){
63
+ // insert if not present, get existing if present
64
+ const { isNew, record } = await this.db.tryInsertOrGetExisting(params);
65
+ if (isNew) {
66
+ // We successfully acquired the lock
67
+ this.log.info(`Acquired lock for duty ${dutyType} at slot ${slot}`, {
68
+ validatorAddress: validatorAddress.toString(),
69
+ nodeId
70
+ });
71
+ return record.lockToken;
72
+ }
73
+ // Record already exists - handle based on status
74
+ if (record.status === DutyStatus.SIGNED) {
75
+ // Duty was already signed - check if same or different data
76
+ if (record.messageHash !== messageHash) {
77
+ this.log.verbose(`Slashing protection triggered for duty ${dutyType} at slot ${slot}`, {
78
+ validatorAddress: validatorAddress.toString(),
79
+ existingMessageHash: record.messageHash,
80
+ attemptedMessageHash: messageHash,
81
+ existingNodeId: record.nodeId,
82
+ attemptingNodeId: nodeId
83
+ });
84
+ throw new SlashingProtectionError(slot, dutyType, record.messageHash, messageHash);
85
+ }
86
+ throw new DutyAlreadySignedError(slot, dutyType, record.nodeId);
87
+ } else if (record.status === DutyStatus.SIGNING) {
88
+ // Another node is currently signing - check for timeout
89
+ if (Date.now() - startTime > this.signingTimeoutMs) {
90
+ this.log.warn(`Timeout waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
91
+ validatorAddress: validatorAddress.toString(),
92
+ timeoutMs: this.signingTimeoutMs,
93
+ signingNodeId: record.nodeId
94
+ });
95
+ throw new DutyAlreadySignedError(slot, dutyType, 'unknown (timeout)');
96
+ }
97
+ // Wait and poll
98
+ this.log.debug(`Waiting for signing to complete for duty ${dutyType} at slot ${slot}`, {
99
+ validatorAddress: validatorAddress.toString(),
100
+ signingNodeId: record.nodeId
101
+ });
102
+ await sleep(this.pollingIntervalMs);
103
+ // Loop continues - next iteration will check status again
104
+ } else {
105
+ throw new Error(`Unknown duty status: ${record.status}`);
106
+ }
107
+ }
108
+ }
109
+ /**
110
+ * Record a successful signing operation.
111
+ * Updates the duty status to 'signed' and stores the signature.
112
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
113
+ *
114
+ * @returns true if the update succeeded, false if token didn't match
115
+ */ async recordSuccess(params) {
116
+ const { validatorAddress, slot, dutyType, signature, nodeId, lockToken } = params;
117
+ const success = await this.db.updateDutySigned(validatorAddress, slot, dutyType, signature.toString(), lockToken);
118
+ if (success) {
119
+ this.log.info(`Recorded successful signing for duty ${dutyType} at slot ${slot}`, {
120
+ validatorAddress: validatorAddress.toString(),
121
+ nodeId
122
+ });
123
+ } else {
124
+ this.log.warn(`Failed to record successful signing for duty ${dutyType} at slot ${slot}: invalid token`, {
125
+ validatorAddress: validatorAddress.toString(),
126
+ nodeId
127
+ });
128
+ }
129
+ return success;
130
+ }
131
+ /**
132
+ * Delete a duty record after a failed signing operation.
133
+ * Removes the record to allow another node/attempt to retry.
134
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
135
+ *
136
+ * @returns true if the delete succeeded, false if token didn't match
137
+ */ async deleteDuty(params) {
138
+ const { validatorAddress, slot, dutyType, lockToken } = params;
139
+ const success = await this.db.deleteDuty(validatorAddress, slot, dutyType, lockToken);
140
+ if (success) {
141
+ this.log.info(`Deleted duty ${dutyType} at slot ${slot} to allow retry`, {
142
+ validatorAddress: validatorAddress.toString()
143
+ });
144
+ } else {
145
+ this.log.warn(`Failed to delete duty ${dutyType} at slot ${slot}: invalid token`, {
146
+ validatorAddress: validatorAddress.toString()
147
+ });
148
+ }
149
+ return success;
150
+ }
151
+ /**
152
+ * Get the node ID for this service
153
+ */ get nodeId() {
154
+ return this.config.nodeId;
155
+ }
156
+ /**
157
+ * Start running tasks.
158
+ * Cleanup runs immediately on start to recover from any previous crashes.
159
+ */ start() {
160
+ this.cleanupRunningPromise.start();
161
+ this.log.info('Slashing protection service started', {
162
+ nodeId: this.config.nodeId
163
+ });
164
+ }
165
+ /**
166
+ * Stop the background cleanup task.
167
+ */ async stop() {
168
+ await this.cleanupRunningPromise.stop();
169
+ this.log.info('Slashing protection service stopped', {
170
+ nodeId: this.config.nodeId
171
+ });
172
+ }
173
+ /**
174
+ * Cleanup own stuck duties
175
+ */ async cleanupStuckDuties() {
176
+ const numDuties = await this.db.cleanupOwnStuckDuties(this.config.nodeId, this.config.maxStuckDutiesAgeMs);
177
+ if (numDuties > 0) {
178
+ this.log.info(`Cleaned up ${numDuties} stuck duties`, {
179
+ nodeId: this.config.nodeId,
180
+ maxStuckDutiesAgeMs: this.config.maxStuckDutiesAgeMs
181
+ });
182
+ }
183
+ }
184
+ }
@@ -0,0 +1,75 @@
1
+ import type { EthAddress } from '@aztec/foundation/eth-address';
2
+ import type { Pool } from 'pg';
3
+ import type { CreateHASignerConfig, SlashingProtectionConfig } from './config.js';
4
+ import type { CheckAndRecordParams, DeleteDutyParams, DutyIdentifier, DutyType, RecordSuccessParams, ValidatorDutyRecord } from './db/types.js';
5
+ export type { CheckAndRecordParams, CreateHASignerConfig, DeleteDutyParams, DutyIdentifier, RecordSuccessParams, SlashingProtectionConfig, ValidatorDutyRecord, };
6
+ export { DutyStatus, DutyType } from './db/types.js';
7
+ /**
8
+ * Result of tryInsertOrGetExisting operation
9
+ */
10
+ export interface TryInsertOrGetResult {
11
+ /** True if we inserted a new record, false if we got an existing record */
12
+ isNew: boolean;
13
+ /** The record (either newly inserted or existing) */
14
+ record: ValidatorDutyRecord;
15
+ }
16
+ /**
17
+ * deps for creating an HA signer
18
+ */
19
+ export interface CreateHASignerDeps {
20
+ /**
21
+ * Optional PostgreSQL connection pool
22
+ * If provided, databaseUrl and poolConfig are ignored
23
+ */
24
+ pool?: Pool;
25
+ }
26
+ /**
27
+ * Context required for slashing protection during signing operations
28
+ */
29
+ export interface SigningContext {
30
+ /** Slot number for this duty */
31
+ slot: bigint;
32
+ /** Block number for this duty */
33
+ blockNumber: bigint;
34
+ /** Type of duty being performed */
35
+ dutyType: DutyType;
36
+ }
37
+ /**
38
+ * Database interface for slashing protection operations
39
+ * This abstraction allows for different database implementations (PostgreSQL, SQLite, etc.)
40
+ *
41
+ * The interface is designed around 3 core operations:
42
+ * 1. tryInsertOrGetExisting - Atomically insert or get existing record (eliminates race conditions)
43
+ * 2. updateDutySigned - Update to signed status on success
44
+ * 3. deleteDuty - Delete a duty record on failure
45
+ */
46
+ export interface SlashingProtectionDatabase {
47
+ /**
48
+ * Atomically try to insert a new duty record, or get the existing one if present.
49
+ *
50
+ * @returns { isNew: true, record } if we successfully inserted and acquired the lock
51
+ * @returns { isNew: false, record } if a record already exists (caller should handle based on status)
52
+ */
53
+ tryInsertOrGetExisting(params: CheckAndRecordParams): Promise<TryInsertOrGetResult>;
54
+ /**
55
+ * Update a duty to 'signed' status with the signature.
56
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
57
+ *
58
+ * @returns true if the update succeeded, false if token didn't match or duty not found
59
+ */
60
+ updateDutySigned(validatorAddress: EthAddress, slot: bigint, dutyType: DutyType, signature: string, lockToken: string): Promise<boolean>;
61
+ /**
62
+ * Delete a duty record.
63
+ * Only succeeds if the lockToken matches (caller must be the one who created the duty).
64
+ * Used when signing fails to allow another node/attempt to retry.
65
+ *
66
+ * @returns true if the delete succeeded, false if token didn't match or duty not found
67
+ */
68
+ deleteDuty(validatorAddress: EthAddress, slot: bigint, dutyType: DutyType, lockToken: string): Promise<boolean>;
69
+ /**
70
+ * Cleanup own stuck duties
71
+ * @returns the number of duties cleaned up
72
+ */
73
+ cleanupOwnStuckDuties(nodeId: string, maxAgeMs: number): Promise<number>;
74
+ }
75
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uL3NyYy90eXBlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEtBQUssRUFBRSxVQUFVLEVBQUUsTUFBTSwrQkFBK0IsQ0FBQztBQUVoRSxPQUFPLEtBQUssRUFBRSxJQUFJLEVBQUUsTUFBTSxJQUFJLENBQUM7QUFFL0IsT0FBTyxLQUFLLEVBQUUsb0JBQW9CLEVBQUUsd0JBQXdCLEVBQUUsT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K,EAAE,OAAO,CAAC;IACf,qDAAqD;IACrD,MAAM,EAAE,mBAAmB,CAAC;CAC7B;AAED;;GAEG;AACH,MAAM,WAAW,kBAAkB;IACjC;;;OAGG;IACH,IAAI,CAAC,EAAE,IAAI,CAAC;CACb;AAED;;GAEG;AACH,MAAM,WAAW,cAAc;IAC7B,gCAAgC;IAChC,IAAI,EAAE,MAAM,CAAC;IACb,iCAAiC;IACjC,WAAW,EAAE,MAAM,CAAC;IACpB,mCAAmC;IACnC,QAAQ,EAAE,QAAQ,CAAC;CACpB;AAED;;;;;;;;GAQG;AACH,MAAM,WAAW,0BAA0B;IACzC;;;;;OAKG;IACH,sBAAsB,CAAC,MAAM,EAAE,oBAAoB,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC;IAEpF;;;;;OAKG;IACH,gBAAgB,CACd,gBAAgB,EAAE,UAAU,EAC5B,IAAI,EAAE,MAAM,EACZ,QAAQ,EAAE,QAAQ,EAClB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,OAAO,CAAC,CAAC;IAEpB;;;;;;OAMG;IACH,UAAU,CAAC,gBAAgB,EAAE,UAAU,EAAE,IAAI,EAAE,MAAM,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAEhH;;;OAGG;IACH,qBAAqB,CAAC,MAAM,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC;CAC1E"}
package/dest/types.js ADDED
@@ -0,0 +1 @@
1
+ export { DutyStatus, DutyType } from './db/types.js';
@@ -0,0 +1,74 @@
1
+ /**
2
+ * Validator High Availability Signer
3
+ *
4
+ * Wraps signing operations with distributed locking and slashing protection.
5
+ * This ensures that even with multiple validator nodes running, only one
6
+ * node will sign for a given duty (slot + duty type).
7
+ */
8
+ import type { Buffer32 } from '@aztec/foundation/buffer';
9
+ import type { EthAddress } from '@aztec/foundation/eth-address';
10
+ import type { Signature } from '@aztec/foundation/eth-signature';
11
+ import type { CreateHASignerConfig } from './config.js';
12
+ import type { SigningContext, SlashingProtectionDatabase } from './types.js';
13
+ /**
14
+ * Validator High Availability Signer
15
+ *
16
+ * Provides signing capabilities with distributed locking for validators
17
+ * in a high-availability setup.
18
+ *
19
+ * Usage:
20
+ * ```
21
+ * const signer = new ValidatorHASigner(db, config);
22
+ *
23
+ * // Sign with slashing protection
24
+ * const signature = await signer.signWithProtection(
25
+ * validatorAddress,
26
+ * messageHash,
27
+ * { slot: 100n, blockNumber: 50n, dutyType: 'BLOCK_PROPOSAL' },
28
+ * async (root) => localSigner.signMessage(root),
29
+ * );
30
+ * ```
31
+ */
32
+ export declare class ValidatorHASigner {
33
+ private readonly config;
34
+ private readonly log;
35
+ private readonly slashingProtection;
36
+ constructor(db: SlashingProtectionDatabase, config: CreateHASignerConfig);
37
+ /**
38
+ * Sign a message with slashing protection.
39
+ *
40
+ * This method:
41
+ * 1. Acquires a distributed lock for (validator, slot, dutyType)
42
+ * 2. Calls the provided signing function
43
+ * 3. Records the result (success or failure)
44
+ *
45
+ * @param validatorAddress - The validator's Ethereum address
46
+ * @param messageHash - The hash to be signed
47
+ * @param context - The signing context (slot, block number, duty type)
48
+ * @param signFn - Function that performs the actual signing
49
+ * @returns The signature
50
+ *
51
+ * @throws DutyAlreadySignedError if the duty was already signed (expected in HA)
52
+ * @throws SlashingProtectionError if attempting to sign different data for same slot (expected in HA)
53
+ */
54
+ signWithProtection(validatorAddress: EthAddress, messageHash: Buffer32, context: SigningContext, signFn: (messageHash: Buffer32) => Promise<Signature>): Promise<Signature>;
55
+ /**
56
+ * Check if slashing protection is enabled
57
+ */
58
+ get isEnabled(): boolean;
59
+ /**
60
+ * Get the node ID for this signer
61
+ */
62
+ get nodeId(): string;
63
+ /**
64
+ * Start the HA signer background tasks (cleanup of stuck duties).
65
+ * Should be called after construction and before signing operations.
66
+ */
67
+ start(): void;
68
+ /**
69
+ * Stop the HA signer background tasks.
70
+ * Should be called during graceful shutdown.
71
+ */
72
+ stop(): Promise<void>;
73
+ }
74
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmFsaWRhdG9yX2hhX3NpZ25lci5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL3ZhbGlkYXRvcl9oYV9zaWduZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUE7Ozs7OztHQU1HO0FBQ0gsT0FBTyxLQUFLLEVBQUUsUUFBUSxFQUFFLE1BQU0sMEJBQTBCLENBQUM7QUFDekQsT0FBTyxLQUFLLEVBQUUsVUFBVSxFQUFFLE1BQU0sK0JBQStCLENBQUM7QUFDaEUsT0FBTyxLQUFLLEVBQUUsU0FBUyxFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFHakUsT0FBTyxLQUFLLEVBQUUsb0JBQW9CLEVBQUUsTUFBTSxhQUFhLENBQUM7QUFFeEQsT0FBTyxLQUFLLEVBQUUsY0FBYyxFQUFFLDBCQUEwQixFQUFFLE1BQU0sWUFBWSxDQUFDO0FBRTdFOzs7Ozs7Ozs7Ozs7Ozs7Ozs7R0FrQkc7QUFDSCxxQkFBYSxpQkFBaUI7SUFNMUIsT0FBTyxDQUFDLFFBQVEsQ0FBQyxNQUFNO0lBTHpCLE9BQU8sQ0FBQyxRQUFRLENBQUMsR0FBRyxDQUFTO0lBQzdCLE9BQU8sQ0FBQyxRQUFRLENBQUMsa0JBQWtCLENBQXdDO0lBRTNFLFlBQ0UsRUFBRSxFQUFFLDBCQUEwQixFQUNiLE1BQU0sRUFBRSxvQkFBb0IsRUFnQjlDO0lBRUQ7Ozs7Ozs7Ozs7Ozs7Ozs7T0FnQkc7SUFDRyxrQkFBa0IsQ0FDdEIsZ0JBQWdCLEVBQUUsVUFBVSxFQUM1QixXQUFXLEVBQUUsUUFBUSxFQUNyQixPQUFPLEVBQUUsY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SAAS,CAAC,GACpD,OAAO,CAAC,SAAS,CAAC,CAmDpB;IAED;;OAEG;IACH,IAAI,SAAS,IAAI,OAAO,CAEvB;IAED;;OAEG;IACH,IAAI,MAAM,IAAI,MAAM,CAEnB;IAED;;;OAGG;IACH,KAAK,SAEJ;IAED;;;OAGG;IACG,IAAI,kBAET;CACF"}
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Validator High Availability Signer
3
+ *
4
+ * Wraps signing operations with distributed locking and slashing protection.
5
+ * This ensures that even with multiple validator nodes running, only one
6
+ * node will sign for a given duty (slot + duty type).
7
+ */ import { createLogger } from '@aztec/foundation/log';
8
+ import { SlashingProtectionService } from './slashing_protection_service.js';
9
+ /**
10
+ * Validator High Availability Signer
11
+ *
12
+ * Provides signing capabilities with distributed locking for validators
13
+ * in a high-availability setup.
14
+ *
15
+ * Usage:
16
+ * ```
17
+ * const signer = new ValidatorHASigner(db, config);
18
+ *
19
+ * // Sign with slashing protection
20
+ * const signature = await signer.signWithProtection(
21
+ * validatorAddress,
22
+ * messageHash,
23
+ * { slot: 100n, blockNumber: 50n, dutyType: 'BLOCK_PROPOSAL' },
24
+ * async (root) => localSigner.signMessage(root),
25
+ * );
26
+ * ```
27
+ */ export class ValidatorHASigner {
28
+ config;
29
+ log;
30
+ slashingProtection;
31
+ constructor(db, config){
32
+ this.config = config;
33
+ this.log = createLogger('validator-ha-signer');
34
+ if (!config.enabled) {
35
+ // this shouldn't happen, the validator should use different signer for non-HA setups
36
+ throw new Error('Validator HA Signer is not enabled in config');
37
+ }
38
+ if (!config.nodeId || config.nodeId === '') {
39
+ throw new Error('NODE_ID is required for high-availability setups');
40
+ }
41
+ this.slashingProtection = new SlashingProtectionService(db, config);
42
+ this.log.info('Validator HA Signer initialized with slashing protection', {
43
+ nodeId: config.nodeId
44
+ });
45
+ }
46
+ /**
47
+ * Sign a message with slashing protection.
48
+ *
49
+ * This method:
50
+ * 1. Acquires a distributed lock for (validator, slot, dutyType)
51
+ * 2. Calls the provided signing function
52
+ * 3. Records the result (success or failure)
53
+ *
54
+ * @param validatorAddress - The validator's Ethereum address
55
+ * @param messageHash - The hash to be signed
56
+ * @param context - The signing context (slot, block number, duty type)
57
+ * @param signFn - Function that performs the actual signing
58
+ * @returns The signature
59
+ *
60
+ * @throws DutyAlreadySignedError if the duty was already signed (expected in HA)
61
+ * @throws SlashingProtectionError if attempting to sign different data for same slot (expected in HA)
62
+ */ async signWithProtection(validatorAddress, messageHash, context, signFn) {
63
+ // If slashing protection is disabled, just sign directly
64
+ if (!this.slashingProtection) {
65
+ this.log.info('Signing without slashing protection enabled', {
66
+ validatorAddress: validatorAddress.toString(),
67
+ nodeId: this.config.nodeId,
68
+ dutyType: context.dutyType,
69
+ slot: context.slot,
70
+ blockNumber: context.blockNumber
71
+ });
72
+ return await signFn(messageHash);
73
+ }
74
+ const { slot, blockNumber, dutyType } = context;
75
+ // Acquire lock and get the token for ownership verification
76
+ const lockToken = await this.slashingProtection.checkAndRecord({
77
+ validatorAddress,
78
+ slot,
79
+ blockNumber,
80
+ dutyType,
81
+ messageHash: messageHash.toString(),
82
+ nodeId: this.config.nodeId
83
+ });
84
+ // Perform signing
85
+ let signature;
86
+ try {
87
+ signature = await signFn(messageHash);
88
+ } catch (error) {
89
+ // Delete duty to allow retry (only succeeds if we own the lock)
90
+ await this.slashingProtection.deleteDuty({
91
+ validatorAddress,
92
+ slot,
93
+ dutyType,
94
+ lockToken
95
+ });
96
+ throw error;
97
+ }
98
+ // Record success (only succeeds if we own the lock)
99
+ await this.slashingProtection.recordSuccess({
100
+ validatorAddress,
101
+ slot,
102
+ dutyType,
103
+ signature,
104
+ nodeId: this.config.nodeId,
105
+ lockToken
106
+ });
107
+ return signature;
108
+ }
109
+ /**
110
+ * Check if slashing protection is enabled
111
+ */ get isEnabled() {
112
+ return this.slashingProtection !== undefined;
113
+ }
114
+ /**
115
+ * Get the node ID for this signer
116
+ */ get nodeId() {
117
+ return this.config.nodeId;
118
+ }
119
+ /**
120
+ * Start the HA signer background tasks (cleanup of stuck duties).
121
+ * Should be called after construction and before signing operations.
122
+ */ start() {
123
+ this.slashingProtection?.start();
124
+ }
125
+ /**
126
+ * Stop the HA signer background tasks.
127
+ * Should be called during graceful shutdown.
128
+ */ async stop() {
129
+ await this.slashingProtection?.stop();
130
+ }
131
+ }
package/package.json ADDED
@@ -0,0 +1,105 @@
1
+ {
2
+ "name": "@aztec/validator-ha-signer",
3
+ "version": "4.0.0-nightly.20260110",
4
+ "type": "module",
5
+ "exports": {
6
+ "./config": "./dest/config.js",
7
+ "./db": "./dest/db/index.js",
8
+ "./errors": "./dest/errors.js",
9
+ "./factory": "./dest/factory.js",
10
+ "./migrations": "./dest/migrations.js",
11
+ "./slashing-protection-service": "./dest/slashing_protection_service.js",
12
+ "./types": "./dest/types.js",
13
+ "./validator-ha-signer": "./dest/validator_ha_signer.js"
14
+ },
15
+ "typedocOptions": {
16
+ "entryPoints": [
17
+ "./src/config.ts",
18
+ "./src/db/index.ts",
19
+ "./src/errors.ts",
20
+ "./src/factory.ts",
21
+ "./src/migrations.ts",
22
+ "./src/slashing_protection_service.ts",
23
+ "./src/types.ts",
24
+ "./src/validator_ha_signer.ts"
25
+ ],
26
+ "name": "Validator High-Availability Signer",
27
+ "tsconfig": "./tsconfig.json"
28
+ },
29
+ "scripts": {
30
+ "build": "yarn clean && ../scripts/tsc.sh",
31
+ "build:dev": "../scripts/tsc.sh --watch",
32
+ "clean": "rm -rf ./dest .tsbuildinfo",
33
+ "test": "NODE_NO_WARNINGS=1 node --experimental-vm-modules ../node_modules/.bin/jest --passWithNoTests --maxWorkers=${JEST_MAX_WORKERS:-8}"
34
+ },
35
+ "inherits": [
36
+ "../package.common.json"
37
+ ],
38
+ "jest": {
39
+ "moduleNameMapper": {
40
+ "^(\\.{1,2}/.*)\\.[cm]?js$": "$1"
41
+ },
42
+ "testRegex": "./src/.*\\.test\\.(js|mjs|ts)$",
43
+ "rootDir": "./src",
44
+ "transform": {
45
+ "^.+\\.tsx?$": [
46
+ "@swc/jest",
47
+ {
48
+ "jsc": {
49
+ "parser": {
50
+ "syntax": "typescript",
51
+ "decorators": true
52
+ },
53
+ "transform": {
54
+ "decoratorVersion": "2022-03"
55
+ }
56
+ }
57
+ }
58
+ ]
59
+ },
60
+ "extensionsToTreatAsEsm": [
61
+ ".ts"
62
+ ],
63
+ "reporters": [
64
+ "default"
65
+ ],
66
+ "testTimeout": 120000,
67
+ "setupFiles": [
68
+ "../../foundation/src/jest/setup.mjs"
69
+ ],
70
+ "testEnvironment": "../../foundation/src/jest/env.mjs",
71
+ "setupFilesAfterEnv": [
72
+ "../../foundation/src/jest/setupAfterEnv.mjs"
73
+ ]
74
+ },
75
+ "dependencies": {
76
+ "@aztec/foundation": "4.0.0-nightly.20260110",
77
+ "@aztec/node-keystore": "4.0.0-nightly.20260110",
78
+ "node-pg-migrate": "^8.0.4",
79
+ "pg": "^8.11.3",
80
+ "tslib": "^2.4.0"
81
+ },
82
+ "devDependencies": {
83
+ "@electric-sql/pglite": "^0.2.17",
84
+ "@jest/globals": "^30.0.0",
85
+ "@middle-management/pglite-pg-adapter": "^0.0.3",
86
+ "@types/jest": "^30.0.0",
87
+ "@types/node": "^22.15.17",
88
+ "@types/node-pg-migrate": "^2.3.1",
89
+ "@types/pg": "^8.10.9",
90
+ "@typescript/native-preview": "7.0.0-dev.20251126.1",
91
+ "jest": "^30.0.0",
92
+ "jest-mock-extended": "^4.0.0",
93
+ "ts-node": "^10.9.1",
94
+ "typescript": "^5.3.3"
95
+ },
96
+ "types": "./dest/types.d.ts",
97
+ "files": [
98
+ "dest",
99
+ "src",
100
+ "!*.test.*"
101
+ ],
102
+ "engines": {
103
+ "node": ">=20.10"
104
+ }
105
+ }