@aztec/validator-client 0.0.1-commit.fce3e4f → 0.0.1-commit.ff7989d6c

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 (69) hide show
  1. package/README.md +285 -0
  2. package/dest/block_proposal_handler.d.ts +24 -13
  3. package/dest/block_proposal_handler.d.ts.map +1 -1
  4. package/dest/block_proposal_handler.js +329 -87
  5. package/dest/checkpoint_builder.d.ts +66 -0
  6. package/dest/checkpoint_builder.d.ts.map +1 -0
  7. package/dest/checkpoint_builder.js +175 -0
  8. package/dest/config.d.ts +1 -1
  9. package/dest/config.d.ts.map +1 -1
  10. package/dest/config.js +16 -8
  11. package/dest/duties/validation_service.d.ts +42 -13
  12. package/dest/duties/validation_service.d.ts.map +1 -1
  13. package/dest/duties/validation_service.js +111 -28
  14. package/dest/factory.d.ts +13 -8
  15. package/dest/factory.d.ts.map +1 -1
  16. package/dest/factory.js +2 -2
  17. package/dest/index.d.ts +3 -1
  18. package/dest/index.d.ts.map +1 -1
  19. package/dest/index.js +2 -0
  20. package/dest/key_store/ha_key_store.d.ts +99 -0
  21. package/dest/key_store/ha_key_store.d.ts.map +1 -0
  22. package/dest/key_store/ha_key_store.js +208 -0
  23. package/dest/key_store/index.d.ts +2 -1
  24. package/dest/key_store/index.d.ts.map +1 -1
  25. package/dest/key_store/index.js +1 -0
  26. package/dest/key_store/interface.d.ts +36 -6
  27. package/dest/key_store/interface.d.ts.map +1 -1
  28. package/dest/key_store/local_key_store.d.ts +10 -5
  29. package/dest/key_store/local_key_store.d.ts.map +1 -1
  30. package/dest/key_store/local_key_store.js +9 -5
  31. package/dest/key_store/node_keystore_adapter.d.ts +18 -5
  32. package/dest/key_store/node_keystore_adapter.d.ts.map +1 -1
  33. package/dest/key_store/node_keystore_adapter.js +18 -4
  34. package/dest/key_store/web3signer_key_store.d.ts +10 -5
  35. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  36. package/dest/key_store/web3signer_key_store.js +9 -5
  37. package/dest/metrics.d.ts +4 -3
  38. package/dest/metrics.d.ts.map +1 -1
  39. package/dest/metrics.js +34 -30
  40. package/dest/tx_validator/index.d.ts +3 -0
  41. package/dest/tx_validator/index.d.ts.map +1 -0
  42. package/dest/tx_validator/index.js +2 -0
  43. package/dest/tx_validator/nullifier_cache.d.ts +14 -0
  44. package/dest/tx_validator/nullifier_cache.d.ts.map +1 -0
  45. package/dest/tx_validator/nullifier_cache.js +24 -0
  46. package/dest/tx_validator/tx_validator_factory.d.ts +19 -0
  47. package/dest/tx_validator/tx_validator_factory.d.ts.map +1 -0
  48. package/dest/tx_validator/tx_validator_factory.js +54 -0
  49. package/dest/validator.d.ts +74 -21
  50. package/dest/validator.d.ts.map +1 -1
  51. package/dest/validator.js +452 -56
  52. package/package.json +23 -13
  53. package/src/block_proposal_handler.ts +253 -59
  54. package/src/checkpoint_builder.ts +321 -0
  55. package/src/config.ts +15 -7
  56. package/src/duties/validation_service.ts +162 -33
  57. package/src/factory.ts +17 -8
  58. package/src/index.ts +2 -0
  59. package/src/key_store/ha_key_store.ts +269 -0
  60. package/src/key_store/index.ts +1 -0
  61. package/src/key_store/interface.ts +44 -5
  62. package/src/key_store/local_key_store.ts +14 -5
  63. package/src/key_store/node_keystore_adapter.ts +28 -5
  64. package/src/key_store/web3signer_key_store.ts +18 -5
  65. package/src/metrics.ts +45 -33
  66. package/src/tx_validator/index.ts +2 -0
  67. package/src/tx_validator/nullifier_cache.ts +30 -0
  68. package/src/tx_validator/tx_validator_factory.ts +154 -0
  69. package/src/validator.ts +619 -85
