@aztec/validator-client 0.0.0-test.1 → 0.0.1-commit.017a351

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 (66) hide show
  1. package/README.md +325 -0
  2. package/dest/checkpoint_builder.d.ts +79 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +251 -0
  5. package/dest/config.d.ts +3 -14
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +75 -12
  8. package/dest/duties/validation_service.d.ts +49 -13
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +112 -18
  11. package/dest/factory.d.ts +34 -6
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +19 -6
  14. package/dest/index.d.ts +5 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +4 -1
  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 +4 -1
  21. package/dest/key_store/index.d.ts.map +1 -1
  22. package/dest/key_store/index.js +3 -0
  23. package/dest/key_store/interface.d.ts +85 -6
  24. package/dest/key_store/interface.d.ts.map +1 -1
  25. package/dest/key_store/interface.js +3 -3
  26. package/dest/key_store/local_key_store.d.ts +46 -11
  27. package/dest/key_store/local_key_store.d.ts.map +1 -1
  28. package/dest/key_store/local_key_store.js +68 -17
  29. package/dest/key_store/node_keystore_adapter.d.ts +151 -0
  30. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -0
  31. package/dest/key_store/node_keystore_adapter.js +330 -0
  32. package/dest/key_store/web3signer_key_store.d.ts +66 -0
  33. package/dest/key_store/web3signer_key_store.d.ts.map +1 -0
  34. package/dest/key_store/web3signer_key_store.js +156 -0
  35. package/dest/metrics.d.ts +25 -5
  36. package/dest/metrics.d.ts.map +1 -1
  37. package/dest/metrics.js +86 -21
  38. package/dest/proposal_handler.d.ts +134 -0
  39. package/dest/proposal_handler.d.ts.map +1 -0
  40. package/dest/proposal_handler.js +1072 -0
  41. package/dest/validator.d.ts +109 -59
  42. package/dest/validator.d.ts.map +1 -1
  43. package/dest/validator.js +698 -171
  44. package/package.json +37 -21
  45. package/src/checkpoint_builder.ts +417 -0
  46. package/src/config.ts +87 -26
  47. package/src/duties/validation_service.ts +200 -21
  48. package/src/factory.ts +82 -11
  49. package/src/index.ts +4 -1
  50. package/src/key_store/ha_key_store.ts +269 -0
  51. package/src/key_store/index.ts +3 -0
  52. package/src/key_store/interface.ts +100 -5
  53. package/src/key_store/local_key_store.ts +77 -18
  54. package/src/key_store/node_keystore_adapter.ts +398 -0
  55. package/src/key_store/web3signer_key_store.ts +205 -0
  56. package/src/metrics.ts +121 -22
  57. package/src/proposal_handler.ts +1161 -0
  58. package/src/validator.ts +975 -222
  59. package/dest/errors/index.d.ts +0 -2
  60. package/dest/errors/index.d.ts.map +0 -1
  61. package/dest/errors/index.js +0 -1
  62. package/dest/errors/validator.error.d.ts +0 -29
  63. package/dest/errors/validator.error.d.ts.map +0 -1
  64. package/dest/errors/validator.error.js +0 -45
  65. package/src/errors/index.ts +0 -1
  66. package/src/errors/validator.error.ts +0 -55
