@aztec/stdlib 0.0.1-commit.c949de6bc → 0.0.1-commit.cbf2c2d5d

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 (258) hide show
  1. package/dest/abi/abi.d.ts +138 -1
  2. package/dest/abi/abi.d.ts.map +1 -1
  3. package/dest/abi/abi.js +10 -2
  4. package/dest/abi/buffer.d.ts +14 -4
  5. package/dest/abi/buffer.d.ts.map +1 -1
  6. package/dest/abi/buffer.js +25 -4
  7. package/dest/abi/decoder.d.ts +2 -2
  8. package/dest/abi/decoder.d.ts.map +1 -1
  9. package/dest/abi/decoder.js +6 -1
  10. package/dest/abi/encoder.d.ts +1 -1
  11. package/dest/abi/encoder.d.ts.map +1 -1
  12. package/dest/abi/encoder.js +28 -1
  13. package/dest/abi/event_metadata_definition.d.ts +3 -1
  14. package/dest/abi/event_metadata_definition.d.ts.map +1 -1
  15. package/dest/abi/event_metadata_definition.js +1 -1
  16. package/dest/abi/utils.d.ts +14 -1
  17. package/dest/abi/utils.d.ts.map +1 -1
  18. package/dest/abi/utils.js +15 -0
  19. package/dest/avm/avm.d.ts +300 -300
  20. package/dest/block/l2_block.d.ts +9 -1
  21. package/dest/block/l2_block.d.ts.map +1 -1
  22. package/dest/block/l2_block.js +12 -2
  23. package/dest/block/l2_block_source.d.ts +16 -8
  24. package/dest/block/l2_block_source.d.ts.map +1 -1
  25. package/dest/checkpoint/checkpoint.d.ts +2 -1
  26. package/dest/checkpoint/checkpoint.d.ts.map +1 -1
  27. package/dest/checkpoint/checkpoint.js +9 -4
  28. package/dest/checkpoint/index.d.ts +2 -1
  29. package/dest/checkpoint/index.d.ts.map +1 -1
  30. package/dest/checkpoint/index.js +1 -0
  31. package/dest/checkpoint/validate.d.ts +36 -0
  32. package/dest/checkpoint/validate.d.ts.map +1 -0
  33. package/dest/checkpoint/validate.js +120 -0
  34. package/dest/config/index.d.ts +2 -1
  35. package/dest/config/index.d.ts.map +1 -1
  36. package/dest/config/index.js +1 -0
  37. package/dest/config/pipelining-config.d.ts +19 -0
  38. package/dest/config/pipelining-config.d.ts.map +1 -0
  39. package/dest/config/pipelining-config.js +18 -0
  40. package/dest/config/sequencer-config.d.ts +4 -2
  41. package/dest/config/sequencer-config.d.ts.map +1 -1
  42. package/dest/config/sequencer-config.js +6 -0
  43. package/dest/contract/contract_address.d.ts +3 -3
  44. package/dest/contract/contract_address.js +3 -3
  45. package/dest/contract/contract_class_id.d.ts +2 -2
  46. package/dest/contract/contract_class_id.js +2 -2
  47. package/dest/contract/index.d.ts +1 -3
  48. package/dest/contract/index.d.ts.map +1 -1
  49. package/dest/contract/index.js +0 -2
  50. package/dest/contract/interfaces/contract_class.d.ts +3 -156
  51. package/dest/contract/interfaces/contract_class.d.ts.map +1 -1
  52. package/dest/contract/interfaces/contract_class.js +1 -28
  53. package/dest/epoch-helpers/index.d.ts +7 -1
  54. package/dest/epoch-helpers/index.d.ts.map +1 -1
  55. package/dest/epoch-helpers/index.js +10 -2
  56. package/dest/gas/gas_fees.d.ts +1 -1
  57. package/dest/gas/gas_fees.d.ts.map +1 -1
  58. package/dest/gas/gas_fees.js +4 -1
  59. package/dest/ha-signing/config.d.ts +49 -14
  60. package/dest/ha-signing/config.d.ts.map +1 -1
  61. package/dest/ha-signing/config.js +20 -15
  62. package/dest/ha-signing/index.d.ts +3 -2
  63. package/dest/ha-signing/index.d.ts.map +1 -1
  64. package/dest/ha-signing/index.js +2 -1
  65. package/dest/ha-signing/local_config.d.ts +63 -0
  66. package/dest/ha-signing/local_config.d.ts.map +1 -0
  67. package/dest/ha-signing/local_config.js +24 -0
  68. package/dest/hash/hash.d.ts +16 -1
  69. package/dest/hash/hash.d.ts.map +1 -1
  70. package/dest/hash/hash.js +24 -0
  71. package/dest/interfaces/allowed_element.d.ts +26 -20
  72. package/dest/interfaces/allowed_element.d.ts.map +1 -1
  73. package/dest/interfaces/allowed_element.js +8 -8
  74. package/dest/interfaces/archiver.d.ts +1 -1
  75. package/dest/interfaces/archiver.d.ts.map +1 -1
  76. package/dest/interfaces/archiver.js +3 -2
  77. package/dest/interfaces/aztec-node-admin.d.ts +76 -30
  78. package/dest/interfaces/aztec-node-admin.d.ts.map +1 -1
  79. package/dest/interfaces/aztec-node.d.ts +12 -6
  80. package/dest/interfaces/aztec-node.d.ts.map +1 -1
  81. package/dest/interfaces/aztec-node.js +5 -2
  82. package/dest/interfaces/block-builder.d.ts +38 -11
  83. package/dest/interfaces/block-builder.d.ts.map +1 -1
  84. package/dest/interfaces/block-builder.js +13 -6
  85. package/dest/interfaces/configs.d.ts +62 -32
  86. package/dest/interfaces/configs.d.ts.map +1 -1
  87. package/dest/interfaces/configs.js +6 -2
  88. package/dest/interfaces/l2_logs_source.d.ts +5 -3
  89. package/dest/interfaces/l2_logs_source.d.ts.map +1 -1
  90. package/dest/interfaces/merkle_tree_operations.d.ts +9 -19
  91. package/dest/interfaces/merkle_tree_operations.d.ts.map +1 -1
  92. package/dest/interfaces/prover-client.d.ts +6 -1
  93. package/dest/interfaces/prover-client.d.ts.map +1 -1
  94. package/dest/interfaces/prover-client.js +7 -1
  95. package/dest/interfaces/proving-job.d.ts +200 -200
  96. package/dest/interfaces/validator.d.ts +103 -41
  97. package/dest/interfaces/validator.d.ts.map +1 -1
  98. package/dest/interfaces/validator.js +8 -4
  99. package/dest/interfaces/world_state.d.ts +5 -4
  100. package/dest/interfaces/world_state.d.ts.map +1 -1
  101. package/dest/kernel/private_kernel_tail_circuit_public_inputs.d.ts +2 -1
  102. package/dest/kernel/private_kernel_tail_circuit_public_inputs.d.ts.map +1 -1
  103. package/dest/kernel/private_kernel_tail_circuit_public_inputs.js +4 -0
  104. package/dest/kv-store/config.d.ts +17 -0
  105. package/dest/kv-store/config.d.ts.map +1 -0
  106. package/dest/kv-store/config.js +26 -0
  107. package/dest/kv-store/index.d.ts +2 -0
  108. package/dest/kv-store/index.d.ts.map +1 -0
  109. package/dest/kv-store/index.js +1 -0
  110. package/dest/logs/index.d.ts +2 -1
  111. package/dest/logs/index.d.ts.map +1 -1
  112. package/dest/logs/index.js +1 -0
  113. package/dest/logs/log_filter.d.ts +4 -1
  114. package/dest/logs/log_filter.d.ts.map +1 -1
  115. package/dest/logs/log_filter.js +2 -1
  116. package/dest/logs/public_log.d.ts +4 -3
  117. package/dest/logs/public_log.d.ts.map +1 -1
  118. package/dest/logs/public_log.js +2 -1
  119. package/dest/logs/tagging_index_range.d.ts +40 -0
  120. package/dest/logs/tagging_index_range.d.ts.map +1 -0
  121. package/dest/logs/tagging_index_range.js +8 -0
  122. package/dest/logs/tx_scoped_l2_log.d.ts +3 -1
  123. package/dest/logs/tx_scoped_l2_log.d.ts.map +1 -1
  124. package/dest/logs/tx_scoped_l2_log.js +7 -0
  125. package/dest/messaging/l1_to_l2_message_source.d.ts +4 -2
  126. package/dest/messaging/l1_to_l2_message_source.d.ts.map +1 -1
  127. package/dest/messaging/l2_to_l1_membership.d.ts +32 -6
  128. package/dest/messaging/l2_to_l1_membership.d.ts.map +1 -1
  129. package/dest/messaging/l2_to_l1_membership.js +69 -26
  130. package/dest/noir/index.d.ts +3 -3
  131. package/dest/noir/index.d.ts.map +1 -1
  132. package/dest/p2p/checkpoint_proposal.d.ts +1 -6
  133. package/dest/p2p/checkpoint_proposal.d.ts.map +1 -1
  134. package/dest/p2p/checkpoint_proposal.js +13 -23
  135. package/dest/p2p/peer_error.d.ts +3 -1
  136. package/dest/p2p/peer_error.d.ts.map +1 -1
  137. package/dest/p2p/peer_error.js +5 -0
  138. package/dest/slashing/tally.d.ts +7 -2
  139. package/dest/slashing/tally.d.ts.map +1 -1
  140. package/dest/slashing/tally.js +30 -2
  141. package/dest/tests/factories.d.ts +2 -4
  142. package/dest/tests/factories.d.ts.map +1 -1
  143. package/dest/tests/factories.js +0 -27
  144. package/dest/tests/mocks.d.ts +4 -2
  145. package/dest/tests/mocks.d.ts.map +1 -1
  146. package/dest/tests/mocks.js +13 -8
  147. package/dest/tx/block_header.d.ts +3 -1
  148. package/dest/tx/block_header.d.ts.map +1 -1
  149. package/dest/tx/block_header.js +4 -0
  150. package/dest/tx/private_execution_result.d.ts +6 -6
  151. package/dest/tx/private_execution_result.d.ts.map +1 -1
  152. package/dest/tx/private_execution_result.js +6 -6
  153. package/dest/tx/profiling.d.ts +14 -2
  154. package/dest/tx/profiling.d.ts.map +1 -1
  155. package/dest/tx/profiling.js +13 -3
  156. package/dest/tx/simulated_tx.d.ts +113 -2
  157. package/dest/tx/simulated_tx.d.ts.map +1 -1
  158. package/dest/tx/simulated_tx.js +4 -1
  159. package/dest/tx/tx.d.ts +6 -5
  160. package/dest/tx/tx.d.ts.map +1 -1
  161. package/dest/tx/tx.js +18 -6
  162. package/dest/tx/tx_receipt.d.ts +7 -2
  163. package/dest/tx/tx_receipt.d.ts.map +1 -1
  164. package/dest/tx/tx_receipt.js +6 -3
  165. package/dest/tx/validator/error_texts.d.ts +9 -1
  166. package/dest/tx/validator/error_texts.d.ts.map +1 -1
  167. package/dest/tx/validator/error_texts.js +10 -0
  168. package/dest/update-checker/index.d.ts +3 -2
  169. package/dest/update-checker/index.d.ts.map +1 -1
  170. package/dest/update-checker/index.js +2 -1
  171. package/dest/update-checker/package_version.d.ts +3 -0
  172. package/dest/update-checker/package_version.d.ts.map +1 -0
  173. package/dest/update-checker/package_version.js +24 -0
  174. package/dest/update-checker/version_checker.d.ts +25 -0
  175. package/dest/update-checker/version_checker.d.ts.map +1 -0
  176. package/dest/update-checker/version_checker.js +50 -0
  177. package/dest/validators/errors.d.ts +6 -1
  178. package/dest/validators/errors.d.ts.map +1 -1
  179. package/dest/validators/errors.js +7 -0
  180. package/dest/versioning/versioning.d.ts +4 -2
  181. package/dest/versioning/versioning.d.ts.map +1 -1
  182. package/dest/versioning/versioning.js +4 -1
  183. package/package.json +10 -9
  184. package/src/abi/abi.ts +25 -2
  185. package/src/abi/buffer.ts +25 -4
  186. package/src/abi/decoder.ts +14 -2
  187. package/src/abi/encoder.ts +41 -1
  188. package/src/abi/event_metadata_definition.ts +2 -0
  189. package/src/abi/utils.ts +25 -0
  190. package/src/block/l2_block.ts +13 -1
  191. package/src/block/l2_block_source.ts +16 -7
  192. package/src/checkpoint/checkpoint.ts +12 -3
  193. package/src/checkpoint/index.ts +1 -0
  194. package/src/checkpoint/validate.ts +230 -0
  195. package/src/config/index.ts +1 -0
  196. package/src/config/pipelining-config.ts +31 -0
  197. package/src/config/sequencer-config.ts +9 -1
  198. package/src/contract/contract_address.ts +3 -3
  199. package/src/contract/contract_class_id.ts +2 -2
  200. package/src/contract/index.ts +0 -2
  201. package/src/contract/interfaces/contract_class.ts +2 -82
  202. package/src/epoch-helpers/index.ts +14 -0
  203. package/src/gas/README.md +123 -0
  204. package/src/gas/gas_fees.ts +7 -1
  205. package/src/ha-signing/config.ts +45 -38
  206. package/src/ha-signing/index.ts +9 -0
  207. package/src/ha-signing/local_config.ts +46 -0
  208. package/src/hash/hash.ts +29 -0
  209. package/src/interfaces/allowed_element.ts +29 -9
  210. package/src/interfaces/archiver.ts +3 -2
  211. package/src/interfaces/aztec-node.ts +24 -5
  212. package/src/interfaces/block-builder.ts +60 -14
  213. package/src/interfaces/configs.ts +25 -8
  214. package/src/interfaces/l2_logs_source.ts +4 -1
  215. package/src/interfaces/merkle_tree_operations.ts +8 -18
  216. package/src/interfaces/prover-client.ts +8 -0
  217. package/src/interfaces/validator.ts +50 -28
  218. package/src/interfaces/world_state.ts +4 -3
  219. package/src/kernel/private_kernel_tail_circuit_public_inputs.ts +9 -0
  220. package/src/kv-store/config.ts +36 -0
  221. package/src/kv-store/index.ts +1 -0
  222. package/src/logs/index.ts +1 -0
  223. package/src/logs/log_filter.ts +5 -0
  224. package/src/logs/public_log.ts +4 -2
  225. package/src/logs/tagging_index_range.ts +24 -0
  226. package/src/logs/tx_scoped_l2_log.ts +16 -0
  227. package/src/messaging/l1_to_l2_message_source.ts +3 -1
  228. package/src/messaging/l2_to_l1_membership.ts +98 -33
  229. package/src/noir/index.ts +2 -2
  230. package/src/p2p/checkpoint_proposal.ts +23 -37
  231. package/src/p2p/peer_error.ts +7 -0
  232. package/src/slashing/tally.ts +34 -1
  233. package/src/tests/factories.ts +0 -33
  234. package/src/tests/mocks.ts +18 -7
  235. package/src/tx/block_header.ts +6 -0
  236. package/src/tx/private_execution_result.ts +5 -5
  237. package/src/tx/profiling.ts +11 -2
  238. package/src/tx/simulated_tx.ts +8 -1
  239. package/src/tx/tx.ts +20 -11
  240. package/src/tx/tx_receipt.ts +7 -2
  241. package/src/tx/validator/error_texts.ts +12 -0
  242. package/src/update-checker/index.ts +2 -1
  243. package/src/update-checker/package_version.ts +30 -0
  244. package/src/update-checker/version_checker.ts +65 -0
  245. package/src/validators/errors.ts +9 -0
  246. package/src/versioning/versioning.ts +4 -1
  247. package/dest/contract/private_function_membership_proof.d.ts +0 -32
  248. package/dest/contract/private_function_membership_proof.d.ts.map +0 -1
  249. package/dest/contract/private_function_membership_proof.js +0 -124
  250. package/dest/contract/utility_function_membership_proof.d.ts +0 -27
  251. package/dest/contract/utility_function_membership_proof.d.ts.map +0 -1
  252. package/dest/contract/utility_function_membership_proof.js +0 -87
  253. package/dest/update-checker/update-checker.d.ts +0 -49
  254. package/dest/update-checker/update-checker.d.ts.map +0 -1
  255. package/dest/update-checker/update-checker.js +0 -130
  256. package/src/contract/private_function_membership_proof.ts +0 -167
  257. package/src/contract/utility_function_membership_proof.ts +0 -118
  258. package/src/update-checker/update-checker.ts +0 -166