@@ -0,0 +1,321 @@
1
+ import { BlockNumber, CheckpointNumber } from '@aztec/foundation/branded-types';
2
+ import { merge, pick } from '@aztec/foundation/collection';
3
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
+ import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
5
+ import { bufferToHex } from '@aztec/foundation/string';
6
+ import { DateProvider, elapsed } from '@aztec/foundation/timer';
7
+ import { getDefaultAllowedSetupFunctions } from '@aztec/p2p/msg_validators';
8
+ import { LightweightCheckpointBuilder } from '@aztec/prover-client/light';
9
+ import {
10
+ GuardedMerkleTreeOperations,
11
+ PublicContractsDB,
12
+ PublicProcessor,
13
+ createPublicTxSimulatorForBlockBuilding,
14
+ } from '@aztec/simulator/server';
15
+ import { L2Block } from '@aztec/stdlib/block';
16
+ import { Checkpoint } from '@aztec/stdlib/checkpoint';
17
+ import type { ContractDataSource } from '@aztec/stdlib/contract';
18
+ import type { L1RollupConstants } from '@aztec/stdlib/epoch-helpers';
19
+ import { Gas } from '@aztec/stdlib/gas';
20
+ import {
21
+ type BuildBlockInCheckpointResult,
22
+ type FullNodeBlockBuilderConfig,
23
+ FullNodeBlockBuilderConfigKeys,
24
+ type ICheckpointBlockBuilder,
25
+ type ICheckpointsBuilder,
26
+ type MerkleTreeWriteOperations,
27
+ NoValidTxsError,
28
+ type PublicProcessorLimits,
29
+ type WorldStateSynchronizer,
30
+ } from '@aztec/stdlib/interfaces/server';
31
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
32
+ import { type CheckpointGlobalVariables, GlobalVariables, StateReference, Tx } from '@aztec/stdlib/tx';
33
+ import { type TelemetryClient, getTelemetryClient } from '@aztec/telemetry-client';
34
+
35
+ import { createValidatorForBlockBuilding } from './tx_validator/tx_validator_factory.js';
36
+
37
+ // Re-export for backward compatibility
38
+ export type { BuildBlockInCheckpointResult } from '@aztec/stdlib/interfaces/server';
39
+
40
+ /**
41
+ * Builder for a single checkpoint. Handles building blocks within the checkpoint
42
+ * and completing it.
43
+ */
44
+ export class CheckpointBuilder implements ICheckpointBlockBuilder {
45
+ private log: Logger;
46
+
47
+ constructor(
48
+ private checkpointBuilder: LightweightCheckpointBuilder,
49
+ private fork: MerkleTreeWriteOperations,
50
+ private config: FullNodeBlockBuilderConfig,
51
+ private contractDataSource: ContractDataSource,
52
+ private dateProvider: DateProvider,
53
+ private telemetryClient: TelemetryClient,
54
+ bindings?: LoggerBindings,
55
+ ) {
56
+ this.log = createLogger('checkpoint-builder', {
57
+ ...bindings,
58
+ instanceId: `checkpoint-${checkpointBuilder.checkpointNumber}`,
59
+ });
60
+ }
61
+
62
+ getConstantData(): CheckpointGlobalVariables {
63
+ return this.checkpointBuilder.constants;
64
+ }
65
+
66
+ /**
67
+ * Builds a single block within this checkpoint.
68
+ */
69
+ async buildBlock(
70
+ pendingTxs: Iterable<Tx> | AsyncIterable<Tx>,
71
+ blockNumber: BlockNumber,
72
+ timestamp: bigint,
73
+ opts: PublicProcessorLimits & { expectedEndState?: StateReference } = {},
74
+ ): Promise<BuildBlockInCheckpointResult> {
75
+ const slot = this.checkpointBuilder.constants.slotNumber;
76
+
77
+ this.log.verbose(`Building block ${blockNumber} for slot ${slot} within checkpoint`, {
78
+ slot,
79
+ blockNumber,
80
+ ...opts,
81
+ currentTime: new Date(this.dateProvider.now()),
82
+ });
83
+
84
+ const constants = this.checkpointBuilder.constants;
85
+ const globalVariables = GlobalVariables.from({
86
+ chainId: constants.chainId,
87
+ version: constants.version,
88
+ blockNumber,
89
+ slotNumber: constants.slotNumber,
90
+ timestamp,
91
+ coinbase: constants.coinbase,
92
+ feeRecipient: constants.feeRecipient,
93
+ gasFees: constants.gasFees,
94
+ });
95
+ const { processor, validator } = await this.makeBlockBuilderDeps(globalVariables, this.fork);
96
+
97
+ const [publicProcessorDuration, [processedTxs, failedTxs, usedTxs, _, usedTxBlobFields]] = await elapsed(() =>
98
+ processor.process(pendingTxs, opts, validator),
99
+ );
100
+
101
+ // Throw if we didn't collect a single valid tx and we're not allowed to build empty blocks
102
+ // (only the first block in a checkpoint can be empty)
103
+ if (processedTxs.length === 0 && this.checkpointBuilder.getBlockCount() > 0) {
104
+ throw new NoValidTxsError(failedTxs);
105
+ }
106
+
107
+ // Add block to checkpoint
108
+ const block = await this.checkpointBuilder.addBlock(globalVariables, processedTxs, {
109
+ expectedEndState: opts.expectedEndState,
110
+ });
111
+
112
+ // How much public gas was processed
113
+ const publicGas = processedTxs.reduce((acc, tx) => acc.add(tx.gasUsed.publicGas), Gas.empty());
114
+
115
+ this.log.debug('Built block within checkpoint', {
116
+ header: block.header.toInspect(),
117
+ processedTxs: processedTxs.map(tx => tx.hash.toString()),
118
+ failedTxs: failedTxs.map(tx => tx.tx.txHash.toString()),
119
+ });
120
+
121
+ return {
122
+ block,
123
+ publicGas,
124
+ publicProcessorDuration,
125
+ numTxs: processedTxs.length,
126
+ failedTxs,
127
+ usedTxs,
128
+ usedTxBlobFields,
129
+ };
130
+ }
131
+
132
+ /** Completes the checkpoint and returns it. */
133
+ async completeCheckpoint(): Promise<Checkpoint> {
134
+ const checkpoint = await this.checkpointBuilder.completeCheckpoint();
135
+
136
+ this.log.verbose(`Completed checkpoint ${checkpoint.number}`, {
137
+ checkpointNumber: checkpoint.number,
138
+ numBlocks: checkpoint.blocks.length,
139
+ archiveRoot: checkpoint.archive.root.toString(),
140
+ });
141
+
142
+ return checkpoint;
143
+ }
144
+
145
+ /** Gets the checkpoint currently in progress. */
146
+ getCheckpoint(): Promise<Checkpoint> {
147
+ return this.checkpointBuilder.clone().completeCheckpoint();
148
+ }
149
+
150
+ protected async makeBlockBuilderDeps(globalVariables: GlobalVariables, fork: MerkleTreeWriteOperations) {
151
+ const txPublicSetupAllowList = this.config.txPublicSetupAllowList ?? (await getDefaultAllowedSetupFunctions());
152
+ const contractsDB = new PublicContractsDB(this.contractDataSource, this.log.getBindings());
153
+ const guardedFork = new GuardedMerkleTreeOperations(fork);
154
+
155
+ const bindings = this.log.getBindings();
156
+ const publicTxSimulator = createPublicTxSimulatorForBlockBuilding(
157
+ guardedFork,
158
+ contractsDB,
159
+ globalVariables,
160
+ this.telemetryClient,
161
+ bindings,
162
+ );
163
+
164
+ const processor = new PublicProcessor(
165
+ globalVariables,
166
+ guardedFork,
167
+ contractsDB,
168
+ publicTxSimulator,
169
+ this.dateProvider,
170
+ this.telemetryClient,
171
+ createLogger('simulator:public-processor', bindings),
172
+ this.config,
173
+ );
174
+
175
+ const validator = createValidatorForBlockBuilding(
176
+ fork,
177
+ this.contractDataSource,
178
+ globalVariables,
179
+ txPublicSetupAllowList,
180
+ this.log.getBindings(),
181
+ );
182
+
183
+ return {
184
+ processor,
185
+ validator,
186
+ };
187
+ }
188
+ }
189
+
190
+ /** Factory for creating checkpoint builders. */
191
+ export class FullNodeCheckpointsBuilder implements ICheckpointsBuilder {
192
+ private log: Logger;
193
+
194
+ constructor(
195
+ private config: FullNodeBlockBuilderConfig & Pick<L1RollupConstants, 'l1GenesisTime' | 'slotDuration'>,
196
+ private worldState: WorldStateSynchronizer,
197
+ private contractDataSource: ContractDataSource,
198
+ private dateProvider: DateProvider,
199
+ private telemetryClient: TelemetryClient = getTelemetryClient(),
200
+ ) {
201
+ this.log = createLogger('checkpoint-builder');
202
+ }
203
+
204
+ public getConfig(): FullNodeBlockBuilderConfig {
205
+ return this.config;
206
+ }
207
+
208
+ public updateConfig(config: Partial<FullNodeBlockBuilderConfig>) {
209
+ this.config = merge(this.config, pick(config, ...FullNodeBlockBuilderConfigKeys));
210
+ }
211
+
212
+ /**
213
+ * Starts a new checkpoint and returns a CheckpointBuilder to build blocks within it.
214
+ */
215
+ async startCheckpoint(
216
+ checkpointNumber: CheckpointNumber,
217
+ constants: CheckpointGlobalVariables,
218
+ feeAssetPriceModifier: bigint,
219
+ l1ToL2Messages: Fr[],
220
+ previousCheckpointOutHashes: Fr[],
221
+ fork: MerkleTreeWriteOperations,
222
+ bindings?: LoggerBindings,
223
+ ): Promise<CheckpointBuilder> {
224
+ const stateReference = await fork.getStateReference();
225
+ const archiveTree = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
226
+
227
+ this.log.verbose(`Building new checkpoint ${checkpointNumber}`, {
228
+ checkpointNumber,
229
+ msgCount: l1ToL2Messages.length,
230
+ initialStateReference: stateReference.toInspect(),
231
+ initialArchiveRoot: bufferToHex(archiveTree.root),
232
+ constants,
233
+ feeAssetPriceModifier,
234
+ });
235
+
236
+ const lightweightBuilder = await LightweightCheckpointBuilder.startNewCheckpoint(
237
+ checkpointNumber,
238
+ constants,
239
+ l1ToL2Messages,
240
+ previousCheckpointOutHashes,
241
+ fork,
242
+ bindings,
243
+ feeAssetPriceModifier,
244
+ );
245
+
246
+ return new CheckpointBuilder(
247
+ lightweightBuilder,
248
+ fork,
249
+ this.config,
250
+ this.contractDataSource,
251
+ this.dateProvider,
252
+ this.telemetryClient,
253
+ bindings,
254
+ );
255
+ }
256
+
257
+ /**
258
+ * Opens a checkpoint, either starting fresh or resuming from existing blocks.
259
+ */
260
+ async openCheckpoint(
261
+ checkpointNumber: CheckpointNumber,
262
+ constants: CheckpointGlobalVariables,
263
+ feeAssetPriceModifier: bigint,
264
+ l1ToL2Messages: Fr[],
265
+ previousCheckpointOutHashes: Fr[],
266
+ fork: MerkleTreeWriteOperations,
267
+ existingBlocks: L2Block[] = [],
268
+ bindings?: LoggerBindings,
269
+ ): Promise<CheckpointBuilder> {
270
+ const stateReference = await fork.getStateReference();
271
+ const archiveTree = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
272
+
273
+ if (existingBlocks.length === 0) {
274
+ return this.startCheckpoint(
275
+ checkpointNumber,
276
+ constants,
277
+ feeAssetPriceModifier,
278
+ l1ToL2Messages,
279
+ previousCheckpointOutHashes,
280
+ fork,
281
+ bindings,
282
+ );
283
+ }
284
+
285
+ this.log.verbose(`Resuming checkpoint ${checkpointNumber} with ${existingBlocks.length} existing blocks`, {
286
+ checkpointNumber,
287
+ msgCount: l1ToL2Messages.length,
288
+ existingBlockCount: existingBlocks.length,
289
+ initialStateReference: stateReference.toInspect(),
290
+ initialArchiveRoot: bufferToHex(archiveTree.root),
291
+ constants,
292
+ feeAssetPriceModifier,
293
+ });
294
+
295
+ const lightweightBuilder = await LightweightCheckpointBuilder.resumeCheckpoint(
296
+ checkpointNumber,
297
+ constants,
298
+ feeAssetPriceModifier,
299
+ l1ToL2Messages,
300
+ previousCheckpointOutHashes,
301
+ fork,
302
+ existingBlocks,
303
+ bindings,
304
+ );
305
+
306
+ return new CheckpointBuilder(
307
+ lightweightBuilder,
308
+ fork,
309
+ this.config,
310
+ this.contractDataSource,
311
+ this.dateProvider,
312
+ this.telemetryClient,
313
+ bindings,
314
+ );
315
+ }
316
+
317
+ /** Returns a fork of the world state at the given block number. */
318
+ getFork(blockNumber: BlockNumber): Promise<MerkleTreeWriteOperations> {
319
+ return this.worldState.fork(blockNumber);
320
+ }
321
+ }
package/src/config.ts CHANGED
@@ -6,6 +6,7 @@ import {
6
6
  secretValueConfigHelper,
7
7
  } from '@aztec/foundation/config';
