@aztec/validator-client 0.0.1-commit.5476d83 → 0.0.1-commit.5914bae

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 +326 -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 +1 -1
  6. package/dest/config.d.ts.map +1 -1
  7. package/dest/config.js +36 -8
  8. package/dest/duties/validation_service.d.ts +42 -13
  9. package/dest/duties/validation_service.d.ts.map +1 -1
  10. package/dest/duties/validation_service.js +105 -28
  11. package/dest/factory.d.ts +19 -11
  12. package/dest/factory.d.ts.map +1 -1
  13. package/dest/factory.js +6 -5
  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 +10 -5
  32. package/dest/key_store/web3signer_key_store.d.ts.map +1 -1
  33. package/dest/key_store/web3signer_key_store.js +9 -5
  34. package/dest/metrics.d.ts +12 -3
  35. package/dest/metrics.d.ts.map +1 -1
  36. package/dest/metrics.js +46 -30
  37. package/dest/proposal_handler.d.ts +94 -0
  38. package/dest/proposal_handler.d.ts.map +1 -0
  39. package/dest/proposal_handler.js +852 -0
  40. package/dest/validator.d.ts +64 -22
  41. package/dest/validator.d.ts.map +1 -1
  42. package/dest/validator.js +278 -61
  43. package/package.json +23 -13
  44. package/src/checkpoint_builder.ts +417 -0
  45. package/src/config.ts +35 -7
  46. package/src/duties/validation_service.ts +156 -33
  47. package/src/factory.ts +26 -11
  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 +18 -5
  55. package/src/metrics.ts +63 -33
  56. package/src/proposal_handler.ts +903 -0
  57. package/src/validator.ts +433 -91
  58. package/dest/block_proposal_handler.d.ts +0 -52
  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 -341