@@ -3,6 +3,9 @@ import type { EpochNumber } from '@aztec/foundation/branded-types';
3
3
  import { Fr } from '@aztec/foundation/curves/bn254';
4
4
  import { SiblingPath, UnbalancedMerkleTreeCalculator, computeUnbalancedShaRoot } from '@aztec/foundation/trees';
5
5
 
6
+ import type { AztecNode } from '../interfaces/aztec-node.js';
7
+ import { TxHash } from '../tx/tx_hash.js';
8
+
6
9
  /**
7
10
  * # L2-to-L1 Message Tree Structure and Leaf IDs
8
11
  *
@@ -92,59 +95,94 @@ export function getL2ToL1MessageLeafId(
92
95
  return 2n ** BigInt(membershipWitness.siblingPath.pathSize) + membershipWitness.leafIndex;
93
96
  }
94
97
 
95
- export interface MessageRetrieval {
96
- getL2ToL1Messages(epoch: EpochNumber): Promise<Fr[][][][]>;
97
- }
98
-
99
98
  export type L2ToL1MembershipWitness = {
100
99
  root: Fr;
101
100
  leafIndex: bigint;
102
101
  siblingPath: SiblingPath<number>;
102
+ epochNumber: EpochNumber;
103
103
  };
104
104
 
105
+ /**
106
+ * Computes the L2 to L1 membership witness for a given message in a transaction.
107
+ *
108
+ * @param node - The Aztec node to query for block/tx/epoch data.
109
+ * @param message - The L2 to L1 message hash to prove membership of.
110
+ * @param txHash - The hash of the transaction that emitted the message.
111
+ * @param messageIndexInTx - Optional index of the message within the transaction's L2-to-L1 messages.
112
+ * If not provided, the message is found by scanning the tx's messages (throws if duplicates exist).
113
+ * @returns The membership witness and epoch number, or undefined if the tx is not yet in a block/epoch.
114
+ */
105
115
  export async function computeL2ToL1MembershipWitness(
106
- messageRetriever: MessageRetrieval,
107
- epoch: EpochNumber,
116
+ node: Pick<
117
+ AztecNode,
118
+ 'getL2ToL1Messages' | 'getTxReceipt' | 'getTxEffect' | 'getBlock' | 'getCheckpointsDataForEpoch'
119
+ >,
108
120
  message: Fr,
121
+ txHash: TxHash,
122
+ messageIndexInTx?: number,
109
123
  ): Promise<L2ToL1MembershipWitness | undefined> {
110
- const messagesInEpoch = await messageRetriever.getL2ToL1Messages(epoch);
111
- if (messagesInEpoch.length === 0) {
124
+ const { epochNumber, blockNumber } = await node.getTxReceipt(txHash);
125
+ if (epochNumber === undefined || blockNumber === undefined) {
126
+ return undefined;
127
+ }
128
+
129
+ const [messagesInEpoch, block, txEffect, checkpointsData] = await Promise.all([
130
+ node.getL2ToL1Messages(epochNumber),
131
+ node.getBlock(blockNumber),
132
+ node.getTxEffect(txHash),
133
+ node.getCheckpointsDataForEpoch(epochNumber),
134
+ ]);
135
+
136
+ if (messagesInEpoch.length === 0 || !block || !txEffect) {
137
+ return undefined;
138
+ }
139
+
140
+ const checkpointIndex = checkpointsData.findIndex(c => c.checkpointNumber === block.checkpointNumber);
141
+ if (checkpointIndex === -1) {
112
142
  return undefined;
113
143
  }
114
144
 
115
- return computeL2ToL1MembershipWitnessFromMessagesInEpoch(messagesInEpoch, message);
145
+ const blockIndex = block.indexWithinCheckpoint;
146
+ const txIndex = txEffect.txIndexInBlock;
147
+
148
+ const { root, leafIndex, siblingPath } = computeL2ToL1MembershipWitnessFromMessagesInEpoch(
149
+ messagesInEpoch,
150
+ message,
151
+ checkpointIndex,
152
+ blockIndex,
153
+ txIndex,
154
+ messageIndexInTx,
155
+ );
156
+ return { epochNumber, root, leafIndex, siblingPath };
116
157
  }
117
158
 
118
- // TODO: Allow to specify the message to consume by its index or by an offset, in case there are multiple messages with
119
- // the same value.
159
+ /**
160
+ * Computes a membership witness for a message in the epoch's L2-to-L1 message tree, given explicit position indices.
161
+ *
162
+ * @param messagesInEpoch - All L2-to-L1 messages in the epoch, organized as checkpoints → blocks → txs → messages.
163
+ * @param message - The message hash to prove membership of.
164
+ * @param checkpointIndex - Index of the checkpoint within the epoch's message array.
165
+ * @param blockIndex - Index of the block within the checkpoint.
166
+ * @param txIndex - Index of the transaction within the block.
167
+ * @param messageIndexInTx - Optional index of the message within the transaction's messages.
168
+ * If not provided, the message is found by scanning (throws if duplicates exist within the tx).
169
+ */
170
+ /** @internal Exported for testing only. */
120
171
  export function computeL2ToL1MembershipWitnessFromMessagesInEpoch(
121
172
  messagesInEpoch: Fr[][][][],
122
173
  message: Fr,
123
- ): L2ToL1MembershipWitness {
124
- // Find the index of the message in the tx, index of the tx in the block, and index of the block in the epoch.
125
- let messageIndexInTx = -1;
126
- let txIndex = -1;
127
- let blockIndex = -1;
128
- const checkpointIndex = messagesInEpoch.findIndex(messagesInCheckpoint => {
129
- blockIndex = messagesInCheckpoint.findIndex(messagesInBlock => {
130
- txIndex = messagesInBlock.findIndex(messagesInTx => {
131
- messageIndexInTx = messagesInTx.findIndex(msg => msg.equals(message));
132
- return messageIndexInTx !== -1;
133
- });
134
- return txIndex !== -1;
135
- });
136
- return blockIndex !== -1;
137
- });
138
-
139
- if (checkpointIndex === -1) {
140
- throw new Error('The L2ToL1Message you are trying to prove inclusion of does not exist');
141
- }
174
+ checkpointIndex: number,
175
+ blockIndex: number,
176
+ txIndex: number,
177
+ messageIndexInTx?: number,
178
+ ): { root: Fr; leafIndex: bigint; siblingPath: SiblingPath<number> } {
179
+ const messagesInTx = messagesInEpoch[checkpointIndex][blockIndex][txIndex];
180
+ const resolvedMessageIndex = resolveMessageIndex(messagesInTx, message, messageIndexInTx);
142
181
 
143
182
  // Build the tx tree.
144
- const messagesInTx = messagesInEpoch[checkpointIndex][blockIndex][txIndex];
145
183
  const txTree = UnbalancedMerkleTreeCalculator.create(messagesInTx.map(msg => msg.toBuffer()));
146
184
  // Get the sibling path of the target message in the tx tree.
147
- const pathToMessageInTxSubtree = txTree.getSiblingPathByLeafIndex(messageIndexInTx);
185
+ const pathToMessageInTxSubtree = txTree.getSiblingPathByLeafIndex(resolvedMessageIndex);
148
186
 
149
187
  // Build the tree of the block containing the target message.
150
188
  const blockTree = buildBlockTree(messagesInEpoch[checkpointIndex][blockIndex]);
@@ -189,7 +227,7 @@ export function computeL2ToL1MembershipWitnessFromMessagesInEpoch(
189
227
  // Compute the combined index.
190
228
  // It is the index of the message in the balanced tree (by filling up the wonky tree with empty nodes) at its current
191
229
  // height. It's used to validate the membership proof.
192
- const messageLeafPosition = txTree.getLeafLocation(messageIndexInTx);
230
+ const messageLeafPosition = txTree.getLeafLocation(resolvedMessageIndex);
193
231
  const txLeafPosition = blockTree.getLeafLocation(txIndex);
194
232
  const blockLeafPosition = checkpointTree.getLeafLocation(blockIndex);
195
233
  const checkpointLeafPosition = epochTree.getLeafLocation(checkpointIndex);
@@ -207,6 +245,33 @@ export function computeL2ToL1MembershipWitnessFromMessagesInEpoch(
207
245
  };
208
246
  }
209
247
 
248
+ function resolveMessageIndex(messagesInTx: Fr[], message: Fr, messageIndexInTx?: number): number {
249
+ if (messageIndexInTx !== undefined) {
250
+ if (!messagesInTx[messageIndexInTx]?.equals(message)) {
251
+ throw new Error(`Message at index ${messageIndexInTx} in tx does not match the expected message ${message}`);
252
+ }
253
+ return messageIndexInTx;
254
+ }
255
+
256
+ const indices = messagesInTx.reduce<number[]>((acc, msg, i) => {
257
+ if (msg.equals(message)) {
258
+ acc.push(i);
259
+ }
260
+ return acc;
261
+ }, []);
262
+
263
+ if (indices.length === 0) {
264
+ throw new Error('The L2ToL1Message you are trying to prove inclusion of does not exist');
265
+ }
266
+ if (indices.length > 1) {
267
+ throw new Error(
268
+ `Multiple messages with the same value ${message} found in tx (indices: ${indices.join(', ')}). ` +
269
+ `Provide messageIndexInTx to disambiguate.`,
270
+ );
271
+ }
272
+ return indices[0];
273
+ }
274
+
210
275
  function buildCheckpointTree(messagesInCheckpoint: Fr[][][]) {
211
276
  const blockOutHashes = messagesInCheckpoint.map(messagesInBlock => buildBlockTree(messagesInBlock).getRoot());
212
277
  return buildCompressedTree(blockOutHashes);
package/src/noir/index.ts CHANGED
@@ -19,7 +19,7 @@ export const AZTEC_VIEW_ATTRIBUTE = 'abi_view';
19
19
  export interface NoirFunctionAbi {
20
20
  /** The parameters of the function. */
21
21
  parameters: ABIParameter[];
22
- /** The return type of the function. */
22
+ /** The return type of the function, or null for void functions. */
23
23
  return_type: {
24
24
  /**
25
25
  * The type of the return value.
@@ -29,7 +29,7 @@ export interface NoirFunctionAbi {
29
29
  * The visibility of the return value.
30
30
  */
31
31
  visibility: ABIParameterVisibility;
32
- };
32
+ } | null;
33
33
  /** Mapping of error selector => error type */
34
34
  error_types: Partial<Record<string, AbiErrorType>>;
35
35
  }
@@ -101,23 +101,6 @@ export class CheckpointProposal extends Gossipable {
101
101
  return this.checkpointHeader.slotNumber;
102
102
  }
103
103
 
104
- get blockNumber(): BlockNumber {
105
- if (!this.lastBlock) {
106
- throw new Error('Cannot get blockNumber without lastBlock');
107
- }
108
- return this.lastBlock.blockHeader.getBlockNumber();
109
- }
110
-
111
- /** Convenience getter for txHashes from lastBlock */
112
- get txHashes(): TxHash[] {
113
- return this.lastBlock?.txHashes ?? [];
114
- }
115
-
116
- /** Convenience getter for txs from lastBlock */
117
- get txs(): Tx[] | undefined {
118
- return this.lastBlock?.signedTxs?.txs;
119
- }
120
-
121
104
  /**
122
105
  * Extract a BlockProposal from the last block info.
123
106
  * Uses inHash from checkpointHeader.contentCommitment.inHash
@@ -195,29 +178,32 @@ export class CheckpointProposal extends Gossipable {
195
178
  blockNumber: lastBlockInfo?.blockHeader?.globalVariables.blockNumber ?? BlockNumber(0),
196
179
  dutyType: DutyType.CHECKPOINT_PROPOSAL,
197
180
  };
198
- const checkpointSignature = await payloadSigner(checkpointHash, checkpointContext);
199
181
 
200
- if (!lastBlockInfo) {
201
- return new CheckpointProposal(checkpointHeader, archiveRoot, feeAssetPriceModifier, checkpointSignature);
182
+ if (lastBlockInfo) {
183
+ // Sign block proposal before signing checkpoint proposal to ensure HA protection
184
+ const lastBlockProposal = await BlockProposal.createProposalFromSigner(
185
+ lastBlockInfo.blockHeader,
186
+ lastBlockInfo.indexWithinCheckpoint,
187
+ checkpointHeader.inHash,
188
+ archiveRoot,
189
+ lastBlockInfo.txHashes,
190
+ lastBlockInfo.txs,
191
+ payloadSigner,
192
+ );
193
+
194
+ const checkpointSignature = await payloadSigner(checkpointHash, checkpointContext);
195
+
196
+ return new CheckpointProposal(checkpointHeader, archiveRoot, feeAssetPriceModifier, checkpointSignature, {
197
+ blockHeader: lastBlockInfo.blockHeader,
198
+ indexWithinCheckpoint: lastBlockInfo.indexWithinCheckpoint,
199
+ txHashes: lastBlockInfo.txHashes,
200
+ signature: lastBlockProposal.signature,
201
+ signedTxs: lastBlockProposal.signedTxs,
202
+ });
202
203
  }
203
204
 
204
- const lastBlockProposal = await BlockProposal.createProposalFromSigner(
205
- lastBlockInfo.blockHeader,
206
- lastBlockInfo.indexWithinCheckpoint,
207
- checkpointHeader.inHash,
208
- archiveRoot,
209
- lastBlockInfo.txHashes,
210
- lastBlockInfo.txs,
211
- payloadSigner,
212
- );
213
-
214
- return new CheckpointProposal(checkpointHeader, archiveRoot, feeAssetPriceModifier, checkpointSignature, {
215
- blockHeader: lastBlockInfo.blockHeader,
216
- indexWithinCheckpoint: lastBlockInfo.indexWithinCheckpoint,
217
- txHashes: lastBlockInfo.txHashes,
218
- signature: lastBlockProposal.signature,
219
- signedTxs: lastBlockProposal.signedTxs,
220
- });
205
+ const checkpointSignature = await payloadSigner(checkpointHash, checkpointContext);
206
+ return new CheckpointProposal(checkpointHeader, archiveRoot, feeAssetPriceModifier, checkpointSignature);
221
207
  }
222
208
 
223
209
  /**
@@ -15,3 +15,10 @@ export enum PeerErrorSeverity {
15
15
  */
16
16
  HighToleranceError = 'HighToleranceError',
17
17
  }
18
+
19
+ /** Severities ordered from mildest to harshest. */
20
+ export const PeerErrorSeverityByHarshness = [
21
+ PeerErrorSeverity.HighToleranceError,
22
+ PeerErrorSeverity.MidToleranceError,
23
+ PeerErrorSeverity.LowToleranceError,
24
+ ] as const;
@@ -1,6 +1,7 @@
1
1
  import { sumBigint } from '@aztec/foundation/bigint';
2
2
  import { padArrayEnd } from '@aztec/foundation/collection';
3
3
  import { EthAddress } from '@aztec/foundation/eth-address';
4
+ import { type Logger, createLogger } from '@aztec/foundation/log';
4
5
  import type { PartialBy } from '@aztec/foundation/types';
5
6
 
6
7
  import { getEpochForOffense } from './helpers.js';
@@ -12,6 +13,9 @@ import type { Offense, ValidatorSlashVote } from './types.js';
12
13
  * @param committees - Array of committees (each containing array of validator addresses)
13
14
  * @param epochsForCommittees - Array of epochs corresponding to each committee
14
15
  * @param settings - Settings including slashingAmounts and optional validator override lists
16
+ * @param settings.maxSlashedValidators - If set, limits the total number of [validator, epoch] pairs
17
+ * with non-zero votes. The lowest-vote pairs are zeroed out to stay within the limit.
18
+ * @param logger - Logger, logs which validators were dropped.
15
19
  * @returns Array of ValidatorSlashVote, where each vote is how many slash units the validator in that position should be slashed
16
20
  */
17
21
  export function getSlashConsensusVotesFromOffenses(
@@ -22,9 +26,11 @@ export function getSlashConsensusVotesFromOffenses(
22
26
  slashingAmounts: [bigint, bigint, bigint];
23
27
  epochDuration: number;
24
28
  targetCommitteeSize: number;
29
+ maxSlashedValidators?: number;
25
30
  },
31
+ logger: Logger = createLogger('slasher:tally'),
26
32
  ): ValidatorSlashVote[] {
27
- const { slashingAmounts, targetCommitteeSize } = settings;
33
+ const { slashingAmounts, targetCommitteeSize, maxSlashedValidators } = settings;
28
34
 
29
35
  if (committees.length !== epochsForCommittees.length) {
30
36
  throw new Error('committees and epochsForCommittees must have the same length');
@@ -53,6 +59,33 @@ export function getSlashConsensusVotesFromOffenses(
53
59
  return padArrayEnd(votes, 0, targetCommitteeSize);
54
60
  });
55
61
 
62
+ // if a cap is set, zero out the lowest-vote [validator, epoch] pairs so that the most severe slashes stay.
63
+ if (maxSlashedValidators === undefined) {
64
+ return votes;
65
+ }
66
+
67
+ const nonZeroByDescendingVote = [...votes.entries()].filter(([, vote]) => vote > 0).sort(([, a], [, b]) => b - a);
68
+
69
+ const toTruncate = nonZeroByDescendingVote.slice(maxSlashedValidators);
70
+ for (const [idx] of toTruncate) {
71
+ votes[idx] = 0;
72
+ }
73
+
74
+ if (toTruncate.length > 0) {
75
+ const truncated = toTruncate.map(([idx]) => {
76
+ const committeeIndex = Math.floor(idx / targetCommitteeSize);
77
+ const positionInCommittee = idx % targetCommitteeSize;
78
+ return {
79
+ validator: committees[committeeIndex][positionInCommittee].toString(),
80
+ epoch: epochsForCommittees[committeeIndex],
81
+ };
82
+ });
83
+ logger.warn(
84
+ `Truncated ${toTruncate.length} validator-epoch pairs to stay within limit of ${maxSlashedValidators}`,
85
+ { truncated },
86
+ );
87
+ }
88
+
56
89
  return votes;
57
90
  }
58
91
 
@@ -92,10 +92,8 @@ import {
92
92
  type ContractClassPublic,
93
93
  ContractDeploymentData,
94
94
  type ContractInstanceWithAddress,
95
- type ExecutablePrivateFunctionWithMembershipProof,
96
95
  type PrivateFunction,
97
96
  SerializableContractInstance,
98
- type UtilityFunctionWithMembershipProof,
99
97
  computeContractClassId,
100
98
  computePublicBytecodeCommitment,
101
99
  } from '../contract/index.js';
@@ -1183,35 +1181,6 @@ export function makePublicTxBaseRollupPrivateInputs(seed = 0) {
1183
1181
  });