8
8
  import { EthAddress } from '@aztec/foundation/eth-address';
9
+ import { validatorHASignerConfigMappings } from '@aztec/stdlib/ha-signing';
9
10
  import type { ValidatorClientConfig } from '@aztec/stdlib/interfaces/server';
10
11
 
11
12
  export type { ValidatorClientConfig };
@@ -53,16 +54,10 @@ export const validatorClientConfigMappings: ConfigMappingsType<ValidatorClientCo
53
54
  description: 'Re-execute transactions before attesting',
54
55
  ...booleanConfigHelper(true),
55
56
  },
56
- validatorReexecuteDeadlineMs: {
57
- env: 'VALIDATOR_REEXECUTE_DEADLINE_MS',
58
- description: 'Will re-execute until this many milliseconds are left in the slot',
59
- ...numberConfigHelper(6000),
60
- },
61
57
  alwaysReexecuteBlockProposals: {
62
- env: 'ALWAYS_REEXECUTE_BLOCK_PROPOSALS',
63
58
  description:
64
59
  'Whether to always reexecute block proposals, even for non-validator nodes (useful for monitoring network status).',
65
- ...booleanConfigHelper(false),
60
+ defaultValue: true,
66
61
  },
67
62
  fishermanMode: {
68
63
  env: 'FISHERMAN_MODE',
@@ -70,6 +65,19 @@ export const validatorClientConfigMappings: ConfigMappingsType<ValidatorClientCo
70
65
  'Whether to run in fisherman mode: validates all proposals and attestations but does not broadcast attestations or participate in consensus.',
71
66
  ...booleanConfigHelper(false),
72
67
  },