@@ -0,0 +1,251 @@
1
+ import { NUM_CHECKPOINT_END_MARKER_FIELDS, getNumBlockEndBlobFields } from '@aztec/blob-lib/encoding';
2
+ import { BLOBS_PER_CHECKPOINT, FIELDS_PER_BLOB, MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT } from '@aztec/constants';
3
+ import { merge, pick, sum } from '@aztec/foundation/collection';
4
+ import { createLogger } from '@aztec/foundation/log';
5
+ import { bufferToHex } from '@aztec/foundation/string';
6
+ import { elapsed } from '@aztec/foundation/timer';
7
+ import { createTxValidatorForBlockBuilding, getDefaultAllowedSetupFunctions } from '@aztec/p2p/msg_validators';
8
+ import { LightweightCheckpointBuilder } from '@aztec/prover-client/light';
9
+ import { GuardedMerkleTreeOperations, PublicContractsDB, PublicProcessor, createPublicTxSimulatorForBlockBuilding } from '@aztec/simulator/server';
10
+ import { Gas } from '@aztec/stdlib/gas';
11
+ import { FullNodeBlockBuilderConfigKeys, InsufficientValidTxsError } from '@aztec/stdlib/interfaces/server';
12
+ import { NullDebugLogStore } from '@aztec/stdlib/logs';
13
+ import { MerkleTreeId } from '@aztec/stdlib/trees';
14
+ import { GlobalVariables } from '@aztec/stdlib/tx';
15
+ import { getTelemetryClient } from '@aztec/telemetry-client';
16
+ import { ForkCheckpoint } from '@aztec/world-state';
17
+ /**
18
+ * Builder for a single checkpoint. Handles building blocks within the checkpoint
19
+ * and completing it.
20
+ */ export class CheckpointBuilder {
21
+ checkpointBuilder;
22
+ fork;
23
+ config;
24
+ contractDataSource;
25
+ dateProvider;
26
+ telemetryClient;
27
+ debugLogStore;
28
+ log;
29
+ /** Persistent contracts DB shared across all blocks in this checkpoint. */ contractsDB;
30
+ constructor(checkpointBuilder, fork, config, contractDataSource, dateProvider, telemetryClient, bindings, debugLogStore = new NullDebugLogStore()){
31
+ this.checkpointBuilder = checkpointBuilder;
32
+ this.fork = fork;
33
+ this.config = config;
34
+ this.contractDataSource = contractDataSource;
35
+ this.dateProvider = dateProvider;
36
+ this.telemetryClient = telemetryClient;
37
+ this.debugLogStore = debugLogStore;
38
+ this.log = createLogger('checkpoint-builder', {
39
+ ...bindings,
40
+ instanceId: `checkpoint-${checkpointBuilder.checkpointNumber}`
41
+ });
42
+ this.contractsDB = new PublicContractsDB(this.contractDataSource, this.log.getBindings());
43
+ }
44
+ getConstantData() {
45
+ return this.checkpointBuilder.constants;
46
+ }
47
+ /**
48
+ * Builds a single block within this checkpoint.
49
+ * Automatically caps gas and blob field limits based on checkpoint-level budgets and prior blocks.
50
+ */ async buildBlock(pendingTxs, blockNumber, timestamp, opts) {
51
+ const slot = this.checkpointBuilder.constants.slotNumber;
52
+ this.log.verbose(`Building block ${blockNumber} for slot ${slot} within checkpoint`, {
53
+ slot,
54
+ blockNumber,
55
+ ...opts,
56
+ currentTime: new Date(this.dateProvider.now())
57
+ });
58
+ const constants = this.checkpointBuilder.constants;
59
+ const globalVariables = GlobalVariables.from({
60
+ chainId: constants.chainId,
61
+ version: constants.version,
62
+ blockNumber,
63
+ slotNumber: constants.slotNumber,
64
+ timestamp,
65
+ coinbase: constants.coinbase,
66
+ feeRecipient: constants.feeRecipient,
67
+ gasFees: constants.gasFees
68
+ });
69
+ const { processor, validator } = await this.makeBlockBuilderDeps(globalVariables, this.fork);
70
+ // Cap gas limits amd available blob fields by remaining checkpoint-level budgets
71
+ const cappedOpts = {
72
+ ...opts,
73
+ ...this.capLimitsByCheckpointBudgets(opts)
74
+ };
75
+ // Create a block-level checkpoint on the contracts DB so we can roll back on failure
76
+ this.contractsDB.createCheckpoint();
77
+ // We execute all merkle tree operations on a world state fork checkpoint
78
+ // This enables us to discard all modifications in the event that we fail to successfully process sufficient transactions
79
+ const forkCheckpoint = await ForkCheckpoint.new(this.fork);
80
+ try {
81
+ const [publicProcessorDuration, [processedTxs, failedTxs, usedTxs]] = await elapsed(()=>processor.process(pendingTxs, cappedOpts, validator));
82
+ // Throw before updating state if we don't have enough valid txs
83
+ const minValidTxs = opts.minValidTxs ?? 0;
84
+ if (processedTxs.length < minValidTxs) {
85
+ throw new InsufficientValidTxsError(processedTxs.length, minValidTxs, failedTxs);
86
+ }
87
+ // Commit the fork checkpoint
88
+ await forkCheckpoint.commit();
89
+ // Add block to checkpoint
90
+ const block = await this.checkpointBuilder.addBlock(globalVariables, processedTxs, {
91
+ expectedEndState: opts.expectedEndState
92
+ });
93
+ this.contractsDB.commitCheckpoint();
94
+ this.log.debug('Built block within checkpoint', {
95
+ header: block.header.toInspect(),
96
+ processedTxs: processedTxs.map((tx)=>tx.hash.toString()),
97
+ failedTxs: failedTxs.map((tx)=>tx.tx.txHash.toString())
98
+ });
99
+ return {
100
+ block,
101
+ publicProcessorDuration,
102
+ numTxs: processedTxs.length,
103
+ failedTxs,
104
+ usedTxs
105
+ };
106
+ } catch (err) {
107
+ // Revert all changes to contracts db
108
+ this.contractsDB.revertCheckpoint();
109
+ // If we reached the point of committing the checkpoint, this does nothing
110
+ // Otherwise it reverts any changes made to the fork for this failed block
111
+ await forkCheckpoint.revert();
112
+ throw err;
113
+ }
114
+ }
115
+ /** Completes the checkpoint and returns it. */ async completeCheckpoint() {
116
+ const checkpoint = await this.checkpointBuilder.completeCheckpoint();
117
+ this.log.verbose(`Completed checkpoint ${checkpoint.number}`, {
118
+ checkpointNumber: checkpoint.number,
119
+ numBlocks: checkpoint.blocks.length,
120
+ archiveRoot: checkpoint.archive.root.toString()
121
+ });
122
+ return checkpoint;
123
+ }
124
+ /** Gets the checkpoint currently in progress. */ getCheckpoint() {
125
+ return this.checkpointBuilder.clone().completeCheckpoint();
126
+ }
127
+ /**
128
+ * Caps per-block gas and blob field limits by remaining checkpoint-level budgets.
129
+ * When building a proposal (isBuildingProposal=true), computes a fair share of remaining budget
130
+ * across remaining blocks scaled by the multiplier. When validating, only caps by per-block limit
131
+ * and remaining checkpoint budget (no redistribution or multiplier).
132
+ */ capLimitsByCheckpointBudgets(opts) {
133
+ const existingBlocks = this.checkpointBuilder.getBlocks();
134
+ // Remaining L2 gas (mana)
135
+ // IMPORTANT: This assumes mana is computed solely based on L2 gas used in transactions.
136
+ // This may change in the future.
137
+ const usedMana = sum(existingBlocks.map((b)=>b.header.totalManaUsed.toNumber()));
138
+ const remainingMana = this.config.rollupManaLimit - usedMana;
139
+ // Remaining DA gas
140
+ const usedDAGas = sum(existingBlocks.map((b)=>b.computeDAGasUsed())) ?? 0;
141
+ const remainingDAGas = MAX_PROCESSABLE_DA_GAS_PER_CHECKPOINT - usedDAGas;
142
+ // Remaining blob fields (block blob fields include both tx data and block-end overhead)
143
+ const usedBlobFields = sum(existingBlocks.map((b)=>b.toBlobFields().length));
144
+ const totalBlobCapacity = BLOBS_PER_CHECKPOINT * FIELDS_PER_BLOB - NUM_CHECKPOINT_END_MARKER_FIELDS;
145
+ const isFirstBlock = existingBlocks.length === 0;
146
+ const blockEndOverhead = getNumBlockEndBlobFields(isFirstBlock);
147
+ const maxBlobFieldsForTxs = totalBlobCapacity - usedBlobFields - blockEndOverhead;
148
+ // Remaining txs
149
+ const usedTxs = sum(existingBlocks.map((b)=>b.body.txEffects.length));
150
+ const remainingTxs = Math.max(0, (this.config.maxTxsPerCheckpoint ?? Infinity) - usedTxs);
151
+ // Cap by per-block limit + remaining checkpoint budget
152
+ let cappedL2Gas = Math.min(opts.maxBlockGas?.l2Gas ?? Infinity, remainingMana);
153
+ let cappedDAGas = Math.min(opts.maxBlockGas?.daGas ?? Infinity, remainingDAGas);
154
+ let cappedBlobFields = Math.min(opts.maxBlobFields ?? Infinity, maxBlobFieldsForTxs);
155
+ let cappedMaxTransactions = Math.min(opts.maxTransactions ?? Infinity, remainingTxs);
156
+ // Proposer mode: further cap by fair share of remaining budget across remaining blocks
157
+ if (opts.isBuildingProposal) {
158
+ const remainingBlocks = Math.max(1, opts.maxBlocksPerCheckpoint - existingBlocks.length);
159
+ const multiplier = opts.perBlockAllocationMultiplier;
160
+ cappedL2Gas = Math.min(cappedL2Gas, Math.ceil(remainingMana / remainingBlocks * multiplier));
161
+ cappedDAGas = Math.min(cappedDAGas, Math.ceil(remainingDAGas / remainingBlocks * multiplier));
162
+ cappedBlobFields = Math.min(cappedBlobFields, Math.ceil(maxBlobFieldsForTxs / remainingBlocks * multiplier));
163
+ cappedMaxTransactions = Math.min(cappedMaxTransactions, Math.ceil(remainingTxs / remainingBlocks * multiplier));
164
+ }
165
+ return {
166
+ maxBlockGas: new Gas(cappedDAGas, cappedL2Gas),
167
+ maxBlobFields: cappedBlobFields,
168
+ maxTransactions: Number.isFinite(cappedMaxTransactions) ? cappedMaxTransactions : undefined
169
+ };
170
+ }
171
+ async makeBlockBuilderDeps(globalVariables, fork) {
172
+ const txPublicSetupAllowList = [
173
+ ...await getDefaultAllowedSetupFunctions(),
174
+ ...this.config.txPublicSetupAllowListExtend ?? []
175
+ ];
176
+ const contractsDB = this.contractsDB;
177
+ const guardedFork = new GuardedMerkleTreeOperations(fork);
178
+ const collectDebugLogs = this.debugLogStore.isEnabled;
179
+ const bindings = this.log.getBindings();
180
+ const publicTxSimulator = createPublicTxSimulatorForBlockBuilding(guardedFork, contractsDB, globalVariables, this.telemetryClient, bindings, collectDebugLogs);
181
+ const processor = new PublicProcessor(globalVariables, guardedFork, contractsDB, publicTxSimulator, this.dateProvider, this.telemetryClient, createLogger('simulator:public-processor', bindings), this.config, this.debugLogStore);
182
+ const validator = createTxValidatorForBlockBuilding(fork, this.contractDataSource, globalVariables, txPublicSetupAllowList, this.log.getBindings());
183
+ return {
184
+ processor,
185
+ validator
186
+ };
187
+ }
188
+ }
189
+ /** Factory for creating checkpoint builders. */ export class FullNodeCheckpointsBuilder {
190
+ config;
191
+ worldState;
192
+ contractDataSource;
193
+ dateProvider;
194
+ telemetryClient;
195
+ debugLogStore;
196
+ log;
197
+ constructor(config, worldState, contractDataSource, dateProvider, telemetryClient = getTelemetryClient(), debugLogStore = new NullDebugLogStore()){
198
+ this.config = config;
199
+ this.worldState = worldState;
200
+ this.contractDataSource = contractDataSource;
201
+ this.dateProvider = dateProvider;
202
+ this.telemetryClient = telemetryClient;
203
+ this.debugLogStore = debugLogStore;
204
+ this.log = createLogger('checkpoint-builder');
205
+ }
206
+ getConfig() {
207
+ return this.config;
208
+ }
209
+ updateConfig(config) {
210
+ this.config = merge(this.config, pick(config, ...FullNodeBlockBuilderConfigKeys));
211
+ }
212
+ /**
213
+ * Starts a new checkpoint and returns a CheckpointBuilder to build blocks within it.
214
+ */ async startCheckpoint(checkpointNumber, constants, feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, bindings) {
215
+ const stateReference = await fork.getStateReference();
216
+ const archiveTree = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
217
+ this.log.verbose(`Building new checkpoint ${checkpointNumber}`, {
218
+ checkpointNumber,
219
+ msgCount: l1ToL2Messages.length,
220
+ initialStateReference: stateReference.toInspect(),
221
+ initialArchiveRoot: bufferToHex(archiveTree.root),
222
+ constants,
223
+ feeAssetPriceModifier
224
+ });
225
+ const lightweightBuilder = await LightweightCheckpointBuilder.startNewCheckpoint(checkpointNumber, constants, l1ToL2Messages, previousCheckpointOutHashes, fork, bindings, feeAssetPriceModifier);
226
+ return new CheckpointBuilder(lightweightBuilder, fork, this.config, this.contractDataSource, this.dateProvider, this.telemetryClient, bindings, this.debugLogStore);
227
+ }
228
+ /**
229
+ * Opens a checkpoint, either starting fresh or resuming from existing blocks.
230
+ */ async openCheckpoint(checkpointNumber, constants, feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, existingBlocks = [], bindings) {
231
+ const stateReference = await fork.getStateReference();
232
+ const archiveTree = await fork.getTreeInfo(MerkleTreeId.ARCHIVE);
233
+ if (existingBlocks.length === 0) {
234
+ return this.startCheckpoint(checkpointNumber, constants, feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, bindings);
235
+ }
236
+ this.log.verbose(`Resuming checkpoint ${checkpointNumber} with ${existingBlocks.length} existing blocks`, {
237
+ checkpointNumber,
238
+ msgCount: l1ToL2Messages.length,
239
+ existingBlockCount: existingBlocks.length,
240
+ initialStateReference: stateReference.toInspect(),
241
+ initialArchiveRoot: bufferToHex(archiveTree.root),
242
+ constants,
243
+ feeAssetPriceModifier
244
+ });
245
+ const lightweightBuilder = await LightweightCheckpointBuilder.resumeCheckpoint(checkpointNumber, constants, feeAssetPriceModifier, l1ToL2Messages, previousCheckpointOutHashes, fork, existingBlocks, bindings);
246
+ return new CheckpointBuilder(lightweightBuilder, fork, this.config, this.contractDataSource, this.dateProvider, this.telemetryClient, bindings, this.debugLogStore);
247
+ }
248
+ /** Returns a fork of the world state at the given block number. */ getFork(blockNumber) {
249
+ return this.worldState.fork(blockNumber);
250
+ }
251
+ }
package/dest/config.d.ts CHANGED
@@ -8,4 +8,4 @@ export declare const validatorClientConfigMappings: ConfigMappingsType<Validator
8
8
  * @returns The validator configuration.
