@aztec/validator-client 0.0.1-commit.d3ec352c → 0.0.1-commit.d58ff9d0

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 (61) hide show
  1. package/README.md +327 -0
  2. package/dest/checkpoint_builder.d.ts +81 -0
  3. package/dest/checkpoint_builder.d.ts.map +1 -0
  4. package/dest/checkpoint_builder.js +259 -0
  5. package/dest/config.d.ts +9 -3
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +56 -14
  8. package/dest/duties/validation_service.d.ts +44 -16
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +102 -31
  11. package/dest/factory.d.ts +22 -11
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +19 -6
  14. package/dest/index.d.ts +3 -2
  15. package/dest/index.d.ts.map +1 -1
  16. package/dest/index.js +2 -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 +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 +9 -5
  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 +19 -6
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +41 -46
  34. package/dest/metrics.d.ts +16 -3
  35. package/dest/metrics.d.ts.map +1 -1
  36. package/dest/metrics.js +58 -30
  37. package/dest/proposal_handler.d.ts +165 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +1207 -0
  40. package/dest/validator.d.ts +93 -25
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +491 -89
  43. package/package.json +21 -11
  44. package/src/checkpoint_builder.ts +426 -0
  45. package/src/config.ts +63 -15
  46. package/src/duties/validation_service.ts +168 -41
  47. package/src/factory.ts +46 -12
  48. package/src/index.ts +2 -1
  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 +14 -5
  53. package/src/key_store/node_keystore_adapter.ts +28 -5
  54. package/src/key_store/web3signer_key_store.ts +61 -64
  55. package/src/metrics.ts +81 -33
  56. package/src/proposal_handler.ts +1314 -0
  57. package/src/validator.ts +721 -139
  58. package/dest/block_proposal_handler.d.ts +0 -53
  59. package/dest/block_proposal_handler.d.ts.map +0 -1
  60. package/dest/block_proposal_handler.js +0 -290
  61. package/src/block_proposal_handler.ts +0 -344