1184
1182
  }
1185
1183
 
1186
- export function makeExecutablePrivateFunctionWithMembershipProof(
1187
- seed = 0,
1188
- ): ExecutablePrivateFunctionWithMembershipProof {
1189
- return {
1190
- selector: makeSelector(seed),
1191
- bytecode: makeBytes(100, seed + 1),
1192
- artifactTreeSiblingPath: makeTuple(3, fr, seed + 2),
1193
- artifactTreeLeafIndex: seed + 2,
1194
- privateFunctionTreeSiblingPath: makeTuple(3, fr, seed + 3),
1195
- privateFunctionTreeLeafIndex: seed + 3,
1196
- artifactMetadataHash: fr(seed + 4),
1197
- functionMetadataHash: fr(seed + 5),
1198
- utilityFunctionsTreeRoot: fr(seed + 6),
1199
- vkHash: fr(seed + 7),
1200
- };
1201
- }
1202
-
1203
- export function makeUtilityFunctionWithMembershipProof(seed = 0): UtilityFunctionWithMembershipProof {
1204
- return {
1205
- selector: makeSelector(seed),
1206
- bytecode: makeBytes(100, seed + 1),
1207
- artifactTreeSiblingPath: makeTuple(3, fr, seed + 2),
1208
- artifactTreeLeafIndex: seed + 2,
1209
- artifactMetadataHash: fr(seed + 4),
1210
- functionMetadataHash: fr(seed + 5),
1211
- privateFunctionsArtifactTreeRoot: fr(seed + 6),
1212
- };
1213
- }
1214
-
1215
1184
  export async function makeContractClassPublic(seed = 0, publicBytecode?: Buffer): Promise<ContractClassPublic> {
1216
1185
  const artifactHash = fr(seed + 1);
1217
1186
  const privateFunctionsRoot = fr(seed + 3);
@@ -1223,8 +1192,6 @@ export async function makeContractClassPublic(seed = 0, publicBytecode?: Buffer)
1223
1192
  artifactHash,
1224
1193
  packedBytecode,
1225
1194
  privateFunctionsRoot,
1226
- privateFunctions: [],
1227
- utilityFunctions: [],
1228
1195
  version: 1,
1229
1196
  };
