@aztec/validator-client 0.0.1-commit.96bb3f7 → 0.0.1-commit.993d240

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 (73) hide show
  1. package/README.md +93 -24
  2. package/dest/checkpoint_builder.d.ts +35 -26
  3. package/dest/checkpoint_builder.d.ts.map +1 -1
  4. package/dest/checkpoint_builder.js +144 -48
  5. package/dest/config.d.ts +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +44 -20
  8. package/dest/duties/validation_service.d.ts +26 -14
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +79 -38
  11. package/dest/factory.d.ts +11 -5
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +11 -5
  14. package/dest/index.d.ts +2 -3
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +1 -2
  17. package/dest/key_store/ha_key_store.d.ts +99 -0
  18. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  19. package/dest/key_store/ha_key_store.js +208 -0
  20. package/dest/key_store/index.d.ts +2 -1
  21. package/dest/key_store/index.d.ts.map +1 -1
  22. package/dest/key_store/index.js +1 -0
  23. package/dest/key_store/interface.d.ts +36 -6
  24. package/dest/key_store/interface.d.ts.map +1 -1
  25. package/dest/key_store/local_key_store.d.ts +10 -5
  26. package/dest/key_store/local_key_store.d.ts.map +1 -1
  27. package/dest/key_store/local_key_store.js +8 -4
  28. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  29. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  30. package/dest/key_store/node_keystore_adapter.js +18 -4
  31. package/dest/key_store/web3signer_key_store.d.ts +10 -5
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +8 -4
  34. package/dest/metrics.d.ts +16 -3
  35. package/dest/metrics.d.ts.map +1 -1
  36. package/dest/metrics.js +58 -5
  37. package/dest/proposal_handler.d.ts +135 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +1111 -0
  40. package/dest/validator.d.ts +60 -25
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +393 -257
  43. package/package.json +21 -17
  44. package/src/checkpoint_builder.ts +211 -61
  45. package/src/config.ts +43 -18
  46. package/src/duties/validation_service.ts +119 -46
  47. package/src/factory.ts +21 -3
  48. package/src/index.ts +1 -2
  49. package/src/key_store/ha_key_store.ts +269 -0
  50. package/src/key_store/index.ts +1 -0
  51. package/src/key_store/interface.ts +44 -5
  52. package/src/key_store/local_key_store.ts +13 -4
  53. package/src/key_store/node_keystore_adapter.ts +27 -4
  54. package/src/key_store/web3signer_key_store.ts +17 -4
  55. package/src/metrics.ts +81 -6
  56. package/src/proposal_handler.ts +1207 -0
  57. package/src/validator.ts +529 -307
  58. package/dest/block_proposal_handler.d.ts +0 -63
  59. package/dest/block_proposal_handler.d.ts.map +0 -1
  60. package/dest/block_proposal_handler.js +0 -551
  61. package/dest/tx_validator/index.d.ts +0 -3
  62. package/dest/tx_validator/index.d.ts.map +0 -1
  63. package/dest/tx_validator/index.js +0 -2
  64. package/dest/tx_validator/nullifier_cache.d.ts +0 -14
  65. package/dest/tx_validator/nullifier_cache.d.ts.map +0 -1
  66. package/dest/tx_validator/nullifier_cache.js +0 -24
  67. package/dest/tx_validator/tx_validator_factory.d.ts +0 -18
  68. package/dest/tx_validator/tx_validator_factory.d.ts.map +0 -1
  69. package/dest/tx_validator/tx_validator_factory.js +0 -53
  70. package/src/block_proposal_handler.ts +0 -556
  71. package/src/tx_validator/index.ts +0 -2
  72. package/src/tx_validator/nullifier_cache.ts +0 -30
  73. package/src/tx_validator/tx_validator_factory.ts +0 -133
@@ -1,11 +1,9 @@
1
- import { Buffer32 } from '@aztec/foundation/buffer';
2
- import { keccak256 } from '@aztec/foundation/crypto/keccak';
1
+ import { type CheckpointNumber, IndexWithinCheckpoint, type SlotNumber } from '@aztec/foundation/branded-types';
3
2
  import { Fr } from '@aztec/foundation/curves/bn254';
