@aztec/validator-ha-signer 0.0.1-commit.001888fc

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 (62) hide show
  1. package/README.md +195 -0
  2. package/dest/db/index.d.ts +5 -0
  3. package/dest/db/index.d.ts.map +1 -0
  4. package/dest/db/index.js +4 -0
  5. package/dest/db/lmdb.d.ts +66 -0
  6. package/dest/db/lmdb.d.ts.map +1 -0
  7. package/dest/db/lmdb.js +188 -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 +86 -0
  12. package/dest/db/postgres.d.ts.map +1 -0
  13. package/dest/db/postgres.js +208 -0
  14. package/dest/db/schema.d.ts +96 -0
  15. package/dest/db/schema.d.ts.map +1 -0
  16. package/dest/db/schema.js +230 -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 +185 -0
  21. package/dest/db/types.d.ts.map +1 -0
  22. package/dest/db/types.js +64 -0
  23. package/dest/errors.d.ts +34 -0
  24. package/dest/errors.d.ts.map +1 -0
  25. package/dest/errors.js +34 -0
  26. package/dest/factory.d.ts +60 -0
  27. package/dest/factory.d.ts.map +1 -0
  28. package/dest/factory.js +115 -0
  29. package/dest/metrics.d.ts +51 -0
  30. package/dest/metrics.d.ts.map +1 -0
  31. package/dest/metrics.js +103 -0
  32. package/dest/migrations.d.ts +15 -0
  33. package/dest/migrations.d.ts.map +1 -0
  34. package/dest/migrations.js +53 -0
  35. package/dest/slashing_protection_service.d.ts +93 -0
  36. package/dest/slashing_protection_service.d.ts.map +1 -0
  37. package/dest/slashing_protection_service.js +236 -0
  38. package/dest/test/pglite_pool.d.ts +92 -0
  39. package/dest/test/pglite_pool.d.ts.map +1 -0
  40. package/dest/test/pglite_pool.js +210 -0
  41. package/dest/types.d.ts +99 -0
  42. package/dest/types.d.ts.map +1 -0
  43. package/dest/types.js +4 -0
  44. package/dest/validator_ha_signer.d.ts +79 -0
  45. package/dest/validator_ha_signer.d.ts.map +1 -0
  46. package/dest/validator_ha_signer.js +140 -0
  47. package/package.json +110 -0
  48. package/src/db/index.ts +4 -0
  49. package/src/db/lmdb.ts +264 -0
  50. package/src/db/migrations/1_initial-schema.ts +26 -0
  51. package/src/db/postgres.ts +284 -0
  52. package/src/db/schema.ts +267 -0
  53. package/src/db/test_helper.ts +17 -0
  54. package/src/db/types.ts +251 -0
  55. package/src/errors.ts +47 -0
  56. package/src/factory.ts +139 -0
  57. package/src/metrics.ts +138 -0
  58. package/src/migrations.ts +75 -0
  59. package/src/slashing_protection_service.ts +308 -0
  60. package/src/test/pglite_pool.ts +256 -0
  61. package/src/types.ts +154 -0
  62. package/src/validator_ha_signer.ts +183 -0