1230
1197
  }
@@ -98,6 +98,7 @@ export const mockTx = async (
98
98
  publicCalldataSize = 2,
99
99
  feePayer,
100
100
  chonkProof = ChonkProof.random(),
101
+ gasLimits,
101
102
  maxFeesPerGas = new GasFees(10, 10),
102
103
  maxPriorityFeesPerGas,
103
104
  gasUsed = Gas.empty(),
@@ -114,6 +115,7 @@ export const mockTx = async (
114
115
  publicCalldataSize?: number;
115
116
  feePayer?: AztecAddress;
116
117
  chonkProof?: ChonkProof;
118
+ gasLimits?: Gas;
117
119
  maxFeesPerGas?: GasFees;
118
120
  maxPriorityFeesPerGas?: GasFees;
119
121
  gasUsed?: Gas;
@@ -132,7 +134,7 @@ export const mockTx = async (
132
134
  const data = PrivateKernelTailCircuitPublicInputs.empty();
133
135
  const firstNullifier = new Nullifier(new Fr(seed + 1), Fr.ZERO, 0);
134
136
  data.constants.anchorBlockHeader = anchorBlockHeader;
135
- data.constants.txContext.gasSettings = GasSettings.default({ maxFeesPerGas, maxPriorityFeesPerGas });
137
+ data.constants.txContext.gasSettings = GasSettings.default({ gasLimits, maxFeesPerGas, maxPriorityFeesPerGas });
136
138
  data.feePayer = feePayer ?? (await AztecAddress.random());
137
139
  data.gasUsed = gasUsed;
138
140
  data.constants.txContext.chainId = chainId;
@@ -425,10 +427,13 @@ export async function mockCheckpointAndMessages(
425
427
  Partial<Parameters<typeof L2Block.random>[1]> = {},
426
428
  ) {
427
429
  const slotNumber = options.slotNumber ?? SlotNumber(Number(checkpointNumber) * 10);
430
+ const globals = GlobalVariables.random({ slotNumber, ...options });
428
431
  const blocksAndMessages = [];
432
+
429
433
  // Track the previous block's archive to ensure consecutive blocks have consistent archive roots.
430
434
  // The current block's header.lastArchive must equal the previous block's archive.
431
435
  let lastArchive: AppendOnlyTreeSnapshot | undefined = previousArchive;
436
+
432
437
  // Pass maxEffects via txOptions so it reaches TxEffect.random
433
438
  const txOptions = maxEffects !== undefined ? { maxEffects } : {};
434
439
  for (let i = 0; i < (blocks?.length ?? numBlocks); i++) {
@@ -437,11 +442,11 @@ export async function mockCheckpointAndMessages(
437
442
  block:
438
443
  blocks?.[i] ??
439
444
  (await L2Block.random(blockNumber, {
445
+ ...globals,
440
446
  checkpointNumber,
441
447
  indexWithinCheckpoint: IndexWithinCheckpoint(i),
442
448
  txsPerBlock: numTxsPerBlock,
443
449
  txOptions,
444
- slotNumber,
445
450
  ...options,
446
451
  ...makeBlockOptions(blockNumber),
447
452
  ...(lastArchive ? { lastArchive } : {}),
@@ -455,12 +460,18 @@ export async function mockCheckpointAndMessages(
455
460
 
456
461
  const messages = blocksAndMessages[0].messages;
457
462
  const inHash = computeInHashFromL1ToL2Messages(messages);
458
- const checkpoint = await Checkpoint.random(checkpointNumber, { numBlocks: 0, slotNumber, inHash, ...options });
463
+ const firstBlockLastArchive = blocksAndMessages[0].block.header.lastArchive;
464
+ const checkpoint = await Checkpoint.random(checkpointNumber, {
465
+ numBlocks: 0,
466
+ inHash,
467
+ ...options,
468
+ ...globals,
469
+ lastArchive: firstBlockLastArchive,
470
+ lastArchiveRoot: firstBlockLastArchive.root,
471
+ archive: lastArchive,
472
+ });
473
+
459
474
  checkpoint.blocks = blocksAndMessages.map(({ block }) => block);
460
- // Set the checkpoint's archive to match the last block's archive for proper chaining.
461
- // When the archiver reconstructs checkpoints from L1, it uses the checkpoint's archive root
462
- // from the L1 event to set the last block's archive. Without this, the archive chain breaks.
463
- checkpoint.archive = lastArchive!;
464
475
 
465
476
  // Return lastArchive so callers can chain it across multiple checkpoints
466
477
  return { checkpoint, messages, lastArchive };
@@ -176,6 +176,12 @@ export class BlockHeader {
176
176
  this._cachedHash = Promise.resolve(new BlockHash(hashed));
177
177
  }
178
178
 
179
+ /** Recomputes the cached hash. Used for testing when header fields are mutated via unfreeze. */
180
+ recomputeHash(): Promise<BlockHash> {
181
+ this._cachedHash = undefined;
182
+ return this.hash();
183
+ }
184
+
179
185
  static random(overrides: Partial<FieldsOf<BlockHeader>> & Partial<FieldsOf<GlobalVariables>> = {}): BlockHeader {
180
186
  return BlockHeader.from({
181
187
  lastArchive: AppendOnlyTreeSnapshot.random(),
@@ -11,7 +11,7 @@ import { PrivateCircuitPublicInputs } from '../kernel/private_circuit_public_inp
11
11
  import type { IsEmpty } from '../kernel/utils/interfaces.js';
12
12
  import { sortByCounter } from '../kernel/utils/order_and_comparison.js';
13
13
  import { ContractClassLog, ContractClassLogFields } from '../logs/contract_class_log.js';
14
- import { type PreTag, PreTagSchema } from '../logs/pre_tag.js';
14
+ import { type TaggingIndexRange, TaggingIndexRangeSchema } from '../logs/tagging_index_range.js';
15
15
  import { Note } from '../note/note.js';
16
16
  import { type ZodFor, mapSchema, schemas } from '../schemas/index.js';
17
17
  import { HashedValues } from './hashed_values.js';
@@ -137,8 +137,8 @@ export class PrivateCallExecutionResult {
137
137
  public returnValues: Fr[],
138
138
  /** The offchain effects emitted during execution of this function call via the `emit_offchain_effect` oracle. */
139
139
  public offchainEffects: { data: Fr[] }[],
140
- /** The pre-tags used in this tx to compute tags for private logs */
141
- public preTags: PreTag[],
140
+ /** The tagging index ranges used in this tx to compute tags for private logs */
141
+ public taggingIndexRanges: TaggingIndexRange[],
142
142
  /** The nested executions. */
143
143
  public nestedExecutionResults: PrivateCallExecutionResult[],
144
144
  /**
@@ -161,7 +161,7 @@ export class PrivateCallExecutionResult {
161
161
  noteHashNullifierCounterMap: mapSchema(z.coerce.number(), z.number()),
162
162
  returnValues: z.array(schemas.Fr),
163
163
  offchainEffects: z.array(z.object({ data: z.array(schemas.Fr) })),
164
- preTags: z.array(PreTagSchema),
164
+ taggingIndexRanges: z.array(TaggingIndexRangeSchema),
165
165
  nestedExecutionResults: z.array(z.lazy(() => PrivateCallExecutionResult.schema)),
166
166
  contractClassLogs: z.array(CountedContractClassLog.schema),
167
167
  })
@@ -178,7 +178,7 @@ export class PrivateCallExecutionResult {
178
178
  fields.noteHashNullifierCounterMap,
179
179
  fields.returnValues,
180
180
  fields.offchainEffects,
181
- fields.preTags,
181
+ fields.taggingIndexRanges,
182
182
  fields.nestedExecutionResults,
183
183
  fields.contractClassLogs,
184
184
  );
@@ -3,6 +3,7 @@ import { type ZodFor, optional, schemas } from '@aztec/foundation/schemas';
3
3
 
4
4
  import { z } from 'zod';
5
5
 
6
+ import { AztecAddress } from '../aztec-address/index.js';
6
7
  import type { AztecNode } from '../interfaces/aztec-node.js';
7
8
  import { type PrivateExecutionStep, PrivateExecutionStepSchema } from '../kernel/private_kernel_prover_output.js';
8
9
 
@@ -160,6 +161,9 @@ export class TxProfileResult {
160
161
  export class UtilityExecutionResult {
161
162
  constructor(
162
163
  public result: Fr[],
164
+ public offchainEffects: { data: Fr[]; contractAddress: AztecAddress }[],
165
+ /** Timestamp of the anchor block used during utility execution. */
166
+ public anchorBlockTimestamp: bigint,
163
167
  public stats?: SimulationStats,
164
168
  ) {}
165
169
 
@@ -167,13 +171,18 @@ export class UtilityExecutionResult {
167
171
  return z
168
172
  .object({
169
173
  result: z.array(schemas.Fr),
174
+ offchainEffects: z.array(z.object({ data: z.array(schemas.Fr), contractAddress: AztecAddress.schema })),
175
+ anchorBlockTimestamp: schemas.BigInt,
170
176
  stats: optional(SimulationStatsSchema),
171
177
  })
172
- .transform(({ result, stats }) => new UtilityExecutionResult(result, stats));
178
+ .transform(
179
+ ({ result, offchainEffects, anchorBlockTimestamp, stats }) =>
180
+ new UtilityExecutionResult(result, offchainEffects, anchorBlockTimestamp, stats),
181
+ );
173
182
  }
174
183
 
175
184
  static random(): UtilityExecutionResult {
176
- return new UtilityExecutionResult([Fr.random()], {
185
+ return new UtilityExecutionResult([Fr.random()], [], 0n, {
177
186
  nodeRPCCalls: {
178
187
  perMethod: { getBlockHeader: { times: [1] } },
179
188
  roundTrips: {
@@ -12,9 +12,11 @@ import { Gas } from '../gas/gas.js';
12
12
  import type { GasUsed } from '../gas/gas_used.js';
13
13
  import { PrivateKernelTailCircuitPublicInputs } from '../kernel/private_kernel_tail_circuit_public_inputs.js';
14
14
  import { ChonkProof } from '../proofs/chonk_proof.js';
15
+ import type { OffchainEffect } from './offchain_effect.js';
15
16
  import {
16
17
  PrivateCallExecutionResult,
17
18
  PrivateExecutionResult,
19
+ collectOffchainEffects,
18
20
  collectSortedContractClassLogs,
19
21
  } from './private_execution_result.js';
20
22
  import { type SimulationStats, SimulationStatsSchema } from './profiling.js';
@@ -84,6 +86,11 @@ export class TxSimulationResult {
84
86
  public stats?: SimulationStats,
85
87
  ) {}
86
88
 
89
+ /** Returns offchain effects collected from private execution. */
90
+ get offchainEffects(): OffchainEffect[] {
91
+ return collectOffchainEffects(this.privateExecutionResult);
92
+ }
93
+
87
94
  get gasUsed(): GasUsed {
88
95
  return (
89
96
  this.publicOutput?.gasUsed ?? {
@@ -106,7 +113,7 @@ export class TxSimulationResult {
106
113
  .transform(TxSimulationResult.from);
107
114
  }
108
115
 
109
- static from(fields: Omit<FieldsOf<TxSimulationResult>, 'gasUsed'>) {
116
+ static from(fields: Omit<FieldsOf<TxSimulationResult>, 'gasUsed' | 'offchainEffects'>) {
110
117
  return new TxSimulationResult(
111
118
  fields.privateExecutionResult,
112
119
  fields.publicInputs,
package/src/tx/tx.ts CHANGED
@@ -1,8 +1,9 @@
1
+ import { DA_GAS_PER_FIELD, TX_DA_GAS_OVERHEAD } from '@aztec/constants';
1
2
  import { Buffer32 } from '@aztec/foundation/buffer';
2
3
  import { Fr } from '@aztec/foundation/curves/bn254';
3
4
  import type { ZodFor } from '@aztec/foundation/schemas';
4
5
  import { BufferReader, serializeArrayOfBufferableToVector, serializeToBuffer } from '@aztec/foundation/serialize';
5
- import type { FieldsOf } from '@aztec/foundation/types';
6
+ import { type FieldsOf, unfreeze } from '@aztec/foundation/types';
6
7
 
7
8
  import { z } from 'zod';
8
9
 
@@ -264,16 +265,24 @@ export class Tx extends Gossipable {
264
265
  }
265
266
 
266
267
  /**
267
- * Estimates the tx size based on its private effects. Note that the actual size of the tx
268
- * after processing will probably be larger, as public execution would generate more data.
268
+ * Returns the number of fields this tx's effects will occupy in the blob,
269
+ * based on its private side effects only. Accurate for txs without public calls.
270
+ * For txs with public calls, the actual size will be larger due to public execution outputs.
269
271
  */
270
- getEstimatedPrivateTxEffectsSize() {
271
- return (
272
- this.data.getNonEmptyNoteHashes().length * Fr.SIZE_IN_BYTES +
273
- this.data.getNonEmptyNullifiers().length * Fr.SIZE_IN_BYTES +
274
- this.data.getEmittedPrivateLogsLength() * Fr.SIZE_IN_BYTES +
275
- this.data.getEmittedContractClassLogsLength() * Fr.SIZE_IN_BYTES
276
- );
272
+ getPrivateTxEffectsSizeInFields(): number {
273
+ // 3 fields overhead: tx_start_marker, tx_hash, tx_fee.
274
+ // TX_DA_GAS_OVERHEAD is defined as N * DA_GAS_PER_FIELD, so this division is always exact.
275
+ const overheadFields = TX_DA_GAS_OVERHEAD / DA_GAS_PER_FIELD;
276
+ const noteHashes = this.data.getNonEmptyNoteHashes().length;
277
+ const nullifiers = this.data.getNonEmptyNullifiers().length;
278
+ const l2ToL1Msgs = this.data.getNonEmptyL2ToL1Msgs().length;
279
+ // Each private log occupies (emittedLength + 1) fields: content + length field
280
+ const privateLogFields = this.data.getNonEmptyPrivateLogs().reduce((acc, log) => acc + log.emittedLength + 1, 0);
281
+ // Each contract class log occupies (length + 1) fields: content + contract address
282
+ const contractClassLogFields = this.data
283
+ .getNonEmptyContractClassLogsHashes()
284
+ .reduce((acc, log) => acc + log.logHash.length + 1, 0);
285
+ return overheadFields + noteHashes + nullifiers + l2ToL1Msgs + privateLogFields + contractClassLogFields;
277
286
  }
278
287
 
279
288
  /**
@@ -309,7 +318,7 @@ export class Tx extends Gossipable {
309
318
 
310
319
  /** Recomputes the tx hash. Used for testing purposes only when a property of the tx was mutated. */
311
320
  public async recomputeHash(): Promise<TxHash> {
312
- (this as any).txHash = await Tx.computeTxHash(this);
321
+ unfreeze(this).txHash = await Tx.computeTxHash(this);
313
322
  return this.txHash;
314
323
  }
315
324