4
3
  import type { EthAddress } from '@aztec/foundation/eth-address';
5
4
  import type { Signature } from '@aztec/foundation/eth-signature';
6
5
  import { createLogger } from '@aztec/foundation/log';
7
- import type { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
8
- import type { CreateCheckpointProposalLastBlockData } from '@aztec/stdlib/interfaces/server';
6
+ import { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
9
7
  import {
10
8
  BlockProposal,
11
9
  type BlockProposalOptions,
@@ -14,16 +12,20 @@ import {
14
12
  type CheckpointProposalCore,
15
13
  type CheckpointProposalOptions,
16
14
  ConsensusPayload,
17
- SignatureDomainSeparator,
15
+ type CoordinationSignatureContext,
16
+ getCoordinationSignatureTypedData,
18
17
  } from '@aztec/stdlib/p2p';
19
- import type { CheckpointHeader } from '@aztec/stdlib/rollup';
18
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
20
19
  import type { BlockHeader, Tx } from '@aztec/stdlib/tx';
20
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
21
+ import { DutyType, type SigningContext } from '@aztec/validator-ha-signer/types';
21
22
 
22
23
  import type { ValidatorKeyStore } from '../key_store/interface.js';
23
24
 
24
25
  export class ValidationService {
25
26
  constructor(
26
27
  private keyStore: ValidatorKeyStore,
28
+ private signatureContext: CoordinationSignatureContext,
27
29
  private log = createLogger('validator:validation-service'),
28
30
  ) {}
29
31
 
@@ -31,39 +33,55 @@ export class ValidationService {
31
33
  * Create a block proposal with the given header, archive, and transactions
32
34
  *
33
35
  * @param blockHeader - The block header
34
- * @param indexWithinCheckpoint - Index of this block within the checkpoint (0-indexed)
36
+ * @param blockIndexWithinCheckpoint - The block index within checkpoint for HA signing context
35
37
  * @param inHash - Hash of L1 to L2 messages for this checkpoint
36
38
  * @param archive - The archive of the current block
37
- * @param txs - TxHash[] ordered list of transactions
39
+ * @param txs - Ordered list of transactions (Tx[])
40
+ * @param proposerAttesterAddress - The address of the proposer/attester, or undefined
38
41
  * @param options - Block proposal options (including broadcastInvalidBlockProposal for testing)
39
42
  *
40
43
  * @returns A block proposal signing the above information
44
+ * @throws DutyAlreadySignedError if HA signer indicates duty already signed by another node
45
+ * @throws SlashingProtectionError if attempting to sign different data for same slot
41
46
  */
42
47
  public createBlockProposal(
43
48
  blockHeader: BlockHeader,
44
- indexWithinCheckpoint: number,
49
+ checkpointNumber: CheckpointNumber,
50
+ blockIndexWithinCheckpoint: IndexWithinCheckpoint,
45
51
  inHash: Fr,
46
52
  archive: Fr,
47
53
  txs: Tx[],
48
54
  proposerAttesterAddress: EthAddress | undefined,
49
55
  options: BlockProposalOptions,
50
56
  ): Promise<BlockProposal> {
51
- const payloadSigner = this.getPayloadSigner(proposerAttesterAddress);
52
-
53
57
  // For testing: change the new archive to trigger state_mismatch validation failure
54
58
  if (options.broadcastInvalidBlockProposal) {
55
59
  archive = Fr.random();
56
60
  this.log.warn(`Creating INVALID block proposal for slot ${blockHeader.globalVariables.slotNumber}`);
57
61
  }
58
62
 
63
+ // Create a signer that uses the appropriate address
64
+ const address = proposerAttesterAddress ?? this.keyStore.getAddress(0);
65
+ const payloadSigner = (
66
+ typedData: Parameters<ValidatorKeyStore['signTypedDataWithAddress']>[1],
67
+ context: SigningContext,
68
+ ) => this.keyStore.signTypedDataWithAddress(address, typedData, context);
69
+ const txsSigner = (
70
+ typedData: Parameters<ValidatorKeyStore['signTypedDataWithAddress']>[1],
71
+ context: SigningContext,
72
+ ) => this.keyStore.signTypedDataWithAddress(address, typedData, context);
73
+
59
74
  return BlockProposal.createProposalFromSigner(
60
75
  blockHeader,
61
- indexWithinCheckpoint,
76
+ checkpointNumber,
77
+ blockIndexWithinCheckpoint,
62
78
  inHash,
63
79
  archive,
64
80
  txs.map(tx => tx.getTxHash()),
65
81
  options.publishFullTxs ? txs : undefined,
82
+ this.signatureContext,
66
83
  payloadSigner,
84
+ txsSigner,
67
85
  );
68
86
  }
69
87
 
@@ -72,7 +90,7 @@ export class ValidationService {
72
90
  *
73
91
  * @param checkpointHeader - The checkpoint header containing aggregated data
74
92
  * @param archive - The archive of the checkpoint
75
- * @param lastBlockInfo - Info about the last block (header, index, txs) or undefined
93
+ * @param lastBlockProposal - Signed block proposal for the last block in the checkpoint, or undefined
76
94
  * @param proposerAttesterAddress - The address of the proposer
77
95
  * @param options - Checkpoint proposal options
78
96
  *
@@ -81,37 +99,43 @@ export class ValidationService {
81
99
  public createCheckpointProposal(
82
100
  checkpointHeader: CheckpointHeader,
83
101
  archive: Fr,
84
- lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
102
+ checkpointNumber: CheckpointNumber,
103
+ feeAssetPriceModifier: bigint,
104
+ lastBlockProposal: BlockProposal | undefined,
85
105
  proposerAttesterAddress: EthAddress | undefined,
86
106
  options: CheckpointProposalOptions,
87
107
  ): Promise<CheckpointProposal> {
88
- const payloadSigner = this.getPayloadSigner(proposerAttesterAddress);
89
-
90
- // For testing: change the archive to trigger state_mismatch validation failure
108
+ // For testing: corrupt the checkpoint so observers' checkpoint validation fails.
109
+ //
110
+ // Keep `archive` aligned with `lastBlockProposal.archiveRoot` so the archive-based lookup
111
+ // in `validateCheckpointProposal` (`getBlockData({ archive })`) still succeeds
91
112
  if (options.broadcastInvalidCheckpointProposal) {
92
- archive = Fr.random();
113
+ archive = lastBlockProposal?.archiveRoot ?? Fr.random();
114
+ checkpointHeader = CheckpointHeader.from({
115
+ ...checkpointHeader,
116
+ epochOutHash: Fr.random(),
117
+ });
93
118
  this.log.warn(`Creating INVALID checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
94
119
  }
95
120
 
96
- // Last block to include in the proposal
97
- const lastBlock = lastBlockInfo && {
98
- blockHeader: lastBlockInfo.blockHeader,
99
- indexWithinCheckpoint: lastBlockInfo.indexWithinCheckpoint,
100
- txHashes: lastBlockInfo.txs.map(tx => tx.getTxHash()),
101
- txs: options.publishFullTxs ? lastBlockInfo.txs : undefined,
121
+ // Create a signer that takes payload and context, and uses the appropriate address
122
+ const payloadSigner = (
123
+ typedData: Parameters<ValidatorKeyStore['signTypedDataWithAddress']>[1],
124
+ context: SigningContext,
125
+ ) => {
126
+ const address = proposerAttesterAddress ?? this.keyStore.getAddress(0);
127
+ return this.keyStore.signTypedDataWithAddress(address, typedData, context);
102
128
  };
103
129
 
104
- return CheckpointProposal.createProposalFromSigner(checkpointHeader, archive, lastBlock, payloadSigner);
105
- }
106
-
107
- private getPayloadSigner(proposerAttesterAddress: EthAddress | undefined): (payload: Buffer32) => Promise<Signature> {
108
- if (proposerAttesterAddress !== undefined) {
109
- return (payload: Buffer32) => this.keyStore.signMessageWithAddress(proposerAttesterAddress, payload);
110
- } else {
111
- // if there is no proposer attester address, just use the first signer
112
- const signer = this.keyStore.getAddress(0);
113
- return (payload: Buffer32) => this.keyStore.signMessageWithAddress(signer, payload);
114
- }
130
+ return CheckpointProposal.createProposalFromSigner(
131
+ checkpointHeader,
132
+ archive,
133
+ checkpointNumber,
134
+ feeAssetPriceModifier,
135
+ lastBlockProposal,
136
+ this.signatureContext,
137
+ payloadSigner,
138
+ );
115
139
  }
116
140
 
117
141
  /**
@@ -127,25 +151,74 @@ export class ValidationService {
127
151
  async attestToCheckpointProposal(
128
152
  proposal: CheckpointProposalCore,
129
153
  attestors: EthAddress[],
154
+ checkpointNumber: CheckpointNumber,
130
155
  ): Promise<CheckpointAttestation[]> {
131
156
  // Create the attestation payload from the checkpoint proposal
132
- const payload = new ConsensusPayload(proposal.checkpointHeader, proposal.archive);
133
- const buf = Buffer32.fromBuffer(
134
- keccak256(payload.getPayloadToSign(SignatureDomainSeparator.checkpointAttestation)),
157
+ const payload = new ConsensusPayload(
158
+ proposal.checkpointHeader,
159
+ proposal.archive,
160
+ proposal.feeAssetPriceModifier,
161
+ this.signatureContext,
135
162
  );
136
- const signatures = await Promise.all(
137
- attestors.map(attestor => this.keyStore.signMessageWithAddress(attestor, buf)),
163
+ const typedData = getCoordinationSignatureTypedData(payload);
164
+
165
+ const context: SigningContext = {
166
+ slot: proposal.slotNumber,
167
+ checkpointNumber,
168
+ dutyType: DutyType.ATTESTATION,
169
+ };
170
+
171
+ // Sign each attestor in parallel, catching HA errors per-attestor
172
+ const results = await Promise.allSettled(
173
+ attestors.map(async attestor => {
174
+ const sig = await this.keyStore.signTypedDataWithAddress(attestor, typedData, context);
175
+ return new CheckpointAttestation(payload, sig, proposal.signature);
176
+ }),
138
177
  );
139
- return signatures.map(sig => new CheckpointAttestation(payload, sig, proposal.signature));
178
+
179
+ const attestations: CheckpointAttestation[] = [];
180
+ for (let i = 0; i < results.length; i++) {
181
+ const result = results[i];
182
+ if (result.status === 'fulfilled') {
183
+ attestations.push(result.value);
184
+ } else {
185
+ const error = result.reason;
186
+ if (error instanceof DutyAlreadySignedError || error instanceof SlashingProtectionError) {
187
+ this.log.verbose(
188
+ `Attestation for slot ${proposal.slotNumber} by ${attestors[i]} already signed by another High-Availability node`,
189
+ );
190
+ // Continue with remaining attestors
191
+ } else {
192
+ throw error;
193
+ }
194
+ }
195
+ }
196
+
197
+ return attestations;
140
198
  }
141
199
 
142
- async signAttestationsAndSigners(
200
+ /**
201
+ * Sign attestations and signers payload
202
+ * @param attestationsAndSigners - The attestations and signers to sign
203
+ * @param proposer - The proposer address to sign with
204
+ * @param slot - The slot number for HA signing context
205
+ * @returns signature
206
+ * @throws DutyAlreadySignedError if already signed by another HA node
207
+ * @throws SlashingProtectionError if attempting to sign different data for same slot
208
+ */
209
+ signAttestationsAndSigners(
143
210
  attestationsAndSigners: CommitteeAttestationsAndSigners,
144
211
  proposer: EthAddress,
212
+ slot: SlotNumber,
213
+ checkpointNumber: CheckpointNumber,
145
214
  ): Promise<Signature> {
146
- const buf = Buffer32.fromBuffer(
147
- keccak256(attestationsAndSigners.getPayloadToSign(SignatureDomainSeparator.attestationsAndSigners)),
148
- );
149
- return await this.keyStore.signMessageWithAddress(proposer, buf);
215
+ const context: SigningContext = {
216
+ slot,
217
+ checkpointNumber,
218
+ dutyType: DutyType.ATTESTATIONS_AND_SIGNERS,
219
+ };
220
+
221
+ const typedData = getCoordinationSignatureTypedData(attestationsAndSigners);
222
+ return this.keyStore.signTypedDataWithAddress(proposer, typedData, context);
150
223
  }
151
224
  }
package/src/factory.ts CHANGED
@@ -4,16 +4,18 @@ import type { DateProvider } from '@aztec/foundation/timer';
4
4
  import type { KeystoreManager } from '@aztec/node-keystore';
5
5
  import { BlockProposalValidator, type P2PClient } from '@aztec/p2p';
6
6
  import type { L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
7
+ import type { CheckpointReexecutionTracker } from '@aztec/stdlib/checkpoint';
7
8
  import type { ValidatorClientFullConfig, WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
8
9
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
9
10
  import type { TelemetryClient } from '@aztec/telemetry-client';
11
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
10
12
 
11
- import { BlockProposalHandler } from './block_proposal_handler.js';
12
13
  import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
13
14
  import { ValidatorMetrics } from './metrics.js';
15
+ import { ProposalHandler } from './proposal_handler.js';
14
16
  import { ValidatorClient } from './validator.js';
15
17
 
16
- export function createBlockProposalHandler(
18
+ export function createProposalHandler(
17
19
  config: ValidatorClientFullConfig,
18
20
  deps: {
19
21
  checkpointsBuilder: FullNodeCheckpointsBuilder;
@@ -22,25 +24,37 @@ export function createBlockProposalHandler(
22
24
  l1ToL2MessageSource: L1ToL2MessageSource;
23
25
  p2pClient: P2PClient;
24
26
  epochCache: EpochCache;
27
+ blobClient: BlobClientInterface;
25
28
  dateProvider: DateProvider;
26
29
  telemetry: TelemetryClient;
30
+ reexecutionTracker: CheckpointReexecutionTracker;
27
31
  },
28
32
  ) {
29
33
  const metrics = new ValidatorMetrics(deps.telemetry);
30
34
  const blockProposalValidator = new BlockProposalValidator(deps.epochCache, {
31
35
  txsPermitted: !config.disableTransactions,
36
+ maxTxsPerBlock: config.validateMaxTxsPerBlock ?? config.validateMaxTxsPerCheckpoint,
37
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint,
38
+ signatureContext: {
39
+ chainId: config.l1ChainId,
40
+ rollupAddress: config.rollupAddress,
41
+ },
32
42
  });
33
- return new BlockProposalHandler(
43
+ return new ProposalHandler(
34
44
  deps.checkpointsBuilder,
35
45
  deps.worldState,
36
46
  deps.blockSource,
37
47
  deps.l1ToL2MessageSource,
38
48
  deps.p2pClient.getTxProvider(),
39
49
  blockProposalValidator,
50
+ deps.epochCache,
40
51
  config,
52
+ deps.blobClient,
53
+ deps.reexecutionTracker,
41
54
  metrics,
42
55
  deps.dateProvider,
43
56
  deps.telemetry,
57
+ undefined,
44
58
  );
45
59
  }
46
60
 
@@ -57,6 +71,8 @@ export function createValidatorClient(
57
71
  epochCache: EpochCache;
58
72
  keyStoreManager: KeystoreManager | undefined;
59
73
  blobClient: BlobClientInterface;
74
+ reexecutionTracker: CheckpointReexecutionTracker;
75
+ slashingProtectionDb?: SlashingProtectionDatabase;
60
76
  },
61
77
  ) {
62
78
  if (config.disableValidator || !deps.keyStoreManager) {
@@ -75,7 +91,9 @@ export function createValidatorClient(
75
91
  txProvider,
76
92
  deps.keyStoreManager,
77
93
  deps.blobClient,
94
+ deps.reexecutionTracker,
78
95
  deps.dateProvider,
79
96
  deps.telemetry,
97
+ deps.slashingProtectionDb,
80
98
  );
81
99
  }
package/src/index.ts CHANGED
@@ -1,7 +1,6 @@
1
- export * from './block_proposal_handler.js';
1
+ export * from './proposal_handler.js';
2
2
  export * from './checkpoint_builder.js';
3
3
  export * from './config.js';
4
4
  export * from './factory.js';
5
5
  export * from './validator.js';
6
6
  export * from './key_store/index.js';
7
- export * from './tx_validator/index.js';
@@ -0,0 +1,269 @@
1
+ /**
2
+ * High Availability Key Store
3
+ *
4
+ * A ValidatorKeyStore wrapper that adds slashing protection for HA validator setups.
5
+ * When multiple validator nodes are running, only one node will sign for a given duty.
6
+ */
7
+ import { Buffer32 } from '@aztec/foundation/buffer';
8
+ import type { EthAddress } from '@aztec/foundation/eth-address';
9
+ import type { Signature } from '@aztec/foundation/eth-signature';
10
+ import { createLogger } from '@aztec/foundation/log';
11
+ import type { EthRemoteSignerConfig } from '@aztec/node-keystore';
12
+ import type { AztecAddress } from '@aztec/stdlib/aztec-address';
13
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
14
+ import {
15
+ type HAProtectedSigningContext,
16
+ type SigningContext,
17
+ isHAProtectedContext,
18
+ } from '@aztec/validator-ha-signer/types';
19
+ import type { ValidatorHASigner } from '@aztec/validator-ha-signer/validator-ha-signer';
20
+
21
+ import { type TypedDataDefinition, hashTypedData } from 'viem';
22
+
23
+ import type { ExtendedValidatorKeyStore } from './interface.js';
24
+
25
+ /**
26
+ * High Availability Key Store
27
+ *
28
+ * Wraps a base ExtendedValidatorKeyStore and ValidatorHASigner to provide
29
+ * HA-protected signing operations (when context is provided).
30
+ *
31
+ * The extended interface methods (getAttesterAddresses, getCoinbaseAddress, etc.)
32
+ * are pure pass-through since they don't require HA coordination.
33
+ *
34
+ * Usage:
35
+ * ```typescript
36
+ * const baseKeyStore = NodeKeystoreAdapter.fromPrivateKeys(privateKeys);
37
+ * const haSigner = new ValidatorHASigner(db, config);
38
+ * const haKeyStore = new HAKeyStore(baseKeyStore, haSigner);
39
+ *
40
+ * // Without context - signs directly (no HA protection)
41
+ * const sig = await haKeyStore.signMessageWithAddress(addr, msg);
42
+ *
43
+ * // With context - HA protected, throws DutyAlreadySignedError if already signed
44
+ * const result = await haKeyStore.signMessageWithAddress(addr, msg, {
45
+ * slot: 100n,
46
+ * blockNumber: 50n,
47
+ * dutyType: DutyType.BLOCK_PROPOSAL,
48
+ * });
49
+ * ```
50
+ */
51
+ export class HAKeyStore implements ExtendedValidatorKeyStore {
52
+ private readonly log = createLogger('ha-key-store');
53
+
54
+ constructor(
55
+ private readonly baseKeyStore: ExtendedValidatorKeyStore,
56
+ private readonly haSigner: ValidatorHASigner,
57
+ ) {
58
+ this.log.info('HAKeyStore initialized', {
59
+ nodeId: haSigner.nodeId,
60
+ });
61
+ }
62
+
63
+ /**
64
+ * Sign typed data with all addresses.
65
+ * Coordinates across nodes to prevent double-signing for most duty types.
66
+ * AUTH_REQUEST and TXS duties bypass HA protection since signing multiple times is safe.
67
+ * Returns only signatures that were successfully claimed by this node.
68
+ */
69
+ async signTypedData(typedData: TypedDataDefinition, context: SigningContext): Promise<Signature[]> {
70
+ // no need for HA protection on auth request and txs signatures
71
+ if (!isHAProtectedContext(context)) {
72
+ return this.baseKeyStore.signTypedData(typedData, context);
73
+ }
74
+
75
+ // Sign each address with HA protection
76
+ const addresses = this.getAddresses();
77
+ const results = await Promise.allSettled(
78
+ addresses.map(addr => this.signTypedDataWithAddress(addr, typedData, context)),
79
+ );
80
+
81
+ // Filter out failures (already signed by other nodes or other errors)
82
+ return results
83
+ .filter((result): result is PromiseFulfilledResult<Signature> => {
84
+ if (result.status === 'fulfilled') {
85
+ return true;
86
+ }
87
+ // Log expected HA errors (already signed) at debug level
88
+ if (result.reason instanceof DutyAlreadySignedError) {
89
+ this.log.debug(`Duty already signed by another node`, {
90
+ dutyType: context.dutyType,
91
+ slot: context.slot,
92
+ signedByNode: result.reason.signedByNode,
93
+ });
94
+ return false;
95
+ }
96
+ // Re-throw unexpected errors
97
+ throw result.reason;
98
+ })
99
+ .map(result => result.value);
100
+ }
101
+
102
+ /**
103
+ * Sign a message with all addresses.
104
+ * Coordinates across nodes to prevent double-signing for most duty types.
105
+ * AUTH_REQUEST and TXS duties bypass HA protection since signing multiple times is safe.
106
+ * Returns only signatures that were successfully claimed by this node.
107
+ */
108
+ async signMessage(message: Buffer32, context: SigningContext): Promise<Signature[]> {
109
+ // no need for HA protection on auth request and txs signatures
110
+ if (!isHAProtectedContext(context)) {
111
+ return this.baseKeyStore.signMessage(message, context);
112
+ }
113
+
114
+ // Sign each address with HA protection
115
+ const addresses = this.getAddresses();
116
+ const results = await Promise.allSettled(
117
+ addresses.map(addr => this.signMessageWithAddress(addr, message, context)),
118
+ );
119
+
120
+ // Filter out failures (already signed by other nodes or other errors)
121
+ return results
122
+ .filter((result): result is PromiseFulfilledResult<Signature> => {
123
+ if (result.status === 'fulfilled') {
124
+ return true;
125
+ }
126
+ // Log expected HA errors (already signed) at debug level
127
+ if (result.reason instanceof DutyAlreadySignedError) {
128
+ this.log.debug(`Duty already signed by another node`, {
129
+ dutyType: context.dutyType,
130
+ slot: context.slot,
131
+ signedByNode: result.reason.signedByNode,
132
+ });
133
+ return false;
134
+ }
135
+ // Re-throw unexpected errors
136
+ throw result.reason;
137
+ })
138
+ .map(result => result.value);
139
+ }
140
+
141
+ /**
142
+ * Sign typed data with a specific address.
143
+ * Coordinates across nodes to prevent double-signing for most duty types.
144
+ * AUTH_REQUEST and TXS duties bypass HA protection since signing multiple times is safe.
145
+ * @throws DutyAlreadySignedError if the duty was already signed by another node
146
+ * @throws SlashingProtectionError if attempting to sign different data for the same slot
147
+ */
148
+ async signTypedDataWithAddress(
149
+ address: EthAddress,
150
+ typedData: TypedDataDefinition,
151
+ context: SigningContext,
152
+ ): Promise<Signature> {
153
+ // AUTH_REQUEST and TXS bypass HA protection - multiple signatures are safe
154
+ if (!isHAProtectedContext(context)) {
155
+ return this.baseKeyStore.signTypedDataWithAddress(address, typedData, context);
156
+ }
157
+
158
+ // Compute signing root from typed data for HA tracking
159
+ const digest = hashTypedData(typedData);
160
+ const messageHash = Buffer32.fromString(digest);
161
+
162
+ try {
163
+ return await this.haSigner.signWithProtection(address, messageHash, context, () =>
164
+ this.baseKeyStore.signTypedDataWithAddress(address, typedData, context),
165
+ );
166
+ } catch (error) {
167
+ this.processSigningError(error, context);
168
+ throw error;
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Sign a message with a specific address.
174
+ * Coordinates across nodes to prevent double-signing for most duty types.
175
+ * AUTH_REQUEST and TXS duties bypass HA protection since signing multiple times is safe.
176
+ * @throws DutyAlreadySignedError if the duty was already signed by another node
177
+ * @throws SlashingProtectionError if attempting to sign different data for the same slot
178
+ */
179
+ async signMessageWithAddress(address: EthAddress, message: Buffer32, context: SigningContext): Promise<Signature> {
180
+ // no need for HA protection on auth request and txs signatures
181
+ if (!isHAProtectedContext(context)) {
182
+ return this.baseKeyStore.signMessageWithAddress(address, message, context);
183
+ }
184
+
185
+ try {
186
+ return await this.haSigner.signWithProtection(address, message, context, messageHash =>
187
+ this.baseKeyStore.signMessageWithAddress(address, messageHash, context),
188
+ );
189
+ } catch (error) {
190
+ this.processSigningError(error, context);
191
+ throw error;
192
+ }
193
+ }
194
+
195
+ // ─────────────────────────────────────────────────────────────────────────────
196
+ // pass-through methods (no HA logic needed)
197
+ // ─────────────────────────────────────────────────────────────────────────────
198
+
199
+ getAddress(index: number): EthAddress {
200
+ return this.baseKeyStore.getAddress(index);
201
+ }
202
+
203
+ getAddresses(): EthAddress[] {
204
+ return this.baseKeyStore.getAddresses();
205
+ }
206
+
207
+ getAttesterAddresses(): EthAddress[] {
208
+ return this.baseKeyStore.getAttesterAddresses();
209
+ }
210
+
211
+ getCoinbaseAddress(attesterAddress: EthAddress): EthAddress {
212
+ return this.baseKeyStore.getCoinbaseAddress(attesterAddress);
213
+ }
214
+
215
+ getPublisherAddresses(attesterAddress: EthAddress): EthAddress[] {
216
+ return this.baseKeyStore.getPublisherAddresses(attesterAddress);
217
+ }
218
+
219
+ getFeeRecipient(attesterAddress: EthAddress): AztecAddress {
220
+ return this.baseKeyStore.getFeeRecipient(attesterAddress);
221
+ }
222
+
223
+ getRemoteSignerConfig(attesterAddress: EthAddress): EthRemoteSignerConfig | undefined {
224
+ return this.baseKeyStore.getRemoteSignerConfig(attesterAddress);
225
+ }
226
+
227
+ /**
228
+ * Process signing errors from the HA signer.
229
+ * Logs expected HA errors (already signed) at appropriate levels.
230
+ * Re-throws unexpected errors.
231
+ */
232
+ private processSigningError(error: unknown, context: HAProtectedSigningContext) {
233
+ if (error instanceof DutyAlreadySignedError) {
234
+ this.log.debug(`Duty already signed by another node with the same payload`, {
235
+ dutyType: context.dutyType,
236
+ slot: context.slot,
237
+ signedByNode: error.signedByNode,
238
+ });
239
+ return;
240
+ }
241
+
242
+ if (error instanceof SlashingProtectionError) {
243
+ this.log.info(`Duty already signed by another node with different payload`, {
244
+ dutyType: context.dutyType,
245
+ slot: context.slot,
246
+ existingMessageHash: error.existingMessageHash,
247
+ attemptedMessageHash: error.attemptedMessageHash,
248
+ });
249
+ return;
250
+ }
251
+
252
+ // Re-throw errors
253
+ throw error;
254
+ }
255
+
256
+ /**
257
+ * Start the high-availability key store
258
+ */
259
+ public async start() {
260
+ await this.haSigner.start();
261
+ }
262
+
263
+ /**
264
+ * Stop the high-availability key store
265
+ */
266
+ public async stop() {
267
+ await this.haSigner.stop();
268
+ }
269
+ }
@@ -2,3 +2,4 @@ export * from './interface.js';
2
2
  export * from './local_key_store.js';
3
3
  export * from './node_keystore_adapter.js';
4
4
  export * from './web3signer_key_store.js';
5
+ export * from './ha_key_store.js';