@aztec/p2p 4.0.0-devnet.2-patch.4 → 4.0.0-devnet.3-patch.0

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 (212) hide show
  1. package/README.md +129 -3
  2. package/dest/client/factory.d.ts +4 -5
  3. package/dest/client/factory.d.ts.map +1 -1
  4. package/dest/client/factory.js +30 -28
  5. package/dest/client/interface.d.ts +8 -13
  6. package/dest/client/interface.d.ts.map +1 -1
  7. package/dest/client/p2p_client.d.ts +6 -13
  8. package/dest/client/p2p_client.d.ts.map +1 -1
  9. package/dest/client/p2p_client.js +22 -88
  10. package/dest/client/test/tx_proposal_collector/proposal_tx_collector_worker.js +2 -4
  11. package/dest/config.d.ts +29 -10
  12. package/dest/config.d.ts.map +1 -1
  13. package/dest/config.js +80 -31
  14. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts +1 -1
  15. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -1
  16. package/dest/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.js +2 -1
  17. package/dest/mem_pools/tx_pool/priority.d.ts +2 -2
  18. package/dest/mem_pools/tx_pool/priority.d.ts.map +1 -1
  19. package/dest/mem_pools/tx_pool/priority.js +4 -4
  20. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts +1 -1
  21. package/dest/mem_pools/tx_pool/tx_pool_test_suite.d.ts.map +1 -1
  22. package/dest/mem_pools/tx_pool/tx_pool_test_suite.js +3 -1
  23. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts +1 -1
  24. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.d.ts.map +1 -1
  25. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.js +3 -2
  26. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts +1 -1
  27. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.d.ts.map +1 -1
  28. package/dest/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.js +2 -0
  29. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts +7 -1
  30. package/dest/mem_pools/tx_pool_v2/eviction/interfaces.d.ts.map +1 -1
  31. package/dest/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.js +2 -2
  32. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts +2 -2
  33. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.d.ts.map +1 -1
  34. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.js +10 -6
  35. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts +1 -1
  36. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.d.ts.map +1 -1
  37. package/dest/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.js +8 -6
  38. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts +2 -2
  39. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.d.ts.map +1 -1
  40. package/dest/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.js +2 -2
  41. package/dest/mem_pools/tx_pool_v2/index.d.ts +2 -2
  42. package/dest/mem_pools/tx_pool_v2/index.d.ts.map +1 -1
  43. package/dest/mem_pools/tx_pool_v2/index.js +1 -1
  44. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts +9 -5
  45. package/dest/mem_pools/tx_pool_v2/interfaces.d.ts.map +1 -1
  46. package/dest/mem_pools/tx_pool_v2/interfaces.js +2 -1
  47. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts +46 -8
  48. package/dest/mem_pools/tx_pool_v2/tx_metadata.d.ts.map +1 -1
  49. package/dest/mem_pools/tx_pool_v2/tx_metadata.js +81 -17
  50. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts +1 -1
  51. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.d.ts.map +1 -1
  52. package/dest/mem_pools/tx_pool_v2/tx_pool_indices.js +9 -10
  53. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts +5 -3
  54. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.d.ts.map +1 -1
  55. package/dest/mem_pools/tx_pool_v2/tx_pool_v2.js +3 -0
  56. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts +2 -2
  57. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.d.ts.map +1 -1
  58. package/dest/mem_pools/tx_pool_v2/tx_pool_v2_impl.js +179 -151
  59. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts +6 -4
  60. package/dest/msg_validators/proposal_validator/block_proposal_validator.d.ts.map +1 -1
  61. package/dest/msg_validators/proposal_validator/block_proposal_validator.js +10 -2
  62. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts +6 -4
  63. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.d.ts.map +1 -1
  64. package/dest/msg_validators/proposal_validator/checkpoint_proposal_validator.js +16 -2
  65. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts +13 -8
  66. package/dest/msg_validators/proposal_validator/proposal_validator.d.ts.map +1 -1
  67. package/dest/msg_validators/proposal_validator/proposal_validator.js +48 -36
  68. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts +2 -2
  69. package/dest/msg_validators/tx_validator/aggregate_tx_validator.d.ts.map +1 -1
  70. package/dest/msg_validators/tx_validator/aggregate_tx_validator.js +3 -3
  71. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts +2 -1
  72. package/dest/msg_validators/tx_validator/allowed_public_setup.d.ts.map +1 -1
  73. package/dest/msg_validators/tx_validator/allowed_public_setup.js +24 -20
  74. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts +17 -0
  75. package/dest/msg_validators/tx_validator/allowed_setup_helpers.d.ts.map +1 -0
  76. package/dest/msg_validators/tx_validator/allowed_setup_helpers.js +24 -0
  77. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts +9 -0
  78. package/dest/msg_validators/tx_validator/contract_instance_validator.d.ts.map +1 -0
  79. package/dest/msg_validators/tx_validator/contract_instance_validator.js +48 -0
  80. package/dest/msg_validators/tx_validator/data_validator.d.ts +1 -1
  81. package/dest/msg_validators/tx_validator/data_validator.d.ts.map +1 -1
  82. package/dest/msg_validators/tx_validator/data_validator.js +35 -2
  83. package/dest/msg_validators/tx_validator/factory.d.ts +133 -6
  84. package/dest/msg_validators/tx_validator/factory.d.ts.map +1 -1
  85. package/dest/msg_validators/tx_validator/factory.js +247 -60
  86. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts +1 -1
  87. package/dest/msg_validators/tx_validator/fee_payer_balance.d.ts.map +1 -1
  88. package/dest/msg_validators/tx_validator/fee_payer_balance.js +6 -2
  89. package/dest/msg_validators/tx_validator/gas_validator.d.ts +67 -3
  90. package/dest/msg_validators/tx_validator/gas_validator.d.ts.map +1 -1
  91. package/dest/msg_validators/tx_validator/gas_validator.js +104 -37
  92. package/dest/msg_validators/tx_validator/index.d.ts +3 -1
  93. package/dest/msg_validators/tx_validator/index.d.ts.map +1 -1
  94. package/dest/msg_validators/tx_validator/index.js +2 -0
  95. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts +14 -0
  96. package/dest/msg_validators/tx_validator/nullifier_cache.d.ts.map +1 -0
  97. package/dest/msg_validators/tx_validator/nullifier_cache.js +24 -0
  98. package/dest/msg_validators/tx_validator/phases_validator.d.ts +22 -2
  99. package/dest/msg_validators/tx_validator/phases_validator.d.ts.map +1 -1
  100. package/dest/msg_validators/tx_validator/phases_validator.js +72 -24
  101. package/dest/services/dummy_service.d.ts +4 -4
  102. package/dest/services/dummy_service.d.ts.map +1 -1
  103. package/dest/services/dummy_service.js +4 -4
  104. package/dest/services/encoding.d.ts +6 -2
  105. package/dest/services/encoding.d.ts.map +1 -1
  106. package/dest/services/encoding.js +14 -8
  107. package/dest/services/gossipsub/topic_score_params.d.ts +18 -6
  108. package/dest/services/gossipsub/topic_score_params.d.ts.map +1 -1
  109. package/dest/services/gossipsub/topic_score_params.js +32 -10
  110. package/dest/services/libp2p/libp2p_service.d.ts +16 -13
  111. package/dest/services/libp2p/libp2p_service.d.ts.map +1 -1
  112. package/dest/services/libp2p/libp2p_service.js +97 -93
  113. package/dest/services/reqresp/batch-tx-requester/tx_validator.js +2 -2
  114. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts +5 -4
  115. package/dest/services/reqresp/rate-limiter/rate_limiter.d.ts.map +1 -1
  116. package/dest/services/reqresp/rate-limiter/rate_limiter.js +10 -8
  117. package/dest/services/reqresp/reqresp.d.ts +1 -1
  118. package/dest/services/reqresp/reqresp.d.ts.map +1 -1
  119. package/dest/services/reqresp/reqresp.js +16 -8
  120. package/dest/services/service.d.ts +5 -3
  121. package/dest/services/service.d.ts.map +1 -1
  122. package/dest/services/tx_collection/file_store_tx_source.d.ts +5 -4
  123. package/dest/services/tx_collection/file_store_tx_source.d.ts.map +1 -1
  124. package/dest/services/tx_collection/file_store_tx_source.js +39 -29
  125. package/dest/services/tx_collection/tx_source.d.ts +6 -5
  126. package/dest/services/tx_collection/tx_source.d.ts.map +1 -1
  127. package/dest/services/tx_collection/tx_source.js +9 -7
  128. package/dest/services/tx_provider.d.ts +3 -3
  129. package/dest/services/tx_provider.d.ts.map +1 -1
  130. package/dest/services/tx_provider.js +4 -4
  131. package/dest/test-helpers/make-test-p2p-clients.d.ts +5 -6
  132. package/dest/test-helpers/make-test-p2p-clients.d.ts.map +1 -1
  133. package/dest/test-helpers/make-test-p2p-clients.js +1 -2
  134. package/dest/test-helpers/mock-pubsub.d.ts +4 -4
  135. package/dest/test-helpers/mock-pubsub.d.ts.map +1 -1
  136. package/dest/test-helpers/mock-pubsub.js +8 -2
  137. package/dest/test-helpers/reqresp-nodes.d.ts +2 -3
  138. package/dest/test-helpers/reqresp-nodes.d.ts.map +1 -1
  139. package/dest/test-helpers/reqresp-nodes.js +2 -2
  140. package/dest/test-helpers/testbench-utils.d.ts +2 -2
  141. package/dest/test-helpers/testbench-utils.d.ts.map +1 -1
  142. package/dest/test-helpers/testbench-utils.js +2 -1
  143. package/dest/testbench/p2p_client_testbench_worker.js +7 -6
  144. package/dest/testbench/worker_client_manager.d.ts +3 -1
  145. package/dest/testbench/worker_client_manager.d.ts.map +1 -1
  146. package/dest/testbench/worker_client_manager.js +4 -1
  147. package/dest/util.d.ts +2 -2
  148. package/dest/util.d.ts.map +1 -1
  149. package/package.json +14 -14
  150. package/src/client/factory.ts +49 -45
  151. package/src/client/interface.ts +8 -13
  152. package/src/client/p2p_client.ts +24 -117
  153. package/src/client/test/tx_proposal_collector/proposal_tx_collector_worker.ts +2 -3
  154. package/src/config.ts +115 -33
  155. package/src/mem_pools/tx_pool/eviction/fee_payer_balance_eviction_rule.ts +2 -1
  156. package/src/mem_pools/tx_pool/priority.ts +4 -4
  157. package/src/mem_pools/tx_pool/tx_pool_test_suite.ts +3 -1
  158. package/src/mem_pools/tx_pool_v2/README.md +9 -1
  159. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_eviction_rule.ts +3 -2
  160. package/src/mem_pools/tx_pool_v2/eviction/fee_payer_balance_pre_add_rule.ts +3 -0
  161. package/src/mem_pools/tx_pool_v2/eviction/interfaces.ts +11 -1
  162. package/src/mem_pools/tx_pool_v2/eviction/invalid_txs_after_reorg_rule.ts +2 -2
  163. package/src/mem_pools/tx_pool_v2/eviction/low_priority_eviction_rule.ts +10 -6
  164. package/src/mem_pools/tx_pool_v2/eviction/low_priority_pre_add_rule.ts +15 -6
  165. package/src/mem_pools/tx_pool_v2/eviction/nullifier_conflict_rule.ts +2 -1
  166. package/src/mem_pools/tx_pool_v2/index.ts +1 -1
  167. package/src/mem_pools/tx_pool_v2/interfaces.ts +9 -4
  168. package/src/mem_pools/tx_pool_v2/tx_metadata.ts +113 -18
  169. package/src/mem_pools/tx_pool_v2/tx_pool_indices.ts +11 -11
  170. package/src/mem_pools/tx_pool_v2/tx_pool_v2.ts +14 -2
  171. package/src/mem_pools/tx_pool_v2/tx_pool_v2_impl.ts +188 -153
  172. package/src/msg_validators/attestation_validator/README.md +49 -0
  173. package/src/msg_validators/proposal_validator/README.md +123 -0
  174. package/src/msg_validators/proposal_validator/block_proposal_validator.ts +14 -4
  175. package/src/msg_validators/proposal_validator/checkpoint_proposal_validator.ts +20 -7
  176. package/src/msg_validators/proposal_validator/proposal_validator.ts +63 -40
  177. package/src/msg_validators/tx_validator/README.md +119 -0
  178. package/src/msg_validators/tx_validator/aggregate_tx_validator.ts +3 -3
  179. package/src/msg_validators/tx_validator/allowed_public_setup.ts +22 -27
  180. package/src/msg_validators/tx_validator/allowed_setup_helpers.ts +31 -0
  181. package/src/msg_validators/tx_validator/contract_instance_validator.ts +56 -0
  182. package/src/msg_validators/tx_validator/data_validator.ts +42 -1
  183. package/src/msg_validators/tx_validator/factory.ts +394 -78
  184. package/src/msg_validators/tx_validator/fee_payer_balance.ts +6 -2
  185. package/src/msg_validators/tx_validator/gas_validator.ts +123 -27
  186. package/src/msg_validators/tx_validator/index.ts +2 -0
  187. package/src/msg_validators/tx_validator/nullifier_cache.ts +30 -0
  188. package/src/msg_validators/tx_validator/phases_validator.ts +82 -27
  189. package/src/services/dummy_service.ts +6 -6
  190. package/src/services/encoding.ts +14 -7
  191. package/src/services/gossipsub/README.md +29 -14
  192. package/src/services/gossipsub/topic_score_params.ts +49 -13
  193. package/src/services/libp2p/libp2p_service.ts +111 -101
  194. package/src/services/reqresp/README.md +229 -0
  195. package/src/services/reqresp/batch-tx-requester/tx_validator.ts +2 -2
  196. package/src/services/reqresp/rate-limiter/rate_limiter.ts +13 -9
  197. package/src/services/reqresp/reqresp.ts +18 -10
  198. package/src/services/service.ts +11 -2
  199. package/src/services/tx_collection/file_store_tx_source.ts +43 -31
  200. package/src/services/tx_collection/tx_source.ts +8 -7
  201. package/src/services/tx_provider.ts +2 -2
  202. package/src/test-helpers/make-test-p2p-clients.ts +0 -2
  203. package/src/test-helpers/mock-pubsub.ts +13 -6
  204. package/src/test-helpers/reqresp-nodes.ts +2 -5
  205. package/src/test-helpers/testbench-utils.ts +2 -1
  206. package/src/testbench/p2p_client_testbench_worker.ts +3 -6
  207. package/src/testbench/worker_client_manager.ts +11 -4
  208. package/src/util.ts +7 -1
  209. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts +0 -23
  210. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.d.ts.map +0 -1
  211. package/dest/msg_validators/proposal_validator/proposal_validator_test_suite.js +0 -212
  212. package/src/msg_validators/proposal_validator/proposal_validator_test_suite.ts +0 -230