9
9
  */
10
10
  export declare function getProverEnvVars(): ValidatorClientConfig;
11
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFDTCxLQUFLLGtCQUFrQixFQUt4QixNQUFNLDBCQUEwQixDQUFDO0FBRWxDLE9BQU8sS0FBSyxFQUFFLHFCQUFxQixFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFFN0UsWUFBWSxFQUFFLHFCQUFxQixFQUFFLENBQUM7QUFFdEMsZUFBTyxNQUFNLDZCQUE2QixFQUFFLGtCQUFrQixDQUFDLHFCQUFxQixDQTREbkYsQ0FBQztBQUVGOzs7O0dBSUc7QUFDSCx3QkFBZ0IsZ0JBQWdCLElBQUkscUJBQXFCLENBRXhEIn0=
11
+ //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlnLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi9zcmMvY29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBLE9BQU8sRUFDTCxLQUFLLGtCQUFrQixFQUt4QixNQUFNLDBCQUEwQixDQUFDO0FBRWxDLE9BQU8sS0FBSyxFQUFFLHFCQUFxQixFQUFFLE1BQU0saUNBQWlDLENBQUM7QUFHN0UsWUFBWSxFQUFFLHFCQUFxQixFQUFFLENBQUM7QUFFdEMsZUFBTyxNQUFNLDZCQUE2QixFQUFFLGtCQUFrQixDQUFDLHFCQUFxQixDQXVGbkYsQ0FBQztBQUVGOzs7O0dBSUc7QUFDSCx3QkFBZ0IsZ0JBQWdCLElBQUkscUJBQXFCLENBRXhEIn0=
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EAKxB,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAE7E,YAAY,EAAE,qBAAqB,EAAE,CAAC;AAEtC,eAAO,MAAM,6BAA6B,EAAE,kBAAkB,CAAC,qBAAqB,CA4DnF,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,qBAAqB,CAExD"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../src/config.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EAKxB,MAAM,0BAA0B,CAAC;AAElC,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,iCAAiC,CAAC;AAG7E,YAAY,EAAE,qBAAqB,EAAE,CAAC;AAEtC,eAAO,MAAM,6BAA6B,EAAE,kBAAkB,CAAC,qBAAqB,CAuFnF,CAAC;AAEF;;;;GAIG;AACH,wBAAgB,gBAAgB,IAAI,qBAAqB,CAExD"}
package/dest/config.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { booleanConfigHelper, getConfigFromMappings, numberConfigHelper, secretValueConfigHelper } from '@aztec/foundation/config';
2
2
  import { EthAddress } from '@aztec/foundation/eth-address';
