From 28c29a22d9c89576df6893edfb4f0b596b7b5607 Mon Sep 17 00:00:00 2001 From: Leila Wang Date: Mon, 18 Nov 2024 18:04:27 +0000 Subject: [PATCH 1/3] Remove public kernels in noir. --- .../mock-protocol-circuits/Nargo.toml | 2 +- .../Nargo.toml | 2 +- .../src/main.nr | 0 .../Nargo.template.toml | 3 - .../crates/public-kernel-lib/Nargo.toml | 9 - .../public-kernel-lib/src/components/mod.nr | 2 - .../public_kernel_output_composer.nr | 156 ---- .../propagate_accumulated_data.nr | 75 -- .../components/public_tail_output_composer.nr | 60 -- .../combine_data.nr | 89 --- .../generate_output_hints.nr | 37 - ...generate_overridable_public_data_writes.nr | 52 -- .../generate_public_data_leaves.nr | 102 --- .../crates/public-kernel-lib/src/lib.nr | 7 - .../src/public_kernel_merge.nr | 163 ----- .../src/public_kernel_phase.nr | 8 - .../src/public_kernel_tail.nr | 673 ------------------ .../public-kernel-merge-simulated/Nargo.toml | 9 - .../public-kernel-merge-simulated/src/main.nr | 8 - .../public-kernel-tail-simulated/Nargo.toml | 9 - .../public-kernel-tail-simulated/src/main.nr | 8 - .../crates/reset-kernel-lib/src/lib.nr | 6 - ...llifier_non_existent_read_request_reset.nr | 31 - .../src/public_data_read_request_hints.nr | 58 -- .../public_validation_request_processor.nr | 173 ----- .../crates/reset-kernel-lib/src/reset/mod.nr | 3 - .../src/reset/mutable_data_read_request.nr | 526 -------------- .../src/reset/non_existent_read_request.nr | 387 ---------- .../src/reset/read_request.nr | 1 - .../src/reset/tree_leaf_read_request.nr | 26 - .../crates/reset-kernel-lib/src/tests/mod.nr | 1 - ...non_existent_read_request_hints_builder.nr | 86 --- .../rollup-lib/src/base/base_rollup_inputs.nr | 5 +- .../rollup-lib/src/base/public_base_rollup.nr | 2 +- .../types/src/abis/accumulated_data/mod.nr | 4 - .../public_accumulated_data.nr | 265 ------- .../public_accumulated_data_builder.nr | 82 --- .../types/src/abis/enqueued_call_data.nr | 9 - .../abis/kernel_circuit_public_inputs/mod.nr | 6 - .../public_kernel_circuit_public_inputs.nr | 98 --- ...ic_kernel_circuit_public_inputs_builder.nr | 68 -- .../vm_circuit_public_inputs.nr | 135 ---- .../crates/types/src/abis/mod.nr | 8 - .../crates/types/src/abis/public_call_data.nr | 11 - .../types/src/abis/public_call_request.nr | 2 +- .../abis/public_call_stack_item_compressed.nr | 94 --- .../src/abis/public_circuit_public_inputs.nr | 237 ------ .../crates/types/src/abis/public_data_read.nr | 57 -- .../src/abis/public_data_update_request.nr | 67 -- .../types/src/abis/public_data_write.nr | 61 +- .../src/abis/public_inner_call_request.nr | 64 -- .../types/src/abis/public_kernel_data.nr | 47 -- .../crates/types/src/abis/side_effect.nr | 5 - .../types/src/abis/tree_leaf_read_request.nr | 38 - .../types/src/abis/validation_requests/mod.nr | 4 - .../public_validation_requests.nr | 216 ------ .../public_validation_requests_builder.nr | 71 -- .../crates/types/src/contrakt/mod.nr | 2 - .../crates/types/src/contrakt/storage_read.nr | 51 -- .../src/contrakt/storage_update_request.nr | 52 -- .../crates/types/src/data/mod.nr | 4 +- .../crates/types/src/data/public_data_hint.nr | 2 - .../types/src/data/public_data_leaf_hint.nr | 19 - .../types/src/data/public_data_tree_leaf.nr | 37 +- .../crates/types/src/hash.nr | 1 - .../crates/types/src/lib.nr | 3 +- .../crates/types/src/tests/fixture_builder.nr | 219 +----- .../src/tests/fixtures/contract_functions.nr | 16 - .../crates/types/src/utils/arrays.nr | 7 - ...combined_sorted_transformed_value_array.nr | 394 ---------- .../get_combined_order_hints.nr | 257 ------- .../src/utils/arrays/assert_deduped_array.nr | 156 ---- 72 files changed, 19 insertions(+), 5629 deletions(-) rename noir-projects/mock-protocol-circuits/crates/{mock-public-kernel => mock-public-base}/Nargo.toml (84%) rename noir-projects/mock-protocol-circuits/crates/{mock-public-kernel => mock-public-base}/src/main.nr (100%) delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/Nargo.toml delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/mod.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer/propagate_accumulated_data.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/combine_data.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_output_hints.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_overridable_public_data_writes.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_public_data_leaves.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/lib.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_merge.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_phase.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_tail.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/Nargo.toml delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/src/main.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/Nargo.toml delete mode 100644 noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/src/main.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_non_existent_read_request_reset.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/public_data_read_request_hints.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/public_validation_request_processor.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mutable_data_read_request.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/non_existent_read_request.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/tree_leaf_read_request.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_non_existent_read_request_hints_builder.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data_builder.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/enqueued_call_data.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs_builder.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/vm_circuit_public_inputs.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_data.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_stack_item_compressed.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/public_circuit_public_inputs.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_read.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_update_request.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/public_inner_call_request.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_data.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/tree_leaf_read_request.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests_builder.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/contrakt/mod.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_read.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_update_request.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_leaf_hint.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array/get_combined_order_hints.nr delete mode 100644 noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_deduped_array.nr diff --git a/noir-projects/mock-protocol-circuits/Nargo.toml b/noir-projects/mock-protocol-circuits/Nargo.toml index 32eb55ee14b4..dc7c6926f778 100644 --- a/noir-projects/mock-protocol-circuits/Nargo.toml +++ b/noir-projects/mock-protocol-circuits/Nargo.toml @@ -7,5 +7,5 @@ members = [ "crates/mock-private-kernel-inner", "crates/mock-private-kernel-reset", "crates/mock-private-kernel-tail", - "crates/mock-public-kernel", + "crates/mock-public-base", ] diff --git a/noir-projects/mock-protocol-circuits/crates/mock-public-kernel/Nargo.toml b/noir-projects/mock-protocol-circuits/crates/mock-public-base/Nargo.toml similarity index 84% rename from noir-projects/mock-protocol-circuits/crates/mock-public-kernel/Nargo.toml rename to noir-projects/mock-protocol-circuits/crates/mock-public-base/Nargo.toml index 26644c8f2958..b27e4dcb8daf 100644 --- a/noir-projects/mock-protocol-circuits/crates/mock-public-kernel/Nargo.toml +++ b/noir-projects/mock-protocol-circuits/crates/mock-public-base/Nargo.toml @@ -1,5 +1,5 @@ [package] -name = "mock_public_kernel" +name = "mock_public_base" type = "bin" authors = [""] compiler_version = ">=0.32.0" diff --git a/noir-projects/mock-protocol-circuits/crates/mock-public-kernel/src/main.nr b/noir-projects/mock-protocol-circuits/crates/mock-public-base/src/main.nr similarity index 100% rename from noir-projects/mock-protocol-circuits/crates/mock-public-kernel/src/main.nr rename to noir-projects/mock-protocol-circuits/crates/mock-public-base/src/main.nr diff --git a/noir-projects/noir-protocol-circuits/Nargo.template.toml b/noir-projects/noir-protocol-circuits/Nargo.template.toml index 8f497e3b8182..349516d481e9 100644 --- a/noir-projects/noir-protocol-circuits/Nargo.template.toml +++ b/noir-projects/noir-protocol-circuits/Nargo.template.toml @@ -20,9 +20,6 @@ members = [ "crates/private-kernel-empty-simulated", "crates/empty-nested", "crates/empty-nested-simulated", - "crates/public-kernel-lib", - "crates/public-kernel-merge-simulated", - "crates/public-kernel-tail-simulated", "crates/reset-kernel-lib", "crates/rollup-lib", "crates/rollup-merge", diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/Nargo.toml b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/Nargo.toml deleted file mode 100644 index 6806f1835976..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/Nargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "public_kernel_lib" -type = "lib" -authors = [""] -compiler_version = ">=0.18.0" - -[dependencies] -types = { path = "../types" } -reset_kernel_lib = { path = "../reset-kernel-lib" } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/mod.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/mod.nr deleted file mode 100644 index fbccb685e14a..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/mod.nr +++ /dev/null @@ -1,2 +0,0 @@ -mod public_kernel_output_composer; -mod public_tail_output_composer; diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer.nr deleted file mode 100644 index bb35add7cf72..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer.nr +++ /dev/null @@ -1,156 +0,0 @@ -mod propagate_accumulated_data; - -use crate::{ - components::public_kernel_output_composer::propagate_accumulated_data::propagate_accumulated_data, - public_kernel_phase::PublicKernelPhase, -}; -use dep::types::{ - abis::{ - accumulated_data::PublicAccumulatedDataBuilder, - kernel_circuit_public_inputs::{ - PublicKernelCircuitPublicInputs, PublicKernelCircuitPublicInputsBuilder, - VMCircuitPublicInputs, - }, - public_call_request::PublicCallRequest, - }, - traits::is_empty, -}; - -pub struct PublicKernelOutputComposer { - output_builder: PublicKernelCircuitPublicInputsBuilder, -} - -impl PublicKernelOutputComposer { - pub fn new_from_previous_kernel(previous_kernel: PublicKernelCircuitPublicInputs) -> Self { - let output_builder = PublicKernelCircuitPublicInputsBuilder::new(previous_kernel); - PublicKernelOutputComposer { output_builder } - } - - pub fn remove_top_call_request(&mut self, phase: u8) -> Self { - if phase == PublicKernelPhase.SETUP { - let _ = self.output_builder.end_non_revertible.public_call_stack.pop(); - } - if phase == PublicKernelPhase.APP_LOGIC { - let _ = self.output_builder.end.public_call_stack.pop(); - } - if phase == PublicKernelPhase.TEARDOWN { - self.output_builder.public_teardown_call_request = PublicCallRequest::empty(); - } - *self - } - - pub fn propagate_from_enqueued_call( - &mut self, - enqueued_call: VMCircuitPublicInputs, - phase: u8, - ) -> Self { - self.output_builder.constants.global_variables = enqueued_call.constants.global_variables; - self.propagate_revert_code(enqueued_call, phase); - self.propagate_validation_requests(enqueued_call); - self.propagate_accumulated_data(enqueued_call, phase); - self.propagate_end_side_effect_counter(enqueued_call); - *self - } - - pub fn finish(self) -> PublicKernelCircuitPublicInputs { - self.output_builder.finish() - } - - fn propagate_revert_code(&mut self, enqueued_call: VMCircuitPublicInputs, phase: u8) { - if enqueued_call.reverted { - let prev_revert_code = self.output_builder.revert_code; - if phase == PublicKernelPhase.SETUP { - // enqueued_call.reverted should be false. If not, EnqueuedCallDataValidator > validate_revert_flag will fail. - } - if phase == PublicKernelPhase.APP_LOGIC { - self.output_builder.revert_code = 1; - } - if phase == PublicKernelPhase.TEARDOWN { - // See https://docs.aztec.network/protocol-specs/gas-and-fees/kernel-tracking#handling-reverts - self.output_builder.revert_code = if prev_revert_code == 0 { - // Case where there is a new error in teardown - 2 - } else { - // Case where there is an error in both app logic and teardown - 3 - }; - } - } - } - - fn propagate_validation_requests(&mut self, enqueued_call: VMCircuitPublicInputs) { - let data = enqueued_call.validation_requests; - // Note that the public kernel cannot modify the max block number value - it simply forwards it to the rollup - let note_hash_read_requests = data.note_hash_read_requests; - for i in 0..note_hash_read_requests.len() { - let request = note_hash_read_requests[i]; - if !is_empty(request) { - self.output_builder.validation_requests.note_hash_read_requests.push(request); - } - } - - let nullifier_read_requests = data.nullifier_read_requests; - for i in 0..nullifier_read_requests.len() { - let request = nullifier_read_requests[i]; - if !is_empty(request) { - self.output_builder.validation_requests.nullifier_read_requests.push(request); - } - } - - let nullifier_non_existent_read_requests = data.nullifier_non_existent_read_requests; - for i in 0..nullifier_non_existent_read_requests.len() { - let request = nullifier_non_existent_read_requests[i]; - if !is_empty(request) { - self.output_builder.validation_requests.nullifier_non_existent_read_requests.push( - request, - ); - } - } - - let l1_to_l2_msg_read_requests = data.l1_to_l2_msg_read_requests; - for i in 0..l1_to_l2_msg_read_requests.len() { - let request = l1_to_l2_msg_read_requests[i]; - if !is_empty(request) { - self.output_builder.validation_requests.l1_to_l2_msg_read_requests.push(request); - } - } - - let read_requests = data.public_data_reads; - for i in 0..read_requests.len() { - let read_request = read_requests[i]; - if !is_empty(read_request) { - self.output_builder.validation_requests.public_data_reads.push(read_request); - } - } - } - - fn propagate_accumulated_data(&mut self, enqueued_call: VMCircuitPublicInputs, phase: u8) { - if phase == PublicKernelPhase.SETUP { - self.output_builder.end_non_revertible = propagate_accumulated_data( - &mut self.output_builder.end_non_revertible, - enqueued_call.accumulated_data, - ); - } - if (phase == PublicKernelPhase.APP_LOGIC) | (phase == PublicKernelPhase.TEARDOWN) { - self.output_builder.end = propagate_accumulated_data( - &mut self.output_builder.end, - enqueued_call.accumulated_data, - ); - } - - // TODO: Should keep the data even when reverts. - // The data is required for verifying validation requests in the tail circuit, which will then discard the - // revertible data. - let revert_in_phase = (self.output_builder.revert_code != 0) - & ((phase != PublicKernelPhase.TEARDOWN) | (self.output_builder.revert_code != 1)); // Revert in APP_LOGIC - if revert_in_phase { - let gas_used = self.output_builder.end.gas_used; - self.output_builder.end = PublicAccumulatedDataBuilder::empty(); - self.output_builder.end.gas_used = gas_used; - } - } - - fn propagate_end_side_effect_counter(&mut self, enqueued_call: VMCircuitPublicInputs) { - self.output_builder.end_side_effect_counter = enqueued_call.end_side_effect_counter; - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer/propagate_accumulated_data.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer/propagate_accumulated_data.nr deleted file mode 100644 index 2024caf04443..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_kernel_output_composer/propagate_accumulated_data.nr +++ /dev/null @@ -1,75 +0,0 @@ -use dep::types::abis::accumulated_data::{PublicAccumulatedData, PublicAccumulatedDataBuilder}; - -pub fn propagate_accumulated_data( - data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, -) -> PublicAccumulatedDataBuilder { - propagate_note_hashes(data, from_data); - propagate_nullifiers(data, from_data); - propagate_l2_to_l1_messages(data, from_data); - propagate_unencrypted_logs(data, from_data); - propagate_public_data_writes(data, from_data); - *data -} - -fn propagate_note_hashes( - data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, -) { - let note_hashes = from_data.note_hashes; - for i in 0..note_hashes.len() { - let note_hash = note_hashes[i]; - if note_hash.counter() != 0 { - data.note_hashes.push(note_hash); - } - } -} - -fn propagate_nullifiers(data: &mut PublicAccumulatedDataBuilder, from_data: PublicAccumulatedData) { - let nullifiers = from_data.nullifiers; - for i in 0..nullifiers.len() { - let nullifier = nullifiers[i]; - if nullifier.counter() != 0 { - data.nullifiers.push(nullifier); - } - } -} - -fn propagate_l2_to_l1_messages( - data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, -) { - let msgs = from_data.l2_to_l1_msgs; - for i in 0..msgs.len() { - let msg = msgs[i]; - if msg.counter() != 0 { - data.l2_to_l1_msgs.push(msg); - } - } -} - -fn propagate_unencrypted_logs( - data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, -) { - let logs = from_data.unencrypted_logs_hashes; - for i in 0..logs.len() { - let log = logs[i]; - if log.counter() != 0 { - data.unencrypted_logs_hashes.push(log); - } - } -} - -fn propagate_public_data_writes( - data: &mut PublicAccumulatedDataBuilder, - from_data: PublicAccumulatedData, -) { - let writes = from_data.public_data_update_requests; - for i in 0..writes.len() { - let write = writes[i]; - if write.counter() != 0 { - data.public_data_update_requests.push(write); - } - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer.nr deleted file mode 100644 index 87d6118f8f34..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer.nr +++ /dev/null @@ -1,60 +0,0 @@ -mod combine_data; -mod generate_output_hints; -mod generate_overridable_public_data_writes; -mod generate_public_data_leaves; - -pub use generate_output_hints::OutputHints; - -use crate::components::public_tail_output_composer::{ - combine_data::combine_data, generate_output_hints::generate_output_hints, -}; -use dep::types::{ - abis::kernel_circuit_public_inputs::{ - KernelCircuitPublicInputs, PublicKernelCircuitPublicInputs, - }, - data::PublicDataLeafHint, - partial_state_reference::PartialStateReference, -}; - -pub struct PublicTailOutputComposer { - previous_kernel: PublicKernelCircuitPublicInputs, - start_state: PartialStateReference, - public_data_leaf_hints: [PublicDataLeafHint; NUM_PUBLIC_DATA_LEAVES], -} - -impl PublicTailOutputComposer { - pub unconstrained fn new( - previous_kernel: PublicKernelCircuitPublicInputs, - start_state: PartialStateReference, - public_data_leaf_hints: [PublicDataLeafHint; NUM_PUBLIC_DATA_LEAVES], - ) -> Self { - PublicTailOutputComposer { previous_kernel, start_state, public_data_leaf_hints } - } - - pub unconstrained fn finish( - self, - ) -> (KernelCircuitPublicInputs, OutputHints) { - let output_hints = generate_output_hints(self.previous_kernel, self.public_data_leaf_hints); - - let end = combine_data( - self.previous_kernel.end_non_revertible, - self.previous_kernel.end, - output_hints, - ); - - let gas_used = - self.previous_kernel.end_non_revertible.gas_used + self.previous_kernel.end.gas_used; - - ( - KernelCircuitPublicInputs { - rollup_validation_requests: self.previous_kernel.validation_requests.for_rollup, - end, - constants: self.previous_kernel.constants, - start_state: self.start_state, - revert_code: self.previous_kernel.revert_code, - gas_used, - fee_payer: self.previous_kernel.fee_payer, - }, output_hints, - ) - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/combine_data.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/combine_data.nr deleted file mode 100644 index 8c9c4ca3dc08..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/combine_data.nr +++ /dev/null @@ -1,89 +0,0 @@ -use crate::components::public_tail_output_composer::generate_output_hints::OutputHints; -use dep::types::{ - abis::{ - accumulated_data::{CombinedAccumulatedData, PublicAccumulatedData}, - log_hash::{LogHash, ScopedLogHash}, - nullifier::Nullifier, - public_data_update_request::PublicDataUpdateRequest, - public_data_write::PublicDataWrite, - }, - constants::{MAX_CONTRACT_CLASS_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX}, - hash::silo_note_hash, - utils::arrays::{array_merge, dedupe_array, sort_by_counter_asc}, -}; - -pub unconstrained fn combine_data( - non_revertible: PublicAccumulatedData, - revertible: PublicAccumulatedData, - output_hints: OutputHints, -) -> CombinedAccumulatedData { - // Note hashes. - let mut siloed_note_hashes = [0; MAX_NOTE_HASHES_PER_TX]; - let sorted_unsiloed_note_hashes = sort_by_counter_asc(array_merge( - non_revertible.note_hashes, - revertible.note_hashes, - )); - let tx_hash = non_revertible.nullifiers[0].value; - for i in 0..sorted_unsiloed_note_hashes.len() { - let note_hash = sorted_unsiloed_note_hashes[i]; - siloed_note_hashes[i] = if note_hash.counter() == 0 { - // If counter is zero, the note hash is either empty or is emitted from private and has been siloed in private_kernel_tail_to_public. - note_hash.value() - } else { - silo_note_hash(note_hash, tx_hash, i) - }; - } - - let nullifiers = sort_by_counter_asc(array_merge( - non_revertible.nullifiers, - revertible.nullifiers, - )) - .map(|n: Nullifier| n.value); - - let l2_to_l1_msgs = sort_by_counter_asc(array_merge( - non_revertible.l2_to_l1_msgs, - revertible.l2_to_l1_msgs, - )); - - let public_data_writes = dedupe_array(output_hints.public_data_writes).map( - |w: PublicDataUpdateRequest| { - PublicDataWrite { leaf_slot: w.leaf_slot, value: w.new_value } - }, - ); - - let note_encrypted_logs_hashes = sort_by_counter_asc(array_merge( - non_revertible.note_encrypted_logs_hashes, - revertible.note_encrypted_logs_hashes, - )); - let note_encrypted_log_preimages_length = - note_encrypted_logs_hashes.fold(0, |a, b: LogHash| a + b.length); - - let encrypted_logs_hashes = sort_by_counter_asc(array_merge( - non_revertible.encrypted_logs_hashes, - revertible.encrypted_logs_hashes, - )); - let encrypted_log_preimages_length = - encrypted_logs_hashes.fold(0, |a, b: ScopedLogHash| a + b.log_hash.length); - - let unencrypted_logs_hashes = sort_by_counter_asc(array_merge( - non_revertible.unencrypted_logs_hashes, - revertible.unencrypted_logs_hashes, - )); - let unencrypted_log_preimages_length = - unencrypted_logs_hashes.fold(0, |a, b: ScopedLogHash| a + b.log_hash.length); - - CombinedAccumulatedData { - note_hashes: siloed_note_hashes, - nullifiers, - l2_to_l1_msgs, - note_encrypted_logs_hashes, - encrypted_logs_hashes, - unencrypted_logs_hashes, - contract_class_logs_hashes: [ScopedLogHash::empty(); MAX_CONTRACT_CLASS_LOGS_PER_TX], - note_encrypted_log_preimages_length, - encrypted_log_preimages_length, - unencrypted_log_preimages_length, - contract_class_log_preimages_length: 0, - public_data_writes, - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_output_hints.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_output_hints.nr deleted file mode 100644 index c87831fc683f..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_output_hints.nr +++ /dev/null @@ -1,37 +0,0 @@ -use crate::components::public_tail_output_composer::{ - generate_overridable_public_data_writes::generate_overridable_public_data_writes, - generate_public_data_leaves::generate_public_data_leaves, -}; -use dep::types::{ - abis::{ - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - public_data_write::OverridablePublicDataWrite, - }, - constants::MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - data::{OverridablePublicDataTreeLeaf, PublicDataLeafHint}, - utils::arrays::array_merge, -}; - -pub struct OutputHints { - public_data_writes: [OverridablePublicDataWrite; MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], - public_data_leaves: [OverridablePublicDataTreeLeaf; NUM_PUBLIC_DATA_LEAVES], -} - -pub unconstrained fn generate_output_hints( - previous_kernel: PublicKernelCircuitPublicInputs, - public_data_leaf_hints: [PublicDataLeafHint; NUM_PUBLIC_DATA_LEAVES], -) -> OutputHints { - let combined_writes = array_merge( - previous_kernel.end_non_revertible.public_data_update_requests, - previous_kernel.end.public_data_update_requests, - ); - let public_data_leaves = generate_public_data_leaves( - previous_kernel.validation_requests.public_data_reads, - combined_writes, - public_data_leaf_hints, - ); - let public_data_writes = - generate_overridable_public_data_writes(combined_writes, public_data_leaves); - - OutputHints { public_data_writes, public_data_leaves } -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_overridable_public_data_writes.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_overridable_public_data_writes.nr deleted file mode 100644 index b19c7b9f26eb..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_overridable_public_data_writes.nr +++ /dev/null @@ -1,52 +0,0 @@ -use dep::types::{ - abis::{ - public_data_update_request::PublicDataUpdateRequest, - public_data_write::OverridablePublicDataWrite, - }, - data::OverridablePublicDataTreeLeaf, - utils::arrays::{array_length, find_index_hint}, -}; - -pub unconstrained fn generate_overridable_public_data_writes( - public_data_writes: [PublicDataUpdateRequest; NUM_WRITES], - public_data_leaves: [OverridablePublicDataTreeLeaf; NUM_LEAVES], -) -> [OverridablePublicDataWrite; NUM_WRITES] { - let mut overridable_public_data_writes = [OverridablePublicDataWrite::empty(); NUM_WRITES]; - - let writes_len = array_length(public_data_writes); - for i in 0..writes_len { - let write = public_data_writes[i]; - let mut override_counter = 0; - let mut is_first_write = false; - let mut prev_index = 0; - let mut prev_counter = 0; - - for j in 0..writes_len { - let other = public_data_writes[j]; - if (j != i) & (other.leaf_slot == write.leaf_slot) { - if other.counter > write.counter { - if (override_counter == 0) | (other.counter < override_counter) { - override_counter = other.counter; - } - } else if other.counter < write.counter { - if other.counter > prev_counter { - prev_counter = other.counter; - prev_index = j; - } - } - } - } - - if prev_counter == 0 { - is_first_write = true; - prev_index = find_index_hint( - public_data_leaves, - |leaf: OverridablePublicDataTreeLeaf| leaf.leaf.slot == write.leaf_slot, - ); - } - - overridable_public_data_writes[i] = OverridablePublicDataWrite { write, override_counter }; - } - - (overridable_public_data_writes) -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_public_data_leaves.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_public_data_leaves.nr deleted file mode 100644 index 043a819cfb37..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/components/public_tail_output_composer/generate_public_data_leaves.nr +++ /dev/null @@ -1,102 +0,0 @@ -use dep::types::{ - abis::{public_data_read::PublicDataRead, public_data_update_request::PublicDataUpdateRequest}, - data::{OverridablePublicDataTreeLeaf, PublicDataLeafHint, PublicDataTreeLeaf}, - traits::Empty, - utils::arrays::get_sorted_result, -}; - -pub struct SlotIndex { - slot: Field, - index: u32, - counter: u32, -} - -impl Eq for SlotIndex { - fn eq(self, other: Self) -> bool { - (self.slot == other.slot) & (self.index == other.index) & (self.counter == other.counter) - } -} - -impl Empty for SlotIndex { - fn empty() -> Self { - SlotIndex { slot: 0, index: 0, counter: 0 } - } -} - -fn compare_by_slot_then_index(a: SlotIndex, b: SlotIndex) -> bool { - if a.slot == b.slot { - (a.index == 0) | (b.index > a.index) - } else { - (b.slot == 0) | ((a.slot != 0) & a.slot.lt(b.slot)) - } -} - -fn compare_by_index(a: SlotIndex, b: SlotIndex) -> bool { - (a.slot != 0) & ((b.slot == 0) | (a.index < b.index)) -} - -pub unconstrained fn generate_public_data_leaves( - reads: [PublicDataRead; NUM_READS], - writes: [PublicDataUpdateRequest; NUM_WRITES], - hints: [PublicDataLeafHint; NUM_HINTS], -) -> [OverridablePublicDataTreeLeaf; NUM_HINTS] { - // Combine reads and writes. The combined data has the slots and original indexes. - // Original indexes for writes are modified to have an offset of NUM_READS, ensuring that writes are placed after reads. - let mut combined_data: BoundedVec = BoundedVec::new(); - for i in 0..reads.len() { - let read = reads[i]; - if read.leaf_slot != 0 { - combined_data.push(SlotIndex { slot: read.leaf_slot, index: i, counter: 0 }); - } - } - for i in 0..writes.len() { - let write = writes[i]; - if write.leaf_slot != 0 { - combined_data.push( - SlotIndex { slot: write.leaf_slot, index: i + NUM_READS, counter: write.counter }, - ); - } - } - - // Sort the combined data by slot then index. - // Find the data with unique slots from the sorted result. - let sorted_combined_data = combined_data.storage.sort_via(compare_by_slot_then_index); - let mut prev_slot = 0; - let mut override_counter = 0; - let mut data_with_unique_slot: BoundedVec = BoundedVec::new(); - for i in 0..combined_data.len() { - let data = sorted_combined_data[i]; - if data.slot != prev_slot { - // Found an unique slot. - data_with_unique_slot.push(data); - prev_slot = data.slot; - override_counter = 0; - } - if data.index >= NUM_READS { - // Found a write. - // If it's the first write, update the override_counter of the data with the same slot. - if (override_counter == 0) | (data.counter < override_counter) { - override_counter = data.counter; - data_with_unique_slot.storage[data_with_unique_slot.len() - 1].counter = - override_counter; - } - } - } - - // Sort the data by original index. - let mut leaves = [OverridablePublicDataTreeLeaf::empty(); NUM_HINTS]; - let sorted_result = get_sorted_result(data_with_unique_slot.storage(), compare_by_index); - for i in 0..data_with_unique_slot.len() { - let sorted = sorted_result.sorted_array[i]; - // The provided hints should've been sorted. - let hint = hints[i]; - let exists = hint.preimage.slot == sorted.slot; - let value = if exists { hint.preimage.value } else { 0 }; - leaves[i] = OverridablePublicDataTreeLeaf { - leaf: PublicDataTreeLeaf { slot: sorted.slot, value }, - override_counter: sorted.counter, - }; - } - - leaves -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/lib.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/lib.nr deleted file mode 100644 index 0fd94c3a1d4a..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/lib.nr +++ /dev/null @@ -1,7 +0,0 @@ -mod components; -mod public_kernel_merge; -mod public_kernel_phase; -mod public_kernel_tail; - -pub use public_kernel_merge::PublicKernelMergeCircuitPrivateInputs; -pub use public_kernel_tail::PublicKernelTailCircuitPrivateInputs; diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_merge.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_merge.nr deleted file mode 100644 index 6fac486040f7..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_merge.nr +++ /dev/null @@ -1,163 +0,0 @@ -use crate::{ - components::public_kernel_output_composer::PublicKernelOutputComposer, - public_kernel_phase::PublicKernelPhase, -}; -use dep::types::abis::{ - enqueued_call_data::EnqueuedCallData, - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - public_kernel_data::PublicKernelData, -}; - -pub struct PublicKernelMergeCircuitPrivateInputs { - previous_kernel: PublicKernelData, - enqueued_call: EnqueuedCallData, -} - -impl PublicKernelMergeCircuitPrivateInputs { - fn get_phase(self) -> u8 { - let public_inputs = self.previous_kernel.public_inputs; - let needs_setup = - !public_inputs.end_non_revertible.public_call_stack[0].contract_address.is_zero(); - let needs_app_logic = !public_inputs.end.public_call_stack[0].contract_address.is_zero(); - if needs_setup { - PublicKernelPhase.SETUP - } else if needs_app_logic { - PublicKernelPhase.APP_LOGIC - } else { - PublicKernelPhase.TEARDOWN - } - } - - fn execute(self) -> PublicKernelCircuitPublicInputs { - let phase = self.get_phase(); - - PublicKernelOutputComposer::new_from_previous_kernel(self.previous_kernel.public_inputs) - .remove_top_call_request(phase) - .propagate_from_enqueued_call(self.enqueued_call.data, phase) - .finish() - } -} - -mod tests { - use crate::{ - public_kernel_merge::PublicKernelMergeCircuitPrivateInputs, - public_kernel_phase::PublicKernelPhase, - }; - use dep::types::{ - abis::{ - accumulated_data::PublicAccumulatedDataArrayLengths, - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - max_block_number::MaxBlockNumber, - validation_requests::PublicValidationRequestArrayLengths, - }, - tests::{fixture_builder::FixtureBuilder, utils::assert_array_eq}, - }; - - struct PublicKernelMergeCircuitPrivateInputsBuilder { - previous_kernel: FixtureBuilder, - previous_revertible: FixtureBuilder, - enqueued_call: FixtureBuilder, - phase: u8, - } - - impl PublicKernelMergeCircuitPrivateInputsBuilder { - pub fn new() -> Self { - let previous_kernel = FixtureBuilder::new().as_parent_contract(); - let mut previous_revertible = FixtureBuilder::new(); - let mut enqueued_call = FixtureBuilder::new().is_public_function(); - // Add an offset so that the mock data won't be the same as the values in previous_kernel. - previous_revertible.value_offset = 5555; - enqueued_call.counter_start = 7777; - enqueued_call.value_offset = 9999; - - let phase = PublicKernelPhase.SETUP; - - PublicKernelMergeCircuitPrivateInputsBuilder { - previous_kernel, - previous_revertible, - enqueued_call, - phase, - } - } - - pub fn execute(&mut self) -> PublicKernelCircuitPublicInputs { - let enqueued_call_request = self.enqueued_call.to_public_call_request(); - if self.phase == PublicKernelPhase.SETUP { - self.previous_kernel.add_public_call_request(enqueued_call_request); - } else { - self.previous_revertible.add_public_call_request(enqueued_call_request); - } - - let mut previous_kernel = self.previous_kernel.to_public_kernel_data(false); - previous_kernel.public_inputs.end = - self.previous_revertible.to_public_accumulated_data(); - - let mut enqueued_call = self.enqueued_call.to_enqueued_call_data(); - enqueued_call.data.previous_validation_request_array_lengths = PublicValidationRequestArrayLengths::new( - previous_kernel.public_inputs.validation_requests, - ); - enqueued_call.data.previous_accumulated_data_array_lengths = if self.phase - == PublicKernelPhase.SETUP { - PublicAccumulatedDataArrayLengths::new( - previous_kernel.public_inputs.end_non_revertible, - ) - } else { - PublicAccumulatedDataArrayLengths::new(previous_kernel.public_inputs.end) - }; - - previous_kernel.public_inputs.end_side_effect_counter = - enqueued_call.data.start_side_effect_counter - 1; - - let kernel = PublicKernelMergeCircuitPrivateInputs { previous_kernel, enqueued_call }; - kernel.execute() - } - - pub fn succeeded(&mut self) { - let _ = self.execute(); - } - - pub fn failed(&mut self) { - let _ = self.execute(); - } - } - - #[test] - unconstrained fn circuit_outputs_should_be_correctly_populated_with_previous_private_kernel() { - let mut builder = PublicKernelMergeCircuitPrivateInputsBuilder::new(); - - builder.previous_kernel.max_block_number = MaxBlockNumber::new(13); - - builder.enqueued_call.append_public_data_read_requests(1); - let curr_reads = builder.enqueued_call.public_data_reads.storage; - builder.previous_kernel.append_public_data_read_requests(2); - let prev_reads = builder.previous_kernel.public_data_reads.storage; - - builder.enqueued_call.append_note_hashes(2); - let curr_note_hashes = builder.enqueued_call.note_hashes.storage; - builder.previous_kernel.append_note_hashes(1); - let prev_note_hashes = builder.previous_kernel.note_hashes.storage; - - builder.enqueued_call.append_public_call_requests(2); - builder.previous_kernel.append_public_call_requests(1); - let prev_calls = builder.previous_kernel.public_call_requests.storage; - - let public_inputs = builder.execute(); - - assert_eq(public_inputs.validation_requests.for_rollup.max_block_number.unwrap(), 13); - - assert_array_eq( - public_inputs.validation_requests.public_data_reads, - [prev_reads[0], prev_reads[1], curr_reads[0]], - ); - - assert_array_eq( - public_inputs.end_non_revertible.note_hashes, - [prev_note_hashes[0], curr_note_hashes[0], curr_note_hashes[1]], - ); - - assert_array_eq( - public_inputs.end_non_revertible.public_call_stack, - [prev_calls[0].inner], // Public call requests can only be propagated from previous kernel. - ); - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_phase.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_phase.nr deleted file mode 100644 index e3de48775316..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_phase.nr +++ /dev/null @@ -1,8 +0,0 @@ -struct PublicKernelPhaseEnum { - SETUP: u8, - APP_LOGIC: u8, - TEARDOWN: u8, - TAIL: u8, -} - -global PublicKernelPhase = PublicKernelPhaseEnum { SETUP: 0, APP_LOGIC: 1, TEARDOWN: 2, TAIL: 3 }; diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_tail.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_tail.nr deleted file mode 100644 index 3d88d23b463f..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-lib/src/public_kernel_tail.nr +++ /dev/null @@ -1,673 +0,0 @@ -use crate::{ - components::public_tail_output_composer::{OutputHints, PublicTailOutputComposer}, - public_kernel_phase::PublicKernelPhase, -}; -use dep::reset_kernel_lib::{ - NullifierNonExistentReadRequestHints, - NullifierReadRequestHints, - public_data_read_request_hints::{ - build_public_data_read_request_hints, PublicDataReadRequestHints, - }, - PublicValidationRequestProcessor, - TreeLeafReadRequestHint, -}; -use dep::types::{ - abis::{ - kernel_circuit_public_inputs::KernelCircuitPublicInputs, - public_kernel_data::PublicKernelData, - }, - constants::{ - L1_TO_L2_MSG_TREE_HEIGHT, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_HINTS, MAX_PUBLIC_DATA_READS_PER_TX, NOTE_HASH_TREE_HEIGHT, - }, - data::PublicDataLeafHint, - partial_state_reference::PartialStateReference, -}; - -pub struct PublicKernelTailCircuitPrivateInputs { - previous_kernel: PublicKernelData, - note_hash_read_request_hints: [TreeLeafReadRequestHint; MAX_NOTE_HASH_READ_REQUESTS_PER_TX], - nullifier_read_request_hints: NullifierReadRequestHints, - nullifier_non_existent_read_request_hints: NullifierNonExistentReadRequestHints, - l1_to_l2_msg_read_request_hints: [TreeLeafReadRequestHint; MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX], - public_data_hints: [PublicDataLeafHint; MAX_PUBLIC_DATA_HINTS], - start_state: PartialStateReference, -} - -impl PublicKernelTailCircuitPrivateInputs { - unconstrained fn generate_output_and_hints( - self, - ) -> (KernelCircuitPublicInputs, OutputHints, PublicDataReadRequestHints) { - let (output, output_hints) = PublicTailOutputComposer::new( - self.previous_kernel.public_inputs, - self.start_state, - self.public_data_hints, - ) - .finish(); - - let public_data_read_request_hints = build_public_data_read_request_hints( - self.previous_kernel.public_inputs.validation_requests.public_data_reads, - output_hints.public_data_writes, - output_hints.public_data_leaves, - ); - - (output, output_hints, public_data_read_request_hints) - } - - pub fn execute(self) -> KernelCircuitPublicInputs { - let (output, output_hints, public_data_read_request_hints) = - unsafe { self.generate_output_and_hints() }; - - PublicValidationRequestProcessor::new( - self.previous_kernel.public_inputs, - self.start_state, - self.note_hash_read_request_hints, - self.nullifier_read_request_hints, - self.nullifier_non_existent_read_request_hints, - self.l1_to_l2_msg_read_request_hints, - output_hints.public_data_writes, - output_hints.public_data_leaves, - public_data_read_request_hints, - ) - .validate(); - - output - } -} - -mod tests { - use crate::public_kernel_tail::PublicKernelTailCircuitPrivateInputs; - use dep::reset_kernel_lib::{ - reset::read_request::{PendingReadHint, ReadRequestState, ReadRequestStatus}, - tests::{ - nullifier_non_existent_read_request_hints_builder::NullifierNonExistentReadRequestHintsBuilder, - nullifier_read_request_hints_builder::NullifierReadRequestHintsBuilder, - }, - TreeLeafReadRequestHint, - }; - use dep::types::{ - abis::{ - kernel_circuit_public_inputs::KernelCircuitPublicInputs, nullifier::ScopedNullifier, - nullifier_leaf_preimage::NullifierLeafPreimage, public_data_write::PublicDataWrite, - }, - address::AztecAddress, - constants::{ - L1_TO_L2_MSG_TREE_HEIGHT, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, MAX_PUBLIC_DATA_HINTS, - MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, NOTE_HASH_SUBTREE_HEIGHT, - NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, NOTE_HASH_TREE_HEIGHT, NULLIFIER_SUBTREE_HEIGHT, - NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_TREE_HEIGHT, - PUBLIC_DATA_SUBTREE_HEIGHT, PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, - PUBLIC_DATA_TREE_HEIGHT, - }, - data::{PublicDataLeafHint, PublicDataTreeLeafPreimage}, - hash::{compute_siloed_nullifier, silo_note_hash}, - merkle_tree::MembershipWitness, - partial_state_reference::PartialStateReference, - tests::{ - fixture_builder::FixtureBuilder, - merkle_tree_utils::NonEmptyMerkleTree, - utils::{assert_array_eq, pad_end, swap_items}, - }, - traits::is_empty, - utils::arrays::{array_merge, find_index_hint}, - }; - - fn build_note_hash_tree( - leaf_preimages: [Field; N], - ) -> NonEmptyMerkleTree { - NonEmptyMerkleTree::new( - pad_end(leaf_preimages, 0), - [0; NOTE_HASH_TREE_HEIGHT], - [0; NOTE_HASH_TREE_HEIGHT - NOTE_HASH_SUBTREE_HEIGHT], - [0; NOTE_HASH_SUBTREE_HEIGHT], - ) - } - - fn build_nullifier_tree() -> NonEmptyMerkleTree { - let mut pre_existing_nullifiers = [NullifierLeafPreimage::empty(); MAX_NULLIFIERS_PER_TX]; - pre_existing_nullifiers[0] = - NullifierLeafPreimage { nullifier: 0, next_nullifier: 100, next_index: 1 }; - pre_existing_nullifiers[1] = - NullifierLeafPreimage { nullifier: 100, next_nullifier: 0, next_index: 0 }; - NonEmptyMerkleTree::new( - pre_existing_nullifiers.map(|preimage: NullifierLeafPreimage| preimage.hash()), - [0; NULLIFIER_TREE_HEIGHT], - [0; NULLIFIER_TREE_HEIGHT - NULLIFIER_SUBTREE_HEIGHT], - [0; NULLIFIER_SUBTREE_HEIGHT], - ) - } - - fn build_public_data_tree( - leaf_preimages: [PublicDataTreeLeafPreimage; N], - ) -> NonEmptyMerkleTree { - NonEmptyMerkleTree::new( - pad_end( - leaf_preimages.map(|preimage: PublicDataTreeLeafPreimage| preimage.hash()), - 0, - ), - [0; PUBLIC_DATA_TREE_HEIGHT], - [0; PUBLIC_DATA_TREE_HEIGHT - PUBLIC_DATA_SUBTREE_HEIGHT], - [0; PUBLIC_DATA_SUBTREE_HEIGHT], - ) - } - - struct PublicKernelTailCircuitPrivateInputsBuilder { - previous_kernel: FixtureBuilder, - previous_revertible: FixtureBuilder, - note_hash_read_request_hints: BoundedVec, MAX_NOTE_HASH_READ_REQUESTS_PER_TX>, - nullifier_read_request_hints_builder: NullifierReadRequestHintsBuilder, - nullifier_non_existent_read_request_hints_builder: NullifierNonExistentReadRequestHintsBuilder, - l1_to_l2_msg_read_request_hints: BoundedVec, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX>, - note_hash_tree: NonEmptyMerkleTree, - note_hash_leaf_preimages: [Field; 2], - public_data_tree: NonEmptyMerkleTree, - public_data_leaf_preimages: [PublicDataTreeLeafPreimage; 6], - start_state: PartialStateReference, - } - - impl PublicKernelTailCircuitPrivateInputsBuilder { - pub fn new() -> PublicKernelTailCircuitPrivateInputsBuilder { - let previous_kernel = FixtureBuilder::new(); - let previous_revertible = FixtureBuilder::new(); - let nullifier_non_existent_read_request_hints_builder = - NullifierNonExistentReadRequestHintsBuilder::new(); - - PublicKernelTailCircuitPrivateInputsBuilder { - previous_kernel, - previous_revertible, - note_hash_read_request_hints: BoundedVec::new(), - nullifier_read_request_hints_builder: NullifierReadRequestHintsBuilder::new(), - nullifier_non_existent_read_request_hints_builder, - l1_to_l2_msg_read_request_hints: BoundedVec::new(), - note_hash_tree: NonEmptyMerkleTree::empty(), - note_hash_leaf_preimages: [598589, 714714], - public_data_tree: NonEmptyMerkleTree::empty(), - public_data_leaf_preimages: pad_end([], PublicDataTreeLeafPreimage::empty()), - start_state: PartialStateReference::empty(), - } - } - - pub fn with_note_hash_tree(&mut self) -> Self { - self.note_hash_tree = build_note_hash_tree(self.note_hash_leaf_preimages); - self.start_state.note_hash_tree.root = self.note_hash_tree.get_root(); - self.previous_kernel.historical_header.state.partial.note_hash_tree.root = 11111; - *self - } - - pub fn with_nullifier_tree(&mut self) -> Self { - let nullifier_tree = build_nullifier_tree(); - self.nullifier_non_existent_read_request_hints_builder.set_nullifier_tree( - nullifier_tree, - ); - self.start_state.nullifier_tree.root = nullifier_tree.get_root(); - self.previous_kernel.historical_header.state.partial.nullifier_tree.root = 22222; - *self - } - - pub fn with_public_data_tree(&mut self) -> Self { - let public_data_leaf_preimages = [ - PublicDataTreeLeafPreimage { slot: 0, value: 0, next_slot: 1111, next_index: 3 }, - PublicDataTreeLeafPreimage { - slot: 2222, - value: 200, - next_slot: 3333, - next_index: 2, - }, - PublicDataTreeLeafPreimage { slot: 3333, value: 300, next_slot: 0, next_index: 0 }, - PublicDataTreeLeafPreimage { - slot: 1111, - value: 100, - next_slot: 2222, - next_index: 1, - }, - ]; - let public_data_tree = build_public_data_tree(public_data_leaf_preimages); - self.public_data_leaf_preimages = pad_end( - public_data_leaf_preimages, - PublicDataTreeLeafPreimage::empty(), - ); - self.public_data_tree = public_data_tree; - self.start_state.public_data_tree.root = public_data_tree.get_root(); - *self - } - - pub fn add_note_hash_read_request(&mut self, leaf_index: u32) { - self.previous_kernel.add_note_hash_tree_leaf_read_requests( - self.note_hash_leaf_preimages[leaf_index], - leaf_index as Field, - ); - let sibling_path = self.note_hash_tree.get_sibling_path(leaf_index); - self.note_hash_read_request_hints.push(TreeLeafReadRequestHint { sibling_path }); - } - - pub fn add_nullifier(&mut self, unsiloed_nullifier: Field) { - self.previous_kernel.add_siloed_nullifier(unsiloed_nullifier); - self.sync_counters(); - self.set_nullifiers_for_non_existent_read_request_hints(); - } - - pub fn append_nullifiers_revertible(&mut self, num_nullifiers: u32) { - self.previous_revertible.append_siloed_nullifiers(num_nullifiers); - self.sync_counters(); - self.set_nullifiers_for_non_existent_read_request_hints(); - } - - pub fn append_nullifiers_non_revertible(&mut self, num_nullifiers: u32) { - self.previous_kernel.append_siloed_nullifiers(num_nullifiers); - self.sync_counters(); - self.set_nullifiers_for_non_existent_read_request_hints(); - } - - fn set_nullifiers_for_non_existent_read_request_hints(&mut self) { - let nullifiers = array_merge( - self.previous_kernel.nullifiers.storage(), - self.previous_revertible.nullifiers.storage(), - ) - .map(|n: ScopedNullifier| n.nullifier); - self.nullifier_non_existent_read_request_hints_builder.set_nullifiers(nullifiers); - } - - pub fn add_pending_revertible_nullifier_read_request(&mut self, nullifier_index: u32) { - let read_request_index = - self.previous_kernel.add_read_request_for_pending_nullifier(nullifier_index); - self.sync_counters(); - let hint_index = self.nullifier_read_request_hints_builder.pending_read_hints.len(); - let pending_value_index = nullifier_index + self.previous_kernel.nullifiers.len(); - let hint = PendingReadHint { read_request_index, pending_value_index }; - self.nullifier_read_request_hints_builder.pending_read_hints.push(hint); - self.nullifier_read_request_hints_builder.read_request_statuses[read_request_index] = - ReadRequestStatus { state: ReadRequestState.PENDING, hint_index }; - } - - pub fn add_pending_non_revertible_nullifier_read_request(&mut self, nullifier_index: u32) { - let read_request_index = - self.previous_kernel.add_read_request_for_pending_nullifier(nullifier_index); - self.sync_counters(); - let hint_index = self.nullifier_read_request_hints_builder.pending_read_hints.len(); - let hint = PendingReadHint { read_request_index, pending_value_index: nullifier_index }; - self.nullifier_read_request_hints_builder.pending_read_hints.push(hint); - self.nullifier_read_request_hints_builder.read_request_statuses[read_request_index] = - ReadRequestStatus { state: ReadRequestState.PENDING, hint_index }; - } - - pub fn read_non_existent_nullifier(&mut self, unsiloed_nullifier: Field) { - self.previous_kernel.add_non_existent_read_request_for_nullifier(unsiloed_nullifier); - self.sync_counters(); - let siloed_nullifier = - compute_siloed_nullifier(self.previous_kernel.contract_address, unsiloed_nullifier); - self.nullifier_non_existent_read_request_hints_builder.add_value_read(siloed_nullifier); - } - - fn create_public_data_leaf_hint(&mut self, leaf_slot: Field) -> PublicDataLeafHint { - let low_leaf_index = unsafe { - find_index_hint( - self.public_data_leaf_preimages, - |p: PublicDataTreeLeafPreimage| { - !leaf_slot.lt(p.slot) & (p.next_slot.eq(0) | leaf_slot.lt(p.next_slot)) - }, - ) - }; - - let preimage = self.public_data_leaf_preimages[low_leaf_index]; - let membership_witness = MembershipWitness { - leaf_index: low_leaf_index as Field, - sibling_path: self.public_data_tree.get_sibling_path(low_leaf_index), - }; - - PublicDataLeafHint { preimage, membership_witness } - } - - fn generate_public_data_leaf_hints( - &mut self, - ) -> [PublicDataLeafHint; MAX_PUBLIC_DATA_HINTS] { - let mut public_data_hints = BoundedVec::new(); - let mut unique_slots: BoundedVec = BoundedVec::new(); - - for i in 0..self.previous_kernel.public_data_reads.len() { - let read = self.previous_kernel.public_data_reads.get(i); - if !unique_slots.any(|s| s == read.leaf_slot) { - public_data_hints.push(self.create_public_data_leaf_hint(read.leaf_slot)); - unique_slots.push(read.leaf_slot); - } - } - - for i in 0..self.previous_kernel.public_data_update_requests.len() { - let write = self.previous_kernel.public_data_update_requests.get(i); - if !unique_slots.any(|s| s == write.leaf_slot) { - public_data_hints.push(self.create_public_data_leaf_hint(write.leaf_slot)); - unique_slots.push(write.leaf_slot); - } - } - - public_data_hints.storage() - } - - fn sync_counters(&mut self) { - let counter_non_revertible = self.previous_kernel.counter; - let counter_revertible = self.previous_revertible.counter; - if counter_non_revertible > counter_revertible { - self.previous_revertible.counter = counter_non_revertible; - } else { - self.previous_kernel.counter = counter_revertible; - } - } - - pub fn execute(&mut self) -> KernelCircuitPublicInputs { - let mut previous_kernel = self.previous_kernel.to_public_kernel_data(false); - previous_kernel.public_inputs.end = - self.previous_revertible.to_public_accumulated_data(); - - self.set_nullifiers_for_non_existent_read_request_hints(); - let public_data_hints = self.generate_public_data_leaf_hints(); - - let nullifier_read_request_hints = - unsafe { self.nullifier_read_request_hints_builder.to_hints() }; - - let nullifier_non_existent_read_request_hints = - unsafe { self.nullifier_non_existent_read_request_hints_builder.to_hints() }; - - let kernel = PublicKernelTailCircuitPrivateInputs { - previous_kernel, - note_hash_read_request_hints: self.note_hash_read_request_hints.storage(), - nullifier_read_request_hints, - nullifier_non_existent_read_request_hints, - l1_to_l2_msg_read_request_hints: self.l1_to_l2_msg_read_request_hints.storage(), - public_data_hints, - start_state: self.start_state, - }; - - kernel.execute() - } - - pub fn succeeded(&mut self) { - let _ = self.execute(); - } - - pub fn failed(&mut self) { - let _ = self.execute(); - } - } - - #[test] - unconstrained fn public_kernel_circuit_tail_succeeds() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - builder.succeeded(); - // TODO: Check the values in public inputs. - } - - #[test] - unconstrained fn measuring_of_log_lengths() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - // Logs for the previous call stack. - let prev_encrypted_logs_hash = 80; - let prev_encrypted_log_preimages_length = 13; - let prev_unencrypted_logs_hash = 956; - let prev_unencrypted_log_preimages_length = 24; - builder.previous_revertible.add_encrypted_log_hash( - prev_encrypted_logs_hash, - prev_encrypted_log_preimages_length, - ); - builder.previous_revertible.add_unencrypted_log_hash( - prev_unencrypted_logs_hash, - prev_unencrypted_log_preimages_length, - ); - // Logs for the current call stack. - let unencrypted_logs_hash = 26; - let unencrypted_log_preimages_length = 50; - builder.previous_revertible.add_unencrypted_log_hash( - unencrypted_logs_hash, - unencrypted_log_preimages_length, - ); - - let public_inputs = builder.execute(); - - assert_eq( - public_inputs.end.encrypted_log_preimages_length, - prev_encrypted_log_preimages_length, - ); - assert_eq( - public_inputs.end.unencrypted_log_preimages_length, - unencrypted_log_preimages_length + prev_unencrypted_log_preimages_length, - ); - - assert_eq( - public_inputs.end.unencrypted_logs_hashes, - builder.previous_revertible.unencrypted_logs_hashes.storage(), - ); - } - - #[test] - unconstrained fn verify_note_hash_read_requests_succeeds() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new().with_note_hash_tree(); - - builder.add_note_hash_read_request(1); - - builder.succeeded(); - } - - #[test] - unconstrained fn one_pending_nullifier_read_request() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - - builder.append_nullifiers_revertible(3); - builder.add_pending_revertible_nullifier_read_request(1); - builder.succeeded(); - } - - #[test] - unconstrained fn two_pending_nullifier_read_requests() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - - builder.append_nullifiers_revertible(3); - builder.add_pending_revertible_nullifier_read_request(1); - builder.add_pending_revertible_nullifier_read_request(0); - - builder.succeeded(); - } - - #[test] - unconstrained fn one_pending_nullifier_read_request_non_revertible() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - - builder.append_nullifiers_non_revertible(3); - builder.add_pending_non_revertible_nullifier_read_request(1); - builder.succeeded(); - } - - #[test(should_fail_with = "Value of the nullifier does not match read request")] - unconstrained fn pending_nullifier_read_request_wrong_hint_fails() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - - builder.append_nullifiers_revertible(3); - builder.add_pending_revertible_nullifier_read_request(1); - let mut hint = builder.nullifier_read_request_hints_builder.pending_read_hints.pop(); - hint.pending_value_index -= 1; - builder.nullifier_read_request_hints_builder.pending_read_hints.push(hint); - - builder.failed(); - } - - #[test(should_fail_with = "Read request counter must be greater than the counter of the nullifier")] - unconstrained fn pending_nullifier_read_request_reads_before_value_fails() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - - builder.append_nullifiers_revertible(3); - builder.add_pending_revertible_nullifier_read_request(1); - let nullifier_being_read = builder.previous_revertible.nullifiers.get(1); - let mut read_request = builder.previous_kernel.nullifier_read_requests.pop(); - read_request.read_request.counter = nullifier_being_read.counter() - 1; - builder.previous_kernel.nullifier_read_requests.push(read_request); - - builder.failed(); - } - - // TODO: Add tests for reading (non-existent) settled values. - - #[test] - unconstrained fn nullifier_non_existent_read_request() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new().with_nullifier_tree(); - - builder.add_nullifier(3); - builder.add_nullifier(1); - builder.add_nullifier(9); - - builder.read_non_existent_nullifier(8); - - builder.succeeded(); - } - - #[test(should_fail_with = "Value exists in pending set")] - unconstrained fn nullifier_non_existent_read_request_failed_read_exist() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new().with_nullifier_tree(); - - builder.add_nullifier(3); - builder.add_nullifier(1); - builder.add_nullifier(9); - - builder.read_non_existent_nullifier(1); - - builder.failed(); - } - - #[test] - unconstrained fn public_data_reads_and_writes_succeeds() { - let mut builder = - PublicKernelTailCircuitPrivateInputsBuilder::new().with_public_data_tree(); - - builder.previous_kernel.add_public_data_read_request(22, 0); - - builder.previous_kernel.add_public_data_update_request(11, 500); - builder.previous_kernel.add_public_data_update_request(22, 700); - - builder.previous_kernel.add_public_data_read_request(22, 700); - builder.previous_kernel.add_public_data_read_request(11, 500); - builder.previous_kernel.add_public_data_read_request(3333, 300); - - // Override the previous value at leaf slot 22. - builder.previous_kernel.add_public_data_update_request(22, 701); - - // Override the value of the leaf. - builder.previous_kernel.add_public_data_update_request(3333, 301); - - // Read the new values. - builder.previous_kernel.add_public_data_read_request(22, 701); - builder.previous_kernel.add_public_data_read_request(3333, 301); - - let prev_writes = builder.previous_kernel.public_data_update_requests.storage; - - // Shuffle the items so that they are not sorted by counter. - swap_items( - &mut builder.previous_kernel.public_data_update_requests, - 0, - 3, - ); - swap_items( - &mut builder.previous_kernel.public_data_update_requests, - 1, - 3, - ); - swap_items(&mut builder.previous_kernel.public_data_reads, 1, 4); - swap_items(&mut builder.previous_kernel.public_data_reads, 0, 3); - - let public_inputs = builder.execute(); - assert_array_eq( - public_inputs.end.public_data_writes, - [ - PublicDataWrite { leaf_slot: 3333, value: 301 }, - PublicDataWrite { leaf_slot: 11, value: 500 }, - PublicDataWrite { leaf_slot: 22, value: 701 }, - ], - ); - } - - #[test(should_fail_with = "value in OverridablePublicDataTreeLeaf does not match read request")] - unconstrained fn reading_uninitialized_public_data_non_zero_value_fails() { - let mut builder = - PublicKernelTailCircuitPrivateInputsBuilder::new().with_public_data_tree(); - - builder.previous_kernel.add_public_data_read_request(1234, 1); - - builder.failed(); - } - - #[test] - unconstrained fn propagate_fee_payer() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - let fee_payer = AztecAddress::from_field(123); - builder.previous_kernel.set_fee_payer(fee_payer); - let public_inputs = builder.execute(); - assert_eq(public_inputs.fee_payer, fee_payer); - - // Check that the fee payer is not set if is_fee_payer is false - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - assert_eq(is_empty(builder.previous_kernel.fee_payer), true); - let public_inputs = builder.execute(); - assert_eq(public_inputs.fee_payer, AztecAddress::empty()); - } - - #[test] - unconstrained fn combine_and_silo_accumulated_note_hashes() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - builder.previous_revertible.value_offset = 999; - builder.previous_revertible.counter = 88; - builder.previous_kernel.set_first_nullifier(); - - builder.previous_kernel.append_note_hashes(3); - // 1 of them is from private. - builder.previous_kernel.note_hashes.storage[0].note_hash.counter = 0; - let non_rev = builder.previous_kernel.note_hashes.storage; - - builder.previous_revertible.append_note_hashes(5); - // 2 of them are from private: - builder.previous_revertible.note_hashes.storage[0].note_hash.counter = 0; - builder.previous_revertible.note_hashes.storage[1].note_hash.counter = 0; - let rev = builder.previous_revertible.note_hashes.storage; - // Swap the items so that they are not ordered by counters. - swap_items(&mut builder.previous_revertible.note_hashes, 2, 3); - - let public_inputs = builder.execute(); - - let tx_hash = builder.previous_kernel.nullifiers.storage[0].value(); - let expected = [ - // Note hashes from private are already siloed. - non_rev[0].value(), - rev[0].value(), - rev[1].value(), - silo_note_hash(non_rev[1], tx_hash, 3), - silo_note_hash(non_rev[2], tx_hash, 4), - silo_note_hash(rev[2], tx_hash, 5), - silo_note_hash(rev[3], tx_hash, 6), - silo_note_hash(rev[4], tx_hash, 7), - ]; - assert_array_eq(public_inputs.end.note_hashes, expected); - } - - #[test] - unconstrained fn combine_accumulated_nullifiers() { - let mut builder = PublicKernelTailCircuitPrivateInputsBuilder::new(); - builder.previous_revertible.value_offset = 999; - builder.previous_revertible.counter = 88; - - builder.previous_kernel.append_nullifiers(3); - // 1 of them is from private: - builder.previous_kernel.nullifiers.storage[0].nullifier.counter = 0; - let non_rev = builder.previous_kernel.nullifiers.storage; - - builder.previous_revertible.append_nullifiers(5); - // 2 of them are from private: - builder.previous_revertible.nullifiers.storage[0].nullifier.counter = 0; - builder.previous_revertible.nullifiers.storage[1].nullifier.counter = 0; - let rev = builder.previous_revertible.nullifiers.storage; - // Swap the items so that they are not ordered by counters. - swap_items(&mut builder.previous_revertible.nullifiers, 2, 3); - - let public_inputs = builder.execute(); - - let expected = [non_rev[0], rev[0], rev[1], non_rev[1], non_rev[2], rev[2], rev[3], rev[4]] - .map(|n: ScopedNullifier| n.nullifier.value); - assert_array_eq(public_inputs.end.nullifiers, expected); - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/Nargo.toml b/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/Nargo.toml deleted file mode 100644 index d2d71db1e5c1..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/Nargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "public_kernel_merge_simulated" -type = "bin" -authors = [""] -compiler_version = ">=0.18.0" - -[dependencies] -types = { path = "../types" } -public_kernel_lib = { path = "../public-kernel-lib" } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/src/main.nr deleted file mode 100644 index c131d7dda9e8..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-merge-simulated/src/main.nr +++ /dev/null @@ -1,8 +0,0 @@ -use dep::public_kernel_lib::PublicKernelMergeCircuitPrivateInputs; -use dep::types::PublicKernelCircuitPublicInputs; - -unconstrained fn main( - input: PublicKernelMergeCircuitPrivateInputs, -) -> pub PublicKernelCircuitPublicInputs { - input.execute() -} diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/Nargo.toml b/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/Nargo.toml deleted file mode 100644 index 57448d5086f0..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/Nargo.toml +++ /dev/null @@ -1,9 +0,0 @@ -[package] -name = "public_kernel_tail_simulated" -type = "bin" -authors = [""] -compiler_version = ">=0.18.0" - -[dependencies] -types = { path = "../types" } -public_kernel_lib = { path = "../public-kernel-lib" } diff --git a/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/src/main.nr b/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/src/main.nr deleted file mode 100644 index d30846be3779..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/public-kernel-tail-simulated/src/main.nr +++ /dev/null @@ -1,8 +0,0 @@ -use dep::public_kernel_lib::PublicKernelTailCircuitPrivateInputs; -use dep::types::KernelCircuitPublicInputs; - -unconstrained fn main( - input: PublicKernelTailCircuitPrivateInputs, -) -> pub KernelCircuitPublicInputs { - input.execute() -} diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/lib.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/lib.nr index ef1eacbc1779..d256feb34510 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/lib.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/lib.nr @@ -1,19 +1,13 @@ mod note_hash_read_request_reset; -mod nullifier_non_existent_read_request_reset; mod nullifier_read_request_reset; mod private_validation_request_processor; -mod public_data_read_request_hints; -mod public_validation_request_processor; mod reset; mod tests; pub use note_hash_read_request_reset::NoteHashReadRequestHints; -pub use nullifier_non_existent_read_request_reset::NullifierNonExistentReadRequestHints; pub use nullifier_read_request_reset::NullifierReadRequestHints; pub use private_validation_request_processor::PrivateValidationRequestProcessor; -pub use public_validation_request_processor::PublicValidationRequestProcessor; pub use reset::{ key_validation_hint::KeyValidationHint, transient_data::{TransientDataIndexHint, verify_squashed_transient_data}, - tree_leaf_read_request::TreeLeafReadRequestHint, }; diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_non_existent_read_request_reset.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_non_existent_read_request_reset.nr deleted file mode 100644 index 4068202c37b1..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/nullifier_non_existent_read_request_reset.nr +++ /dev/null @@ -1,31 +0,0 @@ -use crate::reset::non_existent_read_request::NonMembershipHint; -use dep::types::{ - abis::{nullifier::Nullifier, nullifier_leaf_preimage::NullifierLeafPreimage}, - constants::{ - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, - NULLIFIER_TREE_HEIGHT, - }, - merkle_tree::MembershipWitness, -}; - -pub struct NullifierNonMembershipHint { - low_leaf_preimage: NullifierLeafPreimage, - membership_witness: MembershipWitness, -} - -impl NonMembershipHint for NullifierNonMembershipHint { - fn low_leaf_preimage(self) -> NullifierLeafPreimage { - self.low_leaf_preimage - } - - fn membership_witness(self) -> MembershipWitness { - self.membership_witness - } -} - -pub struct NullifierNonExistentReadRequestHints { - non_membership_hints: [NullifierNonMembershipHint; MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX], - sorted_pending_values: [Nullifier; MAX_NULLIFIERS_PER_TX], - sorted_pending_value_index_hints: [u32; MAX_NULLIFIERS_PER_TX], - next_pending_value_indices: [u32; MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX], -} diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/public_data_read_request_hints.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/public_data_read_request_hints.nr deleted file mode 100644 index 2b8effeed0a8..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/public_data_read_request_hints.nr +++ /dev/null @@ -1,58 +0,0 @@ -use crate::reset::{mutable_data_read_request::ReadIndexHint, read_request::ReadRequestStatus}; -use dep::types::{ - abis::{public_data_read::PublicDataRead, public_data_write::OverridablePublicDataWrite}, - data::OverridablePublicDataTreeLeaf, - utils::arrays::find_index_hint, -}; - -pub struct PublicDataReadRequestHints { - read_request_statuses: [ReadRequestStatus; NUM_READS], - pending_read_hints: [ReadIndexHint; NUM_READS], - leaf_data_read_hints: [ReadIndexHint; NUM_READS], -} - -pub unconstrained fn build_public_data_read_request_hints( - reads: [PublicDataRead; NUM_READS], - writes: [OverridablePublicDataWrite; NUM_WRITES], - leaf_data: [OverridablePublicDataTreeLeaf; NUM_LEAVES], -) -> PublicDataReadRequestHints { - let mut read_request_statuses = [ReadRequestStatus::empty(); NUM_READS]; - let mut pending_read_hints = [ReadIndexHint::nada(NUM_READS); NUM_READS]; - let mut leaf_data_read_hints = [ReadIndexHint::nada(NUM_READS); NUM_READS]; - let mut num_pending_reads = 0; - let mut num_leaf_data_reads = 0; - for i in 0..reads.len() { - let read = reads[i]; - if read.counter != 0 { - let write_index = find_index_hint( - writes, - |w: OverridablePublicDataWrite| { - (w.inner().leaf_slot == read.leaf_slot) - & (read.counter > w.counter()) - & ((read.counter < w.override_counter) | (w.override_counter == 0)) - }, - ); - if write_index != writes.len() { - pending_read_hints[num_pending_reads] = - ReadIndexHint { read_request_index: i, value_index: write_index }; - read_request_statuses[i] = ReadRequestStatus::pending(num_pending_reads); - num_pending_reads += 1; - } else { - let leaf_data_index = find_index_hint( - leaf_data, - |d: OverridablePublicDataTreeLeaf| d.leaf.slot == read.leaf_slot, - ); - assert( - leaf_data_index != leaf_data.len(), - "cannot find a public data leaf or a pending write for the read request", - ); - leaf_data_read_hints[num_leaf_data_reads] = - ReadIndexHint { read_request_index: i, value_index: leaf_data_index }; - read_request_statuses[i] = ReadRequestStatus::settled(num_leaf_data_reads); - num_leaf_data_reads += 1; - } - } - } - - PublicDataReadRequestHints { read_request_statuses, pending_read_hints, leaf_data_read_hints } -} diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/public_validation_request_processor.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/public_validation_request_processor.nr deleted file mode 100644 index 103a358d2871..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/public_validation_request_processor.nr +++ /dev/null @@ -1,173 +0,0 @@ -use crate::{ - nullifier_non_existent_read_request_reset::NullifierNonExistentReadRequestHints, - nullifier_read_request_reset::NullifierReadRequestHints, - public_data_read_request_hints::PublicDataReadRequestHints, - reset::{ - mutable_data_read_request::reset_mutable_data_read_requests, - non_existent_read_request::reset_non_existent_read_requests, - read_request::verify_reset_read_requests, - tree_leaf_read_request::{TreeLeafReadRequestHint, validate_tree_leaf_read_requests}, - }, -}; -use dep::types::{ - abis::{ - kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, nullifier::Nullifier, - public_data_write::OverridablePublicDataWrite, read_request::ScopedReadRequest, - validation_requests::PublicValidationRequests, - }, - constants::{ - L1_TO_L2_MSG_TREE_HEIGHT, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_NULLIFIERS_PER_TX, MAX_PUBLIC_DATA_READS_PER_TX, NOTE_HASH_TREE_HEIGHT, - }, - data::OverridablePublicDataTreeLeaf, - hash::compute_siloed_nullifier, - partial_state_reference::PartialStateReference, - traits::is_empty, - utils::arrays::{ - array_to_bounded_vec, assert_combined_array, assert_sorted_array, combine_arrays, - }, -}; - -pub struct PublicValidationRequestProcessor { - validation_requests: PublicValidationRequests, - note_hash_read_request_hints: [TreeLeafReadRequestHint; MAX_NOTE_HASH_READ_REQUESTS_PER_TX], - note_hash_tree_root: Field, - pending_nullifiers: [Nullifier; MAX_NULLIFIERS_PER_TX], - nullifier_read_request_hints: NullifierReadRequestHints, - nullifier_non_existent_read_request_hints: NullifierNonExistentReadRequestHints, - nullifier_tree_root: Field, - l1_to_l2_msg_read_request_hints: [TreeLeafReadRequestHint; MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX], - l1_to_l2_msg_tree_root: Field, - pending_public_data_writes: [OverridablePublicDataWrite; NUN_PUBLIC_DATA_WRITES], - public_data_leaves: [OverridablePublicDataTreeLeaf; NUM_PUBLIC_DATA_LEAVES], - public_data_read_request_hints: PublicDataReadRequestHints, -} - -impl PublicValidationRequestProcessor { - pub fn new( - public_inputs: PublicKernelCircuitPublicInputs, - start_state: PartialStateReference, - note_hash_read_request_hints: [TreeLeafReadRequestHint; MAX_NOTE_HASH_READ_REQUESTS_PER_TX], - nullifier_read_request_hints: NullifierReadRequestHints, - nullifier_non_existent_read_request_hints: NullifierNonExistentReadRequestHints, - l1_to_l2_msg_read_request_hints: [TreeLeafReadRequestHint; MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX], - pending_public_data_writes: [OverridablePublicDataWrite; NUN_PUBLIC_DATA_WRITES], - public_data_leaves: [OverridablePublicDataTreeLeaf; NUM_PUBLIC_DATA_LEAVES], - public_data_read_request_hints: PublicDataReadRequestHints, - ) -> Self { - let non_revertible_nullifiers = public_inputs.end_non_revertible.nullifiers; - let revertible_nullifiers = public_inputs.end.nullifiers; - let pending_nullifiers = - unsafe { combine_arrays(non_revertible_nullifiers, revertible_nullifiers) }; - assert_combined_array( - non_revertible_nullifiers, - revertible_nullifiers, - pending_nullifiers, - ); - - PublicValidationRequestProcessor { - validation_requests: public_inputs.validation_requests, - note_hash_read_request_hints, - note_hash_tree_root: start_state.note_hash_tree.root, - pending_nullifiers, - nullifier_read_request_hints, - nullifier_non_existent_read_request_hints, - nullifier_tree_root: start_state.nullifier_tree.root, - l1_to_l2_msg_read_request_hints, - l1_to_l2_msg_tree_root: public_inputs - .constants - .historical_header - .state - .l1_to_l2_message_tree - .root, - pending_public_data_writes, - public_data_leaves, - public_data_read_request_hints, - } - } - - pub fn validate(self) { - self.validate_note_hash_read_requests(); - self.validate_nullifier_read_requests(); - self.validate_nullifier_non_existent_read_requests(); - self.validate_l1_to_l2_msg_read_requests(); - self.validate_public_data_read_requests(); - } - - fn validate_note_hash_read_requests(self) { - validate_tree_leaf_read_requests( - self.validation_requests.note_hash_read_requests, - self.note_hash_read_request_hints, - self.note_hash_tree_root, - ); - } - - fn validate_nullifier_read_requests(self) { - let requests = self.validation_requests.nullifier_read_requests; - let hints = self.nullifier_read_request_hints; - let unverified_nullifier_read_requests = - [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX]; // All nullifier read requests must be verified. - verify_reset_read_requests( - requests, - self.pending_nullifiers, - hints.read_request_statuses, - hints.pending_read_hints, - hints.settled_read_hints, - self.nullifier_tree_root, - unverified_nullifier_read_requests, - ); - } - - fn validate_nullifier_non_existent_read_requests(self) { - // The values of the read requests here need to be siloed. - // Notice that it's not the case for regular read requests, which can be run between two kernel iterations, and will to be verified against unsiloed pending values. - let mut read_requests = self.validation_requests.nullifier_non_existent_read_requests; - for i in 0..read_requests.len() { - let read_request = read_requests[i]; - if !is_empty(read_request) { - read_requests[i].read_request.value = - compute_siloed_nullifier(read_request.contract_address, read_request.value()); - } - } - - let hints = self.nullifier_non_existent_read_request_hints; - - assert_sorted_array( - self.pending_nullifiers, - hints.sorted_pending_values, - hints.sorted_pending_value_index_hints, - |a: Nullifier, b: Nullifier| a.value.lt(b.value), - ); - let sorted_pending_nullifiers = array_to_bounded_vec(hints.sorted_pending_values); - - reset_non_existent_read_requests( - read_requests, - hints.non_membership_hints, - self.nullifier_tree_root, - sorted_pending_nullifiers, - hints.next_pending_value_indices, - ); - } - - fn validate_l1_to_l2_msg_read_requests(self) { - validate_tree_leaf_read_requests( - self.validation_requests.l1_to_l2_msg_read_requests, - self.l1_to_l2_msg_read_request_hints, - self.l1_to_l2_msg_tree_root, - ); - } - - fn validate_public_data_read_requests(self) { - let hints = self.public_data_read_request_hints; - - reset_mutable_data_read_requests( - self.validation_requests.public_data_reads, - hints.read_request_statuses, - self.pending_public_data_writes, - self.public_data_leaves, - hints.pending_read_hints, - hints.leaf_data_read_hints, - ); - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mod.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mod.nr index dfd73f62e64b..e1ac985daf88 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mod.nr @@ -1,6 +1,3 @@ -pub mod mutable_data_read_request; -pub mod non_existent_read_request; pub mod read_request; pub mod transient_data; -pub mod tree_leaf_read_request; pub mod key_validation_hint; diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mutable_data_read_request.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mutable_data_read_request.nr deleted file mode 100644 index 87027b7e18f4..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/mutable_data_read_request.nr +++ /dev/null @@ -1,526 +0,0 @@ -use crate::reset::read_request::{ReadRequestState, ReadRequestStatus}; -use dep::types::abis::side_effect::{Ordered, Overridable, Readable}; - -pub struct ReadIndexHint { - read_request_index: u32, - value_index: u32, -} - -impl ReadIndexHint { - pub fn nada(read_request_len: u32) -> Self { - ReadIndexHint { read_request_index: read_request_len, value_index: 0 } - } -} - -fn validate_pending_read_requests( - read_requests: [R; READ_REQUEST_LEN], - pending_values: [V; PENDING_VALUE_LEN], - index_hints: [ReadIndexHint; NUM_HINTS], -) -where - R: Ordered, - V: Readable + Ordered + Overridable, -{ - for i in 0..index_hints.len() { - let index_hint = index_hints[i]; - let read_request_index = index_hint.read_request_index; - if read_request_index != READ_REQUEST_LEN { - let read_request = read_requests[read_request_index]; - let pending_value = pending_values[index_hint.value_index]; - pending_value.assert_match_read_request(read_request); - assert( - read_request.counter() > pending_value.counter(), - "Read request counter must be greater than the counter of the data write", - ); - assert( - (read_request.counter() < pending_value.override_counter()) - | (pending_value.override_counter() == 0), - "Read request counter must be less than the counter of the next data write", - ); - } - } -} - -fn validate_leaf_data_read_requests( - read_requests: [R; READ_REQUEST_LEN], - leaf_data: [L; LEAF_DATA_LEN], - index_hints: [ReadIndexHint; NUM_HINTS], -) -where - R: Ordered, - L: Readable + Overridable, -{ - for i in 0..index_hints.len() { - let index_hint = index_hints[i]; - let read_request_index = index_hint.read_request_index; - if read_request_index != READ_REQUEST_LEN { - let read_request = read_requests[read_request_index]; - let data = leaf_data[index_hint.value_index]; - data.assert_match_read_request(read_request); - assert( - (read_request.counter() < data.override_counter()) | (data.override_counter() == 0), - "Hinted leaf is overridden before the read request", - ); - } - } -} - -fn ensure_all_read_requests_are_verified( - read_requests: [R; READ_REQUEST_LEN], - read_request_statuses: [ReadRequestStatus; READ_REQUEST_LEN], - pending_read_hints: [ReadIndexHint; NUM_PENDING_READS], - leaf_data_read_hints: [ReadIndexHint; NUM_LEAF_DATA_READS], -) -where - R: Ordered, -{ - for i in 0..READ_REQUEST_LEN { - let read_request = read_requests[i]; - if read_request.counter() != 0 { - let status = read_request_statuses[i]; - if status.state == ReadRequestState.PENDING { - assert( - pending_read_hints[status.hint_index].read_request_index == i, - "Hinted pending read request does not match status", - ); - } else { - assert( - leaf_data_read_hints[status.hint_index].read_request_index == i, - "Hinted settled read request does not match status", - ); - } - } - } -} - -pub fn reset_mutable_data_read_requests( - read_requests: [R; READ_REQUEST_LEN], - read_request_statuses: [ReadRequestStatus; READ_REQUEST_LEN], - pending_values: [V; PENDING_VALUE_LEN], - leaf_data: [L; NUM_LEAF_DATA_HINTS], - pending_read_hints: [ReadIndexHint; NUM_PENDING_READS], - leaf_data_read_hints: [ReadIndexHint; NUM_LEAF_DATA_READS], -) -where - R: Ordered, - V: Readable + Ordered + Overridable, - L: Readable + Overridable, -{ - validate_pending_read_requests(read_requests, pending_values, pending_read_hints); - - validate_leaf_data_read_requests(read_requests, leaf_data, leaf_data_read_hints); - - ensure_all_read_requests_are_verified( - read_requests, - read_request_statuses, - pending_read_hints, - leaf_data_read_hints, - ); -} - -mod tests { - use crate::reset::{ - mutable_data_read_request::{ - ensure_all_read_requests_are_verified, ReadIndexHint, reset_mutable_data_read_requests, - validate_leaf_data_read_requests, validate_pending_read_requests, - }, - read_request::{ReadRequestState, ReadRequestStatus}, - }; - use dep::types::{ - abis::{ - public_data_read::PublicDataRead, - public_data_update_request::PublicDataUpdateRequest, - public_data_write::OverridablePublicDataWrite, - side_effect::{Overridable, Readable}, - }, - tests::utils::pad_end, - traits::Empty, - }; - - struct TestLeafData { - leaf_index: Field, - value: Field, - override_counter: u32, - } - - impl Empty for TestLeafData { - fn empty() -> Self { - TestLeafData { leaf_index: 0, value: 0, override_counter: 0 } - } - } - - impl Overridable for TestLeafData { - fn override_counter(self) -> u32 { - self.override_counter - } - } - - impl Readable for TestLeafData { - fn assert_match_read_request(self, read_request: PublicDataRead) { - assert_eq( - self.leaf_index, - read_request.leaf_slot, - "leaf_index in TestLeafData does not match", - ); - assert_eq(self.value, read_request.value, "value in TestLeafData does not match"); - } - } - - global READ_REQUEST_LEN = 10; - - struct TestBuilder { - read_requests: [PublicDataRead; READ_REQUEST_LEN], - read_request_statuses: [ReadRequestStatus; READ_REQUEST_LEN], - data_writes: [OverridablePublicDataWrite; 6], - leaf_data: [TestLeafData; 12], - pending_read_hints: [ReadIndexHint; 5], - leaf_data_read_hints: [ReadIndexHint; 4], - num_pending_reads: u32, - num_leaf_data_reads: u32, - counter: u32, - } - - impl TestBuilder { - pub fn new() -> TestBuilder { - let read_requests = [PublicDataRead::empty(); READ_REQUEST_LEN]; - let read_request_statuses = [ReadRequestStatus::empty(); READ_REQUEST_LEN]; - - let leaf_data = pad_end( - [ - TestLeafData { leaf_index: 44, value: 0, override_counter: 40 }, - TestLeafData { leaf_index: 77, value: 700, override_counter: 0 }, - TestLeafData { leaf_index: 11, value: 0, override_counter: 20 }, - TestLeafData { leaf_index: 33, value: 300, override_counter: 30 }, - TestLeafData { leaf_index: 66, value: 600, override_counter: 0 }, - TestLeafData { leaf_index: 22, value: 200, override_counter: 10 }, - TestLeafData { leaf_index: 55, value: 500, override_counter: 0 }, - ], - TestLeafData::empty(), - ); - - let data_writes = pad_end( - [ - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 22, - new_value: 201, - counter: 10, - }, - override_counter: 40, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 11, - new_value: 100, - counter: 20, - }, - override_counter: 0, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 33, - new_value: 301, - counter: 30, - }, - override_counter: 0, - }, - OverridablePublicDataWrite { - write: PublicDataUpdateRequest { - leaf_slot: 22, - new_value: 202, - counter: 40, - }, - override_counter: 0, - }, - ], - OverridablePublicDataWrite::empty(), - ); - - let pending_read_hints = pad_end([], ReadIndexHint::nada(READ_REQUEST_LEN)); - - let leaf_data_read_hints = pad_end([], ReadIndexHint::nada(READ_REQUEST_LEN)); - - TestBuilder { - read_requests, - read_request_statuses, - leaf_data, - data_writes, - pending_read_hints, - leaf_data_read_hints, - num_pending_reads: 0, - num_leaf_data_reads: 0, - counter: 50, - } - } - - pub fn add_pending_read(&mut self, data_write_index: u32) { - let write = self.data_writes[data_write_index].write; - let read_request_index = self.num_pending_reads + self.num_leaf_data_reads; - self.read_requests[read_request_index] = PublicDataRead { - leaf_slot: write.leaf_slot, - value: write.new_value, - counter: self.counter, - }; - self.pending_read_hints[self.num_pending_reads] = - ReadIndexHint { read_request_index, value_index: data_write_index }; - self.read_request_statuses[read_request_index] = - ReadRequestStatus::pending(self.num_pending_reads); - self.num_pending_reads += 1; - self.counter += 1; - } - - pub fn add_leaf_data_read(&mut self, data_hint_index: u32) { - let data_hint = self.leaf_data[data_hint_index]; - let read_request_index = self.num_pending_reads + self.num_leaf_data_reads; - self.read_requests[read_request_index] = PublicDataRead { - leaf_slot: data_hint.leaf_index, - value: data_hint.value, - counter: self.counter, - }; - self.leaf_data_read_hints[self.num_leaf_data_reads] = - ReadIndexHint { read_request_index, value_index: data_hint_index }; - self.read_request_statuses[read_request_index] = - ReadRequestStatus::settled(self.num_leaf_data_reads); - self.num_leaf_data_reads += 1; - self.counter += 1; - } - - pub fn validate_pending_read_requests(self) { - validate_pending_read_requests( - self.read_requests, - self.data_writes, - self.pending_read_hints, - ); - } - - pub fn validate_leaf_data_read_requests(self) { - validate_leaf_data_read_requests( - self.read_requests, - self.leaf_data, - self.leaf_data_read_hints, - ) - } - - pub fn ensure_all_read_requests_are_verified(self) { - ensure_all_read_requests_are_verified( - self.read_requests, - self.read_request_statuses, - self.pending_read_hints, - self.leaf_data_read_hints, - ) - } - - pub fn reset(self) { - reset_mutable_data_read_requests( - self.read_requests, - self.read_request_statuses, - self.data_writes, - self.leaf_data, - self.pending_read_hints, - self.leaf_data_read_hints, - ); - } - } - - #[test] - fn reset_pending_reads_succeeds() { - let mut builder = TestBuilder::new(); - - builder.add_pending_read(1); - builder.add_pending_read(2); - builder.add_pending_read(3); - - builder.validate_pending_read_requests(); - } - - #[test] - fn reset_pending_reads_repeated_values() { - let mut builder = TestBuilder::new(); - - builder.add_pending_read(2); - builder.add_pending_read(2); - builder.add_pending_read(2); - - builder.validate_pending_read_requests(); - } - - #[test(should_fail_with = "Read request counter must be less than the counter of the next data write")] - fn reset_pending_reads_overriden_value_fails() { - let mut builder = TestBuilder::new(); - - // 0th write is overriden by the 3rd write. - builder.add_pending_read(0); - - builder.validate_pending_read_requests(); - } - - #[test] - fn reset_pending_reads_overriden_value_before_next_succeeds() { - let mut builder = TestBuilder::new(); - - // 0th write is overriden by the 3rd write. - builder.add_pending_read(0); - - // Tweak the counter of the read request to be before the next value. - builder.read_requests[0].counter = builder.data_writes[3].write.counter - 1; - - builder.validate_pending_read_requests(); - } - - #[test(should_fail_with = "leaf_slot in OverridablePublicDataWrite does not match read request")] - fn reset_pending_reads_wrong_slot_fails() { - let mut builder = TestBuilder::new(); - - builder.add_pending_read(2); - builder.read_requests[0].leaf_slot += 1; - - builder.validate_pending_read_requests(); - } - - #[test(should_fail_with = "value in OverridablePublicDataWrite does not match read request")] - fn reset_pending_reads_wrong_value_fails() { - let mut builder = TestBuilder::new(); - - builder.add_pending_read(2); - builder.read_requests[0].value += 1; - - builder.validate_pending_read_requests(); - } - - #[test(should_fail_with = "Read request counter must be greater than the counter of the data write")] - fn reset_pending_reads_value_write_after_fails() { - let mut builder = TestBuilder::new(); - - builder.add_pending_read(2); - builder.read_requests[0].counter = builder.data_writes[2].write.counter - 1; - - builder.validate_pending_read_requests(); - } - - #[test] - fn reset_leaf_data_reads_succeeds() { - let mut builder = TestBuilder::new(); - - builder.add_leaf_data_read(1); - builder.add_leaf_data_read(4); - builder.add_leaf_data_read(6); - - builder.validate_leaf_data_read_requests(); - } - - #[test] - fn reset_leaf_data_reads_repeated_values() { - let mut builder = TestBuilder::new(); - - builder.add_leaf_data_read(4); - builder.add_leaf_data_read(4); - builder.add_leaf_data_read(4); - - builder.validate_leaf_data_read_requests(); - } - - #[test(should_fail_with = "Hinted leaf is overridden before the read request")] - fn reset_leaf_data_reads_overriden_value_fails() { - let mut builder = TestBuilder::new(); - - // 2nd leaf is overriden by a pending write. - builder.add_leaf_data_read(2); - - builder.validate_leaf_data_read_requests(); - } - - #[test] - fn reset_leaf_data_reads_overriden_value_before_next_succeeds() { - let mut builder = TestBuilder::new(); - - // 2nd leaf is overriden by a pending write. - builder.add_leaf_data_read(2); - - // Tweak the counter of the read request to be before the pending write. - builder.read_requests[0].counter = builder.leaf_data[2].override_counter - 1; - - builder.validate_leaf_data_read_requests(); - } - - #[test(should_fail_with = "leaf_index in TestLeafData does not match")] - fn reset_leaf_reads_wrong_slot_fails() { - let mut builder = TestBuilder::new(); - - builder.add_leaf_data_read(4); - builder.read_requests[0].leaf_slot += 1; - - builder.validate_leaf_data_read_requests(); - } - - #[test(should_fail_with = "value in TestLeafData does not match")] - fn reset_leaf_reads_wrong_value_fails() { - let mut builder = TestBuilder::new(); - - builder.add_leaf_data_read(4); - builder.read_requests[0].value += 1; - - builder.validate_leaf_data_read_requests(); - } - - #[test] - fn ensure_all_read_requests_are_verified_succeeds() { - let mut builder = TestBuilder::new(); - - builder.add_leaf_data_read(4); - builder.add_pending_read(2); - builder.add_pending_read(1); - builder.add_leaf_data_read(1); - - builder.ensure_all_read_requests_are_verified(); - } - - #[test(should_fail_with = "Hinted pending read request does not match status")] - fn ensure_all_read_requests_are_verified_wrong_pending_hint_index_fails() { - let mut builder = TestBuilder::new(); - - builder.add_pending_read(2); - builder.read_request_statuses[0].hint_index += 1; - - builder.ensure_all_read_requests_are_verified(); - } - - #[test(should_fail_with = "Hinted settled read request does not match status")] - fn ensure_all_read_requests_are_verified_wrong_leaf_hint_index_fails() { - let mut builder = TestBuilder::new(); - - builder.add_leaf_data_read(4); - builder.read_request_statuses[0].hint_index += 1; - - builder.ensure_all_read_requests_are_verified(); - } - - #[test(should_fail_with = "Hinted settled read request does not match status")] - fn ensure_all_read_requests_are_verified_wrong_status_fails() { - let mut builder = TestBuilder::new(); - - builder.add_pending_read(2); - builder.read_request_statuses[0].state = ReadRequestState.NADA; - - builder.ensure_all_read_requests_are_verified(); - } - - #[test] - fn reset_mutable_data_read_requests_succeeds() { - let mut builder = TestBuilder::new(); - - builder.add_pending_read(1); - builder.add_leaf_data_read(4); - builder.add_pending_read(2); - builder.add_leaf_data_read(6); - builder.add_leaf_data_read(6); - builder.add_pending_read(1); - - builder.reset(); - } - - #[test] - fn reset_mutable_data_read_requests_no_requests_succeeds() { - let builder = TestBuilder::new(); - builder.reset(); - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/non_existent_read_request.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/non_existent_read_request.nr deleted file mode 100644 index 3cd22aa7443f..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/non_existent_read_request.nr +++ /dev/null @@ -1,387 +0,0 @@ -use dep::types::{ - abis::{read_request::ScopedReadRequest, side_effect::OrderedValue}, - merkle_tree::{assert_check_non_membership, IndexedTreeLeafPreimage, MembershipWitness}, - traits::is_empty, -}; - -trait NonMembershipHint -where - LEAF_PREIMAGE: IndexedTreeLeafPreimage, -{ - fn low_leaf_preimage(self) -> LEAF_PREIMAGE; - fn membership_witness(self) -> MembershipWitness; -} - -fn check_no_matching_pending_value( - read_request: ScopedReadRequest, - sorted_pending_values: BoundedVec, - next_value_index: u32, -) -> bool -where - T: OrderedValue, -{ - if next_value_index == sorted_pending_values.len() { - let highest_value = - sorted_pending_values.get_unchecked(sorted_pending_values.len() - 1).value(); - highest_value.lt(read_request.value()) - } else { - let next_value = sorted_pending_values.get_unchecked(next_value_index).value(); - let is_less_than_next = read_request.value().lt(next_value); - let is_greater_than_prev = if next_value_index == 0 { - true - } else { - let prev_value = sorted_pending_values.get_unchecked(next_value_index - 1).value(); - prev_value.lt(read_request.value()) - }; - is_less_than_next & is_greater_than_prev - } -} - -fn check_is_read_before_pending_value( - read_request: ScopedReadRequest, - sorted_pending_values: BoundedVec, - next_value_index: u32, -) -> bool -where - T: OrderedValue, -{ - if next_value_index == sorted_pending_values.len() { - false - } else { - let pending = sorted_pending_values.get_unchecked(next_value_index); - if pending.value() == read_request.value() { - assert(read_request.counter() < pending.counter(), "Value exists in pending set"); - true - } else { - false - } - } -} - -// Unlike regular read requests, which can be reset at any time between two function executions. -// Non existent read requests can only be verified at the end, after all pending values are present. -// The values in read_requests and in sorted_pending_values should've been siloed before calling this. -pub fn reset_non_existent_read_requests( - siloed_read_requests: [ScopedReadRequest; N], - non_membership_hints: [NON_MEMBERSHIP_HINT; N], - tree_root: Field, - sorted_pending_values: BoundedVec, - next_pending_value_indices: [u32; N], -) -where - T: OrderedValue, - NON_MEMBERSHIP_HINT: NonMembershipHint, - LEAF_PREIMAGE: IndexedTreeLeafPreimage, -{ - for i in 0..siloed_read_requests.len() { - let read_request = siloed_read_requests[i]; - if !is_empty(read_request) { - // Verify that it's not in the tree. - let hint = non_membership_hints[i]; - assert_check_non_membership( - read_request.value(), - hint.low_leaf_preimage(), - hint.membership_witness(), - tree_root, - ); - - // Verify that its value is either not in the pending set, or is created after the read. - let next_value_index = next_pending_value_indices[i]; - assert( - next_value_index <= sorted_pending_values.len(), - "Next pending value index out of bounds", - ); - let no_matching_value = check_no_matching_pending_value( - read_request, - sorted_pending_values, - next_value_index, - ); - let is_read_before_value = check_is_read_before_pending_value( - read_request, - sorted_pending_values, - next_value_index, - ); - assert(no_matching_value | is_read_before_value, "Invalid next pending value index"); - } - } -} - -mod tests { - use crate::reset::non_existent_read_request::{ - NonMembershipHint, reset_non_existent_read_requests, - }; - - use dep::types::{ - abis::{read_request::ReadRequest, side_effect::OrderedValue}, - address::AztecAddress, - merkle_tree::{leaf_preimage::IndexedTreeLeafPreimage, membership::MembershipWitness}, - tests::merkle_tree_utils::NonEmptyMerkleTree, - }; - - struct TestValue { - value: Field, - counter: u32, - } - - impl OrderedValue for TestValue { - fn value(self) -> Field { - self.value - } - fn counter(self) -> u32 { - self.counter - } - } - - impl TestValue { - fn empty() -> Self { - TestValue { value: 0, counter: 0 } - } - } - - struct TestLeafPreimage { - value: Field, - next_value: Field, - } - - impl IndexedTreeLeafPreimage for TestLeafPreimage { - fn get_key(self) -> Field { - self.value - } - - fn get_next_key(self) -> Field { - self.next_value - } - - fn as_leaf(self) -> Field { - self.value * 100 - } - } - - struct TestNonMembershipHint { - low_leaf_preimage: TestLeafPreimage, - membership_witness: MembershipWitness<3>, - } - - impl NonMembershipHint<3, TestLeafPreimage> for TestNonMembershipHint { - fn low_leaf_preimage(self) -> TestLeafPreimage { - self.low_leaf_preimage - } - - fn membership_witness(self) -> MembershipWitness<3> { - self.membership_witness - } - } - - global sorted_pending_values = BoundedVec { - storage: [ - TestValue { value: 5, counter: 17 }, - TestValue { value: 15, counter: 8 }, - TestValue { value: 25, counter: 11 }, - TestValue::empty(), - TestValue::empty(), - ], - len: 3, - }; - - global leaf_preimages = [ - TestLeafPreimage { value: 0, next_value: 10 }, - TestLeafPreimage { value: 20, next_value: 30 }, - TestLeafPreimage { value: 30, next_value: 0 }, - TestLeafPreimage { value: 10, next_value: 20 }, - ]; - - fn build_tree() -> NonEmptyMerkleTree<4, 3, 1, 2> { - NonEmptyMerkleTree::new( - leaf_preimages.map(|leaf_preimage: TestLeafPreimage| leaf_preimage.as_leaf()), - [0; 3], - [0; 1], - [0; 2], - ) - } - - fn get_non_membership_hints( - leaf_indices: [Field; N], - ) -> ([TestNonMembershipHint; N], Field) { - let tree = build_tree(); - let hints = leaf_indices.map(|leaf_index| { - TestNonMembershipHint { - low_leaf_preimage: leaf_preimages[leaf_index], - membership_witness: MembershipWitness { - leaf_index, - sibling_path: tree.get_sibling_path(leaf_index as u32), - }, - } - }); - let tree_root = tree.get_root(); - (hints, tree_root) - } - - #[test] - fn test_reset_non_existent_read_requests_in_range() { - let read_requests = [ - ReadRequest { value: 11, counter: 50 }.scope(AztecAddress::zero()), - ReadRequest { value: 22, counter: 51 }.scope(AztecAddress::zero()), - ReadRequest { value: 6, counter: 52 }.scope(AztecAddress::zero()), - ]; - let (non_membership_hints, root) = get_non_membership_hints([3, 1, 0]); - let next_pending_value_indices = [1, 2, 1]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test] - fn test_reset_non_existent_read_requests_less_than_min() { - let read_requests = [ - ReadRequest { value: 3, counter: 50 }.scope(AztecAddress::zero()), - ReadRequest { value: 2, counter: 51 }.scope(AztecAddress::zero()), - ]; - let (non_membership_hints, root) = get_non_membership_hints([0, 0]); - let next_pending_value_indices = [0, 0]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test] - fn test_reset_non_existent_read_requests_greater_than_max() { - let read_requests = [ - ReadRequest { value: 35, counter: 50 }.scope(AztecAddress::zero()), - ReadRequest { value: 31, counter: 51 }.scope(AztecAddress::zero()), - ]; - let (non_membership_hints, root) = get_non_membership_hints([2, 2]); - let next_pending_value_indices = [3, 3]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test] - fn test_reset_non_existent_read_requests_read_before_pending_emitted() { - let read_requests = [ - ReadRequest { value: 25, counter: 10 }.scope(AztecAddress::zero()), - ReadRequest { value: 5, counter: 11 }.scope(AztecAddress::zero()), - ]; - let (non_membership_hints, root) = get_non_membership_hints([1, 0]); - let next_pending_value_indices = [2, 0]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test(should_fail_with = "Low leaf does not exist")] - fn test_reset_non_existent_read_requests_invalid_preimage_failed() { - let read_requests = [ReadRequest { value: 10, counter: 50 }.scope(AztecAddress::zero())]; - let (non_membership_hints, root) = get_non_membership_hints([3]); - let mut hint = non_membership_hints[0]; - hint.low_leaf_preimage = TestLeafPreimage { value: 9, next_value: 20 }; - let next_pending_value_indices = [1]; - reset_non_existent_read_requests( - read_requests, - [hint], - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test(should_fail_with = "Key is not greater than the low leaf")] - fn test_reset_non_existent_read_requests_read_settled_failed() { - let read_requests = [ReadRequest { value: 10, counter: 50 }.scope(AztecAddress::zero())]; - let (non_membership_hints, root) = get_non_membership_hints([3]); - let next_pending_value_indices = [1]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test(should_fail_with = "Key is not less than the next leaf")] - fn test_reset_non_existent_read_requests_invalid_non_membership_hint_failed() { - let read_requests = [ReadRequest { value: 10, counter: 50 }.scope(AztecAddress::zero())]; - let (non_membership_hints, root) = get_non_membership_hints([0]); - let next_pending_value_indices = [1]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test(should_fail_with = "Value exists in pending set")] - fn test_reset_non_existent_read_requests_read_pending_value_failed() { - let read_requests = [ReadRequest { value: 25, counter: 50 }.scope(AztecAddress::zero())]; - let (non_membership_hints, root) = get_non_membership_hints([1]); - let next_pending_value_indices = [2]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test(should_fail_with = "Invalid next pending value index")] - fn test_reset_non_existent_read_requests_wrong_next_pending_index_failed() { - let read_requests = [ReadRequest { value: 21, counter: 50 }.scope(AztecAddress::zero())]; - let (non_membership_hints, root) = get_non_membership_hints([1]); - let next_pending_value_indices = [1]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test(should_fail_with = "Invalid next pending value index")] - fn test_reset_non_existent_read_requests_wrong_max_next_pending_index_failed() { - let read_requests = [ReadRequest { value: 21, counter: 50 }.scope(AztecAddress::zero())]; - let (non_membership_hints, root) = get_non_membership_hints([1]); - let next_pending_value_indices = [3]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } - - #[test(should_fail_with = "Next pending value index out of bounds")] - fn test_reset_non_existent_read_requests_overflown_index_failed() { - let read_requests = [ReadRequest { value: 21, counter: 50 }.scope(AztecAddress::zero())]; - let (non_membership_hints, root) = get_non_membership_hints([1]); - let next_pending_value_indices = [4]; - reset_non_existent_read_requests( - read_requests, - non_membership_hints, - root, - sorted_pending_values, - next_pending_value_indices, - ); - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/read_request.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/read_request.nr index 96801ae12684..ec5271424ead 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/read_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/read_request.nr @@ -1,4 +1,3 @@ -// This will be moved to a separate Read Request Reset Circuit. use dep::types::{ abis::{read_request::ScopedReadRequest, side_effect::Readable}, merkle_tree::{assert_check_membership, LeafPreimage, MembershipWitness}, diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/tree_leaf_read_request.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/tree_leaf_read_request.nr deleted file mode 100644 index 9798dbdb9481..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/reset/tree_leaf_read_request.nr +++ /dev/null @@ -1,26 +0,0 @@ -use dep::types::{ - abis::tree_leaf_read_request::TreeLeafReadRequest, merkle_tree::assert_check_membership, - traits::is_empty, -}; - -pub struct TreeLeafReadRequestHint { - sibling_path: [Field; N], -} - -pub fn validate_tree_leaf_read_requests( - read_requests: [TreeLeafReadRequest; READ_REQUEST_LEN], - hints: [TreeLeafReadRequestHint; READ_REQUEST_LEN], - tree_root: Field, -) { - for i in 0..READ_REQUEST_LEN { - let read_request = read_requests[i]; - if !is_empty(read_request) { - assert_check_membership( - read_request.value, - read_request.leaf_index, - hints[i].sibling_path, - tree_root, - ); - } - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/mod.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/mod.nr index c590c5806c6d..d7d473cb36ec 100644 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/mod.nr @@ -1,5 +1,4 @@ pub mod note_hash_read_request_hints_builder; -pub mod nullifier_non_existent_read_request_hints_builder; pub mod nullifier_read_request_hints_builder; pub use note_hash_read_request_hints_builder::NoteHashReadRequestHintsBuilder; diff --git a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_non_existent_read_request_hints_builder.nr b/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_non_existent_read_request_hints_builder.nr deleted file mode 100644 index bd3e55294ac1..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/reset-kernel-lib/src/tests/nullifier_non_existent_read_request_hints_builder.nr +++ /dev/null @@ -1,86 +0,0 @@ -use crate::nullifier_non_existent_read_request_reset::{ - NullifierNonExistentReadRequestHints, NullifierNonMembershipHint, -}; -use dep::types::{ - abis::{nullifier::Nullifier, nullifier_leaf_preimage::NullifierLeafPreimage}, - constants::{ - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, - NULLIFIER_SUBTREE_HEIGHT, NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_TREE_HEIGHT, - }, - merkle_tree::MembershipWitness, - tests::merkle_tree_utils::NonEmptyMerkleTree, - utils::arrays::{find_index_hint, get_sorted_result}, -}; - -pub struct NullifierNonExistentReadRequestHintsBuilder { - nullifier_tree: NonEmptyMerkleTree, - non_membership_hints: BoundedVec, - read_values: BoundedVec, - pending_nullifiers: [Nullifier; MAX_NULLIFIERS_PER_TX], -} - -impl NullifierNonExistentReadRequestHintsBuilder { - pub fn new() -> Self { - NullifierNonExistentReadRequestHintsBuilder { - nullifier_tree: NonEmptyMerkleTree::empty(), - non_membership_hints: BoundedVec::new(), - read_values: BoundedVec::new(), - pending_nullifiers: [Nullifier::empty(); MAX_NULLIFIERS_PER_TX], - } - } - - pub fn set_nullifier_tree( - &mut self, - tree: NonEmptyMerkleTree, - ) { - self.nullifier_tree = tree; - } - - pub fn set_nullifiers(&mut self, nullifiers: [Nullifier; MAX_NULLIFIERS_PER_TX]) { - self.pending_nullifiers = nullifiers; - } - - pub fn add_value_read(&mut self, siloed_value: Field) { - self.read_values.push(siloed_value); - - // There are only two pre-existing nullifiers in the tree: [0, 100], generated in public_kernel_tail::tests. - // Assuming the siloed_value is always greater than 100. - let hint = NullifierNonMembershipHint { - low_leaf_preimage: NullifierLeafPreimage { - nullifier: 100, - next_nullifier: 0, - next_index: 0, - }, - membership_witness: MembershipWitness { - leaf_index: 1, - sibling_path: self.nullifier_tree.get_sibling_path(1), - }, - }; - self.non_membership_hints.push(hint); - } - - pub unconstrained fn to_hints(self) -> NullifierNonExistentReadRequestHints { - let sorted_result = get_sorted_result( - self.pending_nullifiers, - |a: Nullifier, b: Nullifier| (b.value == 0) | ((a.value != 0) & a.value.lt(b.value)), - ); - let sorted_pending_values = sorted_result.sorted_array; - let sorted_pending_value_index_hints = sorted_result.sorted_index_hints; - - let mut next_pending_value_indices = [0; MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX]; - for i in 0..MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX { - if i < self.read_values.len() { - let value = self.read_values.get_unchecked(i); - next_pending_value_indices[i] = - find_index_hint(sorted_pending_values, |v: Nullifier| !v.value.lt(value)); - } - } - - NullifierNonExistentReadRequestHints { - non_membership_hints: self.non_membership_hints.storage(), - sorted_pending_values, - sorted_pending_value_index_hints, - next_pending_value_indices, - } - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/base_rollup_inputs.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/base_rollup_inputs.nr index 28bae2e2bd97..87f5cf3fa5bc 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/base_rollup_inputs.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/base_rollup_inputs.nr @@ -287,9 +287,9 @@ impl BaseRollupInputs { all_update_requests } - // Deducts the tx_fee from the FeeJuice balance of the fee_payer. If there is already a PublicDataUpdateRequest + // Deducts the tx_fee from the FeeJuice balance of the fee_payer. If there is already a PublicDataWrite // in this tx for their balance (because they issued a 'claim' to increase their balance by bridging from L1), - // update it by subtracting the tx_fee. Otherwise, build a new PublicDataUpdateRequest to subtract the tx_fee + // update it by subtracting the tx_fee. Otherwise, build a new PublicDataWrite to subtract the tx_fee // from the balance of the fee_payer, using the fee_payer_fee_juice_balance_read_hint to read the current balance. // Returns the data update request that subtracts the tx_fee from the fee_payer's balance, and the index where it // should be inserted in the public data update requests array. @@ -690,7 +690,6 @@ mod tests { PublicDataHint { leaf_slot: leaf_preimage.slot, value: leaf_preimage.value, - override_counter: 0, membership_witness, leaf_preimage, } diff --git a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/public_base_rollup.nr b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/public_base_rollup.nr index 4e3fa619a5a1..54f2c17f54a6 100644 --- a/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/public_base_rollup.nr +++ b/noir-projects/noir-protocol-circuits/crates/rollup-lib/src/base/public_base_rollup.nr @@ -135,7 +135,7 @@ impl PublicBaseRollupInputs { // } // TODO: Validate tube_data.public_inputs vs avm_proof_data.public_inputs // TODO: Deprecate KernelData. - // Temporary workaround to create KernelCircuitPublicInputs from PublicKernelCircuitPublicInputs and AvmCircuitPublicInputs + // Temporary workaround to create KernelCircuitPublicInputs from PrivateToPublicKernelCircuitPublicInputs and AvmCircuitPublicInputs // so that we don't have to modify base_rollup_inputs. let public_inputs = self.generate_kernel_circuit_public_inputs(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/mod.nr index 354485f84eea..c61e2014a188 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/mod.nr @@ -5,8 +5,6 @@ pub mod private_accumulated_data_builder; pub mod private_to_avm_accumulated_data; pub mod private_to_public_accumulated_data; pub mod private_to_public_accumulated_data_builder; -pub mod public_accumulated_data; -pub mod public_accumulated_data_builder; pub use avm_accumulated_data::AvmAccumulatedData; pub use combined_accumulated_data::CombinedAccumulatedData; @@ -15,5 +13,3 @@ pub use private_accumulated_data_builder::PrivateAccumulatedDataBuilder; pub use private_to_avm_accumulated_data::PrivateToAvmAccumulatedData; pub use private_to_public_accumulated_data::PrivateToPublicAccumulatedData; pub use private_to_public_accumulated_data_builder::PrivateToPublicAccumulatedDataBuilder; -pub use public_accumulated_data::{PublicAccumulatedData, PublicAccumulatedDataArrayLengths}; -pub use public_accumulated_data_builder::PublicAccumulatedDataBuilder; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data.nr deleted file mode 100644 index c4d1c87188e2..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data.nr +++ /dev/null @@ -1,265 +0,0 @@ -use crate::{ - abis::{ - gas::Gas, - log_hash::{LogHash, ScopedLogHash}, - note_hash::ScopedNoteHash, - nullifier::Nullifier, - public_call_request::PublicCallRequest, - public_data_update_request::PublicDataUpdateRequest, - }, - constants::{ - MAX_ENCRYPTED_LOGS_PER_TX, MAX_ENQUEUED_CALLS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, - MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX, - NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS, PUBLIC_ACCUMULATED_DATA_LENGTH, - }, - messaging::l2_to_l1_message::ScopedL2ToL1Message, - traits::{Deserialize, Empty, Serialize}, - utils::{arrays::array_length, reader::Reader}, -}; - -// TODO(#9594): To be deprecated. -pub struct PublicAccumulatedData { - pub note_hashes: [ScopedNoteHash; MAX_NOTE_HASHES_PER_TX], - pub nullifiers: [Nullifier; MAX_NULLIFIERS_PER_TX], - pub l2_to_l1_msgs: [ScopedL2ToL1Message; MAX_L2_TO_L1_MSGS_PER_TX], - - pub note_encrypted_logs_hashes: [LogHash; MAX_NOTE_ENCRYPTED_LOGS_PER_TX], - pub encrypted_logs_hashes: [ScopedLogHash; MAX_ENCRYPTED_LOGS_PER_TX], - pub unencrypted_logs_hashes: [ScopedLogHash; MAX_UNENCRYPTED_LOGS_PER_TX], - - pub public_data_update_requests: [PublicDataUpdateRequest; MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], - - pub public_call_stack: [PublicCallRequest; MAX_ENQUEUED_CALLS_PER_TX], - - pub gas_used: Gas, -} - -impl Empty for PublicAccumulatedData { - fn empty() -> Self { - PublicAccumulatedData { - note_hashes: [ScopedNoteHash::empty(); MAX_NOTE_HASHES_PER_TX], - nullifiers: [Nullifier::empty(); MAX_NULLIFIERS_PER_TX], - l2_to_l1_msgs: [ScopedL2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_TX], - note_encrypted_logs_hashes: [LogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX], - encrypted_logs_hashes: [ScopedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX], - unencrypted_logs_hashes: [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX], - public_data_update_requests: [ - PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX - ], - public_call_stack: [PublicCallRequest::empty(); MAX_ENQUEUED_CALLS_PER_TX], - gas_used: Gas::empty(), - } - } -} - -impl Serialize for PublicAccumulatedData { - fn serialize(self) -> [Field; PUBLIC_ACCUMULATED_DATA_LENGTH] { - let mut fields: BoundedVec = BoundedVec::new(); - - for i in 0..MAX_NOTE_HASHES_PER_TX { - fields.extend_from_array(self.note_hashes[i].serialize()); - } - - for i in 0..MAX_NULLIFIERS_PER_TX { - fields.extend_from_array(self.nullifiers[i].serialize()); - } - - for i in 0..MAX_L2_TO_L1_MSGS_PER_TX { - fields.extend_from_array(self.l2_to_l1_msgs[i].serialize()); - } - - for i in 0..MAX_NOTE_ENCRYPTED_LOGS_PER_TX { - fields.extend_from_array(self.note_encrypted_logs_hashes[i].serialize()); - } - - for i in 0..MAX_ENCRYPTED_LOGS_PER_TX { - fields.extend_from_array(self.encrypted_logs_hashes[i].serialize()); - } - - for i in 0..MAX_UNENCRYPTED_LOGS_PER_TX { - fields.extend_from_array(self.unencrypted_logs_hashes[i].serialize()); - } - - for i in 0..MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX { - fields.extend_from_array(self.public_data_update_requests[i].serialize()); - } - - for i in 0..MAX_ENQUEUED_CALLS_PER_TX { - fields.extend_from_array(self.public_call_stack[i].serialize()); - } - - fields.extend_from_array(self.gas_used.serialize()); - - assert_eq(fields.len(), PUBLIC_ACCUMULATED_DATA_LENGTH); - - fields.storage() - } -} - -impl Deserialize for PublicAccumulatedData { - fn deserialize(fields: [Field; PUBLIC_ACCUMULATED_DATA_LENGTH]) -> PublicAccumulatedData { - let mut reader = Reader::new(fields); - - let item = PublicAccumulatedData { - note_hashes: reader.read_struct_array( - ScopedNoteHash::deserialize, - [ScopedNoteHash::empty(); MAX_NOTE_HASHES_PER_TX], - ), - nullifiers: reader.read_struct_array( - Nullifier::deserialize, - [Nullifier::empty(); MAX_NULLIFIERS_PER_TX], - ), - l2_to_l1_msgs: reader.read_struct_array( - ScopedL2ToL1Message::deserialize, - [ScopedL2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_TX], - ), - note_encrypted_logs_hashes: reader.read_struct_array( - LogHash::deserialize, - [LogHash::empty(); MAX_NOTE_ENCRYPTED_LOGS_PER_TX], - ), - encrypted_logs_hashes: reader.read_struct_array( - ScopedLogHash::deserialize, - [ScopedLogHash::empty(); MAX_ENCRYPTED_LOGS_PER_TX], - ), - unencrypted_logs_hashes: reader.read_struct_array( - ScopedLogHash::deserialize, - [ScopedLogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_TX], - ), - public_data_update_requests: reader.read_struct_array( - PublicDataUpdateRequest::deserialize, - [PublicDataUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX], - ), - public_call_stack: reader.read_struct_array( - PublicCallRequest::deserialize, - [PublicCallRequest::empty(); MAX_ENQUEUED_CALLS_PER_TX], - ), - gas_used: reader.read_struct(Gas::deserialize), - }; - reader.finish(); - item - } -} - -impl Eq for PublicAccumulatedData { - fn eq(self, other: Self) -> bool { - (self.note_hashes == other.note_hashes) - & (self.nullifiers == other.nullifiers) - & (self.l2_to_l1_msgs == other.l2_to_l1_msgs) - & (self.note_encrypted_logs_hashes == other.note_encrypted_logs_hashes) - & (self.encrypted_logs_hashes == other.encrypted_logs_hashes) - & (self.unencrypted_logs_hashes == other.unencrypted_logs_hashes) - & (self.public_data_update_requests == other.public_data_update_requests) - & (self.public_call_stack == other.public_call_stack) - & (self.gas_used == other.gas_used) - } -} - -pub struct PublicAccumulatedDataArrayLengths { - note_hashes: u32, - nullifiers: u32, - l2_to_l1_msgs: u32, - note_encrypted_logs_hashes: u32, - encrypted_logs_hashes: u32, - unencrypted_logs_hashes: u32, - public_data_update_requests: u32, - public_call_stack: u32, -} - -impl PublicAccumulatedDataArrayLengths { - pub fn new(data: PublicAccumulatedData) -> Self { - PublicAccumulatedDataArrayLengths { - note_hashes: array_length(data.note_hashes), - nullifiers: array_length(data.nullifiers), - l2_to_l1_msgs: array_length(data.l2_to_l1_msgs), - note_encrypted_logs_hashes: array_length(data.note_encrypted_logs_hashes), - encrypted_logs_hashes: array_length(data.encrypted_logs_hashes), - unencrypted_logs_hashes: array_length(data.unencrypted_logs_hashes), - public_data_update_requests: array_length(data.public_data_update_requests), - public_call_stack: array_length(data.public_call_stack), - } - } -} - -impl Empty for PublicAccumulatedDataArrayLengths { - fn empty() -> Self { - PublicAccumulatedDataArrayLengths { - note_hashes: 0, - nullifiers: 0, - l2_to_l1_msgs: 0, - note_encrypted_logs_hashes: 0, - encrypted_logs_hashes: 0, - unencrypted_logs_hashes: 0, - public_data_update_requests: 0, - public_call_stack: 0, - } - } -} - -impl Eq for PublicAccumulatedDataArrayLengths { - fn eq(self, other: Self) -> bool { - (self.note_hashes == other.note_hashes) - & (self.nullifiers == other.nullifiers) - & (self.l2_to_l1_msgs == other.l2_to_l1_msgs) - & (self.note_encrypted_logs_hashes == other.note_encrypted_logs_hashes) - & (self.encrypted_logs_hashes == other.encrypted_logs_hashes) - & (self.unencrypted_logs_hashes == other.unencrypted_logs_hashes) - & (self.public_data_update_requests == other.public_data_update_requests) - & (self.public_call_stack == other.public_call_stack) - } -} - -impl Serialize for PublicAccumulatedDataArrayLengths { - fn serialize(self) -> [Field; NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS] { - let mut fields: BoundedVec = BoundedVec::new(); - - fields.push(self.note_hashes as Field); - fields.push(self.nullifiers as Field); - fields.push(self.l2_to_l1_msgs as Field); - fields.push(self.note_encrypted_logs_hashes as Field); - fields.push(self.encrypted_logs_hashes as Field); - fields.push(self.unencrypted_logs_hashes as Field); - fields.push(self.public_data_update_requests as Field); - fields.push(self.public_call_stack as Field); - - fields.storage() - } -} - -impl Deserialize for PublicAccumulatedDataArrayLengths { - fn deserialize( - fields: [Field; NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS], - ) -> PublicAccumulatedDataArrayLengths { - let mut reader = Reader::new(fields); - - let item = Self { - note_hashes: reader.read_u32(), - nullifiers: reader.read_u32(), - l2_to_l1_msgs: reader.read_u32(), - note_encrypted_logs_hashes: reader.read_u32(), - encrypted_logs_hashes: reader.read_u32(), - unencrypted_logs_hashes: reader.read_u32(), - public_data_update_requests: reader.read_u32(), - public_call_stack: reader.read_u32(), - }; - - reader.finish(); - item - } -} - -#[test] -fn serialization_of_empty() { - let item = PublicAccumulatedData::empty(); - let serialized = item.serialize(); - let deserialized = PublicAccumulatedData::deserialize(serialized); - assert(item.eq(deserialized)); -} - -#[test] -fn serialization_of_empty_array_lengths() { - let item = PublicAccumulatedDataArrayLengths::empty(); - let serialized = item.serialize(); - let deserialized = PublicAccumulatedDataArrayLengths::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data_builder.nr deleted file mode 100644 index 986db95df09e..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/accumulated_data/public_accumulated_data_builder.nr +++ /dev/null @@ -1,82 +0,0 @@ -use crate::{ - abis::{ - accumulated_data::public_accumulated_data::PublicAccumulatedData, - gas::Gas, - log_hash::{LogHash, ScopedLogHash}, - note_hash::ScopedNoteHash, - nullifier::Nullifier, - public_call_request::PublicCallRequest, - public_data_update_request::PublicDataUpdateRequest, - }, - constants::{ - MAX_ENCRYPTED_LOGS_PER_TX, MAX_ENQUEUED_CALLS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, - MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX, - }, - messaging::l2_to_l1_message::ScopedL2ToL1Message, - traits::Empty, - utils::arrays::array_to_bounded_vec, -}; - -// TODO(#9594): To be deprecated. -pub struct PublicAccumulatedDataBuilder { - pub note_hashes: BoundedVec, - pub nullifiers: BoundedVec, - pub l2_to_l1_msgs: BoundedVec, - - pub note_encrypted_logs_hashes: BoundedVec, - pub encrypted_logs_hashes: BoundedVec, - pub unencrypted_logs_hashes: BoundedVec, - - pub public_data_update_requests: BoundedVec, - - pub public_call_stack: BoundedVec, - - pub gas_used: Gas, -} - -impl PublicAccumulatedDataBuilder { - pub fn new(data: PublicAccumulatedData) -> Self { - PublicAccumulatedDataBuilder { - note_hashes: array_to_bounded_vec(data.note_hashes), - nullifiers: array_to_bounded_vec(data.nullifiers), - l2_to_l1_msgs: array_to_bounded_vec(data.l2_to_l1_msgs), - note_encrypted_logs_hashes: array_to_bounded_vec(data.note_encrypted_logs_hashes), - encrypted_logs_hashes: array_to_bounded_vec(data.encrypted_logs_hashes), - unencrypted_logs_hashes: array_to_bounded_vec(data.unencrypted_logs_hashes), - public_data_update_requests: array_to_bounded_vec(data.public_data_update_requests), - public_call_stack: array_to_bounded_vec(data.public_call_stack), - gas_used: data.gas_used, - } - } - - pub fn finish(self) -> PublicAccumulatedData { - PublicAccumulatedData { - note_hashes: self.note_hashes.storage(), - nullifiers: self.nullifiers.storage(), - l2_to_l1_msgs: self.l2_to_l1_msgs.storage(), - note_encrypted_logs_hashes: self.note_encrypted_logs_hashes.storage(), - encrypted_logs_hashes: self.encrypted_logs_hashes.storage(), - unencrypted_logs_hashes: self.unencrypted_logs_hashes.storage(), - public_data_update_requests: self.public_data_update_requests.storage(), - public_call_stack: self.public_call_stack.storage(), - gas_used: self.gas_used, - } - } -} - -impl Empty for PublicAccumulatedDataBuilder { - fn empty() -> Self { - PublicAccumulatedDataBuilder { - note_hashes: BoundedVec::new(), - nullifiers: BoundedVec::new(), - l2_to_l1_msgs: BoundedVec::new(), - note_encrypted_logs_hashes: BoundedVec::new(), - encrypted_logs_hashes: BoundedVec::new(), - unencrypted_logs_hashes: BoundedVec::new(), - public_data_update_requests: BoundedVec::new(), - public_call_stack: BoundedVec::new(), - gas_used: Gas::empty(), - } - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/enqueued_call_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/enqueued_call_data.nr deleted file mode 100644 index ca862ecdaf4e..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/enqueued_call_data.nr +++ /dev/null @@ -1,9 +0,0 @@ -use crate::abis::kernel_circuit_public_inputs::vm_circuit_public_inputs::VMCircuitPublicInputs; - -// Mocked here as the only remaining non-recursive proof -pub struct Proof {} - -pub struct EnqueuedCallData { - pub data: VMCircuitPublicInputs, - pub proof: Proof, -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/mod.nr index 03d416e5e038..4cc319e29cd1 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/mod.nr @@ -2,9 +2,6 @@ pub mod kernel_circuit_public_inputs; pub mod private_kernel_circuit_public_inputs; pub mod private_kernel_circuit_public_inputs_builder; pub mod private_to_public_kernel_circuit_public_inputs; -pub mod public_kernel_circuit_public_inputs; -pub mod public_kernel_circuit_public_inputs_builder; -pub mod vm_circuit_public_inputs; pub use kernel_circuit_public_inputs::KernelCircuitPublicInputs; pub use private_kernel_circuit_public_inputs::{ @@ -12,6 +9,3 @@ pub use private_kernel_circuit_public_inputs::{ }; pub use private_kernel_circuit_public_inputs_builder::PrivateKernelCircuitPublicInputsBuilder; pub use private_to_public_kernel_circuit_public_inputs::PrivateToPublicKernelCircuitPublicInputs; -pub use public_kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs; -pub use public_kernel_circuit_public_inputs_builder::PublicKernelCircuitPublicInputsBuilder; -pub use vm_circuit_public_inputs::VMCircuitPublicInputs; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs.nr deleted file mode 100644 index 701bd43e1dce..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs.nr +++ /dev/null @@ -1,98 +0,0 @@ -use crate::{ - abis::{ - accumulated_data::PublicAccumulatedData, combined_constant_data::CombinedConstantData, - public_call_request::PublicCallRequest, validation_requests::PublicValidationRequests, - }, - address::AztecAddress, - constants::PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH, - traits::{Deserialize, Empty, Serialize}, - utils::reader::Reader, -}; - -pub struct PublicKernelCircuitPublicInputs { - pub constants: CombinedConstantData, - pub validation_requests: PublicValidationRequests, - pub end_non_revertible: PublicAccumulatedData, - pub end: PublicAccumulatedData, - pub end_side_effect_counter: u32, - pub public_teardown_call_request: PublicCallRequest, - pub fee_payer: AztecAddress, - pub revert_code: u8, -} - -impl Empty for PublicKernelCircuitPublicInputs { - fn empty() -> Self { - PublicKernelCircuitPublicInputs { - constants: CombinedConstantData::empty(), - validation_requests: PublicValidationRequests::empty(), - end_non_revertible: PublicAccumulatedData::empty(), - end: PublicAccumulatedData::empty(), - end_side_effect_counter: 0, - public_teardown_call_request: PublicCallRequest::empty(), - fee_payer: AztecAddress::empty(), - revert_code: 0, - } - } -} - -impl Serialize for PublicKernelCircuitPublicInputs { - fn serialize(self) -> [Field; PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH] { - let mut fields: BoundedVec = - BoundedVec::new(); - - fields.extend_from_array(self.constants.serialize()); - fields.extend_from_array(self.validation_requests.serialize()); - fields.extend_from_array(self.end_non_revertible.serialize()); - fields.extend_from_array(self.end.serialize()); - fields.push(self.end_side_effect_counter as Field); - fields.extend_from_array(self.public_teardown_call_request.serialize()); - fields.extend_from_array(self.fee_payer.serialize()); - fields.push(self.revert_code as Field); - - assert_eq(fields.len(), PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH); - - fields.storage() - } -} - -impl Deserialize for PublicKernelCircuitPublicInputs { - fn deserialize( - fields: [Field; PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH], - ) -> PublicKernelCircuitPublicInputs { - let mut reader = Reader::new(fields); - - let item = PublicKernelCircuitPublicInputs { - constants: reader.read_struct(CombinedConstantData::deserialize), - validation_requests: reader.read_struct(PublicValidationRequests::deserialize), - end_non_revertible: reader.read_struct(PublicAccumulatedData::deserialize), - end: reader.read_struct(PublicAccumulatedData::deserialize), - end_side_effect_counter: reader.read_u32(), - public_teardown_call_request: reader.read_struct(PublicCallRequest::deserialize), - fee_payer: reader.read_struct(AztecAddress::deserialize), - revert_code: reader.read() as u8, - }; - reader.finish(); - item - } -} - -impl Eq for PublicKernelCircuitPublicInputs { - fn eq(self, other: Self) -> bool { - (self.constants == other.constants) - & (self.validation_requests == other.validation_requests) - & (self.end_non_revertible == other.end_non_revertible) - & (self.end == other.end) - & (self.end_side_effect_counter == other.end_side_effect_counter) - & (self.public_teardown_call_request == other.public_teardown_call_request) - & (self.fee_payer == other.fee_payer) - & (self.revert_code == other.revert_code) - } -} - -#[test] -fn serialization_of_empty() { - let item = PublicKernelCircuitPublicInputs::empty(); - let serialized = item.serialize(); - let deserialized = PublicKernelCircuitPublicInputs::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs_builder.nr deleted file mode 100644 index f81c736f9bd9..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/public_kernel_circuit_public_inputs_builder.nr +++ /dev/null @@ -1,68 +0,0 @@ -use crate::{ - abis::{ - accumulated_data::PublicAccumulatedDataBuilder, - combined_constant_data::CombinedConstantData, - kernel_circuit_public_inputs::public_kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - public_call_request::PublicCallRequest, - validation_requests::PublicValidationRequestsBuilder, - }, - address::AztecAddress, - traits::Empty, -}; - -pub struct PublicKernelCircuitPublicInputsBuilder { - constants: CombinedConstantData, - validation_requests: PublicValidationRequestsBuilder, - end_non_revertible: PublicAccumulatedDataBuilder, - end: PublicAccumulatedDataBuilder, - end_side_effect_counter: u32, - public_teardown_call_request: PublicCallRequest, - fee_payer: AztecAddress, - revert_code: u8, -} - -impl PublicKernelCircuitPublicInputsBuilder { - pub fn new(data: PublicKernelCircuitPublicInputs) -> Self { - PublicKernelCircuitPublicInputsBuilder { - constants: data.constants, - validation_requests: PublicValidationRequestsBuilder::new(data.validation_requests), - end_non_revertible: PublicAccumulatedDataBuilder::new(data.end_non_revertible), - end: PublicAccumulatedDataBuilder::new(data.end), - end_side_effect_counter: data.end_side_effect_counter, - public_teardown_call_request: data.public_teardown_call_request, - fee_payer: data.fee_payer, - revert_code: data.revert_code, - } - } - - pub fn finish(self) -> PublicKernelCircuitPublicInputs { - PublicKernelCircuitPublicInputs { - constants: self.constants, - // Note that we're including both the validation_requests AND the rollup_validation requests, because this - // struct is used as an input for both the public kernel and base rollup circuits. In the near future the - // base rollup will only receive rollup_validation_requests, and the public kernel only validation_requests. - validation_requests: self.validation_requests.finish(), - end_non_revertible: self.end_non_revertible.finish(), - end: self.end.finish(), - end_side_effect_counter: self.end_side_effect_counter, - public_teardown_call_request: self.public_teardown_call_request, - fee_payer: self.fee_payer, - revert_code: self.revert_code, - } - } -} - -impl Empty for PublicKernelCircuitPublicInputsBuilder { - fn empty() -> Self { - PublicKernelCircuitPublicInputsBuilder { - constants: CombinedConstantData::empty(), - validation_requests: PublicValidationRequestsBuilder::empty(), - end_non_revertible: PublicAccumulatedDataBuilder::empty(), - end: PublicAccumulatedDataBuilder::empty(), - end_side_effect_counter: 0, - public_teardown_call_request: PublicCallRequest::empty(), - fee_payer: AztecAddress::empty(), - revert_code: 0 as u8, - } - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/vm_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/vm_circuit_public_inputs.nr deleted file mode 100644 index af6fd3b2560c..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/kernel_circuit_public_inputs/vm_circuit_public_inputs.nr +++ /dev/null @@ -1,135 +0,0 @@ -use crate::{ - abis::{ - accumulated_data::{PublicAccumulatedData, PublicAccumulatedDataArrayLengths}, - combined_constant_data::CombinedConstantData, - gas::Gas, - public_call_request::PublicCallRequest, - public_inner_call_request::PublicInnerCallRequest, - validation_requests::{PublicValidationRequestArrayLengths, PublicValidationRequests}, - }, - constants::{MAX_ENQUEUED_CALLS_PER_TX, VM_CIRCUIT_PUBLIC_INPUTS_LENGTH}, - traits::{Deserialize, Empty, Serialize}, - utils::reader::Reader, -}; - -// TODO(#9594): To be deprecated. -pub struct VMCircuitPublicInputs { - pub constants: CombinedConstantData, - pub call_request: PublicCallRequest, - - pub public_call_stack: [PublicInnerCallRequest; MAX_ENQUEUED_CALLS_PER_TX], - - pub previous_validation_request_array_lengths: PublicValidationRequestArrayLengths, // Lengths of the validation requests before the enqueued call. - pub validation_requests: PublicValidationRequests, // Validation requests emitted throughout the enqueued call. - pub previous_accumulated_data_array_lengths: PublicAccumulatedDataArrayLengths, // Lengths of the accumulated data before the enqueued call. - pub accumulated_data: PublicAccumulatedData, // Data emitted throughout the enqueued call. - pub start_side_effect_counter: u32, - pub end_side_effect_counter: u32, - pub start_gas_left: Gas, - pub transaction_fee: Field, - pub reverted: bool, -} - -impl Empty for VMCircuitPublicInputs { - fn empty() -> Self { - VMCircuitPublicInputs { - constants: CombinedConstantData::empty(), - call_request: PublicCallRequest::empty(), - public_call_stack: [PublicInnerCallRequest::empty(); MAX_ENQUEUED_CALLS_PER_TX], - previous_validation_request_array_lengths: PublicValidationRequestArrayLengths::empty(), - validation_requests: PublicValidationRequests::empty(), - previous_accumulated_data_array_lengths: PublicAccumulatedDataArrayLengths::empty(), - accumulated_data: PublicAccumulatedData::empty(), - start_side_effect_counter: 0, - end_side_effect_counter: 0, - start_gas_left: Gas::empty(), - transaction_fee: 0, - reverted: false, - } - } -} - -impl Eq for VMCircuitPublicInputs { - fn eq(self, other: Self) -> bool { - (self.constants == other.constants) - & (self.call_request == other.call_request) - & (self.public_call_stack == other.public_call_stack) - & ( - self.previous_validation_request_array_lengths - == other.previous_validation_request_array_lengths - ) - & (self.validation_requests == other.validation_requests) - & ( - self.previous_accumulated_data_array_lengths - == other.previous_accumulated_data_array_lengths - ) - & (self.accumulated_data == other.accumulated_data) - & (self.start_side_effect_counter == other.start_side_effect_counter) - & (self.end_side_effect_counter == other.end_side_effect_counter) - & (self.start_gas_left == other.start_gas_left) - & (self.transaction_fee == other.transaction_fee) - & (self.reverted == other.reverted) - } -} - -impl Serialize for VMCircuitPublicInputs { - fn serialize(self) -> [Field; VM_CIRCUIT_PUBLIC_INPUTS_LENGTH] { - let mut fields: BoundedVec = BoundedVec::new(); - - fields.extend_from_array(self.constants.serialize()); - fields.extend_from_array(self.call_request.serialize()); - for i in 0..MAX_ENQUEUED_CALLS_PER_TX { - fields.extend_from_array(self.public_call_stack[i].serialize()); - } - fields.extend_from_array(self.previous_validation_request_array_lengths.serialize()); - fields.extend_from_array(self.validation_requests.serialize()); - fields.extend_from_array(self.previous_accumulated_data_array_lengths.serialize()); - fields.extend_from_array(self.accumulated_data.serialize()); - fields.push(self.start_side_effect_counter as Field); - fields.push(self.end_side_effect_counter as Field); - fields.extend_from_array(self.start_gas_left.serialize()); - fields.push(self.transaction_fee); - fields.push(self.reverted as Field); - - assert_eq(fields.len(), VM_CIRCUIT_PUBLIC_INPUTS_LENGTH); - - fields.storage() - } -} - -impl Deserialize for VMCircuitPublicInputs { - fn deserialize(fields: [Field; VM_CIRCUIT_PUBLIC_INPUTS_LENGTH]) -> VMCircuitPublicInputs { - let mut reader = Reader::new(fields); - let item = VMCircuitPublicInputs { - constants: reader.read_struct(CombinedConstantData::deserialize), - call_request: reader.read_struct(PublicCallRequest::deserialize), - public_call_stack: reader.read_struct_array( - PublicInnerCallRequest::deserialize, - [PublicInnerCallRequest::empty(); MAX_ENQUEUED_CALLS_PER_TX], - ), - previous_validation_request_array_lengths: reader.read_struct( - PublicValidationRequestArrayLengths::deserialize, - ), - validation_requests: reader.read_struct(PublicValidationRequests::deserialize), - previous_accumulated_data_array_lengths: reader.read_struct( - PublicAccumulatedDataArrayLengths::deserialize, - ), - accumulated_data: reader.read_struct(PublicAccumulatedData::deserialize), - start_side_effect_counter: reader.read_u32(), - end_side_effect_counter: reader.read_u32(), - start_gas_left: reader.read_struct(Gas::deserialize), - transaction_fee: reader.read(), - reverted: reader.read() as bool, - }; - reader.finish(); - item - } -} - -#[test] -fn serialization_of_empty() { - let item = VMCircuitPublicInputs::empty(); - let serialized = item.serialize(); - let deserialized = VMCircuitPublicInputs::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/mod.nr index e29706c42ed0..a0eb63aead9a 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/mod.nr @@ -16,12 +16,9 @@ pub mod combined_constant_data; pub mod side_effect; pub mod read_request; -pub mod tree_leaf_read_request; pub mod log_hash; pub mod note_hash; pub mod nullifier; -pub mod public_data_read; -pub mod public_data_update_request; pub mod public_data_write; pub mod accumulated_data; @@ -32,16 +29,11 @@ pub mod max_block_number; pub mod private_kernel; pub mod kernel_circuit_public_inputs; pub mod private_kernel_data; -pub mod public_kernel_data; pub mod private_call_request; pub mod public_call_request; -pub mod public_call_stack_item_compressed; -pub mod public_inner_call_request; pub mod call_context; -pub mod enqueued_call_data; - pub mod private_circuit_public_inputs; pub mod gas_fees; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_data.nr deleted file mode 100644 index d1efafb102ec..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_data.nr +++ /dev/null @@ -1,11 +0,0 @@ -use crate::abis::public_circuit_public_inputs::PublicCircuitPublicInputs; - -// Mocked here as the only remaining non-recursive proof -pub struct Proof {} - -// TODO(#7124): To be deprecated. -pub struct PublicCallData { - pub public_inputs: PublicCircuitPublicInputs, - pub proof: Proof, - pub bytecode_hash: Field, -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_request.nr index 8e4aa25fa6b5..6a9e7929f0cb 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_request.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_request.nr @@ -1,5 +1,5 @@ use crate::{ - abis::{call_context::CallContext, function_selector::FunctionSelector, side_effect::Ordered}, + abis::function_selector::FunctionSelector, address::AztecAddress, constants::PUBLIC_CALL_REQUEST_LENGTH, traits::{Deserialize, Empty, Serialize}, diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_stack_item_compressed.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_stack_item_compressed.nr deleted file mode 100644 index 69a604f32d8d..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_call_stack_item_compressed.nr +++ /dev/null @@ -1,94 +0,0 @@ -use crate::abis::{call_context::CallContext, gas::Gas}; -use crate::address::AztecAddress; -use crate::constants::PUBLIC_CALL_STACK_ITEM_COMPRESSED_LENGTH; -use crate::traits::{Deserialize, Empty, Serialize}; -use crate::utils::reader::Reader; - -/** - * A compressed version of the PublicCallStackItem struct used to compute the "hash" - * of a PublicCallStackItem. - * - * Historically, we have been zeroing most values in the PublicCallStackItem struct - * to compute the hash involved when adding a PublicCallStackItem to the PublicCallStack. - * - * This struct is used to store the values that we did not zero out, and allow us to hash - * only these, thereby skipping a lot of computation and saving us a lot of constraints - * - * Essentially this struct exists such that we don't have a `hash` function in the - * PublicCallStackItem struct that practically throws away some values of the struct - * without clearly indicating that it does so. - */ -pub struct PublicCallStackItemCompressed { - contract_address: AztecAddress, - call_context: CallContext, - args_hash: Field, - returns_hash: Field, - revert_code: u8, - start_gas_left: Gas, - end_gas_left: Gas, -} - -impl Eq for PublicCallStackItemCompressed { - fn eq(self, other: PublicCallStackItemCompressed) -> bool { - (self.contract_address == other.contract_address) - & (self.call_context == other.call_context) - & (self.args_hash == other.args_hash) - & (self.returns_hash == other.returns_hash) - & (self.revert_code == other.revert_code) - & (self.start_gas_left == other.start_gas_left) - & (self.end_gas_left == other.end_gas_left) - } -} - -impl Empty for PublicCallStackItemCompressed { - fn empty() -> Self { - PublicCallStackItemCompressed { - contract_address: AztecAddress::empty(), - call_context: CallContext::empty(), - args_hash: 0, - returns_hash: 0, - revert_code: 0, - start_gas_left: Gas::empty(), - end_gas_left: Gas::empty(), - } - } -} - -impl Serialize for PublicCallStackItemCompressed { - fn serialize(self) -> [Field; PUBLIC_CALL_STACK_ITEM_COMPRESSED_LENGTH] { - let mut fields: BoundedVec = - BoundedVec::new(); - - fields.push(self.contract_address.to_field()); - fields.extend_from_array(self.call_context.serialize()); - fields.push(self.args_hash); - fields.push(self.returns_hash); - fields.push(self.revert_code as Field); - fields.extend_from_array(self.start_gas_left.serialize()); - fields.extend_from_array(self.end_gas_left.serialize()); - - assert_eq(fields.len(), PUBLIC_CALL_STACK_ITEM_COMPRESSED_LENGTH); - - fields.storage() - } -} - -impl Deserialize for PublicCallStackItemCompressed { - fn deserialize( - fields: [Field; PUBLIC_CALL_STACK_ITEM_COMPRESSED_LENGTH], - ) -> PublicCallStackItemCompressed { - let mut reader = Reader::new(fields); - - let item = PublicCallStackItemCompressed { - contract_address: reader.read_struct(AztecAddress::deserialize), - call_context: reader.read_struct(CallContext::deserialize), - args_hash: reader.read(), - returns_hash: reader.read(), - revert_code: reader.read() as u8, - start_gas_left: reader.read_struct(Gas::deserialize), - end_gas_left: reader.read_struct(Gas::deserialize), - }; - reader.finish(); - item - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_circuit_public_inputs.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_circuit_public_inputs.nr deleted file mode 100644 index 3a5cf64961c1..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_circuit_public_inputs.nr +++ /dev/null @@ -1,237 +0,0 @@ -use crate::{ - abis::{ - call_context::CallContext, gas::Gas, global_variables::GlobalVariables, log_hash::LogHash, - note_hash::NoteHash, nullifier::Nullifier, - public_inner_call_request::PublicInnerCallRequest, read_request::ReadRequest, - tree_leaf_read_request::TreeLeafReadRequest, - }, - address::AztecAddress, - constants::{ - MAX_ENQUEUED_CALLS_PER_CALL, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL, - MAX_L2_TO_L1_MSGS_PER_CALL, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, MAX_NOTE_HASHES_PER_CALL, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL, MAX_NULLIFIER_READ_REQUESTS_PER_CALL, - MAX_NULLIFIERS_PER_CALL, MAX_PUBLIC_DATA_READS_PER_CALL, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, MAX_UNENCRYPTED_LOGS_PER_CALL, - PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH, - }, - contrakt::{storage_read::StorageRead, storage_update_request::StorageUpdateRequest}, - header::Header, - messaging::l2_to_l1_message::L2ToL1Message, - traits::{Deserialize, Empty, Serialize}, - utils::reader::Reader, -}; - -// Public inputs to public app circuit. -pub struct PublicCircuitPublicInputs { - pub call_context: CallContext, - - pub args_hash: Field, - pub returns_hash: Field, - - pub note_hash_read_requests: [TreeLeafReadRequest; MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - pub nullifier_read_requests: [ReadRequest; MAX_NULLIFIER_READ_REQUESTS_PER_CALL], - pub nullifier_non_existent_read_requests: [ReadRequest; MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL], - pub l1_to_l2_msg_read_requests: [TreeLeafReadRequest; MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL], - pub contract_storage_update_requests: [StorageUpdateRequest; MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL], - pub contract_storage_reads: [StorageRead; MAX_PUBLIC_DATA_READS_PER_CALL], - - // todo: add sideeffect ranges for the input to these hashes - pub public_call_requests: [PublicInnerCallRequest; MAX_ENQUEUED_CALLS_PER_CALL], - pub note_hashes: [NoteHash; MAX_NOTE_HASHES_PER_CALL], - pub nullifiers: [Nullifier; MAX_NULLIFIERS_PER_CALL], - pub l2_to_l1_msgs: [L2ToL1Message; MAX_L2_TO_L1_MSGS_PER_CALL], - - pub start_side_effect_counter: u32, - pub end_side_effect_counter: u32, - - pub unencrypted_logs_hashes: [LogHash; MAX_UNENCRYPTED_LOGS_PER_CALL], - - // Header of a block whose state is used during public execution. Set by sequencer to be a header of a block - // previous to the one in which the tx is included. - pub historical_header: Header, - - // Global variables injected into this circuit - pub global_variables: GlobalVariables, - - pub prover_address: AztecAddress, - - pub revert_code: u8, - - pub start_gas_left: Gas, - pub end_gas_left: Gas, - pub transaction_fee: Field, -} - -impl Eq for PublicCircuitPublicInputs { - fn eq(self, other: Self) -> bool { - self.serialize() == other.serialize() - } -} - -impl Serialize for PublicCircuitPublicInputs { - fn serialize(self) -> [Field; PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH] { - let mut fields: BoundedVec = BoundedVec::new(); - fields.extend_from_array(self.call_context.serialize()); - fields.push(self.args_hash); - fields.push(self.returns_hash); - for i in 0..MAX_NOTE_HASH_READ_REQUESTS_PER_CALL { - fields.extend_from_array(self.note_hash_read_requests[i].serialize()); - } - for i in 0..MAX_NULLIFIER_READ_REQUESTS_PER_CALL { - fields.extend_from_array(self.nullifier_read_requests[i].serialize()); - } - for i in 0..MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL { - fields.extend_from_array(self.nullifier_non_existent_read_requests[i].serialize()); - } - for i in 0..MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL { - fields.extend_from_array(self.l1_to_l2_msg_read_requests[i].serialize()); - } - for i in 0..MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL { - fields.extend_from_array(self.contract_storage_update_requests[i].serialize()); - } - for i in 0..MAX_PUBLIC_DATA_READS_PER_CALL { - fields.extend_from_array(self.contract_storage_reads[i].serialize()); - } - for i in 0..MAX_ENQUEUED_CALLS_PER_CALL { - fields.extend_from_array(self.public_call_requests[i].serialize()); - } - for i in 0..MAX_NOTE_HASHES_PER_CALL { - fields.extend_from_array(self.note_hashes[i].serialize()); - } - for i in 0..MAX_NULLIFIERS_PER_CALL { - fields.extend_from_array(self.nullifiers[i].serialize()); - } - for i in 0..MAX_L2_TO_L1_MSGS_PER_CALL { - fields.extend_from_array(self.l2_to_l1_msgs[i].serialize()); - } - - fields.push(self.start_side_effect_counter as Field); - fields.push(self.end_side_effect_counter as Field); - - for i in 0..MAX_UNENCRYPTED_LOGS_PER_CALL { - fields.extend_from_array(self.unencrypted_logs_hashes[i].serialize()); - } - fields.extend_from_array(self.historical_header.serialize()); - fields.extend_from_array(self.global_variables.serialize()); - fields.push(self.prover_address.to_field()); - fields.push(self.revert_code as Field); - fields.extend_from_array(self.start_gas_left.serialize()); - fields.extend_from_array(self.end_gas_left.serialize()); - fields.push(self.transaction_fee); - fields.storage() - } -} - -impl Deserialize for PublicCircuitPublicInputs { - fn deserialize(serialized: [Field; PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH]) -> Self { - // TODO(#4390): This should accept a reader ^ to avoid copying data. - let mut reader = Reader::new(serialized); - let inputs = PublicCircuitPublicInputs { - call_context: reader.read_struct(CallContext::deserialize), - args_hash: reader.read(), - returns_hash: reader.read(), - note_hash_read_requests: reader.read_struct_array( - TreeLeafReadRequest::deserialize, - [TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL], - ), - nullifier_read_requests: reader.read_struct_array( - ReadRequest::deserialize, - [ReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_CALL], - ), - nullifier_non_existent_read_requests: reader.read_struct_array( - ReadRequest::deserialize, - [ReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL], - ), - l1_to_l2_msg_read_requests: reader.read_struct_array( - TreeLeafReadRequest::deserialize, - [TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL], - ), - contract_storage_update_requests: reader.read_struct_array( - StorageUpdateRequest::deserialize, - [StorageUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL], - ), - contract_storage_reads: reader.read_struct_array( - StorageRead::deserialize, - [StorageRead::empty(); MAX_PUBLIC_DATA_READS_PER_CALL], - ), - public_call_requests: reader.read_struct_array( - PublicInnerCallRequest::deserialize, - [PublicInnerCallRequest::empty(); MAX_ENQUEUED_CALLS_PER_CALL], - ), - note_hashes: reader.read_struct_array( - NoteHash::deserialize, - [NoteHash::empty(); MAX_NOTE_HASHES_PER_CALL], - ), - nullifiers: reader.read_struct_array( - Nullifier::deserialize, - [Nullifier::empty(); MAX_NULLIFIERS_PER_CALL], - ), - l2_to_l1_msgs: reader.read_struct_array( - L2ToL1Message::deserialize, - [L2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_CALL], - ), - start_side_effect_counter: reader.read() as u32, - end_side_effect_counter: reader.read() as u32, - unencrypted_logs_hashes: reader.read_struct_array( - LogHash::deserialize, - [LogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_CALL], - ), - historical_header: reader.read_struct(Header::deserialize), - global_variables: reader.read_struct(GlobalVariables::deserialize), - prover_address: reader.read_struct(AztecAddress::deserialize), - revert_code: reader.read() as u8, - start_gas_left: reader.read_struct(Gas::deserialize), - end_gas_left: reader.read_struct(Gas::deserialize), - transaction_fee: reader.read(), - }; - - reader.finish(); - inputs - } -} - -impl Empty for PublicCircuitPublicInputs { - fn empty() -> Self { - PublicCircuitPublicInputs { - call_context: CallContext::empty(), - args_hash: 0, - returns_hash: 0, - note_hash_read_requests: [ - TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_CALL - ], - nullifier_read_requests: [ReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_CALL], - nullifier_non_existent_read_requests: [ - ReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL - ], - l1_to_l2_msg_read_requests: [ - TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL - ], - contract_storage_update_requests: [ - StorageUpdateRequest::empty(); MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL - ], - contract_storage_reads: [StorageRead::empty(); MAX_PUBLIC_DATA_READS_PER_CALL], - public_call_requests: [PublicInnerCallRequest::empty(); MAX_ENQUEUED_CALLS_PER_CALL], - note_hashes: [NoteHash::empty(); MAX_NOTE_HASHES_PER_CALL], - nullifiers: [Nullifier::empty(); MAX_NULLIFIERS_PER_CALL], - l2_to_l1_msgs: [L2ToL1Message::empty(); MAX_L2_TO_L1_MSGS_PER_CALL], - start_side_effect_counter: 0 as u32, - end_side_effect_counter: 0 as u32, - unencrypted_logs_hashes: [LogHash::empty(); MAX_UNENCRYPTED_LOGS_PER_CALL], - historical_header: Header::empty(), - global_variables: GlobalVariables::empty(), - prover_address: AztecAddress::zero(), - revert_code: 0 as u8, - start_gas_left: Gas::empty(), - end_gas_left: Gas::empty(), - transaction_fee: 0, - } - } -} - -#[test] -fn serialization_of_empty() { - let pcpi = PublicCircuitPublicInputs::empty(); - let serialized = pcpi.serialize(); - let deserialized = PublicCircuitPublicInputs::deserialize(serialized); - assert(pcpi.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_read.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_read.nr deleted file mode 100644 index f2dc6e6d739b..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_read.nr +++ /dev/null @@ -1,57 +0,0 @@ -use crate::{ - abis::side_effect::Ordered, - constants::PUBLIC_DATA_READ_LENGTH, - traits::{Deserialize, Empty, Serialize}, -}; - -pub struct PublicDataRead { - pub leaf_slot: Field, - pub value: Field, - pub counter: u32, -} - -impl Eq for PublicDataRead { - fn eq(self, other: PublicDataRead) -> bool { - (other.leaf_slot == self.leaf_slot) - & (other.value == self.value) - & (other.counter == self.counter) - } -} - -impl Empty for PublicDataRead { - fn empty() -> Self { - Self { leaf_slot: 0, value: 0, counter: 0 } - } -} - -impl Ordered for PublicDataRead { - fn counter(self) -> u32 { - self.counter - } -} - -impl PublicDataRead { - pub fn is_empty(self) -> bool { - (self.leaf_slot == 0) & (self.value == 0) & (self.counter == 0) - } -} - -impl Serialize for PublicDataRead { - fn serialize(self) -> [Field; PUBLIC_DATA_READ_LENGTH] { - [self.leaf_slot, self.value, self.counter as Field] - } -} - -impl Deserialize for PublicDataRead { - fn deserialize(fields: [Field; PUBLIC_DATA_READ_LENGTH]) -> Self { - PublicDataRead { leaf_slot: fields[0], value: fields[1], counter: fields[2] as u32 } - } -} - -#[test] -fn serialization_of_empty() { - let item = PublicDataRead::empty(); - let serialized = item.serialize(); - let deserialized = PublicDataRead::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_update_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_update_request.nr deleted file mode 100644 index 1cbcc3f6a56f..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_update_request.nr +++ /dev/null @@ -1,67 +0,0 @@ -use crate::{ - abis::side_effect::Ordered, - constants::PUBLIC_DATA_UPDATE_REQUEST_LENGTH, - data::public_data_tree_leaf::PublicDataTreeLeaf, - traits::{Deserialize, Empty, Serialize}, -}; - -// TODO: Rename to PublicDataWrite -pub struct PublicDataUpdateRequest { - pub leaf_slot: Field, - pub new_value: Field, - pub counter: u32, -} - -impl Ordered for PublicDataUpdateRequest { - fn counter(self) -> u32 { - self.counter - } -} - -impl Eq for PublicDataUpdateRequest { - fn eq(self, update_request: PublicDataUpdateRequest) -> bool { - (update_request.leaf_slot == self.leaf_slot) & (update_request.new_value == self.new_value) - } -} - -impl Empty for PublicDataUpdateRequest { - fn empty() -> Self { - Self { leaf_slot: 0, new_value: 0, counter: 0 } - } -} - -impl From for PublicDataTreeLeaf { - fn from(update_request: PublicDataUpdateRequest) -> PublicDataTreeLeaf { - PublicDataTreeLeaf { slot: update_request.leaf_slot, value: update_request.new_value } - } -} - -impl PublicDataUpdateRequest { - pub fn is_empty(self) -> bool { - (self.leaf_slot == 0) & (self.new_value == 0) - } -} - -impl Serialize for PublicDataUpdateRequest { - fn serialize(self) -> [Field; PUBLIC_DATA_UPDATE_REQUEST_LENGTH] { - [self.leaf_slot, self.new_value, self.counter as Field] - } -} - -impl Deserialize for PublicDataUpdateRequest { - fn deserialize(fields: [Field; PUBLIC_DATA_UPDATE_REQUEST_LENGTH]) -> PublicDataUpdateRequest { - PublicDataUpdateRequest { - leaf_slot: fields[0], - new_value: fields[1], - counter: fields[2] as u32, - } - } -} - -#[test] -fn serialization_of_empty() { - let item = PublicDataUpdateRequest::empty(); - let serialized = item.serialize(); - let deserialized = PublicDataUpdateRequest::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_write.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_write.nr index 1465aa16055a..9a1d57e262c3 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_write.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_data_write.nr @@ -1,12 +1,4 @@ -use crate::{ - abis::{ - public_data_read::PublicDataRead, - public_data_update_request::PublicDataUpdateRequest, - side_effect::{Inner, Ordered, Overridable, Readable}, - }, - constants::PUBLIC_DATA_WRITE_LENGTH, - traits::{Deserialize, Empty, Serialize}, -}; +use crate::{constants::PUBLIC_DATA_WRITE_LENGTH, traits::{Deserialize, Empty, Serialize}}; pub struct PublicDataWrite { leaf_slot: Field, @@ -37,57 +29,6 @@ impl Deserialize for PublicDataWrite { } } -// TODO: To be deprecated. -pub struct OverridablePublicDataWrite { - write: PublicDataUpdateRequest, - override_counter: u32, -} - -impl Eq for OverridablePublicDataWrite { - fn eq(self, other: OverridablePublicDataWrite) -> bool { - (other.write == self.write) & (other.override_counter == self.override_counter) - } -} - -impl Empty for OverridablePublicDataWrite { - fn empty() -> Self { - Self { write: PublicDataUpdateRequest::empty(), override_counter: 0 } - } -} - -impl Ordered for OverridablePublicDataWrite { - fn counter(self) -> u32 { - self.write.counter() - } -} - -impl Readable for OverridablePublicDataWrite { - fn assert_match_read_request(self, read_request: PublicDataRead) { - assert_eq( - self.write.leaf_slot, - read_request.leaf_slot, - "leaf_slot in OverridablePublicDataWrite does not match read request", - ); - assert_eq( - self.write.new_value, - read_request.value, - "value in OverridablePublicDataWrite does not match read request", - ); - } -} - -impl Overridable for OverridablePublicDataWrite { - fn override_counter(self) -> u32 { - self.override_counter - } -} - -impl Inner for OverridablePublicDataWrite { - fn inner(self) -> PublicDataUpdateRequest { - self.write - } -} - #[test] fn serialization_of_empty_public_data_write() { let item = PublicDataWrite::empty(); diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_inner_call_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_inner_call_request.nr deleted file mode 100644 index 801df9e64f11..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_inner_call_request.nr +++ /dev/null @@ -1,64 +0,0 @@ -use crate::{ - abis::{public_call_stack_item_compressed::PublicCallStackItemCompressed, side_effect::Ordered}, - constants::PUBLIC_INNER_CALL_REQUEST_LENGTH, - traits::{Deserialize, Empty, Serialize}, - utils::reader::Reader, -}; - -// TODO(#9594): To be deprecated. -pub struct PublicInnerCallRequest { - item: PublicCallStackItemCompressed, - counter: u32, -} - -impl Ordered for PublicInnerCallRequest { - fn counter(self) -> u32 { - self.counter - } -} - -impl Eq for PublicInnerCallRequest { - fn eq(self, other: PublicInnerCallRequest) -> bool { - (other.item == self.item) & (other.counter == self.counter) - } -} - -impl Empty for PublicInnerCallRequest { - fn empty() -> Self { - PublicInnerCallRequest { item: PublicCallStackItemCompressed::empty(), counter: 0 } - } -} - -impl Serialize for PublicInnerCallRequest { - fn serialize(self) -> [Field; PUBLIC_INNER_CALL_REQUEST_LENGTH] { - let mut fields: BoundedVec = BoundedVec::new(); - - fields.extend_from_array(self.item.serialize()); - fields.push(self.counter as Field); - - assert_eq(fields.len(), PUBLIC_INNER_CALL_REQUEST_LENGTH); - - fields.storage() - } -} - -impl Deserialize for PublicInnerCallRequest { - fn deserialize(fields: [Field; PUBLIC_INNER_CALL_REQUEST_LENGTH]) -> PublicInnerCallRequest { - let mut reader = Reader::new(fields); - - let request = PublicInnerCallRequest { - item: reader.read_struct(PublicCallStackItemCompressed::deserialize), - counter: reader.read_u32(), - }; - reader.finish(); - request - } -} - -#[test] -fn serialization_of_empty() { - let item = PublicInnerCallRequest::empty(); - let serialized = item.serialize(); - let deserialized = PublicInnerCallRequest::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_data.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_data.nr deleted file mode 100644 index e65ee0473290..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/public_kernel_data.nr +++ /dev/null @@ -1,47 +0,0 @@ -use crate::{ - abis::kernel_circuit_public_inputs::PublicKernelCircuitPublicInputs, - constants::{TUBE_VK_INDEX, VK_TREE_HEIGHT}, - merkle_tree::membership::check_membership, - proof::{ - recursive_proof::NestedRecursiveProof, traits::Verifiable, - verification_key::HonkVerificationKey, - }, - utils::arrays::find_index_hint, -}; - -pub struct PublicKernelData { - pub public_inputs: PublicKernelCircuitPublicInputs, - pub proof: NestedRecursiveProof, - pub vk: HonkVerificationKey, - pub vk_index: u32, - pub vk_path: [Field; VK_TREE_HEIGHT], -} - -impl Verifiable for PublicKernelData { - fn verify(self) { - let inputs = PublicKernelCircuitPublicInputs::serialize(self.public_inputs); - std::verify_proof(self.vk.key, self.proof.fields, inputs, self.vk.hash); - } -} - -impl PublicKernelData { - fn validate_in_vk_tree(self, allowed_indices: [u32; N]) { - self.vk.check_hash(); - - let index_hint = - unsafe { find_index_hint(allowed_indices, |index: u32| index == self.vk_index) }; - assert(index_hint < N, "Invalid vk index"); - assert_eq(allowed_indices[index_hint], self.vk_index, "Invalid vk index"); - - // TODO(#7410) Remove the exception for the tube index - assert( - check_membership( - self.vk.hash, - self.vk_index as Field, - self.vk_path, - self.public_inputs.constants.vk_tree_root, - ) - | (self.vk_index == TUBE_VK_INDEX), - ); - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/side_effect.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/side_effect.nr index a0ca4da6a8a2..ca005878c92b 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/side_effect.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/side_effect.nr @@ -33,11 +33,6 @@ pub trait Readable { fn assert_match_read_request(self, read_request: T); } -pub trait Overridable { - // The counter of the next side effect that's overriding the current side effect. - fn override_counter(self) -> u32; -} - pub trait Inner { fn inner(self) -> T; } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/tree_leaf_read_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/tree_leaf_read_request.nr deleted file mode 100644 index 97076df51e80..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/tree_leaf_read_request.nr +++ /dev/null @@ -1,38 +0,0 @@ -use crate::{constants::TREE_LEAF_READ_REQUEST_LENGTH, traits::{Deserialize, Empty, Serialize}}; - -pub struct TreeLeafReadRequest { - pub value: Field, - pub leaf_index: Field, -} - -impl Eq for TreeLeafReadRequest { - fn eq(self, other: TreeLeafReadRequest) -> bool { - (self.value == other.value) & (self.leaf_index == other.leaf_index) - } -} - -impl Empty for TreeLeafReadRequest { - fn empty() -> Self { - TreeLeafReadRequest { value: 0, leaf_index: 0 } - } -} - -impl Serialize for TreeLeafReadRequest { - fn serialize(self) -> [Field; TREE_LEAF_READ_REQUEST_LENGTH] { - [self.value, self.leaf_index] - } -} - -impl Deserialize for TreeLeafReadRequest { - fn deserialize(values: [Field; TREE_LEAF_READ_REQUEST_LENGTH]) -> Self { - Self { value: values[0], leaf_index: values[1] } - } -} - -#[test] -fn serialization_of_empty_read() { - let item = TreeLeafReadRequest::empty(); - let serialized = item.serialize(); - let deserialized = TreeLeafReadRequest::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/mod.nr index d6cf2668f072..957c22423f27 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/mod.nr @@ -2,8 +2,6 @@ pub mod key_validation_request; pub mod key_validation_request_and_generator; pub mod private_validation_requests; pub mod private_validation_requests_builder; -pub mod public_validation_requests; -pub mod public_validation_requests_builder; pub mod rollup_validation_requests; pub mod scoped_key_validation_request_and_generator; @@ -11,7 +9,5 @@ pub use key_validation_request::KeyValidationRequest; pub use key_validation_request_and_generator::KeyValidationRequestAndGenerator; pub use private_validation_requests::PrivateValidationRequests; pub use private_validation_requests_builder::PrivateValidationRequestsBuilder; -pub use public_validation_requests::{PublicValidationRequestArrayLengths, PublicValidationRequests}; -pub use public_validation_requests_builder::PublicValidationRequestsBuilder; pub use rollup_validation_requests::RollupValidationRequests; pub use scoped_key_validation_request_and_generator::ScopedKeyValidationRequestAndGenerator; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests.nr deleted file mode 100644 index 165249091fc3..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests.nr +++ /dev/null @@ -1,216 +0,0 @@ -use crate::{ - abis::{ - public_data_read::PublicDataRead, read_request::ScopedReadRequest, - tree_leaf_read_request::TreeLeafReadRequest, - validation_requests::rollup_validation_requests::RollupValidationRequests, - }, - constants::{ - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_READS_PER_TX, NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS, - PUBLIC_VALIDATION_REQUESTS_LENGTH, - }, - traits::{Deserialize, Empty, Serialize}, - utils::{arrays::array_length, reader::Reader}, -}; - -pub struct PublicValidationRequests { - pub for_rollup: RollupValidationRequests, - pub note_hash_read_requests: [TreeLeafReadRequest; MAX_NOTE_HASH_READ_REQUESTS_PER_TX], - pub nullifier_read_requests: [ScopedReadRequest; MAX_NULLIFIER_READ_REQUESTS_PER_TX], - pub nullifier_non_existent_read_requests: [ScopedReadRequest; MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX], - pub l1_to_l2_msg_read_requests: [TreeLeafReadRequest; MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX], - pub public_data_reads: [PublicDataRead; MAX_PUBLIC_DATA_READS_PER_TX], -} - -impl Serialize for PublicValidationRequests { - fn serialize(self) -> [Field; PUBLIC_VALIDATION_REQUESTS_LENGTH] { - let mut fields: BoundedVec = BoundedVec::new(); - - fields.extend_from_array(self.for_rollup.serialize()); - - for i in 0..self.note_hash_read_requests.len() { - fields.extend_from_array(self.note_hash_read_requests[i].serialize()); - } - - for i in 0..self.nullifier_read_requests.len() { - fields.extend_from_array(self.nullifier_read_requests[i].serialize()); - } - - for i in 0..self.nullifier_non_existent_read_requests.len() { - fields.extend_from_array(self.nullifier_non_existent_read_requests[i].serialize()); - } - - for i in 0..self.l1_to_l2_msg_read_requests.len() { - fields.extend_from_array(self.l1_to_l2_msg_read_requests[i].serialize()); - } - - for i in 0..self.public_data_reads.len() { - fields.extend_from_array(self.public_data_reads[i].serialize()); - } - - assert_eq(fields.len(), PUBLIC_VALIDATION_REQUESTS_LENGTH); - - fields.storage() - } -} - -impl Deserialize for PublicValidationRequests { - fn deserialize(serialized: [Field; PUBLIC_VALIDATION_REQUESTS_LENGTH]) -> Self { - // TODO(#4390): This should accept a reader ^ to avoid copying data. - let mut reader = Reader::new(serialized); - let item = Self { - for_rollup: reader.read_struct(RollupValidationRequests::deserialize), - note_hash_read_requests: reader.read_struct_array( - TreeLeafReadRequest::deserialize, - [TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX], - ), - nullifier_read_requests: reader.read_struct_array( - ScopedReadRequest::deserialize, - [ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX], - ), - nullifier_non_existent_read_requests: reader.read_struct_array( - ScopedReadRequest::deserialize, - [ScopedReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX], - ), - l1_to_l2_msg_read_requests: reader.read_struct_array( - TreeLeafReadRequest::deserialize, - [TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX], - ), - public_data_reads: reader.read_struct_array( - PublicDataRead::deserialize, - [PublicDataRead::empty(); MAX_PUBLIC_DATA_READS_PER_TX], - ), - }; - - reader.finish(); - item - } -} - -impl Empty for PublicValidationRequests { - fn empty() -> Self { - PublicValidationRequests { - for_rollup: RollupValidationRequests::empty(), - note_hash_read_requests: [ - TreeLeafReadRequest::empty(); MAX_NOTE_HASH_READ_REQUESTS_PER_TX - ], - nullifier_read_requests: [ - ScopedReadRequest::empty(); MAX_NULLIFIER_READ_REQUESTS_PER_TX - ], - nullifier_non_existent_read_requests: [ - ScopedReadRequest::empty(); MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX - ], - l1_to_l2_msg_read_requests: [ - TreeLeafReadRequest::empty(); MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX - ], - public_data_reads: [PublicDataRead::empty(); MAX_PUBLIC_DATA_READS_PER_TX], - } - } -} - -impl Eq for PublicValidationRequests { - fn eq(self, other: Self) -> bool { - (self.for_rollup.eq(other.for_rollup)) - & (self.note_hash_read_requests == other.note_hash_read_requests) - & (self.nullifier_read_requests == other.nullifier_read_requests) - & ( - self.nullifier_non_existent_read_requests - == other.nullifier_non_existent_read_requests - ) - & (self.l1_to_l2_msg_read_requests == other.l1_to_l2_msg_read_requests) - & (self.public_data_reads == other.public_data_reads) - } -} - -pub struct PublicValidationRequestArrayLengths { - note_hash_read_requests: u32, - nullifier_read_requests: u32, - nullifier_non_existent_read_requests: u32, - l1_to_l2_msg_read_requests: u32, - public_data_reads: u32, -} - -impl PublicValidationRequestArrayLengths { - pub fn new(requests: PublicValidationRequests) -> Self { - PublicValidationRequestArrayLengths { - note_hash_read_requests: array_length(requests.note_hash_read_requests), - nullifier_read_requests: array_length(requests.nullifier_read_requests), - nullifier_non_existent_read_requests: array_length( - requests.nullifier_non_existent_read_requests, - ), - l1_to_l2_msg_read_requests: array_length(requests.l1_to_l2_msg_read_requests), - public_data_reads: array_length(requests.public_data_reads), - } - } -} - -impl Empty for PublicValidationRequestArrayLengths { - fn empty() -> Self { - PublicValidationRequestArrayLengths { - note_hash_read_requests: 0, - nullifier_read_requests: 0, - nullifier_non_existent_read_requests: 0, - l1_to_l2_msg_read_requests: 0, - public_data_reads: 0, - } - } -} - -impl Eq for PublicValidationRequestArrayLengths { - fn eq(self, other: Self) -> bool { - (self.note_hash_read_requests == other.note_hash_read_requests) - & (self.nullifier_read_requests == other.nullifier_read_requests) - & ( - self.nullifier_non_existent_read_requests - == other.nullifier_non_existent_read_requests - ) - & (self.l1_to_l2_msg_read_requests == other.l1_to_l2_msg_read_requests) - & (self.public_data_reads == other.public_data_reads) - } -} - -impl Serialize for PublicValidationRequestArrayLengths { - fn serialize(self) -> [Field; NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS] { - let mut fields: BoundedVec = BoundedVec::new(); - - fields.push(self.note_hash_read_requests as Field); - fields.push(self.nullifier_read_requests as Field); - fields.push(self.nullifier_non_existent_read_requests as Field); - fields.push(self.l1_to_l2_msg_read_requests as Field); - fields.push(self.public_data_reads as Field); - - fields.storage() - } -} - -impl Deserialize for PublicValidationRequestArrayLengths { - fn deserialize(serialized: [Field; NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS]) -> Self { - let mut reader = Reader::new(serialized); - let item = Self { - note_hash_read_requests: reader.read_u32(), - nullifier_read_requests: reader.read_u32(), - nullifier_non_existent_read_requests: reader.read_u32(), - l1_to_l2_msg_read_requests: reader.read_u32(), - public_data_reads: reader.read_u32(), - }; - reader.finish(); - item - } -} - -#[test] -fn serialization_of_empty() { - let item = PublicValidationRequests::empty(); - let serialized = item.serialize(); - let deserialized = PublicValidationRequests::deserialize(serialized); - assert(item.eq(deserialized)); -} - -#[test] -fn serialization_of_empty_array_lengths() { - let item = PublicValidationRequestArrayLengths::empty(); - let serialized = item.serialize(); - let deserialized = PublicValidationRequestArrayLengths::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests_builder.nr deleted file mode 100644 index 30f38166770d..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/abis/validation_requests/public_validation_requests_builder.nr +++ /dev/null @@ -1,71 +0,0 @@ -use crate::{ - abis::{ - max_block_number::MaxBlockNumber, - public_data_read::PublicDataRead, - read_request::ScopedReadRequest, - tree_leaf_read_request::TreeLeafReadRequest, - validation_requests::{ - public_validation_requests::PublicValidationRequests, - rollup_validation_requests::RollupValidationRequests, - }, - }, - constants::{ - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_READS_PER_TX, - }, - traits::Empty, - utils::arrays::array_to_bounded_vec, -}; - -pub struct PublicValidationRequestsBuilder { - max_block_number: MaxBlockNumber, - note_hash_read_requests: BoundedVec, - nullifier_read_requests: BoundedVec, - nullifier_non_existent_read_requests: BoundedVec, - public_data_reads: BoundedVec, - l1_to_l2_msg_read_requests: BoundedVec, -} - -impl PublicValidationRequestsBuilder { - pub fn new(requests: PublicValidationRequests) -> Self { - PublicValidationRequestsBuilder { - max_block_number: requests.for_rollup.max_block_number, - note_hash_read_requests: array_to_bounded_vec(requests.note_hash_read_requests), - nullifier_read_requests: array_to_bounded_vec(requests.nullifier_read_requests), - nullifier_non_existent_read_requests: array_to_bounded_vec( - requests.nullifier_non_existent_read_requests, - ), - public_data_reads: array_to_bounded_vec(requests.public_data_reads), - l1_to_l2_msg_read_requests: array_to_bounded_vec(requests.l1_to_l2_msg_read_requests), - } - } - - pub fn finish(self) -> PublicValidationRequests { - PublicValidationRequests { - for_rollup: self.for_rollup(), - note_hash_read_requests: self.note_hash_read_requests.storage(), - nullifier_read_requests: self.nullifier_read_requests.storage(), - nullifier_non_existent_read_requests: self.nullifier_non_existent_read_requests.storage(), - public_data_reads: self.public_data_reads.storage(), - l1_to_l2_msg_read_requests: self.l1_to_l2_msg_read_requests.storage(), - } - } - - pub fn for_rollup(self) -> RollupValidationRequests { - RollupValidationRequests { max_block_number: self.max_block_number } - } -} - -impl Empty for PublicValidationRequestsBuilder { - fn empty() -> Self { - PublicValidationRequestsBuilder { - max_block_number: MaxBlockNumber::empty(), - note_hash_read_requests: BoundedVec::new(), - nullifier_read_requests: BoundedVec::new(), - nullifier_non_existent_read_requests: BoundedVec::new(), - public_data_reads: BoundedVec::new(), - l1_to_l2_msg_read_requests: BoundedVec::new(), - } - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/mod.nr deleted file mode 100644 index d4562b82bd79..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/mod.nr +++ /dev/null @@ -1,2 +0,0 @@ -pub mod storage_read; -pub mod storage_update_request; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_read.nr b/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_read.nr deleted file mode 100644 index ac94988b6ea5..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_read.nr +++ /dev/null @@ -1,51 +0,0 @@ -use crate::{constants::CONTRACT_STORAGE_READ_LENGTH, traits::{Deserialize, Empty, Serialize}}; - -pub struct StorageRead { - pub storage_slot: Field, - pub current_value: Field, - pub counter: u32, -} - -impl Eq for StorageRead { - fn eq(self, other: Self) -> bool { - (self.storage_slot == other.storage_slot) - & (self.current_value == other.current_value) - & (self.current_value == other.current_value) - } -} - -impl Empty for StorageRead { - fn empty() -> Self { - Self { storage_slot: 0, current_value: 0, counter: 0 } - } -} - -impl Serialize for StorageRead { - fn serialize(self) -> [Field; CONTRACT_STORAGE_READ_LENGTH] { - [self.storage_slot, self.current_value, self.counter as Field] - } -} - -impl Deserialize for StorageRead { - fn deserialize(serialized: [Field; CONTRACT_STORAGE_READ_LENGTH]) -> Self { - Self { - storage_slot: serialized[0], - current_value: serialized[1], - counter: serialized[2] as u32, - } - } -} - -impl StorageRead { - pub fn is_empty(self) -> bool { - (self.storage_slot == 0) & (self.current_value == 0) & (self.counter == 0) - } -} - -#[test] -fn serialization_of_empty() { - let item = StorageRead::empty(); - let serialized = item.serialize(); - let deserialized = StorageRead::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_update_request.nr b/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_update_request.nr deleted file mode 100644 index 3ab1442f1a5e..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/contrakt/storage_update_request.nr +++ /dev/null @@ -1,52 +0,0 @@ -use crate::{ - constants::CONTRACT_STORAGE_UPDATE_REQUEST_LENGTH, - traits::{Deserialize, Empty, Serialize}, -}; - -pub struct StorageUpdateRequest { - pub storage_slot: Field, - pub new_value: Field, - pub counter: u32, -} - -impl Eq for StorageUpdateRequest { - fn eq(self, request: Self) -> bool { - (request.storage_slot == self.storage_slot) & (request.new_value == self.new_value) - } -} - -impl Empty for StorageUpdateRequest { - fn empty() -> Self { - StorageUpdateRequest { storage_slot: 0, new_value: 0, counter: 0 } - } -} - -impl Serialize for StorageUpdateRequest { - fn serialize(self) -> [Field; CONTRACT_STORAGE_UPDATE_REQUEST_LENGTH] { - [self.storage_slot, self.new_value, self.counter as Field] - } -} - -impl Deserialize for StorageUpdateRequest { - fn deserialize(serialized: [Field; CONTRACT_STORAGE_UPDATE_REQUEST_LENGTH]) -> Self { - StorageUpdateRequest { - storage_slot: serialized[0], - new_value: serialized[1], - counter: serialized[2] as u32, - } - } -} - -impl StorageUpdateRequest { - pub fn is_empty(self) -> bool { - self.storage_slot == 0 - } -} - -#[test] -fn serialization_of_empty() { - let item = StorageUpdateRequest::empty(); - let serialized = item.serialize(); - let deserialized = StorageUpdateRequest::deserialize(serialized); - assert(item.eq(deserialized)); -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/mod.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/mod.nr index a450152ea7e3..bc017a6e2ef0 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/mod.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/data/mod.nr @@ -1,10 +1,8 @@ pub mod public_data_hint; -pub mod public_data_leaf_hint; pub mod public_data_tree_leaf; pub mod public_data_tree_leaf_preimage; pub mod hash; pub use public_data_hint::PublicDataHint; -pub use public_data_leaf_hint::PublicDataLeafHint; -pub use public_data_tree_leaf::{OverridablePublicDataTreeLeaf, PublicDataTreeLeaf}; +pub use public_data_tree_leaf::PublicDataTreeLeaf; pub use public_data_tree_leaf_preimage::PublicDataTreeLeafPreimage; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_hint.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_hint.nr index 6adec664620e..f2371ea78710 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_hint.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_hint.nr @@ -8,7 +8,6 @@ use crate::{ pub struct PublicDataHint { leaf_slot: Field, value: Field, - override_counter: u32, membership_witness: MembershipWitness, leaf_preimage: PublicDataTreeLeafPreimage, } @@ -44,7 +43,6 @@ impl Empty for PublicDataHint { PublicDataHint { leaf_slot: 0, value: 0, - override_counter: 0, membership_witness: MembershipWitness::empty(), leaf_preimage: PublicDataTreeLeafPreimage::empty(), } diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_leaf_hint.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_leaf_hint.nr deleted file mode 100644 index 7bbc6e2c6592..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_leaf_hint.nr +++ /dev/null @@ -1,19 +0,0 @@ -use crate::{ - constants::PUBLIC_DATA_TREE_HEIGHT, - data::public_data_tree_leaf_preimage::PublicDataTreeLeafPreimage, - merkle_tree::MembershipWitness, traits::Empty, -}; - -pub struct PublicDataLeafHint { - preimage: PublicDataTreeLeafPreimage, - membership_witness: MembershipWitness, -} - -impl Empty for PublicDataLeafHint { - fn empty() -> Self { - PublicDataLeafHint { - preimage: PublicDataTreeLeafPreimage::empty(), - membership_witness: MembershipWitness::empty(), - } - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf.nr b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf.nr index a65c295d8ed2..e97a21614160 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/data/public_data_tree_leaf.nr @@ -1,7 +1,4 @@ -use crate::{ - abis::{public_data_read::PublicDataRead, side_effect::{Overridable, Readable}}, - traits::Empty, -}; +use crate::traits::Empty; pub struct PublicDataTreeLeaf { pub slot: Field, @@ -25,35 +22,3 @@ impl PublicDataTreeLeaf { (self.slot == 0) & (self.value == 0) } } - -pub struct OverridablePublicDataTreeLeaf { - leaf: PublicDataTreeLeaf, - override_counter: u32, -} - -impl Empty for OverridablePublicDataTreeLeaf { - fn empty() -> Self { - OverridablePublicDataTreeLeaf { leaf: PublicDataTreeLeaf::empty(), override_counter: 0 } - } -} - -impl Readable for OverridablePublicDataTreeLeaf { - fn assert_match_read_request(self, read_request: PublicDataRead) { - assert_eq( - self.leaf.slot, - read_request.leaf_slot, - "leaf_slot in OverridablePublicDataTreeLeaf does not match read request", - ); - assert_eq( - self.leaf.value, - read_request.value, - "value in OverridablePublicDataTreeLeaf does not match read request", - ); - } -} - -impl Overridable for OverridablePublicDataTreeLeaf { - fn override_counter(self) -> u32 { - self.override_counter - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr b/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr index 84004c7c2f49..4aee1c46d571 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/hash.nr @@ -10,7 +10,6 @@ use crate::{ constants::{ FUNCTION_TREE_HEIGHT, GENERATOR_INDEX__NOTE_HASH_NONCE, GENERATOR_INDEX__OUTER_NULLIFIER, GENERATOR_INDEX__SILOED_NOTE_HASH, GENERATOR_INDEX__UNIQUE_NOTE_HASH, - MAX_CONTRACT_CLASS_LOGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, }, merkle_tree::root::root_from_sibling_path, messaging::l2_to_l1_message::{L2ToL1Message, ScopedL2ToL1Message}, diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/lib.nr b/noir-projects/noir-protocol-circuits/crates/types/src/lib.nr index 25274b49b48f..d5ead85a57f2 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/lib.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/lib.nr @@ -31,6 +31,5 @@ pub mod meta; pub mod indexed_tagging_secret; pub use abis::kernel_circuit_public_inputs::{ - KernelCircuitPublicInputs, PrivateKernelCircuitPublicInputs, PublicKernelCircuitPublicInputs, - VMCircuitPublicInputs, + KernelCircuitPublicInputs, PrivateKernelCircuitPublicInputs, }; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixture_builder.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixture_builder.nr index 96fd4a771d66..a2bf6a855d60 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixture_builder.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixture_builder.nr @@ -2,20 +2,17 @@ use crate::{ abis::{ accumulated_data::{ CombinedAccumulatedData, PrivateAccumulatedData, PrivateAccumulatedDataBuilder, - PrivateToPublicAccumulatedData, PublicAccumulatedData, - PublicAccumulatedDataArrayLengths, PublicAccumulatedDataBuilder, + PrivateToPublicAccumulatedData, }, call_context::CallContext, combined_constant_data::CombinedConstantData, - enqueued_call_data::{EnqueuedCallData, Proof}, function_data::FunctionData, gas::Gas, gas_settings::GasSettings, global_variables::GlobalVariables, kernel_circuit_public_inputs::{ KernelCircuitPublicInputs, PrivateKernelCircuitPublicInputs, - PrivateToPublicKernelCircuitPublicInputs, PublicKernelCircuitPublicInputs, - VMCircuitPublicInputs, + PrivateToPublicKernelCircuitPublicInputs, }, log_hash::{EncryptedLogHash, LogHash, NoteLogHash, ScopedEncryptedLogHash, ScopedLogHash}, max_block_number::MaxBlockNumber, @@ -26,33 +23,25 @@ use crate::{ private_kernel::private_call_data::PrivateCallData, private_kernel_data::PrivateKernelData, public_call_request::PublicCallRequest, - public_data_read::PublicDataRead, - public_data_update_request::PublicDataUpdateRequest, public_data_write::PublicDataWrite, - public_inner_call_request::PublicInnerCallRequest, - public_kernel_data::PublicKernelData, read_request::{ReadRequest, ScopedReadRequest}, side_effect::Counted, - tree_leaf_read_request::TreeLeafReadRequest, tx_constant_data::TxConstantData, validation_requests::{ KeyValidationRequest, KeyValidationRequestAndGenerator, PrivateValidationRequests, - PublicValidationRequestArrayLengths, PublicValidationRequests, RollupValidationRequests, - ScopedKeyValidationRequestAndGenerator, + RollupValidationRequests, ScopedKeyValidationRequestAndGenerator, }, }, address::{AztecAddress, EthAddress, SaltedInitializationHash}, constants::{ CLIENT_IVC_VERIFICATION_KEY_LENGTH_IN_FIELDS, FUNCTION_TREE_HEIGHT, MAX_CONTRACT_CLASS_LOGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, MAX_ENQUEUED_CALLS_PER_TX, - MAX_FIELD_VALUE, MAX_KEY_VALIDATION_REQUESTS_PER_TX, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_L2_TO_L1_MSGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_NULLIFIERS_PER_TX, MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, MAX_PUBLIC_DATA_READS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX, - PRIVATE_CALL_REQUEST_LENGTH, PROTOCOL_CONTRACT_TREE_HEIGHT, PUBLIC_CALL_REQUEST_LENGTH, - VK_TREE_HEIGHT, + MAX_FIELD_VALUE, MAX_KEY_VALIDATION_REQUESTS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, + MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NOTE_HASHES_PER_TX, + MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, + MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, + MAX_UNENCRYPTED_LOGS_PER_TX, PRIVATE_CALL_REQUEST_LENGTH, PROTOCOL_CONTRACT_TREE_HEIGHT, + PUBLIC_CALL_REQUEST_LENGTH, VK_TREE_HEIGHT, }, hash::{ compute_l2_to_l1_hash, compute_siloed_nullifier, compute_tx_logs_hash, @@ -127,22 +116,16 @@ pub struct FixtureBuilder { pub unencrypted_log_preimages_length: Field, pub contract_class_log_preimages_length: Field, pub public_data_writes: BoundedVec, - pub public_data_update_requests: BoundedVec, pub private_call_requests: BoundedVec, pub public_call_requests: BoundedVec, MAX_ENQUEUED_CALLS_PER_TX>, - pub public_inner_call_requests: BoundedVec, pub gas_used: Gas, pub revert_code: u8, // Validation requests. pub max_block_number: MaxBlockNumber, pub note_hash_read_requests: BoundedVec, - pub note_hash_tree_leaf_read_requests: BoundedVec, pub nullifier_read_requests: BoundedVec, - pub nullifier_non_existent_read_requests: BoundedVec, - pub l1_to_l2_msg_read_requests: BoundedVec, pub scoped_key_validation_requests_and_generators: BoundedVec, - pub public_data_reads: BoundedVec, pub validation_requests_split_counter: Option, // Function. @@ -277,13 +260,6 @@ impl FixtureBuilder { *self } - pub fn is_public_function(&mut self) -> Self { - let contract_function = fixtures::contract_functions::default_public_function; - self.function_data = contract_function.data; - self.bytecode_hash = contract_function.acir_hash; - *self - } - pub fn is_static_call(&mut self) -> Self { self.is_static_call = true; *self @@ -427,41 +403,6 @@ impl FixtureBuilder { } } - pub fn to_public_accumulated_data_builder(self) -> PublicAccumulatedDataBuilder { - let nullifiers = self.nullifiers.map(|n: ScopedNullifier| n.nullifier); - let note_encrypted_logs_hashes = self.note_encrypted_logs_hashes.map(|l: NoteLogHash| { - LogHash { value: l.value, counter: l.counter, length: l.length } - }); - let encrypted_logs_hashes = self.encrypted_logs_hashes.map(|l: ScopedEncryptedLogHash| { - ScopedLogHash { - log_hash: LogHash { - value: l.log_hash.value, - counter: l.log_hash.counter, - length: l.log_hash.length, - }, - contract_address: l.contract_address, - } - }); - - PublicAccumulatedDataBuilder { - note_hashes: self.note_hashes, - nullifiers, - l2_to_l1_msgs: self.l2_to_l1_msgs, - note_encrypted_logs_hashes, - encrypted_logs_hashes, - unencrypted_logs_hashes: self.unencrypted_logs_hashes, - public_data_update_requests: self.public_data_update_requests, - public_call_stack: self.public_call_requests.map(|r: Counted| { - r.inner - }), - gas_used: self.gas_used, - } - } - - pub fn to_public_accumulated_data(self) -> PublicAccumulatedData { - self.to_public_accumulated_data_builder().finish() - } - pub fn to_private_to_public_accumulated_data(self) -> PrivateToPublicAccumulatedData { PrivateToPublicAccumulatedData { note_hashes: self.note_hashes.storage().map(|n: ScopedNoteHash| n.value()), @@ -577,78 +518,6 @@ impl FixtureBuilder { } } - pub fn to_public_validation_requests(self) -> PublicValidationRequests { - PublicValidationRequests { - for_rollup: self.to_rollup_validation_requests(), - note_hash_read_requests: self.note_hash_tree_leaf_read_requests.storage(), - nullifier_read_requests: self.nullifier_read_requests.storage(), - nullifier_non_existent_read_requests: self.nullifier_non_existent_read_requests.storage(), - public_data_reads: self.public_data_reads.storage(), - l1_to_l2_msg_read_requests: self.l1_to_l2_msg_read_requests.storage(), - } - } - - pub fn to_vm_circuit_public_inputs(self) -> VMCircuitPublicInputs { - VMCircuitPublicInputs { - constants: self.to_constant_data(), - call_request: self.to_public_call_request(), - public_call_stack: subarray(self.public_inner_call_requests.storage()), - previous_validation_request_array_lengths: PublicValidationRequestArrayLengths::empty(), - validation_requests: self.to_public_validation_requests(), - previous_accumulated_data_array_lengths: PublicAccumulatedDataArrayLengths::empty(), - accumulated_data: self.to_public_accumulated_data(), - start_side_effect_counter: self.counter_start, - end_side_effect_counter: self.counter, - start_gas_left: self.start_gas_left, - transaction_fee: self.transaction_fee, - reverted: self.revert_code != 0, - } - } - - pub fn to_enqueued_call_data(self) -> EnqueuedCallData { - EnqueuedCallData { data: self.to_vm_circuit_public_inputs(), proof: Proof {} } - } - - pub fn to_public_kernel_circuit_public_inputs( - self, - revertible: bool, - ) -> PublicKernelCircuitPublicInputs { - // TODO: Split the data using self.min_revertible_side_effect_counter. - let accumulated_data = self.to_public_accumulated_data(); - let end_non_revertible = if revertible { - PublicAccumulatedData::empty() - } else { - accumulated_data - }; - let end = if revertible { - accumulated_data - } else { - PublicAccumulatedData::empty() - }; - - PublicKernelCircuitPublicInputs { - constants: self.to_constant_data(), - validation_requests: self.to_public_validation_requests(), - end_non_revertible, - end, - end_side_effect_counter: self.counter, - public_teardown_call_request: self.public_teardown_call_request, - fee_payer: self.fee_payer, - revert_code: self.revert_code, - } - } - - pub fn to_public_kernel_data(self, revertible: bool) -> PublicKernelData { - let public_inputs = self.to_public_kernel_circuit_public_inputs(revertible); - PublicKernelData { - public_inputs, - proof: self.proof, - vk: self.honk_vk, - vk_index: self.vk_index, - vk_path: self.vk_path, - } - } - pub fn to_rollup_validation_requests(self) -> RollupValidationRequests { RollupValidationRequests { max_block_number: self.max_block_number } } @@ -814,38 +683,6 @@ impl FixtureBuilder { } } - pub fn add_public_data_update_request(&mut self, leaf_slot: Field, value: Field) { - let update_request = - PublicDataUpdateRequest { leaf_slot, new_value: value, counter: self.next_counter() }; - self.public_data_update_requests.push(update_request); - } - - pub fn append_public_data_update_requests(&mut self, num_updates: u32) { - let index_offset = self.public_data_update_requests.len(); - for i in 0..self.public_data_update_requests.max_len() { - if i < num_updates { - let (leaf_slot, value) = self.mock_public_data_write(index_offset + i); - self.add_public_data_update_request(leaf_slot, value); - } - } - } - - pub fn add_public_data_read_request(&mut self, leaf_slot: Field, value: Field) { - self.public_data_reads.push( - PublicDataRead { leaf_slot, value, counter: self.next_counter() }, - ); - } - - pub fn append_public_data_read_requests(&mut self, num_reads: u32) { - let index_offset = self.public_data_reads.len(); - for i in 0..self.public_data_reads.max_len() { - if i < num_reads { - let (leaf_slot, value) = self.mock_public_data_read(index_offset + i); - self.add_public_data_read_request(leaf_slot, value); - } - } - } - pub fn add_read_request_for_pending_note_hash(&mut self, note_hash_index: u32) -> u32 { let read_request_index = self.note_hash_read_requests.len(); let value = self.mock_note_hash_value(note_hash_index); @@ -868,21 +705,6 @@ impl FixtureBuilder { } } - pub fn add_note_hash_tree_leaf_read_requests(&mut self, value: Field, leaf_index: Field) { - let read_request = TreeLeafReadRequest { value, leaf_index }; - self.note_hash_tree_leaf_read_requests.push(read_request); - } - - pub fn append_note_hash_tree_leaf_read_requests(&mut self, num_reads: u32) { - let index_offset = self.note_hash_tree_leaf_read_requests.len(); - for i in 0..self.note_hash_tree_leaf_read_requests.max_len() { - if i < num_reads { - let value = self.mock_note_hash_read_value(index_offset + i); - self.add_note_hash_tree_leaf_read_requests(value, (index_offset + i) as Field); - } - } - } - pub fn add_read_request_for_pending_nullifier(&mut self, nullifier_index: u32) -> u32 { let read_request_index = self.nullifier_read_requests.len(); let nullifier = self.mock_nullifier_value(nullifier_index); @@ -893,13 +715,6 @@ impl FixtureBuilder { read_request_index } - pub fn add_non_existent_read_request_for_nullifier(&mut self, nullifier: Field) { - let read_request = ReadRequest { value: nullifier, counter: self.next_counter() }.scope( - self.contract_address, - ); - self.nullifier_non_existent_read_requests.push(read_request); - } - pub fn append_nullifier_read_requests(&mut self, num_reads: u32) { let index_offset = self.nullifier_read_requests.len(); for i in 0..self.nullifier_read_requests.max_len() { @@ -913,16 +728,6 @@ impl FixtureBuilder { } } - pub fn append_nullifier_non_existent_read_requests(&mut self, num: u32) { - let index_offset = self.nullifier_non_existent_read_requests.len(); - for i in 0..self.nullifier_non_existent_read_requests.max_len() { - if i < num { - let value = self.mock_nullifier_read_value(index_offset + i); - self.add_non_existent_read_request_for_nullifier(value); - } - } - } - pub fn add_request_for_key_validation( &mut self, pk_m: Point, @@ -1268,18 +1073,12 @@ impl Empty for FixtureBuilder { unencrypted_log_preimages_length: 0, contract_class_log_preimages_length: 0, public_data_writes: BoundedVec::new(), - public_data_update_requests: BoundedVec::new(), private_call_requests: BoundedVec::new(), public_call_requests: BoundedVec::new(), - public_inner_call_requests: BoundedVec::new(), max_block_number: MaxBlockNumber::empty(), note_hash_read_requests: BoundedVec::new(), - note_hash_tree_leaf_read_requests: BoundedVec::new(), nullifier_read_requests: BoundedVec::new(), - nullifier_non_existent_read_requests: BoundedVec::new(), - l1_to_l2_msg_read_requests: BoundedVec::new(), scoped_key_validation_requests_and_generators: BoundedVec::new(), - public_data_reads: BoundedVec::new(), validation_requests_split_counter: Option::none(), function_data: FunctionData::empty(), args_hash: 0, diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contract_functions.nr b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contract_functions.nr index 733d8cde55c1..d84418d2e754 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contract_functions.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/tests/fixtures/contract_functions.nr @@ -28,22 +28,6 @@ pub global default_private_function = ContractFunction { }, }; -pub global default_public_function = ContractFunction { - data: FunctionData { selector: FunctionSelector { inner: 3030303 }, is_private: false }, - vk_hash: 0, - acir_hash: 3333, - membership_witness: MembershipWitness { - leaf_index: 2, - sibling_path: [ - 0x27b1d0839a5b23baf12a8d195b18ac288fcf401afb2f70b8a4b529ede5fa9fed, - 0x1204fec45a58f11be9981f153319860aea2ece9152efab01885006e53dd70a79, - 0x0e1ce4f11f4d51a7d3136abbd625315fff3876d322e46ad8401da96f8e43a614, - 0x1a0ca5eecb1430479902264f04e557160a4666fb42bb8b283c6397e3d17ac937, - 0x2a6595890719fef7967c209488728aa5342438ba52058a3c770202f55acf6854, - ], - }, -}; - pub fn get_protocol_contract_function(contract_index: u32) -> ContractFunction { ContractFunction { data: FunctionData { diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays.nr index fdd6a184b54a..638cc76ecce6 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays.nr @@ -1,9 +1,7 @@ pub mod assert_array_appended; pub mod assert_array_prepended; pub mod assert_combined_array; -pub mod assert_combined_sorted_transformed_value_array; pub mod assert_combined_transformed_array; -pub mod assert_deduped_array; pub mod assert_exposed_sorted_transformed_value_array; pub mod assert_sorted_array; pub mod assert_sorted_transformed_value_array; @@ -20,14 +18,9 @@ pub use assert_array_appended::{ }; pub use assert_array_prepended::assert_array_prepended; pub use assert_combined_array::{assert_combined_array, combine_arrays}; -pub use assert_combined_sorted_transformed_value_array::{ - assert_combined_sorted_transformed_value_array_asc, - get_combined_order_hints::{CombinedOrderHint, get_combined_order_hints_asc}, -}; pub use assert_combined_transformed_array::{ assert_combined_transformed_array, combine_and_transform_arrays, }; -pub use assert_deduped_array::{assert_deduped_array, dedupe_array}; pub use assert_exposed_sorted_transformed_value_array::{ assert_exposed_sorted_transformed_value_array, get_order_hints::{get_order_hints_asc, get_order_hints_desc, OrderHint}, diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array.nr deleted file mode 100644 index 4b4e7bd74996..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array.nr +++ /dev/null @@ -1,394 +0,0 @@ -pub mod get_combined_order_hints; - -use crate::{ - abis::side_effect::Ordered, - traits::{Empty, is_empty}, - utils::arrays::{ - array_length, - assert_combined_sorted_transformed_value_array::get_combined_order_hints::{ - CombinedOrderHint, count_private_items, - }, - }, -}; - -fn get_num_private_items(array: [T; N]) -> u32 -where - T: Ordered + Empty + Eq, -{ - let length = unsafe { count_private_items(array) }; - if length != 0 { - let last_private_item = array[length - 1]; - assert(!is_empty(last_private_item) & (last_private_item.counter() == 0)); - } - if length != N { - let first_non_private_item = array[length]; - assert(is_empty(first_non_private_item) | (first_non_private_item.counter() != 0)); - } - length -} - -// original_array(_lt/_gte) must be valid, i.e. validate_array(original_array) == true -// Both arrays come from the previous kernel, so they are guaranteed to be valid, and meet the following conditions: -// - Items with a counter of 0 are placed at the begining of each array. -// - All non-zero counters in original_array_lt must be less than those in original_array_gte. -pub fn assert_combined_sorted_transformed_value_array_asc( - original_array_lt: [T; N], - original_array_gte: [T; N], - sorted_transformed_value_array: [S; N], - is_transformed: fn[Env](T, S) -> bool, - hints: [CombinedOrderHint; N], -) -where - T: Ordered + Empty + Eq, - S: Empty + Eq, -{ - let num_private_lt = get_num_private_items(original_array_lt); - let num_private_gte = get_num_private_items(original_array_gte); - let total_private = num_private_lt + num_private_gte; - let num_lt = array_length(original_array_lt); - let num_gte = array_length(original_array_gte); - let total_non_public_gte = num_lt + num_private_gte; - let total_num = num_lt + num_gte; - - let mut prev_counter = 0; - let mut should_be_private_lt = true; - let mut should_be_private = true; - let mut should_be_public_gte = false; - let mut should_be_empty = false; - for i in 0..N { - should_be_private_lt &= i != num_private_lt; - should_be_private &= i != total_private; - should_be_public_gte |= i == total_non_public_gte; - should_be_empty |= i == total_num; - let hint = hints[i]; - let from_lt = original_array_lt[hint.original_index]; - let from_gte = original_array_gte[hint.original_index]; - let from = if should_be_private_lt { - assert_eq(hint.original_index, i, "items with a counter of 0 should be prepended"); - from_lt - } else if should_be_private { - assert_eq( - hint.original_index, - i - num_private_lt, - "items with a counter of 0 should be prepended", - ); - from_gte - } else if should_be_public_gte { - from_gte - } else { - from_lt - }; - let dest = sorted_transformed_value_array[i]; - let dest_counter = hint.counter; - assert(is_transformed(from, dest), "incorrect transformed value"); - assert_eq(from.counter(), dest_counter, "mismatch counter"); - if !should_be_empty { - if !should_be_private { - assert( - dest_counter > prev_counter, - "value array must be sorted by counter in ascending order", - ); - } - } else { - assert(is_empty(dest), "array must be padded with empty items"); - } - prev_counter = dest_counter; - } -} - -mod tests { - use crate::{ - tests::{ - types::{ - combine_two_values, is_combined_from_two_values, TestCombinedValue, TestTwoValues, - }, - utils::pad_end, - }, - utils::arrays::{ - array_merge, - assert_combined_sorted_transformed_value_array::{ - assert_combined_sorted_transformed_value_array_asc, - get_combined_order_hints::{CombinedOrderHint, get_combined_order_hints_asc}, - }, - sort_by_counter::sort_by_counter_asc, - }, - }; - - struct TestDataBuilder { - original_array_lt: [TestTwoValues; N], - original_array_gte: [TestTwoValues; N], - sorted_transformed_value_array: [TestCombinedValue; N], - hints: [CombinedOrderHint; N], - } - - impl TestDataBuilder<12> { - pub fn new() -> Self { - let original_array_lt = pad_end( - [ - TestTwoValues { value_1: 40, value_2: 7, counter: 0 }, - TestTwoValues { value_1: 70, value_2: 6, counter: 0 }, - TestTwoValues { value_1: 80, value_2: 1, counter: 22 }, - TestTwoValues { value_1: 30, value_2: 4, counter: 11 }, - ], - TestTwoValues::empty(), - ); - - let original_array_gte = pad_end( - [ - TestTwoValues { value_1: 20, value_2: 2, counter: 0 }, - TestTwoValues { value_1: 90, value_2: 3, counter: 0 }, - TestTwoValues { value_1: 50, value_2: 9, counter: 55 }, - TestTwoValues { value_1: 60, value_2: 8, counter: 33 }, - TestTwoValues { value_1: 10, value_2: 5, counter: 44 }, - ], - TestTwoValues::empty(), - ); - - let sorted_transformed_value_array = pad_end( - [ - TestCombinedValue { value: 47 }, - TestCombinedValue { value: 76 }, - TestCombinedValue { value: 22 }, - TestCombinedValue { value: 93 }, - TestCombinedValue { value: 34 }, - TestCombinedValue { value: 81 }, - TestCombinedValue { value: 68 }, - TestCombinedValue { value: 15 }, - TestCombinedValue { value: 59 }, - ], - TestCombinedValue::empty(), - ); - - let hints = [ - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 11, original_index: 3 }, - CombinedOrderHint { counter: 22, original_index: 2 }, - CombinedOrderHint { counter: 33, original_index: 3 }, - CombinedOrderHint { counter: 44, original_index: 4 }, - CombinedOrderHint { counter: 55, original_index: 2 }, - CombinedOrderHint { counter: 0, original_index: 5 }, - CombinedOrderHint { counter: 0, original_index: 6 }, - CombinedOrderHint { counter: 0, original_index: 7 }, - ]; - - TestDataBuilder { - original_array_lt, - original_array_gte, - sorted_transformed_value_array, - hints, - } - } - } - - impl TestDataBuilder<8> { - pub fn new_without_prepended() -> Self { - let original_array_lt = pad_end( - [ - TestTwoValues { value_1: 80, value_2: 1, counter: 22 }, - TestTwoValues { value_1: 30, value_2: 4, counter: 11 }, - ], - TestTwoValues::empty(), - ); - - let original_array_gte = pad_end( - [ - TestTwoValues { value_1: 50, value_2: 9, counter: 55 }, - TestTwoValues { value_1: 60, value_2: 8, counter: 33 }, - TestTwoValues { value_1: 10, value_2: 5, counter: 44 }, - ], - TestTwoValues::empty(), - ); - - let sorted_transformed_value_array = pad_end( - [ - TestCombinedValue { value: 34 }, - TestCombinedValue { value: 81 }, - TestCombinedValue { value: 68 }, - TestCombinedValue { value: 15 }, - TestCombinedValue { value: 59 }, - ], - TestCombinedValue::empty(), - ); - - let hints = [ - CombinedOrderHint { counter: 11, original_index: 1 }, - CombinedOrderHint { counter: 22, original_index: 0 }, - CombinedOrderHint { counter: 33, original_index: 1 }, - CombinedOrderHint { counter: 44, original_index: 2 }, - CombinedOrderHint { counter: 55, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 3 }, - CombinedOrderHint { counter: 0, original_index: 4 }, - CombinedOrderHint { counter: 0, original_index: 5 }, - ]; - - TestDataBuilder { - original_array_lt, - original_array_gte, - sorted_transformed_value_array, - hints, - } - } - } - - impl TestDataBuilder { - pub fn swap_items(&mut self, from: u32, to: u32) { - let tmp = self.sorted_transformed_value_array[from]; - self.sorted_transformed_value_array[from] = self.sorted_transformed_value_array[to]; - self.sorted_transformed_value_array[to] = tmp; - } - - pub fn swap_hints(&mut self, from: u32, to: u32) { - let tmp = self.hints[from]; - self.hints[from] = self.hints[to]; - self.hints[to] = tmp; - } - - pub fn execute(self) { - assert_combined_sorted_transformed_value_array_asc( - self.original_array_lt, - self.original_array_gte, - self.sorted_transformed_value_array, - is_combined_from_two_values, - self.hints, - ); - } - - pub fn check_and_execute(self) { - let hints = unsafe { - get_combined_order_hints_asc(self.original_array_lt, self.original_array_gte) - }; - assert_eq(hints, self.hints); - - let sorted = unsafe { - sort_by_counter_asc(array_merge(self.original_array_lt, self.original_array_gte)) - .map(combine_two_values) - }; - assert_eq(sorted, self.sorted_transformed_value_array); - - self.execute(); - } - } - - #[test] - fn assert_combined_sorted_transformed_value_array_asc_succeeds() { - let builder = TestDataBuilder::new(); - builder.check_and_execute(); - } - - #[test] - fn assert_combined_sorted_transformed_value_array_asc_without_prepended_counter_zeros_succeeds() { - let builder = TestDataBuilder::new_without_prepended(); - builder.check_and_execute(); - } - - #[test(should_fail_with = "incorrect transformed value")] - fn assert_combined_sorted_transformed_value_array_asc_mismatch_value_fails() { - let mut builder = TestDataBuilder::new(); - - // Tweak the value at index 1. - builder.sorted_transformed_value_array[1].value += 1; - - builder.execute(); - } - - #[test(should_fail_with = "incorrect transformed value")] - fn assert_combined_sorted_transformed_value_array_asc_cross_boundary_fails() { - let mut builder = TestDataBuilder::new(); - - builder.swap_items(4, 6); - - builder.execute(); - } - - #[test(should_fail_with = "items with a counter of 0 should be prepended")] - fn assert_combined_sorted_transformed_value_array_asc_unordered_prepended_fails() { - let mut builder = TestDataBuilder::new(); - - builder.swap_items(0, 1); - builder.swap_hints(0, 1); - - builder.execute(); - } - - #[test(should_fail_with = "items with a counter of 0 should be prepended")] - fn assert_combined_sorted_transformed_value_array_asc_mixed_prepended_fails() { - let mut builder = TestDataBuilder::new(); - - builder.swap_items(1, 4); - builder.swap_hints(1, 4); - - builder.execute(); - } - - #[test(should_fail_with = "value array must be sorted by counter in ascending order")] - fn assert_combined_sorted_transformed_value_array_asc_unordered_fails() { - let mut builder = TestDataBuilder::new(); - - builder.swap_items(4, 5); - builder.swap_hints(4, 5); - - builder.execute(); - } - - #[test(should_fail_with = "mismatch counter")] - fn assert_combined_sorted_transformed_value_array_asc_unordered_values_with_ordered_counters_fails() { - let mut builder = TestDataBuilder::new(); - - builder.swap_items(4, 5); - - // Update indexes in hints. - let tmp = builder.hints[4].original_index; - builder.hints[4].original_index = builder.hints[5].original_index; - builder.hints[5].original_index = tmp; - - builder.execute(); - } - - #[test(should_fail_with = "array must be padded with empty items")] - fn assert_combined_sorted_transformed_value_array_asc_extra_non_empty_fails() { - let mut builder = TestDataBuilder::new(); - - // Add an item. - builder.sorted_transformed_value_array[9] = builder.sorted_transformed_value_array[8]; - builder.hints[9] = builder.hints[8]; - - builder.execute(); - } - - #[test(should_fail_with = "value array must be sorted by counter in ascending order")] - fn assert_combined_sorted_transformed_value_array_asc_extra_empty_fails() { - let mut builder = TestDataBuilder::new(); - - // Clear an item. - builder.sorted_transformed_value_array[8] = TestCombinedValue::empty(); - builder.hints[8] = CombinedOrderHint { counter: 0, original_index: 6 }; - - builder.execute(); - } - - #[test(should_fail_with = "value array must be sorted by counter in ascending order")] - fn assert_combined_sorted_transformed_value_array_asc_duplicate_fails() { - let mut builder = TestDataBuilder::new(); - - // Duplicate an item. - builder.sorted_transformed_value_array[5] = builder.sorted_transformed_value_array[4]; - builder.hints[5] = builder.hints[4]; - - builder.execute(); - } - - #[test(should_fail_with = "items with a counter of 0 should be prepended")] - fn assert_combined_sorted_transformed_value_array_asc_duplicate_zero_counter_fails() { - let mut builder = TestDataBuilder::new(); - - // Duplicate an item with 0 counter. - builder.sorted_transformed_value_array[1] = builder.sorted_transformed_value_array[0]; - builder.hints[1] = builder.hints[0]; - - builder.execute(); - } -} - diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array/get_combined_order_hints.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array/get_combined_order_hints.nr deleted file mode 100644 index 9a16ea9896fa..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_combined_sorted_transformed_value_array/get_combined_order_hints.nr +++ /dev/null @@ -1,257 +0,0 @@ -use crate::{ - abis::side_effect::Ordered, - traits::{Empty, is_empty}, - utils::arrays::{ - array_length, get_sorted_tuple::get_sorted_tuple, - sort_by_counter::compare_by_counter_empty_padded_asc, - }, -}; - -pub struct CombinedOrderHint { - pub counter: u32, - pub original_index: u32, -} - -impl CombinedOrderHint { - pub fn empty() -> Self { - CombinedOrderHint { counter: 0, original_index: 0 } - } -} - -impl Eq for CombinedOrderHint { - fn eq(self, other: Self) -> bool { - (self.counter == other.counter) & (self.original_index == other.original_index) - } -} - -pub unconstrained fn count_private_items(array: [T; N]) -> u32 -where - T: Ordered + Empty + Eq, -{ - let mut length = 0; - for item in array { - if !is_empty(item) & (item.counter() == 0) { - length += 1; - } - } - length -} - -pub unconstrained fn get_combined_order_hints_asc( - array_lt: [T; N], - array_gte: [T; N], -) -> [CombinedOrderHint; N] -where - T: Ordered + Eq + Empty, -{ - let mut hints = [CombinedOrderHint::empty(); N]; - let sorted_lt = get_sorted_tuple(array_lt, compare_by_counter_empty_padded_asc); - let sorted_gte = get_sorted_tuple(array_gte, compare_by_counter_empty_padded_asc); - let num_private_lt = count_private_items(array_lt); - let num_private_gte = count_private_items(array_gte); - let num_lt = array_length(array_lt); - let total_private = num_private_lt + num_private_gte; - let total_non_public_gte = num_lt + num_private_gte; - for i in 0..N { - let sorted = if i < num_private_lt { - sorted_lt[i] - } else if i < total_private { - sorted_gte[i - num_private_lt] - } else if i < total_non_public_gte { - sorted_lt[i - num_private_gte] - } else { - sorted_gte[i - num_lt] - }; - hints[i].original_index = sorted.original_index; - hints[i].counter = sorted.elem.counter(); - } - hints -} - -mod tests { - use crate::{ - tests::{types::TestValue, utils::pad_end}, - utils::arrays::assert_combined_sorted_transformed_value_array::get_combined_order_hints::{ - CombinedOrderHint, get_combined_order_hints_asc, - }, - }; - - fn asc_to_equal( - array_lt: [TestValue; N], - array_gte: [TestValue; N], - expected: [CombinedOrderHint; N], - ) { - let hints = unsafe { get_combined_order_hints_asc(array_lt, array_gte) }; - assert_eq(hints, expected); - } - - #[test] - fn get_combined_order_hints_asc_full_non_empty() { - let array_lt = pad_end( - [ - TestValue { value: 600, counter: 9 }, - TestValue { value: 400, counter: 3 }, - TestValue { value: 500, counter: 6 }, - ], - TestValue::empty(), - ); - let array_gte = pad_end( - [ - TestValue { value: 200, counter: 13 }, - TestValue { value: 100, counter: 19 }, - TestValue { value: 300, counter: 16 }, - ], - TestValue::empty(), - ); - let expected_hints = [ - CombinedOrderHint { counter: 3, original_index: 1 }, - CombinedOrderHint { counter: 6, original_index: 2 }, - CombinedOrderHint { counter: 9, original_index: 0 }, - CombinedOrderHint { counter: 13, original_index: 0 }, - CombinedOrderHint { counter: 16, original_index: 2 }, - CombinedOrderHint { counter: 19, original_index: 1 }, - ]; - asc_to_equal(array_lt, array_gte, expected_hints); - } - - #[test] - fn get_combined_order_hints_asc_padded_empty() { - let array_lt = pad_end( - [TestValue { value: 500, counter: 6 }, TestValue { value: 400, counter: 3 }], - TestValue::empty(), - ); - let array_gte = pad_end([TestValue { value: 100, counter: 19 }], TestValue::empty()); - let expected_hints = [ - CombinedOrderHint { counter: 3, original_index: 1 }, - CombinedOrderHint { counter: 6, original_index: 0 }, - CombinedOrderHint { counter: 19, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 0, original_index: 2 }, - ]; - asc_to_equal(array_lt, array_gte, expected_hints); - } - - #[test] - fn get_combined_order_hints_asc_lt_empty() { - let array_lt = [TestValue::empty(); 4]; - let array_gte = pad_end( - [TestValue { value: 200, counter: 13 }, TestValue { value: 100, counter: 19 }], - TestValue::empty(), - ); - let expected_hints = [ - CombinedOrderHint { counter: 13, original_index: 0 }, - CombinedOrderHint { counter: 19, original_index: 1 }, - CombinedOrderHint { counter: 0, original_index: 2 }, - CombinedOrderHint { counter: 0, original_index: 3 }, - ]; - asc_to_equal(array_lt, array_gte, expected_hints); - } - - #[test] - fn get_combined_order_hints_asc_gte_empty() { - let array_lt = pad_end( - [TestValue { value: 400, counter: 3 }, TestValue { value: 500, counter: 6 }], - TestValue::empty(), - ); - let array_gte = [TestValue::empty(); 4]; - let expected_hints = [ - CombinedOrderHint { counter: 3, original_index: 0 }, - CombinedOrderHint { counter: 6, original_index: 1 }, - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - ]; - asc_to_equal(array_lt, array_gte, expected_hints); - } - - #[test] - fn get_combined_order_hints_asc_all_empty() { - let array_lt = [TestValue::empty(); 3]; - let array_gte = [TestValue::empty(); 3]; - let expected_hints = [ - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 0, original_index: 2 }, - ]; - asc_to_equal(array_lt, array_gte, expected_hints); - } - - #[test] - fn get_combined_order_hints_asc_prepended_zero_counters() { - let array_lt = pad_end( - [ - TestValue { value: 700, counter: 0 }, - TestValue { value: 500, counter: 0 }, - TestValue { value: 100, counter: 16 }, - TestValue { value: 400, counter: 13 }, - ], - TestValue::empty(), - ); - let array_gte = pad_end( - [ - TestValue { value: 300, counter: 0 }, - TestValue { value: 600, counter: 0 }, - TestValue { value: 200, counter: 19 }, - ], - TestValue::empty(), - ); - let expected_hints = [ - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 13, original_index: 3 }, - CombinedOrderHint { counter: 16, original_index: 2 }, - CombinedOrderHint { counter: 19, original_index: 2 }, - CombinedOrderHint { counter: 0, original_index: 3 }, - CombinedOrderHint { counter: 0, original_index: 4 }, - CombinedOrderHint { counter: 0, original_index: 5 }, - ]; - asc_to_equal(array_lt, array_gte, expected_hints); - } - - #[test] - fn get_combined_order_hints_asc_prepended_zero_counters_lt_empty() { - let array_lt = [TestValue::empty(); 6]; - let array_gte = pad_end( - [ - TestValue { value: 300, counter: 0 }, - TestValue { value: 600, counter: 0 }, - TestValue { value: 200, counter: 19 }, - TestValue { value: 400, counter: 13 }, - ], - TestValue::empty(), - ); - let expected_hints = [ - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 13, original_index: 3 }, - CombinedOrderHint { counter: 19, original_index: 2 }, - CombinedOrderHint { counter: 0, original_index: 4 }, - CombinedOrderHint { counter: 0, original_index: 5 }, - ]; - asc_to_equal(array_lt, array_gte, expected_hints); - } - - #[test] - fn get_combined_order_hints_asc_prepended_zero_counters_gte_empty() { - let array_lt = pad_end( - [ - TestValue { value: 300, counter: 0 }, - TestValue { value: 600, counter: 0 }, - TestValue { value: 200, counter: 19 }, - TestValue { value: 400, counter: 13 }, - ], - TestValue::empty(), - ); - let array_gte = [TestValue::empty(); 6]; - let expected_hints = [ - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - CombinedOrderHint { counter: 13, original_index: 3 }, - CombinedOrderHint { counter: 19, original_index: 2 }, - CombinedOrderHint { counter: 0, original_index: 0 }, - CombinedOrderHint { counter: 0, original_index: 1 }, - ]; - asc_to_equal(array_lt, array_gte, expected_hints); - } -} diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_deduped_array.nr b/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_deduped_array.nr deleted file mode 100644 index 6912c7c08685..000000000000 --- a/noir-projects/noir-protocol-circuits/crates/types/src/utils/arrays/assert_deduped_array.nr +++ /dev/null @@ -1,156 +0,0 @@ -use crate::{abis::side_effect::{Inner, Overridable}, traits::{Empty, is_empty}}; - -// Check that deduped_array contains values that are not being overriden, i.e. override_counter == 0. -pub fn assert_deduped_array(original_array: [S; N], deduped_array: [T; N]) -where - S: Overridable + Inner, - T: Eq + Empty, -{ - let mut num_added = 0; - for i in 0..original_array.len() { - let original = original_array[i]; - if original.override_counter() == 0 { - assert_eq(original.inner(), deduped_array[num_added], "mismatch deduped item"); - num_added += 1; - } - } - let mut should_be_empty = false; - for i in 0..original_array.len() { - should_be_empty |= i == num_added; - if should_be_empty { - assert(is_empty(deduped_array[i]), "empty items must be padded to the deduped array"); - } - } -} - -pub unconstrained fn dedupe_array(original_array: [S; N]) -> [T; N] -where - S: Overridable + Inner, -{ - let mut deduped = BoundedVec::new(); - for i in 0..original_array.len() { - let original = original_array[i]; - if original.override_counter() == 0 { - deduped.push(original.inner()); - } - } - deduped.storage() -} - -mod tests { - use crate::{ - abis::side_effect::{Inner, Overridable}, - tests::{types::TestValue, utils::pad_end}, - traits::Empty, - utils::arrays::assert_deduped_array::{assert_deduped_array, dedupe_array}, - }; - - struct TestItem { - value: TestValue, - override_by: TestValue, - } - - impl Overridable for TestItem { - fn override_counter(self) -> u32 { - self.override_by.counter - } - } - - impl Inner for TestItem { - fn inner(self) -> TestValue { - self.value - } - } - - impl Empty for TestItem { - fn empty() -> Self { - TestItem { value: TestValue::empty(), override_by: TestValue::empty() } - } - } - - impl Eq for TestItem { - fn eq(self, other: Self) -> bool { - (self.value == other.value) & (self.override_by == other.override_by) - } - } - - global NUM_TEST_ITEMS = 10; - - struct TestBuilder { - original_array: [TestItem; NUM_TEST_ITEMS], - deduped_array: [TestValue; NUM_TEST_ITEMS], - } - - impl TestBuilder { - pub fn new_empty() -> Self { - let original_array = pad_end([], TestItem::empty()); - let deduped_array = pad_end([], TestValue::empty()); - TestBuilder { original_array, deduped_array } - } - - pub fn new() -> Self { - let values = [ - TestValue { value: 22, counter: 2 }, - TestValue { value: 11, counter: 1 }, - TestValue { value: 44, counter: 4 }, - TestValue { value: 11, counter: 6 }, - TestValue { value: 11, counter: 3 }, - TestValue { value: 33, counter: 5 }, - ]; - let mut original_array = pad_end( - values.map(|value: TestValue| TestItem { value, override_by: TestValue::empty() }), - TestItem::empty(), - ); - original_array[1].override_by = values[4]; - original_array[4].override_by = values[3]; - - let deduped_array = pad_end( - [values[0], values[2], values[3], values[5]], - TestValue::empty(), - ); - - TestBuilder { original_array, deduped_array } - } - - pub fn execute(self) { - assert_deduped_array(self.original_array, self.deduped_array); - } - - pub fn check_and_execute(self) { - let deduped = unsafe { dedupe_array(self.original_array) }; - assert_eq(self.deduped_array, deduped); - - self.execute(); - } - } - - #[test] - fn assert_deduped_array_empty_succeeds() { - let builder = TestBuilder::new_empty(); - builder.check_and_execute(); - } - - #[test] - fn assert_deduped_array_succeeds() { - let builder = TestBuilder::new(); - builder.check_and_execute(); - } - - #[test(should_fail_with = "mismatch deduped item")] - fn assert_deduped_array_extra_item_fails() { - let mut builder = TestBuilder::new(); - - builder.deduped_array[7] = builder.original_array[1].inner(); - - builder.execute(); - } - - #[test(should_fail_with = "empty items must be padded to the deduped array")] - fn assert_deduped_array_extra_item_at_end_fails() { - let mut builder = TestBuilder::new(); - - builder.deduped_array[NUM_TEST_ITEMS - 1] = builder.original_array[1].inner(); - - builder.execute(); - } -} From 1de28abb9c66a671e3d4a0f188e77e5f66e309ca Mon Sep 17 00:00:00 2001 From: Leila Wang Date: Mon, 18 Nov 2024 20:28:49 +0000 Subject: [PATCH 2/3] Remove public kernel related structs and utils. --- .../src/barretenberg/vm/aztec_constants.hpp | 1 - .../src/core/libraries/ConstantsGen.sol | 9 - .../crates/types/src/constants.nr | 46 -- yarn-project/circuit-types/src/mocks.ts | 4 +- .../circuit-types/src/tx/processed_tx.ts | 27 -- yarn-project/circuits.js/src/constants.gen.ts | 9 - ...er_non_existent_read_request_hints.test.ts | 138 ------ ...llifier_non_existent_read_request_hints.ts | 86 ---- .../src/hints/build_public_data_hints.test.ts | 116 ----- .../src/hints/build_public_data_hints.ts | 52 -- yarn-project/circuits.js/src/hints/index.ts | 2 - .../circuits.js/src/scripts/constants.in.ts | 1 - yarn-project/circuits.js/src/structs/index.ts | 11 - .../src/structs/kernel/enqueued_call_data.ts | 20 - ...vate_to_public_accumulated_data_builder.ts | 25 +- .../structs/kernel/public_accumulated_data.ts | 321 ------------- ...blic_kernel_circuit_private_inputs.test.ts | 23 - .../public_kernel_circuit_private_inputs.ts | 65 --- ...ublic_kernel_circuit_public_inputs.test.ts | 23 - .../public_kernel_circuit_public_inputs.ts | 136 ------ .../src/structs/kernel/public_kernel_data.ts | 74 --- ...kernel_tail_circuit_private_inputs.test.ts | 24 - ...blic_kernel_tail_circuit_private_inputs.ts | 94 ---- .../kernel/vm_circuit_public_inputs.ts | 131 ------ .../non_existent_read_request_hints.ts | 161 ------- .../public_call_stack_item_compressed.ts | 1 + .../public_circuit_public_inputs.test.ts | 28 -- .../structs/public_circuit_public_inputs.ts | 5 +- .../src/structs/public_data_hint.ts | 11 +- .../src/structs/public_data_leaf_hint.ts | 28 -- .../src/structs/public_data_update_request.ts | 1 + .../src/structs/public_inner_call_request.ts | 1 + .../src/structs/public_validation_requests.ts | 239 ---------- .../structs/tree_leaf_read_request_hint.ts | 38 -- .../circuits.js/src/tests/factories.ts | 289 +----------- .../src/avm_integration.test.ts | 8 +- yarn-project/ivc-integration/src/index.ts | 12 +- .../src/scripts/generate_ts_from_abi.ts | 2 +- .../src/artifacts.ts | 6 - .../noir-protocol-circuits-types/src/index.ts | 66 --- .../src/scripts/generate_ts_from_abi.ts | 2 - .../src/type_conversion.ts | 444 ------------------ .../orchestrator/block-building-helpers.ts | 25 +- .../src/public/dual_side_effect_trace.ts | 26 - .../enqueued_call_side_effect_trace.test.ts | 163 ++----- .../public/enqueued_call_side_effect_trace.ts | 150 ++---- .../simulator/src/public/hints_builder.ts | 168 ------- yarn-project/simulator/src/public/index.ts | 4 - .../simulator/src/public/public_kernel.ts | 74 --- .../public/public_kernel_circuit_simulator.ts | 24 - .../public/public_kernel_tail_simulator.ts | 97 ---- .../simulator/src/public/public_tx_context.ts | 40 +- .../simulator/src/public/side_effect_trace.ts | 19 - .../src/public/side_effect_trace_interface.ts | 16 - yarn-project/simulator/src/public/utils.ts | 17 +- 55 files changed, 163 insertions(+), 3440 deletions(-) delete mode 100644 yarn-project/circuits.js/src/hints/build_nullifier_non_existent_read_request_hints.test.ts delete mode 100644 yarn-project/circuits.js/src/hints/build_nullifier_non_existent_read_request_hints.ts delete mode 100644 yarn-project/circuits.js/src/hints/build_public_data_hints.test.ts delete mode 100644 yarn-project/circuits.js/src/hints/build_public_data_hints.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/enqueued_call_data.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/public_accumulated_data.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_private_inputs.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_private_inputs.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_public_inputs.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_public_inputs.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/public_kernel_data.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/public_kernel_tail_circuit_private_inputs.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/public_kernel_tail_circuit_private_inputs.ts delete mode 100644 yarn-project/circuits.js/src/structs/kernel/vm_circuit_public_inputs.ts delete mode 100644 yarn-project/circuits.js/src/structs/non_existent_read_request_hints.ts delete mode 100644 yarn-project/circuits.js/src/structs/public_circuit_public_inputs.test.ts delete mode 100644 yarn-project/circuits.js/src/structs/public_data_leaf_hint.ts delete mode 100644 yarn-project/circuits.js/src/structs/public_validation_requests.ts delete mode 100644 yarn-project/circuits.js/src/structs/tree_leaf_read_request_hint.ts delete mode 100644 yarn-project/simulator/src/public/hints_builder.ts delete mode 100644 yarn-project/simulator/src/public/public_kernel.ts delete mode 100644 yarn-project/simulator/src/public/public_kernel_circuit_simulator.ts delete mode 100644 yarn-project/simulator/src/public/public_kernel_tail_simulator.ts diff --git a/barretenberg/cpp/src/barretenberg/vm/aztec_constants.hpp b/barretenberg/cpp/src/barretenberg/vm/aztec_constants.hpp index 52df3243076b..86d562e27038 100644 --- a/barretenberg/cpp/src/barretenberg/vm/aztec_constants.hpp +++ b/barretenberg/cpp/src/barretenberg/vm/aztec_constants.hpp @@ -34,7 +34,6 @@ #define TOTAL_FEES_LENGTH 1 #define HEADER_LENGTH 24 #define PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH 866 -#define PUBLIC_CONTEXT_INPUTS_LENGTH 41 #define AVM_ACCUMULATED_DATA_LENGTH 318 #define AVM_CIRCUIT_PUBLIC_INPUTS_LENGTH 1006 #define AVM_VERIFICATION_KEY_LENGTH_IN_FIELDS 86 diff --git a/l1-contracts/src/core/libraries/ConstantsGen.sol b/l1-contracts/src/core/libraries/ConstantsGen.sol index 2f9ba8e4d62e..8334c5952088 100644 --- a/l1-contracts/src/core/libraries/ConstantsGen.sol +++ b/l1-contracts/src/core/libraries/ConstantsGen.sol @@ -72,7 +72,6 @@ library Constants { uint256 internal constant MAX_ENCRYPTED_LOGS_PER_TX = 8; uint256 internal constant MAX_UNENCRYPTED_LOGS_PER_TX = 8; uint256 internal constant MAX_CONTRACT_CLASS_LOGS_PER_TX = 1; - uint256 internal constant MAX_PUBLIC_DATA_HINTS = 128; uint256 internal constant NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP = 16; uint256 internal constant EMPTY_NESTED_INDEX = 0; uint256 internal constant PRIVATE_KERNEL_EMPTY_INDEX = 1; @@ -207,28 +206,20 @@ library Constants { uint256 internal constant PRIVATE_CIRCUIT_PUBLIC_INPUTS_LENGTH = 490; uint256 internal constant PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH = 866; uint256 internal constant PRIVATE_CONTEXT_INPUTS_LENGTH = 37; - uint256 internal constant PUBLIC_CONTEXT_INPUTS_LENGTH = 41; uint256 internal constant FEE_RECIPIENT_LENGTH = 2; uint256 internal constant AGGREGATION_OBJECT_LENGTH = 16; uint256 internal constant SCOPED_READ_REQUEST_LEN = 3; uint256 internal constant PUBLIC_DATA_READ_LENGTH = 3; uint256 internal constant PRIVATE_VALIDATION_REQUESTS_LENGTH = 772; - uint256 internal constant NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS = 5; - uint256 internal constant PUBLIC_VALIDATION_REQUESTS_LENGTH = 834; - uint256 internal constant PUBLIC_DATA_UPDATE_REQUEST_LENGTH = 3; uint256 internal constant COMBINED_ACCUMULATED_DATA_LENGTH = 550; uint256 internal constant TX_CONSTANT_DATA_LENGTH = 34; uint256 internal constant COMBINED_CONSTANT_DATA_LENGTH = 43; uint256 internal constant PRIVATE_ACCUMULATED_DATA_LENGTH = 1036; uint256 internal constant PRIVATE_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH = 1849; - uint256 internal constant PUBLIC_ACCUMULATED_DATA_LENGTH = 1023; - uint256 internal constant NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS = 8; uint256 internal constant PRIVATE_TO_PUBLIC_ACCUMULATED_DATA_LENGTH = 548; uint256 internal constant PRIVATE_TO_AVM_ACCUMULATED_DATA_LENGTH = 160; uint256 internal constant NUM_PRIVATE_TO_AVM_ACCUMULATED_DATA_ARRAYS = 3; uint256 internal constant PRIVATE_TO_PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH = 1140; - uint256 internal constant PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH = 2931; - uint256 internal constant VM_CIRCUIT_PUBLIC_INPUTS_LENGTH = 2340; uint256 internal constant KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH = 605; uint256 internal constant CONSTANT_ROLLUP_DATA_LENGTH = 13; uint256 internal constant BASE_OR_MERGE_PUBLIC_INPUTS_LENGTH = 30; diff --git a/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr b/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr index b7542af13b3f..9d875fcf4fe7 100644 --- a/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr +++ b/noir-projects/noir-protocol-circuits/crates/types/src/constants.nr @@ -98,11 +98,6 @@ pub global MAX_UNENCRYPTED_LOGS_PER_TX: u32 = 8; pub global MAX_CONTRACT_CLASS_LOGS_PER_TX: u32 = 1; // docs:end:constants -// KERNEL CIRCUIT PRIVATE INPUTS CONSTANTS -// pub global MAX_PUBLIC_DATA_HINTS: u32 = MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX + MAX_PUBLIC_DATA_READS_PER_TX; -// FIX: Sadly, writing this as above causes a type error in type_conversion.ts. -pub global MAX_PUBLIC_DATA_HINTS: u32 = 128; - // ROLLUP CONTRACT CONSTANTS - constants used only in l1-contracts pub global NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP: u32 = 16; @@ -349,8 +344,6 @@ pub global PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH: u32 = CALL_CONTEXT_LENGTH + /* transaction_fee */ 1; pub global PRIVATE_CONTEXT_INPUTS_LENGTH: u32 = CALL_CONTEXT_LENGTH + HEADER_LENGTH + TX_CONTEXT_LENGTH + 1; -pub global PUBLIC_CONTEXT_INPUTS_LENGTH: u32 = - CALL_CONTEXT_LENGTH + HEADER_LENGTH + GLOBAL_VARIABLES_LENGTH + GAS_LENGTH + 2; pub global FEE_RECIPIENT_LENGTH: u32 = 2; pub global AGGREGATION_OBJECT_LENGTH: u32 = 16; @@ -362,15 +355,7 @@ pub global PRIVATE_VALIDATION_REQUESTS_LENGTH: u32 = ROLLUP_VALIDATION_REQUESTS_ + (SCOPED_READ_REQUEST_LEN * MAX_NULLIFIER_READ_REQUESTS_PER_TX) + (SCOPED_KEY_VALIDATION_REQUEST_AND_GENERATOR_LENGTH * MAX_KEY_VALIDATION_REQUESTS_PER_TX) + 2; -pub global NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS: u32 = 5; -pub global PUBLIC_VALIDATION_REQUESTS_LENGTH: u32 = ROLLUP_VALIDATION_REQUESTS_LENGTH - + (TREE_LEAF_READ_REQUEST_LENGTH * MAX_NOTE_HASH_READ_REQUESTS_PER_TX) - + (SCOPED_READ_REQUEST_LEN * MAX_NULLIFIER_READ_REQUESTS_PER_TX) - + (SCOPED_READ_REQUEST_LEN * MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX) - + (PUBLIC_DATA_READ_LENGTH * MAX_PUBLIC_DATA_READS_PER_TX) - + (TREE_LEAF_READ_REQUEST_LENGTH * MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX); -pub global PUBLIC_DATA_UPDATE_REQUEST_LENGTH: u32 = 3; // To be deprecated. pub global COMBINED_ACCUMULATED_DATA_LENGTH: u32 = MAX_NOTE_HASHES_PER_TX + MAX_NULLIFIERS_PER_TX + (MAX_L2_TO_L1_MSGS_PER_TX * SCOPED_L2_TO_L1_MESSAGE_LENGTH) @@ -401,17 +386,6 @@ pub global PRIVATE_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH: u32 = TX_CONSTANT_DATA_L + PUBLIC_CALL_REQUEST_LENGTH + AZTEC_ADDRESS_LENGTH; -pub global PUBLIC_ACCUMULATED_DATA_LENGTH: u32 = (MAX_NOTE_HASHES_PER_TX * SCOPED_NOTE_HASH_LENGTH) - + (MAX_NULLIFIERS_PER_TX * NULLIFIER_LENGTH) - + (MAX_L2_TO_L1_MSGS_PER_TX * SCOPED_L2_TO_L1_MESSAGE_LENGTH) - + (MAX_NOTE_ENCRYPTED_LOGS_PER_TX * LOG_HASH_LENGTH) - + (MAX_ENCRYPTED_LOGS_PER_TX * SCOPED_LOG_HASH_LENGTH) - + (MAX_UNENCRYPTED_LOGS_PER_TX * SCOPED_LOG_HASH_LENGTH) - + (MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX * PUBLIC_DATA_UPDATE_REQUEST_LENGTH) - + (MAX_ENQUEUED_CALLS_PER_TX * PUBLIC_CALL_REQUEST_LENGTH) - + GAS_LENGTH; -pub global NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS: u32 = 8; - pub global PRIVATE_TO_PUBLIC_ACCUMULATED_DATA_LENGTH: u32 = MAX_NOTE_HASHES_PER_TX + MAX_NULLIFIERS_PER_TX + (MAX_L2_TO_L1_MSGS_PER_TX * SCOPED_L2_TO_L1_MESSAGE_LENGTH) @@ -438,26 +412,6 @@ pub global PRIVATE_TO_PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH: u32 = TX_CONST + PUBLIC_CALL_REQUEST_LENGTH /* public_teardown_call_request */ + GAS_LENGTH /* gas_used */ + AZTEC_ADDRESS_LENGTH /* fee_payer */; -pub global PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH: u32 = COMBINED_CONSTANT_DATA_LENGTH - + PUBLIC_VALIDATION_REQUESTS_LENGTH - + PUBLIC_ACCUMULATED_DATA_LENGTH - + PUBLIC_ACCUMULATED_DATA_LENGTH - + 1 /* end_side_effect_counter */ - + PUBLIC_CALL_REQUEST_LENGTH - + AZTEC_ADDRESS_LENGTH - + 1 /* revert_code */; -pub global VM_CIRCUIT_PUBLIC_INPUTS_LENGTH: u32 = COMBINED_CONSTANT_DATA_LENGTH - + PUBLIC_CALL_REQUEST_LENGTH - + PUBLIC_VALIDATION_REQUESTS_LENGTH - + NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS - + PUBLIC_ACCUMULATED_DATA_LENGTH - + NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS - + 1 /* start_side_effect_counter */ - + 1 /* end_side_effect_counter */ - + GAS_LENGTH - + 1 - + 1 - + (PUBLIC_INNER_CALL_REQUEST_LENGTH * MAX_ENQUEUED_CALLS_PER_TX); pub global KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH: u32 = ROLLUP_VALIDATION_REQUESTS_LENGTH + COMBINED_ACCUMULATED_DATA_LENGTH diff --git a/yarn-project/circuit-types/src/mocks.ts b/yarn-project/circuit-types/src/mocks.ts index 7b4a3f13ffdc..24cc07d0c3a3 100644 --- a/yarn-project/circuit-types/src/mocks.ts +++ b/yarn-project/circuit-types/src/mocks.ts @@ -155,11 +155,11 @@ export const mockTx = ( data.forPublic.nonRevertibleAccumulatedData = nonRevertibleBuilder .pushNullifier(firstNullifier.value) - .withPublicCallStack(publicCallRequests.slice(numberOfRevertiblePublicCallRequests)) + .withPublicCallRequests(publicCallRequests.slice(numberOfRevertiblePublicCallRequests)) .build(); data.forPublic.revertibleAccumulatedData = revertibleBuilder - .withPublicCallStack(publicCallRequests.slice(0, numberOfRevertiblePublicCallRequests)) + .withPublicCallRequests(publicCallRequests.slice(0, numberOfRevertiblePublicCallRequests)) .build(); if (hasLogs) { diff --git a/yarn-project/circuit-types/src/tx/processed_tx.ts b/yarn-project/circuit-types/src/tx/processed_tx.ts index 58c129272875..69da14b2f12c 100644 --- a/yarn-project/circuit-types/src/tx/processed_tx.ts +++ b/yarn-project/circuit-types/src/tx/processed_tx.ts @@ -7,7 +7,6 @@ import { type Header, PrivateKernelTailCircuitPublicInputs, type PublicDataWrite, - type PublicKernelCircuitPublicInputs, RevertCode, } from '@aztec/circuits.js'; import { siloL2ToL1Message } from '@aztec/circuits.js/hash'; @@ -68,32 +67,6 @@ export type ProcessedTx = { isEmpty: boolean; }; -export type RevertedTx = ProcessedTx & { - data: PublicKernelCircuitPublicInputs & { - reverted: true; - }; - - revertReason: SimulationError; -}; - -export function isRevertedTx(tx: ProcessedTx): tx is RevertedTx { - return !tx.txEffect.revertCode.isOK(); -} - -export function partitionReverts(txs: ProcessedTx[]): { reverted: RevertedTx[]; nonReverted: ProcessedTx[] } { - return txs.reduce( - ({ reverted, nonReverted }, tx) => { - if (isRevertedTx(tx)) { - reverted.push(tx); - } else { - nonReverted.push(tx); - } - return { reverted, nonReverted }; - }, - { reverted: [], nonReverted: [] } as ReturnType, - ); -} - /** * Represents a tx that failed to be processed by the sequencer public processor. */ diff --git a/yarn-project/circuits.js/src/constants.gen.ts b/yarn-project/circuits.js/src/constants.gen.ts index c4c26d55c391..d315587a46f8 100644 --- a/yarn-project/circuits.js/src/constants.gen.ts +++ b/yarn-project/circuits.js/src/constants.gen.ts @@ -58,7 +58,6 @@ export const MAX_NOTE_ENCRYPTED_LOGS_PER_TX = 64; export const MAX_ENCRYPTED_LOGS_PER_TX = 8; export const MAX_UNENCRYPTED_LOGS_PER_TX = 8; export const MAX_CONTRACT_CLASS_LOGS_PER_TX = 1; -export const MAX_PUBLIC_DATA_HINTS = 128; export const NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP = 16; export const EMPTY_NESTED_INDEX = 0; export const PRIVATE_KERNEL_EMPTY_INDEX = 1; @@ -185,29 +184,21 @@ export const HEADER_LENGTH = 24; export const PRIVATE_CIRCUIT_PUBLIC_INPUTS_LENGTH = 490; export const PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH = 866; export const PRIVATE_CONTEXT_INPUTS_LENGTH = 37; -export const PUBLIC_CONTEXT_INPUTS_LENGTH = 41; export const FEE_RECIPIENT_LENGTH = 2; export const AGGREGATION_OBJECT_LENGTH = 16; export const SCOPED_READ_REQUEST_LEN = 3; export const PUBLIC_DATA_READ_LENGTH = 3; export const PRIVATE_VALIDATION_REQUESTS_LENGTH = 772; -export const NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS = 5; -export const PUBLIC_VALIDATION_REQUESTS_LENGTH = 834; -export const PUBLIC_DATA_UPDATE_REQUEST_LENGTH = 3; export const COMBINED_ACCUMULATED_DATA_LENGTH = 550; export const TX_CONSTANT_DATA_LENGTH = 34; export const COMBINED_CONSTANT_DATA_LENGTH = 43; export const PRIVATE_ACCUMULATED_DATA_LENGTH = 1036; export const PRIVATE_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH = 1849; -export const PUBLIC_ACCUMULATED_DATA_LENGTH = 1023; -export const NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS = 8; export const PRIVATE_TO_PUBLIC_ACCUMULATED_DATA_LENGTH = 548; export const PRIVATE_TO_AVM_ACCUMULATED_DATA_LENGTH = 160; export const NUM_PRIVATE_TO_AVM_ACCUMULATED_DATA_ARRAYS = 3; export const AVM_ACCUMULATED_DATA_LENGTH = 318; export const PRIVATE_TO_PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH = 1140; -export const PUBLIC_KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH = 2931; -export const VM_CIRCUIT_PUBLIC_INPUTS_LENGTH = 2340; export const KERNEL_CIRCUIT_PUBLIC_INPUTS_LENGTH = 605; export const AVM_CIRCUIT_PUBLIC_INPUTS_LENGTH = 1006; export const CONSTANT_ROLLUP_DATA_LENGTH = 13; diff --git a/yarn-project/circuits.js/src/hints/build_nullifier_non_existent_read_request_hints.test.ts b/yarn-project/circuits.js/src/hints/build_nullifier_non_existent_read_request_hints.test.ts deleted file mode 100644 index beb031fb2592..000000000000 --- a/yarn-project/circuits.js/src/hints/build_nullifier_non_existent_read_request_hints.test.ts +++ /dev/null @@ -1,138 +0,0 @@ -import { makeTuple } from '@aztec/foundation/array'; -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { padArrayEnd } from '@aztec/foundation/collection'; -import { Fr } from '@aztec/foundation/fields'; - -import { MAX_NULLIFIERS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX } from '../constants.gen.js'; -import { siloNullifier } from '../hash/index.js'; -import { - Nullifier, - NullifierNonExistentReadRequestHintsBuilder, - ReadRequest, - ScopedReadRequest, -} from '../structs/index.js'; -import { buildNullifierNonExistentReadRequestHints } from './build_nullifier_non_existent_read_request_hints.js'; - -describe('buildNullifierNonExistentReadRequestHints', () => { - const contractAddress = AztecAddress.random(); - const oracle = { - getLowNullifierMembershipWitness: () => ({ membershipWitness: {}, leafPreimage: {} } as any), - }; - const nonExistentReadRequests = makeTuple(MAX_NULLIFIER_READ_REQUESTS_PER_TX, ScopedReadRequest.empty); - let nullifiers = makeTuple(MAX_NULLIFIERS_PER_TX, Nullifier.empty); - - const innerNullifier = (index: number) => index + 1; - - const makeReadRequest = (value: number, counter = 2) => - new ReadRequest(new Fr(value), counter).scope(contractAddress); - - const makeNullifier = (value: number, counter = 1) => { - const siloedValue = siloNullifier(contractAddress, new Fr(value)); - return new Nullifier(siloedValue, 0, new Fr(counter)); - }; - - interface TestNullifier { - value: number; - siloedValue: Fr; - } - - const populateNullifiers = (numNullifiers = MAX_NULLIFIERS_PER_TX) => { - nullifiers = makeTuple(MAX_NULLIFIERS_PER_TX, i => - i < numNullifiers ? makeNullifier(innerNullifier(i)) : Nullifier.empty(), - ); - }; - - const generateSortedNullifiers = (numNullifiers: number) => { - const nullifiers: TestNullifier[] = []; - for (let i = 0; i < numNullifiers; ++i) { - const value = i; - nullifiers.push({ - value, - siloedValue: siloNullifier(contractAddress, new Fr(value)), - }); - } - return nullifiers.sort((a, b) => (b.siloedValue.lt(a.siloedValue) ? 1 : -1)); - }; - - const buildHints = () => buildNullifierNonExistentReadRequestHints(oracle, nonExistentReadRequests, nullifiers); - - it('builds empty hints', async () => { - const hints = await buildHints(); - const emptyHints = NullifierNonExistentReadRequestHintsBuilder.empty(); - expect(hints).toEqual(emptyHints); - }); - - it('builds hints for full sorted nullifiers', async () => { - populateNullifiers(); - - const hints = await buildHints(); - const { sortedPendingValues, sortedPendingValueHints } = hints; - for (let i = 0; i < sortedPendingValues.length - 1; ++i) { - expect(sortedPendingValues[i].value.lt(sortedPendingValues[i + 1].value)).toBe(true); - } - for (let i = 0; i < nullifiers.length; ++i) { - const index = sortedPendingValueHints[i]; - expect(nullifiers[i].value.equals(sortedPendingValues[index].value)).toBe(true); - } - }); - - it('builds hints for half-full sorted nullifiers', async () => { - const numNonEmptyNullifiers = MAX_NULLIFIERS_PER_TX / 2; - populateNullifiers(numNonEmptyNullifiers); - - const hints = await buildHints(); - const { sortedPendingValues, sortedPendingValueHints } = hints; - - // The first half contains sorted values. - for (let i = 0; i < numNonEmptyNullifiers - 1; ++i) { - expect(sortedPendingValues[i]).not.toEqual(Nullifier.empty()); - expect(sortedPendingValues[i].value.lt(sortedPendingValues[i + 1].value)).toBe(true); - } - for (let i = 0; i < numNonEmptyNullifiers; ++i) { - const index = sortedPendingValueHints[i]; - expect(nullifiers[i].value.equals(sortedPendingValues[index].value)).toBe(true); - } - - // The second half is empty. - for (let i = numNonEmptyNullifiers; i < sortedPendingValues.length; ++i) { - expect(sortedPendingValues[i]).toEqual(Nullifier.empty()); - } - for (let i = numNonEmptyNullifiers; i < sortedPendingValueHints.length; ++i) { - expect(sortedPendingValueHints[i]).toBe(0); - } - }); - - it('builds hints for read requests', async () => { - const numNonEmptyNullifiers = MAX_NULLIFIERS_PER_TX / 2; - expect(numNonEmptyNullifiers > 1).toBe(true); // Need at least 2 nullifiers to test a value in the middle. - - const sortedNullifiers = generateSortedNullifiers(numNonEmptyNullifiers + 3); - const minNullifier = sortedNullifiers.splice(0, 1)[0]; - const maxNullifier = sortedNullifiers.pop()!; - const midIndex = Math.floor(numNonEmptyNullifiers / 2); - const midNullifier = sortedNullifiers.splice(midIndex, 1)[0]; - - nonExistentReadRequests[0] = makeReadRequest(midNullifier.value); - nonExistentReadRequests[1] = makeReadRequest(maxNullifier.value); - nonExistentReadRequests[2] = makeReadRequest(minNullifier.value); - nullifiers = padArrayEnd( - sortedNullifiers.map(n => makeNullifier(n.value)), - Nullifier.empty(), - MAX_NULLIFIERS_PER_TX, - ); - - const hints = await buildHints(); - const { nextPendingValueIndices } = hints; - expect(nextPendingValueIndices.slice(0, 3)).toEqual([midIndex, numNonEmptyNullifiers, 0]); - }); - - it('throws if reading existing value', async () => { - populateNullifiers(); - - nonExistentReadRequests[0] = makeReadRequest(innerNullifier(2)); - - await expect(() => buildHints()).rejects.toThrow( - 'Nullifier DOES exists in the pending set at the time of reading, but there is a NonExistentReadRequest for it.', - ); - }); -}); diff --git a/yarn-project/circuits.js/src/hints/build_nullifier_non_existent_read_request_hints.ts b/yarn-project/circuits.js/src/hints/build_nullifier_non_existent_read_request_hints.ts deleted file mode 100644 index ea142b12ccd1..000000000000 --- a/yarn-project/circuits.js/src/hints/build_nullifier_non_existent_read_request_hints.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { padArrayEnd } from '@aztec/foundation/collection'; -import { type Fr } from '@aztec/foundation/fields'; -import { type Tuple } from '@aztec/foundation/serialize'; - -import { - MAX_NULLIFIERS_PER_TX, - type MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - type NULLIFIER_TREE_HEIGHT, -} from '../constants.gen.js'; -import { siloNullifier } from '../hash/index.js'; -import { Nullifier, type NullifierLeafPreimage } from '../structs/index.js'; -import { type MembershipWitness } from '../structs/membership_witness.js'; -import { NullifierNonExistentReadRequestHintsBuilder } from '../structs/non_existent_read_request_hints.js'; -import { type ScopedReadRequest } from '../structs/read_request.js'; -import { countAccumulatedItems } from '../utils/index.js'; - -interface NullifierMembershipWitnessWithPreimage { - membershipWitness: MembershipWitness; - leafPreimage: NullifierLeafPreimage; -} - -interface SortedResult { - sortedValues: Tuple; - sortedIndexHints: Tuple; -} - -function sortNullifiersByValues( - nullifiers: Tuple, -): SortedResult { - const numNullifiers = countAccumulatedItems(nullifiers); - const sorted = nullifiers - .slice(0, numNullifiers) - .map((nullifier, originalIndex) => ({ nullifier, originalIndex })) - .sort((a, b) => (b.nullifier.value.lt(a.nullifier.value) ? 1 : -1)); - - const sortedIndexHints: number[] = []; - for (let i = 0; i < numNullifiers; ++i) { - sortedIndexHints[sorted[i].originalIndex] = i; - } - - return { - sortedValues: padArrayEnd( - sorted.map(s => s.nullifier), - Nullifier.empty(), - MAX_NULLIFIERS_PER_TX, - ), - sortedIndexHints: padArrayEnd(sortedIndexHints, 0, MAX_NULLIFIERS_PER_TX), - }; -} - -export async function buildNullifierNonExistentReadRequestHints( - oracle: { - getLowNullifierMembershipWitness(nullifier: Fr): Promise; - }, - nullifierNonExistentReadRequests: Tuple, - pendingNullifiers: Tuple, -) { - const { sortedValues, sortedIndexHints } = sortNullifiersByValues(pendingNullifiers); - - const builder = new NullifierNonExistentReadRequestHintsBuilder(sortedValues, sortedIndexHints); - - const numPendingNullifiers = countAccumulatedItems(pendingNullifiers); - const numReadRequests = countAccumulatedItems(nullifierNonExistentReadRequests); - for (let i = 0; i < numReadRequests; ++i) { - const readRequest = nullifierNonExistentReadRequests[i]; - const siloedValue = siloNullifier(readRequest.contractAddress, readRequest.value); - - const { membershipWitness, leafPreimage } = await oracle.getLowNullifierMembershipWitness(siloedValue); - - let nextPendingValueIndex = sortedValues.findIndex(v => !v.value.lt(siloedValue)); - if (nextPendingValueIndex == -1) { - nextPendingValueIndex = numPendingNullifiers; - } else if ( - sortedValues[nextPendingValueIndex].value.equals(siloedValue) && - sortedValues[nextPendingValueIndex].counter < readRequest.counter - ) { - throw new Error( - 'Nullifier DOES exists in the pending set at the time of reading, but there is a NonExistentReadRequest for it.', - ); - } - - builder.addHint(membershipWitness, leafPreimage, nextPendingValueIndex); - } - - return builder.toHints(); -} diff --git a/yarn-project/circuits.js/src/hints/build_public_data_hints.test.ts b/yarn-project/circuits.js/src/hints/build_public_data_hints.test.ts deleted file mode 100644 index d88703a1d754..000000000000 --- a/yarn-project/circuits.js/src/hints/build_public_data_hints.test.ts +++ /dev/null @@ -1,116 +0,0 @@ -import { makeTuple } from '@aztec/foundation/array'; -import { padArrayEnd } from '@aztec/foundation/collection'; -import { Fr } from '@aztec/foundation/fields'; -import { type Tuple } from '@aztec/foundation/serialize'; - -import { - MAX_PUBLIC_DATA_HINTS, - MAX_PUBLIC_DATA_READS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, -} from '../constants.gen.js'; -import { PublicDataRead, PublicDataTreeLeafPreimage, PublicDataUpdateRequest } from '../structs/index.js'; -import { buildPublicDataHints } from './build_public_data_hints.js'; - -describe('buildPublicDataHints', () => { - let publicDataReads: Tuple; - let publicDataUpdateRequests: Tuple; - - const publicDataLeaves = [ - new PublicDataTreeLeafPreimage(new Fr(0), new Fr(0), new Fr(11), 2n), - new PublicDataTreeLeafPreimage(new Fr(22), new Fr(200), new Fr(0), 0n), - new PublicDataTreeLeafPreimage(new Fr(11), new Fr(100), new Fr(22), 1n), - ]; - - const makePublicDataRead = (leafSlot: number, value: number) => - new PublicDataRead(new Fr(leafSlot), new Fr(value), 0); - const makePublicDataWrite = (leafSlot: number, value: number) => - new PublicDataUpdateRequest(new Fr(leafSlot), new Fr(value), 0); - - const oracle = { - getMatchOrLowPublicDataMembershipWitness: (leafSlot: bigint) => { - const leafPreimage = publicDataLeaves.find( - l => l.slot.toBigInt() <= leafSlot && (l.nextSlot.isZero() || l.nextSlot.toBigInt() > leafSlot), - ); - return { membershipWitness: {}, leafPreimage } as any; - }, - }; - - const buildAndCheckHints = async (expectedSlots: number[]) => { - const hints = await buildPublicDataHints(oracle, publicDataReads, publicDataUpdateRequests); - const partialHints = expectedSlots.map(s => - expect.objectContaining({ - preimage: publicDataLeaves.find(l => l.slot.equals(new Fr(s))), - }), - ); - const emptyPartialHint = expect.objectContaining({ preimage: PublicDataTreeLeafPreimage.empty() }); - expect(hints).toEqual(padArrayEnd(partialHints, emptyPartialHint, MAX_PUBLIC_DATA_HINTS)); - }; - - beforeEach(() => { - publicDataReads = makeTuple(MAX_PUBLIC_DATA_READS_PER_TX, PublicDataRead.empty); - publicDataUpdateRequests = makeTuple(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, PublicDataUpdateRequest.empty); - }); - - it('returns empty hints', async () => { - await buildAndCheckHints([]); - }); - - it('builds hints for reads for uninitialized slots', async () => { - publicDataReads[0] = makePublicDataRead(12, 0); - publicDataReads[1] = makePublicDataRead(39, 0); - await buildAndCheckHints([11, 22]); - }); - - it('builds hints for reads for initialized slots', async () => { - publicDataReads[0] = makePublicDataRead(22, 200); - publicDataReads[1] = makePublicDataRead(11, 100); - await buildAndCheckHints([22, 11]); - }); - - it('builds hints for writes to uninitialized slots', async () => { - publicDataUpdateRequests[0] = makePublicDataWrite(5, 500); - publicDataUpdateRequests[1] = makePublicDataWrite(17, 700); - await buildAndCheckHints([0, 11]); - }); - - it('builds hints for writes to initialized slots', async () => { - publicDataUpdateRequests[0] = makePublicDataWrite(11, 111); - publicDataUpdateRequests[1] = makePublicDataWrite(22, 222); - await buildAndCheckHints([11, 22]); - }); - - it('skip hints for repeated reads', async () => { - publicDataReads[0] = makePublicDataRead(22, 200); // 22 - publicDataReads[1] = makePublicDataRead(39, 0); // 22 - publicDataReads[2] = makePublicDataRead(22, 200); // No hint needed because slot 22 was read. - publicDataReads[3] = makePublicDataRead(39, 0); // No hint needed because slot 39 was read. - publicDataReads[4] = makePublicDataRead(12, 0); // 11 - publicDataReads[5] = makePublicDataRead(39, 0); // // No hint needed because slot 39 was read. - await buildAndCheckHints([22, 22, 11]); - }); - - it('skip hints for repeated writes', async () => { - publicDataUpdateRequests[0] = makePublicDataWrite(11, 111); // 11 - publicDataUpdateRequests[1] = makePublicDataWrite(5, 500); // 0 - publicDataUpdateRequests[2] = makePublicDataWrite(11, 112); // No hint needed because slot 11 was written. - publicDataUpdateRequests[3] = makePublicDataWrite(17, 700); // 11 - publicDataUpdateRequests[4] = makePublicDataWrite(11, 113); // No hint needed because slot 11 was written. - publicDataUpdateRequests[5] = makePublicDataWrite(5, 222); // No hint needed because slot 5 was written. - publicDataUpdateRequests[6] = makePublicDataWrite(37, 700); // 22 - await buildAndCheckHints([11, 0, 11, 22]); - }); - - it('builds hints for mixed reads and writes', async () => { - publicDataReads[0] = makePublicDataRead(22, 200); // 22 - publicDataReads[1] = makePublicDataRead(7, 0); // 0 - publicDataReads[2] = makePublicDataRead(41, 0); // 22 - publicDataReads[3] = makePublicDataRead(11, 100); // 11 - publicDataReads[4] = makePublicDataRead(39, 0); // 22 - publicDataUpdateRequests[0] = makePublicDataWrite(11, 111); // No hint needed because slot 11 was read. - publicDataUpdateRequests[1] = makePublicDataWrite(5, 500); // 0 - publicDataUpdateRequests[2] = makePublicDataWrite(17, 700); // 11 - publicDataUpdateRequests[3] = makePublicDataWrite(22, 222); // No hint needed because slot 22 was read. - publicDataUpdateRequests[4] = makePublicDataWrite(39, 700); // No hint needed because slot 39 was read. - await buildAndCheckHints([22, 0, 22, 11, 22, 0, 11]); - }); -}); diff --git a/yarn-project/circuits.js/src/hints/build_public_data_hints.ts b/yarn-project/circuits.js/src/hints/build_public_data_hints.ts deleted file mode 100644 index 53200bab3640..000000000000 --- a/yarn-project/circuits.js/src/hints/build_public_data_hints.ts +++ /dev/null @@ -1,52 +0,0 @@ -import { padArrayEnd } from '@aztec/foundation/collection'; -import { Fr } from '@aztec/foundation/fields'; -import { type Tuple } from '@aztec/foundation/serialize'; - -import { - MAX_PUBLIC_DATA_HINTS, - type MAX_PUBLIC_DATA_READS_PER_TX, - type MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - type PUBLIC_DATA_TREE_HEIGHT, -} from '../constants.gen.js'; -import { - PublicDataLeafHint, - type PublicDataRead, - type PublicDataTreeLeafPreimage, - type PublicDataUpdateRequest, -} from '../structs/index.js'; -import { type MembershipWitness } from '../structs/membership_witness.js'; -import { PublicDataHint } from '../structs/public_data_hint.js'; - -interface PublicDataMembershipWitnessWithPreimage { - membershipWitness: MembershipWitness; - leafPreimage: PublicDataTreeLeafPreimage; -} - -type PublicDataMembershipWitnessOracle = { - getMatchOrLowPublicDataMembershipWitness(leafSlot: bigint): Promise; -}; - -async function buildPublicDataLeafHint(oracle: PublicDataMembershipWitnessOracle, leafSlot: bigint) { - const { membershipWitness, leafPreimage } = await oracle.getMatchOrLowPublicDataMembershipWitness(leafSlot); - return new PublicDataLeafHint(leafPreimage, membershipWitness); -} - -export async function buildPublicDataHints( - oracle: PublicDataMembershipWitnessOracle, - publicDataReads: Tuple, - publicDataUpdateRequests: Tuple, -): Promise> { - const leafSlots = [...publicDataReads.map(r => r.leafSlot), ...publicDataUpdateRequests.map(w => w.leafSlot)] - .filter(s => !s.isZero()) - .map(s => s.toBigInt()); - const uniqueLeafSlots = [...new Set(leafSlots)]; - const hints = await Promise.all(uniqueLeafSlots.map(slot => buildPublicDataLeafHint(oracle, slot))); - return padArrayEnd(hints, PublicDataLeafHint.empty(), MAX_PUBLIC_DATA_HINTS); -} - -export async function buildPublicDataHint(oracle: PublicDataMembershipWitnessOracle, leafSlot: bigint) { - const { membershipWitness, leafPreimage } = await oracle.getMatchOrLowPublicDataMembershipWitness(leafSlot); - const exists = leafPreimage.slot.toBigInt() === leafSlot; - const value = exists ? leafPreimage.value : Fr.ZERO; - return new PublicDataHint(new Fr(leafSlot), value, 0, membershipWitness, leafPreimage); -} diff --git a/yarn-project/circuits.js/src/hints/index.ts b/yarn-project/circuits.js/src/hints/index.ts index 2da0098c29b5..5d673ff520a7 100644 --- a/yarn-project/circuits.js/src/hints/index.ts +++ b/yarn-project/circuits.js/src/hints/index.ts @@ -1,6 +1,4 @@ export * from './build_note_hash_read_request_hints.js'; -export * from './build_nullifier_non_existent_read_request_hints.js'; export * from './build_nullifier_read_request_hints.js'; -export * from './build_public_data_hints.js'; export * from './build_transient_data_hints.js'; export * from './find_private_kernel_reset_dimensions.js'; diff --git a/yarn-project/circuits.js/src/scripts/constants.in.ts b/yarn-project/circuits.js/src/scripts/constants.in.ts index 369a9c94ae95..0b3aff93742f 100644 --- a/yarn-project/circuits.js/src/scripts/constants.in.ts +++ b/yarn-project/circuits.js/src/scripts/constants.in.ts @@ -21,7 +21,6 @@ const CPP_CONSTANTS = [ 'STATE_REFERENCE_LENGTH', 'HEADER_LENGTH', 'CALL_CONTEXT_LENGTH', - 'PUBLIC_CONTEXT_INPUTS_LENGTH', 'PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH', 'READ_REQUEST_LENGTH', 'MAX_NOTE_HASH_READ_REQUESTS_PER_CALL', diff --git a/yarn-project/circuits.js/src/structs/index.ts b/yarn-project/circuits.js/src/structs/index.ts index 39b77654dce1..96b87bbbc6f0 100644 --- a/yarn-project/circuits.js/src/structs/index.ts +++ b/yarn-project/circuits.js/src/structs/index.ts @@ -18,7 +18,6 @@ export * from './header.js'; export * from './tagging_secret.js'; export * from './kernel/combined_accumulated_data.js'; export * from './kernel/combined_constant_data.js'; -export * from './kernel/enqueued_call_data.js'; export * from './kernel/private_kernel_empty_inputs.js'; export * from './kernel/kernel_circuit_public_inputs.js'; export * from './kernel/private_accumulated_data.js'; @@ -36,20 +35,13 @@ export * from './kernel/private_to_avm_accumulated_data.js'; export * from './kernel/private_to_public_accumulated_data.js'; export * from './kernel/private_to_public_accumulated_data_builder.js'; export * from './kernel/private_to_public_kernel_circuit_public_inputs.js'; -export * from './kernel/public_accumulated_data.js'; -export * from './kernel/public_kernel_circuit_private_inputs.js'; -export * from './kernel/public_kernel_circuit_public_inputs.js'; -export * from './kernel/public_kernel_data.js'; -export * from './kernel/public_kernel_tail_circuit_private_inputs.js'; export * from './kernel/tx_constant_data.js'; -export * from './kernel/vm_circuit_public_inputs.js'; export * from './key_validation_request.js'; export * from './key_validation_request_and_generator.js'; export * from './l2_to_l1_message.js'; export * from './log_hash.js'; export * from './max_block_number.js'; export * from './membership_witness.js'; -export * from './non_existent_read_request_hints.js'; export * from './note_hash.js'; export * from './nullifier.js'; export * from './optional_number.js'; @@ -66,12 +58,10 @@ export * from './public_call_request.js'; export * from './public_call_stack_item_compressed.js'; export * from './public_circuit_public_inputs.js'; export * from './public_data_hint.js'; -export * from './public_data_leaf_hint.js'; export * from './public_data_read.js'; export * from './public_data_update_request.js'; export * from './public_data_write.js'; export * from './public_inner_call_request.js'; -export * from './public_validation_requests.js'; export * from './read_request.js'; export * from './read_request_hints/index.js'; export * from './recursive_proof.js'; @@ -100,7 +90,6 @@ export * from './scoped_key_validation_request_and_generator.js'; export * from './shared.js'; export * from './state_reference.js'; export * from './tree_leaf_read_request.js'; -export * from './tree_leaf_read_request_hint.js'; export * from './tree_snapshots.js'; export * from './trees/index.js'; export * from './tx_context.js'; diff --git a/yarn-project/circuits.js/src/structs/kernel/enqueued_call_data.ts b/yarn-project/circuits.js/src/structs/kernel/enqueued_call_data.ts deleted file mode 100644 index 86a500d2bc1b..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/enqueued_call_data.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { Proof } from '../proof.js'; -import { VMCircuitPublicInputs } from './vm_circuit_public_inputs.js'; - -/** - * Public calldata assembled from the kernel execution result and proof. - */ -export class EnqueuedCallData { - constructor(public readonly data: VMCircuitPublicInputs, public readonly proof: Proof) {} - - toBuffer() { - return serializeToBuffer(this.data, this.proof); - } - - static fromBuffer(buffer: BufferReader | Buffer) { - const reader = BufferReader.asReader(buffer); - return new EnqueuedCallData(reader.readObject(VMCircuitPublicInputs), reader.readObject(Proof)); - } -} diff --git a/yarn-project/circuits.js/src/structs/kernel/private_to_public_accumulated_data_builder.ts b/yarn-project/circuits.js/src/structs/kernel/private_to_public_accumulated_data_builder.ts index dd734a3e8ff9..66733d24df01 100644 --- a/yarn-project/circuits.js/src/structs/kernel/private_to_public_accumulated_data_builder.ts +++ b/yarn-project/circuits.js/src/structs/kernel/private_to_public_accumulated_data_builder.ts @@ -17,8 +17,8 @@ import { PrivateToPublicAccumulatedData } from './private_to_public_accumulated_ /** * TESTS-ONLY CLASS - * Builder for PublicAccumulatedData, used to conveniently construct instances for testing, - * as PublicAccumulatedData is (or will shortly be) immutable. + * Builder for PrivateToPublicAccumulatedData, used to conveniently construct instances for testing, + * as PrivateToPublicAccumulatedData is (or will shortly be) immutable. * */ export class PrivateToPublicAccumulatedDataBuilder { @@ -28,7 +28,7 @@ export class PrivateToPublicAccumulatedDataBuilder { private noteEncryptedLogsHashes: LogHash[] = []; private encryptedLogsHashes: ScopedLogHash[] = []; private contractClassLogsHashes: ScopedLogHash[] = []; - private publicCallStack: PublicCallRequest[] = []; + private publicCallRequests: PublicCallRequest[] = []; pushNoteHash(newNoteHash: Fr) { this.noteHashes.push(newNoteHash); @@ -91,12 +91,12 @@ export class PrivateToPublicAccumulatedDataBuilder { } pushPublicCall(publicCall: PublicCallRequest) { - this.publicCallStack.push(publicCall); + this.publicCallRequests.push(publicCall); return this; } - withPublicCallStack(publicCallStack: PublicCallRequest[]) { - this.publicCallStack = publicCallStack; + withPublicCallRequests(publicCallRequests: PublicCallRequest[]) { + this.publicCallRequests = publicCallRequests; return this; } @@ -108,18 +108,7 @@ export class PrivateToPublicAccumulatedDataBuilder { padArrayEnd(this.noteEncryptedLogsHashes, LogHash.empty(), MAX_NOTE_ENCRYPTED_LOGS_PER_TX), padArrayEnd(this.encryptedLogsHashes, ScopedLogHash.empty(), MAX_ENCRYPTED_LOGS_PER_TX), padArrayEnd(this.contractClassLogsHashes, ScopedLogHash.empty(), MAX_CONTRACT_CLASS_LOGS_PER_TX), - padArrayEnd(this.publicCallStack, PublicCallRequest.empty(), MAX_ENQUEUED_CALLS_PER_TX), + padArrayEnd(this.publicCallRequests, PublicCallRequest.empty(), MAX_ENQUEUED_CALLS_PER_TX), ); } - - static fromPublicAccumulatedData(publicAccumulatedData: PrivateToPublicAccumulatedData) { - return new PrivateToPublicAccumulatedDataBuilder() - .withNoteHashes(publicAccumulatedData.noteHashes) - .withNullifiers(publicAccumulatedData.nullifiers) - .withL2ToL1Msgs(publicAccumulatedData.l2ToL1Msgs) - .withNoteEncryptedLogsHashes(publicAccumulatedData.noteEncryptedLogsHashes) - .withEncryptedLogsHashes(publicAccumulatedData.encryptedLogsHashes) - .withContractClassLogsHashes(publicAccumulatedData.contractClassLogsHashes) - .withPublicCallStack(publicAccumulatedData.publicCallRequests); - } } diff --git a/yarn-project/circuits.js/src/structs/kernel/public_accumulated_data.ts b/yarn-project/circuits.js/src/structs/kernel/public_accumulated_data.ts deleted file mode 100644 index 4a366853ebf8..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/public_accumulated_data.ts +++ /dev/null @@ -1,321 +0,0 @@ -import { makeTuple } from '@aztec/foundation/array'; -import { arraySerializedSizeOfNonEmpty } from '@aztec/foundation/collection'; -import { type Fr } from '@aztec/foundation/fields'; -import { BufferReader, FieldReader, type Tuple, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { inspect } from 'util'; - -import { - MAX_ENCRYPTED_LOGS_PER_TX, - MAX_ENQUEUED_CALLS_PER_TX, - MAX_L2_TO_L1_MSGS_PER_TX, - MAX_NOTE_ENCRYPTED_LOGS_PER_TX, - MAX_NOTE_HASHES_PER_TX, - MAX_NULLIFIERS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - MAX_UNENCRYPTED_LOGS_PER_TX, - NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS, -} from '../../constants.gen.js'; -import { countAccumulatedItems } from '../../utils/index.js'; -import { Gas } from '../gas.js'; -import { ScopedL2ToL1Message } from '../l2_to_l1_message.js'; -import { LogHash, ScopedLogHash } from '../log_hash.js'; -import { ScopedNoteHash } from '../note_hash.js'; -import { Nullifier } from '../nullifier.js'; -import { PublicCallRequest } from '../public_call_request.js'; -import { PublicDataUpdateRequest } from '../public_data_update_request.js'; - -export class PublicAccumulatedData { - constructor( - /** - * The new note hashes made in this transaction. - */ - public readonly noteHashes: Tuple, - /** - * The new nullifiers made in this transaction. - */ - public readonly nullifiers: Tuple, - /** - * All the new L2 to L1 messages created in this transaction. - */ - public readonly l2ToL1Msgs: Tuple, - /** - * Accumulated encrypted note logs hashes from all the previous kernel iterations. - * Note: Truncated to 31 bytes to fit in Fr. - */ - public readonly noteEncryptedLogsHashes: Tuple, - /** - * Accumulated encrypted logs hashes from all the previous kernel iterations. - * Note: Truncated to 31 bytes to fit in Fr. - */ - public readonly encryptedLogsHashes: Tuple, - /** - * Accumulated unencrypted logs hashes from all the previous kernel iterations. - * Note: Truncated to 31 bytes to fit in Fr. - */ - public readonly unencryptedLogsHashes: Tuple, - /** - * All the public data update requests made in this transaction. - */ - public readonly publicDataUpdateRequests: Tuple< - PublicDataUpdateRequest, - typeof MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX - >, - /** - * Current public call stack. - */ - public readonly publicCallStack: Tuple, - - /** Gas used so far by the transaction. */ - public readonly gasUsed: Gas, - ) {} - - getSize() { - return ( - arraySerializedSizeOfNonEmpty(this.noteHashes) + - arraySerializedSizeOfNonEmpty(this.nullifiers) + - arraySerializedSizeOfNonEmpty(this.l2ToL1Msgs) + - arraySerializedSizeOfNonEmpty(this.noteEncryptedLogsHashes) + - arraySerializedSizeOfNonEmpty(this.encryptedLogsHashes) + - arraySerializedSizeOfNonEmpty(this.unencryptedLogsHashes) + - arraySerializedSizeOfNonEmpty(this.publicDataUpdateRequests) + - arraySerializedSizeOfNonEmpty(this.publicCallStack) + - this.gasUsed.toBuffer().length - ); - } - - toBuffer() { - return serializeToBuffer( - this.noteHashes, - this.nullifiers, - this.l2ToL1Msgs, - this.noteEncryptedLogsHashes, - this.encryptedLogsHashes, - this.unencryptedLogsHashes, - this.publicDataUpdateRequests, - this.publicCallStack, - this.gasUsed, - ); - } - - toString() { - return this.toBuffer().toString('hex'); - } - - isEmpty(): boolean { - return ( - this.noteHashes.every(x => x.isEmpty()) && - this.nullifiers.every(x => x.isEmpty()) && - this.l2ToL1Msgs.every(x => x.isEmpty()) && - this.noteEncryptedLogsHashes.every(x => x.isEmpty()) && - this.encryptedLogsHashes.every(x => x.isEmpty()) && - this.unencryptedLogsHashes.every(x => x.isEmpty()) && - this.publicDataUpdateRequests.every(x => x.isEmpty()) && - this.publicCallStack.every(x => x.isEmpty()) && - this.gasUsed.isEmpty() - ); - } - - [inspect.custom]() { - // print out the non-empty fields - return `PublicAccumulatedData { - noteHashes: [${this.noteHashes - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - nullifiers: [${this.nullifiers - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - l2ToL1Msgs: [${this.l2ToL1Msgs - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - noteEncryptedLogsHashes: [${this.noteEncryptedLogsHashes - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - encryptedLogsHashes: [${this.encryptedLogsHashes - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - unencryptedLogsHashes: [${this.unencryptedLogsHashes - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - publicDataUpdateRequests: [${this.publicDataUpdateRequests - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - publicCallStack: [${this.publicCallStack - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - gasUsed: [${inspect(this.gasUsed)}] -}`; - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or reader to read from. - * @returns Deserialized object. - */ - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new this( - reader.readArray(MAX_NOTE_HASHES_PER_TX, ScopedNoteHash), - reader.readArray(MAX_NULLIFIERS_PER_TX, Nullifier), - reader.readArray(MAX_L2_TO_L1_MSGS_PER_TX, ScopedL2ToL1Message), - reader.readArray(MAX_NOTE_ENCRYPTED_LOGS_PER_TX, LogHash), - reader.readArray(MAX_ENCRYPTED_LOGS_PER_TX, ScopedLogHash), - reader.readArray(MAX_UNENCRYPTED_LOGS_PER_TX, ScopedLogHash), - reader.readArray(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, PublicDataUpdateRequest), - reader.readArray(MAX_ENQUEUED_CALLS_PER_TX, PublicCallRequest), - reader.readObject(Gas), - ); - } - - static fromFields(fields: Fr[] | FieldReader) { - const reader = FieldReader.asReader(fields); - return new this( - reader.readArray(MAX_NOTE_HASHES_PER_TX, ScopedNoteHash), - reader.readArray(MAX_NULLIFIERS_PER_TX, Nullifier), - reader.readArray(MAX_L2_TO_L1_MSGS_PER_TX, ScopedL2ToL1Message), - reader.readArray(MAX_NOTE_ENCRYPTED_LOGS_PER_TX, LogHash), - reader.readArray(MAX_ENCRYPTED_LOGS_PER_TX, ScopedLogHash), - reader.readArray(MAX_UNENCRYPTED_LOGS_PER_TX, ScopedLogHash), - reader.readArray(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, PublicDataUpdateRequest), - reader.readArray(MAX_ENQUEUED_CALLS_PER_TX, PublicCallRequest), - reader.readObject(Gas), - ); - } - - /** - * Deserializes from a string, corresponding to a write in cpp. - * @param str - String to read from. - * @returns Deserialized object. - */ - static fromString(str: string) { - return this.fromBuffer(Buffer.from(str, 'hex')); - } - - static empty() { - return new this( - makeTuple(MAX_NOTE_HASHES_PER_TX, ScopedNoteHash.empty), - makeTuple(MAX_NULLIFIERS_PER_TX, Nullifier.empty), - makeTuple(MAX_L2_TO_L1_MSGS_PER_TX, ScopedL2ToL1Message.empty), - makeTuple(MAX_NOTE_ENCRYPTED_LOGS_PER_TX, LogHash.empty), - makeTuple(MAX_ENCRYPTED_LOGS_PER_TX, ScopedLogHash.empty), - makeTuple(MAX_UNENCRYPTED_LOGS_PER_TX, ScopedLogHash.empty), - makeTuple(MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, PublicDataUpdateRequest.empty), - makeTuple(MAX_ENQUEUED_CALLS_PER_TX, PublicCallRequest.empty), - Gas.empty(), - ); - } -} - -export class PublicAccumulatedDataArrayLengths { - constructor( - public readonly noteHashes: number, - public readonly nullifiers: number, - public readonly l2ToL1Msgs: number, - public readonly noteEncryptedLogsHashes: number, - public readonly encryptedLogsHashes: number, - public readonly unencryptedLogsHashes: number, - public readonly publicDataUpdateRequests: number, - public readonly publicCallStack: number, - ) {} - - static new(data: PublicAccumulatedData) { - return new PublicAccumulatedDataArrayLengths( - countAccumulatedItems(data.noteHashes), - countAccumulatedItems(data.nullifiers), - countAccumulatedItems(data.l2ToL1Msgs), - countAccumulatedItems(data.noteEncryptedLogsHashes), - countAccumulatedItems(data.encryptedLogsHashes), - countAccumulatedItems(data.unencryptedLogsHashes), - countAccumulatedItems(data.publicDataUpdateRequests), - countAccumulatedItems(data.publicCallStack), - ); - } - - getSize() { - return NUM_PUBLIC_ACCUMULATED_DATA_ARRAYS; - } - - toBuffer() { - return serializeToBuffer( - this.noteHashes, - this.nullifiers, - this.l2ToL1Msgs, - this.noteEncryptedLogsHashes, - this.encryptedLogsHashes, - this.unencryptedLogsHashes, - this.publicDataUpdateRequests, - this.publicCallStack, - ); - } - - toString() { - return this.toBuffer().toString('hex'); - } - - isEmpty(): boolean { - return ( - this.noteHashes == 0 && - this.nullifiers == 0 && - this.l2ToL1Msgs == 0 && - this.noteEncryptedLogsHashes == 0 && - this.encryptedLogsHashes == 0 && - this.unencryptedLogsHashes == 0 && - this.publicDataUpdateRequests == 0 && - this.publicCallStack == 0 - ); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or reader to read from. - * @returns Deserialized object. - */ - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new this( - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - ); - } - - static fromFields(fields: Fr[] | FieldReader) { - const reader = FieldReader.asReader(fields); - return new this( - reader.readU32(), - reader.readU32(), - reader.readU32(), - reader.readU32(), - reader.readU32(), - reader.readU32(), - reader.readU32(), - reader.readU32(), - ); - } - - /** - * Deserializes from a string, corresponding to a write in cpp. - * @param str - String to read from. - * @returns Deserialized object. - */ - static fromString(str: string) { - return this.fromBuffer(Buffer.from(str, 'hex')); - } - - static empty() { - return new this(0, 0, 0, 0, 0, 0, 0, 0); - } -} diff --git a/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_private_inputs.test.ts b/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_private_inputs.test.ts deleted file mode 100644 index 9f783f1a3057..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_private_inputs.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { makePublicKernelCircuitPrivateInputs } from '../../tests/factories.js'; -import { PublicKernelCircuitPrivateInputs } from './public_kernel_circuit_private_inputs.js'; - -describe('PublicKernelCircuitPrivateInputs', () => { - it('PublicKernelCircuitPrivateInputs after serialization and deserialization is equal to the original', () => { - const original = makePublicKernelCircuitPrivateInputs(123); - const serialized = PublicKernelCircuitPrivateInputs.fromBuffer(original.toBuffer()); - expect(original).toEqual(serialized); - }); - - it('PublicKernelCircuitPrivateInputs after clone is equal to the original', () => { - const original = makePublicKernelCircuitPrivateInputs(123); - const serialized = original.clone(); - expect(original).toEqual(serialized); - expect(original).not.toBe(serialized); - }); - - it('serializes to and deserializes from a string', () => { - const original = makePublicKernelCircuitPrivateInputs(123); - const serialized = PublicKernelCircuitPrivateInputs.fromString(original.toString()); - expect(original).toEqual(serialized); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_private_inputs.ts b/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_private_inputs.ts deleted file mode 100644 index 8d6cf9870070..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_private_inputs.ts +++ /dev/null @@ -1,65 +0,0 @@ -import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { EnqueuedCallData } from './enqueued_call_data.js'; -import { PublicKernelData } from './public_kernel_data.js'; - -/** - * Inputs to the public kernel circuit. - */ -export class PublicKernelCircuitPrivateInputs { - constructor( - /** - * Kernels are recursive and this is the data from the previous kernel. - */ - public readonly previousKernel: PublicKernelData, - /** - * Public calldata assembled from the execution result and proof. - */ - public readonly enqueuedCall: EnqueuedCallData, - ) {} - - /** - * Serializes the object to a buffer. - * @returns - Buffer representation of the object. - */ - toBuffer() { - return serializeToBuffer(this.previousKernel, this.enqueuedCall); - } - - /** - * Serializes the object to a hex string. - * @returns - Hex string representation of the object. - */ - toString() { - return this.toBuffer().toString('hex'); - } - - /** - * Deserializes the object from a buffer. - * @param buffer - Buffer to deserialize. - * @returns - Deserialized object. - */ - static fromBuffer(buffer: BufferReader | Buffer) { - const reader = BufferReader.asReader(buffer); - const previousKernel = reader.readObject(PublicKernelData); - const enqueuedCall = reader.readObject(EnqueuedCallData); - return new PublicKernelCircuitPrivateInputs(previousKernel, enqueuedCall); - } - - /** - * Deserializes the object from a hex string. - * @param str - Hex string to deserialize. - * @returns - Deserialized object. - */ - static fromString(str: string) { - return PublicKernelCircuitPrivateInputs.fromBuffer(Buffer.from(str, 'hex')); - } - - /** - * Clones the object. - * @returns - Cloned object. - */ - clone() { - return PublicKernelCircuitPrivateInputs.fromBuffer(this.toBuffer()); - } -} diff --git a/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_public_inputs.test.ts b/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_public_inputs.test.ts deleted file mode 100644 index 8242e119c55b..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_public_inputs.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { makePublicKernelCircuitPublicInputs } from '../../tests/factories.js'; -import { PublicKernelCircuitPublicInputs } from './public_kernel_circuit_public_inputs.js'; - -describe('PublicKernelCircuitPublicInputs', () => { - it('PublicKernelCircuitPublicInputs after serialization and deserialization is equal to the original', () => { - const original = makePublicKernelCircuitPublicInputs(123); - const serialized = PublicKernelCircuitPublicInputs.fromBuffer(original.toBuffer()); - expect(original).toEqual(serialized); - }); - - it('PublicKernelCircuitPublicInputs after clone is equal to the original', () => { - const original = makePublicKernelCircuitPublicInputs(123); - const serialized = original.clone(); - expect(original).toEqual(serialized); - expect(original).not.toBe(serialized); - }); - - it('serializes to and deserializes from a string', () => { - const original = makePublicKernelCircuitPublicInputs(123); - const serialized = PublicKernelCircuitPublicInputs.fromString(original.toString()); - expect(original).toEqual(serialized); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_public_inputs.ts b/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_public_inputs.ts deleted file mode 100644 index 04214ea5b028..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/public_kernel_circuit_public_inputs.ts +++ /dev/null @@ -1,136 +0,0 @@ -import { AztecAddress } from '@aztec/foundation/aztec-address'; -import { type Fr } from '@aztec/foundation/fields'; -import { BufferReader, FieldReader, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { inspect } from 'util'; - -import { PublicCallRequest } from '../public_call_request.js'; -import { PublicValidationRequests } from '../public_validation_requests.js'; -import { RevertCode } from '../revert_code.js'; -import { CombinedConstantData } from './combined_constant_data.js'; -import { PublicAccumulatedData } from './public_accumulated_data.js'; - -/** - * Outputs from the public kernel circuits. - * All Public kernels use this shape for outputs. - */ -export class PublicKernelCircuitPublicInputs { - constructor( - /** - * Data which is not modified by the circuits. - */ - public constants: CombinedConstantData, - /** - * Validation requests accumulated from public functions. - */ - public validationRequests: PublicValidationRequests, - /** - * Accumulated side effects and enqueued calls that are not revertible. - */ - public endNonRevertibleData: PublicAccumulatedData, - /** - * Data accumulated from both public and private circuits. - */ - public end: PublicAccumulatedData, - /** - * Counter of the last side effect. - */ - public endSideEffectCounter: number, - /** - * The call request for the public teardown function - */ - public publicTeardownCallRequest: PublicCallRequest, - /** - * The address of the fee payer for the transaction - */ - public feePayer: AztecAddress, - /** - * Indicates whether execution of the public circuit reverted. - */ - public revertCode: RevertCode, - ) {} - - toBuffer() { - return serializeToBuffer( - this.constants, - this.validationRequests, - this.endNonRevertibleData, - this.end, - this.endSideEffectCounter, - this.publicTeardownCallRequest, - this.feePayer, - this.revertCode, - ); - } - - clone() { - return PublicKernelCircuitPublicInputs.fromBuffer(this.toBuffer()); - } - - toString() { - return this.toBuffer().toString('hex'); - } - - static fromString(str: string) { - return PublicKernelCircuitPublicInputs.fromBuffer(Buffer.from(str, 'hex')); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or reader to read from. - * @returns A new instance of PublicKernelCircuitPublicInputs. - */ - static fromBuffer(buffer: Buffer | BufferReader): PublicKernelCircuitPublicInputs { - const reader = BufferReader.asReader(buffer); - return new PublicKernelCircuitPublicInputs( - reader.readObject(CombinedConstantData), - reader.readObject(PublicValidationRequests), - reader.readObject(PublicAccumulatedData), - reader.readObject(PublicAccumulatedData), - reader.readNumber(), - reader.readObject(PublicCallRequest), - reader.readObject(AztecAddress), - reader.readObject(RevertCode), - ); - } - - static empty() { - return new PublicKernelCircuitPublicInputs( - CombinedConstantData.empty(), - PublicValidationRequests.empty(), - PublicAccumulatedData.empty(), - PublicAccumulatedData.empty(), - 0, - PublicCallRequest.empty(), - AztecAddress.ZERO, - RevertCode.OK, - ); - } - - static fromFields(fields: Fr[] | FieldReader): PublicKernelCircuitPublicInputs { - const reader = FieldReader.asReader(fields); - return new PublicKernelCircuitPublicInputs( - CombinedConstantData.fromFields(reader), - PublicValidationRequests.fromFields(reader), - PublicAccumulatedData.fromFields(reader), - PublicAccumulatedData.fromFields(reader), - reader.readU32(), - PublicCallRequest.fromFields(reader), - AztecAddress.fromFields(reader), - RevertCode.fromField(reader.readField()), - ); - } - - [inspect.custom]() { - return `PublicKernelCircuitPublicInputs { - constants: ${inspect(this.constants)}, - validationRequests: ${inspect(this.validationRequests)}, - endNonRevertibleData: ${inspect(this.endNonRevertibleData)}, - end: ${inspect(this.end)}, - endSideEffectCounter: ${this.endSideEffectCounter}, - publicTeardownCallRequest: ${inspect(this.publicTeardownCallRequest)}, - feePayer: ${this.feePayer}, - revertCode: ${this.revertCode}, - }`; - } -} diff --git a/yarn-project/circuits.js/src/structs/kernel/public_kernel_data.ts b/yarn-project/circuits.js/src/structs/kernel/public_kernel_data.ts deleted file mode 100644 index f771cc2207cf..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/public_kernel_data.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { makeTuple } from '@aztec/foundation/array'; -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader, type Tuple, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { NESTED_RECURSIVE_PROOF_LENGTH, VK_TREE_HEIGHT } from '../../constants.gen.js'; -import { ClientIvcProof } from '../client_ivc_proof.js'; -import { RecursiveProof, makeEmptyRecursiveProof } from '../recursive_proof.js'; -import { type UInt32 } from '../shared.js'; -import { VerificationKeyData } from '../verification_key.js'; -import { PublicKernelCircuitPublicInputs } from './public_kernel_circuit_public_inputs.js'; - -/** - * Data of the previous public kernel iteration in the chain of kernels. - */ -export class PublicKernelData { - constructor( - /** - * Public inputs of the previous kernel. - */ - public publicInputs: PublicKernelCircuitPublicInputs, - /** - * Proof of the previous kernel. - */ - public proof: RecursiveProof, - /** - * Verification key of the previous kernel. - */ - public vk: VerificationKeyData, - /** - * Index of the previous kernel's vk in a tree of vks. - */ - public vkIndex: UInt32, - /** - * Sibling path of the previous kernel's vk in a tree of vks. - */ - public vkPath: Tuple, - - /** - * TODO(https://github.com/AztecProtocol/aztec-packages/issues/7369) this should be tube-proved for the first iteration and replace proof above - */ - public clientIvcProof: ClientIvcProof = ClientIvcProof.empty(), - ) {} - - static fromBuffer(buffer: Buffer | BufferReader): PublicKernelData { - const reader = BufferReader.asReader(buffer); - return new this( - reader.readObject(PublicKernelCircuitPublicInputs), - RecursiveProof.fromBuffer(reader, NESTED_RECURSIVE_PROOF_LENGTH), - reader.readObject(VerificationKeyData), - reader.readNumber(), - reader.readArray(VK_TREE_HEIGHT, Fr), - reader.readObject(ClientIvcProof), - ); - } - - static empty(): PublicKernelData { - return new this( - PublicKernelCircuitPublicInputs.empty(), - makeEmptyRecursiveProof(NESTED_RECURSIVE_PROOF_LENGTH), - VerificationKeyData.makeFakeHonk(), - 0, - makeTuple(VK_TREE_HEIGHT, Fr.zero), - ClientIvcProof.empty(), - ); - } - - /** - * Serialize this as a buffer. - * @returns The buffer. - */ - toBuffer() { - return serializeToBuffer(this.publicInputs, this.proof, this.vk, this.vkIndex, this.vkPath, this.clientIvcProof); - } -} diff --git a/yarn-project/circuits.js/src/structs/kernel/public_kernel_tail_circuit_private_inputs.test.ts b/yarn-project/circuits.js/src/structs/kernel/public_kernel_tail_circuit_private_inputs.test.ts deleted file mode 100644 index 3e2767cbda35..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/public_kernel_tail_circuit_private_inputs.test.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { makePublicKernelTailCircuitPrivateInputs } from '../../tests/factories.js'; -import { PublicKernelTailCircuitPrivateInputs } from './public_kernel_tail_circuit_private_inputs.js'; - -describe('PublicKernelTailCircuitPrivateInputs', () => { - it('PublicKernelTailCircuitPrivateInputs after serialization and deserialization is equal to the original', () => { - const original = makePublicKernelTailCircuitPrivateInputs(123); - const serialized = PublicKernelTailCircuitPrivateInputs.fromBuffer(original.toBuffer()); - expect(original).toEqual(serialized); - }); - - it('PublicKernelTailCircuitPrivateInputs after clone is equal to the original', () => { - const original = makePublicKernelTailCircuitPrivateInputs(123); - const serialized = original.clone(); - expect(original).toEqual(serialized); - expect(original).not.toBe(serialized); - }); - - it('serializes to string and back', () => { - const original = makePublicKernelTailCircuitPrivateInputs(123); - const str = original.toString(); - const deserialized = PublicKernelTailCircuitPrivateInputs.fromString(str); - expect(original).toEqual(deserialized); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/kernel/public_kernel_tail_circuit_private_inputs.ts b/yarn-project/circuits.js/src/structs/kernel/public_kernel_tail_circuit_private_inputs.ts deleted file mode 100644 index c0bb9b4d82ff..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/public_kernel_tail_circuit_private_inputs.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { BufferReader, type Tuple, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { - L1_TO_L2_MSG_TREE_HEIGHT, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_HINTS, - NOTE_HASH_TREE_HEIGHT, -} from '../../constants.gen.js'; -import { - type NullifierNonExistentReadRequestHints, - nullifierNonExistentReadRequestHintsFromBuffer, -} from '../non_existent_read_request_hints.js'; -import { PartialStateReference } from '../partial_state_reference.js'; -import { PublicDataLeafHint } from '../public_data_leaf_hint.js'; -import { type NullifierReadRequestHints, nullifierReadRequestHintsFromBuffer } from '../read_request_hints/index.js'; -import { TreeLeafReadRequestHint } from '../tree_leaf_read_request_hint.js'; -import { PublicKernelData } from './public_kernel_data.js'; - -export class PublicKernelTailCircuitPrivateInputs { - constructor( - /** - * Kernels are recursive and this is the data from the previous kernel. - */ - public readonly previousKernel: PublicKernelData, - public readonly noteHashReadRequestHints: Tuple< - TreeLeafReadRequestHint, - typeof MAX_NOTE_HASH_READ_REQUESTS_PER_TX - >, - /** - * Contains hints for the nullifier read requests to locate corresponding pending or settled nullifiers. - */ - public readonly nullifierReadRequestHints: NullifierReadRequestHints< - typeof MAX_NULLIFIER_READ_REQUESTS_PER_TX, - typeof MAX_NULLIFIER_READ_REQUESTS_PER_TX - >, - /** - * Contains hints for the nullifier non existent read requests. - */ - public readonly nullifierNonExistentReadRequestHints: NullifierNonExistentReadRequestHints, - public readonly l1ToL2MsgReadRequestHints: Tuple< - TreeLeafReadRequestHint, - typeof MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX - >, - public readonly publicDataHints: Tuple, - public readonly startState: PartialStateReference, - ) {} - - toBuffer() { - return serializeToBuffer( - this.previousKernel, - this.noteHashReadRequestHints, - this.nullifierReadRequestHints, - this.nullifierNonExistentReadRequestHints, - this.l1ToL2MsgReadRequestHints, - this.publicDataHints, - this.startState, - ); - } - - toString() { - return this.toBuffer().toString('hex'); - } - - static fromString(str: string) { - return PublicKernelTailCircuitPrivateInputs.fromBuffer(Buffer.from(str, 'hex')); - } - - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new PublicKernelTailCircuitPrivateInputs( - reader.readObject(PublicKernelData), - reader.readArray(MAX_NOTE_HASH_READ_REQUESTS_PER_TX, { - fromBuffer: buf => TreeLeafReadRequestHint.fromBuffer(buf, NOTE_HASH_TREE_HEIGHT), - }), - nullifierReadRequestHintsFromBuffer( - reader, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, - ), - nullifierNonExistentReadRequestHintsFromBuffer(reader), - reader.readArray(MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, { - fromBuffer: buf => TreeLeafReadRequestHint.fromBuffer(buf, L1_TO_L2_MSG_TREE_HEIGHT), - }), - reader.readArray(MAX_PUBLIC_DATA_HINTS, PublicDataLeafHint), - reader.readObject(PartialStateReference), - ); - } - - clone() { - return PublicKernelTailCircuitPrivateInputs.fromBuffer(this.toBuffer()); - } -} diff --git a/yarn-project/circuits.js/src/structs/kernel/vm_circuit_public_inputs.ts b/yarn-project/circuits.js/src/structs/kernel/vm_circuit_public_inputs.ts deleted file mode 100644 index 7182981a3cb3..000000000000 --- a/yarn-project/circuits.js/src/structs/kernel/vm_circuit_public_inputs.ts +++ /dev/null @@ -1,131 +0,0 @@ -import { makeTuple } from '@aztec/foundation/array'; -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader, FieldReader, type Tuple, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { inspect } from 'util'; - -import { MAX_ENQUEUED_CALLS_PER_TX } from '../../constants.gen.js'; -import { Gas } from '../gas.js'; -import { PublicCallRequest } from '../public_call_request.js'; -import { PublicInnerCallRequest } from '../public_inner_call_request.js'; -import { PublicValidationRequestArrayLengths, PublicValidationRequests } from '../public_validation_requests.js'; -import { CombinedConstantData } from './combined_constant_data.js'; -import { PublicAccumulatedData, PublicAccumulatedDataArrayLengths } from './public_accumulated_data.js'; - -/** - * Call stack item on a public call. - */ -export class VMCircuitPublicInputs { - constructor( - public constants: CombinedConstantData, - public callRequest: PublicCallRequest, - public publicCallStack: Tuple, - public previousValidationRequestArrayLengths: PublicValidationRequestArrayLengths, - public validationRequests: PublicValidationRequests, - public previousAccumulatedDataArrayLengths: PublicAccumulatedDataArrayLengths, - public accumulatedData: PublicAccumulatedData, - public startSideEffectCounter: number, - public endSideEffectCounter: number, - public startGasLeft: Gas, - public transactionFee: Fr, - public reverted: boolean, - ) {} - - toBuffer() { - return serializeToBuffer( - this.constants, - this.callRequest, - this.publicCallStack, - this.previousValidationRequestArrayLengths, - this.validationRequests, - this.previousAccumulatedDataArrayLengths, - this.accumulatedData, - this.startSideEffectCounter, - this.endSideEffectCounter, - this.startGasLeft, - this.transactionFee, - this.reverted, - ); - } - - clone() { - return VMCircuitPublicInputs.fromBuffer(this.toBuffer()); - } - - toString() { - return this.toBuffer().toString('hex'); - } - - static fromString(str: string) { - return VMCircuitPublicInputs.fromBuffer(Buffer.from(str, 'hex')); - } - - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new VMCircuitPublicInputs( - reader.readObject(CombinedConstantData), - reader.readObject(PublicCallRequest), - reader.readArray(MAX_ENQUEUED_CALLS_PER_TX, PublicInnerCallRequest), - reader.readObject(PublicValidationRequestArrayLengths), - reader.readObject(PublicValidationRequests), - reader.readObject(PublicAccumulatedDataArrayLengths), - reader.readObject(PublicAccumulatedData), - reader.readNumber(), - reader.readNumber(), - reader.readObject(Gas), - reader.readObject(Fr), - reader.readBoolean(), - ); - } - - static empty() { - return new VMCircuitPublicInputs( - CombinedConstantData.empty(), - PublicCallRequest.empty(), - makeTuple(MAX_ENQUEUED_CALLS_PER_TX, PublicInnerCallRequest.empty), - PublicValidationRequestArrayLengths.empty(), - PublicValidationRequests.empty(), - PublicAccumulatedDataArrayLengths.empty(), - PublicAccumulatedData.empty(), - 0, - 0, - Gas.empty(), - Fr.ZERO, - false, - ); - } - - static fromFields(fields: Fr[] | FieldReader) { - const reader = FieldReader.asReader(fields); - return new VMCircuitPublicInputs( - CombinedConstantData.fromFields(reader), - PublicCallRequest.fromFields(reader), - reader.readArray(MAX_ENQUEUED_CALLS_PER_TX, PublicInnerCallRequest), - PublicValidationRequestArrayLengths.fromFields(reader), - PublicValidationRequests.fromFields(reader), - PublicAccumulatedDataArrayLengths.fromFields(reader), - PublicAccumulatedData.fromFields(reader), - reader.readU32(), - reader.readU32(), - Gas.fromFields(reader), - reader.readField(), - reader.readBoolean(), - ); - } - - [inspect.custom]() { - return `VMCircuitPublicInputs { - constants: ${inspect(this.constants)}, - callRequest: ${inspect(this.callRequest)} - previousValidationRequestArrayLengths: ${inspect(this.previousValidationRequestArrayLengths)}, - validationRequests: ${inspect(this.validationRequests)}, - previousAccumulatedDataArrayLengths: ${inspect(this.previousAccumulatedDataArrayLengths)}, - accumulatedData: ${inspect(this.accumulatedData)}, - startSideEffectCounter: ${this.startSideEffectCounter}, - endSideEffectCounter: ${this.endSideEffectCounter}, - startGasLeft: ${this.startGasLeft}, - transactionFee: ${this.transactionFee}, - reverted: ${this.reverted}, - }`; - } -} diff --git a/yarn-project/circuits.js/src/structs/non_existent_read_request_hints.ts b/yarn-project/circuits.js/src/structs/non_existent_read_request_hints.ts deleted file mode 100644 index 2c675326077b..000000000000 --- a/yarn-project/circuits.js/src/structs/non_existent_read_request_hints.ts +++ /dev/null @@ -1,161 +0,0 @@ -import { makeTuple } from '@aztec/foundation/array'; -import { BufferReader, type Tuple, serializeToBuffer } from '@aztec/foundation/serialize'; -import { type IndexedTreeLeafPreimage } from '@aztec/foundation/trees'; - -import { - MAX_NULLIFIERS_PER_TX, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - NULLIFIER_TREE_HEIGHT, -} from '../constants.gen.js'; -import { MembershipWitness } from './membership_witness.js'; -import { Nullifier } from './nullifier.js'; -import { NullifierLeafPreimage } from './trees/index.js'; - -interface PendingValue { - toBuffer(): Buffer; -} - -export class NonMembershipHint { - constructor(public membershipWitness: MembershipWitness, public leafPreimage: LEAF_PREIMAGE) {} - - static empty( - treeHeight: TREE_HEIGHT, - makeEmptyLeafPreimage: () => LEAF_PREIMAGE, - ) { - return new NonMembershipHint(MembershipWitness.empty(treeHeight), makeEmptyLeafPreimage()); - } - - static fromBuffer( - buffer: Buffer | BufferReader, - treeHeight: TREE_HEIGHT, - leafPreimageFromBuffer: { fromBuffer: (buffer: BufferReader) => LEAF_PREIMAGE }, - ): NonMembershipHint { - const reader = BufferReader.asReader(buffer); - return new NonMembershipHint( - MembershipWitness.fromBuffer(reader, treeHeight), - reader.readObject(leafPreimageFromBuffer), - ); - } - - toBuffer() { - return serializeToBuffer(this.membershipWitness, this.leafPreimage); - } -} - -export class NonExistentReadRequestHints< - READ_REQUEST_LEN extends number, - TREE_HEIGHT extends number, - LEAF_PREIMAGE extends IndexedTreeLeafPreimage, - PENDING_VALUE_LEN extends number, - PENDING_VALUE extends PendingValue, -> { - constructor( - /** - * The hints for the low leaves of the read requests. - */ - public nonMembershipHints: Tuple, READ_REQUEST_LEN>, - /** - * Indices of the smallest pending values greater than the read requests. - */ - public nextPendingValueIndices: Tuple, - public sortedPendingValues: Tuple, - public sortedPendingValueHints: Tuple, - ) {} - - static fromBuffer< - READ_REQUEST_LEN extends number, - TREE_HEIGHT extends number, - LEAF_PREIMAGE extends IndexedTreeLeafPreimage, - PENDING_VALUE_LEN extends number, - PENDING_VALUE extends PendingValue, - >( - buffer: Buffer | BufferReader, - readRequestLen: READ_REQUEST_LEN, - treeHeight: TREE_HEIGHT, - leafPreimageFromBuffer: { fromBuffer: (buffer: BufferReader) => LEAF_PREIMAGE }, - pendingValueLen: PENDING_VALUE_LEN, - orderedValueFromBuffer: { fromBuffer: (buffer: BufferReader) => PENDING_VALUE }, - ): NonExistentReadRequestHints { - const reader = BufferReader.asReader(buffer); - return new NonExistentReadRequestHints( - reader.readArray(readRequestLen, { - fromBuffer: buf => NonMembershipHint.fromBuffer(buf, treeHeight, leafPreimageFromBuffer), - }), - reader.readNumbers(readRequestLen), - reader.readArray(pendingValueLen, orderedValueFromBuffer), - reader.readNumbers(pendingValueLen), - ); - } - - toBuffer() { - return serializeToBuffer( - this.nonMembershipHints, - this.nextPendingValueIndices, - this.sortedPendingValues, - this.sortedPendingValueHints, - ); - } -} - -export type NullifierNonExistentReadRequestHints = NonExistentReadRequestHints< - typeof MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - typeof NULLIFIER_TREE_HEIGHT, - NullifierLeafPreimage, - typeof MAX_NULLIFIERS_PER_TX, - Nullifier ->; - -export function nullifierNonExistentReadRequestHintsFromBuffer( - buffer: Buffer | BufferReader, -): NullifierNonExistentReadRequestHints { - return NonExistentReadRequestHints.fromBuffer( - buffer, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - NULLIFIER_TREE_HEIGHT, - NullifierLeafPreimage, - MAX_NULLIFIERS_PER_TX, - Nullifier, - ); -} - -export class NullifierNonExistentReadRequestHintsBuilder { - private hints: NullifierNonExistentReadRequestHints; - private readRequestIndex = 0; - - constructor( - sortedPendingNullifiers: Tuple, - sortedPendingNullifierIndexHints: Tuple, - ) { - this.hints = new NonExistentReadRequestHints( - makeTuple(MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, () => - NonMembershipHint.empty(NULLIFIER_TREE_HEIGHT, NullifierLeafPreimage.empty), - ), - makeTuple(MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, () => 0), - sortedPendingNullifiers, - sortedPendingNullifierIndexHints, - ); - } - - static empty() { - const emptySortedPendingNullifiers = makeTuple(MAX_NULLIFIERS_PER_TX, Nullifier.empty); - const emptySortedPendingNullifierIndexHints = makeTuple(MAX_NULLIFIERS_PER_TX, () => 0); - return new NullifierNonExistentReadRequestHintsBuilder( - emptySortedPendingNullifiers, - emptySortedPendingNullifierIndexHints, - ).toHints(); - } - - addHint( - membershipWitness: MembershipWitness, - lowLeafPreimage: NullifierLeafPreimage, - nextPendingValueIndex: number, - ) { - this.hints.nonMembershipHints[this.readRequestIndex] = new NonMembershipHint(membershipWitness, lowLeafPreimage); - this.hints.nextPendingValueIndices[this.readRequestIndex] = nextPendingValueIndex; - this.readRequestIndex++; - } - - toHints() { - return this.hints; - } -} diff --git a/yarn-project/circuits.js/src/structs/public_call_stack_item_compressed.ts b/yarn-project/circuits.js/src/structs/public_call_stack_item_compressed.ts index 8df09f6bf4a8..64965ffd59e3 100644 --- a/yarn-project/circuits.js/src/structs/public_call_stack_item_compressed.ts +++ b/yarn-project/circuits.js/src/structs/public_call_stack_item_compressed.ts @@ -8,6 +8,7 @@ import { CallContext } from './call_context.js'; import { Gas } from './gas.js'; import { RevertCode } from './revert_code.js'; +// TO BE REMOVED /** * Compressed call stack item on a public call. */ diff --git a/yarn-project/circuits.js/src/structs/public_circuit_public_inputs.test.ts b/yarn-project/circuits.js/src/structs/public_circuit_public_inputs.test.ts deleted file mode 100644 index 7d4f900e4f22..000000000000 --- a/yarn-project/circuits.js/src/structs/public_circuit_public_inputs.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { randomInt } from '@aztec/foundation/crypto'; -import { setupCustomSnapshotSerializers } from '@aztec/foundation/testing'; - -import { PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH } from '../constants.gen.js'; -import { makePublicCircuitPublicInputs } from '../tests/factories.js'; -import { PublicCircuitPublicInputs } from './public_circuit_public_inputs.js'; - -describe('PublicCircuitPublicInputs', () => { - setupCustomSnapshotSerializers(expect); - it('serializes to field array and deserializes it back', () => { - const expected = makePublicCircuitPublicInputs(randomInt(1000), undefined); - - const fieldArray = expected.toFields(); - const res = PublicCircuitPublicInputs.fromFields(fieldArray); - expect(res).toEqual(expected); - }); - - it(`initializes an empty PrivateCircuitPublicInputs`, () => { - const target = PublicCircuitPublicInputs.empty(); - expect(target.isEmpty()).toBe(true); - }); - - it('number of fields matches constant', () => { - const target = makePublicCircuitPublicInputs(327); - const fields = target.toFields(); - expect(fields.length).toBe(PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH); - }); -}); diff --git a/yarn-project/circuits.js/src/structs/public_circuit_public_inputs.ts b/yarn-project/circuits.js/src/structs/public_circuit_public_inputs.ts index b307b33f2a9a..bb411de60c88 100644 --- a/yarn-project/circuits.js/src/structs/public_circuit_public_inputs.ts +++ b/yarn-project/circuits.js/src/structs/public_circuit_public_inputs.ts @@ -40,9 +40,8 @@ import { ReadRequest } from './read_request.js'; import { RevertCode } from './revert_code.js'; import { TreeLeafReadRequest } from './tree_leaf_read_request.js'; -/** - * Public inputs to a public circuit. - */ +// TO BE REMOVED +// This is currently the output of the AVM. It should be replaced by AvmCircuitPublicInputs eventually. export class PublicCircuitPublicInputs { constructor( /** diff --git a/yarn-project/circuits.js/src/structs/public_data_hint.ts b/yarn-project/circuits.js/src/structs/public_data_hint.ts index d1e4c70f381d..a3e6b766725c 100644 --- a/yarn-project/circuits.js/src/structs/public_data_hint.ts +++ b/yarn-project/circuits.js/src/structs/public_data_hint.ts @@ -9,7 +9,6 @@ export class PublicDataHint { constructor( public leafSlot: Fr, public value: Fr, - public overrideCounter: number, public membershipWitness: MembershipWitness, public leafPreimage: PublicDataTreeLeafPreimage, ) {} @@ -18,7 +17,6 @@ export class PublicDataHint { return new PublicDataHint( Fr.ZERO, Fr.ZERO, - 0, MembershipWitness.empty(PUBLIC_DATA_TREE_HEIGHT), PublicDataTreeLeafPreimage.empty(), ); @@ -29,19 +27,12 @@ export class PublicDataHint { return new PublicDataHint( reader.readObject(Fr), reader.readObject(Fr), - reader.readNumber(), MembershipWitness.fromBuffer(reader, PUBLIC_DATA_TREE_HEIGHT), reader.readObject(PublicDataTreeLeafPreimage), ); } toBuffer() { - return serializeToBuffer( - this.leafSlot, - this.value, - this.overrideCounter, - this.membershipWitness, - this.leafPreimage, - ); + return serializeToBuffer(this.leafSlot, this.value, this.membershipWitness, this.leafPreimage); } } diff --git a/yarn-project/circuits.js/src/structs/public_data_leaf_hint.ts b/yarn-project/circuits.js/src/structs/public_data_leaf_hint.ts deleted file mode 100644 index aba7c583e37d..000000000000 --- a/yarn-project/circuits.js/src/structs/public_data_leaf_hint.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { BufferReader, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { PUBLIC_DATA_TREE_HEIGHT } from '../constants.gen.js'; -import { MembershipWitness } from './membership_witness.js'; -import { PublicDataTreeLeafPreimage } from './trees/index.js'; - -export class PublicDataLeafHint { - constructor( - public preimage: PublicDataTreeLeafPreimage, - public membershipWitness: MembershipWitness, - ) {} - - static empty() { - return new PublicDataLeafHint(PublicDataTreeLeafPreimage.empty(), MembershipWitness.empty(PUBLIC_DATA_TREE_HEIGHT)); - } - - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new PublicDataLeafHint( - reader.readObject(PublicDataTreeLeafPreimage), - MembershipWitness.fromBuffer(reader, PUBLIC_DATA_TREE_HEIGHT), - ); - } - - toBuffer() { - return serializeToBuffer(this.preimage, this.membershipWitness); - } -} diff --git a/yarn-project/circuits.js/src/structs/public_data_update_request.ts b/yarn-project/circuits.js/src/structs/public_data_update_request.ts index d048a1100a45..35aa6a4a9a24 100644 --- a/yarn-project/circuits.js/src/structs/public_data_update_request.ts +++ b/yarn-project/circuits.js/src/structs/public_data_update_request.ts @@ -3,6 +3,7 @@ import { BufferReader, FieldReader, serializeToBuffer } from '@aztec/foundation/ import { inspect } from 'util'; +// TO BE REMOVED. /** * Write operations on the public data tree including the previous value. */ diff --git a/yarn-project/circuits.js/src/structs/public_inner_call_request.ts b/yarn-project/circuits.js/src/structs/public_inner_call_request.ts index 9dd2abd4de0d..984b3b47c446 100644 --- a/yarn-project/circuits.js/src/structs/public_inner_call_request.ts +++ b/yarn-project/circuits.js/src/structs/public_inner_call_request.ts @@ -6,6 +6,7 @@ import { inspect } from 'util'; import { PublicCallStackItemCompressed } from './public_call_stack_item_compressed.js'; +// TO BE REMOVED /** * Represents a request to call a public function. */ diff --git a/yarn-project/circuits.js/src/structs/public_validation_requests.ts b/yarn-project/circuits.js/src/structs/public_validation_requests.ts deleted file mode 100644 index 4d45328914c1..000000000000 --- a/yarn-project/circuits.js/src/structs/public_validation_requests.ts +++ /dev/null @@ -1,239 +0,0 @@ -import { makeTuple } from '@aztec/foundation/array'; -import { arraySerializedSizeOfNonEmpty } from '@aztec/foundation/collection'; -import { type Fr } from '@aztec/foundation/fields'; -import { BufferReader, FieldReader, type Tuple, serializeToBuffer } from '@aztec/foundation/serialize'; - -import { inspect } from 'util'; - -import { - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_READS_PER_TX, - NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS, -} from '../constants.gen.js'; -import { countAccumulatedItems } from '../utils/index.js'; -import { PublicDataRead } from './public_data_read.js'; -import { ScopedReadRequest } from './read_request.js'; -import { RollupValidationRequests } from './rollup_validation_requests.js'; -import { TreeLeafReadRequest } from './tree_leaf_read_request.js'; - -/** - * Validation requests accumulated during the execution of the transaction. - */ -export class PublicValidationRequests { - constructor( - /** - * Validation requests that cannot be fulfilled in the current context (private or public), and must be instead be - * forwarded to the rollup for it to take care of them. - */ - public forRollup: RollupValidationRequests, - public noteHashReadRequests: Tuple, - /** - * All the nullifier read requests made in this transaction. - */ - public nullifierReadRequests: Tuple, - /** - * The nullifier read requests made in this transaction. - */ - public nullifierNonExistentReadRequests: Tuple< - ScopedReadRequest, - typeof MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX - >, - public l1ToL2MsgReadRequests: Tuple, - /** - * All the public data reads made in this transaction. - */ - public publicDataReads: Tuple, - ) {} - - getSize() { - return ( - this.forRollup.getSize() + - arraySerializedSizeOfNonEmpty(this.noteHashReadRequests) + - arraySerializedSizeOfNonEmpty(this.nullifierReadRequests) + - arraySerializedSizeOfNonEmpty(this.nullifierNonExistentReadRequests) + - arraySerializedSizeOfNonEmpty(this.l1ToL2MsgReadRequests) + - arraySerializedSizeOfNonEmpty(this.publicDataReads) - ); - } - - toBuffer() { - return serializeToBuffer( - this.forRollup, - this.noteHashReadRequests, - this.nullifierReadRequests, - this.nullifierNonExistentReadRequests, - this.l1ToL2MsgReadRequests, - this.publicDataReads, - ); - } - - toString() { - return this.toBuffer().toString('hex'); - } - - static fromFields(fields: Fr[] | FieldReader) { - const reader = FieldReader.asReader(fields); - return new PublicValidationRequests( - reader.readObject(RollupValidationRequests), - reader.readArray(MAX_NOTE_HASH_READ_REQUESTS_PER_TX, TreeLeafReadRequest), - reader.readArray(MAX_NULLIFIER_READ_REQUESTS_PER_TX, ScopedReadRequest), - reader.readArray(MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, ScopedReadRequest), - reader.readArray(MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, TreeLeafReadRequest), - reader.readArray(MAX_PUBLIC_DATA_READS_PER_TX, PublicDataRead), - ); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or reader to read from. - * @returns Deserialized object. - */ - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new PublicValidationRequests( - reader.readObject(RollupValidationRequests), - reader.readArray(MAX_NOTE_HASH_READ_REQUESTS_PER_TX, TreeLeafReadRequest), - reader.readArray(MAX_NULLIFIER_READ_REQUESTS_PER_TX, ScopedReadRequest), - reader.readArray(MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, ScopedReadRequest), - reader.readArray(MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, TreeLeafReadRequest), - reader.readArray(MAX_PUBLIC_DATA_READS_PER_TX, PublicDataRead), - ); - } - - /** - * Deserializes from a string, corresponding to a write in cpp. - * @param str - String to read from. - * @returns Deserialized object. - */ - static fromString(str: string) { - return PublicValidationRequests.fromBuffer(Buffer.from(str, 'hex')); - } - - static empty() { - return new PublicValidationRequests( - RollupValidationRequests.empty(), - makeTuple(MAX_NOTE_HASH_READ_REQUESTS_PER_TX, TreeLeafReadRequest.empty), - makeTuple(MAX_NULLIFIER_READ_REQUESTS_PER_TX, ScopedReadRequest.empty), - makeTuple(MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, ScopedReadRequest.empty), - makeTuple(MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, TreeLeafReadRequest.empty), - makeTuple(MAX_PUBLIC_DATA_READS_PER_TX, PublicDataRead.empty), - ); - } - - [inspect.custom]() { - return `PublicValidationRequests { - forRollup: ${inspect(this.forRollup)}, - noteHashReadRequests: [${this.noteHashReadRequests - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - nullifierReadRequests: [${this.nullifierReadRequests - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - nullifierNonExistentReadRequests: [${this.nullifierNonExistentReadRequests - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - l1ToL2MsgReadRequests: [${this.l1ToL2MsgReadRequests - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}], - publicDataReads: [${this.publicDataReads - .filter(x => !x.isEmpty()) - .map(h => inspect(h)) - .join(', ')}] -}`; - } -} - -export class PublicValidationRequestArrayLengths { - constructor( - public noteHashReadRequests: number, - public nullifierReadRequests: number, - public nullifierNonExistentReadRequests: number, - public l1ToL2MsgReadRequests: number, - public publicDataReads: number, - ) {} - - static new(requests: PublicValidationRequests) { - return new PublicValidationRequestArrayLengths( - countAccumulatedItems(requests.noteHashReadRequests), - countAccumulatedItems(requests.nullifierReadRequests), - countAccumulatedItems(requests.nullifierNonExistentReadRequests), - countAccumulatedItems(requests.l1ToL2MsgReadRequests), - countAccumulatedItems(requests.publicDataReads), - ); - } - - getSize() { - return NUM_PUBLIC_VALIDATION_REQUEST_ARRAYS; - } - - toBuffer() { - return serializeToBuffer( - this.noteHashReadRequests, - this.nullifierReadRequests, - this.nullifierNonExistentReadRequests, - this.l1ToL2MsgReadRequests, - this.publicDataReads, - ); - } - - toString() { - return this.toBuffer().toString('hex'); - } - - static fromFields(fields: Fr[] | FieldReader) { - const reader = FieldReader.asReader(fields); - return new PublicValidationRequestArrayLengths( - reader.readU32(), - reader.readU32(), - reader.readU32(), - reader.readU32(), - reader.readU32(), - ); - } - - /** - * Deserializes from a buffer or reader, corresponding to a write in cpp. - * @param buffer - Buffer or reader to read from. - * @returns Deserialized object. - */ - static fromBuffer(buffer: Buffer | BufferReader) { - const reader = BufferReader.asReader(buffer); - return new PublicValidationRequestArrayLengths( - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - reader.readNumber(), - ); - } - - /** - * Deserializes from a string, corresponding to a write in cpp. - * @param str - String to read from. - * @returns Deserialized object. - */ - static fromString(str: string) { - return PublicValidationRequestArrayLengths.fromBuffer(Buffer.from(str, 'hex')); - } - - static empty() { - return new PublicValidationRequestArrayLengths(0, 0, 0, 0, 0); - } - - [inspect.custom]() { - return `PublicValidationRequestArrayLengths { - noteHashReadRequests: ${this.noteHashReadRequests}, - nullifierReadRequests: ${this.nullifierReadRequests}, - nullifierNonExistentReadRequests: ${this.nullifierNonExistentReadRequests}, - l1ToL2MsgReadRequests: ${this.l1ToL2MsgReadRequests}, - publicDataReads: ${this.publicDataReads} -}`; - } -} diff --git a/yarn-project/circuits.js/src/structs/tree_leaf_read_request_hint.ts b/yarn-project/circuits.js/src/structs/tree_leaf_read_request_hint.ts deleted file mode 100644 index e6b64deb6cb3..000000000000 --- a/yarn-project/circuits.js/src/structs/tree_leaf_read_request_hint.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { assertMemberLength } from '@aztec/foundation/array'; -import { Fr } from '@aztec/foundation/fields'; -import { BufferReader, type Tuple, serializeToBuffer } from '@aztec/foundation/serialize'; - -/** - * Contains information which can be used to prove that a leaf is a member of a Merkle tree. - */ -export class TreeLeafReadRequestHint { - constructor( - /** - * Size of the sibling path (number of fields it contains). - */ - pathSize: N, - /** - * Sibling path of the leaf in the Merkle tree. - */ - public siblingPath: Tuple, - ) { - assertMemberLength(this, 'siblingPath', pathSize); - } - - toBuffer() { - return serializeToBuffer(this.siblingPath); - } - - public static empty(pathSize: N): TreeLeafReadRequestHint { - const arr = Array(pathSize) - .fill(0) - .map(() => Fr.ZERO) as Tuple; - return new TreeLeafReadRequestHint(pathSize, arr); - } - - static fromBuffer(buffer: Buffer | BufferReader, size: N): TreeLeafReadRequestHint { - const reader = BufferReader.asReader(buffer); - const siblingPath = reader.readArray(size, Fr); - return new TreeLeafReadRequestHint(size, siblingPath); - } -} diff --git a/yarn-project/circuits.js/src/tests/factories.ts b/yarn-project/circuits.js/src/tests/factories.ts index 9c448588c3ba..a21dd5f1e497 100644 --- a/yarn-project/circuits.js/src/tests/factories.ts +++ b/yarn-project/circuits.js/src/tests/factories.ts @@ -43,7 +43,6 @@ import { KeyValidationRequest, KeyValidationRequestAndGenerator, L1_TO_L2_MSG_SUBTREE_SIBLING_PATH_LENGTH, - L1_TO_L2_MSG_TREE_HEIGHT, L2ToL1Message, LogHash, MAX_CONTRACT_CLASS_LOGS_PER_TX, @@ -52,8 +51,6 @@ import { MAX_ENQUEUED_CALLS_PER_CALL, MAX_ENQUEUED_CALLS_PER_TX, MAX_KEY_VALIDATION_REQUESTS_PER_CALL, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_CALL, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_L2_TO_L1_MSGS_PER_CALL, MAX_L2_TO_L1_MSGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_CALL, @@ -61,28 +58,18 @@ import { MAX_NOTE_HASHES_PER_CALL, MAX_NOTE_HASHES_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_CALL, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_CALL, MAX_NULLIFIERS_PER_TX, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_CALL, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_CALL, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, - MAX_PUBLIC_DATA_HINTS, - MAX_PUBLIC_DATA_READS_PER_CALL, - MAX_PUBLIC_DATA_READS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_CALL, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_TOTAL_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - MAX_UNENCRYPTED_LOGS_PER_CALL, MAX_UNENCRYPTED_LOGS_PER_TX, MaxBlockNumber, MembershipWitness, MergeRollupInputs, NESTED_RECURSIVE_PROOF_LENGTH, NOTE_HASH_SUBTREE_SIBLING_PATH_LENGTH, - NOTE_HASH_TREE_HEIGHT, NULLIFIER_SUBTREE_SIBLING_PATH_LENGTH, NULLIFIER_TREE_HEIGHT, NUMBER_OF_L1_L2_MESSAGES_PER_ROLLUP, @@ -92,8 +79,7 @@ import { NoteLogHash, Nullifier, NullifierLeafPreimage, - NullifierNonExistentReadRequestHintsBuilder, - NullifierReadRequestHintsBuilder, + PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH, PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, PUBLIC_DATA_TREE_HEIGHT, ParityPublicInputs, @@ -106,18 +92,12 @@ import { PrivateCircuitPublicInputs, PrivateKernelTailCircuitPublicInputs, Proof, - PublicAccumulatedData, PublicCallRequest, - PublicCallStackItemCompressed, PublicCircuitPublicInputs, PublicDataHint, PublicDataRead, PublicDataTreeLeaf, PublicDataTreeLeafPreimage, - PublicDataUpdateRequest, - PublicKernelCircuitPublicInputs, - PublicKernelData, - PublicKernelTailCircuitPrivateInputs, PublicKeys, RECURSIVE_PROOF_LENGTH, ReadRequest, @@ -128,7 +108,6 @@ import { RootRollupInputs, RootRollupPublicInputs, ScopedLogHash, - ScopedReadRequest, StateDiffHints, StateReference, TUBE_PROOF_LENGTH, @@ -163,29 +142,18 @@ import { AvmPublicDataWriteTreeHint, BaseRollupHints, CountedPublicCallRequest, - EnqueuedCallData, PrivateBaseRollupInputs, PrivateToAvmAccumulatedData, PrivateToAvmAccumulatedDataArrayLengths, PrivateToPublicAccumulatedData, PrivateToPublicKernelCircuitPublicInputs, PrivateTubeData, - PublicAccumulatedDataArrayLengths, PublicBaseRollupInputs, - PublicDataLeafHint, PublicDataWrite, - PublicInnerCallRequest, - PublicKernelCircuitPrivateInputs, PublicTubeData, - PublicValidationRequestArrayLengths, - PublicValidationRequests, ScopedL2ToL1Message, - ScopedNoteHash, - TreeLeafReadRequest, - TreeLeafReadRequestHint, TreeSnapshots, TxConstantData, - VMCircuitPublicInputs, VkWitnessData, } from '../structs/index.js'; import { KernelCircuitPublicInputs } from '../structs/kernel/kernel_circuit_public_inputs.js'; @@ -224,10 +192,6 @@ function makeNoteHash(seed: number) { return new NoteHash(fr(seed), seed + 1); } -function makeScopedNoteHash(seed: number) { - return new NoteHash(fr(seed), seed + 1).scope(makeAztecAddress(seed + 3)); -} - function makeNullifier(seed: number) { return new Nullifier(fr(seed), seed + 1, fr(seed + 2)); } @@ -262,18 +226,6 @@ function makeReadRequest(n: number): ReadRequest { return new ReadRequest(new Fr(BigInt(n)), n + 1); } -function makeScopedReadRequest(n: number): ScopedReadRequest { - return new ScopedReadRequest(makeReadRequest(n), AztecAddress.fromBigInt(BigInt(n + 2))); -} - -function makeTreeLeafReadRequest(seed: number) { - return new TreeLeafReadRequest(new Fr(seed), new Fr(seed + 1)); -} - -function makeTreeLeafReadRequestHint(seed: number, size: N) { - return new TreeLeafReadRequestHint(size, makeSiblingPath(seed, size)); -} - /** * Creates arbitrary KeyValidationRequest from the given seed. * @param seed - The seed to use for generating the KeyValidationRequest. @@ -292,23 +244,6 @@ function makeKeyValidationRequestAndGenerators(seed: number): KeyValidationReque return new KeyValidationRequestAndGenerator(makeKeyValidationRequests(seed), fr(seed + 4)); } -/** - * Creates arbitrary public data update request. - * @param seed - The seed to use for generating the public data update request. - * @returns A public data update request. - */ -export function makePublicDataUpdateRequest(seed = 1): PublicDataUpdateRequest { - return new PublicDataUpdateRequest(fr(seed), fr(seed + 1), seed + 2); -} - -/** - * Creates empty public data update request. - * @returns An empty public data update request. - */ -export function makeEmptyPublicDataUpdateRequest(): PublicDataUpdateRequest { - return new PublicDataUpdateRequest(fr(0), fr(0), 0); -} - function makePublicDataWrite(seed = 1) { return new PublicDataWrite(fr(seed), fr(seed + 1)); } @@ -348,21 +283,6 @@ export function makeContractStorageRead(seed = 1): ContractStorageRead { return new ContractStorageRead(fr(seed), fr(seed + 1), seed + 2); } -function makePublicValidationRequests(seed = 1) { - return new PublicValidationRequests( - makeRollupValidationRequests(seed), - makeTuple(MAX_NOTE_HASH_READ_REQUESTS_PER_TX, makeTreeLeafReadRequest, seed + 0x10), - makeTuple(MAX_NULLIFIER_READ_REQUESTS_PER_TX, makeScopedReadRequest, seed + 0x80), - makeTuple(MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, makeScopedReadRequest, seed + 0x95), - makeTuple(MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, makeTreeLeafReadRequest, seed + 0x100), - makeTuple(MAX_PUBLIC_DATA_READS_PER_TX, makePublicDataRead, seed + 0xe00), - ); -} - -function makePublicValidationRequestArrayLengths(seed = 1) { - return new PublicValidationRequestArrayLengths(seed, seed + 1, seed + 2, seed + 3, seed + 4); -} - export function makeRollupValidationRequests(seed = 1) { return new RollupValidationRequests(new MaxBlockNumber(true, new Fr(seed + 0x31415))); } @@ -443,45 +363,6 @@ export function makeGas(seed = 1) { return new Gas(seed, seed + 1); } -/** - * Creates arbitrary accumulated data. - * @param seed - The seed to use for generating the accumulated data. - * @returns An accumulated data. - */ -function makePublicAccumulatedData(seed = 1, full = false): PublicAccumulatedData { - const tupleGenerator = full ? makeTuple : makeHalfFullTuple; - - return new PublicAccumulatedData( - tupleGenerator(MAX_NOTE_HASHES_PER_TX, makeScopedNoteHash, seed + 0x120, ScopedNoteHash.empty), - tupleGenerator(MAX_NULLIFIERS_PER_TX, makeNullifier, seed + 0x200, Nullifier.empty), - tupleGenerator(MAX_L2_TO_L1_MSGS_PER_TX, makeScopedL2ToL1Message, seed + 0x600, ScopedL2ToL1Message.empty), - tupleGenerator(MAX_NOTE_ENCRYPTED_LOGS_PER_TX, makeLogHash, seed + 0x700, LogHash.empty), // note encrypted logs hashes - tupleGenerator(MAX_ENCRYPTED_LOGS_PER_TX, makeScopedLogHash, seed + 0x800, ScopedLogHash.empty), // encrypted logs hashes - tupleGenerator(MAX_UNENCRYPTED_LOGS_PER_TX, makeScopedLogHash, seed + 0x900, ScopedLogHash.empty), // unencrypted logs hashes - tupleGenerator( - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - makePublicDataUpdateRequest, - seed + 0xd00, - PublicDataUpdateRequest.empty, - ), - tupleGenerator(MAX_ENQUEUED_CALLS_PER_TX, makePublicCallRequest, seed + 0x500, PublicCallRequest.empty), - makeGas(seed + 0x600), - ); -} - -function makePublicAccumulatedDataArrayLengths(seed = 1) { - return new PublicAccumulatedDataArrayLengths( - seed, - seed + 1, - seed + 2, - seed + 3, - seed + 4, - seed + 5, - seed + 6, - seed + 7, - ); -} - /** * Creates arbitrary call context. * @param seed - The seed to use for generating the call context. @@ -497,82 +378,6 @@ export function makeCallContext(seed = 0, overrides: Partial(NESTED_RECURSIVE_PROOF_LENGTH, seed + 0x80), - VerificationKeyData.makeFakeHonk(), - 0x42, - makeTuple(VK_TREE_HEIGHT, fr, 0x1000), - ); -} - /** * Makes arbitrary proof. * @param seed - The seed to use for generating/mocking the proof. @@ -746,19 +518,6 @@ function makePrivateCallRequest(seed = 1): PrivateCallRequest { return new PrivateCallRequest(makeCallContext(seed + 0x1), fr(seed + 0x3), fr(seed + 0x4), seed + 0x10, seed + 0x11); } -function makePublicCallStackItemCompressed(seed = 1): PublicCallStackItemCompressed { - const callContext = makeCallContext(seed); - return new PublicCallStackItemCompressed( - callContext.contractAddress, - callContext, - fr(seed + 0x20), - fr(seed + 0x30), - RevertCode.OK, - makeGas(seed + 0x40), - makeGas(seed + 0x50), - ); -} - export function makePublicCallRequest(seed = 1) { return new PublicCallRequest( makeAztecAddress(seed), @@ -773,48 +532,6 @@ function makeCountedPublicCallRequest(seed = 1) { return new CountedPublicCallRequest(makePublicCallRequest(seed), seed + 0x100); } -function makePublicInnerCallRequest(seed = 1): PublicInnerCallRequest { - return new PublicInnerCallRequest(makePublicCallStackItemCompressed(seed), seed + 0x60); -} - -function makeEnqueuedCallData(seed = 1) { - return new EnqueuedCallData(makeVMCircuitPublicInputs(seed), makeProof()); -} - -/** - * Makes arbitrary public kernel inputs. - * @param seed - The seed to use for generating the public kernel inputs. - * @returns Public kernel inputs. - */ -export function makePublicKernelCircuitPrivateInputs(seed = 1): PublicKernelCircuitPrivateInputs { - return new PublicKernelCircuitPrivateInputs(makePublicKernelData(seed), makeEnqueuedCallData(seed + 0x1000)); -} - -/** - * Makes arbitrary public kernel tail inputs. - * @param seed - The seed to use for generating the public kernel inputs. - * @returns Public kernel inputs. - */ -export function makePublicKernelTailCircuitPrivateInputs(seed = 1): PublicKernelTailCircuitPrivateInputs { - return new PublicKernelTailCircuitPrivateInputs( - makePublicKernelData(seed), - makeTuple( - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - s => makeTreeLeafReadRequestHint(s, NOTE_HASH_TREE_HEIGHT), - seed + 0x20, - ), - NullifierReadRequestHintsBuilder.empty(MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX), - NullifierNonExistentReadRequestHintsBuilder.empty(), - makeTuple( - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - s => makeTreeLeafReadRequestHint(s, L1_TO_L2_MSG_TREE_HEIGHT), - seed + 0x80, - ), - makeTuple(MAX_PUBLIC_DATA_HINTS, PublicDataLeafHint.empty), - makePartialStateReference(seed + 0x200), - ); -} - /** * Makes arbitrary tx request. * @param seed - The seed to use for generating the tx request. @@ -1645,10 +1362,12 @@ export function makeAvmExecutionHints( * @returns the execution hints. */ export function makeAvmCircuitInputs(seed = 0, overrides: Partial> = {}): AvmCircuitInputs { + const values = Array(PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH).map((_, i) => seed + 0x2000 + i); + const publicInputs = PublicCircuitPublicInputs.fromBuffer(Buffer.from(values)); return AvmCircuitInputs.from({ functionName: `function${seed}`, calldata: makeArray((seed % 100) + 10, i => new Fr(i), seed + 0x1000), - publicInputs: makePublicCircuitPublicInputs(seed + 0x2000), + publicInputs, avmHints: makeAvmExecutionHints(seed + 0x3000), output: makeAvmCircuitPublicInputs(seed + 0x4000), ...overrides, diff --git a/yarn-project/ivc-integration/src/avm_integration.test.ts b/yarn-project/ivc-integration/src/avm_integration.test.ts index 967fd92bc1cf..909d4c778187 100644 --- a/yarn-project/ivc-integration/src/avm_integration.test.ts +++ b/yarn-project/ivc-integration/src/avm_integration.test.ts @@ -49,7 +49,7 @@ import os from 'os'; import path from 'path'; import { fileURLToPath } from 'url'; -import { MockPublicKernelCircuit, witnessGenMockPublicKernelCircuit } from './index.js'; +import { MockPublicBaseCircuit, witnessGenMockPublicBaseCircuit } from './index.js'; // Auto-generated types from noir are not in camel case. /* eslint-disable camelcase */ @@ -75,7 +75,7 @@ describe('AVM Integration', () => { const provingResult = await generateProof( bbBinaryPath, bbWorkingDirectory, - 'mock-public-kernel', + 'mock-public-base', Buffer.from(bytecode, 'base64'), recursive, witnessFileName, @@ -127,7 +127,7 @@ describe('AVM Integration', () => { const vk = vkReader.readArray(AVM_VERIFICATION_KEY_LENGTH_IN_FIELDS, Fr); expect(vk.length).toBe(AVM_VERIFICATION_KEY_LENGTH_IN_FIELDS); - const witGenResult = await witnessGenMockPublicKernelCircuit({ + const witGenResult = await witnessGenMockPublicBaseCircuit({ verification_key: vk.map(x => x.toString()) as FixedLengthArray< string, typeof AVM_VERIFICATION_KEY_LENGTH_IN_FIELDS @@ -139,7 +139,7 @@ describe('AVM Integration', () => { >, }); - await createHonkProof(witGenResult.witness, MockPublicKernelCircuit.bytecode); + await createHonkProof(witGenResult.witness, MockPublicBaseCircuit.bytecode); const verifyResult = await verifyProof( bbBinaryPath, diff --git a/yarn-project/ivc-integration/src/index.ts b/yarn-project/ivc-integration/src/index.ts index 17b6a95888f3..932345648646 100644 --- a/yarn-project/ivc-integration/src/index.ts +++ b/yarn-project/ivc-integration/src/index.ts @@ -9,7 +9,7 @@ import MockPrivateKernelInitCircuit from '../artifacts/mock_private_kernel_init. import MockPrivateKernelInnerCircuit from '../artifacts/mock_private_kernel_inner.json' assert { type: 'json' }; import MockPrivateKernelResetCircuit from '../artifacts/mock_private_kernel_reset.json' assert { type: 'json' }; import MockPrivateKernelTailCircuit from '../artifacts/mock_private_kernel_tail.json' assert { type: 'json' }; -import MockPublicKernelCircuit from '../artifacts/mock_public_kernel.json' assert { type: 'json' }; +import MockPublicBaseCircuit from '../artifacts/mock_public_base.json' assert { type: 'json' }; import type { AppCreatorInputType, AppPublicInputs, @@ -19,7 +19,7 @@ import type { MockPrivateKernelInnerInputType, MockPrivateKernelResetInputType, MockPrivateKernelTailInputType, - MockPublicKernelInputType, + MockPublicBaseInputType, PrivateKernelPublicInputs, u8, } from './types/index.js'; @@ -32,7 +32,7 @@ export { MockPrivateKernelInnerCircuit, MockPrivateKernelResetCircuit, MockPrivateKernelTailCircuit, - MockPublicKernelCircuit, + MockPublicBaseCircuit, }; createDebug.enable('*'); @@ -117,10 +117,8 @@ export async function witnessGenMockPrivateKernelTailCircuit( }; } -export async function witnessGenMockPublicKernelCircuit( - args: MockPublicKernelInputType, -): Promise> { - const program = new Noir(MockPublicKernelCircuit); +export async function witnessGenMockPublicBaseCircuit(args: MockPublicBaseInputType): Promise> { + const program = new Noir(MockPublicBaseCircuit); const { witness, returnValue } = await program.execute(args, foreignCallHandler); return { witness, diff --git a/yarn-project/ivc-integration/src/scripts/generate_ts_from_abi.ts b/yarn-project/ivc-integration/src/scripts/generate_ts_from_abi.ts index d020c891fa53..80545c2587ac 100644 --- a/yarn-project/ivc-integration/src/scripts/generate_ts_from_abi.ts +++ b/yarn-project/ivc-integration/src/scripts/generate_ts_from_abi.ts @@ -14,7 +14,7 @@ const circuits = [ 'mock_private_kernel_inner', 'mock_private_kernel_reset', 'mock_private_kernel_tail', - 'mock_public_kernel', + 'mock_public_base', ]; const main = async () => { diff --git a/yarn-project/noir-protocol-circuits-types/src/artifacts.ts b/yarn-project/noir-protocol-circuits-types/src/artifacts.ts index 2befc9ad5fe3..d0339d17050b 100644 --- a/yarn-project/noir-protocol-circuits-types/src/artifacts.ts +++ b/yarn-project/noir-protocol-circuits-types/src/artifacts.ts @@ -14,8 +14,6 @@ import PrivateKernelTailJson from '../artifacts/private_kernel_tail.json' assert import PrivateKernelTailSimulatedJson from '../artifacts/private_kernel_tail_simulated.json' assert { type: 'json' }; import PrivateKernelTailToPublicJson from '../artifacts/private_kernel_tail_to_public.json' assert { type: 'json' }; import PrivateKernelTailToPublicSimulatedJson from '../artifacts/private_kernel_tail_to_public_simulated.json' assert { type: 'json' }; -import PublicKernelMergeSimulatedJson from '../artifacts/public_kernel_merge_simulated.json' assert { type: 'json' }; -import PublicKernelTailSimulatedJson from '../artifacts/public_kernel_tail_simulated.json' assert { type: 'json' }; import PrivateBaseRollupJson from '../artifacts/rollup_base_private.json' assert { type: 'json' }; import PrivateBaseRollupSimulatedJson from '../artifacts/rollup_base_private_simulated.json' assert { type: 'json' }; import PublicBaseRollupJson from '../artifacts/rollup_base_public.json' assert { type: 'json' }; @@ -31,10 +29,6 @@ import { type PrivateResetArtifact, } from './private_kernel_reset_data.js'; -// To be deprecated. -export const SimulatedPublicKernelMergeArtifact = PublicKernelMergeSimulatedJson as NoirCompiledCircuit; -export const SimulatedPublicKernelTailArtifact = PublicKernelTailSimulatedJson as NoirCompiledCircuit; - // These are all circuits that should generate proofs with the `recursive` flag. export type ServerProtocolArtifact = | 'EmptyNestedArtifact' diff --git a/yarn-project/noir-protocol-circuits-types/src/index.ts b/yarn-project/noir-protocol-circuits-types/src/index.ts index c7744134bfdd..82b3e206384b 100644 --- a/yarn-project/noir-protocol-circuits-types/src/index.ts +++ b/yarn-project/noir-protocol-circuits-types/src/index.ts @@ -19,9 +19,6 @@ import { type PrivateKernelTailCircuitPrivateInputs, type PrivateKernelTailCircuitPublicInputs, type PublicBaseRollupInputs, - type PublicKernelCircuitPrivateInputs, - type PublicKernelCircuitPublicInputs, - type PublicKernelTailCircuitPrivateInputs, type RootParityInputs, type RootRollupInputs, type RootRollupPublicInputs, @@ -38,8 +35,6 @@ import { ClientCircuitArtifacts, ServerCircuitArtifacts, SimulatedClientCircuitArtifacts, - SimulatedPublicKernelMergeArtifact, - SimulatedPublicKernelTailArtifact, SimulatedServerCircuitArtifacts, } from './artifacts.js'; import { type PrivateResetArtifact } from './private_kernel_reset_data.js'; @@ -65,9 +60,6 @@ import { mapPrivateKernelTailCircuitPublicInputsForPublicFromNoir, mapPrivateKernelTailCircuitPublicInputsForRollupFromNoir, mapPublicBaseRollupInputsToNoir, - mapPublicKernelCircuitPrivateInputsToNoir, - mapPublicKernelCircuitPublicInputsFromNoir, - mapPublicKernelTailCircuitPrivateInputsToNoir, mapRootParityInputsToNoir, mapRootRollupInputsToNoir, mapRootRollupPublicInputsFromNoir, @@ -82,8 +74,6 @@ import { type PrivateKernelResetReturnType, type PrivateKernelTailReturnType, type PrivateKernelTailToPublicReturnType, - type PublicKernelMergeSimulatedReturnType, - type PublicKernelTailSimulatedReturnType, type RollupBasePrivateReturnType, type RollupBasePublicReturnType, type RollupBlockMergeReturnType, @@ -541,32 +531,6 @@ export function convertRootRollupInputsToWitnessMap(inputs: RootRollupInputs): W return initialWitnessMap; } -/** - * Converts the inputs of the public merge circuit into a witness map - * @param inputs - The public kernel inputs. - * @returns The witness map - */ -export function convertSimulatedPublicMergeInputsToWitnessMap(inputs: PublicKernelCircuitPrivateInputs): WitnessMap { - const mapped = mapPublicKernelCircuitPrivateInputsToNoir(inputs); - const initialWitnessMap = abiEncode(SimulatedPublicKernelMergeArtifact.abi, { - input: mapped as any, - }); - return initialWitnessMap; -} - -/** - * Converts the inputs of the public tail circuit into a witness map - * @param inputs - The public kernel inputs. - * @returns The witness map - */ -export function convertSimulatedPublicTailInputsToWitnessMap(inputs: PublicKernelTailCircuitPrivateInputs): WitnessMap { - const mapped = mapPublicKernelTailCircuitPrivateInputsToNoir(inputs); - const initialWitnessMap = abiEncode(SimulatedPublicKernelTailArtifact.abi, { - input: mapped as any, - }); - return initialWitnessMap; -} - export function convertPrivateKernelEmptyOutputsFromWitnessMap(outputs: WitnessMap): KernelCircuitPublicInputs { const decodedInputs: DecodedInputs = abiDecode(ServerCircuitArtifacts.PrivateKernelEmptyArtifact.abi, outputs); const returnType = decodedInputs.return_value as PrivateKernelEmptyReturnType; @@ -760,36 +724,6 @@ export function convertRootParityOutputsFromWitnessMap(outputs: WitnessMap): Par return mapParityPublicInputsFromNoir(returnType); } -/** - * Converts the outputs of the public merge circuit from a witness map. - * @param outputs - The public kernel outputs as a witness map. - * @returns The public inputs. - */ -export function convertSimulatedPublicMergeOutputFromWitnessMap(outputs: WitnessMap): PublicKernelCircuitPublicInputs { - // Decode the witness map into two fields, the return values and the inputs - const decodedInputs: DecodedInputs = abiDecode(SimulatedPublicKernelMergeArtifact.abi, outputs); - - // Cast the inputs as the return type - const returnType = decodedInputs.return_value as PublicKernelMergeSimulatedReturnType; - - return mapPublicKernelCircuitPublicInputsFromNoir(returnType); -} - -/** - * Converts the outputs of the public tail circuit from a witness map. - * @param outputs - The public kernel outputs as a witness map. - * @returns The public inputs. - */ -export function convertSimulatedPublicTailOutputFromWitnessMap(outputs: WitnessMap): KernelCircuitPublicInputs { - // Decode the witness map into two fields, the return values and the inputs - const decodedInputs: DecodedInputs = abiDecode(SimulatedPublicKernelTailArtifact.abi, outputs); - - // Cast the inputs as the return type - const returnType = decodedInputs.return_value as PublicKernelTailSimulatedReturnType; - - return mapKernelCircuitPublicInputsFromNoir(returnType); -} - function fromACVMField(field: string): Fr { return Fr.fromBuffer(Buffer.from(field.slice(2), 'hex')); } diff --git a/yarn-project/noir-protocol-circuits-types/src/scripts/generate_ts_from_abi.ts b/yarn-project/noir-protocol-circuits-types/src/scripts/generate_ts_from_abi.ts index ea26faf21022..a6b6ceae2ea0 100644 --- a/yarn-project/noir-protocol-circuits-types/src/scripts/generate_ts_from_abi.ts +++ b/yarn-project/noir-protocol-circuits-types/src/scripts/generate_ts_from_abi.ts @@ -15,8 +15,6 @@ const circuits = [ 'private_kernel_reset', 'private_kernel_tail', 'private_kernel_tail_to_public', - 'public_kernel_merge_simulated', - 'public_kernel_tail_simulated', 'rollup_base_private', 'rollup_base_public', 'rollup_merge', diff --git a/yarn-project/noir-protocol-circuits-types/src/type_conversion.ts b/yarn-project/noir-protocol-circuits-types/src/type_conversion.ts index 0bfc86ba3358..68bf1e98cc05 100644 --- a/yarn-project/noir-protocol-circuits-types/src/type_conversion.ts +++ b/yarn-project/noir-protocol-circuits-types/src/type_conversion.ts @@ -22,7 +22,6 @@ import { type EmptyBlockRootRollupInputs, type EmptyNestedData, EncryptedLogHash, - type EnqueuedCallData, EthAddress, FeeRecipient, Fr, @@ -39,23 +38,19 @@ import { type KeyValidationHint, KeyValidationRequest, KeyValidationRequestAndGenerator, - type L1_TO_L2_MSG_TREE_HEIGHT, L2ToL1Message, LogHash, MAX_CONTRACT_CLASS_LOGS_PER_TX, MAX_ENCRYPTED_LOGS_PER_TX, MAX_ENQUEUED_CALLS_PER_TX, MAX_KEY_VALIDATION_REQUESTS_PER_TX, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_PRIVATE_CALL_STACK_LENGTH_PER_TX, - MAX_PUBLIC_DATA_READS_PER_TX, MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_UNENCRYPTED_LOGS_PER_TX, MaxBlockNumber, @@ -65,13 +60,11 @@ import { type NOTE_HASH_TREE_HEIGHT, type NULLIFIER_TREE_HEIGHT, NUM_BYTES_PER_SHA256, - type NonMembershipHint, NoteHash, type NoteHashReadRequestHints, NoteLogHash, Nullifier, type NullifierLeafPreimage, - type NullifierNonExistentReadRequestHints, type NullifierReadRequestHints, OptionalNumber, type PUBLIC_DATA_TREE_HEIGHT, @@ -99,27 +92,14 @@ import { type PrivateToPublicKernelCircuitPublicInputs, type PrivateTubeData, PrivateValidationRequests, - PublicAccumulatedData, - PublicAccumulatedDataArrayLengths, type PublicBaseRollupInputs, PublicCallRequest, - PublicCallStackItemCompressed, type PublicDataHint, - type PublicDataLeafHint, - PublicDataRead, type PublicDataTreeLeaf, type PublicDataTreeLeafPreimage, - PublicDataUpdateRequest, PublicDataWrite, - PublicInnerCallRequest, - type PublicKernelCircuitPrivateInputs, - PublicKernelCircuitPublicInputs, - type PublicKernelData, - type PublicKernelTailCircuitPrivateInputs, type PublicKeys, type PublicTubeData, - PublicValidationRequestArrayLengths, - PublicValidationRequests, type RECURSIVE_PROOF_LENGTH, ReadRequest, type ReadRequestStatus, @@ -142,13 +122,10 @@ import { StateReference, type TUBE_PROOF_LENGTH, type TransientDataIndexHint, - TreeLeafReadRequest, - type TreeLeafReadRequestHint, type TreeSnapshots, TxConstantData, TxContext, type TxRequest, - VMCircuitPublicInputs, type VerificationKeyAsFields, type VkWitnessData, } from '@aztec/circuits.js'; @@ -174,7 +151,6 @@ import type { EmptyBlockRootRollupInputs as EmptyBlockRootRollupInputsNoir, EmptyNestedCircuitPublicInputs as EmptyNestedDataNoir, EncryptedLogHash as EncryptedLogHashNoir, - EnqueuedCallData as EnqueuedCallDataNoir, FeeRecipient as FeeRecipientNoir, Field, FixedLengthArray, @@ -206,8 +182,6 @@ import type { NoteLogHash as NoteLogHashNoir, NullifierLeafPreimage as NullifierLeafPreimageNoir, Nullifier as NullifierNoir, - NullifierNonExistentReadRequestHints as NullifierNonExistentReadRequestHintsNoir, - NullifierNonMembershipHint as NullifierNonMembershipHintNoir, NullifierReadRequestHints as NullifierReadRequestHintsNoir, NullifierSettledReadHint as NullifierSettledReadHintNoir, Option as OptionalNumberNoir, @@ -232,27 +206,14 @@ import type { PrivateToPublicKernelCircuitPublicInputs as PrivateToPublicKernelCircuitPublicInputsNoir, PrivateTubeData as PrivateTubeDataNoir, PrivateValidationRequests as PrivateValidationRequestsNoir, - PublicAccumulatedDataArrayLengths as PublicAccumulatedDataArrayLengthsNoir, - PublicAccumulatedData as PublicAccumulatedDataNoir, PublicBaseRollupInputs as PublicBaseRollupInputsNoir, PublicCallRequest as PublicCallRequestNoir, - PublicCallStackItemCompressed as PublicCallStackItemCompressedNoir, PublicDataHint as PublicDataHintNoir, - PublicDataLeafHint as PublicDataLeafHintNoir, - PublicDataRead as PublicDataReadNoir, PublicDataTreeLeaf as PublicDataTreeLeafNoir, PublicDataTreeLeafPreimage as PublicDataTreeLeafPreimageNoir, - PublicDataUpdateRequest as PublicDataUpdateRequestNoir, PublicDataWrite as PublicDataWriteNoir, - PublicInnerCallRequest as PublicInnerCallRequestNoir, - PublicKernelCircuitPublicInputs as PublicKernelCircuitPublicInputsNoir, - PublicKernelData as PublicKernelDataNoir, - PublicKernelMergeCircuitPrivateInputs as PublicKernelMergeCircuitPrivateInputsNoir, - PublicKernelTailCircuitPrivateInputs as PublicKernelTailCircuitPrivateInputsNoir, PublicKeys as PublicKeysNoir, PublicTubeData as PublicTubeDataNoir, - PublicValidationRequestArrayLengths as PublicValidationRequestArrayLengthsNoir, - PublicValidationRequests as PublicValidationRequestsNoir, ReadRequest as ReadRequestNoir, ReadRequestStatus as ReadRequestStatusNoir, RollupValidationRequests as RollupValidationRequestsNoir, @@ -270,13 +231,10 @@ import type { StateDiffHints as StateDiffHintsNoir, StateReference as StateReferenceNoir, TransientDataIndexHint as TransientDataIndexHintNoir, - TreeLeafReadRequestHint as TreeLeafReadRequestHintNoir, - TreeLeafReadRequest as TreeLeafReadRequestNoir, TreeSnapshots as TreeSnapshotsNoir, TxConstantData as TxConstantDataNoir, TxContext as TxContextNoir, TxRequest as TxRequestNoir, - VMCircuitPublicInputs as VMCircuitPublicInputsNoir, VerificationKey as VerificationKeyNoir, VkData as VkDataNoir, } from './types/index.js'; @@ -564,32 +522,6 @@ function mapPrivateCallRequestToNoir(callRequest: PrivateCallRequest): PrivateCa }; } -function mapPublicCallStackItemCompressedFromNoir(data: PublicCallStackItemCompressedNoir) { - return new PublicCallStackItemCompressed( - mapAztecAddressFromNoir(data.contract_address), - mapCallContextFromNoir(data.call_context), - mapFieldFromNoir(data.args_hash), - mapFieldFromNoir(data.returns_hash), - mapRevertCodeFromNoir(data.revert_code), - mapGasFromNoir(data.start_gas_left), - mapGasFromNoir(data.end_gas_left), - ); -} - -function mapPublicCallStackItemCompressedToNoir( - data: PublicCallStackItemCompressed, -): PublicCallStackItemCompressedNoir { - return { - contract_address: mapAztecAddressToNoir(data.contractAddress), - call_context: mapCallContextToNoir(data.callContext), - args_hash: mapFieldToNoir(data.argsHash), - returns_hash: mapFieldToNoir(data.returnsHash), - revert_code: mapRevertCodeToNoir(data.revertCode), - start_gas_left: mapGasToNoir(data.startGasLeft), - end_gas_left: mapGasToNoir(data.endGasLeft), - }; -} - function mapPublicCallRequestFromNoir(request: PublicCallRequestNoir) { return new PublicCallRequest( mapAztecAddressFromNoir(request.msg_sender), @@ -621,20 +553,6 @@ function mapCountedPublicCallRequestToNoir(request: CountedPublicCallRequest): C }; } -function mapPublicInnerCallRequestFromNoir(request: PublicInnerCallRequestNoir) { - return new PublicInnerCallRequest( - mapPublicCallStackItemCompressedFromNoir(request.item), - mapNumberFromNoir(request.counter), - ); -} - -function mapPublicInnerCallRequestToNoir(request: PublicInnerCallRequest): PublicInnerCallRequestNoir { - return { - item: mapPublicCallStackItemCompressedToNoir(request.item), - counter: mapNumberToNoir(request.counter), - }; -} - function mapNoteHashToNoir(noteHash: NoteHash): NoteHashNoir { return { value: mapFieldToNoir(noteHash.value), @@ -860,17 +778,6 @@ export function mapScopedReadRequestFromNoir(scoped: ScopedReadRequestNoir): Sco ); } -function mapTreeLeafReadRequestToNoir(readRequest: TreeLeafReadRequest): TreeLeafReadRequestNoir { - return { - value: mapFieldToNoir(readRequest.value), - leaf_index: mapFieldToNoir(readRequest.leafIndex), - }; -} - -function mapTreeLeafReadRequestFromNoir(readRequest: TreeLeafReadRequestNoir) { - return new TreeLeafReadRequest(mapFieldFromNoir(readRequest.value), mapFieldFromNoir(readRequest.leaf_index)); -} - /** * Maps a KeyValidationRequest to a noir KeyValidationRequest. * @param request - The KeyValidationRequest. @@ -1079,36 +986,6 @@ export function mapSha256HashToNoir(hash: Buffer): Field { return mapFieldToNoir(toTruncField(hash)); } -/** - * Maps public data update request from noir to the parsed type. - * @param publicDataUpdateRequest - The noir public data update request. - * @returns The parsed public data update request. - */ -export function mapPublicDataUpdateRequestFromNoir( - publicDataUpdateRequest: PublicDataUpdateRequestNoir, -): PublicDataUpdateRequest { - return new PublicDataUpdateRequest( - mapFieldFromNoir(publicDataUpdateRequest.leaf_slot), - mapFieldFromNoir(publicDataUpdateRequest.new_value), - mapNumberFromNoir(publicDataUpdateRequest.counter), - ); -} - -/** - * Maps public data update request to noir public data update request. - * @param publicDataUpdateRequest - The public data update request. - * @returns The noir public data update request. - */ -export function mapPublicDataUpdateRequestToNoir( - publicDataUpdateRequest: PublicDataUpdateRequest, -): PublicDataUpdateRequestNoir { - return { - leaf_slot: mapFieldToNoir(publicDataUpdateRequest.leafSlot), - new_value: mapFieldToNoir(publicDataUpdateRequest.newValue), - counter: mapNumberToNoir(publicDataUpdateRequest.sideEffectCounter), - }; -} - function mapPublicDataWriteFromNoir(write: PublicDataWriteNoir) { return new PublicDataWrite(mapFieldFromNoir(write.leaf_slot), mapFieldFromNoir(write.value)); } @@ -1120,32 +997,6 @@ function mapPublicDataWriteToNoir(write: PublicDataWrite): PublicDataWriteNoir { }; } -/** - * Maps public data read from noir to the parsed type. - * @param publicDataRead - The noir public data read. - * @returns The parsed public data read. - */ -export function mapPublicDataReadFromNoir(publicDataRead: PublicDataReadNoir): PublicDataRead { - return new PublicDataRead( - mapFieldFromNoir(publicDataRead.leaf_slot), - mapFieldFromNoir(publicDataRead.value), - mapNumberFromNoir(publicDataRead.counter), - ); -} - -/** - * Maps public data read to noir public data read. - * @param publicDataRead - The public data read. - * @returns The noir public data read. - */ -export function mapPublicDataReadToNoir(publicDataRead: PublicDataRead): PublicDataReadNoir { - return { - leaf_slot: mapFieldToNoir(publicDataRead.leafSlot), - value: mapFieldToNoir(publicDataRead.value), - counter: mapNumberToNoir(publicDataRead.counter), - }; -} - function mapReadRequestStatusToNoir(readRequestStatus: ReadRequestStatus): ReadRequestStatusNoir { return { state: mapNumberToNoir(readRequestStatus.state), @@ -1160,14 +1011,6 @@ function mapPendingReadHintToNoir(hint: PendingReadHint): PendingReadHintNoir { }; } -function mapTreeLeafReadRequestHintToNoir( - hint: TreeLeafReadRequestHint, -): TreeLeafReadRequestHintNoir { - return { - sibling_path: mapTuple(hint.siblingPath, mapFieldToNoir) as FixedLengthArray, - }; -} - function mapNoteHashSettledReadHintToNoir( hint: SettledReadHint, ): NoteHashSettledReadHintNoir { @@ -1221,43 +1064,15 @@ function mapNullifierReadRequestHintsToNoir, -): NullifierNonMembershipHintNoir { - return { - low_leaf_preimage: mapNullifierLeafPreimageToNoir(hint.leafPreimage), - membership_witness: mapMembershipWitnessToNoir(hint.membershipWitness), - }; -} - -function mapNullifierNonExistentReadRequestHintsToNoir( - hints: NullifierNonExistentReadRequestHints, -): NullifierNonExistentReadRequestHintsNoir { - return { - non_membership_hints: mapTuple(hints.nonMembershipHints, mapNullifierNonMembershipHintToNoir), - sorted_pending_values: mapTuple(hints.sortedPendingValues, mapNullifierToNoir), - sorted_pending_value_index_hints: mapTuple(hints.sortedPendingValueHints, mapNumberToNoir), - next_pending_value_indices: mapTuple(hints.nextPendingValueIndices, mapNumberToNoir), - }; -} - function mapPublicDataHintToNoir(hint: PublicDataHint): PublicDataHintNoir { return { leaf_slot: mapFieldToNoir(hint.leafSlot), value: mapFieldToNoir(hint.value), - override_counter: mapNumberToNoir(hint.overrideCounter), membership_witness: mapMembershipWitnessToNoir(hint.membershipWitness), leaf_preimage: mapPublicDataTreePreimageToNoir(hint.leafPreimage), }; } -function mapPublicDataLeafHintToNoir(hint: PublicDataLeafHint): PublicDataLeafHintNoir { - return { - preimage: mapPublicDataTreePreimageToNoir(hint.preimage), - membership_witness: mapMembershipWitnessToNoir(hint.membershipWitness), - }; -} - function mapOptionalNumberToNoir(option: OptionalNumber): OptionalNumberNoir { return { _is_some: option.isSome, @@ -1304,69 +1119,6 @@ function mapPrivateValidationRequestsFromNoir(requests: PrivateValidationRequest ); } -function mapPublicValidationRequestsToNoir(requests: PublicValidationRequests): PublicValidationRequestsNoir { - return { - for_rollup: mapRollupValidationRequestsToNoir(requests.forRollup), - note_hash_read_requests: mapTuple(requests.noteHashReadRequests, mapTreeLeafReadRequestToNoir), - nullifier_read_requests: mapTuple(requests.nullifierReadRequests, mapScopedReadRequestToNoir), - nullifier_non_existent_read_requests: mapTuple( - requests.nullifierNonExistentReadRequests, - mapScopedReadRequestToNoir, - ), - l1_to_l2_msg_read_requests: mapTuple(requests.l1ToL2MsgReadRequests, mapTreeLeafReadRequestToNoir), - public_data_reads: mapTuple(requests.publicDataReads, mapPublicDataReadToNoir), - }; -} - -function mapPublicValidationRequestsFromNoir(requests: PublicValidationRequestsNoir): PublicValidationRequests { - return new PublicValidationRequests( - mapRollupValidationRequestsFromNoir(requests.for_rollup), - mapTupleFromNoir( - requests.note_hash_read_requests, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - mapTreeLeafReadRequestFromNoir, - ), - mapTupleFromNoir( - requests.nullifier_read_requests, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, - mapScopedReadRequestFromNoir, - ), - mapTupleFromNoir( - requests.nullifier_non_existent_read_requests, - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - mapScopedReadRequestFromNoir, - ), - mapTupleFromNoir( - requests.l1_to_l2_msg_read_requests, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - mapTreeLeafReadRequestFromNoir, - ), - mapTupleFromNoir(requests.public_data_reads, MAX_PUBLIC_DATA_READS_PER_TX, mapPublicDataReadFromNoir), - ); -} - -function mapPublicValidationRequestArrayLengthsFromNoir(lengths: PublicValidationRequestArrayLengthsNoir) { - return new PublicValidationRequestArrayLengths( - mapNumberFromNoir(lengths.note_hash_read_requests), - mapNumberFromNoir(lengths.nullifier_read_requests), - mapNumberFromNoir(lengths.nullifier_non_existent_read_requests), - mapNumberFromNoir(lengths.l1_to_l2_msg_read_requests), - mapNumberFromNoir(lengths.public_data_reads), - ); -} - -function mapPublicValidationRequestArrayLengthsToNoir( - lengths: PublicValidationRequestArrayLengths, -): PublicValidationRequestArrayLengthsNoir { - return { - note_hash_read_requests: mapNumberToNoir(lengths.noteHashReadRequests), - nullifier_read_requests: mapNumberToNoir(lengths.nullifierReadRequests), - nullifier_non_existent_read_requests: mapNumberToNoir(lengths.nullifierNonExistentReadRequests), - l1_to_l2_msg_read_requests: mapNumberToNoir(lengths.l1ToL2MsgReadRequests), - public_data_reads: mapNumberToNoir(lengths.publicDataReads), - }; -} - export function mapPrivateAccumulatedDataFromNoir( privateAccumulatedData: PrivateAccumulatedDataNoir, ): PrivateAccumulatedData { @@ -1415,81 +1167,6 @@ export function mapPrivateAccumulatedDataToNoir(data: PrivateAccumulatedData): P }; } -export function mapPublicAccumulatedDataFromNoir( - publicAccumulatedData: PublicAccumulatedDataNoir, -): PublicAccumulatedData { - return new PublicAccumulatedData( - mapTupleFromNoir(publicAccumulatedData.note_hashes, MAX_NOTE_HASHES_PER_TX, mapScopedNoteHashFromNoir), - mapTupleFromNoir(publicAccumulatedData.nullifiers, MAX_NULLIFIERS_PER_TX, mapNullifierFromNoir), - mapTupleFromNoir(publicAccumulatedData.l2_to_l1_msgs, MAX_L2_TO_L1_MSGS_PER_TX, mapScopedL2ToL1MessageFromNoir), - mapTupleFromNoir( - publicAccumulatedData.note_encrypted_logs_hashes, - MAX_NOTE_ENCRYPTED_LOGS_PER_TX, - mapLogHashFromNoir, - ), - mapTupleFromNoir(publicAccumulatedData.encrypted_logs_hashes, MAX_ENCRYPTED_LOGS_PER_TX, mapScopedLogHashFromNoir), - mapTupleFromNoir( - publicAccumulatedData.unencrypted_logs_hashes, - MAX_UNENCRYPTED_LOGS_PER_TX, - mapScopedLogHashFromNoir, - ), - mapTupleFromNoir( - publicAccumulatedData.public_data_update_requests, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - mapPublicDataUpdateRequestFromNoir, - ), - mapTupleFromNoir(publicAccumulatedData.public_call_stack, MAX_ENQUEUED_CALLS_PER_TX, mapPublicCallRequestFromNoir), - mapGasFromNoir(publicAccumulatedData.gas_used), - ); -} - -export function mapPublicAccumulatedDataToNoir( - publicAccumulatedData: PublicAccumulatedData, -): PublicAccumulatedDataNoir { - return { - note_hashes: mapTuple(publicAccumulatedData.noteHashes, mapScopedNoteHashToNoir), - nullifiers: mapTuple(publicAccumulatedData.nullifiers, mapNullifierToNoir), - l2_to_l1_msgs: mapTuple(publicAccumulatedData.l2ToL1Msgs, mapScopedL2ToL1MessageToNoir), - note_encrypted_logs_hashes: mapTuple(publicAccumulatedData.noteEncryptedLogsHashes, mapLogHashToNoir), - encrypted_logs_hashes: mapTuple(publicAccumulatedData.encryptedLogsHashes, mapScopedLogHashToNoir), - unencrypted_logs_hashes: mapTuple(publicAccumulatedData.unencryptedLogsHashes, mapScopedLogHashToNoir), - public_data_update_requests: mapTuple( - publicAccumulatedData.publicDataUpdateRequests, - mapPublicDataUpdateRequestToNoir, - ), - public_call_stack: mapTuple(publicAccumulatedData.publicCallStack, mapPublicCallRequestToNoir), - gas_used: mapGasToNoir(publicAccumulatedData.gasUsed), - }; -} - -function mapPublicAccumulatedDataArrayLengthsFromNoir(lengths: PublicAccumulatedDataArrayLengthsNoir) { - return new PublicAccumulatedDataArrayLengths( - mapNumberFromNoir(lengths.note_hashes), - mapNumberFromNoir(lengths.nullifiers), - mapNumberFromNoir(lengths.l2_to_l1_msgs), - mapNumberFromNoir(lengths.note_encrypted_logs_hashes), - mapNumberFromNoir(lengths.encrypted_logs_hashes), - mapNumberFromNoir(lengths.unencrypted_logs_hashes), - mapNumberFromNoir(lengths.public_data_update_requests), - mapNumberFromNoir(lengths.public_call_stack), - ); -} - -function mapPublicAccumulatedDataArrayLengthsToNoir( - lengths: PublicAccumulatedDataArrayLengths, -): PublicAccumulatedDataArrayLengthsNoir { - return { - note_hashes: mapNumberToNoir(lengths.noteHashes), - nullifiers: mapNumberToNoir(lengths.nullifiers), - l2_to_l1_msgs: mapNumberToNoir(lengths.l2ToL1Msgs), - note_encrypted_logs_hashes: mapNumberToNoir(lengths.noteEncryptedLogsHashes), - encrypted_logs_hashes: mapNumberToNoir(lengths.encryptedLogsHashes), - unencrypted_logs_hashes: mapNumberToNoir(lengths.unencryptedLogsHashes), - public_data_update_requests: mapNumberToNoir(lengths.publicDataUpdateRequests), - public_call_stack: mapNumberToNoir(lengths.publicCallStack), - }; -} - export function mapGasFromNoir(gasUsed: GasNoir): Gas { return Gas.from({ daGas: mapNumberFromNoir(gasUsed.da_gas), @@ -1686,21 +1363,6 @@ function mapCombinedConstantDataToNoir(combinedConstantData: CombinedConstantDat }; } -export function mapPublicKernelCircuitPublicInputsToNoir( - inputs: PublicKernelCircuitPublicInputs, -): PublicKernelCircuitPublicInputsNoir { - return { - constants: mapCombinedConstantDataToNoir(inputs.constants), - validation_requests: mapPublicValidationRequestsToNoir(inputs.validationRequests), - end: mapPublicAccumulatedDataToNoir(inputs.end), - end_non_revertible: mapPublicAccumulatedDataToNoir(inputs.endNonRevertibleData), - end_side_effect_counter: mapNumberToNoir(inputs.endSideEffectCounter), - public_teardown_call_request: mapPublicCallRequestToNoir(inputs.publicTeardownCallRequest), - fee_payer: mapAztecAddressToNoir(inputs.feePayer), - revert_code: mapRevertCodeToNoir(inputs.revertCode), - }; -} - export function mapPrivateToPublicKernelCircuitPublicInputsToNoir( inputs: PrivateToPublicKernelCircuitPublicInputs, ): PrivateToPublicKernelCircuitPublicInputsNoir { @@ -1739,21 +1401,6 @@ export function mapKernelCircuitPublicInputsToNoir(inputs: KernelCircuitPublicIn }; } -/** - * Maps a public kernel inner data to a noir public kernel data. - * @param publicKernelData - The public kernel inner data. - * @returns The noir public kernel data. - */ -function mapPublicKernelDataToNoir(publicKernelData: PublicKernelData): PublicKernelDataNoir { - return { - public_inputs: mapPublicKernelCircuitPublicInputsToNoir(publicKernelData.publicInputs), - proof: mapRecursiveProofToNoir(publicKernelData.proof), - vk: mapVerificationKeyToNoir(publicKernelData.vk.keyAsFields, HONK_VERIFICATION_KEY_LENGTH_IN_FIELDS), - vk_index: mapFieldToNoir(new Fr(publicKernelData.vkIndex)), - vk_path: mapTuple(publicKernelData.vkPath, mapFieldToNoir), - }; -} - export function mapVerificationKeyToNoir( key: VerificationKeyAsFields, length: N, @@ -1893,52 +1540,6 @@ export function mapPrivateKernelResetHintsToNoir< }; } -export function mapPublicKernelCircuitPrivateInputsToNoir( - inputs: PublicKernelCircuitPrivateInputs, -): PublicKernelMergeCircuitPrivateInputsNoir { - return { - previous_kernel: mapPublicKernelDataToNoir(inputs.previousKernel), - enqueued_call: mapEnqueuedCallDataToNoir(inputs.enqueuedCall), - }; -} - -export function mapPublicKernelTailCircuitPrivateInputsToNoir( - inputs: PublicKernelTailCircuitPrivateInputs, -): PublicKernelTailCircuitPrivateInputsNoir { - return { - previous_kernel: mapPublicKernelDataToNoir(inputs.previousKernel), - note_hash_read_request_hints: mapTuple( - inputs.noteHashReadRequestHints, - (hint: TreeLeafReadRequestHint) => mapTreeLeafReadRequestHintToNoir(hint), - ), - nullifier_read_request_hints: mapNullifierReadRequestHintsToNoir(inputs.nullifierReadRequestHints), - nullifier_non_existent_read_request_hints: mapNullifierNonExistentReadRequestHintsToNoir( - inputs.nullifierNonExistentReadRequestHints, - ), - l1_to_l2_msg_read_request_hints: mapTuple( - inputs.l1ToL2MsgReadRequestHints, - (hint: TreeLeafReadRequestHint) => mapTreeLeafReadRequestHintToNoir(hint), - ), - public_data_hints: mapTuple(inputs.publicDataHints, mapPublicDataLeafHintToNoir), - start_state: mapPartialStateReferenceToNoir(inputs.startState), - }; -} - -export function mapPublicKernelCircuitPublicInputsFromNoir( - inputs: PublicKernelCircuitPublicInputsNoir, -): PublicKernelCircuitPublicInputs { - return new PublicKernelCircuitPublicInputs( - mapCombinedConstantDataFromNoir(inputs.constants), - mapPublicValidationRequestsFromNoir(inputs.validation_requests), - mapPublicAccumulatedDataFromNoir(inputs.end_non_revertible), - mapPublicAccumulatedDataFromNoir(inputs.end), - mapNumberFromNoir(inputs.end_side_effect_counter), - mapPublicCallRequestFromNoir(inputs.public_teardown_call_request), - mapAztecAddressFromNoir(inputs.fee_payer), - mapRevertCodeFromNoir(inputs.revert_code), - ); -} - /** * Maps global variables to the noir type. * @param globalVariables - The global variables. @@ -2068,51 +1669,6 @@ export function mapBlockRootOrBlockMergePublicInputsToNoir( }; } -function mapVMCircuitPublicInputsToNoir(inputs: VMCircuitPublicInputs): VMCircuitPublicInputsNoir { - return { - constants: mapCombinedConstantDataToNoir(inputs.constants), - call_request: mapPublicCallRequestToNoir(inputs.callRequest), - public_call_stack: mapTuple(inputs.publicCallStack, mapPublicInnerCallRequestToNoir), - previous_validation_request_array_lengths: mapPublicValidationRequestArrayLengthsToNoir( - inputs.previousValidationRequestArrayLengths, - ), - validation_requests: mapPublicValidationRequestsToNoir(inputs.validationRequests), - previous_accumulated_data_array_lengths: mapPublicAccumulatedDataArrayLengthsToNoir( - inputs.previousAccumulatedDataArrayLengths, - ), - accumulated_data: mapPublicAccumulatedDataToNoir(inputs.accumulatedData), - start_side_effect_counter: mapNumberToNoir(inputs.startSideEffectCounter), - end_side_effect_counter: mapNumberToNoir(inputs.endSideEffectCounter), - start_gas_left: mapGasToNoir(inputs.startGasLeft), - transaction_fee: mapFieldToNoir(inputs.transactionFee), - reverted: inputs.reverted, - }; -} - -export function mapVMCircuitPublicInputsFromNoir(inputs: VMCircuitPublicInputsNoir) { - return new VMCircuitPublicInputs( - mapCombinedConstantDataFromNoir(inputs.constants), - mapPublicCallRequestFromNoir(inputs.call_request), - mapTupleFromNoir(inputs.public_call_stack, MAX_ENQUEUED_CALLS_PER_TX, mapPublicInnerCallRequestFromNoir), - mapPublicValidationRequestArrayLengthsFromNoir(inputs.previous_validation_request_array_lengths), - mapPublicValidationRequestsFromNoir(inputs.validation_requests), - mapPublicAccumulatedDataArrayLengthsFromNoir(inputs.previous_accumulated_data_array_lengths), - mapPublicAccumulatedDataFromNoir(inputs.accumulated_data), - mapNumberFromNoir(inputs.start_side_effect_counter), - mapNumberFromNoir(inputs.end_side_effect_counter), - mapGasFromNoir(inputs.start_gas_left), - mapFieldFromNoir(inputs.transaction_fee), - inputs.reverted, - ); -} - -function mapEnqueuedCallDataToNoir(enqueuedCallData: EnqueuedCallData): EnqueuedCallDataNoir { - return { - data: mapVMCircuitPublicInputsToNoir(enqueuedCallData.data), - proof: {}, - }; -} - function mapAvmCircuitPublicInputsToNoir(inputs: AvmCircuitPublicInputs): AvmCircuitPublicInputsNoir { return { global_variables: mapGlobalVariablesToNoir(inputs.globalVariables), diff --git a/yarn-project/prover-client/src/orchestrator/block-building-helpers.ts b/yarn-project/prover-client/src/orchestrator/block-building-helpers.ts index 75044301ba51..77551c3693e2 100644 --- a/yarn-project/prover-client/src/orchestrator/block-building-helpers.ts +++ b/yarn-project/prover-client/src/orchestrator/block-building-helpers.ts @@ -58,7 +58,7 @@ import { type Tuple, assertLength, toFriendlyJSON } from '@aztec/foundation/seri import { computeUnbalancedMerkleRoot } from '@aztec/foundation/trees'; import { getVKIndex, getVKSiblingPath, getVKTreeRoot } from '@aztec/noir-protocol-circuits-types'; import { protocolContractTreeRoot } from '@aztec/protocol-contracts'; -import { HintsBuilder, computeFeePayerBalanceLeafSlot } from '@aztec/simulator'; +import { computeFeePayerBalanceLeafSlot } from '@aztec/simulator'; import { type MerkleTreeReadOperations } from '@aztec/world-state'; import { inspect } from 'util'; @@ -98,11 +98,10 @@ export async function buildBaseRollupHints( // Create data hint for reading fee payer initial balance in Fee Juice // If no fee payer is set, read hint should be empty - const hintsBuilder = new HintsBuilder(db); const leafSlot = computeFeePayerBalanceLeafSlot(tx.data.feePayer); const feePayerFeeJuiceBalanceReadHint = tx.data.feePayer.isZero() ? PublicDataHint.empty() - : await hintsBuilder.getPublicDataHint(leafSlot.toBigInt()); + : await getPublicDataHint(db, leafSlot.toBigInt()); // Update the note hash trees with the new items being inserted to get the new roots // that will be used by the next iteration of the base rollup circuit, skipping the empty ones @@ -181,6 +180,26 @@ export async function buildBaseRollupHints( }); } +async function getPublicDataHint(db: MerkleTreeWriteOperations, leafSlot: bigint) { + const { index } = (await db.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot)) ?? {}; + if (index === undefined) { + throw new Error(`Cannot find the previous value index for public data ${leafSlot}.`); + } + + const siblingPath = await db.getSiblingPath(MerkleTreeId.PUBLIC_DATA_TREE, index); + const membershipWitness = new MembershipWitness(PUBLIC_DATA_TREE_HEIGHT, index, siblingPath.toTuple()); + + const leafPreimage = (await db.getLeafPreimage(MerkleTreeId.PUBLIC_DATA_TREE, index)) as PublicDataTreeLeafPreimage; + if (!leafPreimage) { + throw new Error(`Cannot find the leaf preimage for public data tree at index ${index}.`); + } + + const exists = leafPreimage.slot.toBigInt() === leafSlot; + const value = exists ? leafPreimage.value : Fr.ZERO; + + return new PublicDataHint(new Fr(leafSlot), value, membershipWitness, leafPreimage); +} + export function createMergeRollupInputs( left: [BaseOrMergeRollupPublicInputs, RecursiveProof, VerificationKeyAsFields], right: [BaseOrMergeRollupPublicInputs, RecursiveProof, VerificationKeyAsFields], diff --git a/yarn-project/simulator/src/public/dual_side_effect_trace.ts b/yarn-project/simulator/src/public/dual_side_effect_trace.ts index 83928af67771..c875ebdf9def 100644 --- a/yarn-project/simulator/src/public/dual_side_effect_trace.ts +++ b/yarn-project/simulator/src/public/dual_side_effect_trace.ts @@ -1,13 +1,11 @@ import { type UnencryptedL2Log } from '@aztec/circuit-types'; import { - type CombinedConstantData, type ContractClassIdPreimage, type Gas, type NullifierLeafPreimage, type PublicCallRequest, type PublicDataTreeLeafPreimage, type SerializableContractInstance, - type VMCircuitPublicInputs, } from '@aztec/circuits.js'; import { type AztecAddress } from '@aztec/foundation/aztec-address'; import { type Fr } from '@aztec/foundation/fields'; @@ -271,30 +269,6 @@ export class DualSideEffectTrace implements PublicSideEffectTraceInterface { ); } - public toVMCircuitPublicInputs( - /** Constants */ - constants: CombinedConstantData, - /** The call request that triggered public execution. */ - callRequest: PublicCallRequest, - /** How much gas was available for this public execution. */ - startGasLeft: Gas, - /** How much gas was left after this public execution. */ - endGasLeft: Gas, - /** Transaction fee. */ - transactionFee: Fr, - /** The call's results */ - avmCallResults: AvmContractCallResult, - ): VMCircuitPublicInputs { - return this.enqueuedCallTrace.toVMCircuitPublicInputs( - constants, - callRequest, - startGasLeft, - endGasLeft, - transactionFee, - avmCallResults, - ); - } - public getUnencryptedLogs(): UnencryptedL2Log[] { return this.enqueuedCallTrace.getUnencryptedLogs(); } diff --git a/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.test.ts b/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.test.ts index a5e3460a082c..27d508393897 100644 --- a/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.test.ts +++ b/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.test.ts @@ -1,9 +1,8 @@ import { UnencryptedL2Log } from '@aztec/circuit-types'; import { AztecAddress, - CombinedConstantData, EthAddress, - Gas, + type IsEmpty, L2ToL1Message, LogHash, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, @@ -19,42 +18,22 @@ import { NoteHash, Nullifier, NullifierLeafPreimage, - PublicAccumulatedData, - PublicAccumulatedDataArrayLengths, - PublicCallRequest, PublicDataRead, PublicDataTreeLeafPreimage, PublicDataUpdateRequest, - PublicValidationRequestArrayLengths, - PublicValidationRequests, ReadRequest, SerializableContractInstance, TreeLeafReadRequest, + countAccumulatedItems, } from '@aztec/circuits.js'; -import { computePublicDataTreeLeafSlot, computeVarArgsHash, siloNullifier } from '@aztec/circuits.js/hash'; +import { computePublicDataTreeLeafSlot, siloNullifier } from '@aztec/circuits.js/hash'; import { Fr } from '@aztec/foundation/fields'; import { randomInt } from 'crypto'; -import { AvmContractCallResult } from '../avm/avm_contract_call_result.js'; -import { type AvmExecutionEnvironment } from '../avm/avm_execution_environment.js'; -import { initExecutionEnvironment } from '../avm/fixtures/index.js'; -import { PublicEnqueuedCallSideEffectTrace } from './enqueued_call_side_effect_trace.js'; +import { PublicEnqueuedCallSideEffectTrace, SideEffectArrayLengths } from './enqueued_call_side_effect_trace.js'; import { SideEffectLimitReachedError } from './side_effect_errors.js'; -/** - * Helper function to create a public execution request from an AVM execution environment - */ -function createPublicCallRequest(avmEnvironment: AvmExecutionEnvironment): PublicCallRequest { - return new PublicCallRequest( - avmEnvironment.sender, - avmEnvironment.address, - avmEnvironment.functionSelector, - avmEnvironment.isStaticCall, - computeVarArgsHash(avmEnvironment.calldata), - ); -} - describe('Enqueued-call Side Effect Trace', () => { const address = AztecAddress.random(); const utxo = Fr.random(); @@ -66,27 +45,17 @@ describe('Enqueued-call Side Effect Trace', () => { const log = [Fr.random(), Fr.random(), Fr.random()]; const contractInstance = SerializableContractInstance.default(); - const startGasLeft = Gas.fromFields([new Fr(randomInt(10000)), new Fr(randomInt(10000))]); - const endGasLeft = Gas.fromFields([new Fr(randomInt(10000)), new Fr(randomInt(10000))]); - const transactionFee = Fr.random(); - const calldata = [Fr.random(), Fr.random(), Fr.random(), Fr.random()]; - const returnValues = [Fr.random(), Fr.random()]; - - const constants = CombinedConstantData.empty(); - const avmEnvironment = initExecutionEnvironment({ - address, - calldata, - transactionFee, - }); - const avmCallResults = new AvmContractCallResult(/*reverted=*/ false, returnValues); - - const emptyValidationRequests = PublicValidationRequests.empty(); - let startCounter: number; let startCounterFr: Fr; let startCounterPlus1: number; let trace: PublicEnqueuedCallSideEffectTrace; + const expectNonEmptyItems = (array: T[], expected: T[]) => { + const numNonEmptyItems = countAccumulatedItems(array); + expect(expected.length).toBe(numNonEmptyItems); + expect(array.slice(0, numNonEmptyItems)).toEqual(expected); + }; + beforeEach(() => { startCounter = randomInt(/*max=*/ 1000000); startCounterFr = new Fr(startCounter); @@ -94,28 +63,15 @@ describe('Enqueued-call Side Effect Trace', () => { trace = new PublicEnqueuedCallSideEffectTrace(startCounter); }); - const toVMCircuitPublicInputs = (trc: PublicEnqueuedCallSideEffectTrace) => { - return trc.toVMCircuitPublicInputs( - constants, - createPublicCallRequest(avmEnvironment), - startGasLeft, - endGasLeft, - transactionFee, - avmCallResults, - ); - }; - it('Should trace storage reads', () => { const leafPreimage = new PublicDataTreeLeafPreimage(slot, value, Fr.ZERO, 0n); trace.tracePublicStorageRead(address, slot, value, leafPreimage, Fr.ZERO, []); expect(trace.getCounter()).toBe(startCounterPlus1); - const expectedArray = PublicValidationRequests.empty().publicDataReads; const leafSlot = computePublicDataTreeLeafSlot(address, slot); - expectedArray[0] = new PublicDataRead(leafSlot, value, startCounter /*contractAddress*/); + const expected = [new PublicDataRead(leafSlot, value, startCounter /*contractAddress*/)]; + expectNonEmptyItems(trace.getSideEffects().publicDataReads, expected); - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.validationRequests.publicDataReads).toEqual(expectedArray); expect(trace.getAvmCircuitHints().storageValues.items).toEqual([{ key: startCounterFr, value }]); }); @@ -126,23 +82,17 @@ describe('Enqueued-call Side Effect Trace', () => { trace.tracePublicStorageWrite(address, slot, value, lowLeafPreimage, Fr.ZERO, [], newLeafPreimage, []); expect(trace.getCounter()).toBe(startCounterPlus1); - const expectedArray = PublicAccumulatedData.empty().publicDataUpdateRequests; const leafSlot = computePublicDataTreeLeafSlot(address, slot); - expectedArray[0] = new PublicDataUpdateRequest(leafSlot, value, startCounter /*contractAddress*/); - - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.accumulatedData.publicDataUpdateRequests).toEqual(expectedArray); + const expected = [new PublicDataUpdateRequest(leafSlot, value, startCounter /*contractAddress*/)]; + expectNonEmptyItems(trace.getSideEffects().publicDataWrites, expected); }); it('Should trace note hash checks', () => { const exists = true; trace.traceNoteHashCheck(address, utxo, leafIndex, exists, []); - const expectedArray = PublicValidationRequests.empty().noteHashReadRequests; - expectedArray[0] = new TreeLeafReadRequest(utxo, leafIndex); - - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.validationRequests.noteHashReadRequests).toEqual(expectedArray); + const expected = [new TreeLeafReadRequest(utxo, leafIndex)]; + expectNonEmptyItems(trace.getSideEffects().noteHashReadRequests, expected); expect(trace.getAvmCircuitHints().noteHashExists.items).toEqual([{ key: leafIndex, value: new Fr(exists) }]); }); @@ -151,11 +101,8 @@ describe('Enqueued-call Side Effect Trace', () => { trace.traceNewNoteHash(address, utxo, Fr.ZERO, []); expect(trace.getCounter()).toBe(startCounterPlus1); - const expectedArray = PublicAccumulatedData.empty().noteHashes; - expectedArray[0] = new NoteHash(utxo, startCounter).scope(address); - - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.accumulatedData.noteHashes).toEqual(expectedArray); + const expected = [new NoteHash(utxo, startCounter).scope(address)]; + expectNonEmptyItems(trace.getSideEffects().noteHashes, expected); }); it('Should trace nullifier checks', () => { @@ -164,14 +111,10 @@ describe('Enqueued-call Side Effect Trace', () => { trace.traceNullifierCheck(address, utxo, exists, lowLeafPreimage, Fr.ZERO, []); expect(trace.getCounter()).toBe(startCounterPlus1); - const expectedArray = PublicValidationRequests.empty().nullifierReadRequests; - expectedArray[0] = new ReadRequest(utxo, startCounter).scope(address); - - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.validationRequests.nullifierReadRequests).toEqual(expectedArray); - expect(circuitPublicInputs.validationRequests.nullifierNonExistentReadRequests).toEqual( - emptyValidationRequests.nullifierNonExistentReadRequests, - ); + const { nullifierReadRequests, nullifierNonExistentReadRequests } = trace.getSideEffects(); + const expected = [new ReadRequest(utxo, startCounter).scope(address)]; + expectNonEmptyItems(nullifierReadRequests, expected); + expectNonEmptyItems(nullifierNonExistentReadRequests, []); expect(trace.getAvmCircuitHints().nullifierExists.items).toEqual([{ key: startCounterFr, value: new Fr(exists) }]); }); @@ -182,14 +125,11 @@ describe('Enqueued-call Side Effect Trace', () => { trace.traceNullifierCheck(address, utxo, exists, lowLeafPreimage, Fr.ZERO, []); expect(trace.getCounter()).toBe(startCounterPlus1); - const expectedArray = PublicValidationRequests.empty().nullifierNonExistentReadRequests; - expectedArray[0] = new ReadRequest(utxo, startCounter).scope(address); + const { nullifierReadRequests, nullifierNonExistentReadRequests } = trace.getSideEffects(); + expectNonEmptyItems(nullifierReadRequests, []); - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.validationRequests.nullifierReadRequests).toEqual( - emptyValidationRequests.nullifierReadRequests, - ); - expect(circuitPublicInputs.validationRequests.nullifierNonExistentReadRequests).toEqual(expectedArray); + const expected = [new ReadRequest(utxo, startCounter).scope(address)]; + expectNonEmptyItems(nullifierNonExistentReadRequests, expected); expect(trace.getAvmCircuitHints().nullifierExists.items).toEqual([{ key: startCounterFr, value: new Fr(exists) }]); }); @@ -199,22 +139,16 @@ describe('Enqueued-call Side Effect Trace', () => { trace.traceNewNullifier(address, utxo, lowLeafPreimage, Fr.ZERO, [], []); expect(trace.getCounter()).toBe(startCounterPlus1); - const expectedArray = PublicAccumulatedData.empty().nullifiers; - expectedArray[0] = new Nullifier(siloNullifier(address, utxo), startCounter, Fr.ZERO); - - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.accumulatedData.nullifiers).toEqual(expectedArray); + const expected = [new Nullifier(siloNullifier(address, utxo), startCounter, Fr.ZERO)]; + expectNonEmptyItems(trace.getSideEffects().nullifiers, expected); }); it('Should trace L1ToL2 Message checks', () => { const exists = true; trace.traceL1ToL2MessageCheck(address, utxo, leafIndex, exists, []); - const expectedArray = PublicValidationRequests.empty().l1ToL2MsgReadRequests; - expectedArray[0] = new TreeLeafReadRequest(utxo, leafIndex); - - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.validationRequests.l1ToL2MsgReadRequests).toEqual(expectedArray); + const expected = [new TreeLeafReadRequest(utxo, leafIndex)]; + expectNonEmptyItems(trace.getSideEffects().l1ToL2MsgReadRequests, expected); expect(trace.getAvmCircuitHints().l1ToL2MessageExists.items).toEqual([ { @@ -228,11 +162,8 @@ describe('Enqueued-call Side Effect Trace', () => { trace.traceNewL2ToL1Message(address, recipient, content); expect(trace.getCounter()).toBe(startCounterPlus1); - const expectedArray = PublicAccumulatedData.empty().l2ToL1Msgs; - expectedArray[0] = new L2ToL1Message(EthAddress.fromField(recipient), content, startCounter).scope(address); - - const circuitPublicInputs = toVMCircuitPublicInputs(trace); - expect(circuitPublicInputs.accumulatedData.l2ToL1Msgs).toEqual(expectedArray); + const expected = [new L2ToL1Message(EthAddress.fromField(recipient), content, startCounter).scope(address)]; + expectNonEmptyItems(trace.getSideEffects().l2ToL1Msgs, expected); }); it('Should trace new unencrypted logs', () => { @@ -240,16 +171,12 @@ describe('Enqueued-call Side Effect Trace', () => { expect(trace.getCounter()).toBe(startCounterPlus1); const expectedLog = new UnencryptedL2Log(address, Buffer.concat(log.map(f => f.toBuffer()))); - const expectedArray = PublicAccumulatedData.empty().unencryptedLogsHashes; - expectedArray[0] = new LogHash( - Fr.fromBuffer(expectedLog.hash()), - startCounter, - new Fr(expectedLog.length + 4), - ).scope(address); - - const circuitPublicInputs = toVMCircuitPublicInputs(trace); + const expectedHashes = [ + new LogHash(Fr.fromBuffer(expectedLog.hash()), startCounter, new Fr(expectedLog.length + 4)).scope(address), + ]; + expect(trace.getUnencryptedLogs()).toEqual([expectedLog]); - expect(circuitPublicInputs.accumulatedData.unencryptedLogsHashes).toEqual(expectedArray); + expectNonEmptyItems(trace.getSideEffects().unencryptedLogsHashes, expectedHashes); }); it('Should trace get contract instance', () => { @@ -259,7 +186,6 @@ describe('Enqueued-call Side Effect Trace', () => { trace.traceGetContractInstance(address, exists, instance); expect(trace.getCounter()).toBe(startCounterPlus1); - //const circuitPublicInputs = toVMCircuitPublicInputs(trace); expect(trace.getAvmCircuitHints().contractInstances.items).toEqual([ { address, @@ -418,22 +344,17 @@ describe('Enqueued-call Side Effect Trace', () => { it('PreviousValidationRequestArrayLengths and PreviousAccumulatedDataArrayLengths contribute to limits', () => { trace = new PublicEnqueuedCallSideEffectTrace( 0, - new PublicValidationRequestArrayLengths( + new SideEffectArrayLengths( + MAX_PUBLIC_DATA_READS_PER_TX, + MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, + MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIER_READ_REQUESTS_PER_TX, MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_PUBLIC_DATA_READS_PER_TX, - ), - new PublicAccumulatedDataArrayLengths( - MAX_NOTE_HASHES_PER_TX, MAX_NULLIFIERS_PER_TX, + MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, - 0, - 0, MAX_UNENCRYPTED_LOGS_PER_TX, - MAX_PUBLIC_DATA_READS_PER_TX, - 0, ), ); expect(() => trace.tracePublicStorageRead(AztecAddress.fromNumber(42), new Fr(42), new Fr(42))).toThrow( diff --git a/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.ts b/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.ts index 43f24639abbf..bcaef703b848 100644 --- a/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.ts +++ b/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.ts @@ -14,7 +14,6 @@ import { AvmPublicDataReadTreeHint, AvmPublicDataWriteTreeHint, type AztecAddress, - type CombinedConstantData, type ContractClassIdPreimage, EthAddress, Gas, @@ -23,11 +22,9 @@ import { L1_TO_L2_MSG_TREE_HEIGHT, L2ToL1Message, LogHash, - MAX_ENCRYPTED_LOGS_PER_TX, MAX_ENQUEUED_CALLS_PER_TX, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, MAX_L2_TO_L1_MSGS_PER_TX, - MAX_NOTE_ENCRYPTED_LOGS_PER_TX, MAX_NOTE_HASHES_PER_TX, MAX_NOTE_HASH_READ_REQUESTS_PER_TX, MAX_NULLIFIERS_PER_TX, @@ -44,29 +41,21 @@ import { PUBLIC_DATA_TREE_HEIGHT, PrivateToAvmAccumulatedData, PrivateToAvmAccumulatedDataArrayLengths, - PublicAccumulatedData, - PublicAccumulatedDataArrayLengths, PublicCallRequest, PublicDataRead, PublicDataTreeLeafPreimage, PublicDataUpdateRequest, PublicDataWrite, - PublicInnerCallRequest, - PublicValidationRequestArrayLengths, - PublicValidationRequests, ReadRequest, - RollupValidationRequests, ScopedL2ToL1Message, ScopedLogHash, - ScopedNoteHash, - ScopedReadRequest, + type ScopedNoteHash, + type ScopedReadRequest, SerializableContractInstance, TreeLeafReadRequest, type TreeSnapshots, - VMCircuitPublicInputs, } from '@aztec/circuits.js'; import { computePublicDataTreeLeafSlot, siloNullifier } from '@aztec/circuits.js/hash'; -import { makeTuple } from '@aztec/foundation/array'; import { padArrayEnd } from '@aztec/foundation/collection'; import { Fr } from '@aztec/foundation/fields'; import { createDebugLogger } from '@aztec/foundation/log'; @@ -110,6 +99,29 @@ export type SideEffects = { unencryptedLogsHashes: ScopedLogHash[]; }; +export class SideEffectArrayLengths { + constructor( + public readonly publicDataReads: number, + public readonly publicDataWrites: number, + + public readonly noteHashReadRequests: number, + public readonly noteHashes: number, + + public readonly nullifierReadRequests: number, + public readonly nullifierNonExistentReadRequests: number, + public readonly nullifiers: number, + + public readonly l1ToL2MsgReadRequests: number, + public readonly l2ToL1Msgs: number, + + public readonly unencryptedLogs: number, + ) {} + + static empty() { + return new this(0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + } +} + /** * Trace side effects for an entire enqueued call. */ @@ -148,8 +160,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI /** Track parent's (or previous kernel's) lengths so the AVM can properly enforce TX-wide limits, * otherwise the public kernel can fail to prove because TX limits are breached. */ - private readonly previousValidationRequestArrayLengths: PublicValidationRequestArrayLengths = PublicValidationRequestArrayLengths.empty(), - private readonly previousAccumulatedDataArrayLengths: PublicAccumulatedDataArrayLengths = PublicAccumulatedDataArrayLengths.empty(), + private readonly previousSideEffectArrayLengths: SideEffectArrayLengths = SideEffectArrayLengths.empty(), ) { this.log.debug(`Creating trace instance with startSideEffectCounter: ${startSideEffectCounter}`); this.sideEffectCounter = startSideEffectCounter; @@ -159,23 +170,18 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI public fork() { return new PublicEnqueuedCallSideEffectTrace( this.sideEffectCounter, - new PublicValidationRequestArrayLengths( - this.previousValidationRequestArrayLengths.noteHashReadRequests + this.noteHashReadRequests.length, - this.previousValidationRequestArrayLengths.nullifierReadRequests + this.nullifierReadRequests.length, - this.previousValidationRequestArrayLengths.nullifierNonExistentReadRequests + + new SideEffectArrayLengths( + this.previousSideEffectArrayLengths.publicDataReads + this.publicDataReads.length, + this.previousSideEffectArrayLengths.publicDataWrites + this.publicDataWrites.length, + this.previousSideEffectArrayLengths.noteHashReadRequests + this.noteHashReadRequests.length, + this.previousSideEffectArrayLengths.noteHashes + this.noteHashes.length, + this.previousSideEffectArrayLengths.nullifierReadRequests + this.nullifierReadRequests.length, + this.previousSideEffectArrayLengths.nullifierNonExistentReadRequests + this.nullifierNonExistentReadRequests.length, - this.previousValidationRequestArrayLengths.l1ToL2MsgReadRequests + this.l1ToL2MsgReadRequests.length, - this.previousValidationRequestArrayLengths.publicDataReads + this.publicDataReads.length, - ), - new PublicAccumulatedDataArrayLengths( - this.previousAccumulatedDataArrayLengths.noteHashes + this.noteHashes.length, - this.previousAccumulatedDataArrayLengths.nullifiers + this.nullifiers.length, - this.previousAccumulatedDataArrayLengths.l2ToL1Msgs + this.l2ToL1Messages.length, - this.previousAccumulatedDataArrayLengths.noteEncryptedLogsHashes, - this.previousAccumulatedDataArrayLengths.encryptedLogsHashes, - this.previousAccumulatedDataArrayLengths.unencryptedLogsHashes + this.unencryptedLogsHashes.length, - this.previousAccumulatedDataArrayLengths.publicDataUpdateRequests + this.publicDataWrites.length, - this.previousAccumulatedDataArrayLengths.publicCallStack, + this.previousSideEffectArrayLengths.nullifiers + this.nullifiers.length, + this.previousSideEffectArrayLengths.l1ToL2MsgReadRequests + this.l1ToL2MsgReadRequests.length, + this.previousSideEffectArrayLengths.l2ToL1Msgs + this.l2ToL1Messages.length, + this.previousSideEffectArrayLengths.unencryptedLogs + this.unencryptedLogs.length, ), ); } @@ -226,7 +232,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI } // NOTE: exists and cached are unused for now but may be used for optimizations or kernel hints later if ( - this.publicDataReads.length + this.previousValidationRequestArrayLengths.publicDataReads >= + this.publicDataReads.length + this.previousSideEffectArrayLengths.publicDataReads >= MAX_PUBLIC_DATA_READS_PER_TX ) { throw new SideEffectLimitReachedError('public data (contract storage) read', MAX_PUBLIC_DATA_READS_PER_TX); @@ -259,7 +265,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI assert(newLeafPreimage.value.equals(value), 'Value mismatch when tracing in public data read'); } if ( - this.publicDataWrites.length + this.previousAccumulatedDataArrayLengths.publicDataUpdateRequests >= + this.publicDataWrites.length + this.previousSideEffectArrayLengths.publicDataWrites >= MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX ) { throw new SideEffectLimitReachedError( @@ -293,7 +299,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI ) { // NOTE: contractAddress is unused because noteHash is an already-siloed leaf if ( - this.noteHashReadRequests.length + this.previousValidationRequestArrayLengths.noteHashReadRequests >= + this.noteHashReadRequests.length + this.previousSideEffectArrayLengths.noteHashReadRequests >= MAX_NOTE_HASH_READ_REQUESTS_PER_TX ) { throw new SideEffectLimitReachedError('note hash read request', MAX_NOTE_HASH_READ_REQUESTS_PER_TX); @@ -315,7 +321,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI leafIndex: Fr, path: Fr[] = emptyNoteHashPath(), ) { - if (this.noteHashes.length + this.previousAccumulatedDataArrayLengths.noteHashes >= MAX_NOTE_HASHES_PER_TX) { + if (this.noteHashes.length + this.previousSideEffectArrayLengths.noteHashes >= MAX_NOTE_HASHES_PER_TX) { throw new SideEffectLimitReachedError('note hash', MAX_NOTE_HASHES_PER_TX); } @@ -366,7 +372,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI lowLeafPath: Fr[] = emptyNullifierPath(), insertionPath: Fr[] = emptyNullifierPath(), ) { - if (this.nullifiers.length + this.previousAccumulatedDataArrayLengths.nullifiers >= MAX_NULLIFIERS_PER_TX) { + if (this.nullifiers.length + this.previousSideEffectArrayLengths.nullifiers >= MAX_NULLIFIERS_PER_TX) { throw new SideEffectLimitReachedError('nullifier', MAX_NULLIFIERS_PER_TX); } @@ -390,7 +396,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI ) { // NOTE: contractAddress is unused because msgHash is an already-siloed leaf if ( - this.l1ToL2MsgReadRequests.length + this.previousValidationRequestArrayLengths.l1ToL2MsgReadRequests >= + this.l1ToL2MsgReadRequests.length + this.previousSideEffectArrayLengths.l1ToL2MsgReadRequests >= MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX ) { throw new SideEffectLimitReachedError('l1 to l2 message read request', MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX); @@ -405,7 +411,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI } public traceNewL2ToL1Message(contractAddress: AztecAddress, recipient: Fr, content: Fr) { - if (this.l2ToL1Messages.length + this.previousAccumulatedDataArrayLengths.l2ToL1Msgs >= MAX_L2_TO_L1_MSGS_PER_TX) { + if (this.l2ToL1Messages.length + this.previousSideEffectArrayLengths.l2ToL1Msgs >= MAX_L2_TO_L1_MSGS_PER_TX) { throw new SideEffectLimitReachedError('l2 to l1 message', MAX_L2_TO_L1_MSGS_PER_TX); } @@ -419,7 +425,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI public traceUnencryptedLog(contractAddress: AztecAddress, log: Fr[]) { if ( - this.unencryptedLogs.length + this.previousAccumulatedDataArrayLengths.unencryptedLogsHashes >= + this.unencryptedLogs.length + this.previousSideEffectArrayLengths.unencryptedLogs >= MAX_UNENCRYPTED_LOGS_PER_TX ) { throw new SideEffectLimitReachedError('unencrypted log', MAX_UNENCRYPTED_LOGS_PER_TX); @@ -594,39 +600,6 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI }; } - /** - * Construct AVM circuit public inputs based on traced contents. - */ - public toVMCircuitPublicInputs( - /** Constants. */ - constants: CombinedConstantData, - /** The call request that triggered public execution. */ - callRequest: PublicCallRequest, - /** How much gas was available for this public execution. */ - startGasLeft: Gas, - /** How much gas was left after this public execution. */ - endGasLeft: Gas, - /** Transaction fee. */ - transactionFee: Fr, - /** The call's results */ - avmCallResults: AvmContractCallResult, - ): VMCircuitPublicInputs { - return new VMCircuitPublicInputs( - /*constants=*/ constants, - /*callRequest=*/ callRequest, - /*publicCallStack=*/ makeTuple(MAX_ENQUEUED_CALLS_PER_TX, PublicInnerCallRequest.empty), - /*previousValidationRequestArrayLengths=*/ this.previousValidationRequestArrayLengths, - /*validationRequests=*/ this.getValidationRequests(), - /*previousAccumulatedDataArrayLengths=*/ this.previousAccumulatedDataArrayLengths, - /*accumulatedData=*/ this.getAccumulatedData(startGasLeft.sub(endGasLeft)), - /*startSideEffectCounter=*/ this.startSideEffectCounter, - /*endSideEffectCounter=*/ this.sideEffectCounter, - /*startGasLeft=*/ startGasLeft, - /*transactionFee=*/ transactionFee, - /*reverted=*/ avmCallResults.reverted, - ); - } - public toAvmCircuitPublicInputs( /** Globals. */ globalVariables: GlobalVariables, @@ -699,21 +672,6 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI return this.avmCircuitHints; } - private getValidationRequests() { - return new PublicValidationRequests( - RollupValidationRequests.empty(), - padArrayEnd(this.noteHashReadRequests, TreeLeafReadRequest.empty(), MAX_NOTE_HASH_READ_REQUESTS_PER_TX), - padArrayEnd(this.nullifierReadRequests, ScopedReadRequest.empty(), MAX_NULLIFIER_READ_REQUESTS_PER_TX), - padArrayEnd( - this.nullifierNonExistentReadRequests, - ScopedReadRequest.empty(), - MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - ), - padArrayEnd(this.l1ToL2MsgReadRequests, TreeLeafReadRequest.empty(), MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX), - padArrayEnd(this.publicDataReads, PublicDataRead.empty(), MAX_PUBLIC_DATA_READS_PER_TX), - ); - } - private getAvmAccumulatedData() { return new AvmAccumulatedData( padArrayEnd( @@ -736,20 +694,6 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI ); } - private getAccumulatedData(gasUsed: Gas) { - return new PublicAccumulatedData( - padArrayEnd(this.noteHashes, ScopedNoteHash.empty(), MAX_NOTE_HASHES_PER_TX), - padArrayEnd(this.nullifiers, Nullifier.empty(), MAX_NULLIFIERS_PER_TX), - padArrayEnd(this.l2ToL1Messages, ScopedL2ToL1Message.empty(), MAX_L2_TO_L1_MSGS_PER_TX), - /*noteEncryptedLogsHashes=*/ makeTuple(MAX_NOTE_ENCRYPTED_LOGS_PER_TX, LogHash.empty), - /*encryptedLogsHashes=*/ makeTuple(MAX_ENCRYPTED_LOGS_PER_TX, ScopedLogHash.empty), - padArrayEnd(this.unencryptedLogsHashes, ScopedLogHash.empty(), MAX_UNENCRYPTED_LOGS_PER_TX), - padArrayEnd(this.publicDataWrites, PublicDataUpdateRequest.empty(), MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX), - /*publicCallStack=*/ makeTuple(MAX_ENQUEUED_CALLS_PER_TX, PublicCallRequest.empty), - /*gasUsed=*/ gasUsed, - ); - } - private enforceLimitOnNullifierChecks(errorMsgOrigin: string = '') { // NOTE: Why error if _either_ limit was reached? If user code emits either an existent or non-existent // nullifier read request (NULLIFIEREXISTS, GETCONTRACTINSTANCE, *CALL), and one of the limits has been @@ -758,7 +702,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI // going to skip the read request and just revert instead" when the nullifier actually doesn't exist // (or vice versa). So, if either maximum has been reached, any nullifier-reading operation must error. if ( - this.nullifierReadRequests.length + this.previousValidationRequestArrayLengths.nullifierReadRequests >= + this.nullifierReadRequests.length + this.previousSideEffectArrayLengths.nullifierReadRequests >= MAX_NULLIFIER_READ_REQUESTS_PER_TX ) { throw new SideEffectLimitReachedError( @@ -768,7 +712,7 @@ export class PublicEnqueuedCallSideEffectTrace implements PublicSideEffectTraceI } if ( this.nullifierNonExistentReadRequests.length + - this.previousValidationRequestArrayLengths.nullifierNonExistentReadRequests >= + this.previousSideEffectArrayLengths.nullifierNonExistentReadRequests >= MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX ) { throw new SideEffectLimitReachedError( diff --git a/yarn-project/simulator/src/public/hints_builder.ts b/yarn-project/simulator/src/public/hints_builder.ts deleted file mode 100644 index 2674545f0916..000000000000 --- a/yarn-project/simulator/src/public/hints_builder.ts +++ /dev/null @@ -1,168 +0,0 @@ -import { type IndexedTreeId, MerkleTreeId } from '@aztec/circuit-types'; -import { - type Fr, - L1_TO_L2_MSG_TREE_HEIGHT, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - type MAX_NULLIFIERS_PER_TX, - type MAX_NULLIFIER_NON_EXISTENT_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, - type MAX_PUBLIC_DATA_READS_PER_TX, - type MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - MembershipWitness, - NOTE_HASH_TREE_HEIGHT, - NULLIFIER_TREE_HEIGHT, - type Nullifier, - type NullifierLeafPreimage, - PUBLIC_DATA_TREE_HEIGHT, - type PublicDataRead, - type PublicDataTreeLeafPreimage, - type PublicDataUpdateRequest, - type ScopedReadRequest, - type TreeLeafReadRequest, - TreeLeafReadRequestHint, - buildNullifierNonExistentReadRequestHints, - buildPublicDataHint, - buildPublicDataHints, - buildSiloedNullifierReadRequestHints, -} from '@aztec/circuits.js'; -import { makeTuple } from '@aztec/foundation/array'; -import { type Tuple } from '@aztec/foundation/serialize'; -import { type IndexedTreeLeafPreimage } from '@aztec/foundation/trees'; -import { type MerkleTreeReadOperations } from '@aztec/world-state'; - -export class HintsBuilder { - constructor(private db: MerkleTreeReadOperations) {} - - async getNoteHashReadRequestsHints( - readRequests: Tuple, - ) { - return await this.getTreeLeafReadRequestsHints( - readRequests, - MAX_NOTE_HASH_READ_REQUESTS_PER_TX, - NOTE_HASH_TREE_HEIGHT, - MerkleTreeId.NOTE_HASH_TREE, - ); - } - - async getNullifierReadRequestHints( - nullifierReadRequests: Tuple, - pendingNullifiers: Tuple, - ) { - return await buildSiloedNullifierReadRequestHints( - this, - nullifierReadRequests, - pendingNullifiers, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, - MAX_NULLIFIER_READ_REQUESTS_PER_TX, - ); - } - - getNullifierNonExistentReadRequestHints( - nullifierNonExistentReadRequests: Tuple, - pendingNullifiers: Tuple, - ) { - return buildNullifierNonExistentReadRequestHints(this, nullifierNonExistentReadRequests, pendingNullifiers); - } - - async getL1ToL2MsgReadRequestsHints( - readRequests: Tuple, - ) { - return await this.getTreeLeafReadRequestsHints( - readRequests, - MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, - L1_TO_L2_MSG_TREE_HEIGHT, - MerkleTreeId.L1_TO_L2_MESSAGE_TREE, - ); - } - - getPublicDataHints( - publicDataReads: Tuple, - publicDataUpdateRequests: Tuple, - ) { - return buildPublicDataHints(this, publicDataReads, publicDataUpdateRequests); - } - - getPublicDataHint(dataAction: PublicDataRead | PublicDataUpdateRequest | bigint) { - const slot = typeof dataAction === 'bigint' ? dataAction : dataAction.leafSlot.toBigInt(); - return buildPublicDataHint(this, slot); - } - - async getNullifierMembershipWitness(nullifier: Fr) { - const index = await this.db.findLeafIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBuffer()); - if (index === undefined) { - throw new Error(`Cannot find the leaf for nullifier ${nullifier.toBigInt()}.`); - } - - return this.getMembershipWitnessWithPreimage( - MerkleTreeId.NULLIFIER_TREE, - NULLIFIER_TREE_HEIGHT, - index, - ); - } - - async getLowNullifierMembershipWitness(nullifier: Fr) { - const res = await this.db.getPreviousValueIndex(MerkleTreeId.NULLIFIER_TREE, nullifier.toBigInt()); - if (!res) { - throw new Error(`Cannot find the low leaf for nullifier ${nullifier.toBigInt()}.`); - } - - const { index, alreadyPresent } = res; - if (alreadyPresent) { - throw new Error(`Nullifier ${nullifier.toBigInt()} already exists in the tree.`); - } - - // Should find a way to stop casting IndexedTreeLeafPreimage as NullifierLeafPreimage - return this.getMembershipWitnessWithPreimage( - MerkleTreeId.NULLIFIER_TREE, - NULLIFIER_TREE_HEIGHT, - index, - ); - } - - async getMatchOrLowPublicDataMembershipWitness(leafSlot: bigint) { - const res = await this.db.getPreviousValueIndex(MerkleTreeId.PUBLIC_DATA_TREE, leafSlot); - if (!res) { - throw new Error(`Cannot find the previous value index for public data ${leafSlot}.`); - } - - // Should find a way to stop casting IndexedTreeLeafPreimage as PublicDataTreeLeafPreimage everywhere. - return this.getMembershipWitnessWithPreimage( - MerkleTreeId.PUBLIC_DATA_TREE, - PUBLIC_DATA_TREE_HEIGHT, - res.index, - ); - } - - private async getMembershipWitnessWithPreimage< - TREE_HEIGHT extends number, - LEAF_PREIMAGE extends IndexedTreeLeafPreimage = IndexedTreeLeafPreimage, - >(treeId: IndexedTreeId, treeHeight: TREE_HEIGHT, index: bigint) { - const siblingPath = await this.db.getSiblingPath(treeId, index); - const membershipWitness = new MembershipWitness(treeHeight, index, siblingPath.toTuple()); - - const leafPreimage = (await this.db.getLeafPreimage(treeId, index)) as LEAF_PREIMAGE; - if (!leafPreimage) { - throw new Error(`Cannot find the leaf preimage for tree ${treeId} at index ${index}.`); - } - - return { membershipWitness, leafPreimage }; - } - - private async getTreeLeafReadRequestsHints( - readRequests: Tuple, - size: N, - treeHeight: TREE_HEIGHT, - treeId: MerkleTreeId, - ): Promise, N>> { - const hints = makeTuple(size, () => TreeLeafReadRequestHint.empty(treeHeight)); - for (let i = 0; i < readRequests.length; i++) { - const request = readRequests[i]; - if (!request.isEmpty()) { - const siblingPath = await this.db.getSiblingPath(treeId, request.leafIndex.toBigInt()); - hints[i] = new TreeLeafReadRequestHint(treeHeight, siblingPath.toTuple()); - } - } - return hints; - } -} diff --git a/yarn-project/simulator/src/public/index.ts b/yarn-project/simulator/src/public/index.ts index 52d955828e09..41cb04956e0b 100644 --- a/yarn-project/simulator/src/public/index.ts +++ b/yarn-project/simulator/src/public/index.ts @@ -6,12 +6,8 @@ export { } from './execution.js'; export { PublicExecutor } from './executor.js'; export * from './fee_payment.js'; -export { HintsBuilder } from './hints_builder.js'; export * from './public_db_sources.js'; -export * from './public_kernel.js'; -export * from './public_kernel_circuit_simulator.js'; export { PublicProcessor, PublicProcessorFactory } from './public_processor.js'; export { PublicSideEffectTrace } from './side_effect_trace.js'; export { PublicEnqueuedCallSideEffectTrace } from './enqueued_call_side_effect_trace.js'; -export { DualSideEffectTrace } from './dual_side_effect_trace.js'; export { getExecutionRequestsByPhase } from './utils.js'; diff --git a/yarn-project/simulator/src/public/public_kernel.ts b/yarn-project/simulator/src/public/public_kernel.ts deleted file mode 100644 index 146c3441f235..000000000000 --- a/yarn-project/simulator/src/public/public_kernel.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { - type KernelCircuitPublicInputs, - type PublicKernelCircuitPrivateInputs, - type PublicKernelCircuitPublicInputs, - type PublicKernelTailCircuitPrivateInputs, -} from '@aztec/circuits.js'; -import { createDebugLogger } from '@aztec/foundation/log'; -import { elapsed } from '@aztec/foundation/timer'; -import { - SimulatedPublicKernelMergeArtifact, - SimulatedPublicKernelTailArtifact, - convertSimulatedPublicMergeInputsToWitnessMap, - convertSimulatedPublicMergeOutputFromWitnessMap, - convertSimulatedPublicTailInputsToWitnessMap, - convertSimulatedPublicTailOutputFromWitnessMap, -} from '@aztec/noir-protocol-circuits-types'; - -import { type SimulationProvider } from '../providers/simulation_provider.js'; -import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js'; - -/** - * Implements the PublicKernelCircuitSimulator. - */ -export class RealPublicKernelCircuitSimulator implements PublicKernelCircuitSimulator { - private log = createDebugLogger('aztec:public-kernel-simulator'); - - constructor(private simulator: SimulationProvider) {} - - /** - * Simulates the public kernel app logic circuit from its inputs. - * @param input - Inputs to the circuit. - * @returns The public inputs as outputs of the simulation. - */ - public async publicKernelCircuitMerge( - input: PublicKernelCircuitPrivateInputs, - ): Promise { - const inputWitness = convertSimulatedPublicMergeInputsToWitnessMap(input); - const [duration, witness] = await elapsed(() => - this.simulator.simulateCircuit(inputWitness, SimulatedPublicKernelMergeArtifact), - ); - const result = convertSimulatedPublicMergeOutputFromWitnessMap(witness); - this.log.debug(`Simulated public kernel merge circuit`, { - eventName: 'circuit-simulation', - circuitName: 'public-kernel-merge', - duration, - inputSize: input.toBuffer().length, - outputSize: result.toBuffer().length, - }); - return result; - } - - /** - * Simulates the public kernel tail circuit from its inputs. - * @param input - Inputs to the circuit. - * @returns The public inputs as outputs of the simulation. - */ - public async publicKernelCircuitTail( - input: PublicKernelTailCircuitPrivateInputs, - ): Promise { - const inputWitness = convertSimulatedPublicTailInputsToWitnessMap(input); - const [duration, witness] = await elapsed(() => - this.simulator.simulateCircuit(inputWitness, SimulatedPublicKernelTailArtifact), - ); - const result = convertSimulatedPublicTailOutputFromWitnessMap(witness); - this.log.debug(`Simulated public kernel tail circuit`, { - eventName: 'circuit-simulation', - circuitName: 'public-kernel-tail', - duration, - inputSize: input.toBuffer().length, - outputSize: result.toBuffer().length, - }); - return result; - } -} diff --git a/yarn-project/simulator/src/public/public_kernel_circuit_simulator.ts b/yarn-project/simulator/src/public/public_kernel_circuit_simulator.ts deleted file mode 100644 index 36f26b36c4a4..000000000000 --- a/yarn-project/simulator/src/public/public_kernel_circuit_simulator.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { - type KernelCircuitPublicInputs, - type PublicKernelCircuitPrivateInputs, - type PublicKernelCircuitPublicInputs, - type PublicKernelTailCircuitPrivateInputs, -} from '@aztec/circuits.js'; - -/** - * Circuit simulator for the public kernel circuits. - */ -export interface PublicKernelCircuitSimulator { - /** - * Simulates the public kernel merge circuit from its inputs. - * @param inputs - Inputs to the circuit. - * @returns The public inputs as outputs of the simulation. - */ - publicKernelCircuitMerge(inputs: PublicKernelCircuitPrivateInputs): Promise; - /** - * Simulates the public kernel tail circuit from its inputs. - * @param inputs - Inputs to the circuit. - * @returns The public inputs as outputs of the simulation. - */ - publicKernelCircuitTail(inputs: PublicKernelTailCircuitPrivateInputs): Promise; -} diff --git a/yarn-project/simulator/src/public/public_kernel_tail_simulator.ts b/yarn-project/simulator/src/public/public_kernel_tail_simulator.ts deleted file mode 100644 index 6143f5b316dc..000000000000 --- a/yarn-project/simulator/src/public/public_kernel_tail_simulator.ts +++ /dev/null @@ -1,97 +0,0 @@ -import { - type KernelCircuitPublicInputs, - MAX_NULLIFIERS_PER_TX, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - NESTED_RECURSIVE_PROOF_LENGTH, - type PublicKernelCircuitPublicInputs, - PublicKernelData, - PublicKernelTailCircuitPrivateInputs, - VerificationKeyData, - makeEmptyRecursiveProof, - mergeAccumulatedData, -} from '@aztec/circuits.js'; -import { getVKSiblingPath } from '@aztec/noir-protocol-circuits-types'; -import { type MerkleTreeReadOperations } from '@aztec/world-state'; - -import { HintsBuilder } from './hints_builder.js'; -import { type PublicKernelCircuitSimulator } from './public_kernel_circuit_simulator.js'; - -export class PublicKernelTailSimulator { - constructor( - private db: MerkleTreeReadOperations, - private publicKernelSimulator: PublicKernelCircuitSimulator, - private hintsBuilder: HintsBuilder, - ) {} - - static create(db: MerkleTreeReadOperations, publicKernelSimulator: PublicKernelCircuitSimulator) { - const hintsBuilder = new HintsBuilder(db); - return new PublicKernelTailSimulator(db, publicKernelSimulator, hintsBuilder); - } - - async simulate(previousOutput: PublicKernelCircuitPublicInputs): Promise { - const inputs = await this.buildPrivateInputs(previousOutput); - - return await this.publicKernelSimulator.publicKernelCircuitTail(inputs); - } - - private async buildPrivateInputs(previousOutput: PublicKernelCircuitPublicInputs) { - const previousKernel = this.getPreviousKernelData(previousOutput); - - const { validationRequests, endNonRevertibleData: nonRevertibleData, end: revertibleData } = previousOutput; - - const noteHashReadRequestHints = await this.hintsBuilder.getNoteHashReadRequestsHints( - validationRequests.noteHashReadRequests, - ); - - const pendingNullifiers = mergeAccumulatedData( - nonRevertibleData.nullifiers, - revertibleData.nullifiers, - MAX_NULLIFIERS_PER_TX, - ); - - const nullifierReadRequestHints = await this.hintsBuilder.getNullifierReadRequestHints( - validationRequests.nullifierReadRequests, - pendingNullifiers, - ); - - const nullifierNonExistentReadRequestHints = await this.hintsBuilder.getNullifierNonExistentReadRequestHints( - validationRequests.nullifierNonExistentReadRequests, - pendingNullifiers, - ); - - const l1ToL2MsgReadRequestHints = await this.hintsBuilder.getL1ToL2MsgReadRequestsHints( - validationRequests.l1ToL2MsgReadRequests, - ); - - const pendingPublicDataWrites = mergeAccumulatedData( - nonRevertibleData.publicDataUpdateRequests, - revertibleData.publicDataUpdateRequests, - MAX_PUBLIC_DATA_UPDATE_REQUESTS_PER_TX, - ); - - const publicDataHints = await this.hintsBuilder.getPublicDataHints( - validationRequests.publicDataReads, - pendingPublicDataWrites, - ); - - const currentState = await this.db.getStateReference(); - - return new PublicKernelTailCircuitPrivateInputs( - previousKernel, - noteHashReadRequestHints, - nullifierReadRequestHints, - nullifierNonExistentReadRequestHints, - l1ToL2MsgReadRequestHints, - publicDataHints, - currentState.partial, - ); - } - - private getPreviousKernelData(previousOutput: PublicKernelCircuitPublicInputs): PublicKernelData { - const proof = makeEmptyRecursiveProof(NESTED_RECURSIVE_PROOF_LENGTH); - const vk = VerificationKeyData.makeFakeHonk(); - const vkIndex = 0; - const siblingPath = getVKSiblingPath(vkIndex); - return new PublicKernelData(previousOutput, proof, vk, vkIndex, siblingPath); - } -} diff --git a/yarn-project/simulator/src/public/public_tx_context.ts b/yarn-project/simulator/src/public/public_tx_context.ts index c5e6faae25e7..7126c5175ce3 100644 --- a/yarn-project/simulator/src/public/public_tx_context.ts +++ b/yarn-project/simulator/src/public/public_tx_context.ts @@ -15,11 +15,10 @@ import { type GlobalVariables, type Header, type PrivateToPublicAccumulatedData, - PublicAccumulatedDataArrayLengths, type PublicCallRequest, - PublicValidationRequestArrayLengths, RevertCode, type StateReference, + countAccumulatedItems, } from '@aztec/circuits.js'; import { type DebugLogger, createDebugLogger } from '@aztec/foundation/log'; @@ -28,12 +27,12 @@ import { inspect } from 'util'; import { AvmPersistableStateManager } from '../avm/index.js'; import { DualSideEffectTrace } from './dual_side_effect_trace.js'; -import { PublicEnqueuedCallSideEffectTrace } from './enqueued_call_side_effect_trace.js'; +import { PublicEnqueuedCallSideEffectTrace, SideEffectArrayLengths } from './enqueued_call_side_effect_trace.js'; import { type EnqueuedPublicCallExecutionResult } from './execution.js'; import { type WorldStateDB } from './public_db_sources.js'; import { PublicSideEffectTrace } from './side_effect_trace.js'; import { generateAvmCircuitPublicInputs, generateAvmProvingRequest } from './transitional_adapters.js'; -import { convertPrivateToPublicAccumulatedData, getCallRequestsByPhase, getExecutionRequestsByPhase } from './utils.js'; +import { getCallRequestsByPhase, getExecutionRequestsByPhase } from './utils.js'; /** * The transaction-level context for public execution. @@ -82,25 +81,30 @@ export class PublicTxContext { tx: Tx, globalVariables: GlobalVariables, ) { - const nonRevertibleAccumulatedDataFromPrivate = convertPrivateToPublicAccumulatedData( - tx.data.forPublic!.nonRevertibleAccumulatedData, - ); - const revertibleAccumulatedDataFromPrivate = convertPrivateToPublicAccumulatedData( - tx.data.forPublic!.revertibleAccumulatedData, + const nonRevertibleAccumulatedDataFromPrivate = tx.data.forPublic!.nonRevertibleAccumulatedData; + const revertibleAccumulatedDataFromPrivate = tx.data.forPublic!.revertibleAccumulatedData; + const nonRevertibleNullifiersFromPrivate = nonRevertibleAccumulatedDataFromPrivate.nullifiers.filter( + n => !n.isEmpty(), ); - - const nonRevertibleNullifiersFromPrivate = nonRevertibleAccumulatedDataFromPrivate.nullifiers - .filter(n => !n.isEmpty()) - .map(n => n.value); - const _revertibleNullifiersFromPrivate = revertibleAccumulatedDataFromPrivate.nullifiers - .filter(n => !n.isEmpty()) - .map(n => n.value); + const _revertibleNullifiersFromPrivate = revertibleAccumulatedDataFromPrivate.nullifiers.filter(n => !n.isEmpty()); const innerCallTrace = new PublicSideEffectTrace(); + + const previousAccumulatedDataArrayLengths = new SideEffectArrayLengths( + /*publicDataReads*/ 0, + /*publicDataWrites*/ 0, + /*noteHashReadRequests*/ 0, + countAccumulatedItems(nonRevertibleAccumulatedDataFromPrivate.noteHashes), + /*nullifierReadRequests*/ 0, + /*nullifierNonExistentReadRequests*/ 0, + countAccumulatedItems(nonRevertibleAccumulatedDataFromPrivate.nullifiers), + /*l1ToL2MsgReadRequests*/ 0, + countAccumulatedItems(nonRevertibleAccumulatedDataFromPrivate.l2ToL1Msgs), + /*unencryptedLogsHashes*/ 0, + ); const enqueuedCallTrace = new PublicEnqueuedCallSideEffectTrace( /*startSideEffectCounter=*/ 0, - PublicValidationRequestArrayLengths.empty(), - PublicAccumulatedDataArrayLengths.new(nonRevertibleAccumulatedDataFromPrivate), + previousAccumulatedDataArrayLengths, ); const trace = new DualSideEffectTrace(innerCallTrace, enqueuedCallTrace); diff --git a/yarn-project/simulator/src/public/side_effect_trace.ts b/yarn-project/simulator/src/public/side_effect_trace.ts index 5682e7cb6cc7..6c1bed9ee8ca 100644 --- a/yarn-project/simulator/src/public/side_effect_trace.ts +++ b/yarn-project/simulator/src/public/side_effect_trace.ts @@ -12,7 +12,6 @@ import { AvmPublicDataWriteTreeHint, type AztecAddress, CallContext, - type CombinedConstantData, type ContractClassIdPreimage, type ContractInstanceWithAddress, ContractStorageRead, @@ -44,7 +43,6 @@ import { ReadRequest, SerializableContractInstance, TreeLeafReadRequest, - type VMCircuitPublicInputs, } from '@aztec/circuits.js'; import { Fr } from '@aztec/foundation/fields'; import { createDebugLogger } from '@aztec/foundation/log'; @@ -510,23 +508,6 @@ export class PublicSideEffectTrace implements PublicSideEffectTraceInterface { throw new Error('Not implemented'); } - public toVMCircuitPublicInputs( - /** Constants. */ - _constants: CombinedConstantData, - /** The call request that triggered public execution. */ - _callRequest: PublicCallRequest, - /** How much gas was available for this public execution. */ - _startGasLeft: Gas, - /** How much gas was left after this public execution. */ - _endGasLeft: Gas, - /** Transaction fee. */ - _transactionFee: Fr, - /** The call's results */ - _avmCallResults: AvmContractCallResult, - ): VMCircuitPublicInputs { - throw new Error('Not implemented'); - } - private enforceLimitOnNullifierChecks(errorMsgOrigin: string = '') { // NOTE: Why error if _either_ limit was reached? If user code emits either an existent or non-existent // nullifier read request (NULLIFIEREXISTS, GETCONTRACTINSTANCE, *CALL), and one of the limits has been diff --git a/yarn-project/simulator/src/public/side_effect_trace_interface.ts b/yarn-project/simulator/src/public/side_effect_trace_interface.ts index f3e427aecaab..8c3c5ae4ac72 100644 --- a/yarn-project/simulator/src/public/side_effect_trace_interface.ts +++ b/yarn-project/simulator/src/public/side_effect_trace_interface.ts @@ -1,13 +1,11 @@ import { type UnencryptedL2Log } from '@aztec/circuit-types'; import { - type CombinedConstantData, type ContractClassIdPreimage, type Gas, type NullifierLeafPreimage, type PublicCallRequest, type PublicDataTreeLeafPreimage, type SerializableContractInstance, - type VMCircuitPublicInputs, } from '@aztec/circuits.js'; import { type AztecAddress } from '@aztec/foundation/aztec-address'; import { type Fr } from '@aztec/foundation/fields'; @@ -122,19 +120,5 @@ export interface PublicSideEffectTraceInterface { /** Function name for logging */ functionName: string, ): PublicFunctionCallResult; - toVMCircuitPublicInputs( - /** Constants. */ - constants: CombinedConstantData, - /** The call request that triggered public execution. */ - callRequest: PublicCallRequest, - /** How much gas was available for this public execution. */ - startGasLeft: Gas, - /** How much gas was left after this public execution. */ - endGasLeft: Gas, - /** Transaction fee. */ - transactionFee: Fr, - /** The call's results */ - avmCallResults: AvmContractCallResult, - ): VMCircuitPublicInputs; getUnencryptedLogs(): UnencryptedL2Log[]; } diff --git a/yarn-project/simulator/src/public/utils.ts b/yarn-project/simulator/src/public/utils.ts index 09379f2daf32..664fb1d23116 100644 --- a/yarn-project/simulator/src/public/utils.ts +++ b/yarn-project/simulator/src/public/utils.ts @@ -1,5 +1,5 @@ import { type PublicExecutionRequest, type Tx, TxExecutionPhase } from '@aztec/circuit-types'; -import { type PrivateToPublicAccumulatedData, PublicAccumulatedData, type PublicCallRequest } from '@aztec/circuits.js'; +import { type PublicCallRequest } from '@aztec/circuits.js'; export function getExecutionRequestsByPhase(tx: Tx, phase: TxExecutionPhase): PublicExecutionRequest[] { switch (phase) { @@ -30,18 +30,3 @@ export function getCallRequestsByPhase(tx: Tx, phase: TxExecutionPhase): PublicC throw new Error(`Unknown phase: ${phase}`); } } - -export function convertPrivateToPublicAccumulatedData( - fromPrivate: PrivateToPublicAccumulatedData, -): PublicAccumulatedData { - const to = PublicAccumulatedData.empty(); - to.noteHashes.forEach((_, i) => (to.noteHashes[i].noteHash.value = fromPrivate.noteHashes[i])); - to.nullifiers.forEach((_, i) => (to.nullifiers[i].value = fromPrivate.nullifiers[i])); - to.l2ToL1Msgs.forEach((_, i) => (to.l2ToL1Msgs[i] = fromPrivate.l2ToL1Msgs[i])); - to.noteEncryptedLogsHashes.forEach( - (_, i) => (to.noteEncryptedLogsHashes[i] = fromPrivate.noteEncryptedLogsHashes[i]), - ); - to.encryptedLogsHashes.forEach((_, i) => (to.encryptedLogsHashes[i] = fromPrivate.encryptedLogsHashes[i])); - to.publicCallStack.forEach((_, i) => (to.publicCallStack[i] = fromPrivate.publicCallRequests[i])); - return to; -} From a927f46de5710e05e5019c59026335da05eaffb2 Mon Sep 17 00:00:00 2001 From: Leila Wang Date: Mon, 18 Nov 2024 22:59:13 +0000 Subject: [PATCH 3/3] Fix. --- .../circuits.js/src/tests/factories.ts | 5 +-- .../enqueued_call_side_effect_trace.test.ts | 32 +++++++------------ 2 files changed, 13 insertions(+), 24 deletions(-) diff --git a/yarn-project/circuits.js/src/tests/factories.ts b/yarn-project/circuits.js/src/tests/factories.ts index a21dd5f1e497..1b3bdfbd8046 100644 --- a/yarn-project/circuits.js/src/tests/factories.ts +++ b/yarn-project/circuits.js/src/tests/factories.ts @@ -79,7 +79,6 @@ import { NoteLogHash, Nullifier, NullifierLeafPreimage, - PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH, PUBLIC_DATA_SUBTREE_SIBLING_PATH_LENGTH, PUBLIC_DATA_TREE_HEIGHT, ParityPublicInputs, @@ -1362,12 +1361,10 @@ export function makeAvmExecutionHints( * @returns the execution hints. */ export function makeAvmCircuitInputs(seed = 0, overrides: Partial> = {}): AvmCircuitInputs { - const values = Array(PUBLIC_CIRCUIT_PUBLIC_INPUTS_LENGTH).map((_, i) => seed + 0x2000 + i); - const publicInputs = PublicCircuitPublicInputs.fromBuffer(Buffer.from(values)); return AvmCircuitInputs.from({ functionName: `function${seed}`, calldata: makeArray((seed % 100) + 10, i => new Fr(i), seed + 0x1000), - publicInputs, + publicInputs: PublicCircuitPublicInputs.empty(), avmHints: makeAvmExecutionHints(seed + 0x3000), output: makeAvmCircuitPublicInputs(seed + 0x4000), ...overrides, diff --git a/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.test.ts b/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.test.ts index 27d508393897..96b415a2e045 100644 --- a/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.test.ts +++ b/yarn-project/simulator/src/public/enqueued_call_side_effect_trace.test.ts @@ -2,7 +2,6 @@ import { UnencryptedL2Log } from '@aztec/circuit-types'; import { AztecAddress, EthAddress, - type IsEmpty, L2ToL1Message, LogHash, MAX_L1_TO_L2_MSG_READ_REQUESTS_PER_TX, @@ -24,7 +23,6 @@ import { ReadRequest, SerializableContractInstance, TreeLeafReadRequest, - countAccumulatedItems, } from '@aztec/circuits.js'; import { computePublicDataTreeLeafSlot, siloNullifier } from '@aztec/circuits.js/hash'; import { Fr } from '@aztec/foundation/fields'; @@ -50,12 +48,6 @@ describe('Enqueued-call Side Effect Trace', () => { let startCounterPlus1: number; let trace: PublicEnqueuedCallSideEffectTrace; - const expectNonEmptyItems = (array: T[], expected: T[]) => { - const numNonEmptyItems = countAccumulatedItems(array); - expect(expected.length).toBe(numNonEmptyItems); - expect(array.slice(0, numNonEmptyItems)).toEqual(expected); - }; - beforeEach(() => { startCounter = randomInt(/*max=*/ 1000000); startCounterFr = new Fr(startCounter); @@ -70,7 +62,7 @@ describe('Enqueued-call Side Effect Trace', () => { const leafSlot = computePublicDataTreeLeafSlot(address, slot); const expected = [new PublicDataRead(leafSlot, value, startCounter /*contractAddress*/)]; - expectNonEmptyItems(trace.getSideEffects().publicDataReads, expected); + expect(trace.getSideEffects().publicDataReads).toEqual(expected); expect(trace.getAvmCircuitHints().storageValues.items).toEqual([{ key: startCounterFr, value }]); }); @@ -84,7 +76,7 @@ describe('Enqueued-call Side Effect Trace', () => { const leafSlot = computePublicDataTreeLeafSlot(address, slot); const expected = [new PublicDataUpdateRequest(leafSlot, value, startCounter /*contractAddress*/)]; - expectNonEmptyItems(trace.getSideEffects().publicDataWrites, expected); + expect(trace.getSideEffects().publicDataWrites).toEqual(expected); }); it('Should trace note hash checks', () => { @@ -92,7 +84,7 @@ describe('Enqueued-call Side Effect Trace', () => { trace.traceNoteHashCheck(address, utxo, leafIndex, exists, []); const expected = [new TreeLeafReadRequest(utxo, leafIndex)]; - expectNonEmptyItems(trace.getSideEffects().noteHashReadRequests, expected); + expect(trace.getSideEffects().noteHashReadRequests).toEqual(expected); expect(trace.getAvmCircuitHints().noteHashExists.items).toEqual([{ key: leafIndex, value: new Fr(exists) }]); }); @@ -102,7 +94,7 @@ describe('Enqueued-call Side Effect Trace', () => { expect(trace.getCounter()).toBe(startCounterPlus1); const expected = [new NoteHash(utxo, startCounter).scope(address)]; - expectNonEmptyItems(trace.getSideEffects().noteHashes, expected); + expect(trace.getSideEffects().noteHashes).toEqual(expected); }); it('Should trace nullifier checks', () => { @@ -113,8 +105,8 @@ describe('Enqueued-call Side Effect Trace', () => { const { nullifierReadRequests, nullifierNonExistentReadRequests } = trace.getSideEffects(); const expected = [new ReadRequest(utxo, startCounter).scope(address)]; - expectNonEmptyItems(nullifierReadRequests, expected); - expectNonEmptyItems(nullifierNonExistentReadRequests, []); + expect(nullifierReadRequests).toEqual(expected); + expect(nullifierNonExistentReadRequests).toEqual([]); expect(trace.getAvmCircuitHints().nullifierExists.items).toEqual([{ key: startCounterFr, value: new Fr(exists) }]); }); @@ -126,10 +118,10 @@ describe('Enqueued-call Side Effect Trace', () => { expect(trace.getCounter()).toBe(startCounterPlus1); const { nullifierReadRequests, nullifierNonExistentReadRequests } = trace.getSideEffects(); - expectNonEmptyItems(nullifierReadRequests, []); + expect(nullifierReadRequests).toEqual([]); const expected = [new ReadRequest(utxo, startCounter).scope(address)]; - expectNonEmptyItems(nullifierNonExistentReadRequests, expected); + expect(nullifierNonExistentReadRequests).toEqual(expected); expect(trace.getAvmCircuitHints().nullifierExists.items).toEqual([{ key: startCounterFr, value: new Fr(exists) }]); }); @@ -140,7 +132,7 @@ describe('Enqueued-call Side Effect Trace', () => { expect(trace.getCounter()).toBe(startCounterPlus1); const expected = [new Nullifier(siloNullifier(address, utxo), startCounter, Fr.ZERO)]; - expectNonEmptyItems(trace.getSideEffects().nullifiers, expected); + expect(trace.getSideEffects().nullifiers).toEqual(expected); }); it('Should trace L1ToL2 Message checks', () => { @@ -148,7 +140,7 @@ describe('Enqueued-call Side Effect Trace', () => { trace.traceL1ToL2MessageCheck(address, utxo, leafIndex, exists, []); const expected = [new TreeLeafReadRequest(utxo, leafIndex)]; - expectNonEmptyItems(trace.getSideEffects().l1ToL2MsgReadRequests, expected); + expect(trace.getSideEffects().l1ToL2MsgReadRequests).toEqual(expected); expect(trace.getAvmCircuitHints().l1ToL2MessageExists.items).toEqual([ { @@ -163,7 +155,7 @@ describe('Enqueued-call Side Effect Trace', () => { expect(trace.getCounter()).toBe(startCounterPlus1); const expected = [new L2ToL1Message(EthAddress.fromField(recipient), content, startCounter).scope(address)]; - expectNonEmptyItems(trace.getSideEffects().l2ToL1Msgs, expected); + expect(trace.getSideEffects().l2ToL1Msgs).toEqual(expected); }); it('Should trace new unencrypted logs', () => { @@ -176,7 +168,7 @@ describe('Enqueued-call Side Effect Trace', () => { ]; expect(trace.getUnencryptedLogs()).toEqual([expectedLog]); - expectNonEmptyItems(trace.getSideEffects().unencryptedLogsHashes, expectedHashes); + expect(trace.getSideEffects().unencryptedLogsHashes).toEqual(expectedHashes); }); it('Should trace get contract instance', () => {