@@ -1,5 +1,7 @@
1
1
  import { MAX_FR_CALLDATA_TO_ALL_ENQUEUED_CALLS } from '@aztec/constants';
2
2
  import { type Logger, type LoggerBindings, createLogger } from '@aztec/foundation/log';
3
+ import { ContractClassPublishedEvent } from '@aztec/protocol-contracts/class-registry';
4
+ import { computeContractClassId } from '@aztec/stdlib/contract';
3
5
  import { computeCalldataHash } from '@aztec/stdlib/hash';
4
6
  import {
5
7
  TX_ERROR_CALLDATA_COUNT_MISMATCH,
@@ -9,7 +11,9 @@ import {
9
11
  TX_ERROR_CONTRACT_CLASS_LOG_LENGTH,
10
12
  TX_ERROR_CONTRACT_CLASS_LOG_SORTING,
11
13
  TX_ERROR_INCORRECT_CALLDATA,
14
+ TX_ERROR_INCORRECT_CONTRACT_CLASS_ID,
12
15
  TX_ERROR_INCORRECT_HASH,
16
+ TX_ERROR_MALFORMED_CONTRACT_CLASS_LOG,
13
17
  Tx,
14
18
  type TxValidationResult,
15
19
  type TxValidator,
@@ -26,7 +30,8 @@ export class DataTxValidator implements TxValidator<Tx> {
26
30
  const reason =
27
31
  (await this.#hasCorrectHash(tx)) ??
28
32
  (await this.#hasCorrectCalldata(tx)) ??
29
- (await this.#hasCorrectContractClassLogs(tx));
33
+ (await this.#hasCorrectContractClassLogs(tx)) ??
34
+ (await this.#hasCorrectContractClassIds(tx));
30
35
  return reason ? { result: 'invalid', reason: [reason] } : { result: 'valid' };
31
36
  }
32
37
 
@@ -127,4 +132,40 @@ export class DataTxValidator implements TxValidator<Tx> {
127
132
 
128
133
  return undefined;
129
134
  }
135
+
136
+ async #hasCorrectContractClassIds(tx: Tx): Promise<string | undefined> {
137
+ const contractClassLogs = tx.getContractClassLogs();
138
+ for (const log of contractClassLogs) {
139
+ if (!ContractClassPublishedEvent.isContractClassPublishedEvent(log)) {
140
+ continue;
141
+ }
142
+
143
+ let event;
144
+ try {
145
+ event = ContractClassPublishedEvent.fromLog(log);
146
+ } catch (e) {
147
+ this.#log.warn(`Rejecting tx ${tx.getTxHash()}: failed to parse contract class event: ${e}`);
148
+ return TX_ERROR_MALFORMED_CONTRACT_CLASS_LOG;
149
+ }
150
+
151
+ try {
152
+ const { publicBytecodeCommitment } = await event.toContractClassPublicWithBytecodeCommitment();
153
+ const computedClassId = await computeContractClassId({
154
+ artifactHash: event.artifactHash,
155
+ privateFunctionsRoot: event.privateFunctionsRoot,
156
+ publicBytecodeCommitment,
157
+ });
158
+ if (!computedClassId.equals(event.contractClassId)) {
159
+ this.#log.warn(
160
+ `Rejecting tx ${tx.getTxHash()}: contract class id mismatch. Claimed ${event.contractClassId}, computed ${computedClassId}`,
161
+ );
162
+ return TX_ERROR_INCORRECT_CONTRACT_CLASS_ID;
163
+ }
164
+ } catch (e) {
165
+ this.#log.warn(`Rejecting tx ${tx.getTxHash()}: failed to compute contract class id: ${e}`);
166
+ return TX_ERROR_MALFORMED_CONTRACT_CLASS_LOG;
167
+ }
168
+ }
169
+ return undefined;
170
+ }
130
171
  }
@@ -1,41 +1,92 @@
1
+ /**
2
+ * Transaction validator factories for each tx entry point.
3
+ *
4
+ * Unsolicited transactions (gossip and RPC) are fully validated before acceptance.
5
+ * Transactions received via req/resp or block proposals are only checked for
6
+ * well-formedness because we must include them for block re-execution — they may
7
+ * ultimately be invalid, which is caught during block building and reported as
8
+ * part of block validation/attestation. See the README in this directory for the
9
+ * full validation strategy.
10
+ *
11
+ * 1. **Gossip** — full validation in two stages with a pool pre-check in between.
12
+ * Stage 1 (fast): metadata, data, timestamps, double-spend, gas, phases, block header.
13
+ * Pool pre-check: `canAddPendingTx` — skips proof verification if pool would reject.
14
+ * Stage 2 (slow): proof verification.
15
+ * Orchestrated by `handleGossipedTx` in `libp2p_service.ts`.
16
+ *
17
+ * 2. **JSON-RPC** — full validation including all state-dependent checks.
18
+ * Proof verification and fee enforcement are configurable for testing purposes.
19
+ *
20
+ * 3. **Req/resp & block proposals** — well-formedness checks only (metadata, size,
21
+ * data, proof). Stored for re-execution; validity against state is not checked here.
22
+ *
23
+ * 4. **Block building** — re-validates against current state immediately before
24
+ * sequencing. Catches invalid txs that entered via req/resp or block proposals.
25
+ * Proof and data checks are skipped since they were verified on entry.
26
+ *
27
+ * 5. **Pending pool migration** — when unmined txs (e.g. from req/resp or block
28
+ * proposals) are migrated to the pending pool, the pool runs the state-dependent
29
+ * checks they missed: double-spend, block header, gas limits, and timestamps.
30
+ * This runs on every tx potentially entering the pending pool.
31
+ */
1
32
  import { BlockNumber } from '@aztec/foundation/branded-types';
2
33
  import { Fr } from '@aztec/foundation/curves/bn254';
3
34
  import type { LoggerBindings } from '@aztec/foundation/log';
4
35
  import { getVKTreeRoot } from '@aztec/noir-protocol-circuits-types/vk-tree';
5
36
  import { ProtocolContractAddress, protocolContractsHash } from '@aztec/protocol-contracts';
37
+ import type { BlockHash } from '@aztec/stdlib/block';
6
38
  import type { ContractDataSource } from '@aztec/stdlib/contract';
7
39
  import type { GasFees } from '@aztec/stdlib/gas';
8
40
  import type {
9
41
  AllowedElement,
10
42
  ClientProtocolCircuitVerifier,
43
+ MerkleTreeReadOperations,
44
+ PublicProcessorValidator,
11
45
  WorldStateSynchronizer,
12
46
  } from '@aztec/stdlib/interfaces/server';
13
47
  import { PeerErrorSeverity } from '@aztec/stdlib/p2p';
14
- import { DatabasePublicStateSource, MerkleTreeId } from '@aztec/stdlib/trees';
15
- import type { Tx, TxValidationResult, TxValidator } from '@aztec/stdlib/tx';
48
+ import { DatabasePublicStateSource, MerkleTreeId, type PublicStateSource } from '@aztec/stdlib/trees';
49
+ import type { GlobalVariables, Tx, TxValidationResult, TxValidator } from '@aztec/stdlib/tx';
16
50
  import type { UInt64 } from '@aztec/stdlib/types';
17
51
 
52
+ import type { TxMetaData } from '../../mem_pools/tx_pool_v2/tx_metadata.js';
18
53
  import { AggregateTxValidator } from './aggregate_tx_validator.js';
19
54
  import { ArchiveCache } from './archive_cache.js';
20
- import { BlockHeaderTxValidator } from './block_header_validator.js';
55
+ import { type ArchiveSource, BlockHeaderTxValidator } from './block_header_validator.js';
56
+ import { ContractInstanceTxValidator } from './contract_instance_validator.js';
21
57
  import { DataTxValidator } from './data_validator.js';
22
- import { DoubleSpendTxValidator } from './double_spend_validator.js';
23
- import { GasTxValidator } from './gas_validator.js';
58
+ import { DoubleSpendTxValidator, type NullifierSource } from './double_spend_validator.js';
59
+ import { GasLimitsValidator, GasTxValidator } from './gas_validator.js';
24
60
  import { MetadataTxValidator } from './metadata_validator.js';
25
- import { PhasesTxValidator } from './phases_validator.js';
61
+ import { NullifierCache } from './nullifier_cache.js';
62
+ import { AllowedSetupCallsMetaValidator, PhasesTxValidator } from './phases_validator.js';
26
63
  import { SizeTxValidator } from './size_validator.js';
27
64
  import { TimestampTxValidator } from './timestamp_validator.js';
28
65
  import { TxPermittedValidator } from './tx_permitted_validator.js';
29
66
  import { TxProofValidator } from './tx_proof_validator.js';
30
67
 
31
- export interface MessageValidator {
68
+ /**
69
+ * A validator paired with a peer penalty severity.
70
+ * Used for gossip validation where each validator's failure triggers a peer penalization
71
+ * with the associated severity level.
72
+ */
73
+ export interface TransactionValidator {
32
74
  validator: {
33
75
  validateTx(tx: Tx): Promise<TxValidationResult>;
34
76
  };
35
77
  severity: PeerErrorSeverity;
36
78
  }
37
79
 
38
- export function createTxMessageValidators(
80
+ /**
81
+ * First stage of gossip validation — fast checks run before the pool pre-check.
82
+ *
83
+ * If any validator fails, the peer is penalized and the tx is rejected immediately,
84
+ * without consulting the pool or running proof verification.
85
+ *
86
+ * The `doubleSpendValidator` failure is special-cased by the caller (`handleGossipedTx`)
87
+ * to determine severity based on how recently the nullifier appeared.
88
+ */
89
+ export function createFirstStageTxValidationsForGossipedTransactions(
39
90
  timestamp: UInt64,
40
91
  blockNumber: BlockNumber,
41
92
  worldStateSynchronizer: WorldStateSynchronizer,
@@ -44,86 +95,112 @@ export function createTxMessageValidators(
44
95
  rollupVersion: number,
45
96
  protocolContractsHash: Fr,
46
97
  contractDataSource: ContractDataSource,
47
- proofVerifier: ClientProtocolCircuitVerifier,
48
98
  txsPermitted: boolean,
49
99
  allowedInSetup: AllowedElement[] = [],
50
100
  bindings?: LoggerBindings,
51
- ): Record<string, MessageValidator>[] {
101
+ gasLimitOpts?: { rollupManaLimit?: number; maxBlockL2Gas?: number; maxBlockDAGas?: number },
102
+ ): Record<string, TransactionValidator> {
52
103
  const merkleTree = worldStateSynchronizer.getCommitted();
53
104
 
54
- return [
55
- {
56
- txsPermittedValidator: {
57
- validator: new TxPermittedValidator(txsPermitted, bindings),
58
- severity: PeerErrorSeverity.MidToleranceError,
59
- },
60
- dataValidator: {
61
- validator: new DataTxValidator(bindings),
62
- severity: PeerErrorSeverity.HighToleranceError,
63
- },
64
- metadataValidator: {
65
- validator: new MetadataTxValidator(
66
- {
67
- l1ChainId: new Fr(l1ChainId),
68
- rollupVersion: new Fr(rollupVersion),
69
- protocolContractsHash,
70
- vkTreeRoot: getVKTreeRoot(),
71
- },
72
- bindings,
73
- ),
74
- severity: PeerErrorSeverity.HighToleranceError,
75
- },
76
- timestampValidator: {
77
- validator: new TimestampTxValidator<Tx>(
78
- {
79
- timestamp,
80
- blockNumber,
81
- },
82
- bindings,
83
- ),
84
- severity: PeerErrorSeverity.MidToleranceError,
85
- },
86
- doubleSpendValidator: {
87
- validator: new DoubleSpendTxValidator(
88
- {
89
- nullifiersExist: async (nullifiers: Buffer[]) => {
90
- const merkleTree = worldStateSynchronizer.getCommitted();
91
- const indices = await merkleTree.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, nullifiers);
92
- return indices.map(index => index !== undefined);
93
- },
105
+ return {
106
+ timestampValidator: {
107
+ validator: new TimestampTxValidator<Tx>(
108
+ {
109
+ timestamp,
110
+ blockNumber,
111
+ },
112
+ bindings,
113
+ ),
114
+ severity: PeerErrorSeverity.HighToleranceError,
115
+ },
116
+ txsPermittedValidator: {
117
+ validator: new TxPermittedValidator(txsPermitted, bindings),
118
+ severity: PeerErrorSeverity.MidToleranceError,
119
+ },
120
+ txSizeValidator: {
121
+ validator: new SizeTxValidator(bindings),
122
+ severity: PeerErrorSeverity.MidToleranceError,
123
+ },
124
+ metadataValidator: {
125
+ validator: new MetadataTxValidator(
126
+ {
127
+ l1ChainId: new Fr(l1ChainId),
128
+ rollupVersion: new Fr(rollupVersion),
129
+ protocolContractsHash,
130
+ vkTreeRoot: getVKTreeRoot(),
131
+ },
132
+ bindings,
133
+ ),
134
+ severity: PeerErrorSeverity.MidToleranceError,
135
+ },
136
+ phasesValidator: {
137
+ validator: new PhasesTxValidator(contractDataSource, allowedInSetup, timestamp, bindings),
138
+ severity: PeerErrorSeverity.MidToleranceError,
139
+ },
140
+ blockHeaderValidator: {
141
+ validator: new BlockHeaderTxValidator(new ArchiveCache(merkleTree), bindings),
142
+ severity: PeerErrorSeverity.HighToleranceError,
143
+ },
144
+ doubleSpendValidator: {
145
+ validator: new DoubleSpendTxValidator(
146
+ {
147
+ nullifiersExist: async (nullifiers: Buffer[]) => {
148
+ const merkleTree = worldStateSynchronizer.getCommitted();
149
+ const indices = await merkleTree.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, nullifiers);
150
+ return indices.map(index => index !== undefined);
94
151
  },
95
- bindings,
96
- ),
97
- severity: PeerErrorSeverity.HighToleranceError,
98
- },
99
- gasValidator: {
100
- validator: new GasTxValidator(
101
- new DatabasePublicStateSource(merkleTree),
102
- ProtocolContractAddress.FeeJuice,
103
- gasFees,
104
- bindings,
105
- ),
106
- severity: PeerErrorSeverity.HighToleranceError,
107
- },
108
- phasesValidator: {
109
- validator: new PhasesTxValidator(contractDataSource, allowedInSetup, timestamp, bindings),
110
- severity: PeerErrorSeverity.MidToleranceError,
111
- },
112
- blockHeaderValidator: {
113
- validator: new BlockHeaderTxValidator(new ArchiveCache(merkleTree), bindings),
114
- severity: PeerErrorSeverity.HighToleranceError,
115
- },
152
+ },
153
+ bindings,
154
+ ),
155
+ severity: PeerErrorSeverity.MidToleranceError, // This is handled specifically at the point of rejection by considering a recent window where it may have been valid
116
156
  },
117
- {
118
- proofValidator: {
119
- validator: new TxProofValidator(proofVerifier, bindings),
120
- severity: PeerErrorSeverity.MidToleranceError,
121
- },
157
+ gasValidator: {
158
+ validator: new GasTxValidator(
159
+ new DatabasePublicStateSource(merkleTree),
160
+ ProtocolContractAddress.FeeJuice,
161
+ gasFees,
162
+ bindings,
163
+ gasLimitOpts,
164
+ ),
165
+ severity: PeerErrorSeverity.MidToleranceError,
122
166
  },
123
- ];
167
+ dataValidator: {
168
+ validator: new DataTxValidator(bindings),
169
+ severity: PeerErrorSeverity.MidToleranceError,
170
+ },
171
+ contractInstanceValidator: {
172
+ validator: new ContractInstanceTxValidator(bindings),
173
+ severity: PeerErrorSeverity.MidToleranceError,
174
+ },
175
+ };
124
176
  }
125
177
 
126
- export function createTxReqRespValidator(
178
+ /**
179
+ * Second stage of gossip validation — expensive proof verification.
180
+ *
181
+ * Only runs after the first stage passes AND `canAddPendingTx` confirms the pool would
182
+ * accept the tx. This avoids wasting CPU on proof verification for txs the pool would reject
183
+ * (e.g., duplicates, insufficient balance, pool full).
184
+ */
185
+ export function createSecondStageTxValidationsForGossipedTransactions(
186
+ proofVerifier: ClientProtocolCircuitVerifier,
187
+ bindings?: LoggerBindings,
188
+ ): Record<string, TransactionValidator> {
189
+ return {
190
+ proofValidator: {
191
+ validator: new TxProofValidator(proofVerifier, bindings),
192
+ severity: PeerErrorSeverity.LowToleranceError,
193
+ },
194
+ };
195
+ }
196
+
197
+ /**
198
+ * Well-formedness checks only: metadata, size, data, and proof.
199
+ * Used for req/resp and block proposal txs. These txs must be accepted for block
200
+ * re-execution even though they may be invalid against current state — that is
201
+ * caught later by the block building validator.
202
+ */
203
+ function createTxValidatorForMinimumTxIntegrityChecks(
127
204
  verifier: ClientProtocolCircuitVerifier,
128
205
  {
129
206
  l1ChainId,
@@ -146,6 +223,245 @@ export function createTxReqRespValidator(
146
223
  ),
147
224
  new SizeTxValidator(bindings),
148
225
  new DataTxValidator(bindings),
226
+ new ContractInstanceTxValidator(bindings),
149
227
  new TxProofValidator(verifier, bindings),
150
228
  );
151
229
  }
230
+
231
+ /**
232
+ * Validators for txs received via req/resp or filestores.
233
+ * Checks well-formedness only — we must accept these for re-execution even if they
234
+ * are invalid against current state. State-dependent checks happen when the tx
235
+ * enters the pending pool or during block building.
236
+ */
237
+ export function createTxValidatorForReqResponseReceivedTxs(
238
+ verifier: ClientProtocolCircuitVerifier,
239
+ {
240
+ l1ChainId,
241
+ rollupVersion,
242
+ }: {
243
+ l1ChainId: number;
244
+ rollupVersion: number;
245
+ },
246
+ bindings?: LoggerBindings,
247
+ ): TxValidator {
248
+ return createTxValidatorForMinimumTxIntegrityChecks(verifier, { l1ChainId, rollupVersion }, bindings);
249
+ }
250
+
251
+ /**
252
+ * Validators for txs received in block proposals.
253
+ * Same as req/resp — well-formedness only. We must store these for block
254
+ * re-execution; their validity against state is checked during block building.
255
+ */
256
+ export function createTxValidatorForBlockProposalReceivedTxs(
257
+ verifier: ClientProtocolCircuitVerifier,
258
+ {
259
+ l1ChainId,
260
+ rollupVersion,
261
+ }: {
262
+ l1ChainId: number;
263
+ rollupVersion: number;
264
+ },
265
+ bindings?: LoggerBindings,
266
+ ): TxValidator {
267
+ return createTxValidatorForMinimumTxIntegrityChecks(verifier, { l1ChainId, rollupVersion }, bindings);
268
+ }
269
+
270
+ /**
271
+ * Validators for unsolicited txs received over JSON-RPC (from a local wallet/PXE).
272
+ * Full validation — all state-dependent checks are run. Proof verification is optional
273
+ * (can be skipped for testing purposes). Fee enforcement is also optional (skipped for testing/dev).
274
+ * Called from `AztecNodeService.isValidTx()`.
275
+ */
276
+ export function createTxValidatorForAcceptingTxsOverRPC(
277
+ db: MerkleTreeReadOperations,
278
+ contractDataSource: ContractDataSource,
279
+ verifier: ClientProtocolCircuitVerifier | undefined,
280
+ {
281
+ l1ChainId,
282
+ rollupVersion,
283
+ setupAllowList,
284
+ gasFees,
285
+ skipFeeEnforcement,
286
+ timestamp,
287
+ blockNumber,
288
+ txsPermitted,
289
+ rollupManaLimit,
290
+ maxBlockL2Gas,
291
+ maxBlockDAGas,
292
+ }: {
293
+ l1ChainId: number;
294
+ rollupVersion: number;
295
+ setupAllowList: AllowedElement[];
296
+ gasFees: GasFees;
297
+ skipFeeEnforcement?: boolean;
298
+ timestamp: UInt64;
299
+ blockNumber: BlockNumber;
300
+ txsPermitted: boolean;
301
+ rollupManaLimit: number;
302
+ maxBlockL2Gas?: number;
303
+ maxBlockDAGas?: number;
304
+ },
305
+ bindings?: LoggerBindings,
306
+ ): TxValidator<Tx> {
307
+ const validators: TxValidator<Tx>[] = [
308
+ new TxPermittedValidator(txsPermitted, bindings),
309
+ new TimestampTxValidator(
310
+ {
311
+ timestamp,
312
+ blockNumber,
313
+ },
314
+ bindings,
315
+ ),
316
+ new SizeTxValidator(bindings),
317
+ new MetadataTxValidator(
318
+ {
319
+ l1ChainId: new Fr(l1ChainId),
320
+ rollupVersion: new Fr(rollupVersion),
321
+ protocolContractsHash,
322
+ vkTreeRoot: getVKTreeRoot(),
323
+ },
324
+ bindings,
325
+ ),
326
+ new PhasesTxValidator(contractDataSource, setupAllowList, timestamp, bindings),
327
+ new BlockHeaderTxValidator(new ArchiveCache(db), bindings),
328
+ new DoubleSpendTxValidator(new NullifierCache(db), bindings),
329
+ new DataTxValidator(bindings),
330
+ new ContractInstanceTxValidator(bindings),
331
+ ];
332
+
333
+ if (!skipFeeEnforcement) {
334
+ validators.push(
335
+ new GasTxValidator(new DatabasePublicStateSource(db), ProtocolContractAddress.FeeJuice, gasFees, bindings, {
336
+ rollupManaLimit,
337
+ maxBlockL2Gas,
338
+ maxBlockDAGas,
339
+ }),
340
+ );
341
+ }
342
+
343
+ if (verifier) {
344
+ validators.push(new TxProofValidator(verifier, bindings));
345
+ }
346
+
347
+ return new AggregateTxValidator(...validators);
348
+ }
349
+
350
+ /**
351
+ * Validators for txs about to be included in a block by the sequencer.
352
+ * Re-validates against current state. This is where invalid txs that entered via
353
+ * req/resp or block proposals are caught — their invalidity is reported as part
354
+ * of block validation/attestation. Proof and data checks are omitted since they
355
+ * were already verified on entry.
356
+ * Called from `CheckpointBuilder.makeBlockBuilderDeps()`.
357
+ */
358
+ export function createTxValidatorForBlockBuilding(
359
+ db: MerkleTreeReadOperations,
360
+ contractDataSource: ContractDataSource,
361
+ globalVariables: GlobalVariables,
362
+ setupAllowList: AllowedElement[],
363
+ bindings?: LoggerBindings,
364
+ ): PublicProcessorValidator {
365
+ const nullifierCache = new NullifierCache(db);
366
+ const archiveCache = new ArchiveCache(db);
367
+ const publicStateSource = new DatabasePublicStateSource(db);
368
+
369
+ return {
370
+ preprocessValidator: createTxValidatorForValidatingAgainstCurrentState(
371
+ nullifierCache,
372
+ archiveCache,
373
+ publicStateSource,
374
+ contractDataSource,
375
+ globalVariables,
376
+ setupAllowList,
377
+ bindings,
378
+ ),
379
+ nullifierCache,
380
+ };
381
+ }
382
+
383
+ function createTxValidatorForValidatingAgainstCurrentState(
384
+ nullifierSource: NullifierSource,
385
+ archiveSource: ArchiveSource,
386
+ publicStateSource: PublicStateSource,
387
+ contractDataSource: ContractDataSource,
388
+ globalVariables: GlobalVariables,
389
+ setupAllowList: AllowedElement[],
390
+ bindings?: LoggerBindings,
391
+ ): TxValidator<Tx> {
392
+ // We don't include the TxProofValidator nor the DataTxValidator here because they are already checked by the time we get to block building.
393
+ return new AggregateTxValidator(
394
+ new TimestampTxValidator(
395
+ {
396
+ timestamp: globalVariables.timestamp,
397
+ blockNumber: globalVariables.blockNumber,
398
+ },
399
+ bindings,
400
+ ),
401
+ new PhasesTxValidator(contractDataSource, setupAllowList, globalVariables.timestamp, bindings),
402
+ new BlockHeaderTxValidator(archiveSource, bindings),
403
+ new DoubleSpendTxValidator(nullifierSource, bindings),
404
+ new GasTxValidator(publicStateSource, ProtocolContractAddress.FeeJuice, globalVariables.gasFees, bindings),
405
+ );
406
+ }
407
+
408
+ /**
409
+ * Validators for txs migrating to the pending pool.
410
+ *
411
+ * Txs that arrived via req/resp or block proposals only had well-formedness checks
412
+ * on receipt. When they fail to be mined and are migrated to the pending pool, we
413
+ * run the state-dependent checks they missed: double-spend, block header, gas limits,
414
+ * and timestamp expiry. This is run on EVERY tx potentially entering the pending pool
415
+ * — called inside `TxPoolV2Impl` during `addPendingTxs`, `prepareForSlot` (unprotect),
416
+ * `handlePrunedBlocks` (unmine), and startup hydration.
417
+ *
418
+ * Operates on `TxMetaData` rather than full `Tx` since metadata is pre-built by the pool.
419
+ * Injected into `TxPoolV2` as the `createTxValidator` factory in `TxPoolV2Dependencies`.
420
+ */
421
+ export async function createTxValidatorForTransactionsEnteringPendingTxPool(
422
+ worldStateSynchronizer: WorldStateSynchronizer,
423
+ timestamp: bigint,
424
+ blockNumber: BlockNumber,
425
+ gasLimitOpts: { rollupManaLimit?: number; maxBlockL2Gas?: number; maxBlockDAGas?: number },
426
+ bindings?: LoggerBindings,
427
+ ): Promise<TxValidator<TxMetaData>> {
428
+ await worldStateSynchronizer.syncImmediate();
429
+ const merkleTree = worldStateSynchronizer.getCommitted();
430
+ const nullifierSource: NullifierSource = {
431
+ nullifiersExist: async (nullifiers: Buffer[]) => {
432
+ const indices = await merkleTree.findLeafIndices(MerkleTreeId.NULLIFIER_TREE, nullifiers);
433
+ return indices.map(index => index !== undefined);
434
+ },
435
+ };
436
+ const archiveSource: ArchiveSource = {
437
+ getArchiveIndices: (archives: BlockHash[]) => {
438
+ return merkleTree.findLeafIndices(MerkleTreeId.ARCHIVE, archives);
439
+ },
440
+ };
441
+ return new AggregateTxValidator<TxMetaData>(
442
+ new GasLimitsValidator<TxMetaData>({ ...gasLimitOpts, bindings }),
443
+ new TimestampTxValidator<TxMetaData>({ timestamp, blockNumber }, bindings),
444
+ new DoubleSpendTxValidator<TxMetaData>(nullifierSource, bindings),
445
+ new BlockHeaderTxValidator<TxMetaData>(archiveSource, bindings),
446
+ new AllowedSetupCallsMetaValidator<TxMetaData>(bindings),
447
+ );
448
+ }
449
+
450
+ /**
451
+ * Creates a function that checks whether a tx's setup-phase calls are on the allow list.
452
+ *
453
+ * Uses the `PhasesTxValidator` on the full Tx. The result is stored as a boolean
454
+ * flag in `TxMetaData.allowedSetupCalls` at receipt time, so the pending pool
455
+ * migration validator can check it without needing the full Tx or its dependencies.
456
+ */
457
+ export function createCheckAllowedSetupCalls(
458
+ contractDataSource: ContractDataSource,
459
+ setupAllowList: AllowedElement[],
460
+ getTimestamp: () => UInt64,
461
+ ): (tx: Tx) => Promise<boolean> {
462
+ return async (tx: Tx) => {
463
+ const validator = new PhasesTxValidator(contractDataSource, setupAllowList, getTimestamp());
464
+ const result = await validator.validateTx(tx);
465
+ return result.result === 'valid';
466
+ };
467
+ }
@@ -1,5 +1,6 @@
1
+ import { FeeJuiceArtifact } from '@aztec/protocol-contracts/fee-juice';
1
2
  import { getCallRequestsWithCalldataByPhase } from '@aztec/simulator/server';
2
- import { FunctionSelector } from '@aztec/stdlib/abi';
3
+ import { FunctionSelector, getAllFunctionAbis } from '@aztec/stdlib/abi';
3
4
  import type { AztecAddress } from '@aztec/stdlib/aztec-address';
4
5
  import { type Tx, TxExecutionPhase } from '@aztec/stdlib/tx';
5
6
 
@@ -8,7 +9,10 @@ export type FeePayerBalanceDelta = {
8
9
  claimAmount: bigint;
9
10
  };
10
11
 
11
- const increasePublicBalanceSelectorPromise = FunctionSelector.fromSignature('_increase_public_balance((Field),u128)');
12
+ const increasePublicBalanceSelectorPromise = (() => {
13
+ const fn = getAllFunctionAbis(FeeJuiceArtifact).find(f => f.name === '_increase_public_balance')!;
14
+ return FunctionSelector.fromNameAndParameters(fn.name, fn.parameters);
15
+ })();
12
16
 
13
17
  export function getTxFeeLimit(tx: Tx): bigint {
14
18
  return tx.data.constants.txContext.gasSettings.getFeeLimit().toBigInt();