3
+ import { validatorHASignerConfigMappings } from '@aztec/validator-ha-signer/config';
3
4
  export const validatorClientConfigMappings = {
4
5
  validatorPrivateKeys: {
5
6
  env: 'VALIDATOR_PRIVATE_KEYS',
@@ -35,21 +36,48 @@ export const validatorClientConfigMappings = {
35
36
  description: 'Re-execute transactions before attesting',
36
37
  ...booleanConfigHelper(true)
37
38
  },
38
- validatorReexecuteDeadlineMs: {
39
- env: 'VALIDATOR_REEXECUTE_DEADLINE_MS',
40
- description: 'Will re-execute until this many milliseconds are left in the slot',
41
- ...numberConfigHelper(6000)
42
- },
43
39
  alwaysReexecuteBlockProposals: {
44
- env: 'ALWAYS_REEXECUTE_BLOCK_PROPOSALS',
45
40
  description: 'Whether to always reexecute block proposals, even for non-validator nodes (useful for monitoring network status).',
46
- ...booleanConfigHelper(false)
41
+ defaultValue: true
47
42
  },
48
43
  fishermanMode: {
49
44
  env: 'FISHERMAN_MODE',
50
45
  description: 'Whether to run in fisherman mode: validates all proposals and attestations but does not broadcast attestations or participate in consensus.',
51
46
  ...booleanConfigHelper(false)
52
- }
47
+ },
48
+ skipCheckpointProposalValidation: {
49
+ description: 'Skip checkpoint proposal validation and always attest (default: false)',
50
+ defaultValue: false
51
+ },
52
+ skipPushProposedBlocksToArchiver: {
53
+ description: 'Skip pushing re-executed blocks to archiver (default: false)',
54
+ defaultValue: false
55
+ },
56
+ attestToEquivocatedProposals: {
57
+ description: 'Agree to attest to equivocated checkpoint proposals (for testing purposes only)',
58
+ ...booleanConfigHelper(false)
59
+ },
60
+ validateMaxL2BlockGas: {
61
+ env: 'VALIDATOR_MAX_L2_BLOCK_GAS',
62
+ description: 'Maximum L2 block gas for validation. Proposals exceeding this limit are rejected.',
63
+ parseEnv: (val)=>val ? parseInt(val, 10) : undefined
64
+ },
65
+ validateMaxDABlockGas: {
66
+ env: 'VALIDATOR_MAX_DA_BLOCK_GAS',
67
+ description: 'Maximum DA block gas for validation. Proposals exceeding this limit are rejected.',
68
+ parseEnv: (val)=>val ? parseInt(val, 10) : undefined
69
+ },
70
+ validateMaxTxsPerBlock: {
71
+ env: 'VALIDATOR_MAX_TX_PER_BLOCK',
72
+ description: 'Maximum transactions per block for validation. Proposals exceeding this limit are rejected.',
73
+ parseEnv: (val)=>val ? parseInt(val, 10) : undefined
74
+ },
75
+ validateMaxTxsPerCheckpoint: {
76
+ env: 'VALIDATOR_MAX_TX_PER_CHECKPOINT',
77
+ description: 'Maximum transactions per checkpoint for validation. Proposals exceeding this limit are rejected.',
78
+ parseEnv: (val)=>val ? parseInt(val, 10) : undefined
79
+ },
80
+ ...validatorHASignerConfigMappings
53
81
  };