68
+ skipCheckpointProposalValidation: {
69
+ description: 'Skip checkpoint proposal validation and always attest (default: false)',
70
+ defaultValue: false,
71
+ },
72
+ skipPushProposedBlocksToArchiver: {
73
+ description: 'Skip pushing re-executed blocks to archiver (default: false)',
74
+ defaultValue: false,
75
+ },
76
+ attestToEquivocatedProposals: {
77
+ description: 'Agree to attest to equivocated checkpoint proposals (for testing purposes only)',
78
+ ...booleanConfigHelper(false),
79
+ },
80
+ ...validatorHASignerConfigMappings,
73
81
  };
74
82
 
75
83
  /**
@@ -1,19 +1,31 @@
1
+ import {
2
+ BlockNumber,
3
+ type CheckpointNumber,
4
+ IndexWithinCheckpoint,
5
+ type SlotNumber,
6
+ } from '@aztec/foundation/branded-types';
1
7
  import { Buffer32 } from '@aztec/foundation/buffer';
2
- import { keccak256 } from '@aztec/foundation/crypto';
8
+ import { keccak256 } from '@aztec/foundation/crypto/keccak';
9
+ import { Fr } from '@aztec/foundation/curves/bn254';
3
10
  import type { EthAddress } from '@aztec/foundation/eth-address';
4
11
  import type { Signature } from '@aztec/foundation/eth-signature';
5
- import { Fr } from '@aztec/foundation/fields';
6
12
  import { createLogger } from '@aztec/foundation/log';
7
13
  import type { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
14
+ import type { CreateCheckpointProposalLastBlockData } from '@aztec/stdlib/interfaces/server';
8
15
  import {
9
- BlockAttestation,
10
16
  BlockProposal,
11
17
  type BlockProposalOptions,
18
+ CheckpointAttestation,
19
+ CheckpointProposal,
20
+ type CheckpointProposalCore,
21
+ type CheckpointProposalOptions,
12
22
  ConsensusPayload,
13
23
  SignatureDomainSeparator,
14
24
  } from '@aztec/stdlib/p2p';
15
25
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
16
- import type { Tx } from '@aztec/stdlib/tx';
26
+ import type { BlockHeader, Tx } from '@aztec/stdlib/tx';
27
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
28
+ import { DutyType, type SigningContext } from '@aztec/validator-ha-signer/types';
17
29
 
18
30
  import type { ValidatorKeyStore } from '../key_store/interface.js';
19
31
 
@@ -26,72 +38,189 @@ export class ValidationService {
26
38
  /**
27
39
  * Create a block proposal with the given header, archive, and transactions
28
40
  *
29
- * @param header - The block header
41
+ * @param blockHeader - The block header
42
+ * @param blockIndexWithinCheckpoint - The block index within checkpoint for HA signing context
43
+ * @param inHash - Hash of L1 to L2 messages for this checkpoint
30
44
  * @param archive - The archive of the current block
31
- * @param txs - TxHash[] ordered list of transactions
45
+ * @param txs - Ordered list of transactions (Tx[])
46
+ * @param proposerAttesterAddress - The address of the proposer/attester, or undefined
32
47
  * @param options - Block proposal options (including broadcastInvalidBlockProposal for testing)
33
48
  *
34
- * @returns A block proposal signing the above information (not the current implementation!!!)
49
+ * @returns A block proposal signing the above information
50
+ * @throws DutyAlreadySignedError if HA signer indicates duty already signed by another node
51
+ * @throws SlashingProtectionError if attempting to sign different data for same slot
35
52
  */