@@ -1,97 +1,224 @@
1
- import { Buffer32 } from '@aztec/foundation/buffer';
2
- import { keccak256 } from '@aztec/foundation/crypto';
1
+ import { type CheckpointNumber, IndexWithinCheckpoint, type SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
3
  import type { EthAddress } from '@aztec/foundation/eth-address';
4
4
  import type { Signature } from '@aztec/foundation/eth-signature';
5
- import { Fr } from '@aztec/foundation/fields';
6
5
  import { createLogger } from '@aztec/foundation/log';
7
- import type { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
6
+ import { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
8
7
  import {
9
- BlockAttestation,
10
8
  BlockProposal,
11
9
  type BlockProposalOptions,
10
+ CheckpointAttestation,
11
+ CheckpointProposal,
12
+ type CheckpointProposalCore,
13
+ type CheckpointProposalOptions,
12
14
  ConsensusPayload,
13
- SignatureDomainSeparator,
15
+ type CoordinationSignatureContext,
16
+ getCoordinationSignatureTypedData,
14
17
  } from '@aztec/stdlib/p2p';
15
- import type { CheckpointHeader } from '@aztec/stdlib/rollup';
16
- import type { Tx } from '@aztec/stdlib/tx';
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';
17
22
 
18
23
  import type { ValidatorKeyStore } from '../key_store/interface.js';
19
24
 
20
25
  export class ValidationService {
21
26
  constructor(
22
27
  private keyStore: ValidatorKeyStore,
28
+ private signatureContext: CoordinationSignatureContext,
23
29
  private log = createLogger('validator:validation-service'),
24
30
  ) {}
25
31
 
26
32
  /**
27
33
  * Create a block proposal with the given header, archive, and transactions
28
34
  *
29
- * @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
30
38
  * @param archive - The archive of the current block
31
- * @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
32
41
  * @param options - Block proposal options (including broadcastInvalidBlockProposal for testing)
33
42
  *
34
- * @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
35
46
  */
36
- async createBlockProposal(
37
- header: CheckpointHeader,
47
+ public createBlockProposal(
48
+ blockHeader: BlockHeader,
49
+ checkpointNumber: CheckpointNumber,
50
+ blockIndexWithinCheckpoint: IndexWithinCheckpoint,
51
+ inHash: Fr,
38
52
  archive: Fr,
39
53
  txs: Tx[],
40
54
  proposerAttesterAddress: EthAddress | undefined,
41
55
  options: BlockProposalOptions,
42
56
  ): Promise<BlockProposal> {
43
- let payloadSigner: (payload: Buffer32) => Promise<Signature>;
44
- if (proposerAttesterAddress !== undefined) {
45
- payloadSigner = (payload: Buffer32) => this.keyStore.signMessageWithAddress(proposerAttesterAddress, payload);
46
- } else {
47
- // if there is no proposer attester address, just use the first signer
48
- const signer = this.keyStore.getAddress(0);
49
- payloadSigner = (payload: Buffer32) => this.keyStore.signMessageWithAddress(signer, payload);
50
- }
51
- // TODO: check if this is calculated earlier / can not be recomputed
52
- const txHashes = await Promise.all(txs.map(tx => tx.getTxHash()));
53
-
54
57
  // For testing: change the new archive to trigger state_mismatch validation failure
55
58
  if (options.broadcastInvalidBlockProposal) {
56
59
  archive = Fr.random();
57
- this.log.warn(`Creating INVALID block proposal for slot ${header.slotNumber}`);
60
+ this.log.warn(`Creating INVALID block proposal for slot ${blockHeader.globalVariables.slotNumber}`);
58
61
  }
59
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
+
60
74
  return BlockProposal.createProposalFromSigner(
61
- new ConsensusPayload(header, archive),
62
- txHashes,
75
+ blockHeader,
76
+ checkpointNumber,
77
+ blockIndexWithinCheckpoint,
78
+ inHash,
79
+ archive,
80
+ txs.map(tx => tx.getTxHash()),
63
81
  options.publishFullTxs ? txs : undefined,
82
+ this.signatureContext,
64
83
  payloadSigner,
84
+ txsSigner,
65
85
  );
66
86
  }
67
87
 
68
88
  /**
69
- * Attest with selection of validators to the given block proposal, constructed by the current sequencer
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
+ );
139
+ }
140
+
141
+ /**
142
+ * Attest with selection of validators to the given checkpoint proposal
70
143
  *
71
144
  * NOTE: This is just a blind signing.
72
145
  * We assume that the proposal is valid and DA guarantees have been checked previously.
73
146
  *
74
- * @param proposal - The proposal to attest to
147
+ * @param proposal - The checkpoint proposal (core version without lastBlock) to attest to
75
148
  * @param attestors - The validators to attest with
76
- * @returns attestations
149
+ * @returns checkpoint attestations
77
150
  */
78
- async attestToProposal(proposal: BlockProposal, attestors: EthAddress[]): Promise<BlockAttestation[]> {
79
- const buf = Buffer32.fromBuffer(
80
- keccak256(proposal.payload.getPayloadToSign(SignatureDomainSeparator.blockAttestation)),
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,
81
162
  );
82
- const signatures = await Promise.all(
83
- 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
+ }),
84
177
  );
85
- return signatures.map(sig => new BlockAttestation(proposal.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;
86
198
  }
87
199
 
88
- 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(
89
210
  attestationsAndSigners: CommitteeAttestationsAndSigners,
90
211
  proposer: EthAddress,
212
+ slot: SlotNumber,
213
+ checkpointNumber: CheckpointNumber,
91
214
  ): Promise<Signature> {
92
- const buf = Buffer32.fromBuffer(
93
- keccak256(attestationsAndSigners.getPayloadToSign(SignatureDomainSeparator.attestationsAndSigners)),
94
- );
95
- 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);
96
223
  }
97
224
  }
package/src/factory.ts CHANGED
@@ -1,56 +1,86 @@
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
4
  import type { KeystoreManager } from '@aztec/node-keystore';
4
5
  import { BlockProposalValidator, type P2PClient } from '@aztec/p2p';
5
- import type { L2BlockSource } from '@aztec/stdlib/block';
6
- import type { IFullNodeBlockBuilder, ValidatorClientFullConfig } from '@aztec/stdlib/interfaces/server';
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';
7
9
  import type { L1ToL2MessageSource } from '@aztec/stdlib/messaging';
10
+ import { ConsensusTimetable } from '@aztec/stdlib/timetable';
8
11
  import type { TelemetryClient } from '@aztec/telemetry-client';
12
+ import type { SlashingProtectionDatabase } from '@aztec/validator-ha-signer/types';
9
13
 
10
- import { BlockProposalHandler } from './block_proposal_handler.js';
14
+ import type { FullNodeCheckpointsBuilder } from './checkpoint_builder.js';
15
+ import { DEFAULT_MAX_GOSSIP_CLOCK_DISPARITY_MS } from './config.js';
11
16
  import { ValidatorMetrics } from './metrics.js';
17
+ import { ProposalHandler } from './proposal_handler.js';
12
18
  import { ValidatorClient } from './validator.js';
13
19
 
14
- export function createBlockProposalHandler(
20
+ export function createProposalHandler(
15
21
  config: ValidatorClientFullConfig,
16
22
  deps: {
17
- blockBuilder: IFullNodeBlockBuilder;
18
- blockSource: L2BlockSource;
23
+ checkpointsBuilder: FullNodeCheckpointsBuilder;
24
+ worldState: WorldStateSynchronizer;
25
+ blockSource: L2BlockSource & L2BlockSink;
19
26
  l1ToL2MessageSource: L1ToL2MessageSource;
20
27
  p2pClient: P2PClient;
21
28
  epochCache: EpochCache;
29
+ blobClient: BlobClientInterface;
22
30
  dateProvider: DateProvider;
23
31
  telemetry: TelemetryClient;
32
+ reexecutionTracker: CheckpointReexecutionTracker;
24
33
  },
25
34
  ) {
26
35
  const metrics = new ValidatorMetrics(deps.telemetry);
27
- const blockProposalValidator = new BlockProposalValidator(deps.epochCache, {
36
+ const consensusTimetable = new ConsensusTimetable({
37
+ l1Constants: deps.epochCache.getL1Constants(),
38
+ blockDuration: config.blockDurationMs / 1000,
39
+ });
40
+ const blockProposalValidator = new BlockProposalValidator(deps.epochCache, consensusTimetable, {
28
41
  txsPermitted: !config.disableTransactions,
42
+ maxTxsPerBlock: config.validateMaxTxsPerBlock ?? config.validateMaxTxsPerCheckpoint,
43
+ maxBlocksPerCheckpoint: config.maxBlocksPerCheckpoint,
44
+ signatureContext: {
45
+ chainId: config.l1ChainId,
46
+ rollupAddress: config.rollupAddress,
47
+ },
48
+ clockDisparityMs: config.maxGossipClockDisparityMs ?? DEFAULT_MAX_GOSSIP_CLOCK_DISPARITY_MS,
29
49
  });
30
- return new BlockProposalHandler(
31
- deps.blockBuilder,
50
+ return new ProposalHandler(
51
+ deps.checkpointsBuilder,
52
+ deps.worldState,
32
53
  deps.blockSource,
33
54
  deps.l1ToL2MessageSource,
34
55
  deps.p2pClient.getTxProvider(),
35
56
  blockProposalValidator,
57
+ deps.epochCache,
58
+ consensusTimetable,
36
59
  config,
60
+ deps.blobClient,
61
+ deps.reexecutionTracker,
37
62
  metrics,
38
63
  deps.dateProvider,
39
64
  deps.telemetry,
65
+ undefined,
40
66
  );
41
67
  }
42
68
 
43
69
  export function createValidatorClient(
44
70
  config: ValidatorClientFullConfig,
45
71
  deps: {
46
- blockBuilder: IFullNodeBlockBuilder;
72
+ checkpointsBuilder: FullNodeCheckpointsBuilder;
73
+ worldState: WorldStateSynchronizer;
47
74
  p2pClient: P2PClient;
48
- blockSource: L2BlockSource;
75
+ blockSource: L2BlockSource & L2BlockSink;
49
76
  l1ToL2MessageSource: L1ToL2MessageSource;
50
77
  telemetry: TelemetryClient;
51
78
  dateProvider: DateProvider;
52
79
  epochCache: EpochCache;
53
80
  keyStoreManager: KeystoreManager | undefined;
81
+ blobClient: BlobClientInterface;
82
+ reexecutionTracker: CheckpointReexecutionTracker;
83
+ slashingProtectionDb?: SlashingProtectionDatabase;
54
84
  },
55
85
  ) {
56
86
  if (config.disableValidator || !deps.keyStoreManager) {
@@ -60,14 +90,18 @@ export function createValidatorClient(
60
90
  const txProvider = deps.p2pClient.getTxProvider();
61
91
  return ValidatorClient.new(
62
92
  config,
63
- deps.blockBuilder,
93
+ deps.checkpointsBuilder,
94
+ deps.worldState,
64
95
  deps.epochCache,
65
96
  deps.p2pClient,
66
97
  deps.blockSource,
67
98
  deps.l1ToL2MessageSource,
68
99
  txProvider,
69
100
  deps.keyStoreManager,
101
+ deps.blobClient,
102
+ deps.reexecutionTracker,
70
103
  deps.dateProvider,
71
104
  deps.telemetry,
105
+ deps.slashingProtectionDb,
72
106
  );
73
107
  }
package/src/index.ts CHANGED
@@ -1,4 +1,5 @@
1
- export * from './block_proposal_handler.js';
1
+ export * from './proposal_handler.js';
2
+ export * from './checkpoint_builder.js';
2
3
  export * from './config.js';
3
4
  export * from './factory.js';
4
5
  export * from './validator.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';