54
82
  /**
55
83
  * Returns the prover configuration from the environment variables.
@@ -1,10 +1,12 @@
1
+ import { BlockNumber, type CheckpointNumber, IndexWithinCheckpoint, type SlotNumber } from '@aztec/foundation/branded-types';
2
+ import { Fr } from '@aztec/foundation/curves/bn254';
1
3
  import type { EthAddress } from '@aztec/foundation/eth-address';
2
4
  import type { Signature } from '@aztec/foundation/eth-signature';
3
- import { Fr } from '@aztec/foundation/fields';
4
5
  import type { CommitteeAttestationsAndSigners } from '@aztec/stdlib/block';
5
- import { BlockAttestation, BlockProposal, type BlockProposalOptions } from '@aztec/stdlib/p2p';
6
+ import type { CreateCheckpointProposalLastBlockData } from '@aztec/stdlib/interfaces/server';
7
+ import { BlockProposal, type BlockProposalOptions, CheckpointAttestation, CheckpointProposal, type CheckpointProposalCore, type CheckpointProposalOptions } from '@aztec/stdlib/p2p';
6
8
  import type { CheckpointHeader } from '@aztec/stdlib/rollup';
7
- import type { Tx } from '@aztec/stdlib/tx';
9
+ import type { BlockHeader, Tx } from '@aztec/stdlib/tx';
8
10
  import type { ValidatorKeyStore } from '../key_store/interface.js';
9
11
  export declare class ValidationService {
10
12
  private keyStore;
@@ -13,25 +15,52 @@ export declare class ValidationService {
13
15
  /**
14
16
  * Create a block proposal with the given header, archive, and transactions
15
17
  *
16
- * @param header - The block header
18
+ * @param blockHeader - The block header
19
+ * @param blockIndexWithinCheckpoint - The block index within checkpoint for HA signing context
20
+ * @param inHash - Hash of L1 to L2 messages for this checkpoint
17
21
  * @param archive - The archive of the current block
18
- * @param txs - TxHash[] ordered list of transactions
22
+ * @param txs - Ordered list of transactions (Tx[])
23
+ * @param proposerAttesterAddress - The address of the proposer/attester, or undefined
19
24
  * @param options - Block proposal options (including broadcastInvalidBlockProposal for testing)
20
25
  *
21
- * @returns A block proposal signing the above information (not the current implementation!!!)
26
+ * @returns A block proposal signing the above information
27
+ * @throws DutyAlreadySignedError if HA signer indicates duty already signed by another node
28
+ * @throws SlashingProtectionError if attempting to sign different data for same slot
22
29
  */