36
- async createBlockProposal(
37
- header: CheckpointHeader,
53
+ public createBlockProposal(
54
+ blockHeader: BlockHeader,
55
+ blockIndexWithinCheckpoint: IndexWithinCheckpoint,
56
+ inHash: Fr,
38
57
  archive: Fr,
39
58
  txs: Tx[],
40
59
  proposerAttesterAddress: EthAddress | undefined,
41
60
  options: BlockProposalOptions,
42
61
  ): 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
62
  // For testing: change the new archive to trigger state_mismatch validation failure
55
63
  if (options.broadcastInvalidBlockProposal) {
56
64
  archive = Fr.random();
57
- this.log.warn(`Creating INVALID block proposal for slot ${header.slotNumber}`);
65
+ this.log.warn(`Creating INVALID block proposal for slot ${blockHeader.globalVariables.slotNumber}`);
58
66
  }
59
67
 
68
+ // Create a signer that uses the appropriate address
69
+ const address = proposerAttesterAddress ?? this.keyStore.getAddress(0);
70
+ const payloadSigner = (payload: Buffer32, context: SigningContext) =>
71
+ this.keyStore.signMessageWithAddress(address, payload, context);
72
+
60
73
  return BlockProposal.createProposalFromSigner(
61
- new ConsensusPayload(header, archive),
62
- txHashes,
74
+ blockHeader,
75
+ blockIndexWithinCheckpoint,
76
+ inHash,
77
+ archive,
78
+ txs.map(tx => tx.getTxHash()),
63
79
  options.publishFullTxs ? txs : undefined,
64
80
  payloadSigner,
65
81
  );
66
82
  }