@@ -0,0 +1,185 @@
1
+ import { BlockNumber, type CheckpointNumber, type IndexWithinCheckpoint, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import type { Signature } from '@aztec/foundation/eth-signature';
4
+ import { DutyType } from '@aztec/stdlib/ha-signing';
5
+ /**
6
+ * Row type from PostgreSQL query
7
+ */
8
+ export interface DutyRow {
9
+ rollup_address: string;
10
+ validator_address: string;
11
+ slot: string;
12
+ block_number: string;
13
+ block_index_within_checkpoint: number;
14
+ duty_type: DutyType;
15
+ status: DutyStatus;
16
+ message_hash: string;
17
+ signature: string | null;
18
+ node_id: string;
19
+ lock_token: string;
20
+ started_at: Date;
21
+ completed_at: Date | null;
22
+ error_message: string | null;
23
+ }
24
+ /**
25
+ * Plain-primitive representation of a duty record suitable for serialization
26
+ * (e.g. msgpackr for LMDB). All domain types are stored as their string/number
27
+ * equivalents. Timestamps are Unix milliseconds.
28
+ */
29
+ export interface StoredDutyRecord {
30
+ rollupAddress: string;
31
+ validatorAddress: string;
32
+ slot: string;
33
+ blockNumber: string;
34
+ blockIndexWithinCheckpoint: number;
35
+ dutyType: DutyType;
36
+ status: DutyStatus;
37
+ messageHash: string;
38
+ signature?: string;
39
+ nodeId: string;
40
+ lockToken: string;
41
+ /** Unix timestamp in milliseconds when signing started */
42
+ startedAtMs: number;
43
+ /** Unix timestamp in milliseconds when signing completed */
44
+ completedAtMs?: number;
45
+ errorMessage?: string;
46
+ }
47
+ /**
48
+ * Row type from INSERT_OR_GET_DUTY query (includes is_new flag)
49
+ */
50
+ export interface InsertOrGetRow extends DutyRow {
51
+ is_new: boolean;
52
+ }
53
+ /**
54
+ * Status of a duty in the database
55
+ */
56
+ export declare enum DutyStatus {
57
+ SIGNING = "signing",
58
+ SIGNED = "signed"
59
+ }
60
+ export { DutyType };
61
+ /**
62
+ * Rich representation of a validator duty, with branded types and Date objects.
63
+ * This is the common output type returned by all SlashingProtectionDatabase implementations.
64
+ */
65
+ export interface ValidatorDutyRecord {
66
+ /** Ethereum address of the rollup contract */
67
+ rollupAddress: EthAddress;
68
+ /** Ethereum address of the validator */
69
+ validatorAddress: EthAddress;
70
+ /** Slot number for this duty */
71
+ slot: SlotNumber;
72
+ /** Block number for this duty */
73
+ blockNumber: BlockNumber;
74
+ /** Block index within checkpoint (0, 1, 2... for block proposals, -1 for other duty types) */
75
+ blockIndexWithinCheckpoint: number;
76
+ /** Type of duty being performed */
77
+ dutyType: DutyType;
78
+ /** Current status of the duty */
79
+ status: DutyStatus;
80
+ /** The signing root (hash) for this duty */
81
+ messageHash: string;
82
+ /** The signature (populated after successful signing) */
83
+ signature?: string;
84
+ /** Unique identifier for the node that acquired the lock */
85
+ nodeId: string;
86
+ /** Secret token for verifying ownership of the duty lock */
87
+ lockToken: string;
88
+ /** When the duty signing was started */
89
+ startedAt: Date;
90
+ /** When the duty signing was completed (success or failure) */
91
+ completedAt?: Date;
92
+ /** Error message (currently unused) */
93
+ errorMessage?: string;
94
+ }
95
+ /**
96
+ * Convert a {@link StoredDutyRecord} (plain-primitive wire format) to a
97
+ * {@link ValidatorDutyRecord} (rich domain type).
98
+ *
99
+ * Shared by LMDB and any future non-Postgres backend implementations.
100
+ */
101
+ export declare function recordFromFields(stored: StoredDutyRecord): ValidatorDutyRecord;
102
+ /**
103
+ * Duty identifier for block proposals.
104
+ * blockIndexWithinCheckpoint is REQUIRED and must be >= 0.
105
+ */
106
+ export interface BlockProposalDutyIdentifier {
107
+ rollupAddress: EthAddress;
108
+ validatorAddress: EthAddress;
109
+ slot: SlotNumber;
110
+ /** Block index within checkpoint (0, 1, 2...). Required for block proposals. */
111
+ blockIndexWithinCheckpoint: IndexWithinCheckpoint;
112
+ dutyType: DutyType.BLOCK_PROPOSAL;
113
+ }
114
+ /**
115
+ * Duty identifier for non-block-proposal duties.
116
+ * blockIndexWithinCheckpoint is not applicable (internally stored as -1).
117
+ */
118
+ export interface OtherDutyIdentifier {
119
+ rollupAddress: EthAddress;
120
+ validatorAddress: EthAddress;
121
+ slot: SlotNumber;
122
+ dutyType: DutyType.CHECKPOINT_PROPOSAL | DutyType.ATTESTATION | DutyType.ATTESTATIONS_AND_SIGNERS | DutyType.GOVERNANCE_VOTE | DutyType.SLASHING_VOTE | DutyType.AUTH_REQUEST | DutyType.TXS;
123
+ }
124
+ /**
125
+ * Minimal info needed to identify a unique duty.
126
+ * Uses discriminated union to enforce type safety:
127
+ * - BLOCK_PROPOSAL duties MUST have blockIndexWithinCheckpoint >= 0
128
+ * - Other duty types do NOT have blockIndexWithinCheckpoint (internally -1)
129
+ */
130
+ export type DutyIdentifier = BlockProposalDutyIdentifier | OtherDutyIdentifier;
131
+ /**
132
+ * Validates and normalizes the block index for a duty.
133
+ * - BLOCK_PROPOSAL: validates blockIndexWithinCheckpoint is provided and >= 0
134
+ * - Other duty types: always returns -1
135
+ *
136
+ * @throws Error if BLOCK_PROPOSAL is missing blockIndexWithinCheckpoint or has invalid value
137
+ */
138
+ export declare function normalizeBlockIndex(dutyType: DutyType, blockIndexWithinCheckpoint: number | undefined): number;
139
+ /**
140
+ * Gets the block index from a DutyIdentifier.
141
+ * - BLOCK_PROPOSAL: returns the blockIndexWithinCheckpoint
142
+ * - Other duty types: returns -1
143
+ */
144
+ export declare function getBlockIndexFromDutyIdentifier(duty: DutyIdentifier): number;
145
+ /**
146
+ * Additional parameters for checking and recording a new duty
147
+ */
148
+ interface CheckAndRecordExtra {
149
+ /** Block number for this duty */
150
+ blockNumber: BlockNumber | CheckpointNumber;
151
+ /** The signing root (hash) for this duty */
152
+ messageHash: string;
153
+ /** Identifier for the node that acquired the lock */
154
+ nodeId: string;
155
+ }
156
+ /**
157
+ * Parameters for checking and recording a new duty.
158
+ * Uses intersection with DutyIdentifier to preserve the discriminated union.
159
+ */
160
+ export type CheckAndRecordParams = DutyIdentifier & CheckAndRecordExtra;
161
+ /**
162
+ * Additional parameters for recording a successful signing
163
+ */
164
+ interface RecordSuccessExtra {
165
+ signature: Signature;
166
+ nodeId: string;
167
+ lockToken: string;
168
+ }
169
+ /**
170
+ * Parameters for recording a successful signing.
171
+ * Uses intersection with DutyIdentifier to preserve the discriminated union.
172
+ */
173
+ export type RecordSuccessParams = DutyIdentifier & RecordSuccessExtra;
174
+ /**
175
+ * Additional parameters for deleting a duty
176
+ */
177
+ interface DeleteDutyExtra {
178
+ lockToken: string;
179
+ }
180
+ /**
181
+ * Parameters for deleting a duty.
182
+ * Uses intersection with DutyIdentifier to preserve the discriminated union.
183
+ */
184
+ export type DeleteDutyParams = DutyIdentifier & DeleteDutyExtra;
185
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidHlwZXMuZC50cyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9kYi90eXBlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFBQSxPQUFPLEVBQ0wsV0FBVyxFQUNYLEtBQUssZ0JBQWdCLEVBQ3JCLEtBQUsscUJBQXF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kB,CAAC;AAEtE;;GAEG;AACH,UAAU,eAAe;IACvB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,cAAc,GAAG,eAAe,CAAC"}
@@ -0,0 +1,64 @@
1
+ import { BlockNumber, SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import { DutyType } from '@aztec/stdlib/ha-signing';
4
+ /**
5
+ * Status of a duty in the database
6
+ */ export var DutyStatus = /*#__PURE__*/ function(DutyStatus) {
7
+ DutyStatus["SIGNING"] = "signing";
8
+ DutyStatus["SIGNED"] = "signed";
9
+ return DutyStatus;
10
+ }({});
11
+ // Re-export DutyType from stdlib
12
+ export { DutyType };
13
+ /**
14
+ * Convert a {@link StoredDutyRecord} (plain-primitive wire format) to a
15
+ * {@link ValidatorDutyRecord} (rich domain type).
16
+ *
17
+ * Shared by LMDB and any future non-Postgres backend implementations.
18
+ */ export function recordFromFields(stored) {
19
+ return {
20
+ rollupAddress: EthAddress.fromString(stored.rollupAddress),
21
+ validatorAddress: EthAddress.fromString(stored.validatorAddress),
22
+ slot: SlotNumber.fromString(stored.slot),
23
+ blockNumber: BlockNumber.fromString(stored.blockNumber),
24
+ blockIndexWithinCheckpoint: stored.blockIndexWithinCheckpoint,
25
+ dutyType: stored.dutyType,
26
+ status: stored.status,
27
+ messageHash: stored.messageHash,
28
+ signature: stored.signature,
29
+ nodeId: stored.nodeId,
30
+ lockToken: stored.lockToken,
31
+ startedAt: new Date(stored.startedAtMs),
32
+ completedAt: stored.completedAtMs !== undefined ? new Date(stored.completedAtMs) : undefined,
33
+ errorMessage: stored.errorMessage
34
+ };
35
+ }
36
+ /**
37
+ * Validates and normalizes the block index for a duty.
38
+ * - BLOCK_PROPOSAL: validates blockIndexWithinCheckpoint is provided and >= 0
39
+ * - Other duty types: always returns -1
40
+ *
41
+ * @throws Error if BLOCK_PROPOSAL is missing blockIndexWithinCheckpoint or has invalid value
42
+ */ export function normalizeBlockIndex(dutyType, blockIndexWithinCheckpoint) {
43
+ if (dutyType === DutyType.BLOCK_PROPOSAL) {
44
+ if (blockIndexWithinCheckpoint === undefined) {
45
+ throw new Error('BLOCK_PROPOSAL duties require blockIndexWithinCheckpoint to be specified');
46
+ }
47
+ if (blockIndexWithinCheckpoint < 0) {
48
+ throw new Error(`BLOCK_PROPOSAL duties require blockIndexWithinCheckpoint >= 0, got ${blockIndexWithinCheckpoint}`);
49
+ }
50
+ return blockIndexWithinCheckpoint;
51
+ }
52
+ // For all other duty types, always use -1
53
+ return -1;
54
+ }
55
+ /**
56
+ * Gets the block index from a DutyIdentifier.
57
+ * - BLOCK_PROPOSAL: returns the blockIndexWithinCheckpoint
58
+ * - Other duty types: returns -1
59
+ */ export function getBlockIndexFromDutyIdentifier(duty) {
60
+ if (duty.dutyType === DutyType.BLOCK_PROPOSAL) {
61
+ return duty.blockIndexWithinCheckpoint;
62
+ }
63
+ return -1;
64
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Custom errors for the validator HA signer
3
+ */
4
+ import type { SlotNumber } from '@aztec/foundation/branded-types';
5
+ import type { DutyType } from './db/types.js';
6
+ /**
7
+ * Thrown when a duty has already been signed (by any node).
8
+ * This is expected behavior in an HA setup - all nodes try to sign,
9
+ * the first one wins, and subsequent attempts get this error.
10
+ */
11
+ export declare class DutyAlreadySignedError extends Error {
12
+ readonly slot: SlotNumber;
13
+ readonly dutyType: DutyType;
14
+ readonly blockIndexWithinCheckpoint: number;
15
+ readonly signedByNode: string;
16
+ constructor(slot: SlotNumber, dutyType: DutyType, blockIndexWithinCheckpoint: number, signedByNode: string);
17
+ }
18
+ /**
19
+ * Thrown when attempting to sign data that conflicts with an already-signed duty.
20
+ * This means the same validator tried to sign DIFFERENT data for the same slot.
21
+ *
22
+ * This is expected in HA setups where nodes may build different blocks
23
+ * (e.g., different transaction ordering) - the protection prevents double-signing.
24
+ */
25
+ export declare class SlashingProtectionError extends Error {
26
+ readonly slot: SlotNumber;
27
+ readonly dutyType: DutyType;
28
+ readonly blockIndexWithinCheckpoint: number;
29
+ readonly existingMessageHash: string;
30
+ readonly attemptedMessageHash: string;
31
+ readonly signedByNode: string;
32
+ constructor(slot: SlotNumber, dutyType: DutyType, blockIndexWithinCheckpoint: number, existingMessageHash: string, attemptedMessageHash: string, signedByNode: string);
33
+ }
34
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXJyb3JzLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvZXJyb3JzLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBQ0gsT0FBTyxLQUFLLEVBQUUsVUFBVSxFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFFbEUsT0FBTyxLQUFLLEVBQUUsUUFBUSxFQUFFLE1BQU0sZUFBZSxDQUFDO0FBRTlDOzs7O0dBSUc7QUFDSCxxQkFBYSxzQkFBdUIsU0FBUSxLQUFLO2FBRTdCLElBQUksRUFBRSxVQUFVO2FBQ2hCLFFBQVEsRUFBRSxRQUFRO2FBQ2xCLDBCQUEwQixFQUFFLE1BQU07YUFDbEMsWUFBWSxFQUFFLE1BQU07SUFKdEMsWUFDa0IsSUFBSSxFQUFFLFVBQVUsRUFDaEIsUUFBUSxFQUFFLFFBQVEsRUFDbEIsMEJBQTBCLEVBQUUsTUFBTSxFQUNsQyxZQUFZLEVBQUUsTUFBTSxFQUlyQztDQUNGO0FBRUQ7Ozs7OztHQU1HO0FBQ0gscUJBQWEsdUJBQXdCLFNBQVEsS0FBSzthQUU5QixJQUFJLEVBQUUsVUFBVTthQUNoQixRQUFRLEVBQUUsUUFBUTthQUNsQiwwQkFBMEIsRUFBRSxNQUFNO2FBQ2xDLG1CQUFtQixFQUFFLE1BQU07YUFDM0Isb0JBQW9CLEVBQUUsTUFBTTthQUM1QixZQUFZLEVBQUUsTUFBTTtJQU50QyxZQUNrQixJQUFJLEVBQUUsVUFBVSxFQUNoQixRQUFRLEVBQUUsUUFBUSxFQUNsQiwwQkFBMEIsRUFBRSxNQUFNLEVBQ2xDLG1CQUFtQixFQUFFLE1BQU0sRUFDM0Isb0JBQW9CLEVBQUUsTUFBTSxFQUM1QixZQUFZLEVBQUUsTUFBTSxFQU9yQztDQUNGIn0=
@@ -0,0 +1 @@
1
+ {"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,iCAAiC,CAAC;AAElE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AAE9C;;;;GAIG;AACH,qBAAa,sBAAuB,SAAQ,KAAK;aAE7B,IAAI,EAAE,UAAU;aAChB,QAAQ,EAAE,QAAQ;aAClB,0BAA0B,EAAE,MAAM;aAClC,YAAY,EAAE,MAAM;IAJtC,YACkB,IAAI,EAAE,UAAU,EAChB,QAAQ,EAAE,QAAQ,EAClB,0BAA0B,EAAE,MAAM,EAClC,YAAY,EAAE,MAAM,EAIrC;CACF;AAED;;;;;;GAMG;AACH,qBAAa,uBAAwB,SAAQ,KAAK;aAE9B,IAAI,EAAE,UAAU;aAChB,QAAQ,EAAE,QAAQ;aAClB,0BAA0B,EAAE,MAAM;aAClC,mBAAmB,EAAE,MAAM;aAC3B,oBAAoB,EAAE,MAAM;aAC5B,YAAY,EAAE,MAAM;IANtC,YACkB,IAAI,EAAE,UAAU,EAChB,QAAQ,EAAE,QAAQ,EAClB,0BAA0B,EAAE,MAAM,EAClC,mBAAmB,EAAE,MAAM,EAC3B,oBAAoB,EAAE,MAAM,EAC5B,YAAY,EAAE,MAAM,EAOrC;CACF"}
package/dest/errors.js ADDED
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Custom errors for the validator HA signer
3
+ */ /**
4
+ * Thrown when a duty has already been signed (by any node).
5
+ * This is expected behavior in an HA setup - all nodes try to sign,
6
+ * the first one wins, and subsequent attempts get this error.
7
+ */ export class DutyAlreadySignedError extends Error {
8
+ slot;
9
+ dutyType;
10
+ blockIndexWithinCheckpoint;
11
+ signedByNode;
12
+ constructor(slot, dutyType, blockIndexWithinCheckpoint, signedByNode){
13
+ super(`Duty ${dutyType} for slot ${slot} already signed by node ${signedByNode}`), this.slot = slot, this.dutyType = dutyType, this.blockIndexWithinCheckpoint = blockIndexWithinCheckpoint, this.signedByNode = signedByNode;
14
+ this.name = 'DutyAlreadySignedError';
15
+ }
16
+ }
17
+ /**
18
+ * Thrown when attempting to sign data that conflicts with an already-signed duty.
19
+ * This means the same validator tried to sign DIFFERENT data for the same slot.
20
+ *
21
+ * This is expected in HA setups where nodes may build different blocks
22
+ * (e.g., different transaction ordering) - the protection prevents double-signing.
23
+ */ export class SlashingProtectionError extends Error {
24
+ slot;
25
+ dutyType;
26
+ blockIndexWithinCheckpoint;
27
+ existingMessageHash;
28
+ attemptedMessageHash;
29
+ signedByNode;
30
+ constructor(slot, dutyType, blockIndexWithinCheckpoint, existingMessageHash, attemptedMessageHash, signedByNode){
31
+ super(`Slashing protection: ${dutyType} for slot ${slot} was already signed with different data. ` + `Existing: ${existingMessageHash.slice(0, 10)}..., Attempted: ${attemptedMessageHash.slice(0, 10)}...`), this.slot = slot, this.dutyType = dutyType, this.blockIndexWithinCheckpoint = blockIndexWithinCheckpoint, this.existingMessageHash = existingMessageHash, this.attemptedMessageHash = attemptedMessageHash, this.signedByNode = signedByNode;
32
+ this.name = 'SlashingProtectionError';
33
+ }
34
+ }
@@ -0,0 +1,60 @@
1
+ import type { LocalSignerConfig, ValidatorHASignerConfig } from '@aztec/stdlib/ha-signing';
2
+ import type { CreateHASignerDeps, CreateLocalSignerWithProtectionDeps, SlashingProtectionDatabase } from './types.js';
3
+ import { ValidatorHASigner } from './validator_ha_signer.js';
4
+ /**
5
+ * Create a validator HA signer with PostgreSQL backend
6
+ *
7
+ * After creating the signer, call `signer.start()` to begin background
8
+ * cleanup tasks. Call `signer.stop()` during graceful shutdown.
9
+ *
10
+ * Example with manual migrations (recommended for production):
11
+ * ```bash
12
+ * # Run migrations separately
13
+ * yarn migrate:up
14
+ * ```
15
+ *
16
+ * ```typescript
17
+ * const { signer, db } = await createHASigner({
18
+ * databaseUrl: process.env.DATABASE_URL,
19
+ * nodeId: 'validator-node-1',
20
+ * pollingIntervalMs: 100,
21
+ * signingTimeoutMs: 3000,
22
+ * });
23
+ * signer.start(); // Start background cleanup
24
+ *
25
+ * // ... use signer ...
26
+ *
27
+ * await signer.stop(); // On shutdown
28
+ * ```
29
+ *
30
+ * Note: Migrations must be run separately using `aztec migrate-ha-db up` before
31
+ * creating the signer. The factory will verify the schema is initialized via `db.initialize()`.
32
+ *
33
+ * @param config - Configuration for the HA signer
34
+ * @param deps - Optional dependencies (e.g., for testing)
35
+ * @returns An object containing the signer and database instances
36
+ */
37
+ export declare function createHASigner(config: ValidatorHASignerConfig, deps?: CreateHASignerDeps): Promise<{
38
+ signer: ValidatorHASigner;
39
+ db: SlashingProtectionDatabase;
40
+ }>;
41
+ /**
42
+ * Create a local (single-node) signing protection signer backed by LMDB.
43
+ *
44
+ * This provides double-signing protection for nodes that are NOT running in a
45
+ * high-availability (multi-node) setup. It prevents a proposer from sending two
46
+ * proposals for the same slot if the node crashes and restarts mid-proposal.
47
+ *
48
+ * When `config.dataDirectory` is set, the protection database is persisted to disk
49
+ * and survives crashes/restarts. When unset, an ephemeral in-memory store is
50
+ * used which protects within a single run but not across restarts.
51
+ *
52
+ * @param config - Local signer config
53
+ * @param deps - Optional dependencies (telemetry, date provider).
54
+ * @returns An object containing the signer and database instances.
55
+ */
56
+ export declare function createLocalSignerWithProtection(config: LocalSignerConfig, deps?: CreateLocalSignerWithProtectionDeps): Promise<{
57
+ signer: ValidatorHASigner;
58
+ db: SlashingProtectionDatabase;
59
+ }>;
60
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZmFjd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mC,EAAE,0BAA0B,EAAE,MAAM,YAAY,CAAC;AACtH,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAE7D;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AACH,wBAAsB,cAAc,CAClC,MAAM,EAAE,uBAAuB,EAC/B,IAAI,CAAC,EAAE,kBAAkB,GACxB,OAAO,CAAC;IACT,MAAM,EAAE,iBAAiB,CAAC;IAC1B,EAAE,EAAE,0BAA0B,CAAC;CAChC,CAAC,CAsCD;AAED;;;;;;;;;;;;;;GAcG;AACH,wBAAsB,+BAA+B,CACnD,MAAM,EAAE,iBAAiB,EACzB,IAAI,CAAC,EAAE,mCAAmC,GACzC,OAAO,CAAC;IACT,MAAM,EAAE,iBAAiB,CAAC;IAC1B,EAAE,EAAE,0BAA0B,CAAC;CAChC,CAAC,CAsBD"}
@@ -0,0 +1,115 @@
1
+ /**
2
+ * Factory functions for creating validator HA signers
3
+ */ import { DateProvider } from '@aztec/foundation/timer';
4
+ import { createStore } from '@aztec/kv-store/lmdb-v2';
5
+ import { getTelemetryClient } from '@aztec/telemetry-client';
6
+ import { Pool } from 'pg';
7
+ import { LmdbSlashingProtectionDatabase } from './db/lmdb.js';
8
+ import { PostgresSlashingProtectionDatabase } from './db/postgres.js';
9
+ import { HASignerMetrics } from './metrics.js';
10
+ import { ValidatorHASigner } from './validator_ha_signer.js';
11
+ /**
12
+ * Create a validator HA signer with PostgreSQL backend
13
+ *
14
+ * After creating the signer, call `signer.start()` to begin background
15
+ * cleanup tasks. Call `signer.stop()` during graceful shutdown.
16
+ *
17
+ * Example with manual migrations (recommended for production):
18
+ * ```bash
19
+ * # Run migrations separately
20
+ * yarn migrate:up
21
+ * ```
22
+ *
23
+ * ```typescript
24
+ * const { signer, db } = await createHASigner({
25
+ * databaseUrl: process.env.DATABASE_URL,
26
+ * nodeId: 'validator-node-1',
27
+ * pollingIntervalMs: 100,
28
+ * signingTimeoutMs: 3000,
29
+ * });
30
+ * signer.start(); // Start background cleanup
31
+ *
32
+ * // ... use signer ...
33
+ *
34
+ * await signer.stop(); // On shutdown
35
+ * ```
36
+ *
37
+ * Note: Migrations must be run separately using `aztec migrate-ha-db up` before
38
+ * creating the signer. The factory will verify the schema is initialized via `db.initialize()`.
39
+ *
40
+ * @param config - Configuration for the HA signer
41
+ * @param deps - Optional dependencies (e.g., for testing)
42
+ * @returns An object containing the signer and database instances
43
+ */ export async function createHASigner(config, deps) {
44
+ const { databaseUrl, poolMaxCount, poolMinCount, poolIdleTimeoutMs, poolConnectionTimeoutMs, ...signerConfig } = config;
45
+ if (!databaseUrl) {
46
+ throw new Error('databaseUrl is required for createHASigner');
47
+ }
48
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
49
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
50
+ // Create connection pool (or use provided pool)
51
+ let pool;
52
+ if (!deps?.pool) {
53
+ pool = new Pool({
54
+ connectionString: databaseUrl,
55
+ max: poolMaxCount ?? 10,
56
+ min: poolMinCount ?? 0,
57
+ idleTimeoutMillis: poolIdleTimeoutMs ?? 10_000,
58
+ connectionTimeoutMillis: poolConnectionTimeoutMs ?? 0
59
+ });
60
+ } else {
61
+ pool = deps.pool;
62
+ }
63
+ // Create database instance
64
+ const db = new PostgresSlashingProtectionDatabase(pool);
65
+ // Verify database schema is initialized and version matches
66
+ await db.initialize();
67
+ // Create metrics
68
+ const metrics = new HASignerMetrics(telemetryClient, signerConfig.nodeId);
69
+ // Create signer
70
+ const signer = new ValidatorHASigner(db, signerConfig, {
71
+ metrics,
72
+ dateProvider
73
+ });
74
+ return {
75
+ signer,
76
+ db
77
+ };
78
+ }
79
+ /**
80
+ * Create a local (single-node) signing protection signer backed by LMDB.
81
+ *
82
+ * This provides double-signing protection for nodes that are NOT running in a
83
+ * high-availability (multi-node) setup. It prevents a proposer from sending two
84
+ * proposals for the same slot if the node crashes and restarts mid-proposal.
85
+ *
86
+ * When `config.dataDirectory` is set, the protection database is persisted to disk
87
+ * and survives crashes/restarts. When unset, an ephemeral in-memory store is
88
+ * used which protects within a single run but not across restarts.
89
+ *
90
+ * @param config - Local signer config
91
+ * @param deps - Optional dependencies (telemetry, date provider).
92
+ * @returns An object containing the signer and database instances.
93
+ */ export async function createLocalSignerWithProtection(config, deps) {
94
+ const telemetryClient = deps?.telemetryClient ?? getTelemetryClient();
95
+ const dateProvider = deps?.dateProvider ?? new DateProvider();
96
+ const kvStore = await createStore('signing-protection', LmdbSlashingProtectionDatabase.SCHEMA_VERSION, {
97
+ dataDirectory: config.dataDirectory,
98
+ dataStoreMapSizeKb: config.signingProtectionMapSizeKb ?? config.dataStoreMapSizeKb,
99
+ l1Contracts: config.l1Contracts
100
+ });
101
+ const db = new LmdbSlashingProtectionDatabase(kvStore, dateProvider);
102
+ const signerConfig = {
103
+ ...config,
104
+ nodeId: config.nodeId || 'local'
105
+ };
106
+ const metrics = new HASignerMetrics(telemetryClient, signerConfig.nodeId, 'LocalSigningProtectionMetrics');
107
+ const signer = new ValidatorHASigner(db, signerConfig, {
108
+ metrics,
109
+ dateProvider
110
+ });
111
+ return {
112
+ signer,
113
+ db
114
+ };
115
+ }
@@ -0,0 +1,51 @@
1
+ import { type TelemetryClient } from '@aztec/telemetry-client';
2
+ export type HACleanupType = 'stuck' | 'old' | 'outdated_rollup';
3
+ /**
4
+ * Metrics for HA signer tracking signing operations, lock acquisition, and cleanup.
5
+ */
6
+ export declare class HASignerMetrics {
7
+ private nodeId;
8
+ private signingDuration;
9
+ private signingSuccessCount;
10
+ private dutyAlreadySignedCount;
11
+ private slashingProtectionCount;
12
+ private signingErrorCount;
13
+ private lockAcquiredCount;
14
+ private cleanupStuckDutiesCount;
15
+ private cleanupOldDutiesCount;
16
+ private cleanupOutdatedRollupDutiesCount;
17
+ constructor(client: TelemetryClient, nodeId: string, name?: string);
18
+ /**
19
+ * Record a successful signing operation.
20
+ * @param dutyType - The type of duty signed
21
+ * @param durationMs - Duration from start of signWithProtection to completion
22
+ */
23
+ recordSigningSuccess(dutyType: string, durationMs: number): void;
24
+ /**
25
+ * Record a DutyAlreadySignedError (expected in HA; another node signed first).
26
+ * @param dutyType - The type of duty
27
+ */
28
+ recordDutyAlreadySigned(dutyType: string): void;
29
+ /**
30
+ * Record a SlashingProtectionError (attempted to sign different data for same duty).
31
+ * @param dutyType - The type of duty
32
+ */
33
+ recordSlashingProtection(dutyType: string): void;
34
+ /**
35
+ * Record a signing function failure (lock will be deleted for retry).
36
+ * @param dutyType - The type of duty
37
+ */
38
+ recordSigningError(dutyType: string): void;
39
+ /**
40
+ * Record lock acquisition.
41
+ * @param acquired - Whether a new lock was acquired (true) or existing record found (false)
42
+ */
43
+ recordLockAcquire(acquired: boolean): void;
44
+ /**
45
+ * Record cleanup metrics.
46
+ * @param type - Type of cleanup
47
+ * @param count - Number of duties cleaned up
48
+ */
49
+ recordCleanup(type: HACleanupType, count: number): void;
50
+ }
51
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWV0cmljcy5kLnRzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vc3JjL21ldHJpY3MudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6IkFBQUEsT0FBTyxFQUlMLEtBQUssZUFBZSxFQUdyQixNQUFNLHlCQUF5QixDQUFDO0FBRWpDLE1BQU0sTUFBTSxhQUFhLEdBQUcsT0FBTyxHQUFHLEtBQUssR0FBRyxpQkFBaUIsQ0FBQztBQUVoRTs7R0FFRztBQUNILHFCQUFhLGVBQWU7SUFrQnhCLE9BQU8sQ0FBQyxNQUFNO0lBaEJoQixPQUFPLENBQUMsZUFBZSxDQUFZO0lBQ25DLE9BQU8sQ0FBQyxtQkFBbUIsQ0FBZ0I7SUFDM0MsT0FBTyxDQUFDLHNCQUFzQixDQUFnQjtJQUM5QyxPQUFPLENBQUMsdUJBQXVCLENBQWdCO0lBQy9DLE9BQU8sQ0FBQyxpQkFBaUIsQ0FBZ0I7S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