23
- createBlockProposal(header: CheckpointHeader, archive: Fr, txs: Tx[], proposerAttesterAddress: EthAddress | undefined, options: BlockProposalOptions): Promise<BlockProposal>;
30
+ createBlockProposal(blockHeader: BlockHeader, blockIndexWithinCheckpoint: IndexWithinCheckpoint, inHash: Fr, archive: Fr, txs: Tx[], proposerAttesterAddress: EthAddress | undefined, options: BlockProposalOptions): Promise<BlockProposal>;
24
31
  /**
25
- * Attest with selection of validators to the given block proposal, constructed by the current sequencer
32
+ * Create a checkpoint proposal with the last block header and checkpoint header
33
+ *
34
+ * @param checkpointHeader - The checkpoint header containing aggregated data
35
+ * @param archive - The archive of the checkpoint
36
+ * @param lastBlockInfo - Info about the last block (header, index, txs) or undefined
37
+ * @param proposerAttesterAddress - The address of the proposer
38
+ * @param options - Checkpoint proposal options
39
+ *
40
+ * @returns A checkpoint proposal signing the above information
41
+ */
42
+ createCheckpointProposal(checkpointHeader: CheckpointHeader, archive: Fr, feeAssetPriceModifier: bigint, lastBlockInfo: CreateCheckpointProposalLastBlockData | undefined, proposerAttesterAddress: EthAddress | undefined, options: CheckpointProposalOptions): Promise<CheckpointProposal>;
43
+ /**
44
+ * Attest with selection of validators to the given checkpoint proposal
26
45
  *
27
46
  * NOTE: This is just a blind signing.
28
47
  * We assume that the proposal is valid and DA guarantees have been checked previously.
29
48
  *
30
- * @param proposal - The proposal to attest to
49
+ * @param proposal - The checkpoint proposal (core version without lastBlock) to attest to
31
50
  * @param attestors - The validators to attest with
32
- * @returns attestations
51
+ * @returns checkpoint attestations
52
+ */
53
+ attestToCheckpointProposal(proposal: CheckpointProposalCore, attestors: EthAddress[]): Promise<CheckpointAttestation[]>;
54
+ /**
55
+ * Sign attestations and signers payload
56
+ * @param attestationsAndSigners - The attestations and signers to sign
57
+ * @param proposer - The proposer address to sign with
58
+ * @param slot - The slot number for HA signing context
59
+ * @param blockNumber - The block or checkpoint number for HA signing context
60
+ * @returns signature
61
+ * @throws DutyAlreadySignedError if already signed by another HA node
62
+ * @throws SlashingProtectionError if attempting to sign different data for same slot
33
63
  */
34
- attestToProposal(proposal: BlockProposal, attestors: EthAddress[]): Promise<BlockAttestation[]>;
35
- signAttestationsAndSigners(attestationsAndSigners: CommitteeAttestationsAndSigners, proposer: EthAddress): Promise<Signature>;
64
+ signAttestationsAndSigners(attestationsAndSigners: CommitteeAttestationsAndSigners, proposer: EthAddress, slot: SlotNumber, blockNumber: BlockNumber | CheckpointNumber): Promise<Signature>;
36
65
  }
37
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmFsaWRhdGlvbl9zZXJ2aWNlLmQudHMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi9zcmMvZHV0aWVzL3ZhbGlkYXRpb25fc2VydmljZS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUFFQSxPQUFPLEtBQUssRUFBRSxVQUFVLEVBQUUsTUFBTSwrQkFBK0IsQ0FBQztBQUNoRSxPQUFPLEtBQUssRUFBRSxTQUFTLEVBQUUsTUFBTSxpQ0FBaUMsQ0FBQztBQUNqRSxPQUFPLEVBQUUsRUFBRSxFQUFFLE1BQU0sMEJBQTBCLENBQUM7QUFFOUMsT0FBTyxLQUFLLEVBQUUsK0JBQStCLEVBQUUsTUFBTSxxQkFBcUIsQ0FBQztBQUMzRSxPQUFPLEVBQ0wsZ0JBQWdCLEVBQ2hCLGFBQWEsRUFDYixLQUFLLG9CQUFvQixFQUcxQixNQUFNLG1CQUFtQixDQUFDO0FBQzNCLE9BQU8sS0FBSyxFQUFFLGdCQUFnQixFQUFFLE1BQU0sc0JBQXNCLENBQUM7QUFDN0QsT0FBTyxLQUFLLEVBQUUsRUFBRSxFQUFFLE1BQU0sa0JBQWtCLENBQUM7QUFFM0MsT0FBTyxLQUFLLEVBQUUsaUJBQWlCLEVBQUUsTUFBTSwyQkFBMkIsQ0FBQztBQUVuRSxxQkFBYSxpQkFBaUI7SUFFMUIsT0FBTyxDQUFDLFFBQVE7SUFDaEIsT0FBTyxDQUFDLEdBQUc7SUFGYixZQUNVLFFBQVEsRUFBRSxpQkFBaUIsRUFDM0IsR0FBRyx5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,GAAG,gBAAgB,GAC1C,OAAO,CAAC,SAAS,CAAC,CAWpB;CACF"}
@@ -1,8 +1,11 @@
1
+ import { BlockNumber } from '@aztec/foundation/branded-types';
1
2
  import { Buffer32 } from '@aztec/foundation/buffer';