67
83
 
68
84
  /**
69
- * Attest with selection of validators to the given block proposal, constructed by the current sequencer
85
+ * Create a checkpoint proposal with the last block header and checkpoint header
86
+ *
87
+ * @param checkpointHeader - The checkpoint header containing aggregated data
88
+ * @param archive - The archive of the checkpoint
89
+ * @param lastBlockInfo - Info about the last block (header, index, txs) or undefined
90
+ * @param proposerAttesterAddress - The address of the proposer
91
+ * @param options - Checkpoint proposal options
92
+ *
93
+ * @returns A checkpoint proposal signing the above information
94
+ */
95
+ public createCheckpointProposal(
96
+ checkpointHeader: CheckpointHeader,
97
+ archive: Fr,
98
+ feeAssetPriceModifier: bigint,
99
+ lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined,
100
+ proposerAttesterAddress: EthAddress | undefined,
101
+ options: CheckpointProposalOptions,
102
+ ): Promise<CheckpointProposal> {
103
+ // For testing: change the archive to trigger state_mismatch validation failure
104
+ if (options.broadcastInvalidCheckpointProposal) {
105
+ archive = Fr.random();
106
+ this.log.warn(`Creating INVALID checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
107
+ }
108
+
109
+ // Create a signer that takes payload and context, and uses the appropriate address
110
+ const payloadSigner = (payload: Buffer32, context: SigningContext) => {
111
+ const address = proposerAttesterAddress ?? this.keyStore.getAddress(0);
112
+ return this.keyStore.signMessageWithAddress(address, payload, context);
113
+ };
114
+
115
+ // Last block to include in the proposal
116
+ const lastBlock = lastBlockInfo && {
117
+ blockHeader: lastBlockInfo.blockHeader,
118
+ indexWithinCheckpoint: lastBlockInfo.indexWithinCheckpoint,
119
+ txHashes: lastBlockInfo.txs.map(tx => tx.getTxHash()),
120
+ txs: options.publishFullTxs ? lastBlockInfo.txs : undefined,
121
+ };
122
+
123
+ return CheckpointProposal.createProposalFromSigner(
124
+ checkpointHeader,
125
+ archive,
126
+ feeAssetPriceModifier,
127
+ lastBlock,
128
+ payloadSigner,
129
+ );
130
+ }
131
+
132
+ /**
133
+ * Attest with selection of validators to the given checkpoint proposal
70
134
  *
71
135
  * NOTE: This is just a blind signing.
72
136
  * We assume that the proposal is valid and DA guarantees have been checked previously.
73
137
  *
74
- * @param proposal - The proposal to attest to
138
+ * @param proposal - The checkpoint proposal (core version without lastBlock) to attest to
75
139
  * @param attestors - The validators to attest with
76
- * @returns attestations
140
+ * @returns checkpoint attestations
77
141
  */
78
- async attestToProposal(proposal: BlockProposal, attestors: EthAddress[]): Promise<BlockAttestation[]> {
142
+ async attestToCheckpointProposal(
143
+ proposal: CheckpointProposalCore,
144
+ attestors: EthAddress[],
145
+ ): Promise<CheckpointAttestation[]> {
146
+ // Create the attestation payload from the checkpoint proposal
147
+ const payload = new ConsensusPayload(proposal.checkpointHeader, proposal.archive, proposal.feeAssetPriceModifier);
79
148
  const buf = Buffer32.fromBuffer(
80
- keccak256(proposal.payload.getPayloadToSign(SignatureDomainSeparator.blockAttestation)),
149
+ keccak256(payload.getPayloadToSign(SignatureDomainSeparator.checkpointAttestation)),
81
150
  );
82
- const signatures = await Promise.all(
83
- attestors.map(attestor => this.keyStore.signMessageWithAddress(attestor, buf)),
151
+
152
+ // TODO(spy/ha): Use checkpointNumber instead of blockNumber once CheckpointHeader includes it.
153
+ // Currently using lastBlock.blockNumber as a proxy for checkpoint identification in HA signing.
154
+ // blockNumber is NOT used for the primary key so it's safe to use here.
155
+ // See CheckpointHeader TODO and SigningContext types documentation.
156
+ let blockNumber: BlockNumber;
157
+ try {
158
+ blockNumber = proposal.blockNumber;
159
+ } catch {
160
+ // Checkpoint proposal may not have lastBlock, use 0 as fallback
161
+ blockNumber = BlockNumber(0);
162
+ }
163
+ const context: SigningContext = {
164
+ slot: proposal.slotNumber,
165
+ blockNumber,
166
+ dutyType: DutyType.ATTESTATION,
167
+ };
168
+
169
+ // Sign each attestor in parallel, catching HA errors per-attestor
170
+ const results = await Promise.allSettled(
171
+ attestors.map(async attestor => {
172
+ const sig = await this.keyStore.signMessageWithAddress(attestor, buf, context);
173
+ // return new BlockAttestation(proposal.payload, sig, proposal.signature);
174
+ return new CheckpointAttestation(payload, sig, proposal.signature);
175
+ }),
84
176
  );
85
- return signatures.map(sig => new BlockAttestation(proposal.payload, sig, proposal.signature));
177
+
178
+ const attestations: CheckpointAttestation[] = [];
179
+ for (let i = 0; i < results.length; i++) {
180
+ const result = results[i];
181
+ if (result.status === 'fulfilled') {
182
+ attestations.push(result.value);
183
+ } else {
184
+ const error = result.reason;
185
+ if (error instanceof DutyAlreadySignedError || error instanceof SlashingProtectionError) {
186
+ this.log.info(
187
+ `Attestation for slot ${proposal.slotNumber} by ${attestors[i]} already signed by another High-Availability node`,
188
+ );
189
+ // Continue with remaining attestors
190
+ } else {
191
+ throw error;
192
+ }
193
+ }
194
+ }
195
+
196
+ return attestations;
86
197
  }
87
198
 
88
- async signAttestationsAndSigners(
199
+ /**
200
+ * Sign attestations and signers payload
201
+ * @param attestationsAndSigners - The attestations and signers to sign
202
+ * @param proposer - The proposer address to sign with
203
+ * @param slot - The slot number for HA signing context
204
+ * @param blockNumber - The block or checkpoint 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
+ blockNumber: BlockNumber | CheckpointNumber,
91
214
  ): Promise<Signature> {
215
+ const context: SigningContext = {
216
+ slot,
217
+ blockNumber,
218
+ dutyType: DutyType.ATTESTATIONS_AND_SIGNERS,
219
+ };
220
+
92
221
  const buf = Buffer32.fromBuffer(
93
222
  keccak256(attestationsAndSigners.getPayloadToSign(SignatureDomainSeparator.attestationsAndSigners)),
94
223
  );
95
- return await this.keyStore.signMessageWithAddress(proposer, buf);
224
+ return this.keyStore.signMessageWithAddress(proposer, buf, context);
96
225
  }
97
226
  }