@@ -1,45 +1,224 @@
1
- import { Buffer32 } from '@aztec/foundation/buffer';
2
- import { keccak256 } from '@aztec/foundation/crypto';
3
- import type { Fr } from '@aztec/foundation/fields';
4
- import { BlockAttestation, BlockProposal, ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
5
- import type { BlockHeader, TxHash } from '@aztec/stdlib/tx';
1
+ import { type CheckpointNumber, IndexWithinCheckpoint, type SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
+ import type { EthAddress } from '@aztec/foundation/eth-address';
4
+ import type { Signature } from '@aztec/foundation/eth-signature';
5
+ import { createLogger } from '@aztec/foundation/log';
6
+ import { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
7
+ import {
8
+ BlockProposal,
9
+ type BlockProposalOptions,
10
+ CheckpointAttestation,
11
+ CheckpointProposal,
12
+ type CheckpointProposalCore,
13
+ type CheckpointProposalOptions,
14
+ ConsensusPayload,
15
+ type CoordinationSignatureContext,
16
+ getCoordinationSignatureTypedData,
17
+ } from '@aztec/stdlib/p2p';
18
+ import { CheckpointHeader } from '@aztec/stdlib/rollup';
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';
6
22
 
7
23
  import type { ValidatorKeyStore } from '../key_store/interface.js';
8
24
 
9
25
  export class ValidationService {
10
- constructor(private keyStore: ValidatorKeyStore) {}
26
+ constructor(
27
+ private keyStore: ValidatorKeyStore,
28
+ private signatureContext: CoordinationSignatureContext,
29
+ private log = createLogger('validator:validation-service'),
30
+ ) {}
11
31
 
12
32
  /**
13
33
  * Create a block proposal with the given header, archive, and transactions
14
34
  *
15
- * @param header - The block header
35
+ * @param blockHeader - The block header
36
+ * @param blockIndexWithinCheckpoint - The block index within checkpoint for HA signing context
37
+ * @param inHash - Hash of L1 to L2 messages for this checkpoint
16
38
  * @param archive - The archive of the current block
17
- * @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
41
+ * @param options - Block proposal options (including broadcastInvalidBlockProposal for testing)
18
42
  *
19
- * @returns A block proposal signing the above information (not the current implementation!!!)
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
20
46
  */
21
- createBlockProposal(header: BlockHeader, archive: Fr, txs: TxHash[]): Promise<BlockProposal> {
22
- const payloadSigner = (payload: Buffer32) => this.keyStore.signMessage(payload);
47
+ public createBlockProposal(
48
+ blockHeader: BlockHeader,
49
+ checkpointNumber: CheckpointNumber,
50
+ blockIndexWithinCheckpoint: IndexWithinCheckpoint,
51
+ inHash: Fr,
52
+ archive: Fr,
53
+ txs: Tx[],
54
+ proposerAttesterAddress: EthAddress | undefined,
55
+ options: BlockProposalOptions,
56
+ ): Promise<BlockProposal> {
57
+ // For testing: change the new archive to trigger state_mismatch validation failure
58
+ if (options.broadcastInvalidBlockProposal) {
59
+ archive = Fr.random();
60
+ this.log.warn(`Creating INVALID block proposal for slot ${blockHeader.globalVariables.slotNumber}`);
61
+ }
23
62
 
24
- return BlockProposal.createProposalFromSigner(new ConsensusPayload(header, archive, txs), payloadSigner);
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
+
74
+ return BlockProposal.createProposalFromSigner(
75
+ blockHeader,
76
+ checkpointNumber,
77
+ blockIndexWithinCheckpoint,
78
+ inHash,
79
+ archive,
80
+ txs.map(tx => tx.getTxHash()),
81
+ options.publishFullTxs ? txs : undefined,
82
+ this.signatureContext,
83
+ payloadSigner,
84
+ txsSigner,
85
+ );
86
+ }
87
+
88
+ /**
89
+ * Create a checkpoint proposal with the last block header and checkpoint header
90
+ *
91
+ * @param checkpointHeader - The checkpoint header containing aggregated data
92
+ * @param archive - The archive of the checkpoint
93
+ * @param lastBlockProposal - Signed block proposal for the last block in the checkpoint, or undefined
94
+ * @param proposerAttesterAddress - The address of the proposer
95
+ * @param options - Checkpoint proposal options
96
+ *
97
+ * @returns A checkpoint proposal signing the above information
98
+ */
99
+ public createCheckpointProposal(
100
+ checkpointHeader: CheckpointHeader,
101
+ archive: Fr,
102
+ checkpointNumber: CheckpointNumber,
103
+ feeAssetPriceModifier: bigint,
104
+ lastBlockProposal: BlockProposal | undefined,
105
+ proposerAttesterAddress: EthAddress | undefined,
106
+ options: CheckpointProposalOptions,
107
+ ): Promise<CheckpointProposal> {
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
112
+ if (options.broadcastInvalidCheckpointProposal) {
113
+ archive = lastBlockProposal?.archiveRoot ?? Fr.random();
114
+ checkpointHeader = CheckpointHeader.from({
115
+ ...checkpointHeader,
116
+ epochOutHash: Fr.random(),
117
+ });
118
+ this.log.warn(`Creating INVALID checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
119
+ }
120
+
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);
128
+ };
129
+
130
+ return CheckpointProposal.createProposalFromSigner(
131
+ checkpointHeader,
132
+ archive,
133
+ checkpointNumber,
134
+ feeAssetPriceModifier,
135
+ lastBlockProposal,
136
+ this.signatureContext,
137
+ payloadSigner,
138
+ );
25
139
  }
26
140
 
27
141
  /**
28
- * Attest to the given block proposal constructed by the current sequencer
142
+ * Attest with selection of validators to the given checkpoint proposal
29
143
  *
30
144
  * NOTE: This is just a blind signing.
31
145
  * We assume that the proposal is valid and DA guarantees have been checked previously.
32
146
  *
33
- * @param proposal - The proposal to attest to
34
- * @returns attestation
147
+ * @param proposal - The checkpoint proposal (core version without lastBlock) to attest to
148
+ * @param attestors - The validators to attest with
149
+ * @returns checkpoint attestations
35
150
  */
36
- async attestToProposal(proposal: BlockProposal): Promise<BlockAttestation> {
37
- // TODO(https://github.com/AztecProtocol/aztec-packages/issues/7961): check that the current validator is correct
151
+ async attestToCheckpointProposal(
152
+ proposal: CheckpointProposalCore,
153
+ attestors: EthAddress[],
154
+ checkpointNumber: CheckpointNumber,
155
+ ): Promise<CheckpointAttestation[]> {
156
+ // Create the attestation payload from the checkpoint proposal
157
+ const payload = new ConsensusPayload(
158
+ proposal.checkpointHeader,
159
+ proposal.archive,
160
+ proposal.feeAssetPriceModifier,
161
+ this.signatureContext,
162
+ );
163
+ const typedData = getCoordinationSignatureTypedData(payload);
164
+
165
+ const context: SigningContext = {
166
+ slot: proposal.slotNumber,
167
+ checkpointNumber,
168
+ dutyType: DutyType.ATTESTATION,
169
+ };
38
170
 
39
- const buf = Buffer32.fromBuffer(
40
- keccak256(await proposal.payload.getPayloadToSign(SignatureDomainSeparator.blockAttestation)),
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
+ }),
41
177
  );
42
- const sig = await this.keyStore.signMessage(buf);
43
- return new BlockAttestation(proposal.payload, sig);
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;
198
+ }
199
+
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(
210
+ attestationsAndSigners: CommitteeAttestationsAndSigners,
211
+ proposer: EthAddress,
212
+ slot: SlotNumber,
213
+ checkpointNumber: CheckpointNumber,
214
+ ): Promise<Signature> {
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);
44
223
  }
45
224
  }
package/src/factory.ts CHANGED
@@ -1,28 +1,99 @@
1
+ import type { BlobClientInterface } from '@aztec/blob-client/client';
1
2
  import type { EpochCache } from '@aztec/epoch-cache';
2
3
  import type { DateProvider } from '@aztec/foundation/timer';
3
- import type { P2P } from '@aztec/p2p';
4
+ import type { KeystoreManager } from '@aztec/node-keystore';
5
+ import { BlockProposalValidator, type P2PClient } from '@aztec/p2p';
6
+ import type { L2BlockSink, L2BlockSource } from '@aztec/stdlib/block';
7
+ import type { CheckpointReexecutionTracker } from '@aztec/stdlib/checkpoint';
8
+ import type { ValidatorClientFullConfig, WorldStateSynchronizer } from '@aztec/stdlib/interfaces/server';
9
+ import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
4
10
  import type { TelemetryClient } from '@aztec/telemetry-client';
11
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
5
12
 
6
- import { generatePrivateKey } from 'viem/accounts';
7
-
8
- import type { ValidatorClientConfig } from './config.js';
13
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
14
+ import { ValidatorMetrics } from './metrics.js';
15
+ import { ProposalHandler } from './proposal_handler.js';
9
16
  import { ValidatorClient } from './validator.js';
10
17
 
18
+ export function createProposalHandler(
19
+ config: ValidatorClientFullConfig,
20
+ deps: {
21
+ checkpointsBuilder: FullNodeCheckpointsBuilder;
22
+ worldState: WorldStateSynchronizer;
23
+ blockSource: L2BlockSource & L2BlockSink;
24
+ l1ToL2MessageSource: L1ToL2MessageSource;
25
+ p2pClient: P2PClient;
26
+ epochCache: EpochCache;
27
+ blobClient: BlobClientInterface;
28
+ dateProvider: DateProvider;
29
+ telemetry: TelemetryClient;
30
+ reexecutionTracker: CheckpointReexecutionTracker;
31
+ },
32
+ ) {
33
+ const metrics = new ValidatorMetrics(deps.telemetry);
34
+ const blockProposalValidator = new BlockProposalValidator(deps.epochCache, {
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
+ },
42
+ });
43
+ return new ProposalHandler(
44
+ deps.checkpointsBuilder,
45
+ deps.worldState,
46
+ deps.blockSource,
47
+ deps.l1ToL2MessageSource,
48
+ deps.p2pClient.getTxProvider(),
49
+ blockProposalValidator,
50
+ deps.epochCache,
51
+ config,
52
+ deps.blobClient,
53
+ deps.reexecutionTracker,
54
+ metrics,
55
+ deps.dateProvider,
56
+ deps.telemetry,
57
+ undefined,
58
+ );
59
+ }
60
+
11
61
  export function createValidatorClient(
12
- config: ValidatorClientConfig,
62
+ config: ValidatorClientFullConfig,
13
63
  deps: {
14
- p2pClient: P2P;
64
+ checkpointsBuilder: FullNodeCheckpointsBuilder;
65
+ worldState: WorldStateSynchronizer;
66
+ p2pClient: P2PClient;
67
+ blockSource: L2BlockSource & L2BlockSink;
68
+ l1ToL2MessageSource: L1ToL2MessageSource;
15
69
  telemetry: TelemetryClient;
16
70
  dateProvider: DateProvider;
17
71
  epochCache: EpochCache;
72
+ keyStoreManager: KeystoreManager | undefined;
73
+ blobClient: BlobClientInterface;
74
+ reexecutionTracker: CheckpointReexecutionTracker;
75
+ slashingProtectionDb?: SlashingProtectionDatabase;
18
76
  },
19
77
  ) {
20
- if (config.disableValidator) {
78
+ if (config.disableValidator || !deps.keyStoreManager) {
21
79
  return undefined;
22
80
  }
23
- if (config.validatorPrivateKey === undefined || config.validatorPrivateKey === '') {
24
- config.validatorPrivateKey = generatePrivateKey();
25
- }
26
81
 
27
- return ValidatorClient.new(config, deps.epochCache, deps.p2pClient, deps.dateProvider, deps.telemetry);
82
+ const txProvider = deps.p2pClient.getTxProvider();
83
+ return ValidatorClient.new(
84
+ config,
85
+ deps.checkpointsBuilder,
86
+ deps.worldState,
87
+ deps.epochCache,
88
+ deps.p2pClient,
89
+ deps.blockSource,
90
+ deps.l1ToL2MessageSource,
91
+ txProvider,
92
+ deps.keyStoreManager,
93
+ deps.blobClient,
94
+ deps.reexecutionTracker,
95
+ deps.dateProvider,
96
+ deps.telemetry,
97
+ deps.slashingProtectionDb,
98
+ );
28
99
  }
package/src/index.ts CHANGED
@@ -1,3 +1,6 @@
1
+ export * from './proposal_handler.js';
2
+ export * from './checkpoint_builder.js';
1
3
  export * from './config.js';
2
- export * from './validator.js';
3
4
  export * from './factory.js';
5
+ export * from './validator.js';
6
+ export * from './key_store/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
+ }
@@ -1,2 +1,5 @@
1
1
  export * from './interface.js';
2
2
  export * from './local_key_store.js';
3
+ export * from './node_keystore_adapter.js';
4
+ export * from './web3signer_key_store.js';
5
+ export * from './ha_key_store.js';