2
- import { keccak256 } from '@aztec/foundation/crypto';
3
- import { Fr } from '@aztec/foundation/fields';
3
+ import { keccak256 } from '@aztec/foundation/crypto/keccak';
4
+ import { Fr } from '@aztec/foundation/curves/bn254';
4
5
  import { createLogger } from '@aztec/foundation/log';
5
- import { BlockAttestation, BlockProposal, ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
6
+ import { BlockProposal, CheckpointAttestation, CheckpointProposal, ConsensusPayload, SignatureDomainSeparator } from '@aztec/stdlib/p2p';
7
+ import { DutyAlreadySignedError, SlashingProtectionError } from '@aztec/validator-ha-signer/errors';
8
+ import { DutyType } from '@aztec/validator-ha-signer/types';
6
9
  export class ValidationService {
7
10
  keyStore;
8
11
  log;
@@ -13,46 +16,120 @@ export class ValidationService {
13
16
  /**
14
17
  * Create a block proposal with the given header, archive, and transactions
15
18
  *
16
- * @param header - The block header
19
+ * @param blockHeader - The block header
20
+ * @param blockIndexWithinCheckpoint - The block index within checkpoint for HA signing context
21
+ * @param inHash - Hash of L1 to L2 messages for this checkpoint
17
22
  * @param archive - The archive of the current block
18
- * @param txs - TxHash[] ordered list of transactions
23
+ * @param txs - Ordered list of transactions (Tx[])
24
+ * @param proposerAttesterAddress - The address of the proposer/attester, or undefined
19
25
  * @param options - Block proposal options (including broadcastInvalidBlockProposal for testing)
20
26
  *
21
- * @returns A block proposal signing the above information (not the current implementation!!!)
22
- */ async createBlockProposal(header, archive, txs, proposerAttesterAddress, options) {
23
- let payloadSigner;
24
- if (proposerAttesterAddress !== undefined) {
25
- payloadSigner = (payload)=>this.keyStore.signMessageWithAddress(proposerAttesterAddress, payload);
26
- } else {
27
- // if there is no proposer attester address, just use the first signer
28
- const signer = this.keyStore.getAddress(0);
29
- payloadSigner = (payload)=>this.keyStore.signMessageWithAddress(signer, payload);
30
- }
31
- // TODO: check if this is calculated earlier / can not be recomputed
32
- const txHashes = await Promise.all(txs.map((tx)=>tx.getTxHash()));
27
+ * @returns A block proposal signing the above information
28
+ * @throws DutyAlreadySignedError if HA signer indicates duty already signed by another node
29
+ * @throws SlashingProtectionError if attempting to sign different data for same slot
30
+ */ createBlockProposal(blockHeader, blockIndexWithinCheckpoint, inHash, archive, txs, proposerAttesterAddress, options) {
33
31
  // For testing: change the new archive to trigger state_mismatch validation failure
34
32
  if (options.broadcastInvalidBlockProposal) {
35
33
  archive = Fr.random();
36
- this.log.warn(`Creating INVALID block proposal for slot ${header.slotNumber}`);
34
+ this.log.warn(`Creating INVALID block proposal for slot ${blockHeader.globalVariables.slotNumber}`);
37
35
  }
38
- return BlockProposal.createProposalFromSigner(new ConsensusPayload(header, archive), txHashes, options.publishFullTxs ? txs : undefined, payloadSigner);
36
+ // Create a signer that uses the appropriate address
37
+ const address = proposerAttesterAddress ?? this.keyStore.getAddress(0);
38
+ const payloadSigner = (payload, context)=>this.keyStore.signMessageWithAddress(address, payload, context);
39
+ return BlockProposal.createProposalFromSigner(blockHeader, blockIndexWithinCheckpoint, inHash, archive, txs.map((tx)=>tx.getTxHash()), options.publishFullTxs ? txs : undefined, payloadSigner);
39
40
  }
40
41
  /**
41
- * Attest with selection of validators to the given block proposal, constructed by the current sequencer
42
+ * Create a checkpoint proposal with the last block header and checkpoint header
43
+ *
44
+ * @param checkpointHeader - The checkpoint header containing aggregated data
45
+ * @param archive - The archive of the checkpoint
46
+ * @param lastBlockInfo - Info about the last block (header, index, txs) or undefined
47
+ * @param proposerAttesterAddress - The address of the proposer
48
+ * @param options - Checkpoint proposal options
49
+ *
50
+ * @returns A checkpoint proposal signing the above information
51
+ */ createCheckpointProposal(checkpointHeader, archive, feeAssetPriceModifier, lastBlockInfo, proposerAttesterAddress, options) {
52
+ // For testing: change the archive to trigger state_mismatch validation failure
53
+ if (options.broadcastInvalidCheckpointProposal) {
54
+ archive = Fr.random();
55
+ this.log.warn(`Creating INVALID checkpoint proposal for slot ${checkpointHeader.slotNumber}`);
56
+ }
57
+ // Create a signer that takes payload and context, and uses the appropriate address
58
+ const payloadSigner = (payload, context)=>{
59
+ const address = proposerAttesterAddress ?? this.keyStore.getAddress(0);
60
+ return this.keyStore.signMessageWithAddress(address, payload, context);
61
+ };
62
+ // Last block to include in the proposal
63
+ const lastBlock = lastBlockInfo && {
64
+ blockHeader: lastBlockInfo.blockHeader,
65
+ indexWithinCheckpoint: lastBlockInfo.indexWithinCheckpoint,
66
+ txHashes: lastBlockInfo.txs.map((tx)=>tx.getTxHash()),
67
+ txs: options.publishFullTxs ? lastBlockInfo.txs : undefined
68
+ };
69
+ return CheckpointProposal.createProposalFromSigner(checkpointHeader, archive, feeAssetPriceModifier, lastBlock, payloadSigner);
70
+ }
71
+ /**
72
+ * Attest with selection of validators to the given checkpoint proposal
42
73
  *
43
74
  * NOTE: This is just a blind signing.
44
75
  * We assume that the proposal is valid and DA guarantees have been checked previously.
45
76
  *
46
- * @param proposal - The proposal to attest to
77
+ * @param proposal - The checkpoint proposal (core version without lastBlock) to attest to
47
78
  * @param attestors - The validators to attest with
48
- * @returns attestations
49
- */ async attestToProposal(proposal, attestors) {
50
- const buf = Buffer32.fromBuffer(keccak256(proposal.payload.getPayloadToSign(SignatureDomainSeparator.blockAttestation)));
51
- const signatures = await Promise.all(attestors.map((attestor)=>this.keyStore.signMessageWithAddress(attestor, buf)));
52
- return signatures.map((sig)=>new BlockAttestation(proposal.payload, sig, proposal.signature));
79
+ * @returns checkpoint attestations
80
+ */ async attestToCheckpointProposal(proposal, attestors) {
81
+ // Create the attestation payload from the checkpoint proposal
82
+ const payload = new ConsensusPayload(proposal.checkpointHeader, proposal.archive, proposal.feeAssetPriceModifier);
83
+ const buf = Buffer32.fromBuffer(keccak256(payload.getPayloadToSign(SignatureDomainSeparator.checkpointAttestation)));
84
+ // TODO(spy/ha): Use checkpointNumber instead of blockNumber once CheckpointHeader includes it.
85
+ // CheckpointProposalCore doesn't have lastBlock info, so use 0 as a proxy.
86
+ // blockNumber is NOT used for the primary key so it's safe to use here.
87
+ // See CheckpointHeader TODO and SigningContext types documentation.
88
+ const blockNumber = BlockNumber(0);
89
+ const context = {
90
+ slot: proposal.slotNumber,
91
+ blockNumber,
92
+ dutyType: DutyType.ATTESTATION
93
+ };
94
+ // Sign each attestor in parallel, catching HA errors per-attestor
95
+ const results = await Promise.allSettled(attestors.map(async (attestor)=>{
96
+ const sig = await this.keyStore.signMessageWithAddress(attestor, buf, context);
97
+ // return new BlockAttestation(proposal.payload, sig, proposal.signature);
98
+ return new CheckpointAttestation(payload, sig, proposal.signature);
99
+ }));
100
+ const attestations = [];
101
+ for(let i = 0; i < results.length; i++){
102
+ const result = results[i];
103
+ if (result.status === 'fulfilled') {
104
+ attestations.push(result.value);
105
+ } else {
106
+ const error = result.reason;
107
+ if (error instanceof DutyAlreadySignedError || error instanceof SlashingProtectionError) {
108
+ this.log.verbose(`Attestation for slot ${proposal.slotNumber} by ${attestors[i]} already signed by another High-Availability node`);
109
+ // Continue with remaining attestors
110
+ } else {
111
+ throw error;
112
+ }
113
+ }
114
+ }
115
+ return attestations;
53
116
  }
54
- async signAttestationsAndSigners(attestationsAndSigners, proposer) {
117
+ /**
118
+ * Sign attestations and signers payload
119
+ * @param attestationsAndSigners - The attestations and signers to sign
120
+ * @param proposer - The proposer address to sign with
121
+ * @param slot - The slot number for HA signing context
122
+ * @param blockNumber - The block or checkpoint number for HA signing context
123
+ * @returns signature
124
+ * @throws DutyAlreadySignedError if already signed by another HA node
125
+ * @throws SlashingProtectionError if attempting to sign different data for same slot
126
+ */ signAttestationsAndSigners(attestationsAndSigners, proposer, slot, blockNumber) {
127
+ const context = {
128
+ slot,
129
+ blockNumber,
130
+ dutyType: DutyType.ATTESTATIONS_AND_SIGNERS
131
+ };
55
132
  const buf = Buffer32.fromBuffer(keccak256(attestationsAndSigners.getPayloadToSign(SignatureDomainSeparator.attestationsAndSigners)));
56
- return await this.keyStore.signMessageWithAddress(proposer, buf);
133
+ return this.keyStore.signMessageWithAddress(proposer, buf, context);
57
134
  }
58
135
  }