use crate::{ context::{inputs::PrivateContextInputs, NullifierExistenceRequest, ReturnsHash}, hash::hash_args, messaging::process_l1_to_l2_message, oracle::{ call_private_function::call_private_function_internal, public_call::validate_public_calldata, tx_phase::{in_revertible_phase, notify_revertible_phase_start}, execution_cache, logs::notify_created_contract_class_log, nullifiers::notify_created_nullifier, },};use crate::protocol::{ abis::{ block_header::BlockHeader, call_context::CallContext, function_selector::FunctionSelector, gas_settings::GasSettings, log_hash::LogHash, nullifier::Nullifier, private_call_request::PrivateCallRequest, private_circuit_public_inputs::PrivateCircuitPublicInputs, private_log::{PrivateLog, PrivateLogData}, public_call_request::PublicCallRequest, }, address::{AztecAddress, EthAddress}, constants::{ CONTRACT_CLASS_LOG_SIZE_IN_FIELDS, MAX_CONTRACT_CLASS_LOGS_PER_CALL, MAX_ENQUEUED_CALLS_PER_CALL, MAX_TX_LIFETIME, MAX_L2_TO_L1_MSGS_PER_CALL, MAX_NULLIFIER_READ_REQUESTS_PER_CALL, MAX_NULLIFIERS_PER_CALL, MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL, MAX_PRIVATE_LOGS_PER_CALL, NULL_MSG_SENDER_CONTRACT_ADDRESS, PRIVATE_LOG_SIZE_IN_FIELDS, }, hash::poseidon2_hash, messaging::l2_to_l1_message::L2ToL1Message, side_effect::{Counted, scoped::Scoped}, traits::Empty, utils::arrays::{ClaimedLengthArray, trimmed_array_length_hint},};/// Minimal PrivateContext for protocol contracts going to audit./// Contains only the methods actually used by: fee_juice, auth_registry, contract_class_registry, contract_instance_registry#[derive(Eq)]pub struct PrivateContext { pub inputs: PrivateContextInputs, pub side_effect_counter: u32, pub min_revertible_side_effect_counter: u32, pub is_fee_payer: bool, pub args_hash: Field, pub return_hash: Field, pub expiration_timestamp: u64, pub nullifier_read_requests: BoundedVec<Scoped<Counted<Field>>, MAX_NULLIFIER_READ_REQUESTS_PER_CALL>, pub nullifiers: BoundedVec<Counted<Nullifier>, MAX_NULLIFIERS_PER_CALL>, pub private_call_requests: BoundedVec<PrivateCallRequest, MAX_PRIVATE_CALL_STACK_LENGTH_PER_CALL>, pub public_call_requests: BoundedVec<Counted<PublicCallRequest>, MAX_ENQUEUED_CALLS_PER_CALL>, pub public_teardown_call_request: PublicCallRequest, pub l2_to_l1_msgs: BoundedVec<Counted<L2ToL1Message>, MAX_L2_TO_L1_MSGS_PER_CALL>, // Header of a block whose state is used during private execution (not the block the transaction is included in). pub anchor_block_header: BlockHeader, pub private_logs: BoundedVec<Counted<PrivateLogData>, MAX_PRIVATE_LOGS_PER_CALL>, pub contract_class_logs_hashes: BoundedVec<Counted<LogHash>, MAX_CONTRACT_CLASS_LOGS_PER_CALL>, pub expected_non_revertible_side_effect_counter: u32, pub expected_revertible_side_effect_counter: u32,}impl PrivateContext { pub fn new(inputs: PrivateContextInputs, args_hash: Field) -> PrivateContext { PrivateContext { inputs, side_effect_counter: inputs.start_side_effect_counter + 1, min_revertible_side_effect_counter: 0, is_fee_payer: false, args_hash, return_hash: 0, expiration_timestamp: inputs.anchor_block_header.global_variables.timestamp + MAX_TX_LIFETIME, nullifier_read_requests: BoundedVec::new(), nullifiers: BoundedVec::new(), anchor_block_header: inputs.anchor_block_header, private_call_requests: BoundedVec::new(), public_call_requests: BoundedVec::new(), public_teardown_call_request: PublicCallRequest::empty(), l2_to_l1_msgs: BoundedVec::new(), private_logs: BoundedVec::new(), contract_class_logs_hashes: BoundedVec::new(), expected_non_revertible_side_effect_counter: 0, expected_revertible_side_effect_counter: 0, } } /// Returns the contract address that initiated this function call (similar to msg.sender in Solidity). pub fn maybe_msg_sender(self) -> Option<AztecAddress> { let maybe_msg_sender = self.inputs.call_context.msg_sender; if maybe_msg_sender == NULL_MSG_SENDER_CONTRACT_ADDRESS { Option::none() } else { Option::some(maybe_msg_sender) } } /// Returns the contract address of the current function being executed. pub fn this_address(self) -> AztecAddress { self.inputs.call_context.contract_address } /// Returns the chain ID of the current network. pub fn chain_id(self) -> Field { self.inputs.tx_context.chain_id } /// Returns the protocol version. pub fn version(self) -> Field { self.inputs.tx_context.version } /// Returns the gas settings for the current transaction. pub fn gas_settings(self) -> GasSettings { self.inputs.tx_context.gas_settings } /// Returns the function selector of the currently executing function. pub fn selector(self) -> FunctionSelector { self.inputs.call_context.function_selector } /// Returns the hash of the arguments passed to the current function. pub fn get_args_hash(self) -> Field { self.args_hash } /// Returns the anchor block header. pub fn get_anchor_block_header(self) -> BlockHeader { self.anchor_block_header } /// Sets the hash of the return values for this private function. pub fn set_return_hash<let N: u32>(&mut self, serialized_return_values: [Field; N]) { let return_hash = hash_args(serialized_return_values); self.return_hash = return_hash; execution_cache::store(serialized_return_values, return_hash); } /// Builds the PrivateCircuitPublicInputs for this private function. pub fn finish(self) -> PrivateCircuitPublicInputs { PrivateCircuitPublicInputs { call_context: self.inputs.call_context, args_hash: self.args_hash, returns_hash: self.return_hash, min_revertible_side_effect_counter: self.min_revertible_side_effect_counter, is_fee_payer: self.is_fee_payer, expiration_timestamp: self.expiration_timestamp, note_hash_read_requests: ClaimedLengthArray::empty(), // Not used by protocol contracts nullifier_read_requests: ClaimedLengthArray::from_bounded_vec( self.nullifier_read_requests, ), key_validation_requests_and_separators: ClaimedLengthArray::empty(), // Not used by protocol contracts note_hashes: ClaimedLengthArray::empty(), // Not used by protocol contracts nullifiers: ClaimedLengthArray::from_bounded_vec(self.nullifiers), private_call_requests: ClaimedLengthArray::from_bounded_vec(self.private_call_requests), public_call_requests: ClaimedLengthArray::from_bounded_vec(self.public_call_requests), public_teardown_call_request: self.public_teardown_call_request, l2_to_l1_msgs: ClaimedLengthArray::from_bounded_vec(self.l2_to_l1_msgs), start_side_effect_counter: self.inputs.start_side_effect_counter, end_side_effect_counter: self.side_effect_counter, private_logs: ClaimedLengthArray::from_bounded_vec(self.private_logs), contract_class_logs_hashes: ClaimedLengthArray::from_bounded_vec( self.contract_class_logs_hashes, ), anchor_block_header: self.anchor_block_header, tx_context: self.inputs.tx_context, expected_non_revertible_side_effect_counter: self .expected_non_revertible_side_effect_counter, expected_revertible_side_effect_counter: self.expected_revertible_side_effect_counter, tx_request_salt: self.inputs.tx_request_salt, } } /// Declares the end of the "setup phase" of this tx. Used by fee_juice. pub fn end_setup(&mut self) { self.side_effect_counter += 1; self.min_revertible_side_effect_counter = self.next_counter(); notify_revertible_phase_start(self.min_revertible_side_effect_counter); } pub fn in_revertible_phase(&mut self) -> bool { let current_counter = self.side_effect_counter; // Safety: Kernel will validate that the claim is correct by validating the expected counters. let is_revertible = unsafe { in_revertible_phase(current_counter) }; if is_revertible { if (self.expected_revertible_side_effect_counter == 0) | (current_counter < self.expected_revertible_side_effect_counter) { self.expected_revertible_side_effect_counter = current_counter; } } else if current_counter > self.expected_non_revertible_side_effect_counter { self.expected_non_revertible_side_effect_counter = current_counter; } is_revertible } /// Sets a deadline for when this transaction must be included in a block. pub fn set_expiration_timestamp(&mut self, expiration_timestamp: u64) { self.expiration_timestamp = std::cmp::min(self.expiration_timestamp, expiration_timestamp); } /// Pushes a new nullifier. Used by class_registry and instance_registry. pub fn push_nullifier(&mut self, nullifier: Field) { notify_created_nullifier(nullifier); self.nullifiers.push(Nullifier { value: nullifier, note_hash: 0 }.count(self.next_counter())); } /// Asserts that a nullifier has been emitted. Used by instance_registry. pub fn assert_nullifier_exists( &mut self, nullifier_existence_request: NullifierExistenceRequest, ) { let nullifier = nullifier_existence_request.nullifier(); let contract_address = nullifier_existence_request.maybe_contract_address().unwrap_or(AztecAddress::zero()); let request = Scoped::new( Counted::new(nullifier, self.next_counter()), contract_address, ); self.nullifier_read_requests.push(request); } /// Consumes a message sent from Ethereum (L1) to Aztec (L2). Used by fee_juice. pub fn consume_l1_to_l2_message( &mut self, content: Field, secret: Field, sender: EthAddress, leaf_index: Field, ) { let nullifier = process_l1_to_l2_message( self.anchor_block_header.state.l1_to_l2_message_tree.root, self.this_address(), sender, self.chain_id(), self.version(), content, secret, leaf_index, ); // Push nullifier (and the "commitment" corresponding to this can be "empty") self.push_nullifier(nullifier) } /// Emits a private log. Used by instance_registry. pub fn emit_private_log(&mut self, log: [Field; PRIVATE_LOG_SIZE_IN_FIELDS], length: u32) { let counter = self.next_counter(); let private_log = PrivateLogData { log: PrivateLog::new(log, length), note_hash_counter: 0 } .count(counter); self.private_logs.push(private_log); } /// Emits a contract class log. Used by class_registry. pub fn emit_contract_class_log<let N: u32>(&mut self, log: [Field; N]) { let contract_address = self.this_address(); let counter = self.next_counter(); let log_to_emit: [Field; CONTRACT_CLASS_LOG_SIZE_IN_FIELDS] = log.concat([0; CONTRACT_CLASS_LOG_SIZE_IN_FIELDS - N]); // Safety: The below length is constrained in the base rollup, which will make sure that all the fields beyond // length are zero. However, it won't be able to check that we didn't add extra padding (trailing zeroes) or // that we cut trailing zeroes from the end. let length = unsafe { trimmed_array_length_hint(log_to_emit) }; // We hash the entire padded log to ensure a user cannot pass a shorter length and so emit incorrect shorter // bytecode. let log_hash = poseidon2_hash(log_to_emit); // Safety: the below only exists to broadcast the raw log, so we can provide it to the base rollup later to be // constrained. unsafe { notify_created_contract_class_log(contract_address, log_to_emit, length, counter); } self.contract_class_logs_hashes.push(LogHash { value: log_hash, length: length }.count( counter, )); } /// Makes a read-only call to a private function. Used by auth_registry for authwit. pub fn static_call_private_function<let ArgsCount: u32>( &mut self, contract_address: AztecAddress, function_selector: FunctionSelector, args: [Field; ArgsCount], ) -> ReturnsHash { let args_hash = hash_args(args); execution_cache::store(args, args_hash); self.call_private_function_with_args_hash( contract_address, function_selector, args_hash, true, ) } fn call_private_function_with_args_hash( &mut self, contract_address: AztecAddress, function_selector: FunctionSelector, args_hash: Field, is_static_call: bool, ) -> ReturnsHash { let mut is_static_call = is_static_call | self.inputs.call_context.is_static_call; let start_side_effect_counter = self.side_effect_counter; // Safety: The oracle simulates the private call and returns the value of the side effects counter after // execution of the call. let (end_side_effect_counter, returns_hash) = unsafe { call_private_function_internal( contract_address, function_selector, args_hash, start_side_effect_counter, is_static_call, ) }; self.private_call_requests.push( PrivateCallRequest { call_context: CallContext { msg_sender: self.this_address(), contract_address, function_selector, is_static_call, }, args_hash, returns_hash, start_side_effect_counter, end_side_effect_counter, }, ); self.side_effect_counter = end_side_effect_counter + 1; ReturnsHash::new(returns_hash) } /// Enqueues a call to a public function with a calldata hash. Used by fee_juice and auth_registry. pub fn call_public_function_with_calldata_hash( &mut self, contract_address: AztecAddress, calldata_hash: Field, is_static_call: bool, hide_msg_sender: bool, ) { let counter = self.next_counter(); let is_static_call = is_static_call | self.inputs.call_context.is_static_call; validate_public_calldata(calldata_hash); let msg_sender = if hide_msg_sender { NULL_MSG_SENDER_CONTRACT_ADDRESS } else { self.this_address() }; let call_request = PublicCallRequest { msg_sender, contract_address, is_static_call, calldata_hash }; self.public_call_requests.push(Counted::new(call_request, counter)); } fn next_counter(&mut self) -> u32 { let counter = self.side_effect_counter; self.side_effect_counter += 1; counter }}impl Empty for PrivateContext { fn empty() -> Self { PrivateContext { inputs: PrivateContextInputs::empty(), side_effect_counter: 0 as u32, min_revertible_side_effect_counter: 0 as u32, is_fee_payer: false, args_hash: 0, return_hash: 0, expiration_timestamp: 0, nullifier_read_requests: BoundedVec::new(), nullifiers: BoundedVec::new(), private_call_requests: BoundedVec::new(), public_call_requests: BoundedVec::new(), public_teardown_call_request: PublicCallRequest::empty(), l2_to_l1_msgs: BoundedVec::new(), anchor_block_header: BlockHeader::empty(), private_logs: BoundedVec::new(), contract_class_logs_hashes: BoundedVec::new(), expected_non_revertible_side_effect_counter: 0, expected_revertible_side_effect_counter: 0, } }}use crate::{ context::gas::GasOpts, hash::{ compute_l1_to_l2_message_hash, compute_l1_to_l2_message_nullifier, compute_secret_hash, compute_siloed_nullifier, }, oracle::avm,};use crate::protocol::{ abis::function_selector::FunctionSelector, address::{AztecAddress, EthAddress}, constants::{MAX_U32_VALUE, NULL_MSG_SENDER_CONTRACT_ADDRESS}, traits::{Empty, FromField, Packable, Serialize, ToField},};/// Minimal PublicContext for protocol contracts going to audit.pub struct PublicContext { pub args_hash: Option<Field>, pub compute_args_hash: fn() -> Field,}impl Eq for PublicContext { fn eq(self, other: Self) -> bool { (self.args_hash == other.args_hash) // Can't compare the function compute_args_hash }}impl PublicContext { pub fn new(compute_args_hash: fn() -> Field) -> Self { PublicContext { args_hash: Option::none(), compute_args_hash } } /// Emits a _public_ log that will be visible onchain to everyone. pub fn emit_public_log<T>(_self: Self, log: T) where T: Serialize, { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::emit_public_log(Serialize::serialize(log).as_vector()) }; } /// Checks if a given note hash exists in the note hash tree at a particular leaf_index. pub fn note_hash_exists(_self: Self, note_hash: Field, leaf_index: u64) -> bool { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::note_hash_exists(note_hash, leaf_index) } } /// Checks if a specific L1-to-L2 message exists in the L1-to-L2 message tree at a particular leaf index. pub fn l1_to_l2_msg_exists(_self: Self, msg_hash: Field, msg_leaf_index: Field) -> bool { // Safety: AVM opcodes are constrained by the AVM itself TODO(alvaro): Make l1l2msg leaf index a u64 upstream unsafe { avm::l1_to_l2_msg_exists(msg_hash, msg_leaf_index as u64) } } /// Returns `true` if an `unsiloed_nullifier` has been emitted by `contract_address`. pub fn nullifier_exists_unsafe( _self: Self, unsiloed_nullifier: Field, contract_address: AztecAddress, ) -> bool { let siloed_nullifier = compute_siloed_nullifier(contract_address, unsiloed_nullifier); // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::nullifier_exists(siloed_nullifier) } } /// Consumes a message sent from Ethereum (L1) to Aztec (L2). pub fn consume_l1_to_l2_message( self: Self, content: Field, secret: Field, sender: EthAddress, leaf_index: Field, ) { let secret_hash = compute_secret_hash(secret); let message_hash = compute_l1_to_l2_message_hash( sender, self.chain_id(), /*recipient=*/ self.this_address(), self.version(), content, secret_hash, leaf_index, ); let nullifier = compute_l1_to_l2_message_nullifier(message_hash, secret); assert( !self.nullifier_exists_unsafe(nullifier, self.this_address()), "L1-to-L2 message is already nullified", ); assert( self.l1_to_l2_msg_exists(message_hash, leaf_index), "Tried to consume nonexistent L1-to-L2 message", ); self.push_nullifier(nullifier); } /// Sends an "L2 -> L1 message". pub fn message_portal(_self: Self, recipient: EthAddress, content: Field) { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::send_l2_to_l1_msg(recipient, content) }; } /// Calls a public function on another contract. pub unconstrained fn call_public_function<let N: u32>( _self: Self, contract_address: AztecAddress, function_selector: FunctionSelector, args: [Field; N], gas_opts: GasOpts, ) -> [Field] { let calldata = [function_selector.to_field()].concat(args); avm::call( gas_opts.l2_gas.unwrap_or(MAX_U32_VALUE), gas_opts.da_gas.unwrap_or(MAX_U32_VALUE), contract_address, calldata, ); // Use success_copy to determine whether the call succeeded let success = avm::success_copy(); let result_data = avm::returndata_copy(0, avm::returndata_size()); if !success { // Rethrow the revert data. avm::revert(result_data); } result_data } /// Makes a read-only call to a public function on another contract. pub unconstrained fn static_call_public_function<let N: u32>( _self: Self, contract_address: AztecAddress, function_selector: FunctionSelector, args: [Field; N], gas_opts: GasOpts, ) -> [Field] { let calldata = [function_selector.to_field()].concat(args); avm::call_static( gas_opts.l2_gas.unwrap_or(MAX_U32_VALUE), gas_opts.da_gas.unwrap_or(MAX_U32_VALUE), contract_address, calldata, ); // Use success_copy to determine whether the call succeeded let success = avm::success_copy(); let result_data = avm::returndata_copy(0, avm::returndata_size()); if !success { // Rethrow the revert data. avm::revert(result_data); } result_data } /// Adds a new note hash to the Note Hash Tree. pub fn push_note_hash(_self: Self, note_hash: Field) { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::emit_note_hash(note_hash) }; } /// Adds a new nullifier to the Nullifier Tree. pub fn push_nullifier(_self: Self, nullifier: Field) { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::emit_nullifier(nullifier) }; } /// Returns the address of the current contract being executed. pub fn this_address(_self: Self) -> AztecAddress { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::address() } } /// Returns the contract address that initiated this function call. pub fn maybe_msg_sender(_self: Self) -> Option<AztecAddress> { // Safety: AVM opcodes are constrained by the AVM itself let maybe_msg_sender = unsafe { avm::sender() }; if maybe_msg_sender == NULL_MSG_SENDER_CONTRACT_ADDRESS { Option::none() } else { Option::some(maybe_msg_sender) } } /// Returns the function selector of the currently-executing function. pub fn selector(_self: Self) -> FunctionSelector { // The selector is the first element of the calldata when calling a public function through dispatch. // Safety: AVM opcodes are constrained by the AVM itself. let raw_selector: [Field; 1] = unsafe { avm::calldata_copy(0, 1) }; FunctionSelector::from_field(raw_selector[0]) } /// Returns the hash of the arguments passed to the current function. pub fn get_args_hash(mut self) -> Field { if !self.args_hash.is_some() { self.args_hash = Option::some((self.compute_args_hash)()); } self.args_hash.unwrap_unchecked() } /// Returns the "transaction fee" for the current transaction. pub fn transaction_fee(_self: Self) -> Field { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::transaction_fee() } } /// Returns the chain ID of the current network. pub fn chain_id(_self: Self) -> Field { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::chain_id() } } /// Returns the protocol version. pub fn version(_self: Self) -> Field { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::version() } } /// Returns the current block number. pub fn block_number(_self: Self) -> u32 { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::block_number() } } /// Returns the timestamp of the current block. pub fn timestamp(_self: Self) -> u64 { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::timestamp() } } /// Returns the fee per unit of L2 gas. pub fn min_fee_per_l2_gas(_self: Self) -> u128 { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::min_fee_per_l2_gas() } } /// Returns the fee per unit of DA gas. pub fn min_fee_per_da_gas(_self: Self) -> u128 { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::min_fee_per_da_gas() } } /// Returns the remaining L2 gas available. pub fn l2_gas_left(_self: Self) -> u32 { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::l2_gas_left() } } /// Returns the remaining DA gas available. pub fn da_gas_left(_self: Self) -> u32 { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::da_gas_left() } } /// Checks if the current execution is within a staticcall context. pub fn is_static_call(_self: Self) -> bool { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::is_static_call() } } /// Reads raw field values from public storage. pub fn raw_storage_read<let N: u32>(self: Self, storage_slot: Field) -> [Field; N] { let mut out = [0; N]; for i in 0..N { // Safety: AVM opcodes are constrained by the AVM itself out[i] = unsafe { avm::storage_read(storage_slot + i as Field, self.this_address().to_field()) }; } out } /// Reads a typed value from public storage. pub fn storage_read<T>(self, storage_slot: Field) -> T where T: Packable, { T::unpack(self.raw_storage_read(storage_slot)) } /// Writes raw field values to public storage. pub fn raw_storage_write<let N: u32>(_self: Self, storage_slot: Field, values: [Field; N]) { for i in 0..N { // Safety: AVM opcodes are constrained by the AVM itself unsafe { avm::storage_write(storage_slot + i as Field, values[i]) }; } } /// Writes a typed value to public storage. pub fn storage_write<T>(self, storage_slot: Field, value: T) where T: Packable, { self.raw_storage_write(storage_slot, value.pack()); }}impl Empty for PublicContext { fn empty() -> Self { PublicContext::new(|| 0) }}//! Aztec hash functions.use crate::protocol::{ address::{AztecAddress, EthAddress}, constants::{ DOM_SEP__FUNCTION_ARGS, DOM_SEP__MESSAGE_NULLIFIER, DOM_SEP__PUBLIC_BYTECODE, DOM_SEP__PUBLIC_CALLDATA, DOM_SEP__SECRET_HASH, MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS, }, hash::{poseidon2_hash_subarray, poseidon2_hash_with_separator, sha256_to_field}, traits::ToField,};pub use crate::protocol::hash::compute_siloed_nullifier;pub fn compute_secret_hash(secret: Field) -> Field { poseidon2_hash_with_separator([secret], DOM_SEP__SECRET_HASH)}pub fn compute_l1_to_l2_message_hash( sender: EthAddress, chain_id: Field, recipient: AztecAddress, version: Field, content: Field, secret_hash: Field, leaf_index: Field,) -> Field { let mut hash_bytes = [0 as u8; 224]; let sender_bytes: [u8; 32] = sender.to_field().to_be_bytes(); let chain_id_bytes: [u8; 32] = chain_id.to_be_bytes(); let recipient_bytes: [u8; 32] = recipient.to_field().to_be_bytes(); let version_bytes: [u8; 32] = version.to_be_bytes(); let content_bytes: [u8; 32] = content.to_be_bytes(); let secret_hash_bytes: [u8; 32] = secret_hash.to_be_bytes(); let leaf_index_bytes: [u8; 32] = leaf_index.to_be_bytes(); for i in 0..32 { hash_bytes[i] = sender_bytes[i]; hash_bytes[i + 32] = chain_id_bytes[i]; hash_bytes[i + 64] = recipient_bytes[i]; hash_bytes[i + 96] = version_bytes[i]; hash_bytes[i + 128] = content_bytes[i]; hash_bytes[i + 160] = secret_hash_bytes[i]; hash_bytes[i + 192] = leaf_index_bytes[i]; } sha256_to_field(hash_bytes)}// The nullifier of a l1 to l2 message is the hash of the message salted with the secretpub fn compute_l1_to_l2_message_nullifier(message_hash: Field, secret: Field) -> Field { poseidon2_hash_with_separator([message_hash, secret], DOM_SEP__MESSAGE_NULLIFIER)}// Computes the hash of input arguments or return values for private functions, or for authwit creation.pub fn hash_args<let N: u32>(args: [Field; N]) -> Field { if args.len() == 0 { 0 } else { poseidon2_hash_with_separator(args, DOM_SEP__FUNCTION_ARGS) }}// Computes the hash of calldata for public functions.pub fn hash_calldata_array<let N: u32>(calldata: [Field; N]) -> Field { poseidon2_hash_with_separator(calldata, DOM_SEP__PUBLIC_CALLDATA)}/// Computes the public bytecode commitment for a contract class. The commitment is `hash([(length | separator),/// ...bytecode])`.////// @param packed_bytecode - The packed bytecode of the contract class. 0th word is the length in bytes./// packed_bytecode is mutable so that we can avoid copying the array to construct one starting with first_field/// instead of length. @returns The public bytecode commitment.pub fn compute_public_bytecode_commitment( mut packed_public_bytecode: [Field; MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS],) -> Field { // First field element contains the length of the bytecode let bytecode_length_in_bytes: u32 = packed_public_bytecode[0] as u32; let bytecode_length_in_fields: u32 = (bytecode_length_in_bytes / 31) + (bytecode_length_in_bytes % 31 != 0) as u32; // Don't allow empty public bytecode. AVM doesn't handle execution of contracts that exist with empty bytecode. assert(bytecode_length_in_fields != 0); assert(bytecode_length_in_fields < MAX_PACKED_PUBLIC_BYTECODE_SIZE_IN_FIELDS); // Packed_bytecode's 0th entry is the length. Append it to the separator before hashing. let first_field = DOM_SEP__PUBLIC_BYTECODE.to_field() + (packed_public_bytecode[0] as u64 << 32) as Field; packed_public_bytecode[0] = first_field; // `fields_to_hash` is the number of fields from the start of `packed_public_bytecode` that should be included in // the hash. Fields after this length are ignored. +1 to account for the separator. let num_fields_to_hash = bytecode_length_in_fields + 1; poseidon2_hash_subarray(packed_public_bytecode, num_fields_to_hash)}use crate::{ hash::{compute_l1_to_l2_message_hash, compute_l1_to_l2_message_nullifier, compute_secret_hash}, oracle::get_l1_to_l2_membership_witness::get_l1_to_l2_membership_witness,};use crate::protocol::{ address::{AztecAddress, EthAddress}, merkle_tree::root::root_from_sibling_path,};pub fn process_l1_to_l2_message( l1_to_l2_root: Field, contract_address: AztecAddress, portal_contract_address: EthAddress, chain_id: Field, version: Field, content: Field, secret: Field, leaf_index: Field,) -> Field { let secret_hash = compute_secret_hash(secret); let message_hash = compute_l1_to_l2_message_hash( portal_contract_address, chain_id, contract_address, version, content, secret_hash, leaf_index, ); // We prove that `message_hash` is in the tree by showing the derivation of the tree root, using a merkle path we // get from an oracle. // Safety: The witness is only used as a "magical value" that makes the merkle proof below pass. Hence it's safe. let (_leaf_index, sibling_path) = unsafe { get_l1_to_l2_membership_witness(contract_address, message_hash, secret) }; let root = root_from_sibling_path(message_hash, leaf_index, sibling_path); assert_eq(root, l1_to_l2_root, "Message not in state"); compute_l1_to_l2_message_nullifier(message_hash, secret)}/// Stores values represented as slice in execution cache to be later obtained by its hash.pub fn store<let N: u32>(values: [Field; N], hash: Field) { // Safety: This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to // call. When loading the values, however, the caller must check that the values are indeed the preimage. unsafe { store_in_execution_cache_oracle_wrapper(values, hash) };}unconstrained fn store_in_execution_cache_oracle_wrapper<let N: u32>( values: [Field; N], hash: Field,) { store_in_execution_cache_oracle(values, hash);}pub unconstrained fn load<let N: u32>(hash: Field) -> [Field; N] { load_from_execution_cache_oracle(hash)}// TODO(F-498): review naming consistency#[oracle(aztec_prv_setHashPreimage)]unconstrained fn store_in_execution_cache_oracle<let N: u32>(_values: [Field; N], _hash: Field) {}// TODO(F-498): review naming consistency#[oracle(aztec_prv_getHashPreimage)]unconstrained fn load_from_execution_cache_oracle<let N: u32>(_hash: Field) -> [Field; N] {}use crate::protocol::{address::AztecAddress, constants::L1_TO_L2_MSG_TREE_HEIGHT};/// Returns the leaf index and sibling path of an entry in the L1 to L2 messaging tree, which can then be used to prove/// its existence.pub unconstrained fn get_l1_to_l2_membership_witness( contract_address: AztecAddress, message_hash: Field, secret: Field,) -> (Field, [Field; L1_TO_L2_MSG_TREE_HEIGHT]) { get_l1_to_l2_membership_witness_oracle(contract_address, message_hash, secret)}// Obtains membership witness (index and sibling path) for a message in the L1 to L2 message tree.#[oracle(aztec_utl_getL1ToL2MembershipWitness)]unconstrained fn get_l1_to_l2_membership_witness_oracle( _contract_address: AztecAddress, _message_hash: Field, _secret: Field,) -> (Field, [Field; L1_TO_L2_MSG_TREE_HEIGHT]) {}//! Nullifier creation, existence checks, etc.use crate::protocol::address::aztec_address::AztecAddress;/// Notifies the simulator that a nullifier has been created, so that its correct status (pending or settled) can be/// determined when reading nullifiers in subsequent private function calls. The first non-revertible nullifier emitted/// is also used to compute note nonces.pub fn notify_created_nullifier(inner_nullifier: Field) { // Safety: This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to // call. unsafe { notify_created_nullifier_oracle(inner_nullifier) };}#[oracle(aztec_prv_notifyCreatedNullifier)]unconstrained fn notify_created_nullifier_oracle(_inner_nullifier: Field) {}/// Returns true if the nullifier has been emitted in the same transaction, i.e. if [notify_created_nullifier] has been/// called for this inner nullifier from the contract with the specified address.////// Note that despite sharing pending transaction information with the app, this is not a privacy leak: anyone in the/// network can always determine in which transaction a inner nullifier was emitted by a given contract by simply/// inspecting transaction effects. What _would_ constitute a leak would be to share the list of inner pending/// nullifiers, as that would reveal their preimages.pub unconstrained fn is_nullifier_pending( inner_nullifier: Field, contract_address: AztecAddress,) -> bool { is_nullifier_pending_oracle(inner_nullifier, contract_address)}#[oracle(aztec_prv_isNullifierPending)]unconstrained fn is_nullifier_pending_oracle( _inner_nullifier: Field, _contract_address: AztecAddress,) -> bool {}/// Returns true if the nullifier exists. Note that a `true` value can be constrained by proving existence of the/// nullifier, but a `false` value should not be relied upon since other transactions may emit this nullifier before/// the current transaction is included in a block. While this might seem of little use at first, certain design/// patterns benefit from this abstraction (see e.g. `PrivateMutable`).pub unconstrained fn check_nullifier_exists(inner_nullifier: Field) -> bool { check_nullifier_exists_oracle(inner_nullifier)}// TODO(F-498): review naming consistency#[oracle(aztec_utl_doesNullifierExist)]unconstrained fn check_nullifier_exists_oracle(_inner_nullifier: Field) -> bool {}/// Validates public calldata by checking that the preimage exists and the cumulative size is within limits.////// The check is unconstrained and the only purpose of it is to fail early in case of calldata overflow or a bug in/// calldata hashing.pub(crate) fn validate_public_calldata(calldata_hash: Field) { // Safety: This oracle call returns nothing: we only call it for its side effects (validating the calldata). // It is therefore always safe to call. unsafe { validate_public_calldata_wrapper(calldata_hash) }}unconstrained fn validate_public_calldata_wrapper(calldata_hash: Field) { validate_public_calldata_oracle(calldata_hash)}// TODO(F-498): review naming consistency#[oracle(aztec_prv_assertValidPublicCalldata)]unconstrained fn validate_public_calldata_oracle(_calldata_hash: Field) {}/// Notifies PXE of the side effect counter at which the revertible phase begins.////// PXE uses it to classify notes and nullifiers as revertible or non-revertible in its note cache. This information is/// then fed to kernels as hints.pub(crate) fn notify_revertible_phase_start(counter: u32) { // Safety: This oracle call returns nothing: we only call it for its side effects. It is therefore always safe to // call. unsafe { notify_revertible_phase_start_oracle_wrapper(counter) };}/// Returns whether a side effect counter falls in the revertible phase of the transaction.pub(crate) unconstrained fn in_revertible_phase(current_counter: u32) -> bool { in_revertible_phase_oracle(current_counter)}unconstrained fn notify_revertible_phase_start_oracle_wrapper(counter: u32) { notify_revertible_phase_start_oracle(counter);}#[oracle(aztec_prv_notifyRevertiblePhaseStart)]unconstrained fn notify_revertible_phase_start_oracle(_counter: u32) {}// TODO(F-498): review naming consistency#[oracle(aztec_prv_isExecutionInRevertiblePhase)]unconstrained fn in_revertible_phase_oracle(current_counter: u32) -> bool {}/// The oracle version constants are used to check that the oracle interface is in sync between PXE and Aztec.nr./// We version the oracle interface as `major.minor` where:/// - `major` = backward-breaking changes (must match exactly between PXE and Aztec.nr)/// - `minor` = oracle additions (non-breaking; PXE minor >= contract minor)////// The TypeScript counterparts are in `oracle_version.ts`.////// @dev Whenever a contract function or Noir test is run, the `aztec_misc_assertCompatibleOracleVersion` oracle is/// called. If the major version is incompatible, an error is thrown immediately. The minor version is recorded by/// the PXE and used to provide helpful error messages if a contract calls an oracle that doesn't exist. We don't throw/// immediately if AZTEC_NR_MINOR > PXE_MINOR because if a contract is updated to use a newer Aztec.nr dependency/// without actually using any of the new oracles then there is no reason to throw.pub global ORACLE_VERSION_MAJOR: Field = 30;pub global ORACLE_VERSION_MINOR: Field = 0;/// Asserts that the version of the oracle is compatible with the version expected by the contract.pub fn assert_compatible_oracle_version() { // Safety: This oracle call returns nothing: we only call it to check Aztec.nr and Oracle interface versions are // compatible. It is therefore always safe to call. unsafe { assert_compatible_oracle_version_wrapper(); }}unconstrained fn assert_compatible_oracle_version_wrapper() { assert_compatible_oracle_version_oracle(ORACLE_VERSION_MAJOR, ORACLE_VERSION_MINOR);}#[oracle(aztec_misc_assertCompatibleOracleVersion)]unconstrained fn assert_compatible_oracle_version_oracle(major: Field, minor: Field) {}mod test { use super::{ assert_compatible_oracle_version_oracle, ORACLE_VERSION_MAJOR, ORACLE_VERSION_MINOR, }; #[test] unconstrained fn compatible_oracle_version() { assert_compatible_oracle_version_oracle(ORACLE_VERSION_MAJOR, ORACLE_VERSION_MINOR); } #[test(should_fail_with = "Incompatible aztec cli version:")] unconstrained fn incompatible_oracle_version_major() { let arbitrary_incorrect_major = 318183437; assert_compatible_oracle_version_oracle(arbitrary_incorrect_major, ORACLE_VERSION_MINOR); }}use crate::protocol::{storage::map::derive_storage_slot_in_map, traits::ToField};use crate::state_vars::StateVariable;/// A key-value container for state variables.////// A key-value storage container that maps keys to state variables, similar to Solidity mappings.pub struct Map<K, V, Context> { pub context: Context, storage_slot: Field,}// Map reserves a single storage slot regardless of what it stores because nothing is stored at said slot: it is only// used to derive the storage slots of nested state variables.impl<K, V, Context> StateVariable<1, Context> for Map<K, V, Context> { fn new(context: Context, storage_slot: Field) -> Self { assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); Map { context, storage_slot } } fn get_storage_slot(self) -> Field { self.storage_slot }}impl<K, V, Context> Map<K, V, Context> { /// Returns the state variable associated with the given key. /// /// This is equivalent to accessing `mapping[key]` in Solidity. pub fn at<let N: u32>(self, key: K) -> V where K: ToField, V: StateVariable<N, Context>, { V::new( self.context, derive_storage_slot_in_map(self.storage_slot, key), ) }}use crate::context::{PublicContext, UtilityContext};use crate::protocol::traits::Packable;use crate::state_vars::StateVariable;/// Mutable public values.////// This is one of the most basic public state variables. It is equivalent to a non-`immutable` non-`constant` Solidity/// state variable.pub struct PublicMutable<T, Context> { context: Context, storage_slot: Field,}impl<T, Context, let M: u32> StateVariable<M, Context> for PublicMutable<T, Context>where T: Packable<N = M>,{ fn new(context: Context, storage_slot: Field) -> Self { assert(storage_slot != 0, "Storage slot 0 not allowed. Storage slots must start from 1."); PublicMutable { context, storage_slot } } fn get_storage_slot(self) -> Field { self.storage_slot }}impl<T> PublicMutable<T, PublicContext> { /// Returns the current value. pub fn read(self) -> T where T: Packable, { self.context.storage_read(self.storage_slot) } /// Stores a new value. pub fn write(self, value: T) where T: Packable, { self.context.storage_write(self.storage_slot, value); }}impl<T> PublicMutable<T, UtilityContext> { /// Returns the value at the anchor block. pub unconstrained fn read(self) -> T where T: Packable, { self.context.storage_read(self.storage_slot) }}use aztec::context::PublicContext;use aztec::protocol::address::AztecAddress;use aztec::protocol::hash::sha256_to_field;use aztec::protocol::traits::ToField;pub fn calculate_fee<TPublicContext>(context: PublicContext) -> Field { context.transaction_fee()}/// Computes the content hash for an L1-to-L2 "bridge gas" message, matching the hash produced on L1 by/// `FeeJuicePortal.depositToAztecPublic`: `sha256ToField(abi.encodeWithSignature("claim(bytes32,uint256)", to,/// amount))`.////// The 68-byte buffer is: [4-byte selector of "claim(bytes32,uint256)"][32-byte recipient][32-byte amount], hashed/// with `sha256_to_field` to produce a single Field.pub fn get_bridge_gas_msg_hash(owner: AztecAddress, amount: u128) -> Field { let mut hash_bytes = [0; 68]; let recipient_bytes: [u8; 32] = owner.to_field().to_be_bytes(); let amount_bytes: [u8; 32] = (amount as Field).to_be_bytes(); // The purpose of including the following selector is to make the message unique to that specific call. Note that // it has nothing to do with calling the function. let selector = comptime { keccak256::keccak256("claim(bytes32,uint256)".as_bytes(), 22) }; for i in 0..4 { hash_bytes[i] = selector[i]; } for i in 0..32 { hash_bytes[i + 4] = recipient_bytes[i]; hash_bytes[i + 36] = amount_bytes[i]; } let content_hash = sha256_to_field(hash_bytes); content_hash}/// Protocol contract that manages the native gas token ("Fee Juice") used to pay transaction fees.////// Fee Juice is minted on L2 by bridging from L1: a user deposits ERC-20 tokens into the L1 FeeJuicePortal, which/// sends an L1-to-L2 message. On L2, `claim` or `claim_and_end_setup` consumes that message and credits the/// recipient's balance via an enqueued public call to `_increase_public_balance`.////// The protocol's base rollup circuits read directly from this contract's `balances` storage map (at slot 1) to verify/// fee payers can cover their transaction costs. This storage layout is protocol-critical and must not change without/// updating the base rollup circuits.////// There is no withdrawal mechanism -- Fee Juice can only be bridged in, not withdrawn or transferred by users. Tokens/// leave the L1 portal only via `distributeFees` called by the Rollup contract to pay sequencers.mod lib;pub contract FeeJuice { use crate::lib::get_bridge_gas_msg_hash; use aztec::{ protocol::{ abis::function_selector::FunctionSelector, address::{AztecAddress, EthAddress}, constants::FEE_JUICE_ADDRESS, traits::{Deserialize, ToField}, }, state_vars::{Map, PublicMutable}, }; use std::ops::Add; struct Storage<Context> { // contract address --> public fee juice balance balances: Map<AztecAddress, PublicMutable<u128, Context>, Context>, } global INCREASE_PUBLIC_BALANCE_SELECTOR: Field = comptime { FunctionSelector::from_signature("_increase_public_balance((Field),u128)").to_field() }; global CHECK_BALANCE_SELECTOR: Field = comptime { FunctionSelector::from_signature("check_balance(u128)").to_field() }; global BALANCE_OF_PUBLIC_SELECTOR: Field = comptime { FunctionSelector::from_signature("balance_of_public((Field))").to_field() }; /// A helper implementing the core L1-to-L2 message claim logic shared by `claim` and `claim_and_end_setup`. /// Computes the expected content hash, consumes the L1-to-L2 message (emitting a nullifier to prevent /// double-claiming), and enqueues a public call to `_increase_public_balance` to credit the recipient. #[contract_library_method] fn claim_helper( context: &mut aztec::context::PrivateContext, to: AztecAddress, amount: u128, secret: Field, message_leaf_index: Field, ) { let content_hash: Field = get_bridge_gas_msg_hash(to, amount); // The Inbox changes the sender's address to `FEE_JUICE_ADDRESS` if it's from the FeeJuicePortal. // This avoids the need to store the L1 address on L2 and prevents friction if the address changes. let portal_address: EthAddress = EthAddress::from_field(FEE_JUICE_ADDRESS.to_field()); assert(!portal_address.is_zero()); // Consume the L1-to-L2 message (verifies existence + emits nullifier to prevent replay). context.consume_l1_to_l2_message(content_hash, secret, portal_address, message_leaf_index); // Enqueue a public call to _increase_public_balance to credit the recipient. let serialized_params: [Field; 2] = [to.to_field(), amount.to_field()]; let calldata: [Field; 1 + 2] = [INCREASE_PUBLIC_BALANCE_SELECTOR].concat(serialized_params); let calldata_hash: Field = aztec::hash::hash_calldata_array(calldata); aztec::oracle::execution_cache::store(calldata, calldata_hash); context.call_public_function_with_calldata_hash(context.this_address(), calldata_hash, false, false); } /// Claims Fee Juice by consuming an L1-to-L2 message from the FeeJuicePortal. /// /// Use this variant when the claimed Fee Juice is NOT intended to pay for the current transaction's fees (e.g., /// pre-funding an account for future transactions). #[aztec::macros::internals_functions_generation::abi_attributes::abi_private] fn claim( inputs: aztec::context::inputs::PrivateContextInputs, to: AztecAddress, amount: u128, secret: Field, message_leaf_index: Field, ) -> return_data aztec::protocol::abis::private_circuit_public_inputs::PrivateCircuitPublicInputs { // MACRO CODE START // Note: The macros initially inserted a phase check here, but since there is no phase change in this function // nor in the claim helper function or the enqueued public function call, I have removed that check. aztec::oracle::version::assert_compatible_oracle_version(); let serialized_params: [Field; 4] = [to.to_field(), amount.to_field(), secret, message_leaf_index]; let args_hash: Field = aztec::hash::hash_args(serialized_params); let mut context: aztec::context::PrivateContext = aztec::context::PrivateContext::new(inputs, args_hash); // MACRO CODE END claim_helper(&mut context, to, amount, secret, message_leaf_index); // MACRO CODE START context.finish() // MACRO CODE END } /// Claims Fee Juice and ends the transaction setup phase. /// /// Use this variant when the claimed Fee Juice is intended to pay for THIS transaction's fees. By ending setup /// after the claim, the balance increase is placed in the non-revertible phase, ensuring the fee payer's balance /// is credited even if the revertible portion of the transaction fails. This guarantees the sequencer can collect /// fees. #[aztec::macros::internals_functions_generation::abi_attributes::abi_private] fn claim_and_end_setup( inputs: aztec::context::inputs::PrivateContextInputs, to: AztecAddress, amount: u128, secret: Field, message_leaf_index: Field, ) -> return_data aztec::protocol::abis::private_circuit_public_inputs::PrivateCircuitPublicInputs { // MACRO CODE START aztec::oracle::version::assert_compatible_oracle_version(); let serialized_params: [Field; 4] = [to.to_field(), amount.to_field(), secret, message_leaf_index]; let args_hash: Field = aztec::hash::hash_args(serialized_params); let mut context: aztec::context::PrivateContext = aztec::context::PrivateContext::new(inputs, args_hash); // MACRO CODE END claim_helper(&mut context, to, amount, secret, message_leaf_index); // MACRO CODE START // End setup: everything before this point (including the enqueued _increase_public_balance // call) is non-revertible. Everything after is revertible. context.end_setup(); context.finish() // MACRO CODE END } /// Internal function that credits a recipient's Fee Juice balance. Only callable by this contract itself /// (`#[only_self]`), enqueued by `claim` / `claim_and_end_setup` after consuming an L1-to-L2 message. #[aztec::macros::internals_functions_generation::abi_attributes::abi_public] #[aztec::macros::internals_functions_generation::abi_attributes::abi_only_self] unconstrained fn _increase_public_balance(to: AztecAddress, amount: u128) { // MACRO CODE START let context: aztec::context::PublicContext = aztec::context::PublicContext::new( || -> Field { let serialized_args: [Field; 2] = aztec::oracle::avm::calldata_copy( 1, <AztecAddress as aztec::protocol::traits::Serialize>::N + <u128 as aztec::protocol::traits::Serialize>::N, ); aztec::hash::hash_args(serialized_args) }, ); let storage: Storage<aztec::context::PublicContext> = Storage::<aztec::context::PublicContext>::init(context); assert( context.maybe_msg_sender().unwrap() == context.this_address(), "Function _increase_public_balance can only be called by the same contract", ); // MACRO CODE END let new_balance = storage.balances.at(to).read().add(amount); storage.balances.at(to).write(new_balance); } /// Asserts the caller has at least `fee_limit` Fee Juice. Used during transaction validation to verify the fee /// payer can cover the transaction's fee limit. #[aztec::macros::internals_functions_generation::abi_attributes::abi_public] #[aztec::macros::internals_functions_generation::abi_attributes::abi_view] unconstrained fn check_balance(fee_limit: u128) { // MACRO CODE START let context: aztec::context::PublicContext = aztec::context::PublicContext::new( || -> Field { let serialized_args: [Field; 1] = aztec::oracle::avm::calldata_copy(1, <u128 as aztec::protocol::traits::Serialize>::N); aztec::hash::hash_args(serialized_args) }, ); let storage: Storage<aztec::context::PublicContext> = Storage::<aztec::context::PublicContext>::init(context); assert(context.is_static_call(), "Function check_balance can only be called statically"); // MACRO CODE END assert(storage.balances.at(context.maybe_msg_sender().unwrap()).read() >= fee_limit, "Balance too low"); } /// Returns the Fee Juice balance of the given address. #[aztec::macros::internals_functions_generation::abi_attributes::abi_public] #[aztec::macros::internals_functions_generation::abi_attributes::abi_view] unconstrained fn balance_of_public(owner: AztecAddress) -> pub u128 { // MACRO CODE START let context: aztec::context::PublicContext = aztec::context::PublicContext::new( || -> Field { let serialized_args: [Field; 1] = aztec::oracle::avm::calldata_copy(1, <AztecAddress as aztec::protocol::traits::Serialize>::N); aztec::hash::hash_args(serialized_args) }, ); let storage: Storage<aztec::context::PublicContext> = Storage::<aztec::context::PublicContext>::init(context); assert(context.is_static_call(), "Function balance_of_public can only be called statically"); // MACRO CODE END storage.balances.at(owner).read() } // THE REST OF THE CODE IN THIS CONTRACT WAS ORIGINALLY INJECTED BY THE #[aztec] MACRO. #[aztec::macros::internals_functions_generation::abi_attributes::abi_public] pub unconstrained fn public_dispatch(selector: Field) { if selector == INCREASE_PUBLIC_BALANCE_SELECTOR { let input_calldata: [Field; 2] = aztec::oracle::avm::calldata_copy( 1, <AztecAddress as aztec::protocol::traits::Serialize>::N + <u128 as aztec::protocol::traits::Serialize>::N, ); let mut reader: aztec::protocol::utils::reader::Reader<2> = aztec::protocol::utils::reader::Reader::<2>::new(input_calldata); let arg0: AztecAddress = <AztecAddress as Deserialize>::stream_deserialize(&mut reader); let arg1: u128 = <u128 as Deserialize>::stream_deserialize(&mut reader); _increase_public_balance(arg0, arg1); aztec::oracle::avm::avm_return([].as_vector()); }; if selector == CHECK_BALANCE_SELECTOR { let input_calldata: [Field; 1] = aztec::oracle::avm::calldata_copy(1, <u128 as aztec::protocol::traits::Serialize>::N); let mut reader: aztec::protocol::utils::reader::Reader<1> = aztec::protocol::utils::reader::Reader::<1>::new(input_calldata); let arg0: u128 = <u128 as Deserialize>::stream_deserialize(&mut reader); check_balance(arg0); aztec::oracle::avm::avm_return([].as_vector()); }; if selector == BALANCE_OF_PUBLIC_SELECTOR { let input_calldata: [Field; 1] = aztec::oracle::avm::calldata_copy(1, <AztecAddress as aztec::protocol::traits::Serialize>::N); let mut reader: aztec::protocol::utils::reader::Reader<1> = aztec::protocol::utils::reader::Reader::<1>::new(input_calldata); let arg0: AztecAddress = <AztecAddress as Deserialize>::stream_deserialize(&mut reader); let return_value: [Field; 1] = <u128 as aztec::protocol::traits::Serialize>::serialize(balance_of_public(arg0)); aztec::oracle::avm::avm_return(return_value.as_vector()); }; panic(f"Unknown selector {selector}") } pub struct StorageLayoutFields { pub balances: aztec::state_vars::Storable, } pub struct StorageLayout<let N: u32> { pub contract_name: str<N>, pub fields: StorageLayoutFields, } #[abi(storage)] pub global STORAGE_LAYOUT_FeeJuice: StorageLayout<8> = StorageLayout::<8> { contract_name: "FeeJuice", fields: StorageLayoutFields { balances: aztec::state_vars::Storable { slot: 1 } }, }; impl<Context> Storage<Context> { fn init(context: Context) -> Self { Self { balances: <Map<AztecAddress, PublicMutable<u128, Context>, Context> as aztec::state_vars::StateVariable<1, Context>>::new( context, 1, ), } } } pub struct _increase_public_balance_parameters { pub _to: AztecAddress, pub _amount: u128, } pub struct balance_of_public_parameters { pub _owner: AztecAddress, } pub struct check_balance_parameters { pub _fee_limit: u128, } pub struct claim_and_end_setup_parameters { pub _to: AztecAddress, pub _amount: u128, pub _secret: Field, pub _message_leaf_index: Field, } pub struct claim_parameters { pub _to: AztecAddress, pub _amount: u128, pub _secret: Field, pub _message_leaf_index: Field, } #[abi(functions)] pub struct _increase_public_balance_abi { parameters: _increase_public_balance_parameters, } #[abi(functions)] pub struct balance_of_public_abi { parameters: balance_of_public_parameters, return_type: u128, } #[abi(functions)] pub struct check_balance_abi { parameters: check_balance_parameters, } #[abi(functions)] pub struct claim_abi { parameters: claim_parameters, } #[abi(functions)] pub struct claim_and_end_setup_abi { parameters: claim_and_end_setup_parameters, }}pub struct Reader<let N: u32> { data: [Field; N], offset: u32,}impl<let N: u32> Reader<N> { pub fn new(data: [Field; N]) -> Self { Self { data, offset: 0 } } pub fn read(&mut self) -> Field { let result = self.data[self.offset]; self.offset += 1; result } pub fn read_u32(&mut self) -> u32 { self.read() as u32 } pub fn read_u64(&mut self) -> u64 { self.read() as u64 } pub fn read_bool(&mut self) -> bool { self.read() != 0 } pub fn read_array<let K: u32>(&mut self) -> [Field; K] { let mut result = [0; K]; for i in 0..K { result[i] = self.data[self.offset + i]; } self.offset += K; result } pub fn read_struct<T, let K: u32>(&mut self, deserialise: fn([Field; K]) -> T) -> T { let result = deserialise(self.read_array()); result } pub fn read_struct_array<T, let K: u32, let C: u32>( &mut self, deserialise: fn([Field; K]) -> T, mut result: [T; C], ) -> [T; C] { for i in 0..C { result[i] = self.read_struct(deserialise); } result } pub fn peek_offset(&mut self, offset: u32) -> Field { self.data[self.offset + offset] } pub fn advance_offset(&mut self, offset: u32) { self.offset += offset; } pub fn finish(self) { assert_eq(self.offset, self.data.len(), "Reader did not read all data"); }}use crate::{reader::Reader, writer::Writer};/// Trait for serializing Noir types into arrays of Fields.////// An implementation of the Serialize trait has to follow Noir's intrinsic serialization (each member of a struct/// converted directly into one or more Fields without any packing or compression). This trait (and Deserialize) are/// typically used to communicate between Noir and TypeScript (via oracles and function arguments).////// # On Following Noir's Intrinsic Serialization/// When calling a Noir function from TypeScript (TS), first the function arguments are serialized into an array/// of fields. This array is then included in the initial witness. Noir's intrinsic serialization is then used/// to deserialize the arguments from the witness. When the same Noir function is called from Noir this Serialize trait/// is used instead of the serialization in TS. For this reason we need to have a match between TS serialization,/// Noir's intrinsic serialization and the implementation of this trait. If there is a mismatch, the function calls/// fail with an arguments hash mismatch error message.////// # Associated Constants/// * `N` - The length of the output Field array, known at compile time////// # Example/// ```/// impl<let N: u32> Serialize for str<N> {/// let N: u32 = N;////// fn serialize(self) -> [Field; Self::N] {/// let mut writer: Writer<Self::N> = Writer::new();/// self.stream_serialize(&mut writer);/// writer.finish()/// }////// fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {/// let bytes = self.as_bytes();/// for i in 0..bytes.len() {/// writer.write(bytes[i] as Field);/// }/// }/// }/// ```#[derive_via(derive_serialize)]pub trait Serialize { let N: u32; fn serialize(self) -> [Field; Self::N]; fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>);}/// Generates a `Serialize` trait implementation for a struct type.////// # Parameters/// - `s`: The struct type definition to generate the implementation for////// # Returns/// A quoted code block containing the trait implementation////// # Example/// For a struct defined as:/// ```/// struct Log<N> {/// fields: [Field; N],/// length: u32/// }/// ```////// This function generates code equivalent to:/// ```/// impl<let N: u32> Serialize for Log<N> {/// let N: u32 = <[Field; N] as Serialize>::N + <u32 as Serialize>::N;////// fn serialize(self) -> [Field; Self::N] {/// let mut writer: Writer<Self::N> = Writer::new();/// self.stream_serialize(&mut writer);/// writer.finish()/// }////// #[inline_always]/// fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) {/// Serialize::stream_serialize(self.fields, writer);/// Serialize::stream_serialize(self.length, writer);/// }/// }/// ```pub comptime fn derive_serialize(s: TypeDefinition) -> Quoted { let typ = s.as_type(); let nested_struct = typ.as_data_type().unwrap(); // We care only about the name and type so we drop the last item of the tuple let params = nested_struct.0.fields(nested_struct.1).map(|(name, typ, _)| (name, typ)); // Generates the generic parameter declarations (to be placed after the `impl` keyword) and the `where` clause // for the `Serialize` trait. let generics_declarations = get_generics_declarations(s); let where_serialize_clause = get_where_trait_clause(s, quote { Serialize }); let params_len_quote = get_params_len_quote(params); let function_body = params .map(|(name, _typ): (Quoted, Type)| { quote { $crate::serialization::Serialize::stream_serialize(self.$name, writer); } }) .join(quote {}); quote { impl$generics_declarations $crate::serialization::Serialize for $typ $where_serialize_clause { let N: u32 = $params_len_quote; fn serialize(self) -> [Field; Self::N] { let mut writer: $crate::writer::Writer<Self::N> = $crate::writer::Writer::new(); $crate::serialization::Serialize::stream_serialize(self, &mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut $crate::writer::Writer<K>) { $function_body } } }}/// Trait for deserializing Noir types from arrays of Fields.////// An implementation of the Deserialize trait has to follow Noir's intrinsic serialization (each member of a struct/// converted directly into one or more Fields without any packing or compression). This trait is typically used when/// deserializing return values from function calls in Noir. Since the same function could be called from TypeScript/// (TS), in which case the TS deserialization would get used, we need to have a match between the 2.////// # Associated Constants/// * `N` - The length of the input Field array, known at compile time////// # Example/// ```/// impl<let M: u32> Deserialize for str<M> {/// let N: u32 = M;////// fn deserialize(fields: [Field; Self::N]) -> Self {/// let mut reader = Reader::new(fields);/// let result = Self::stream_deserialize(&mut reader);/// reader.finish();/// result/// }////// fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {/// let mut bytes = [0 as u8; M];/// for i in 0..M {/// bytes[i] = reader.read() as u8;/// }/// str::<M>::from(bytes)/// }/// }/// ```#[derive_via(derive_deserialize)]pub trait Deserialize { let N: u32; fn deserialize(fields: [Field; Self::N]) -> Self; fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self;}/// Generates a `Deserialize` trait implementation for a given struct `s`.////// # Arguments/// * `s` - The struct type definition to generate the implementation for////// # Returns/// A `Quoted` block containing the generated trait implementation////// # Requirements/// Each struct member type must implement the `Deserialize` trait (it gets used in the generated code).////// # Example/// For a struct like:/// ```/// struct MyStruct {/// x: AztecAddress,/// y: Field,/// }/// ```////// This generates:/// ```/// impl Deserialize for MyStruct {/// let N: u32 = <AztecAddress as Deserialize>::N + <Field as Deserialize>::N;////// fn deserialize(fields: [Field; Self::N]) -> Self {/// let mut reader = Reader::new(fields);/// let result = Self::stream_deserialize(&mut reader);/// reader.finish();/// result/// }////// #[inline_always]/// fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self {/// let x = <AztecAddress as Deserialize>::stream_deserialize(reader);/// let y = <Field as Deserialize>::stream_deserialize(reader);/// Self { x, y }/// }/// }/// ```pub comptime fn derive_deserialize(s: TypeDefinition) -> Quoted { let typ = s.as_type(); let nested_struct = typ.as_data_type().unwrap(); let params = nested_struct.0.fields(nested_struct.1); // Generates the generic parameter declarations (to be placed after the `impl` keyword) and the `where` clause // for the `Deserialize` trait. let generics_declarations = get_generics_declarations(s); let where_deserialize_clause = get_where_trait_clause(s, quote { Deserialize }); // The following will give us: // <type_of_struct_member_1 as Deserialize>::N + <type_of_struct_member_2 as Deserialize>::N + ... // (or 0 if the struct has no members) let right_hand_side_of_definition_of_n = if params.len() > 0 { params .map(|(_, param_type, _): (Quoted, Type, Quoted)| { quote { <$param_type as $crate::serialization::Deserialize>::N } }) .join(quote {+}) } else { quote { 0 } }; // For structs containing a single member, we can enhance performance by directly deserializing the input array, // bypassing the need for loop-based array construction. While this optimization yields significant benefits in // Brillig where the loops are expected to not be optimized, it is not relevant in ACIR where the loops are // expected to be optimized away. let function_body = if params.len() > 1 { // This generates deserialization code for each struct member and concatenates them together. let deserialization_of_struct_members = params .map(|(param_name, param_type, _): (Quoted, Type, Quoted)| { quote { let $param_name = <$param_type as Deserialize>::stream_deserialize(reader); } }) .join(quote {}); // We join the struct member names with a comma to be used in the `Self { ... }` syntax // This will give us e.g. `a, b, c` for a struct with three fields named `a`, `b`, and `c`. let struct_members = params .map(|(param_name, _, _): (Quoted, Type, Quoted)| quote { $param_name }) .join(quote {,}); quote { $deserialization_of_struct_members Self { $struct_members } } } else if params.len() == 1 { let param_name = params[0].0; quote { Self { $param_name: $crate::serialization::Deserialize::stream_deserialize(reader) } } } else { quote { Self {} } }; quote { impl$generics_declarations $crate::serialization::Deserialize for $typ $where_deserialize_clause { let N: u32 = $right_hand_side_of_definition_of_n; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = $crate::reader::Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut $crate::reader::Reader<K>) -> Self { $function_body } } }}/// Generates a quoted expression that computes the total serialized length of function parameters.////// # Parameters/// * `params` - An array of tuples where each tuple contains a quoted parameter name and its Type. The type needs/// to implement the Serialize trait.////// # Returns/// A quoted expression that evaluates to:/// * `0` if there are no parameters/// * `(<type1 as Serialize>::N + <type2 as Serialize>::N + ...)` for one or more parameterscomptime fn get_params_len_quote(params: [(Quoted, Type)]) -> Quoted { if params.len() == 0 { quote { 0 } } else { let params_quote_without_parentheses = params .map(|(_, param_type): (Quoted, Type)| { quote { <$param_type as $crate::serialization::Serialize>::N } }) .join(quote {+}); quote { ($params_quote_without_parentheses) } }}comptime fn get_generics_declarations(s: TypeDefinition) -> Quoted { let generics = s.generics(); if generics.len() > 0 { let generics_declarations_items = generics .map(|(name, maybe_integer_typ)| { // The second item in the generics tuple is an Option of an integer type that is Some only if // the generic is numeric. if maybe_integer_typ.is_some() { // The generic is numeric, so we return a quote defined as e.g. "let N: u32" let integer_type = maybe_integer_typ.unwrap(); quote {let $name: $integer_type} } else { // The generic is not numeric, so we return a quote containing the name of the generic (e.g. "T") quote { $name } } }) .join(quote {,}); quote {<$generics_declarations_items>} } else { // The struct doesn't have any generics defined, so we just return an empty quote. quote {} }}comptime fn get_where_trait_clause(s: TypeDefinition, trait_name: Quoted) -> Quoted { let generics = s.generics(); // The second item in the generics tuple is an Option of an integer type that is Some only if the generic is // numeric. let non_numeric_generics = generics.filter(|(_, maybe_integer_typ)| maybe_integer_typ.is_none()); if non_numeric_generics.len() > 0 { let non_numeric_generics_declarations = non_numeric_generics.map(|(name, _)| quote {$name: $trait_name}).join(quote {,}); quote {where $non_numeric_generics_declarations} } else { // There are no non-numeric generics, so we return an empty quote. quote {} }}use crate::{reader::Reader, serialization::{Deserialize, Serialize}, writer::Writer};use std::embedded_curve_ops::EmbeddedCurvePoint;use std::embedded_curve_ops::EmbeddedCurveScalar;global BOOL_SERIALIZED_LEN: u32 = 1;global U8_SERIALIZED_LEN: u32 = 1;global U16_SERIALIZED_LEN: u32 = 1;global U32_SERIALIZED_LEN: u32 = 1;global U64_SERIALIZED_LEN: u32 = 1;global U128_SERIALIZED_LEN: u32 = 1;global FIELD_SERIALIZED_LEN: u32 = 1;global I8_SERIALIZED_LEN: u32 = 1;global I16_SERIALIZED_LEN: u32 = 1;global I32_SERIALIZED_LEN: u32 = 1;global I64_SERIALIZED_LEN: u32 = 1;impl Serialize for bool { let N: u32 = BOOL_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as Field); }}impl Deserialize for bool { let N: u32 = BOOL_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> bool { reader.read() != 0 }}impl Serialize for u8 { let N: u32 = U8_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as Field); }}impl Deserialize for u8 { let N: u32 = U8_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u8 }}impl Serialize for u16 { let N: u32 = U16_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as Field); }}impl Deserialize for u16 { let N: u32 = U16_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u16 }}impl Serialize for u32 { let N: u32 = U32_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as Field); }}impl Deserialize for u32 { let N: u32 = U32_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u32 }}impl Serialize for u64 { let N: u32 = U64_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as Field); }}impl Deserialize for u64 { let N: u32 = U64_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u64 }}impl Serialize for u128 { let N: u32 = U128_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as Field); }}impl Deserialize for u128 { let N: u32 = U128_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u128 }}impl Serialize for Field { let N: u32 = FIELD_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self); }}impl Deserialize for Field { let N: u32 = FIELD_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() }}impl Serialize for i8 { let N: u32 = I8_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as u8 as Field); }}impl Deserialize for i8 { let N: u32 = I8_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u8 as i8 }}impl Serialize for i16 { let N: u32 = I16_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as u16 as Field); }}impl Deserialize for i16 { let N: u32 = I16_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u16 as i16 }}impl Serialize for i32 { let N: u32 = I32_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as u32 as Field); }}impl Deserialize for i32 { let N: u32 = I32_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u32 as i32 }}impl Serialize for i64 { let N: u32 = I64_SERIALIZED_LEN; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self as u64 as Field); }}impl Deserialize for i64 { let N: u32 = I64_SERIALIZED_LEN; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { reader.read() as u64 as i64 }}impl<T, let M: u32> Serialize for [T; M]where T: Serialize,{ let N: u32 = <T as Serialize>::N * M; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { for i in 0..M { self[i].stream_serialize(writer); } }}impl<T, let M: u32> Deserialize for [T; M]where T: Deserialize,{ let N: u32 = <T as Deserialize>::N * M; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { let mut result: [T; M] = std::mem::zeroed(); for i in 0..M { result[i] = T::stream_deserialize(reader); } result }}impl<T> Serialize for Option<T>where T: Serialize,{ let N: u32 = <T as Serialize>::N + 1; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write_bool(self.is_some()); if self.is_some() { self.unwrap_unchecked().stream_serialize(writer); } else { writer.advance_offset(<T as Serialize>::N); } }}impl<T> Deserialize for Option<T>where T: Deserialize,{ let N: u32 = <T as Deserialize>::N + 1; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { if reader.read_bool() { Option::some(<T as Deserialize>::stream_deserialize(reader)) } else { reader.advance_offset(<T as Deserialize>::N); Option::none() } }}global SCALAR_SIZE: u32 = 2;impl Serialize for EmbeddedCurveScalar { let N: u32 = SCALAR_SIZE; fn serialize(self) -> [Field; SCALAR_SIZE] { [self.lo, self.hi] } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self.lo); writer.write(self.hi); }}impl Deserialize for EmbeddedCurveScalar { let N: u32 = SCALAR_SIZE; fn deserialize(fields: [Field; Self::N]) -> Self { Self { lo: fields[0], hi: fields[1] } } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { Self { lo: reader.read(), hi: reader.read() } }}global POINT_SIZE: u32 = 2;impl Serialize for EmbeddedCurvePoint { let N: u32 = POINT_SIZE; fn serialize(self) -> [Field; Self::N] { [self.x, self.y] } fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { writer.write(self.x); writer.write(self.y); }}impl Deserialize for EmbeddedCurvePoint { let N: u32 = POINT_SIZE; fn deserialize(fields: [Field; Self::N]) -> Self { Self { x: fields[0], y: fields[1] } } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { Self { x: reader.read(), y: reader.read() } }}impl<let M: u32> Deserialize for str<M> { let N: u32 = M; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { let u8_arr = <[u8; Self::N] as Deserialize>::stream_deserialize(reader); str::<Self::N>::from(u8_arr) }}impl<let M: u32> Serialize for str<M> { let N: u32 = M; fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { self.as_bytes().stream_serialize(writer); }}// Note: Not deriving this because it's not supported to call derive_serialize on a "remote" struct (and it will never// be supported).impl<T, let M: u32> Deserialize for BoundedVec<T, M>where T: Deserialize,{ let N: u32 = <T as Deserialize>::N * M + 1; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { let mut new_bounded_vec: BoundedVec<T, M> = BoundedVec::new(); let payload_len = Self::N - 1; // Length is stored in the last field as we need to match intrinsic Noir serialization and the `len` struct // field is after `storage` struct field (see `bounded_vec.nr` in noir-stdlib) let len = reader.peek_offset(payload_len) as u32; for i in 0..M { if i < len { new_bounded_vec.push(<T as Deserialize>::stream_deserialize(reader)); } } // +1 for the length of the BoundedVec reader.advance_offset((M - len) * <T as Deserialize>::N + 1); new_bounded_vec }}// This may cause issues if used as program input, because noir disallows empty arrays for program input.// I think this is okay because I don't foresee a unit type being used as input. But leaving this comment as a hint// if someone does run into this in the future.impl Deserialize for () { let N: u32 = 0; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(_reader: &mut Reader<K>) -> Self { () }}// Note: Not deriving this because it's not supported to call derive_serialize on a "remote" struct (and it will never// be supported).impl<T, let M: u32> Serialize for BoundedVec<T, M>where T: Serialize,{ let N: u32 = <T as Serialize>::N * M + 1; // +1 for the length of the BoundedVec fn serialize(self) -> [Field; Self::N] { let mut writer: Writer<Self::N> = Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { self.storage().stream_serialize(writer); // Length is stored in the last field as we need to match intrinsic Noir serialization and the `len` struct // field is after `storage` struct field (see `bounded_vec.nr` in noir-stdlib) writer.write_u32(self.len() as u32); }}// Create a slice of the given length with each element made from `f(i)` where `i` is the current indexcomptime fn make_slice<Env, T>(length: u32, f: fn[Env](u32) -> T) -> [T] { let mut slice = @[]; for i in 0..length { slice = slice.push_back(f(i)); } slice}// Implements Serialize and Deserialize for an arbitrary tuple typecomptime fn impl_serialize_for_tuple(_m: Module, length: u32) -> Quoted { // `T0`, `T1`, `T2` let type_names = make_slice(length, |i| f"T{i}".quoted_contents()); // `result0`, `result1`, `result2` let result_names = make_slice(length, |i| f"result{i}".quoted_contents()); // `T0, T1, T2` let field_generics = type_names.join(quote [,]); // `<T0 as Serialize>::N + <T1 as Serialize>::N + <T2 as Serialize>::N` let full_size_serialize = type_names .map(|type_name| quote { <$type_name as Serialize>::N }) .join(quote [+]); // `<T0 as Deserialize>::N + <T1 as Deserialize>::N + <T2 as Deserialize>::N` let full_size_deserialize = type_names .map(|type_name| quote { <$type_name as Deserialize>::N }) .join(quote [+]); // `T0: Serialize, T1: Serialize, T2: Serialize,` let serialize_constraints = type_names .map(|field_name| quote { $field_name: Serialize, }) .join(quote []); // `T0: Deserialize, T1: Deserialize, T2: Deserialize,` let deserialize_constraints = type_names .map(|field_name| quote { $field_name: Deserialize, }) .join(quote []); // Statements to serialize each field let serialized_fields = type_names .mapi(|i, _type_name| quote { $crate::serialization::Serialize::stream_serialize(self.$i, writer); }) .join(quote []); // Statements to deserialize each field let deserialized_fields = type_names .mapi(|i, type_name| { let result_name = result_names[i]; quote { let $result_name = <$type_name as $crate::serialization::Deserialize>::stream_deserialize(reader); } }) .join(quote []); let deserialize_results = result_names.join(quote [,]); quote { impl<$field_generics> Serialize for ($field_generics) where $serialize_constraints { let N: u32 = $full_size_serialize; fn serialize(self) -> [Field; Self::N] { let mut writer: $crate::writer::Writer<Self::N> = $crate::writer::Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut $crate::writer::Writer<K>) { $serialized_fields } } impl<$field_generics> Deserialize for ($field_generics) where $deserialize_constraints { let N: u32 = $full_size_deserialize; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = $crate::reader::Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut $crate::reader::Reader<K>) -> Self { $deserialized_fields ($deserialize_results) } } }}// Keeping these manual impls. They are more efficient since they do not// require copying sub-arrays from any serialized arrays.impl<T1> Serialize for (T1,)where T1: Serialize,{ let N: u32 = <T1 as Serialize>::N; fn serialize(self) -> [Field; Self::N] { let mut writer: crate::writer::Writer<Self::N> = crate::writer::Writer::new(); self.stream_serialize(&mut writer); writer.finish() } #[inline_always] fn stream_serialize<let K: u32>(self, writer: &mut Writer<K>) { self.0.stream_serialize(writer); }}impl<T1> Deserialize for (T1,)where T1: Deserialize,{ let N: u32 = <T1 as Deserialize>::N; fn deserialize(fields: [Field; Self::N]) -> Self { let mut reader = crate::reader::Reader::new(fields); let result = Self::stream_deserialize(&mut reader); reader.finish(); result } #[inline_always] fn stream_deserialize<let K: u32>(reader: &mut Reader<K>) -> Self { (<T1 as Deserialize>::stream_deserialize(reader),) }}#[impl_serialize_for_tuple(2)]#[impl_serialize_for_tuple(3)]#[impl_serialize_for_tuple(4)]#[impl_serialize_for_tuple(5)]#[impl_serialize_for_tuple(6)]mod impls { use crate::serialization::{Deserialize, Serialize};}#[test]unconstrained fn bounded_vec_serialization() { // Test empty BoundedVec let empty_vec: BoundedVec<Field, 3> = BoundedVec::from_array([]); let serialized = empty_vec.serialize(); let deserialized = BoundedVec::<Field, 3>::deserialize(serialized); assert_eq(empty_vec, deserialized); assert_eq(deserialized.len(), 0); // Test partially filled BoundedVec let partial_vec: BoundedVec<[u32; 2], 3> = BoundedVec::from_array([[1, 2]]); let serialized = partial_vec.serialize(); let deserialized = BoundedVec::<[u32; 2], 3>::deserialize(serialized); assert_eq(partial_vec, deserialized); assert_eq(deserialized.len(), 1); assert_eq(deserialized.get(0), [1, 2]); // Test full BoundedVec let full_vec: BoundedVec<[u32; 2], 3> = BoundedVec::from_array([[1, 2], [3, 4], [5, 6]]); let serialized = full_vec.serialize(); let deserialized = BoundedVec::<[u32; 2], 3>::deserialize(serialized); assert_eq(full_vec, deserialized); assert_eq(deserialized.len(), 3); assert_eq(deserialized.get(0), [1, 2]); assert_eq(deserialized.get(1), [3, 4]); assert_eq(deserialized.get(2), [5, 6]);}mod poseidon2_chunks;use crate::{ abis::{ contract_class_function_leaf_preimage::ContractClassFunctionLeafPreimage, function_selector::FunctionSelector, nullifier::Nullifier, private_log::PrivateLog, transaction::tx_request::TxRequest, }, address::{AztecAddress, EthAddress}, constants::{ CONTRACT_CLASS_LOG_SIZE_IN_FIELDS, DOM_SEP__NOTE_HASH_NONCE, DOM_SEP__PRIVATE_LOG_FIRST_FIELD, DOM_SEP__SILOED_NOTE_HASH, DOM_SEP__SILOED_NULLIFIER, DOM_SEP__UNIQUE_NOTE_HASH, FUNCTION_TREE_HEIGHT, NULL_MSG_SENDER_CONTRACT_ADDRESS, TWO_POW_64, }, merkle_tree::root_from_sibling_path, messaging::l2_to_l1_message::L2ToL1Message, poseidon2::Poseidon2Sponge, side_effect::{Counted, Scoped}, traits::{FromField, Hash, ToField}, utils::field::{field_from_bytes, field_from_bytes_32_trunc},};pub use poseidon2_chunks::poseidon2_absorb_in_chunks_existing_sponge;use poseidon2_chunks::poseidon2_absorb_in_chunks;use std::embedded_curve_ops::EmbeddedCurveScalar;// TODO: refactor these into their own files: sha256, poseidon2, some protocol-specific hash computations, some merkle computations.pub fn sha256_to_field<let N: u32>(bytes_to_hash: [u8; N]) -> Field { let sha256_hashed = sha256::digest(bytes_to_hash); let hash_in_a_field = field_from_bytes_32_trunc(sha256_hashed); hash_in_a_field}pub fn private_functions_root_from_siblings( selector: FunctionSelector, vk_hash: Field, function_leaf_index: Field, function_leaf_sibling_path: [Field; FUNCTION_TREE_HEIGHT],) -> Field { let function_leaf_preimage = ContractClassFunctionLeafPreimage { selector, vk_hash }; let function_leaf = function_leaf_preimage.hash(); root_from_sibling_path( function_leaf, function_leaf_index, function_leaf_sibling_path, )}/// Siloing in the context of Aztec refers to the process of hashing a note hash with a contract address (this way/// the note hash is scoped to a specific contract). This is used to prevent intermingling of notes between contracts.pub fn compute_siloed_note_hash(contract_address: AztecAddress, note_hash: Field) -> Field { poseidon2_hash_with_separator( [contract_address.to_field(), note_hash], DOM_SEP__SILOED_NOTE_HASH, )}/// Computes unique, siloed note hashes from siloed note hashes.////// The protocol injects uniqueness into every note_hash, so that every single note_hash in the/// tree is unique. This prevents faerie gold attacks, where a malicious sender could create/// two identical note_hashes for a recipient (meaning only one would be nullifiable in future).////// Most privacy protocols will inject the note's leaf_index (its position in the Note Hashes Tree)/// into the note, but this requires the creator of a note to wait until their tx is included in/// a block to know the note's final note hash (the unique, siloed note hash), because inserting/// leaves into trees is the job of a block producer.////// We took a different approach so that the creator of a note will know each note's unique, siloed/// note hash before broadcasting their tx to the network./// (There was also a historical requirement relating to "chained transactions" -- a feature that/// Aztec Connect had to enable notes to be spent from distinct txs earlier in the same block,/// and hence before an archive block root had been established for that block -- but that feature/// was abandoned for the Aztec Network for having too many bad tradeoffs).////// (/// Edit: it is no longer true that all final note_hashes will be known by the creator of a tx/// before they send it to the network. If a tx makes public function calls, then _revertible_/// note_hashes that are created in private will not be made unique in private by the Reset circuit,/// but will instead be made unique by the AVM, because the `note_index_in_tx` will not be known/// until the AVM has executed the public functions of the tx. (See an explanation in/// reset_output_composer.nr for why)./// For some such txs, the `note_index_in_tx` might still be predictable through simulation, but/// for txs whose public functions create a varying number of non-revertible notes (determined at/// runtime), the `note_index_in_tx` will not be deterministically derivable before submitting the/// tx to the network./// )////// We use the `first_nullifier` of a tx as a seed of uniqueness. We have a guarantee that there will/// always be at least one nullifier per tx, because the init circuit will create one if one isn't/// created naturally by any functions of the tx. (Search "protocol_nullifier")./// We combine the `first_nullifier` with the note's index (its position within this tx's new/// note_hashes array) (`note_index_in_tx`) to get a truly unique value to inject into a note, which/// we call a `note_nonce`.pub fn compute_unique_note_hash(note_nonce: Field, siloed_note_hash: Field) -> Field { let inputs = [note_nonce, siloed_note_hash]; poseidon2_hash_with_separator(inputs, DOM_SEP__UNIQUE_NOTE_HASH)}pub fn compute_note_hash_nonce(first_nullifier_in_tx: Field, note_index_in_tx: u32) -> Field { // Hashing the first nullifier with note index in tx is guaranteed to be unique (because all nullifiers are also // unique). poseidon2_hash_with_separator( [first_nullifier_in_tx, note_index_in_tx as Field], DOM_SEP__NOTE_HASH_NONCE, )}pub fn compute_note_nonce_and_unique_note_hash( siloed_note_hash: Field, first_nullifier: Field, note_index_in_tx: u32,) -> Field { let note_nonce = compute_note_hash_nonce(first_nullifier, note_index_in_tx); compute_unique_note_hash(note_nonce, siloed_note_hash)}pub fn compute_siloed_nullifier(contract_address: AztecAddress, nullifier: Field) -> Field { poseidon2_hash_with_separator( [contract_address.to_field(), nullifier], DOM_SEP__SILOED_NULLIFIER, )}pub fn create_protocol_nullifier(tx_request: TxRequest) -> Scoped<Counted<Nullifier>> { // The protocol nullifier is ascribed a special side-effect counter of 1. No other side-effect // can have counter 1 (see `validate_as_first_call` for that assertion). Nullifier { value: tx_request.hash(), note_hash: 0 }.count(1).scope( NULL_MSG_SENDER_CONTRACT_ADDRESS, )}pub fn compute_log_tag(raw_tag: Field, dom_sep: u32) -> Field { poseidon2_hash_with_separator([raw_tag], dom_sep)}pub fn compute_siloed_private_log_first_field( contract_address: AztecAddress, field: Field,) -> Field { poseidon2_hash_with_separator( [contract_address.to_field(), field], DOM_SEP__PRIVATE_LOG_FIRST_FIELD, )}pub fn compute_siloed_private_log(contract_address: AztecAddress, log: PrivateLog) -> PrivateLog { let mut fields = log.fields; fields[0] = compute_siloed_private_log_first_field(contract_address, fields[0]); PrivateLog::new(fields, log.length)}pub fn compute_contract_class_log_hash(log: [Field; CONTRACT_CLASS_LOG_SIZE_IN_FIELDS]) -> Field { poseidon2_hash(log)}pub fn compute_app_siloed_secret_key( master_secret_key: EmbeddedCurveScalar, app_address: AztecAddress, key_type_domain_separator: Field,) -> Field { poseidon2_hash_with_separator( [master_secret_key.hi, master_secret_key.lo, app_address.to_field()], key_type_domain_separator, )}pub fn compute_l2_to_l1_message_hash( message: Scoped<L2ToL1Message>, rollup_version_id: Field, chain_id: Field,) -> Field { let contract_address_bytes: [u8; 32] = message.contract_address.to_field().to_be_bytes(); let recipient_bytes: [u8; 20] = message.inner.recipient.to_be_bytes(); let content_bytes: [u8; 32] = message.inner.content.to_be_bytes(); let rollup_version_id_bytes: [u8; 32] = rollup_version_id.to_be_bytes(); let chain_id_bytes: [u8; 32] = chain_id.to_be_bytes(); let mut bytes: [u8; 148] = std::mem::zeroed(); for i in 0..32 { bytes[i] = contract_address_bytes[i]; bytes[i + 32] = rollup_version_id_bytes[i]; // 64 - 84 are for recipient. bytes[i + 84] = chain_id_bytes[i]; bytes[i + 116] = content_bytes[i]; } for i in 0..20 { bytes[64 + i] = recipient_bytes[i]; } sha256_to_field(bytes)}// TODO: consider a variant that enables domain separation with a u32 (we seem to have standardised u32s for domain separators)/// Computes sha256 hash of 2 input fields.////// @returns A truncated field (i.e., the first byte is always 0).pub fn accumulate_sha256(v0: Field, v1: Field) -> Field { // Concatenate two fields into 32 x 2 = 64 bytes let v0_as_bytes: [u8; 32] = v0.to_be_bytes(); let v1_as_bytes: [u8; 32] = v1.to_be_bytes(); let hash_input_flattened = v0_as_bytes.concat(v1_as_bytes); sha256_to_field(hash_input_flattened)}pub fn poseidon2_hash<let N: u32>(inputs: [Field; N]) -> Field { poseidon::poseidon2::Poseidon2::hash(inputs, N)}#[no_predicates]pub fn poseidon2_hash_with_separator<let N: u32, T>(inputs: [Field; N], separator: T) -> Fieldwhere T: ToField,{ let inputs_with_separator = [separator.to_field()].concat(inputs); poseidon2_hash(inputs_with_separator)}/// Computes a Poseidon2 hash over a dynamic-length subarray of the given input./// Only the first `in_len` fields of `input` are absorbed; any remaining fields are ignored./// The caller is responsible for ensuring that the input is padded with zeros if required.#[no_predicates]pub fn poseidon2_hash_subarray<let N: u32>(input: [Field; N], in_len: u32) -> Field { let mut sponge = poseidon2_absorb_in_chunks(input, in_len); sponge.squeeze()}// This function is unconstrained because it is intended to be used in unconstrained context only as// in constrained contexts it would be too inefficient.pub unconstrained fn poseidon2_hash_with_separator_bounded_vec<let N: u32, T>( inputs: BoundedVec<Field, N>, separator: T,) -> Fieldwhere T: ToField,{ let in_len = inputs.len() + 1; let iv: Field = (in_len as Field) * TWO_POW_64; let mut sponge = Poseidon2Sponge::new(iv); sponge.absorb(separator.to_field()); for i in 0..inputs.len() { sponge.absorb(inputs.get(i)); } sponge.squeeze()}#[no_predicates]pub fn poseidon2_hash_bytes<let N: u32>(inputs: [u8; N]) -> Field { let mut fields = [0; (N + 30) / 31]; let mut field_index = 0; let mut current_field = [0; 31]; for i in 0..inputs.len() { let index = i % 31; current_field[index] = inputs[i]; if index == 30 { fields[field_index] = field_from_bytes(current_field, false); current_field = [0; 31]; field_index += 1; } } if field_index != fields.len() { fields[field_index] = field_from_bytes(current_field, false); } poseidon2_hash(fields)}#[test]fn subarray_hash_matches_fixed() { let values_to_hash = [3; 17]; let padded = values_to_hash.concat([0; 11]); let subarray_hash = poseidon2_hash_subarray(padded, values_to_hash.len()); // Hash the entire values_to_hash. let fixed_len_hash = poseidon::poseidon2::Poseidon2::hash(values_to_hash, values_to_hash.len()); assert_eq(subarray_hash, fixed_len_hash);}#[test]fn subarray_hash_matches_variable() { let values_to_hash = [3; 17]; let padded = values_to_hash.concat([0; 11]); let subarray_hash = poseidon2_hash_subarray(padded, values_to_hash.len()); // Hash up to values_to_hash.len() fields of the padded array. let variable_len_hash = poseidon::poseidon2::Poseidon2::hash(padded, values_to_hash.len()); assert_eq(subarray_hash, variable_len_hash);}#[test]fn smoke_sha256_to_field() { let full_buffer = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, ]; let result = sha256_to_field(full_buffer); assert(result == 0x448ebbc9e1a31220a2f3830c18eef61b9bd070e5084b7fa2a359fe729184c7); // to show correctness of the current ver (truncate one byte) vs old ver (mod full bytes): let result_bytes = sha256::digest(full_buffer); let truncated_field = crate::utils::field::field_from_bytes_32_trunc(result_bytes); assert(truncated_field == result); let mod_res = result + (result_bytes[31] as Field); assert(mod_res == 0x448ebbc9e1a31220a2f3830c18eef61b9bd070e5084b7fa2a359fe729184e0);}#[test]fn unique_siloed_note_hash_matches_typescript() { let inner_note_hash = 1; let contract_address = AztecAddress::from_field(2); let first_nullifier = 3; let note_index_in_tx = 4; let siloed_note_hash = compute_siloed_note_hash(contract_address, inner_note_hash); let siloed_note_hash_from_ts = 0x1986a4bea3eddb1fff917d629a13e10f63f514f401bdd61838c6b475db949169; assert_eq(siloed_note_hash, siloed_note_hash_from_ts); let nonce: Field = compute_note_hash_nonce(first_nullifier, note_index_in_tx); let note_hash_nonce_from_ts = 0x28e7799791bf066a57bb51fdd0fbcaf3f0926414314c7db515ea343f44f5d58b; assert_eq(nonce, note_hash_nonce_from_ts); let unique_siloed_note_hash_from_nonce = compute_unique_note_hash(nonce, siloed_note_hash); let unique_siloed_note_hash = compute_note_nonce_and_unique_note_hash( siloed_note_hash, first_nullifier, note_index_in_tx, ); assert_eq(unique_siloed_note_hash_from_nonce, unique_siloed_note_hash); let unique_siloed_note_hash_from_ts = 0x29949aef207b715303b24639737c17fbfeb375c1d965ecfa85c7e4f0febb7d16; assert_eq(unique_siloed_note_hash, unique_siloed_note_hash_from_ts);}#[test]fn siloed_nullifier_matches_typescript() { let contract_address = AztecAddress::from_field(123); let nullifier = 456; let res = compute_siloed_nullifier(contract_address, nullifier); let siloed_nullifier_from_ts = 0x169b50336c1f29afdb8a03d955a81e485f5ac7d5f0b8065673d1e407e5877813; assert_eq(res, siloed_nullifier_from_ts);}#[test]fn siloed_private_log_first_field_matches_typescript() { let contract_address = AztecAddress::from_field(123); let field = 456; let res = compute_siloed_private_log_first_field(contract_address, field); let siloed_private_log_first_field_from_ts = 0x29480984f7b9257fded523d50addbcfc8d1d33adcf2db73ef3390a8fd5cdffaa; assert_eq(res, siloed_private_log_first_field_from_ts);}#[test]fn empty_l2_to_l1_message_hash_matches_typescript() { // All zeroes let res = compute_l2_to_l1_message_hash( L2ToL1Message { recipient: EthAddress::zero(), content: 0 }.scope(AztecAddress::from_field( 0, )), 0, 0, ); let empty_l2_to_l1_msg_hash_from_ts = 0x003b18c58c739716e76429634a61375c45b3b5cd470c22ab6d3e14cee23dd992; assert_eq(res, empty_l2_to_l1_msg_hash_from_ts);}#[test]fn l2_to_l1_message_hash_matches_typescript() { let message = L2ToL1Message { recipient: EthAddress::from_field(1), content: 2 }.scope( AztecAddress::from_field(3), ); let version = 4; let chainId = 5; let hash = compute_l2_to_l1_message_hash(message, version, chainId); // The following value was generated by `yarn-project/stdlib/src/hash/hash.test.ts` let l2_to_l1_message_hash_from_ts = 0x0081edf209e087ad31b3fd24263698723d57190bd1d6e9fe056fc0c0a68ee661; assert_eq(hash, l2_to_l1_message_hash_from_ts);}#[test]unconstrained fn poseidon2_hash_with_separator_bounded_vec_matches_non_bounded_vec_version() { let inputs = BoundedVec::<Field, 4>::from_array([1, 2, 3]); let separator = 42; // Hash using bounded vec version let bounded_result = poseidon2_hash_with_separator_bounded_vec(inputs, separator); // Hash using regular version let regular_result = poseidon2_hash_with_separator([1, 2, 3], separator); // Results should match assert_eq(bounded_result, regular_result);}use crate::{ constants::{ DOM_SEP__MERKLE_HASH, DOM_SEP__NULLIFIER_MERKLE, DOM_SEP__PUBLIC_DATA_MERKLE, DOM_SEP__RETRIEVED_BYTECODES_MERKLE, DOM_SEP__WRITTEN_SLOTS_MERKLE, }, hash::{accumulate_sha256, poseidon2_hash_with_separator}, traits::Empty, utils::math::is_power_of_2_u32,};/// Merkle-node hash used by append-only trees.pub fn merkle_hash(left: Field, right: Field) -> Field { poseidon2_hash_with_separator([left, right], DOM_SEP__MERKLE_HASH)}/// Merkle-node hash for the nullifier tree's sibling paths.pub fn nullifier_merkle_hash(left: Field, right: Field) -> Field { poseidon2_hash_with_separator([left, right], DOM_SEP__NULLIFIER_MERKLE)}/// Merkle-node hash for the public-data tree's sibling paths.pub fn public_data_merkle_hash(left: Field, right: Field) -> Field { poseidon2_hash_with_separator([left, right], DOM_SEP__PUBLIC_DATA_MERKLE)}/// Merkle-node hash for the AVM-internal written-public-data-slots tree's sibling paths.pub fn written_slots_merkle_hash(left: Field, right: Field) -> Field { poseidon2_hash_with_separator([left, right], DOM_SEP__WRITTEN_SLOTS_MERKLE)}/// Merkle-node hash for the AVM-internal retrieved-bytecodes (class-id) tree's sibling paths.pub fn retrieved_bytecodes_merkle_hash(left: Field, right: Field) -> Field { poseidon2_hash_with_separator([left, right], DOM_SEP__RETRIEVED_BYTECODES_MERKLE)}pub fn sha_merkle_hash(left: Field, right: Field) -> Field { accumulate_sha256(left, right)}#[derive(Eq)]pub struct MerkleTree<let N: u32> { pub leaves: [Field; N], pub nodes: [Field; N - 1],}impl<let N: u32> Empty for MerkleTree<N> { fn empty() -> Self { MerkleTree { leaves: [0; N], nodes: [0; N - 1] } }}impl<let N: u32> MerkleTree<N> { pub fn new(leaves: [Field; N]) -> Self { let nodes = compute_merkle_tree_nodes(leaves, merkle_hash); MerkleTree { leaves, nodes } } pub fn new_with_hasher(leaves: [Field; N], hasher: fn(Field, Field) -> Field) -> Self { let nodes = compute_merkle_tree_nodes(leaves, hasher); MerkleTree { leaves, nodes } } pub fn new_sha(leaves: [Field; N]) -> Self { let nodes = compute_merkle_tree_nodes(leaves, sha_merkle_hash); MerkleTree { leaves, nodes } } pub fn get_root(self) -> Field { self.nodes[N - 2] } pub fn get_sibling_path<let K: u32>(self, leaf_index: u32) -> [Field; K] { assert_eq(2.pow_32(K as Field), N as Field, "Invalid path length"); let mut path = [0; K]; let mut current_index = leaf_index; let mut subtree_width = N; let mut current_sibling_index = sibling_index(current_index); path[0] = self.leaves[current_sibling_index]; let mut subtree_offset: u32 = 0; for i in 1..K { current_index = current_index / 2; subtree_width = subtree_width / 2; current_sibling_index = sibling_index(current_index); path[i] = self.nodes[subtree_offset + current_sibling_index]; subtree_offset += subtree_width; } path }}pub fn sibling_index(index: u32) -> u32 { if index % 2 == 0 { index + 1 } else { index - 1 }}pub fn compute_merkle_tree_nodes<let N: u32>( leaves: [Field; N], hasher: fn(Field, Field) -> Field,) -> [Field; N - 1] { // Note: `N` must be a power of 2. std::static_assert(is_power_of_2_u32(N), "N must be a power of 2"); std::static_assert(N != 1, "2 must divide N"); let mut nodes = [0; N - 1]; let total_nodes = N - 1; let half_size = N / 2; // Hash base layer. for i in 0..half_size { nodes[i] = hasher(leaves[2 * i], leaves[2 * i + 1]); } // Hash the other layers. for i in 0..(total_nodes - half_size) { nodes[half_size + i] = hasher(nodes[2 * i], nodes[2 * i + 1]); } nodes}use crate::merkle_tree::merkle_tree::{compute_merkle_tree_nodes, merkle_hash, sha_merkle_hash};/// Calculate the Merkle tree root from the sibling path and leaf, using the default merkle hash.pub fn root_from_sibling_path<let N: u32>( leaf: Field, leaf_index: Field, sibling_path: [Field; N],) -> Field { root_from_sibling_path_with_hasher(leaf, leaf_index, sibling_path, merkle_hash)}/// Calculate the Merkle tree root from the sibling path and leaf, using a custom hasher.////// The leaf is hashed with its sibling, the result is then hashed with the next sibling in the path. and so on./// The last hash is the root.pub fn root_from_sibling_path_with_hasher<let N: u32>( leaf: Field, leaf_index: Field, sibling_path: [Field; N], hasher: fn(Field, Field) -> Field,) -> Field { let mut node = leaf; let indices: [bool; N] = leaf_index.to_le_bits(); for i in 0..N { let (hash_left, hash_right) = if indices[i] { (sibling_path[i], node) } else { (node, sibling_path[i]) }; node = hasher(hash_left, hash_right); } node}pub fn compute_tree_root<let N: u32>(leaves: [Field; N]) -> Field { compute_tree_root_with_hasher(leaves, merkle_hash)}pub fn compute_sha_tree_root<let N: u32>(leaves: [Field; N]) -> Field { compute_tree_root_with_hasher(leaves, sha_merkle_hash)}pub fn compute_tree_root_with_hasher<let N: u32>( leaves: [Field; N], hasher: fn(Field, Field) -> Field,) -> Field { compute_merkle_tree_nodes(leaves, hasher)[N - 2]}pub fn compute_empty_tree_root<let TreeHeight: u32>() -> Field { compute_empty_tree_root_with_hasher::<TreeHeight>(merkle_hash)}pub fn compute_empty_sha_tree_root<let TreeHeight: u32>() -> Field { compute_empty_tree_root_with_hasher::<TreeHeight>(sha_merkle_hash)}pub fn compute_empty_tree_root_with_hasher<let TreeHeight: u32>( hasher: fn(Field, Field) -> Field,) -> Field { let mut hashes = [0; TreeHeight + 1]; for i in 1..TreeHeight + 1 { hashes[i] = hasher(hashes[i - 1], hashes[i - 1]); } hashes[TreeHeight]}#[test]fn test_merkle_roots_match_typescript() { // The following hardcoded values are generated from yarn-project/foundation/src/trees/balanced_merkle_tree_root.test.ts let root = compute_tree_root([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); let expected_tree_root_from_ts = 0x2bc86dba04dfdd6352c3b1c66b2300445964e2888aa52fdb023d2e645a3d3399; assert_eq(root, expected_tree_root_from_ts); let empty_root = compute_tree_root([0; 16]); let expected_empty_root_from_ts = 0x1e20ad4181460cbfdc74ca773502c59b890f184efe300ebad895956d318422da; assert_eq(empty_root, expected_empty_root_from_ts); let sha_root = compute_sha_tree_root([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]); let expected_sha_root_from_ts = 0x00b007869b8a5e2a9b3b580a318e702cea04b2f5438f2e26743f545e4d1ecbdb; assert_eq(sha_root, expected_sha_root_from_ts);}#[test]fn test_empty_tree_root() { assert_eq(compute_empty_tree_root::<0>(), 0); assert_eq( compute_empty_tree_root::<1>(), 0x19f1a0c09db4cd026f686e9c8fb45501a9fefb4eb1b4c6c328a51343a0094eeb, ); assert_eq( compute_empty_tree_root::<2>(), 0x14e4b977b2203b70e6ee1c2456eb7114d090fe4b907f631eecd0919fed432e7d, ); assert_eq( compute_empty_tree_root::<6>(), 0x119f56a2e8423a7feaab49b9b5dcbadec0648dfa4096b61b6774ea33ae29dc7f, ); assert_eq( compute_empty_tree_root::<10>(), 0x0d04c63f36bd168215c9b09a227c7e8d3ad48e2f11b8202fd07c524bd30ee88f, );}use crate::{ constants::DOM_SEP__PUBLIC_STORAGE_MAP_SLOT, hash::poseidon2_hash_with_separator, traits::ToField,};// TODO: Move this to src/public_data/storage/map.nrpub fn derive_storage_slot_in_map<K>(storage_slot: Field, key: K) -> Fieldwhere K: ToField,{ poseidon2_hash_with_separator( [storage_slot, key.to_field()], DOM_SEP__PUBLIC_STORAGE_MAP_SLOT, )}mod test { use crate::{address::AztecAddress, storage::map::derive_storage_slot_in_map, traits::FromField}; #[test] fn test_derive_storage_slot_in_map_matches_typescript() { let map_slot = 0x132258fb6962c4387ba659d9556521102d227549a386d39f0b22d1890d59c2b5; let key = AztecAddress::from_field( 0x302dbc2f9b50a73283d5fb2f35bc01eae8935615817a0b4219a057b2ba8a5a3f, ); let slot = derive_storage_slot_in_map(map_slot, key); // The following value was generated by `map_slot.test.ts` let slot_from_typescript = 0x2d225f361108379adc2da91378b9702675c5546b57e78bafc1e74ec7fec55967; assert_eq(slot, slot_from_typescript); }}use crate::traits::{Deserialize, Packable, Serialize};global BOOL_PACKED_LEN: u32 = 1;global U8_PACKED_LEN: u32 = 1;global U16_PACKED_LEN: u32 = 1;global U32_PACKED_LEN: u32 = 1;global U64_PACKED_LEN: u32 = 1;global U128_PACKED_LEN: u32 = 1;global FIELD_PACKED_LEN: u32 = 1;global I8_PACKED_LEN: u32 = 1;global I16_PACKED_LEN: u32 = 1;global I32_PACKED_LEN: u32 = 1;global I64_PACKED_LEN: u32 = 1;global POINT_PACKED_LEN: u32 = 2;impl Packable for bool { let N: u32 = BOOL_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as Field] } /// Unpacks a `bool`, constraining the field to be a canonical boolean. A field outside `{0, 1}` is /// rejected (rather than silently reinterpreted), so an arbitrary-origin field cannot be misread. /// `pack` always emits `0` or `1`, so round-tripping is unaffected. #[inline_always] fn unpack(fields: [Field; Self::N]) -> bool { let v = fields[0]; // v * v == v holds iff v is 0 or 1: a single degree-2 constraint that both validates the field // is a canonical bool and avoids the byte-range decomposition that a cast to u8 would require. assert(v * v == v, "Packable::unpack: bool field must be 0 or 1"); v == 1 }}impl Packable for u8 { let N: u32 = U8_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u8 }}impl Packable for u16 { let N: u32 = U16_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u16 }}impl Packable for u32 { let N: u32 = U32_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u32 }}impl Packable for u64 { let N: u32 = U64_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u64 }}impl Packable for u128 { let N: u32 = U128_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u128 }}impl Packable for Field { let N: u32 = FIELD_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] }}impl Packable for i8 { let N: u32 = I8_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as u8 as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u8 as i8 }}impl Packable for i16 { let N: u32 = I16_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as u16 as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u16 as i16 }}impl Packable for i32 { let N: u32 = I32_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as u32 as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u32 as i32 }}impl Packable for i64 { let N: u32 = I64_PACKED_LEN; #[inline_always] fn pack(self) -> [Field; Self::N] { [self as u64 as Field] } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { fields[0] as u64 as i64 }}impl Packable for super::point::EmbeddedCurvePoint { let N: u32 = POINT_PACKED_LEN; fn pack(self) -> [Field; Self::N] { self.serialize() } fn unpack(packed: [Field; Self::N]) -> Self { Self::deserialize(packed) }}impl<T, let M: u32> Packable for [T; M]where T: Packable,{ let N: u32 = M * <T as Packable>::N; #[inline_always] fn pack(self) -> [Field; Self::N] { let mut result: [Field; Self::N] = std::mem::zeroed(); for i in 0..M { let serialized = self[i].pack(); for j in 0..<T as Packable>::N { result[i * <T as Packable>::N + j] = serialized[j]; } } result } #[inline_always] fn unpack(fields: [Field; Self::N]) -> Self { let mut reader = crate::utils::reader::Reader::new(fields); let result: [T; M] = std::mem::zeroed(); reader.read_struct_array::<T, <T as Packable>::N, M>(Packable::unpack, result) }}#[test]fn test_u16_packing() { let a: u16 = 10; assert_eq(a, u16::unpack(a.pack()));}#[test]fn test_i8_packing() { let a: i8 = -10; assert_eq(a, i8::unpack(a.pack()));}#[test]fn test_i16_packing() { let a: i16 = -10; assert_eq(a, i16::unpack(a.pack()));}#[test]fn test_i32_packing() { let a: i32 = -10; assert_eq(a, i32::unpack(a.pack()));}#[test]fn test_i64_packing() { let a: i64 = -10; assert_eq(a, i64::unpack(a.pack()));}#[test]fn test_bool_unpack_accepts_canonical_values() { assert_eq(bool::unpack([0]), false); assert_eq(bool::unpack([1]), true);}#[test(should_fail_with = "bool field must be 0 or 1")]fn test_bool_unpack_rejects_even_non_bool() { // 2 has LSB 0, so the previous LSB-based unpack silently returned false; now it is rejected. let _ = bool::unpack([2]);}#[test(should_fail_with = "bool field must be 0 or 1")]fn test_bool_unpack_rejects_odd_non_bool() { // 3 has LSB 1, so the previous LSB-based unpack silently returned true; now it is rejected. let _ = bool::unpack([3]);}#[test(should_fail_with = "bool field must be 0 or 1")]fn test_bool_unpack_rejects_large_field() { let _ = bool::unpack([1000000]);}#[test]fn test_bool_pack_unpack_roundtrip() { // `pack` always emits 0 or 1, so it round-trips through the canonical-bool check in `unpack`. assert_eq(true.pack(), [1]); assert_eq(false.pack(), [0]); assert_eq(bool::unpack(true.pack()), true); assert_eq(bool::unpack(false.pack()), false);}use std::default::Default;use std::hash::Hasher;global RATE: u32 = 3;pub struct Poseidon2 { cache: [Field; 3], state: [Field; 4], cache_size: u32, squeeze_mode: bool, // 0 => absorb, 1 => squeeze}impl Poseidon2 { #[no_predicates] pub fn hash<let N: u32>(input: [Field; N], message_size: u32) -> Field { Poseidon2::hash_internal(input, message_size) } pub(crate) fn new(iv: Field) -> Poseidon2 { let mut result = Poseidon2 { cache: [0; 3], state: [0; 4], cache_size: 0, squeeze_mode: false }; result.state[RATE] = iv; result } fn perform_duplex(&mut self) { // add the cache into sponge state self.state[0] += self.cache[0]; self.state[1] += self.cache[1]; self.state[2] += self.cache[2]; self.state = crate::poseidon2_permutation(self.state); } fn absorb(&mut self, input: Field) { assert(!self.squeeze_mode); if self.cache_size == RATE { // If we're absorbing, and the cache is full, apply the sponge permutation to compress the cache self.perform_duplex(); self.cache[0] = input; self.cache_size = 1; } else { // If we're absorbing, and the cache is not full, add the input into the cache self.cache[self.cache_size] = input; self.cache_size += 1; } } fn squeeze(&mut self) -> Field { assert(!self.squeeze_mode); // If we're in absorb mode, apply sponge permutation to compress the cache. self.perform_duplex(); self.squeeze_mode = true; // Pop one item off the top of the permutation and return it. self.state[0] } fn hash_internal<let N: u32>(input: [Field; N], in_len: u32) -> Field { let two_pow_64 = 18446744073709551616; let iv: Field = (in_len as Field) * two_pow_64; let mut state = [0; 4]; state[RATE] = iv; if std::runtime::is_unconstrained() { for i in 0..(in_len / RATE) { state[0] += input[i * RATE]; state[1] += input[i * RATE + 1]; state[2] += input[i * RATE + 2]; state = crate::poseidon2_permutation(state); } // handle remaining elements after last full RATE-sized chunk let num_extra_fields = in_len % RATE; if num_extra_fields != 0 { let remainder_start = in_len - num_extra_fields; state[0] += input[remainder_start]; if num_extra_fields > 1 { state[1] += input[remainder_start + 1]; } } } else { let mut states: [[Field; 4]; N / RATE + 1] = [[0; 4]; N / RATE + 1]; states[0] = state; // process all full RATE-sized chunks, storing state after each permutation for chunk_idx in 0..(N / RATE) { for i in 0..RATE { state[i] += input[chunk_idx * RATE + i]; } state = crate::poseidon2_permutation(state); states[chunk_idx + 1] = state; } // get state at the last full block before in_len let first_partially_filled_chunk = in_len / RATE; state = states[first_partially_filled_chunk]; // handle remaining elements after last full RATE-sized chunk let remainder_start = (in_len / RATE) * RATE; for j in 0..RATE { let idx = remainder_start + j; if idx < in_len { state[j] += input[idx]; } } } // always run final permutation unless we just completed a full chunk // still need to permute once if in_len is 0 if (in_len == 0) | (in_len % RATE != 0) { state = crate::poseidon2_permutation(state); }; state[0] }}pub struct Poseidon2Hasher { _state: [Field],}impl Hasher for Poseidon2Hasher { fn finish(self) -> Field { let iv: Field = (self._state.len() as Field) * 18446744073709551616; // iv = (self._state.len() << 64) let mut sponge = Poseidon2::new(iv); for i in 0..self._state.len() { sponge.absorb(self._state[i]); } sponge.squeeze() } fn write(&mut self, input: Field) { self._state = self._state.push_back(input); }}impl Default for Poseidon2Hasher { fn default() -> Self { Poseidon2Hasher { _state: @[] } }}use std::hash::sha256_compression;use std::runtime::is_unconstrained;use constants::{ BLOCK_BYTE_PTR, BLOCK_SIZE, HASH, INITIAL_STATE, INT_BLOCK_SIZE, INT_SIZE, INT_SIZE_PTR, MSG_BLOCK, MSG_SIZE_PTR, STATE, TWO_POW_16, TWO_POW_24, TWO_POW_32, TWO_POW_8,};pub(crate) mod constants;mod tests;mod oracle_tests;// Implementation of SHA-256 mapping a byte array of variable length to// 32 bytes.// Deprecated in favour of `sha256_var`// docs:start:sha256pub fn sha256<let N: u32>(input: [u8; N]) -> HASH// docs:end:sha256{ digest(input)}// SHA-256 hash function#[no_predicates]pub fn digest<let N: u32>(msg: [u8; N]) -> HASH { sha256_var(msg, N)}// Variable size SHA-256 hashpub fn sha256_var<let N: u32>(msg: [u8; N], message_size: u32) -> HASH { assert(message_size <= N); let (h, msg_block) = process_full_blocks(msg, message_size, INITIAL_STATE); finalize_sha256_blocks(message_size, h, msg_block)}/// Returns the first partially filled message block along with the internal state prior to its compression.pub(crate) fn process_full_blocks<let N: u32>( msg: [u8; N], message_size: u32, initial_state: STATE,) -> (STATE, MSG_BLOCK) { if std::runtime::is_unconstrained() { let num_full_blocks = message_size / BLOCK_SIZE; // Intermediate hash, starting with the canonical initial value let mut h: STATE = initial_state; // Pointer into msg_block on a 64 byte scale for i in 0..num_full_blocks { let msg_block = build_msg_block(msg, message_size, BLOCK_SIZE * i); h = sha256_compression(msg_block, h); } // We now build the final un-filled block. let msg_byte_ptr = message_size % BLOCK_SIZE; let msg_block: MSG_BLOCK = if msg_byte_ptr != 0 { let num_full_blocks = message_size / BLOCK_SIZE; let msg_start = BLOCK_SIZE * num_full_blocks; build_msg_block(msg, message_size, msg_start) } else { // If the message size is a multiple of the block size (i.e. `msg_byte_ptr == 0`) then this block will be empty, // so we short-circuit in this case. [0; 16] }; (h, msg_block) } else { let num_blocks = N / BLOCK_SIZE; // We store the intermediate hash states and message blocks in these two arrays which allows us to select the correct state // for the given message size with a lookup. // // These can be reasoned about as followed: // Consider a message with an unknown number of bytes, `msg_size. It can be seen that this will have `msg_size / BLOCK_SIZE` full blocks. // - `states[i]` should then be the state after processing the first `i` blocks. // - `blocks[i]` should then be the next message block after processing the first `i` blocks. // blocks[first_partially_filled_block_index] is the last block that is partially filled or all 0 if the message is a multiple of the block size. // // In other words: // // blocks = [block 1, block 2, ..., block N / BLOCK_SIZE, block N / BLOCK_SIZE + 1] // states = [INITIAL_STATE, state after block 1, state after block 2, ..., state after block N / BLOCK_SIZE] // // We place the initial state in `states[0]` as in the case where the `message_size < BLOCK_SIZE` then there are no full blocks to process and no compressions should occur. let mut blocks: [MSG_BLOCK; N / BLOCK_SIZE + 1] = std::mem::zeroed(); let mut states: [STATE; N / BLOCK_SIZE + 1] = [initial_state; N / BLOCK_SIZE + 1]; // Optimization for small messages. If the largest possible message is smaller than a block then we know that the first block is partially filled // no matter the value of `message_size`. // // Note that the condition `N >= BLOCK_SIZE` is known during monomorphization so this has no runtime cost. let first_partially_filled_block_index = if N >= BLOCK_SIZE { message_size / BLOCK_SIZE } else { 0 }; for i in 0..num_blocks { let msg_start = BLOCK_SIZE * i; let new_msg_block = build_msg_block(msg, message_size, msg_start); blocks[i] = new_msg_block; states[i + 1] = sha256_compression(new_msg_block, states[i]); } // If message_size/BLOCK_SIZE == N/BLOCK_SIZE, and there is a remainder, we need to process the last block. if N % BLOCK_SIZE != 0 { let new_msg_block = build_msg_block(msg, message_size, BLOCK_SIZE * num_blocks); blocks[num_blocks] = new_msg_block; } (states[first_partially_filled_block_index], blocks[first_partially_filled_block_index]) }}// Take `BLOCK_SIZE` number of bytes from `msg` starting at `msg_start` and pack them into a `MSG_BLOCK`.pub(crate) unconstrained fn build_msg_block_helper<let N: u32>( msg: [u8; N], message_size: u32, msg_start: u32,) -> MSG_BLOCK { let mut msg_block: MSG_BLOCK = [0; INT_BLOCK_SIZE]; // We insert `BLOCK_SIZE` bytes (or up to the end of the message) let block_input = if message_size < msg_start { // This function is sometimes called with `msg_start` past the end of the message. // In this case we return an empty block and zero pointer to signal that the result should be ignored. 0 } else if message_size < msg_start + BLOCK_SIZE { message_size - msg_start } else { BLOCK_SIZE }; // Figure out the number of items in the int array that we have to pack. // e.g. if the input is [0,1,2,3,4,5] then we need to pack it as 2 items: [0123, 4500] let int_input = (block_input + INT_SIZE - 1) / INT_SIZE; for i in 0..int_input { let mut msg_item: u32 = 0; // Always construct the integer as 4 bytes, even if it means going beyond the input. for j in 0..INT_SIZE { let k = i * INT_SIZE + j; let msg_byte = if k < block_input { msg[msg_start + k] } else { 0 }; msg_item = (msg_item << 8) + msg_byte as u32; } msg_block[i] = msg_item; } // Returning the index as if it was a 64 byte array. // We have to project it down to 16 items and bit shifting to get a byte back if we need it. msg_block}// Build a message block from the input message starting at `msg_start`.//// If `message_size` is less than `msg_start` then this is called with the old non-empty block;// in that case we can skip verification, ie. no need to check that everything is zero.fn build_msg_block<let N: u32>(msg: [u8; N], message_size: u32, msg_start: u32) -> MSG_BLOCK { let msg_block = // Safety: We constrain the block below by reconstructing each `u32` word from the input bytes. unsafe { build_msg_block_helper(msg, message_size, msg_start) }; if !is_unconstrained() { let mut msg_end = msg_start + BLOCK_SIZE; let max_read_index = std::cmp::min(message_size, msg_end); // Reconstructed packed item let mut msg_item: Field = 0; // Inclusive at the end so that we can compare the last item. for k in msg_start..=msg_end { if (k != msg_start) & (k % INT_SIZE == 0) { // If we consumed some input we can compare against the block. let msg_block_index = (k - msg_start) / INT_SIZE - 1; assert_eq(msg_block[msg_block_index] as Field, msg_item); msg_item = 0; } // If we have input to consume, add it at the rightmost position. let msg_byte = if k < max_read_index { msg[k] } else { 0 }; msg_item = msg_item * (TWO_POW_8 as Field) + msg_byte as Field; } } msg_block}// Encode `8 * message_size` into two `u32` limbs.unconstrained fn encode_len(message_size: u32) -> (u32, u32) { let len = 8 * message_size as u64; let lo = len & 0xFFFFFFFF; let hi = (len >> 32) & 0xFFFFFFFF; (lo as u32, hi as u32)}// Write the length into the last 8 bytes of the block.fn attach_len_to_msg_block(mut msg_block: MSG_BLOCK, message_size: u32) -> MSG_BLOCK { // Safety: We assert the correctness of the decomposition below. // 2 `u32` limbs cannot overflow the field modulus so performing the check as `Field`s is safe. let (lo, hi) = unsafe { encode_len(message_size) }; assert_eq(8 * (message_size as Field), lo as Field + hi as Field * TWO_POW_32); msg_block[INT_SIZE_PTR] = hi; msg_block[INT_SIZE_PTR + 1] = lo; msg_block}// Perform the final compression, then transform the `STATE` into `HASH`.fn hash_final_block(msg_block: MSG_BLOCK, mut state: STATE) -> HASH { // Hash final padded block state = sha256_compression(msg_block, state); // Return final hash as byte array let mut out_h: HASH = [0; 32]; // Digest as sequence of bytes for j in 0..8 { let h_bytes: [u8; 4] = (state[j] as Field).to_be_bytes(); for k in 0..4 { out_h[4 * j + k] = h_bytes[k]; } } out_h}/// Lookup table for the position of the padding bit within one of the `u32` words in the final message block.global PADDING_BIT_TABLE: [u32; 4] = [(1 << 7) * TWO_POW_24, (1 << 7) * TWO_POW_16, (1 << 7) * TWO_POW_8, (1 << 7)];/// Add 1 bit padding to end of message and compress the block if there's not enough room for the 8-byte length./// Returns the updated hash state and message block that will be used to write the message size.////// # Assumptions:////// - `msg_block[i] == 0` for all `i > msg_byte_ptr / INT_SIZE`/// - `msg_block[msg_byte_ptr / INT_SIZE] & ((1 << 7) * (msg_byte_ptr % INT_SIZE)) == 0`fn add_padding_byte_and_compress_if_needed( mut msg_block: MSG_BLOCK, msg_byte_ptr: BLOCK_BYTE_PTR, h: STATE,) -> (STATE, MSG_BLOCK) { // Pad the rest such that we have a [u32; 2] block at the end representing the length // of the message, and a block of 1 0 ... 0 following the message (i.e. [1 << 7, 0, ..., 0]). // Here we rely on the fact that everything beyond the available input is set to 0. let index = msg_byte_ptr / INT_SIZE; // Lookup the position of the padding bit and insert it into the message block. msg_block[index] += PADDING_BIT_TABLE[msg_byte_ptr % INT_SIZE]; // If we don't have room to write the size, compress the block and reset it. if msg_byte_ptr >= MSG_SIZE_PTR { let h = sha256_compression(msg_block, h); // In this case, the final block consists of all zeros with the last 8 bytes containing the length. // We set msg_block to all zeros and attach_len_to_msg_block will add the length to the last 8 bytes. let msg_block = [0; INT_BLOCK_SIZE]; (h, msg_block) } else { (h, msg_block) }}pub(crate) fn finalize_sha256_blocks( message_size: u32, mut h: STATE, mut msg_block: MSG_BLOCK,) -> HASH { let msg_byte_ptr = message_size % BLOCK_SIZE; let (h, mut msg_block) = add_padding_byte_and_compress_if_needed(msg_block, msg_byte_ptr, h); msg_block = attach_len_to_msg_block(msg_block, message_size); hash_final_block(msg_block, h)}/** * Given some state of a partially computed sha256 hash and part of the preimage, continue hashing * @notice used for complex/ recursive offloading of post-partial hashing * * @param N - the maximum length of the message to hash * @param h - the intermediate hash state * @param msg - the preimage to hash * @param message_size - the actual length of the preimage to hash * @return the intermediate hash state after compressing in msg to h */pub fn partial_sha256_var_interstitial<let N: u32>( mut h: [u32; 8], msg: [u8; N], message_size: u32,) -> [u32; 8] { assert(message_size % BLOCK_SIZE == 0, "Message size must be a multiple of the block size"); if std::runtime::is_unconstrained() { // Safety: running as an unconstrained function unsafe { __sha_partial_var_interstitial(h, msg, message_size) } } else { let (h, _) = process_full_blocks(msg, message_size, h); h }}/** * Given some state of a partially computed sha256 hash and remaining preimage, complete the hash * @notice used for traditional partial hashing * * @param N - the maximum length of the message to hash * @param h - the intermediate hash state * @param msg - the remaining preimage to hash * @param message_size - the size of the current chunk * @param real_message_size - the total size of the original preimage * @return finalized sha256 hash */pub fn partial_sha256_var_end<let N: u32>( mut h: [u32; 8], msg: [u8; N], message_size: u32, real_message_size: u32,) -> [u8; 32] { assert(message_size % BLOCK_SIZE == 0, "Message size must be a multiple of the block size"); if std::runtime::is_unconstrained() { // Safety: running as an unconstrained function unsafe { h = __sha_partial_var_interstitial(h, msg, message_size); // Handle setup of the final msg block. // This case is only hit if the msg is less than the block size, // or our message cannot be evenly split into blocks. finalize_last_sha256_block(h, real_message_size, msg) } } else { let (h, msg_block) = process_full_blocks(msg, message_size, h); finalize_sha256_blocks(real_message_size, h, msg_block) }}unconstrained fn __sha_partial_var_interstitial<let N: u32>( mut h: [u32; 8], msg: [u8; N], message_size: u32,) -> [u32; 8] { let num_full_blocks = message_size / BLOCK_SIZE; // Intermediate hash, starting with the canonical initial value // Pointer into msg_block on a 64 byte scale for i in 0..num_full_blocks { let msg_block = build_msg_block(msg, message_size, BLOCK_SIZE * i); h = sha256_compression(msg_block, h); } h}// Helper function to finalize the message block with padding and lengthunconstrained fn finalize_last_sha256_block<let N: u32>( mut h: STATE, message_size: u32, msg: [u8; N],) -> HASH { let msg_byte_ptr = message_size % BLOCK_SIZE; // We now build the final un-filled block. let msg_block: MSG_BLOCK = if msg_byte_ptr != 0 { let num_full_blocks = message_size / BLOCK_SIZE; let msg_start = BLOCK_SIZE * num_full_blocks; build_msg_block(msg, message_size, msg_start) } else { // If the message size is a multiple of the block size (i.e. `msg_byte_ptr == 0`) then this block will be empty, // so we short-circuit in this case. [0; 16] }; // Once built, we need to add the necessary padding bytes and encoded length let (h, mut msg_block) = add_padding_byte_and_compress_if_needed(msg_block, msg_byte_ptr, h); msg_block = attach_len_to_msg_block(msg_block, message_size); hash_final_block(msg_block, h)}mod test_process_full_blocks { /// Wrapper to force an unconstrained runtime on process_full_blocks. unconstrained fn unconstrained_process_full_blocks<let N: u32>( msg: [u8; N], message_size: u32, h: super::STATE, ) -> (super::STATE, super::MSG_BLOCK) { super::process_full_blocks(msg, message_size, h) } #[test] fn test_implementations_agree(msg: [u8; 100], message_size: u32) { let message_size = message_size % 100; // Safety: test function let unconstrained_state = unsafe { unconstrained_process_full_blocks(msg, message_size, super::INITIAL_STATE) }; let state = super::process_full_blocks(msg, message_size, super::INITIAL_STATE); assert_eq(state, unconstrained_state); }}mod test_sha256_var { /// Wrapper to force an unconstrained runtime on sha256. unconstrained fn unconstrained_sha256<let N: u32>( msg: [u8; N], message_size: u32, ) -> super::HASH { super::sha256_var(msg, message_size) } #[test] fn test_implementations_agree(msg: [u8; 100], message_size: u32) { let message_size = message_size % 100; // Safety: test function let unconstrained_sha = unsafe { unconstrained_sha256(msg, message_size) }; let sha = super::sha256_var(msg, message_size); assert_eq(sha, unconstrained_sha); }}// docs:start:aes128/// Given a plaintext as an array of bytes, returns the corresponding aes128 ciphertext (CBC mode). Input padding is performed using PKCS#7, so that the output length is `input.len() + (16 - input.len() % 16)`.pub fn aes128_encrypt<let N: u32>( input: [u8; N], iv: [u8; 16], key: [u8; 16],) -> [u8; N + 16 - N % 16] { let padding_length = (16 - N % 16) as u8; let mut padded_input: [u8; N + 16 - N % 16] = [0; N + 16 - N % 16]; for i in 0..N { padded_input[i] = input[i]; } for i in N..N + 16 - N % 16 { padded_input[i] = padding_length; } let output = aes128_encrypt_padded_input(padded_input, iv, key); output}#[foreign(aes128_encrypt)]fn aes128_encrypt_padded_input<let N: u32>(input: [u8; N], iv: [u8; 16], key: [u8; 16]) -> [u8; N] {}// docs:end:aes128mod tests { use super::aes128_encrypt; #[test] fn encrypt() { let input = "kevlovesrust".as_bytes(); let iv = "0000000000000000".as_bytes(); let key = "0000000000000000".as_bytes(); let output = [244, 14, 126, 172, 171, 40, 208, 186, 173, 184, 226, 105, 238, 122, 205, 191]; assert_eq(aes128_encrypt(input, iv, key), output); }}use crate::meta::ctstring::AsCtString;use crate::meta::derive_via;/// Compare two values for equality#[derive_via(derive_eq)]// docs:start:eq-traitpub trait Eq { fn eq(self, other: Self) -> bool;}// docs:end:eq-trait// docs:start:derive_eqcomptime fn derive_eq(s: TypeDefinition) -> Quoted { let signature = quote { fn eq(_self: Self, _other: Self) -> bool }; let for_each_field = |name| quote { (_self.$name == _other.$name) }; let body = |fields| { if s.fields_as_written().len() == 0 { quote { true } } else { fields } }; crate::meta::make_trait_impl( s, quote { $crate::cmp::Eq }, signature, for_each_field, quote { & }, body, )}// docs:end:derive_eqimpl Eq for Field { fn eq(self, other: Field) -> bool { self == other }}impl Eq for u128 { fn eq(self, other: u128) -> bool { self == other }}impl Eq for u64 { fn eq(self, other: u64) -> bool { self == other }}impl Eq for u32 { fn eq(self, other: u32) -> bool { self == other }}impl Eq for u16 { fn eq(self, other: u16) -> bool { self == other }}impl Eq for u8 { fn eq(self, other: u8) -> bool { self == other }}impl Eq for i8 { fn eq(self, other: i8) -> bool { self == other }}impl Eq for i16 { fn eq(self, other: i16) -> bool { self == other }}impl Eq for i32 { fn eq(self, other: i32) -> bool { self == other }}impl Eq for i64 { fn eq(self, other: i64) -> bool { self == other }}impl Eq for () { fn eq(_self: Self, _other: ()) -> bool { true }}impl Eq for bool { fn eq(self, other: bool) -> bool { self == other }}impl<T, let N: u32> Eq for [T; N]where T: Eq,{ fn eq(self, other: [T; N]) -> bool { let mut result = true; for i in 0..self.len() { result &= self[i].eq(other[i]); } result }}impl<T> Eq for [T]where T: Eq,{ fn eq(self, other: [T]) -> bool { let mut result = self.len() == other.len(); if result { for i in 0..self.len() { result &= self[i].eq(other[i]); } } result }}impl<let N: u32> Eq for str<N> { fn eq(self, other: str<N>) -> bool { let self_bytes = self.as_bytes(); let other_bytes = other.as_bytes(); self_bytes == other_bytes }}comptime fn make_tuple_eq_body(n: u32) -> Quoted { let mut body = f"self.0.eq(other.0)".as_ctstring(); for i in 1u32..n { body = body.append_fmtstr(f" & self.{i}.eq(other.{i})"); } f"{body}".quoted_contents()}impl<A: Eq> Eq for (A,) { fn eq(self, other: (A,)) -> bool { self.0 == other.0 }}impl<A: Eq, B: Eq> Eq for (A, B) { fn eq(self, other: (A, B)) -> bool { make_tuple_eq_body!(2u32) }}impl<A: Eq, B: Eq, C: Eq> Eq for (A, B, C) { fn eq(self, other: (A, B, C)) -> bool { make_tuple_eq_body!(3u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq> Eq for (A, B, C, D) { fn eq(self, other: (A, B, C, D)) -> bool { make_tuple_eq_body!(4u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq, E: Eq> Eq for (A, B, C, D, E) { fn eq(self, other: (A, B, C, D, E)) -> bool { make_tuple_eq_body!(5u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq> Eq for (A, B, C, D, E, F) { fn eq(self, other: (A, B, C, D, E, F)) -> bool { make_tuple_eq_body!(6u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq> Eq for (A, B, C, D, E, F, G) { fn eq(self, other: (A, B, C, D, E, F, G)) -> bool { make_tuple_eq_body!(7u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq> Eq for (A, B, C, D, E, F, G, H) { fn eq(self, other: (A, B, C, D, E, F, G, H)) -> bool { make_tuple_eq_body!(8u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq, I: Eq> Eq for (A, B, C, D, E, F, G, H, I) { fn eq(self, other: (A, B, C, D, E, F, G, H, I)) -> bool { make_tuple_eq_body!(9u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq, I: Eq, J: Eq> Eq for (A, B, C, D, E, F, G, H, I, J) { fn eq(self, other: (A, B, C, D, E, F, G, H, I, J)) -> bool { make_tuple_eq_body!(10u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq, I: Eq, J: Eq, K: Eq> Eq for (A, B, C, D, E, F, G, H, I, J, K) { fn eq(self, other: (A, B, C, D, E, F, G, H, I, J, K)) -> bool { make_tuple_eq_body!(11u32) }}impl<A: Eq, B: Eq, C: Eq, D: Eq, E: Eq, F: Eq, G: Eq, H: Eq, I: Eq, J: Eq, K: Eq, L: Eq> Eq for (A, B, C, D, E, F, G, H, I, J, K, L) { fn eq(self, other: (A, B, C, D, E, F, G, H, I, J, K, L)) -> bool { make_tuple_eq_body!(12u32) }}impl Eq for Ordering { fn eq(self, other: Ordering) -> bool { self.result == other.result }}// Noir doesn't have enums yet so we emulate (Lt | Eq | Gt) with a struct// that has 3 public functions for constructing the struct./// A value with three states: `Ordering::less()`, `Ordering::equal()` or `Ordering::greater()`./// Most often used to encode the result of a comparison operation.pub struct Ordering { result: Field,}impl Ordering { // Implementation note: 0, 1, and 2 for Lt, Eq, and Gt are built // into the compiler, do not change these without also updating // the compiler itself! pub fn less() -> Ordering { Ordering { result: 0 } } pub fn equal() -> Ordering { Ordering { result: 1 } } pub fn greater() -> Ordering { Ordering { result: 2 } }}/// Compare one object to another, returning whether it is less-than, equal-to,/// or greater-than the other object.#[derive_via(derive_ord)]// docs:start:ord-traitpub trait Ord { fn cmp(self, other: Self) -> Ordering;}// docs:end:ord-trait// docs:start:derive_ordcomptime fn derive_ord(s: TypeDefinition) -> Quoted { let name = quote { $crate::cmp::Ord }; let signature = quote { fn cmp(_self: Self, _other: Self) -> $crate::cmp::Ordering }; let for_each_field = |name| quote { if result == $crate::cmp::Ordering::equal() { result = _self.$name.cmp(_other.$name); } }; let body = |fields| quote { let mut result = $crate::cmp::Ordering::equal(); $fields result }; crate::meta::make_trait_impl(s, name, signature, for_each_field, quote {}, body)}// docs:end:derive_ord// Note: Field deliberately does not implement Ordimpl Ord for u128 { fn cmp(self, other: u128) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for u64 { fn cmp(self, other: u64) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for u32 { fn cmp(self, other: u32) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for u16 { fn cmp(self, other: u16) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for u8 { fn cmp(self, other: u8) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for i8 { fn cmp(self, other: i8) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for i16 { fn cmp(self, other: i16) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for i32 { fn cmp(self, other: i32) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for i64 { fn cmp(self, other: i64) -> Ordering { if self < other { Ordering::less() } else if self > other { Ordering::greater() } else { Ordering::equal() } }}impl Ord for () { fn cmp(_self: Self, _other: ()) -> Ordering { Ordering::equal() }}impl Ord for bool { fn cmp(self, other: bool) -> Ordering { if self { if other { Ordering::equal() } else { Ordering::greater() } } else if other { Ordering::less() } else { Ordering::equal() } }}impl<T, let N: u32> Ord for [T; N]where T: Ord,{ // The first non-equal element of both arrays determines // the ordering for the whole array. fn cmp(self, other: [T; N]) -> Ordering { let mut result = Ordering::equal(); for i in 0..self.len() { if result == Ordering::equal() { result = self[i].cmp(other[i]); } } result }}impl<T> Ord for [T]where T: Ord,{ // The first non-equal element of both arrays determines // the ordering for the whole array. fn cmp(self, other: [T]) -> Ordering { let self_len = self.len(); let other_len = other.len(); let min_len = if self_len < other_len { self_len } else { other_len }; let mut result = Ordering::equal(); for i in 0..min_len { if result == Ordering::equal() { result = self[i].cmp(other[i]); } } if result != Ordering::equal() { result } else { self_len.cmp(other_len) } }}comptime fn make_tuple_ord_body(n: u32) -> Quoted { let last = n - 1u32; let mut body = if last == 1 { f"let result = self.0.cmp(other.0);".as_ctstring() } else { f"let mut result = self.0.cmp(other.0);".as_ctstring() }; for i in 1u32..last { body = body.append_fmtstr( f" if result == Ordering::equal() {{ result = self.{i}.cmp(other.{i}); }}", ); } body = body.append_fmtstr( f" if result != Ordering::equal() {{ result }} else {{ self.{last}.cmp(other.{last}) }}", ); f"{body}".quoted_contents()}impl<A: Ord> Ord for (A,) { fn cmp(self, other: (A,)) -> Ordering { self.0.cmp(other.0) }}impl<A: Ord, B: Ord> Ord for (A, B) { fn cmp(self, other: (A, B)) -> Ordering { make_tuple_ord_body!(2u32) }}impl<A: Ord, B: Ord, C: Ord> Ord for (A, B, C) { fn cmp(self, other: (A, B, C)) -> Ordering { make_tuple_ord_body!(3u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord> Ord for (A, B, C, D) { fn cmp(self, other: (A, B, C, D)) -> Ordering { make_tuple_ord_body!(4u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord, E: Ord> Ord for (A, B, C, D, E) { fn cmp(self, other: (A, B, C, D, E)) -> Ordering { make_tuple_ord_body!(5u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord> Ord for (A, B, C, D, E, F) { fn cmp(self, other: (A, B, C, D, E, F)) -> Ordering { make_tuple_ord_body!(6u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord> Ord for (A, B, C, D, E, F, G) { fn cmp(self, other: (A, B, C, D, E, F, G)) -> Ordering { make_tuple_ord_body!(7u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord> Ord for (A, B, C, D, E, F, G, H) { fn cmp(self, other: (A, B, C, D, E, F, G, H)) -> Ordering { make_tuple_ord_body!(8u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord, I: Ord> Ord for (A, B, C, D, E, F, G, H, I) { fn cmp(self, other: (A, B, C, D, E, F, G, H, I)) -> Ordering { make_tuple_ord_body!(9u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord, I: Ord, J: Ord> Ord for (A, B, C, D, E, F, G, H, I, J) { fn cmp(self, other: (A, B, C, D, E, F, G, H, I, J)) -> Ordering { make_tuple_ord_body!(10u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord, I: Ord, J: Ord, K: Ord> Ord for (A, B, C, D, E, F, G, H, I, J, K) { fn cmp(self, other: (A, B, C, D, E, F, G, H, I, J, K)) -> Ordering { make_tuple_ord_body!(11u32) }}impl<A: Ord, B: Ord, C: Ord, D: Ord, E: Ord, F: Ord, G: Ord, H: Ord, I: Ord, J: Ord, K: Ord, L: Ord> Ord for (A, B, C, D, E, F, G, H, I, J, K, L) { fn cmp(self, other: (A, B, C, D, E, F, G, H, I, J, K, L)) -> Ordering { make_tuple_ord_body!(12u32) }}/// Compares and returns the maximum of two values.////// Returns the second argument if the comparison determines them to be equal.////// # Examples////// ```/// use std::cmp;////// assert_eq(cmp::max(1, 2), 2);/// assert_eq(cmp::max(2, 2), 2);/// ```pub fn max<T>(v1: T, v2: T) -> Twhere T: Ord,{ if v1 > v2 { v1 } else { v2 }}/// Compares and returns the minimum of two values.////// Returns the first argument if the comparison determines them to be equal.////// # Examples////// ```/// use std::cmp;////// assert_eq(cmp::min(1, 2), 1);/// assert_eq(cmp::min(2, 2), 2);/// ```pub fn min<T>(v1: T, v2: T) -> Twhere T: Ord,{ if v1 > v2 { v2 } else { v1 }}mod cmp_tests { use crate::meta::unquote; use super::{Eq, max, min, Ord, Ordering}; #[test] fn sanity_check_min() { assert_eq(min(0_u64, 1), 0); assert_eq(min(0_u64, 0), 0); assert_eq(min(1_u64, 1), 1); assert_eq(min(255_u8, 0), 0); } #[test] fn sanity_check_max() { assert_eq(max(0_u64, 1), 1); assert_eq(max(0_u64, 0), 0); assert_eq(max(1_u64, 1), 1); assert_eq(max(255_u8, 0), 255); } #[test] fn correctly_handles_unequal_length_vectors() { let vector_1 = [0, 1, 2, 3].as_vector(); let vector_2 = [0, 1, 2].as_vector(); assert(!vector_1.eq(vector_2)); } #[test] fn lexicographic_ordering_for_vectors() { assert( [2_u32].as_vector().cmp([1_u32, 1_u32, 1_u32].as_vector()) == super::Ordering::greater(), ); assert( [1_u32, 2_u32].as_vector().cmp([1_u32, 2_u32, 3_u32].as_vector()) == super::Ordering::less(), ); } #[test] fn eq_unit() { assert(().eq(())); } #[test] fn eq_bool() { assert(false.eq(false)); assert(!(false.eq(true))); assert(!(true.eq(false))); assert(true.eq(true)); } #[test] fn eq_integers() { comptime { for typ in @[ quote { u8 }, quote { i8 }, quote { u16 }, quote { i16 }, quote { u32 }, quote { i32 }, quote { u64 }, quote { i64 }, quote { u128 }, quote { Field }, ] { let one = f"1_{typ}".quoted_contents(); let two = f"2_{typ}".quoted_contents(); unquote!( quote { assert($one.eq($one)); assert(!($one.eq($two))); }, ); } } } #[test] fn eq_tuples() { comptime { for i in 1..=12 { let mut tuple1 = @[]; let mut tuple2 = @[]; for _ in 0..i - 1 { tuple1 = tuple1.push_back(quote { 0 }); tuple2 = tuple2.push_back(quote { 0 }); } tuple1 = tuple1.push_back(quote { 0 }); tuple2 = tuple2.push_back(quote { 1 }); let tuple1 = tuple1.join(quote { , }); let tuple2 = tuple2.join(quote { , }); let tuple1 = quote { ($tuple1,) }; let tuple2 = quote { ($tuple2,) }; unquote!( quote { assert($tuple1.eq($tuple1)); assert(!($tuple1.eq($tuple2))); }, ) } } } #[test] fn cmp_unit() { assert_eq(().cmp(()), Ordering::equal()); } #[test] fn cmp_bool() { assert_eq(false.cmp(true), Ordering::less()); assert_eq(false.cmp(false), Ordering::equal()); assert_eq(true.cmp(true), Ordering::equal()); assert_eq(true.cmp(false), Ordering::greater()); } #[test] fn cmp_integers() { comptime { for typ in @[ quote { u8 }, quote { i8 }, quote { u16 }, quote { i16 }, quote { u32 }, quote { i32 }, quote { u64 }, quote { i64 }, quote { u128 }, ] { let one = f"1_{typ}".quoted_contents(); let two = f"2_{typ}".quoted_contents(); unquote!( quote { assert_eq($one.cmp($two), Ordering::less()); assert_eq($one.cmp($one), Ordering::equal()); assert_eq($two.cmp($one), Ordering::greater()); }, ); } } } #[test] fn cmp_tuples() { comptime { for i in 1..=12 { let mut tuple1 = @[]; let mut tuple2 = @[]; for _ in 0..i - 1 { tuple1 = tuple1.push_back(quote { 0_u8 }); tuple2 = tuple2.push_back(quote { 0_u8 }); } tuple1 = tuple1.push_back(quote { 0_u8 }); tuple2 = tuple2.push_back(quote { 1_u8 }); let tuple1 = tuple1.join(quote { , }); let tuple2 = tuple2.join(quote { , }); let tuple1 = quote { ($tuple1,) }; let tuple2 = quote { ($tuple2,) }; unquote!( quote { assert_eq($tuple1.cmp($tuple1), Ordering::equal()); assert_eq($tuple1.cmp($tuple2), Ordering::less()); assert_eq($tuple2.cmp($tuple1), Ordering::greater()); }, ) } } } #[test] fn cmp_array() { assert_eq([1_u8, 2, 3].cmp([1, 2, 3]), Ordering::equal()); assert_eq([1_u8, 2, 3].cmp([1, 3, 2]), Ordering::less()); assert_eq([1_u8, 3, 3].cmp([1, 2, 3]), Ordering::greater()); } #[test] fn cmp_vectors() { // Equal lengths assert_eq(@[1_u8, 2, 3].cmp(@[1, 2, 3]), Ordering::equal()); assert_eq(@[1_u8, 3, 3].cmp(@[1, 2, 3]), Ordering::greater()); assert_eq(@[1_u8, 2, 3].cmp(@[1, 3, 3]), Ordering::less()); // Different lengths assert_eq(@[1_u8, 2].cmp(@[1, 2, 3]), Ordering::less()); assert_eq(@[1_u8, 2, 3].cmp(@[1, 2]), Ordering::greater()); assert_eq(@[10_u8, 0].cmp(@[9]), Ordering::greater()); assert_eq(@[9_u8, 0].cmp(@[10]), Ordering::less()); assert_eq(@[9_u8].cmp(@[10, 0]), Ordering::less()); assert_eq(@[10_u8].cmp(@[9, 0]), Ordering::greater()); }}pub mod bn254;use crate::{runtime::is_unconstrained, static_assert};use bn254::lt as bn254_lt;impl Field { /// Asserts that `self` can be represented in `bit_size` bits. /// /// # Failures /// Causes a constraint failure for `Field` values exceeding `2^{bit_size}`. // docs:start:assert_max_bit_size pub fn assert_max_bit_size<let BIT_SIZE: u32>(self) { // docs:end:assert_max_bit_size static_assert( BIT_SIZE < modulus_num_bits() as u32, "BIT_SIZE must be less than modulus_num_bits", ); __assert_max_bit_size(self, BIT_SIZE); } /// Decomposes `self` into its little endian bit decomposition as a `[bool; N]` array. /// This array will be zero padded should not all bits be necessary to represent `self`. /// /// # Failures /// Causes a constraint failure for `Field` values exceeding `2^N` as the resulting array will not /// be able to represent the original `Field`. /// /// # Safety /// The bit decomposition returned is canonical and is guaranteed to not overflow the modulus. // docs:start:to_le_bits pub fn to_le_bits<let N: u32>(self: Self) -> [bool; N] { // docs:end:to_le_bits let bits = __to_le_bits(self); if !is_unconstrained() { // Ensure that the byte decomposition does not overflow the modulus let p = modulus_le_bits(); assert(bits.len() <= p.len()); let mut ok = bits.len() != p.len(); for i in 0..N { if !ok { if (bits[N - 1 - i] != p[N - 1 - i]) { assert(p[N - 1 - i]); ok = true; } } } assert(ok); } bits } /// Decomposes `self` into its big endian bit decomposition as a `[bool; N]` array. /// This array will be zero padded should not all bits be necessary to represent `self`. /// /// # Failures /// Causes a constraint failure for `Field` values exceeding `2^N` as the resulting array will not /// be able to represent the original `Field`. /// /// # Safety /// The bit decomposition returned is canonical and is guaranteed to not overflow the modulus. // docs:start:to_be_bits pub fn to_be_bits<let N: u32>(self: Self) -> [bool; N] { // docs:end:to_be_bits let bits = __to_be_bits(self); if !is_unconstrained() { // Ensure that the decomposition does not overflow the modulus let p = modulus_be_bits(); assert(bits.len() <= p.len()); let mut ok = bits.len() != p.len(); for i in 0..N { if !ok { if (bits[i] != p[i]) { assert(p[i]); ok = true; } } } assert(ok); } bits } /// Decomposes `self` into its little endian byte decomposition as a `[u8;N]` array /// This array will be zero padded should not all bytes be necessary to represent `self`. /// /// # Failures /// The length N of the array must be big enough to contain all the bytes of the 'self', /// and no more than the number of bytes required to represent the field modulus /// /// # Safety /// The result is ensured to be the canonical decomposition of the field element // docs:start:to_le_bytes pub fn to_le_bytes<let N: u32>(self: Self) -> [u8; N] { // docs:end:to_le_bytes static_assert( N <= modulus_le_bytes().len(), "N must be less than or equal to modulus_le_bytes().len()", ); // Compute the byte decomposition let bytes = self.to_le_radix(256); if !is_unconstrained() { // Ensure that the byte decomposition does not overflow the modulus let p = modulus_le_bytes(); assert(bytes.len() <= p.len()); let mut ok = bytes.len() != p.len(); for i in 0..N { if !ok { if (bytes[N - 1 - i] != p[N - 1 - i]) { assert(bytes[N - 1 - i] < p[N - 1 - i]); ok = true; } } } assert(ok); } bytes } /// Decomposes `self` into its big endian byte decomposition as a `[u8;N]` array of length required to represent the field modulus /// This array will be zero padded should not all bytes be necessary to represent `self`. /// /// # Failures /// The length N of the array must be big enough to contain all the bytes of the 'self', /// and no more than the number of bytes required to represent the field modulus /// /// # Safety /// The result is ensured to be the canonical decomposition of the field element // docs:start:to_be_bytes pub fn to_be_bytes<let N: u32>(self: Self) -> [u8; N] { // docs:end:to_be_bytes static_assert( N <= modulus_le_bytes().len(), "N must be less than or equal to modulus_le_bytes().len()", ); // Compute the byte decomposition let bytes = self.to_be_radix(256); if !is_unconstrained() { // Ensure that the byte decomposition does not overflow the modulus let p = modulus_be_bytes(); assert(bytes.len() <= p.len()); let mut ok = bytes.len() != p.len(); for i in 0..N { if !ok { if (bytes[i] != p[i]) { assert(bytes[i] < p[i]); ok = true; } } } assert(ok); } bytes } fn to_le_radix<let N: u32>(self: Self, radix: u32) -> [u8; N] { // Brillig does not need an immediate radix if !crate::runtime::is_unconstrained() { static_assert(1 < radix, "radix must be greater than 1"); static_assert(radix <= 256, "radix must be less than or equal to 256"); static_assert(radix & (radix - 1) == 0, "radix must be a power of 2"); } __to_le_radix(self, radix) } fn to_be_radix<let N: u32>(self: Self, radix: u32) -> [u8; N] { // Brillig does not need an immediate radix if !crate::runtime::is_unconstrained() { static_assert(1 < radix, "radix must be greater than 1"); static_assert(radix <= 256, "radix must be less than or equal to 256"); static_assert(radix & (radix - 1) == 0, "radix must be a power of 2"); } __to_be_radix(self, radix) } // Returns self to the power of the given exponent value. // Caution: we assume the exponent fits into 32 bits // using a bigger bit size impacts negatively the performance and should be done only if the exponent does not fit in 32 bits pub fn pow_32(self, exponent: Field) -> Field { let mut r: Field = 1; let b: [bool; 32] = exponent.to_le_bits(); for i in 1..33 { r *= r; r = (b[32 - i] as Field) * (r * self) + (1 - b[32 - i] as Field) * r; } r } // Parity of (prime) Field element, i.e. sgn0(x mod p) = false if x `elem` {0, ..., p-1} is even, otherwise sgn0(x mod p) = true. pub fn sgn0(self) -> bool { (self as u8) % 2 == 1 } pub fn lt(self, another: Field) -> bool { if crate::compat::is_bn254() { bn254_lt(self, another) } else { lt_fallback(self, another) } } /// Convert a little endian byte array to a field element. /// If the provided byte array overflows the field modulus then the Field will silently wrap around. /// /// # Failures /// `N` must be no greater than the number of bytes required to represent the field modulus // docs:start:from_le_bytes pub fn from_le_bytes<let N: u32>(bytes: [u8; N]) -> Field { // docs:end:from_le_bytes static_assert( N <= modulus_le_bytes().len(), "N must be less than or equal to modulus_le_bytes().len()", ); let mut v = 1; let mut result = 0; for i in 0..N { result += (bytes[i] as Field) * v; v = v * 256; } result } /// Convert a big endian byte array to a field element. /// If the provided byte array overflows the field modulus then the Field will silently wrap around. /// /// # Failures /// `N` must be no greater than the number of bytes required to represent the field modulus // docs:start:from_be_bytes pub fn from_be_bytes<let N: u32>(bytes: [u8; N]) -> Field { // docs:end:from_be_bytes static_assert( N <= modulus_be_bytes().len(), "N must be less than or equal to modulus_be_bytes().len()", ); let mut v = 1; let mut result = 0; for i in 0..N { result += (bytes[N - 1 - i] as Field) * v; v = v * 256; } result } /// Convert a little endian byte array to a field element, asserting that the input is a /// canonical representation (strictly less than the field modulus). /// /// # Failures /// Causes a constraint failure if `bytes` encodes a value greater than or equal to the /// field modulus. // docs:start:from_le_bytes_checked pub fn from_le_bytes_checked<let N: u32>(bytes: [u8; N]) -> Field { // docs:end:from_le_bytes_checked let p = modulus_le_bytes(); let mut ok = N != p.len(); for i in 0..N { if !ok { if bytes[N - 1 - i] != p[N - 1 - i] { assert( bytes[N - 1 - i] < p[N - 1 - i], "input bytes are not a canonical field representation", ); ok = true; } } } assert(ok, "input bytes are not a canonical field representation"); Field::from_le_bytes(bytes) } /// Convert a big endian byte array to a field element, asserting that the input is a /// canonical representation (strictly less than the field modulus). /// /// # Failures /// Causes a constraint failure if `bytes` encodes a value greater than or equal to the /// field modulus. // docs:start:from_be_bytes_checked pub fn from_be_bytes_checked<let N: u32>(bytes: [u8; N]) -> Field { // docs:end:from_be_bytes_checked let p = modulus_be_bytes(); let mut ok = N != p.len(); for i in 0..N { if !ok { if bytes[i] != p[i] { assert(bytes[i] < p[i], "input bytes are not a canonical field representation"); ok = true; } } } assert(ok, "input bytes are not a canonical field representation"); Field::from_be_bytes(bytes) }}#[builtin(apply_range_constraint)]fn __assert_max_bit_size(value: Field, bit_size: u32) {}// `_radix` must be less than 256#[builtin(to_le_radix)]fn __to_le_radix<let N: u32>(value: Field, radix: u32) -> [u8; N] {}// `_radix` must be less than 256#[builtin(to_be_radix)]fn __to_be_radix<let N: u32>(value: Field, radix: u32) -> [u8; N] {}/// Decomposes `self` into its little endian bit decomposition as a `[bool; N]` array./// This array will be zero padded should not all bits be necessary to represent `self`.////// # Failures/// Causes a constraint failure for `Field` values exceeding `2^N` as the resulting array will not/// be able to represent the original `Field`.////// # Safety/// Values of `N` equal to or greater than the number of bits necessary to represent the `Field` modulus/// (e.g. 254 for the BN254 field) allow for multiple bit decompositions. This is due to how the `Field` will/// wrap around due to overflow when verifying the decomposition.#[builtin(to_le_bits)]fn __to_le_bits<let N: u32>(value: Field) -> [bool; N] {}/// Decomposes `self` into its big endian bit decomposition as a `[bool; N]` array./// This array will be zero padded should not all bits be necessary to represent `self`.////// # Failures/// Causes a constraint failure for `Field` values exceeding `2^N` as the resulting array will not/// be able to represent the original `Field`.////// # Safety/// Values of `N` equal to or greater than the number of bits necessary to represent the `Field` modulus/// (e.g. 254 for the BN254 field) allow for multiple bit decompositions. This is due to how the `Field` will/// wrap around due to overflow when verifying the decomposition.#[builtin(to_be_bits)]fn __to_be_bits<let N: u32>(value: Field) -> [bool; N] {}#[builtin(modulus_num_bits)]pub comptime fn modulus_num_bits() -> u64 {}#[builtin(modulus_be_bits)]pub comptime fn modulus_be_bits() -> [bool] {}#[builtin(modulus_le_bits)]pub comptime fn modulus_le_bits() -> [bool] {}#[builtin(modulus_be_bytes)]pub comptime fn modulus_be_bytes() -> [u8] {}#[builtin(modulus_le_bytes)]pub comptime fn modulus_le_bytes() -> [u8] {}/// An unconstrained only built in to efficiently compare fields.#[builtin(field_less_than)]unconstrained fn __field_less_than(x: Field, y: Field) -> bool {}pub(crate) unconstrained fn field_less_than(x: Field, y: Field) -> bool { __field_less_than(x, y)}fn lt_fallback(x: Field, y: Field) -> bool { if is_unconstrained() { // Safety: unconstrained context unsafe { field_less_than(x, y) } } else { let x_bytes: [u8; 32] = x.to_le_bytes(); let y_bytes: [u8; 32] = y.to_le_bytes(); let mut x_is_lt = false; let mut done = false; for i in 0..32 { if (!done) { let x_byte = x_bytes[32 - 1 - i] as u8; let y_byte = y_bytes[32 - 1 - i] as u8; let bytes_match = x_byte == y_byte; if !bytes_match { x_is_lt = x_byte < y_byte; done = true; } } } x_is_lt }}mod tests { use crate::{panic::panic, runtime, static_assert}; use super::{ field_less_than, modulus_be_bits, modulus_be_bytes, modulus_le_bits, modulus_le_bytes, }; #[test] // docs:start:to_be_bits_example fn test_to_be_bits() { let field = 2; let bits: [bool; 8] = field.to_be_bits(); assert_eq(bits, [false, false, false, false, false, false, true, false]); } // docs:end:to_be_bits_example #[test] // docs:start:to_le_bits_example fn test_to_le_bits() { let field = 2; let bits: [bool; 8] = field.to_le_bits(); assert_eq(bits, [false, true, false, false, false, false, false, false]); } // docs:end:to_le_bits_example #[test] // docs:start:to_be_bytes_example fn test_to_be_bytes() { let field = 2; let bytes: [u8; 8] = field.to_be_bytes(); assert_eq(bytes, [0, 0, 0, 0, 0, 0, 0, 2]); assert_eq(Field::from_be_bytes::<8>(bytes), field); } // docs:end:to_be_bytes_example #[test] // docs:start:to_le_bytes_example fn test_to_le_bytes() { let field = 2; let bytes: [u8; 8] = field.to_le_bytes(); assert_eq(bytes, [2, 0, 0, 0, 0, 0, 0, 0]); assert_eq(Field::from_le_bytes::<8>(bytes), field); } // docs:end:to_le_bytes_example #[test] // docs:start:to_be_radix_example fn test_to_be_radix() { // 259, in base 256, big endian, is [1, 3]. // i.e. 3 * 256^0 + 1 * 256^1 let field = 259; // The radix (in this example, 256) must be a power of 2. // The length of the returned byte array can be specified to be // >= the amount of space needed. let bytes: [u8; 8] = field.to_be_radix(256); assert_eq(bytes, [0, 0, 0, 0, 0, 0, 1, 3]); assert_eq(Field::from_be_bytes::<8>(bytes), field); } // docs:end:to_be_radix_example #[test] // docs:start:to_le_radix_example fn test_to_le_radix() { // 259, in base 256, little endian, is [3, 1]. // i.e. 3 * 256^0 + 1 * 256^1 let field = 259; // The radix (in this example, 256) must be a power of 2. // The length of the returned byte array can be specified to be // >= the amount of space needed. let bytes: [u8; 8] = field.to_le_radix(256); assert_eq(bytes, [3, 1, 0, 0, 0, 0, 0, 0]); assert_eq(Field::from_le_bytes::<8>(bytes), field); } // docs:end:to_le_radix_example #[test(should_fail_with = "radix must be greater than 1")] fn test_to_le_radix_1() { // this test should only fail in constrained mode if !runtime::is_unconstrained() { let field = 2; let _: [u8; 8] = field.to_le_radix(1); } else { panic("radix must be greater than 1"); } } // Updated test to account for Brillig restriction that radix must be greater than 2 #[test(should_fail_with = "radix must be greater than 1")] fn test_to_le_radix_brillig_1() { // this test should only fail in constrained mode if !runtime::is_unconstrained() { let field = 1; let _: [u8; 8] = field.to_le_radix(1); } else { panic("radix must be greater than 1"); } } #[test(should_fail_with = "radix must be a power of 2")] fn test_to_le_radix_3() { // this test should only fail in constrained mode if !runtime::is_unconstrained() { let field = 2; let _: [u8; 8] = field.to_le_radix(3); } else { panic("radix must be a power of 2"); } } #[test] fn test_to_le_radix_brillig_3() { // this test should only fail in constrained mode if runtime::is_unconstrained() { let field = 1; let out: [u8; 8] = field.to_le_radix(3); let mut expected = [0; 8]; expected[0] = 1; assert(out == expected, "unexpected result"); } } #[test(should_fail_with = "radix must be less than or equal to 256")] fn test_to_le_radix_512() { // this test should only fail in constrained mode if !runtime::is_unconstrained() { let field = 2; let _: [u8; 8] = field.to_le_radix(512); } else { panic("radix must be less than or equal to 256") } } #[test(should_fail_with = "Field failed to decompose into specified 16 limbs")] unconstrained fn not_enough_limbs_brillig() { let _: [u8; 16] = 0x100000000000000000000000000000000.to_le_bytes(); } #[test(should_fail_with = "Field failed to decompose into specified 16 limbs")] fn not_enough_limbs() { let _: [u8; 16] = 0x100000000000000000000000000000000.to_le_bytes(); } #[test(should_fail_with = "Field failed to decompose into specified 0 limbs")] unconstrained fn non_zero_field_to_le_bytes_zero_limbs() { let _: [u8; 0] = 5.to_le_bytes(); } #[test(should_fail_with = "Field failed to decompose into specified 0 limbs")] unconstrained fn non_zero_field_to_be_bytes_zero_limbs() { let _: [u8; 0] = 5.to_be_bytes(); } #[test] unconstrained fn test_field_less_than() { assert(field_less_than(0, 1)); assert(field_less_than(0, 0x100)); assert(field_less_than(0x100, 0 - 1)); assert(!field_less_than(0 - 1, 0)); } #[test] unconstrained fn test_large_field_values_unconstrained() { let large_field = 0xffffffffffffffff; let bits: [bool; 64] = large_field.to_le_bits(); assert_eq(bits[0], true); let bytes: [u8; 8] = large_field.to_le_bytes(); assert_eq(Field::from_le_bytes::<8>(bytes), large_field); let radix_bytes: [u8; 8] = large_field.to_le_radix(256); assert_eq(Field::from_le_bytes::<8>(radix_bytes), large_field); } #[test] fn test_large_field_values() { let large_val = 0xffffffffffffffff; let bits: [bool; 64] = large_val.to_le_bits(); assert_eq(bits[0], true); let bytes: [u8; 8] = large_val.to_le_bytes(); assert_eq(Field::from_le_bytes::<8>(bytes), large_val); let radix_bytes: [u8; 8] = large_val.to_le_radix(256); assert_eq(Field::from_le_bytes::<8>(radix_bytes), large_val); } #[test] fn test_decomposition_edge_cases() { let zero_bits: [bool; 8] = 0.to_le_bits(); assert_eq(zero_bits, [false; 8]); let zero_bytes: [u8; 8] = 0.to_le_bytes(); assert_eq(zero_bytes, [0; 8]); let one_bits: [bool; 8] = 1.to_le_bits(); let expected: [bool; 8] = [true, false, false, false, false, false, false, false]; assert_eq(one_bits, expected); let pow2_bits: [bool; 8] = 4.to_le_bits(); let expected: [bool; 8] = [false, false, true, false, false, false, false, false]; assert_eq(pow2_bits, expected); } #[test] fn test_pow_32() { assert_eq(2.pow_32(3), 8); assert_eq(3.pow_32(2), 9); assert_eq(5.pow_32(0), 1); assert_eq(7.pow_32(1), 7); assert_eq(2.pow_32(10), 1024); assert_eq(0.pow_32(5), 0); assert_eq(0.pow_32(0), 1); assert_eq(1.pow_32(100), 1); } #[test] fn test_sgn0() { assert_eq(0.sgn0(), false); assert_eq(2.sgn0(), false); assert_eq(4.sgn0(), false); assert_eq(100.sgn0(), false); assert_eq(1.sgn0(), true); assert_eq(3.sgn0(), true); assert_eq(5.sgn0(), true); assert_eq(101.sgn0(), true); } #[test(should_fail_with = "Field failed to decompose into specified 8 limbs")] fn test_bit_decomposition_overflow() { // 8 bits can't represent large field values let large_val = 0x1000000000000000; let _: [bool; 8] = large_val.to_le_bits(); } #[test(should_fail_with = "Field failed to decompose into specified 4 limbs")] fn test_byte_decomposition_overflow() { // 4 bytes can't represent large field values let large_val = 0x1000000000000000; let _: [u8; 4] = large_val.to_le_bytes(); } #[test] fn test_to_from_be_bytes_bn254_edge_cases() { if crate::compat::is_bn254() { // checking that decrementing this byte produces the expected 32 BE bytes for (modulus - 1) let mut p_minus_1_bytes: [u8; 32] = modulus_be_bytes().as_array(); assert(p_minus_1_bytes[32 - 1] > 0); p_minus_1_bytes[32 - 1] -= 1; let p_minus_1 = Field::from_be_bytes::<32>(p_minus_1_bytes); assert_eq(p_minus_1 + 1, 0); // checking that converting (modulus - 1) from and then to 32 BE bytes produces the same bytes let p_minus_1_converted_bytes: [u8; 32] = p_minus_1.to_be_bytes(); assert_eq(p_minus_1_converted_bytes, p_minus_1_bytes); // checking that incrementing this byte produces 32 BE bytes for (modulus + 1) let mut p_plus_1_bytes: [u8; 32] = modulus_be_bytes().as_array(); assert(p_plus_1_bytes[32 - 1] < 255); p_plus_1_bytes[32 - 1] += 1; let p_plus_1 = Field::from_be_bytes::<32>(p_plus_1_bytes); assert_eq(p_plus_1, 1); // checking that converting p_plus_1 to 32 BE bytes produces the same // byte set to 1 as p_plus_1_bytes and otherwise zeroes let mut p_plus_1_converted_bytes: [u8; 32] = p_plus_1.to_be_bytes(); assert_eq(p_plus_1_converted_bytes[32 - 1], 1); p_plus_1_converted_bytes[32 - 1] = 0; assert_eq(p_plus_1_converted_bytes, [0; 32]); // checking that Field::from_be_bytes::<32> on the Field modulus produces 0 assert_eq(modulus_be_bytes().len(), 32); let p = Field::from_be_bytes::<32>(modulus_be_bytes().as_array()); assert_eq(p, 0); // checking that converting 0 to 32 BE bytes produces 32 zeroes let p_bytes: [u8; 32] = 0.to_be_bytes(); assert_eq(p_bytes, [0; 32]); } } #[test] fn test_to_from_le_bytes_bn254_edge_cases() { if crate::compat::is_bn254() { // checking that decrementing this byte produces the expected 32 LE bytes for (modulus - 1) let mut p_minus_1_bytes: [u8; 32] = modulus_le_bytes().as_array(); assert(p_minus_1_bytes[0] > 0); p_minus_1_bytes[0] -= 1; let p_minus_1 = Field::from_le_bytes::<32>(p_minus_1_bytes); assert_eq(p_minus_1 + 1, 0); // checking that converting (modulus - 1) from and then to 32 BE bytes produces the same bytes let p_minus_1_converted_bytes: [u8; 32] = p_minus_1.to_le_bytes(); assert_eq(p_minus_1_converted_bytes, p_minus_1_bytes); // checking that incrementing this byte produces 32 LE bytes for (modulus + 1) let mut p_plus_1_bytes: [u8; 32] = modulus_le_bytes().as_array(); assert(p_plus_1_bytes[0] < 255); p_plus_1_bytes[0] += 1; let p_plus_1 = Field::from_le_bytes::<32>(p_plus_1_bytes); assert_eq(p_plus_1, 1); // checking that converting p_plus_1 to 32 LE bytes produces the same // byte set to 1 as p_plus_1_bytes and otherwise zeroes let mut p_plus_1_converted_bytes: [u8; 32] = p_plus_1.to_le_bytes(); assert_eq(p_plus_1_converted_bytes[0], 1); p_plus_1_converted_bytes[0] = 0; assert_eq(p_plus_1_converted_bytes, [0; 32]); // checking that Field::from_le_bytes::<32> on the Field modulus produces 0 assert_eq(modulus_le_bytes().len(), 32); let p = Field::from_le_bytes::<32>(modulus_le_bytes().as_array()); assert_eq(p, 0); // checking that converting 0 to 32 LE bytes produces 32 zeroes let p_bytes: [u8; 32] = 0.to_le_bytes(); assert_eq(p_bytes, [0; 32]); } } #[test] fn test_from_le_bytes_checked_accepts_modulus_minus_one() { if crate::compat::is_bn254() { let mut p_minus_1_bytes: [u8; 32] = modulus_le_bytes().as_array(); assert(p_minus_1_bytes[0] > 0); p_minus_1_bytes[0] -= 1; let p_minus_1 = Field::from_le_bytes_checked::<32>(p_minus_1_bytes); assert_eq(p_minus_1 + 1, 0); } } #[test(should_fail_with = "input bytes are not a canonical field representation")] fn test_from_le_bytes_checked_rejects_modulus() { if crate::compat::is_bn254() { let _ = Field::from_le_bytes_checked::<32>(modulus_le_bytes().as_array()); } else { panic("input bytes are not a canonical field representation"); } } #[test(should_fail_with = "input bytes are not a canonical field representation")] fn test_from_le_bytes_checked_rejects_modulus_plus_one() { if crate::compat::is_bn254() { let mut p_plus_1_bytes: [u8; 32] = modulus_le_bytes().as_array(); assert(p_plus_1_bytes[0] < 255); p_plus_1_bytes[0] += 1; let _ = Field::from_le_bytes_checked::<32>(p_plus_1_bytes); } else { panic("input bytes are not a canonical field representation"); } } #[test] fn test_from_be_bytes_checked_accepts_modulus_minus_one() { if crate::compat::is_bn254() { let mut p_minus_1_bytes: [u8; 32] = modulus_be_bytes().as_array(); assert(p_minus_1_bytes[32 - 1] > 0); p_minus_1_bytes[32 - 1] -= 1; let p_minus_1 = Field::from_be_bytes_checked::<32>(p_minus_1_bytes); assert_eq(p_minus_1 + 1, 0); } } #[test(should_fail_with = "input bytes are not a canonical field representation")] fn test_from_be_bytes_checked_rejects_modulus() { if crate::compat::is_bn254() { let _ = Field::from_be_bytes_checked::<32>(modulus_be_bytes().as_array()); } else { panic("input bytes are not a canonical field representation"); } } #[test(should_fail_with = "input bytes are not a canonical field representation")] fn test_from_be_bytes_checked_rejects_modulus_plus_one() { if crate::compat::is_bn254() { let mut p_plus_1_bytes: [u8; 32] = modulus_be_bytes().as_array(); assert(p_plus_1_bytes[32 - 1] < 255); p_plus_1_bytes[32 - 1] += 1; let _ = Field::from_be_bytes_checked::<32>(p_plus_1_bytes); } else { panic("input bytes are not a canonical field representation"); } } #[test] fn test_from_bytes_checked_small_n() { // For N < modulus_bytes().len(), the input cannot overflow the modulus, so the checked // variants behave identically to the unchecked ones. let le_bytes: [u8; 8] = [3, 1, 0, 0, 0, 0, 0, 0]; assert_eq(Field::from_le_bytes_checked::<8>(le_bytes), 259); let be_bytes: [u8; 8] = [0, 0, 0, 0, 0, 0, 1, 3]; assert_eq(Field::from_be_bytes_checked::<8>(be_bytes), 259); } /// Convert a little endian bit array to a field element. /// If the provided bit array overflows the field modulus then the Field will silently wrap around. fn from_le_bits<let N: u32>(bits: [bool; N]) -> Field { static_assert( N <= modulus_le_bits().len(), "N must be less than or equal to modulus_le_bits().len()", ); let mut v = 1; let mut result = 0; for i in 0..N { result += (bits[i] as Field) * v; v = v * 2; } result } /// Convert a big endian bit array to a field element. /// If the provided bit array overflows the field modulus then the Field will silently wrap around. fn from_be_bits<let N: u32>(bits: [bool; N]) -> Field { let mut v = 1; let mut result = 0; for i in 0..N { result += (bits[N - 1 - i] as Field) * v; v = v * 2; } result } #[test] fn test_to_from_be_bits_bn254_edge_cases() { if crate::compat::is_bn254() { // checking that decrementing this bit produces the expected 254 BE bits for (modulus - 1) let mut p_minus_1_bits: [bool; 254] = modulus_be_bits().as_array(); assert(p_minus_1_bits[254 - 1]); p_minus_1_bits[254 - 1] = false; let p_minus_1 = from_be_bits::<254>(p_minus_1_bits); assert_eq(p_minus_1 + 1, 0); // checking that converting (modulus - 1) from and then to 254 BE bits produces the same bits let p_minus_1_converted_bits: [bool; 254] = p_minus_1.to_be_bits(); assert_eq(p_minus_1_converted_bits, p_minus_1_bits); // checking that incrementing this bit produces 254 BE bits for (modulus + 4) let mut p_plus_4_bits: [bool; 254] = modulus_be_bits().as_array(); assert(!p_plus_4_bits[254 - 3]); p_plus_4_bits[254 - 3] = true; let p_plus_4 = from_be_bits::<254>(p_plus_4_bits); assert_eq(p_plus_4, 4); // checking that converting p_plus_4 to 254 BE bits produces the same // bit set to 1 as p_plus_4_bits and otherwise zeroes let mut p_plus_4_converted_bits: [bool; 254] = p_plus_4.to_be_bits(); assert(p_plus_4_converted_bits[254 - 3]); p_plus_4_converted_bits[254 - 3] = false; assert_eq(p_plus_4_converted_bits, [false; 254]); // checking that Field::from_be_bits::<254> on the Field modulus produces 0 assert_eq(modulus_be_bits().len(), 254); let p = from_be_bits::<254>(modulus_be_bits().as_array()); assert_eq(p, 0); // checking that converting 0 to 254 BE bits produces 254 false values let p_bits: [bool; 254] = 0.to_be_bits(); assert_eq(p_bits, [false; 254]); } } #[test] fn test_to_from_le_bits_bn254_edge_cases() { if crate::compat::is_bn254() { // checking that decrementing this bit produces the expected 254 LE bits for (modulus - 1) let mut p_minus_1_bits: [bool; 254] = modulus_le_bits().as_array(); assert(p_minus_1_bits[0]); p_minus_1_bits[0] = false; let p_minus_1 = from_le_bits::<254>(p_minus_1_bits); assert_eq(p_minus_1 + 1, 0); // checking that converting (modulus - 1) from and then to 254 BE bits produces the same bits let p_minus_1_converted_bits: [bool; 254] = p_minus_1.to_le_bits(); assert_eq(p_minus_1_converted_bits, p_minus_1_bits); // checking that incrementing this bit produces 254 LE bits for (modulus + 4) let mut p_plus_4_bits: [bool; 254] = modulus_le_bits().as_array(); assert(!p_plus_4_bits[2]); p_plus_4_bits[2] = true; let p_plus_4 = from_le_bits::<254>(p_plus_4_bits); assert_eq(p_plus_4, 4); // checking that converting p_plus_4 to 254 LE bits produces the same // bit set to 1 as p_plus_4_bits and otherwise zeroes let mut p_plus_4_converted_bits: [bool; 254] = p_plus_4.to_le_bits(); assert(p_plus_4_converted_bits[2]); p_plus_4_converted_bits[2] = false; assert_eq(p_plus_4_converted_bits, [false; 254]); // checking that Field::from_le_bits::<254> on the Field modulus produces 0 assert_eq(modulus_le_bits().len(), 254); let p = from_le_bits::<254>(modulus_le_bits().as_array()); assert_eq(p, 0); // checking that converting 0 to 254 LE bits produces 254 false values let p_bits: [bool; 254] = 0.to_le_bits(); assert_eq(p_bits, [false; 254]); } } #[test(should_fail_with = "call to assert_max_bit_size")] fn max_bit_size_too_large() { let x: Field = 0x010000; x.assert_max_bit_size::<16>(); }}// Exposed only for usage in `std::meta`pub(crate) mod poseidon2;use crate::default::Default;use crate::embedded_curve_ops::{ EmbeddedCurvePoint, EmbeddedCurveScalar, multi_scalar_mul, multi_scalar_mul_array_return,};use crate::meta::derive_via;use crate::static_assert;/// The size of the state accepted by the backend in `poseidon2_permutation`.global POSEIDON2_CONFIG_STATE_SIZE: u32 = poseidon2_config_state_size();#[foreign(sha256_compression)]// docs:start:sha256_compressionpub fn sha256_compression(input: [u32; 16], state: [u32; 8]) -> [u32; 8] {}// docs:end:sha256_compression#[foreign(keccakf1600)]// docs:start:keccakf1600pub fn keccakf1600(input: [u64; 25]) -> [u64; 25] {}// docs:end:keccakf1600pub mod keccak { #[deprecated("This function has been moved to std::hash::keccakf1600")] pub fn keccakf1600(input: [u64; 25]) -> [u64; 25] { super::keccakf1600(input) }}#[foreign(blake2s)]// docs:start:blake2spub fn blake2s<let N: u32>(input: [u8; N]) -> [u8; 32]// docs:end:blake2s{}// docs:start:blake3pub fn blake3<let N: u32>(input: [u8; N]) -> [u8; 32]// docs:end:blake3{ if crate::runtime::is_unconstrained() { // Temporary measure while Barretenberg is main proving system. // Please open an issue if you're working on another proving system and running into problems due to this. crate::static_assert( N <= 1024, "Barretenberg cannot prove blake3 hashes with inputs larger than 1024 bytes", ); } __blake3(input)}#[foreign(blake3)]fn __blake3<let N: u32>(input: [u8; N]) -> [u8; 32] {}// docs:start:pedersen_commitmentpub fn pedersen_commitment<let N: u32>(input: [Field; N]) -> EmbeddedCurvePoint { // docs:end:pedersen_commitment pedersen_commitment_with_separator(input, 0)}#[inline_always]pub fn pedersen_commitment_with_separator<let N: u32>( input: [Field; N], separator: u32,) -> EmbeddedCurvePoint { let mut points = [EmbeddedCurveScalar { lo: 0, hi: 0 }; N]; for i in 0..N { points[i] = EmbeddedCurveScalar::from_field(input[i]); } let generators = derive_generators("DEFAULT_DOMAIN_SEPARATOR".as_bytes(), separator); multi_scalar_mul(generators, points)}// docs:start:pedersen_hashpub fn pedersen_hash<let N: u32>(input: [Field; N]) -> Field// docs:end:pedersen_hash{ pedersen_hash_with_separator(input, 0)}#[no_predicates]pub fn pedersen_hash_with_separator<let N: u32>(input: [Field; N], separator: u32) -> Field { let mut scalars: [EmbeddedCurveScalar; N + 1] = [EmbeddedCurveScalar { lo: 0, hi: 0 }; N + 1]; let mut generators: [EmbeddedCurvePoint; N + 1] = [EmbeddedCurvePoint::point_at_infinity(); N + 1]; crate::assert_constant(separator); let domain_generators: [EmbeddedCurvePoint; N] = derive_generators("DEFAULT_DOMAIN_SEPARATOR".as_bytes(), separator); for i in 0..N { scalars[i] = EmbeddedCurveScalar::from_field(input[i]); generators[i] = domain_generators[i]; } scalars[N] = EmbeddedCurveScalar { lo: N as Field, hi: 0 as Field }; let length_generator: [EmbeddedCurvePoint; 1] = derive_generators("pedersen_hash_length".as_bytes(), 0); generators[N] = length_generator[0]; multi_scalar_mul_array_return(generators, scalars, true)[0].x}#[field(bn254)]#[inline_always]pub fn derive_generators<let N: u32, let M: u32>( domain_separator_bytes: [u8; M], starting_index: u32,) -> [EmbeddedCurvePoint; N] { crate::assert_constant(domain_separator_bytes); crate::assert_constant(starting_index); __derive_generators(domain_separator_bytes, starting_index)}#[builtin(derive_pedersen_generators)]#[field(bn254)]fn __derive_generators<let N: u32, let M: u32>( domain_separator_bytes: [u8; M], starting_index: u32,) -> [EmbeddedCurvePoint; N] {}pub fn poseidon2_permutation<let N: u32>(input: [Field; N]) -> [Field; N] { static_assert( N == POSEIDON2_CONFIG_STATE_SIZE, f"the input length must equal the state size in the Poseidon2 config; expected {POSEIDON2_CONFIG_STATE_SIZE}, got {N}", ); poseidon2_permutation_internal(input)}#[foreign(poseidon2_permutation)]fn poseidon2_permutation_internal<let N: u32>(input: [Field; N]) -> [Field; N] {}#[foreign(poseidon2_config_state_size)]comptime fn poseidon2_config_state_size() -> u32 {}// Generic hashing support.// Partially ported and impacted by rust.// Hash trait shall be implemented per type.#[derive_via(derive_hash)]pub trait Hash { fn hash<H>(self, state: &mut H) where H: Hasher;}// docs:start:derive_hashcomptime fn derive_hash(s: TypeDefinition) -> Quoted { let name = quote { $crate::hash::Hash }; let signature = quote { fn hash<H>(_self: Self, _state: &mut H) where H: $crate::hash::Hasher }; let for_each_field = |name| quote { _self.$name.hash(_state); }; crate::meta::make_trait_impl( s, name, signature, for_each_field, quote {}, |fields| fields, )}// docs:end:derive_hash// Hasher trait shall be implemented by algorithms to provide hash-agnostic means.// TODO: consider making the types generic here ([u8], [Field], etc.)pub trait Hasher { fn finish(self) -> Field; /// Returns the hash value without consuming the hasher. /// Override this for more efficient implementations that avoid copying. /// TODO: deprecate finish() and replace it fn finish_ref(&self) -> Field { (*self).finish() } fn write(&mut self, input: Field);}// BuildHasher is a factory trait, responsible for production of specific Hasher.pub trait BuildHasher { type H: Hasher; fn build_hasher(self) -> H;}pub struct BuildHasherDefault<H>;impl<H> BuildHasher for BuildHasherDefault<H>where H: Hasher + Default,{ type H = H; fn build_hasher(_self: Self) -> H { H::default() }}impl<H> Default for BuildHasherDefault<H>where H: Hasher + Default,{ fn default() -> Self { BuildHasherDefault {} }}impl Hash for Field { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self); }}impl Hash for u8 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as Field); }}impl Hash for u16 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as Field); }}impl Hash for u32 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as Field); }}impl Hash for u64 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as Field); }}impl Hash for u128 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as Field); }}impl Hash for i8 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as u8 as Field); }}impl Hash for i16 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as u16 as Field); }}impl Hash for i32 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as u32 as Field); }}impl Hash for i64 { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as u64 as Field); }}impl Hash for bool { fn hash<H>(self, state: &mut H) where H: Hasher, { H::write(state, self as Field); }}impl Hash for () { fn hash<H>(_self: Self, _state: &mut H) where H: Hasher, {}}impl<T, let N: u32> Hash for [T; N]where T: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { for elem in self { elem.hash(state); } }}impl<T> Hash for [T]where T: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.len().hash(state); for elem in self { elem.hash(state); } }}impl<A> Hash for (A,)where A: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); }}impl<A, B> Hash for (A, B)where A: Hash, B: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); }}impl<A, B, C> Hash for (A, B, C)where A: Hash, B: Hash, C: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); }}impl<A, B, C, D> Hash for (A, B, C, D)where A: Hash, B: Hash, C: Hash, D: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); }}impl<A, B, C, D, E> Hash for (A, B, C, D, E)where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); self.4.hash(state); }}impl<A, B, C, D, E, F> Hash for (A, B, C, D, E, F)where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); self.4.hash(state); self.5.hash(state); }}impl<A, B, C, D, E, F, G> Hash for (A, B, C, D, E, F, G)where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); self.4.hash(state); self.5.hash(state); self.6.hash(state); }}impl<A, B, C, D, E, F, G, H_> Hash for (A, B, C, D, E, F, G, H_)where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H_: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); self.4.hash(state); self.5.hash(state); self.6.hash(state); self.7.hash(state); }}impl<A, B, C, D, E, F, G, H_, I> Hash for (A, B, C, D, E, F, G, H_, I)where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H_: Hash, I: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); self.4.hash(state); self.5.hash(state); self.6.hash(state); self.7.hash(state); self.8.hash(state); }}impl<A, B, C, D, E, F, G, H_, I, J> Hash for (A, B, C, D, E, F, G, H_, I, J)where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H_: Hash, I: Hash, J: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); self.4.hash(state); self.5.hash(state); self.6.hash(state); self.7.hash(state); self.8.hash(state); self.9.hash(state); }}impl<A, B, C, D, E, F, G, H_, I, J, K> Hash for (A, B, C, D, E, F, G, H_, I, J, K)where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H_: Hash, I: Hash, J: Hash, K: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); self.4.hash(state); self.5.hash(state); self.6.hash(state); self.7.hash(state); self.8.hash(state); self.9.hash(state); self.10.hash(state); }}impl<A, B, C, D, E, F, G, H_, I, J, K, L> Hash for (A, B, C, D, E, F, G, H_, I, J, K, L)where A: Hash, B: Hash, C: Hash, D: Hash, E: Hash, F: Hash, G: Hash, H_: Hash, I: Hash, J: Hash, K: Hash, L: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self.0.hash(state); self.1.hash(state); self.2.hash(state); self.3.hash(state); self.4.hash(state); self.5.hash(state); self.6.hash(state); self.7.hash(state); self.8.hash(state); self.9.hash(state); self.10.hash(state); self.11.hash(state); }}// Some test vectors for Pedersen hash and Pedersen Commitment.// They have been generated using the same functions so the tests are for now useless// but they will be useful when we switch to Noir implementation.#[test]fn assert_pedersen() { assert_eq( pedersen_hash_with_separator([1], 1), 0x1b3f4b1a83092a13d8d1a59f7acb62aba15e7002f4440f2275edb99ebbc2305f, ); assert_eq( pedersen_commitment_with_separator([1], 1), EmbeddedCurvePoint { x: 0x054aa86a73cb8a34525e5bbed6e43ba1198e860f5f3950268f71df4591bde402, y: 0x209dcfbf2cfb57f9f6046f44d71ac6faf87254afc7407c04eb621a6287cac126, }, ); assert_eq( pedersen_hash_with_separator([1, 2], 2), 0x26691c129448e9ace0c66d11f0a16d9014a9e8498ee78f4d69f0083168188255, ); assert_eq( pedersen_commitment_with_separator([1, 2], 2), EmbeddedCurvePoint { x: 0x2e2b3b191e49541fe468ec6877721d445dcaffe41728df0a0eafeb15e87b0753, y: 0x2ff4482400ad3a6228be17a2af33e2bcdf41be04795f9782bd96efe7e24f8778, }, ); assert_eq( pedersen_hash_with_separator([1, 2, 3], 3), 0x0bc694b7a1f8d10d2d8987d07433f26bd616a2d351bc79a3c540d85b6206dbe4, ); assert_eq( pedersen_commitment_with_separator([1, 2, 3], 3), EmbeddedCurvePoint { x: 0x1fee4e8cf8d2f527caa2684236b07c4b1bad7342c01b0f75e9a877a71827dc85, y: 0x2f9fedb9a090697ab69bf04c8bc15f7385b3e4b68c849c1536e5ae15ff138fd1, }, ); assert_eq( pedersen_hash_with_separator([1, 2, 3, 4], 4), 0xdae10fb32a8408521803905981a2b300d6a35e40e798743e9322b223a5eddc, ); assert_eq( pedersen_commitment_with_separator([1, 2, 3, 4], 4), EmbeddedCurvePoint { x: 0x07ae3e202811e1fca39c2d81eabe6f79183978e6f12be0d3b8eda095b79bdbc9, y: 0x0afc6f892593db6fbba60f2da558517e279e0ae04f95758587760ba193145014, }, ); assert_eq( pedersen_hash_with_separator([1, 2, 3, 4, 5], 5), 0xfc375b062c4f4f0150f7100dfb8d9b72a6d28582dd9512390b0497cdad9c22, ); assert_eq( pedersen_commitment_with_separator([1, 2, 3, 4, 5], 5), EmbeddedCurvePoint { x: 0x1754b12bd475a6984a1094b5109eeca9838f4f81ac89c5f0a41dbce53189bb29, y: 0x2da030e3cfcdc7ddad80eaf2599df6692cae0717d4e9f7bfbee8d073d5d278f7, }, ); assert_eq( pedersen_hash_with_separator([1, 2, 3, 4, 5, 6], 6), 0x1696ed13dc2730062a98ac9d8f9de0661bb98829c7582f699d0273b18c86a572, ); assert_eq( pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6], 6), EmbeddedCurvePoint { x: 0x190f6c0e97ad83e1e28da22a98aae156da083c5a4100e929b77e750d3106a697, y: 0x1f4b60f34ef91221a0b49756fa0705da93311a61af73d37a0c458877706616fb, }, ); assert_eq( pedersen_hash_with_separator([1, 2, 3, 4, 5, 6, 7], 7), 0x128c0ff144fc66b6cb60eeac8a38e23da52992fc427b92397a7dffd71c45ede3, ); assert_eq( pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6, 7], 7), EmbeddedCurvePoint { x: 0x015441e9d29491b06563fac16fc76abf7a9534c715421d0de85d20dbe2965939, y: 0x1d2575b0276f4e9087e6e07c2cb75aa1baafad127af4be5918ef8a2ef2fea8fc, }, ); assert_eq( pedersen_hash_with_separator([1, 2, 3, 4, 5, 6, 7, 8], 8), 0x2f960e117482044dfc99d12fece2ef6862fba9242be4846c7c9a3e854325a55c, ); assert_eq( pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6, 7, 8], 8), EmbeddedCurvePoint { x: 0x1657737676968887fceb6dd516382ea13b3a2c557f509811cd86d5d1199bc443, y: 0x1f39f0cb569040105fa1e2f156521e8b8e08261e635a2b210bdc94e8d6d65f77, }, ); assert_eq( pedersen_hash_with_separator([1, 2, 3, 4, 5, 6, 7, 8, 9], 9), 0x0c96db0790602dcb166cc4699e2d306c479a76926b81c2cb2aaa92d249ec7be7, ); assert_eq( pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6, 7, 8, 9], 9), EmbeddedCurvePoint { x: 0x0a3ceae42d14914a432aa60ec7fded4af7dad7dd4acdbf2908452675ec67e06d, y: 0xfc19761eaaf621ad4aec9a8b2e84a4eceffdba78f60f8b9391b0bd9345a2f2, }, ); assert_eq( pedersen_hash_with_separator([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10), 0x2cd37505871bc460a62ea1e63c7fe51149df5d0801302cf1cbc48beb8dff7e94, ); assert_eq( pedersen_commitment_with_separator([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 10), EmbeddedCurvePoint { x: 0x2fb3f8b3d41ddde007c8c3c62550f9a9380ee546fcc639ffbb3fd30c8d8de30c, y: 0x300783be23c446b11a4c0fabf6c91af148937cea15fcf5fb054abf7f752ee245, }, );}use crate::convert::AsPrimitive;// docs:start:add-traitpub trait Add { fn add(self, other: Self) -> Self;}// docs:end:add-traitimpl Add for Field { fn add(self, other: Field) -> Field { self + other }}impl Add for u128 { fn add(self, other: u128) -> u128 { self + other }}impl Add for u64 { fn add(self, other: u64) -> u64 { self + other }}impl Add for u32 { fn add(self, other: u32) -> u32 { self + other }}impl Add for u16 { fn add(self, other: u16) -> u16 { self + other }}impl Add for u8 { fn add(self, other: u8) -> u8 { self + other }}impl Add for i8 { fn add(self, other: i8) -> i8 { self + other }}impl Add for i16 { fn add(self, other: i16) -> i16 { self + other }}impl Add for i32 { fn add(self, other: i32) -> i32 { self + other }}impl Add for i64 { fn add(self, other: i64) -> i64 { self + other }}// docs:start:sub-traitpub trait Sub { fn sub(self, other: Self) -> Self;}// docs:end:sub-traitimpl Sub for Field { fn sub(self, other: Field) -> Field { self - other }}impl Sub for u128 { fn sub(self, other: u128) -> u128 { self - other }}impl Sub for u64 { fn sub(self, other: u64) -> u64 { self - other }}impl Sub for u32 { fn sub(self, other: u32) -> u32 { self - other }}impl Sub for u16 { fn sub(self, other: u16) -> u16 { self - other }}impl Sub for u8 { fn sub(self, other: u8) -> u8 { self - other }}impl Sub for i8 { fn sub(self, other: i8) -> i8 { self - other }}impl Sub for i16 { fn sub(self, other: i16) -> i16 { self - other }}impl Sub for i32 { fn sub(self, other: i32) -> i32 { self - other }}impl Sub for i64 { fn sub(self, other: i64) -> i64 { self - other }}// docs:start:mul-traitpub trait Mul { fn mul(self, other: Self) -> Self;}// docs:end:mul-traitimpl Mul for Field { fn mul(self, other: Field) -> Field { self * other }}impl Mul for u128 { fn mul(self, other: u128) -> u128 { self * other }}impl Mul for u64 { fn mul(self, other: u64) -> u64 { self * other }}impl Mul for u32 { fn mul(self, other: u32) -> u32 { self * other }}impl Mul for u16 { fn mul(self, other: u16) -> u16 { self * other }}impl Mul for u8 { fn mul(self, other: u8) -> u8 { self * other }}impl Mul for i8 { fn mul(self, other: i8) -> i8 { self * other }}impl Mul for i16 { fn mul(self, other: i16) -> i16 { self * other }}impl Mul for i32 { fn mul(self, other: i32) -> i32 { self * other }}impl Mul for i64 { fn mul(self, other: i64) -> i64 { self * other }}// docs:start:div-traitpub trait Div { fn div(self, other: Self) -> Self;}// docs:end:div-traitimpl Div for Field { fn div(self, other: Field) -> Field { self / other }}impl Div for u128 { fn div(self, other: u128) -> u128 { self / other }}impl Div for u64 { fn div(self, other: u64) -> u64 { self / other }}impl Div for u32 { fn div(self, other: u32) -> u32 { self / other }}impl Div for u16 { fn div(self, other: u16) -> u16 { self / other }}impl Div for u8 { fn div(self, other: u8) -> u8 { self / other }}impl Div for i8 { fn div(self, other: i8) -> i8 { self / other }}impl Div for i16 { fn div(self, other: i16) -> i16 { self / other }}impl Div for i32 { fn div(self, other: i32) -> i32 { self / other }}impl Div for i64 { fn div(self, other: i64) -> i64 { self / other }}// docs:start:rem-traitpub trait Rem { fn rem(self, other: Self) -> Self;}// docs:end:rem-traitimpl Rem for u128 { fn rem(self, other: u128) -> u128 { self % other }}impl Rem for u64 { fn rem(self, other: u64) -> u64 { self % other }}impl Rem for u32 { fn rem(self, other: u32) -> u32 { self % other }}impl Rem for u16 { fn rem(self, other: u16) -> u16 { self % other }}impl Rem for u8 { fn rem(self, other: u8) -> u8 { self % other }}impl Rem for i8 { fn rem(self, other: i8) -> i8 { self % other }}impl Rem for i16 { fn rem(self, other: i16) -> i16 { self % other }}impl Rem for i32 { fn rem(self, other: i32) -> i32 { self % other }}impl Rem for i64 { fn rem(self, other: i64) -> i64 { self % other }}// docs:start:neg-traitpub trait Neg { fn neg(self) -> Self;}// docs:end:neg-trait// docs:start:neg-trait-implsimpl Neg for Field { fn neg(self) -> Field { -self }}impl Neg for i8 { fn neg(self) -> i8 { -self }}impl Neg for i16 { fn neg(self) -> i16 { -self }}impl Neg for i32 { fn neg(self) -> i32 { -self }}impl Neg for i64 { fn neg(self) -> i64 { -self }}// docs:end:neg-trait-impls// docs:start:wrapping-add-traitpub trait WrappingAdd { fn wrapping_add(self, y: Self) -> Self;}// docs:end:wrapping-add-traitimpl WrappingAdd for u8 { fn wrapping_add(self: u8, y: u8) -> u8 { wrapping_add_hlp(self, y) }}impl WrappingAdd for u16 { fn wrapping_add(self: u16, y: u16) -> u16 { wrapping_add_hlp(self, y) }}impl WrappingAdd for u32 { fn wrapping_add(self: u32, y: u32) -> u32 { wrapping_add_hlp(self, y) }}impl WrappingAdd for u64 { fn wrapping_add(self: u64, y: u64) -> u64 { wrapping_add_hlp(self, y) }}impl WrappingAdd for u128 { fn wrapping_add(self: u128, y: u128) -> u128 { wrapping_add_hlp(self, y) }}impl WrappingAdd for i8 { fn wrapping_add(self: i8, y: i8) -> i8 { let x = self as u8; x.wrapping_add(y as u8) as i8 }}impl WrappingAdd for i16 { fn wrapping_add(self: i16, y: i16) -> i16 { let x = self as u16; x.wrapping_add(y as u16) as i16 }}impl WrappingAdd for i32 { fn wrapping_add(self: i32, y: i32) -> i32 { let x = self as u32; x.wrapping_add(y as u32) as i32 }}impl WrappingAdd for i64 { fn wrapping_add(self: i64, y: i64) -> i64 { let x = self as u64; x.wrapping_add(y as u64) as i64 }}impl WrappingAdd for Field { fn wrapping_add(self: Field, y: Field) -> Field { self + y }}// docs:start:wrapping-sub-traitpub trait WrappingSub { fn wrapping_sub(self, y: Self) -> Self;}// docs:start:wrapping-sub-traitimpl WrappingSub for u8 { fn wrapping_sub(self: u8, y: u8) -> u8 { wrapping_sub_hlp(self, y) as u8 }}impl WrappingSub for u16 { fn wrapping_sub(self: u16, y: u16) -> u16 { wrapping_sub_hlp(self, y) as u16 }}impl WrappingSub for u32 { fn wrapping_sub(self: u32, y: u32) -> u32 { wrapping_sub_hlp(self, y) as u32 }}impl WrappingSub for u64 { fn wrapping_sub(self: u64, y: u64) -> u64 { wrapping_sub_hlp(self, y) as u64 }}impl WrappingSub for u128 { fn wrapping_sub(self: u128, y: u128) -> u128 { wrapping_sub_hlp(self, y) as u128 }}impl WrappingSub for i8 { fn wrapping_sub(self: i8, y: i8) -> i8 { let x = self as u8; x.wrapping_sub(y as u8) as i8 }}impl WrappingSub for i16 { fn wrapping_sub(self: i16, y: i16) -> i16 { let x = self as u16; x.wrapping_sub(y as u16) as i16 }}impl WrappingSub for i32 { fn wrapping_sub(self: i32, y: i32) -> i32 { let x = self as u32; x.wrapping_sub(y as u32) as i32 }}impl WrappingSub for i64 { fn wrapping_sub(self: i64, y: i64) -> i64 { let x = self as u64; x.wrapping_sub(y as u64) as i64 }}impl WrappingSub for Field { fn wrapping_sub(self: Field, y: Field) -> Field { self - y }}// docs:start:wrapping-mul-traitpub trait WrappingMul { fn wrapping_mul(self, y: Self) -> Self;}// docs:start:wrapping-mul-traitimpl WrappingMul for u8 { fn wrapping_mul(self: u8, y: u8) -> u8 { wrapping_mul_hlp(self, y) }}impl WrappingMul for u16 { fn wrapping_mul(self: u16, y: u16) -> u16 { wrapping_mul_hlp(self, y) }}impl WrappingMul for u32 { fn wrapping_mul(self: u32, y: u32) -> u32 { wrapping_mul_hlp(self, y) }}impl WrappingMul for u64 { fn wrapping_mul(self: u64, y: u64) -> u64 { wrapping_mul_hlp(self, y) }}impl WrappingMul for i8 { fn wrapping_mul(self: i8, y: i8) -> i8 { let x = self as u8; x.wrapping_mul(y as u8) as i8 }}impl WrappingMul for i16 { fn wrapping_mul(self: i16, y: i16) -> i16 { let x = self as u16; x.wrapping_mul(y as u16) as i16 }}impl WrappingMul for i32 { fn wrapping_mul(self: i32, y: i32) -> i32 { let x = self as u32; x.wrapping_mul(y as u32) as i32 }}impl WrappingMul for i64 { fn wrapping_mul(self: i64, y: i64) -> i64 { let x = self as u64; x.wrapping_mul(y as u64) as i64 }}impl WrappingMul for u128 { fn wrapping_mul(self: u128, y: u128) -> u128 { wrapping_mul128_hlp(self, y) }}impl WrappingMul for Field { fn wrapping_mul(self: Field, y: Field) -> Field { self * y }}fn wrapping_add_hlp<T>(x: T, y: T) -> Twhere T: AsPrimitive<Field>, Field: AsPrimitive<T>,{ AsPrimitive::as_(x.as_() + y.as_())}fn wrapping_sub_hlp<T>(x: T, y: T) -> Fieldwhere T: AsPrimitive<Field>,{ //340282366920938463463374607431768211456 is 2^128, it is used to avoid underflow x.as_() + 340282366920938463463374607431768211456 - y.as_()}fn wrapping_mul_hlp<T>(x: T, y: T) -> Twhere T: AsPrimitive<Field>, Field: AsPrimitive<T>,{ AsPrimitive::as_(x.as_() * y.as_())}global two_pow_64: u128 = 0x10000000000000000;/// Splits a 128 bits number into two 64 bits limbsunconstrained fn split64(x: u128) -> (u64, u64) { let lo = x as u64; let hi = (x / two_pow_64) as u64; (lo, hi)}/// Split a 128 bits number into two 64 bits limbs/// It will fail if the number is more than 128 bitsfn split_into_64_bit_limbs(x: u128) -> (u64, u64) { // Safety: the limbs are constrained below let (x_lo, x_hi) = unsafe { split64(x) }; assert(x as Field == x_lo as Field + x_hi as Field * two_pow_64 as Field); (x_lo, x_hi)}#[field(bn254)]fn wrapping_mul128_hlp(x: u128, y: u128) -> u128 { let (x_lo, x_hi) = split_into_64_bit_limbs(x); let (y_lo, y_hi) = split_into_64_bit_limbs(y); // Multiplication using the limbs:(x_lo + 2**64*x_hi)*(y_lo + 2**64*y_hi)=x_lo*y_lo+... // and skipping the terms over 2**128 // Working with u64 limbs ensures that we cannot overflow the field modulus. let low = x_lo as Field * y_lo as Field; let lo = low as u64 as Field; let carry = (low - lo) / two_pow_64 as Field; let high = x_lo as Field * y_hi as Field + x_hi as Field * y_lo as Field + carry; let hi = high as u64 as Field; (lo + two_pow_64 as Field * hi) as u128}mod tests { #[test(should_fail_with = "custom message")] fn test_static_assert_custom_message() { crate::static_assert(1 == 2, "custom message"); } mod arithmetic { use crate::ops::arith::{Add, Div, Mul, Neg, Rem, Sub}; #[test] fn test_basic_arithmetic_traits() { // add assert_eq(5.add(3), 8); assert_eq(0u8.add(255u8), 255u8); assert_eq(42.add(58), 100); // sub assert_eq(10.sub(3), 7); assert_eq(100.sub(42), 58); // mul assert_eq(6.mul(7), 42); // div assert_eq(15.div(3), 5); assert_eq(10u8.div(3u8), 3u8); assert_eq(15.div(3), 5); // rem (Field doesn't implement Rem) assert_eq(17u64.rem(5u64), 2u64); assert_eq(10u8.rem(3u8), 1u8); // neg assert_eq(42.neg(), -42); assert_eq((-10).neg(), 10); assert_eq(42.neg(), -42); } #[test] fn test_division() { // test division by one assert_eq(42.div(1), 42); assert_eq(0.div(1), 0); assert_eq(255u8.div(1u8), 255u8); // test division by self assert_eq(42.div(42), 1); assert_eq(1.div(1), 1); // test remainder (Field doesn't implement Rem) assert_eq(42u32.rem(42u32), 0u32); assert_eq(0u16.rem(42u16), 0u16); assert_eq(1u64.rem(42u64), 1u64); } #[test(should_fail)] fn test_u8_sub_overflow_failure() { let _ = 0u8.sub(1u8); } #[test(should_fail)] fn test_u8_add_overflow_failure() { let _ = 255u8.add(1u8); } #[test(should_fail)] fn test_u8_mul_overflow_failure() { let _ = 255u8.mul(2u8); } #[test(should_fail)] fn test_u16_sub_overflow_failure() { let _ = 0u16.sub(1u16); } #[test(should_fail)] fn test_u16_add_overflow_failure() { let _ = 65535u16.add(1u16); } #[test(should_fail)] fn test_u16_mul_overflow_failure() { let _ = 65535u16.mul(2u16); } #[test(should_fail)] fn test_signed_sub_overflow_failure() { let val: i8 = -128; let _ = val.sub(1i8); } #[test(should_fail)] fn test_signed_overflow_failure() { let _ = 127i8.add(1i8); } #[test] fn test_field() { let zero: Field = 0; let one: Field = 1; // test Field basic operations assert_eq(zero.add(one), one); assert_eq(one.add(zero), one); assert_eq(one.sub(one), zero); assert_eq(one.mul(one), one); assert_eq(one.div(one), one); assert_eq(zero.neg(), zero); assert_eq(one.neg(), -one); } } mod wrapping_arithmetic { use crate::ops::arith::{Add, Div, Mul, Neg, Sub, WrappingAdd, WrappingMul, WrappingSub}; #[test] fn test_wrapping_add() { assert_eq(255u8.wrapping_add(1u8), 0u8); assert_eq(255u8.wrapping_add(255u8), 254u8); assert_eq(0u8.wrapping_add(0u8), 0u8); assert_eq(128u8.wrapping_add(128u8), 0u8); // test u16 wrapping add assert_eq(65535u16.wrapping_add(1u16), 0u16); assert_eq(65535u16.wrapping_add(65535u16), 65534u16); // test u32 wrapping add assert_eq(0xffffffffu32.wrapping_add(1u32), 0u32); assert_eq(0xffffffffu32.wrapping_add(0xffffffffu32), 0xfffffffeu32); // test u64 wrapping add assert_eq(0xffffffffffffffffu64.wrapping_add(1u64), 0u64); assert_eq( 0xffffffffffffffffu64.wrapping_add(0xffffffffffffffffu64), 0xfffffffffffffffeu64, ); // test u128 wrapping add assert_eq(0xffffffffffffffffffffffffffffffffu128.wrapping_add(1u128), 0u128); // test signed types assert_eq(127i8.wrapping_add(1i8), -128i8); let val: i8 = -128; assert_eq(val.wrapping_add(-1i8), 127i8); // test Field wrapping add let forty_two: Field = 42; let fifty_eight: Field = 58; let hundred: Field = 100; let neg_two: Field = -2; let two: Field = 2; let zero: Field = 0; let neg_two_hundred: Field = -200; let neg_one_ninety_eight: Field = -198; assert_eq(forty_two.wrapping_add(fifty_eight), hundred); assert_eq(neg_two.wrapping_add(two), zero); assert_eq(neg_two_hundred.wrapping_add(two), neg_one_ninety_eight); } #[test] fn test_wrapping_sub() { assert_eq(0u8.wrapping_sub(1u8), 255u8); assert_eq(255u8.wrapping_sub(255u8), 0u8); assert_eq(0u8.wrapping_sub(0u8), 0u8); assert_eq(1u8.wrapping_sub(2u8), 255u8); // test u16 wrapping sub assert_eq(0u16.wrapping_sub(1u16), 65535u16); assert_eq(65535u16.wrapping_sub(65535u16), 0u16); // test u32 wrapping sub assert_eq(0u32.wrapping_sub(1u32), 0xffffffffu32); assert_eq(0xffffffffu32.wrapping_sub(0xffffffffu32), 0u32); // test u64 wrapping sub assert_eq(0u64.wrapping_sub(1u64), 0xffffffffffffffffu64); assert_eq(0xffffffffffffffffu64.wrapping_sub(0xffffffffffffffffu64), 0u64); // test u128 wrapping sub assert_eq(0u128.wrapping_sub(1u128), 0xffffffffffffffffffffffffffffffffu128); // test signed types let val: i8 = -128; assert_eq(val.wrapping_sub(1i8), 127i8); assert_eq(127i8.wrapping_sub(-1i8), -128i8); // test Field wrapping sub let forty_two: Field = 42; let fifty_eight: Field = 58; let neg_sixteen: Field = -16; assert_eq(forty_two.wrapping_sub(fifty_eight), neg_sixteen); } #[test] fn test_wrapping_mul() { let zero: u128 = 0; let one: u128 = 1; let two_pow_64: u128 = 0x10000000000000000; let u128_max: u128 = 0xffffffffffffffffffffffffffffffff; assert_eq(zero, zero.wrapping_mul(one)); assert_eq(zero, one.wrapping_mul(zero)); assert_eq(one, one.wrapping_mul(one)); assert_eq(zero, zero.wrapping_mul(two_pow_64)); assert_eq(zero, two_pow_64.wrapping_mul(zero)); assert_eq(two_pow_64, two_pow_64.wrapping_mul(one)); assert_eq(two_pow_64, one.wrapping_mul(two_pow_64)); assert_eq(zero, two_pow_64.wrapping_mul(two_pow_64)); assert_eq(one, u128_max.wrapping_mul(u128_max)); // test u8 wrapping mul assert_eq(255u8.wrapping_mul(2u8), 254u8); assert_eq(255u8.wrapping_mul(255u8), 1u8); assert_eq(128u8.wrapping_mul(2u8), 0u8); // test u16 wrapping mul assert_eq(65535u16.wrapping_mul(2u16), 65534u16); assert_eq(65535u16.wrapping_mul(65535u16), 1u16); // test u32 wrapping mul assert_eq(0xffffffffu32.wrapping_mul(2u32), 0xfffffffeu32); assert_eq(0xffffffffu32.wrapping_mul(0xffffffffu32), 1u32); // test u64 wrapping mul // 0xffffffffffffffffu64 is 2^64 - 1 assert_eq(0xffffffffffffffffu64.wrapping_mul(2u64), 0xfffffffffffffffeu64); assert_eq(0xffffffffffffffffu64.wrapping_mul(0xffffffffffffffffu64), 1u64); // test signed types assert_eq(127i8.wrapping_mul(2i8), -2i8); let val: i8 = -128; assert_eq(val.wrapping_mul(-1i8), -128i8); // test Field wrapping mul let six: Field = 6; let seven: Field = 7; let forty_two: Field = 42; let neg_two: Field = -2; let two: Field = 2; let neg_four: Field = -4; assert_eq(six.wrapping_mul(seven), forty_two); assert_eq(neg_two.wrapping_mul(two), neg_four); } // test wrapping operations is the same as the regular operations #[test] fn test_wrapping_vs_regular() { let u64_large = 0x123456789abcdef0u64; let u128_large = 0x123456789abcdef0123456789abcdef0u128; assert_eq(u64_large.wrapping_add(1u64), u64_large + 1u64); assert_eq(u64_large.wrapping_sub(1u64), u64_large - 1u64); assert_eq(u64_large.wrapping_mul(2u64), u64_large * 2u64); assert_eq(u128_large.wrapping_add(1u128), u128_large + 1u128); assert_eq(u128_large.wrapping_sub(1u128), u128_large - 1u128); assert_eq(u128_large.wrapping_mul(2u128), u128_large * 2u128); } #[test] fn test_field_wrapping_operations() { let zero: Field = 0; let one: Field = 1; let large_val = 0xffffffffffffffff; // test Field wrapping operations assert_eq(zero.wrapping_add(one), one); assert_eq(one.wrapping_add(large_val), one + large_val); assert_eq(zero.wrapping_sub(one), -one); assert_eq(one.wrapping_sub(large_val), one - large_val); assert_eq(zero.wrapping_mul(one), zero); assert_eq(one.wrapping_mul(large_val), large_val); // test Field basic operations assert_eq(zero.add(one), one); assert_eq(one.add(zero), one); assert_eq(one.sub(one), zero); assert_eq(one.mul(one), one); assert_eq(one.div(one), one); assert_eq(zero.neg(), zero); assert_eq(one.neg(), -one); } } mod split_functions { use crate::ops::arith::{split64, split_into_64_bit_limbs}; // test split64 and split_into_64_bit_limbs functions #[test] fn test_split_functions() { let small_val = 0x123456789abcdefu128; let large_val = 0x123456789abcdef0123456789abcdef0u128; let max_val = 0xffffffffffffffffffffffffffffffffu128; // test split64 (unconstrained) // Safety: testing unsafe { let (lo, hi) = split64(small_val); assert_eq(lo, 0x123456789abcdefu64); assert_eq(hi, 0u64); let (lo2, hi2) = split64(large_val); assert_eq(lo2, 0x123456789abcdef0u64); assert_eq(hi2, 0x123456789abcdef0u64); } // test split_into_64_bit_limbs (constrained) let (lo3, hi3) = split_into_64_bit_limbs(small_val); assert_eq(lo3, 0x123456789abcdefu64); assert_eq(hi3, 0u64); let (lo4, hi4) = split_into_64_bit_limbs(large_val); assert_eq(lo4, 0x123456789abcdef0u64); assert_eq(hi4, 0x123456789abcdef0u64); let (lo5, hi5) = split_into_64_bit_limbs(max_val); assert_eq(lo5, 0xffffffffffffffffu64); assert_eq(hi5, 0xffffffffffffffffu64); } } mod traits { use crate::ops::arith::{ Add, Div, Mul, Neg, Rem, Sub, WrappingAdd, WrappingMul, WrappingSub, }; #[test] fn add() { assert_eq(1_u8.add(2), 3); assert_eq(1_u16.add(2), 3); assert_eq(1_u32.add(2), 3); assert_eq(1_u64.add(2), 3); assert_eq(1_u128.add(2), 3); assert_eq(1_i8.add(2), 3); assert_eq(1_i16.add(2), 3); assert_eq(1_i32.add(2), 3); assert_eq(1_i64.add(2), 3); assert_eq(1_Field.add(2), 3); } #[test] fn sub() { assert_eq(3_u8.sub(2), 1); assert_eq(3_u16.sub(2), 1); assert_eq(3_u32.sub(2), 1); assert_eq(3_u64.sub(2), 1); assert_eq(3_u128.sub(2), 1); assert_eq(3_i8.sub(2), 1); assert_eq(3_i16.sub(2), 1); assert_eq(3_i32.sub(2), 1); assert_eq(3_i64.sub(2), 1); assert_eq(3_Field.sub(2), 1); } #[test] fn mul() { assert_eq(3_u8.mul(2), 6); assert_eq(3_u16.mul(2), 6); assert_eq(3_u32.mul(2), 6); assert_eq(3_u64.mul(2), 6); assert_eq(3_u128.mul(2), 6); assert_eq(3_i8.mul(2), 6); assert_eq(3_i16.mul(2), 6); assert_eq(3_i32.mul(2), 6); assert_eq(3_i64.mul(2), 6); assert_eq(3_Field.mul(2), 6); } #[test] fn div() { assert_eq(6_u8.div(2), 3); assert_eq(6_u16.div(2), 3); assert_eq(6_u32.div(2), 3); assert_eq(6_u64.div(2), 3); assert_eq(6_u128.div(2), 3); assert_eq(6_i8.div(2), 3); assert_eq(6_i16.div(2), 3); assert_eq(6_i32.div(2), 3); assert_eq(6_i64.div(2), 3); assert_eq(6_Field.div(2), 3); } #[test] fn rem() { assert_eq(3_u8.rem(2), 1); assert_eq(3_u16.rem(2), 1); assert_eq(3_u32.rem(2), 1); assert_eq(3_u64.rem(2), 1); assert_eq(3_u128.rem(2), 1); assert_eq(3_i8.rem(2), 1); assert_eq(3_i16.rem(2), 1); assert_eq(3_i32.rem(2), 1); assert_eq(3_i64.rem(2), 1); } #[test] fn neg() { assert_eq(3_i8.neg(), -3); assert_eq(3_i16.neg(), -3); assert_eq(3_i32.neg(), -3); assert_eq(3_i64.neg(), -3); } #[test] fn wrapping_add() { assert_eq(255_u8.wrapping_add(2), 1); assert_eq(65535_u16.wrapping_add(2), 1); assert_eq(4294967295_u32.wrapping_add(2), 1); assert_eq(18446744073709551615_u64.wrapping_add(2), 1); assert_eq(340282366920938463463374607431768211455_u128.wrapping_add(2), 1); assert_eq(127_i8.wrapping_add(2), -127); assert_eq(32767_i16.wrapping_add(2), -32767); assert_eq(2147483647_i32.wrapping_add(2), -2147483647); assert_eq(9223372036854775807_i64.wrapping_add(2), -9223372036854775807); assert_eq(1_Field.wrapping_add(2), 3); } #[test] fn wrapping_sub() { assert_eq(0_u8.wrapping_sub(1), 255); assert_eq(0_u16.wrapping_sub(1), 65535); assert_eq(0_u32.wrapping_sub(1), 4294967295); assert_eq(0_u64.wrapping_sub(1), 18446744073709551615); assert_eq(0_u128.wrapping_sub(1), 340282366920938463463374607431768211455); assert_eq((-128_i8).wrapping_sub(1), 127); assert_eq((-32768_i16).wrapping_sub(1), 32767); assert_eq((-2147483648_i32).wrapping_sub(1), 2147483647); assert_eq((-9223372036854775808_i64).wrapping_sub(1), 9223372036854775807); assert_eq(3_Field.wrapping_sub(1), 2); } #[test] fn wrapping_mul() { assert_eq(255_u8.wrapping_mul(2), 254); assert_eq(65535_u16.wrapping_mul(2), 65534); assert_eq(4294967295_u32.wrapping_mul(2), 4294967294); assert_eq(18446744073709551615_u64.wrapping_mul(2), 18446744073709551614); assert_eq( 340282366920938463463374607431768211455_u128.wrapping_mul(2), 340282366920938463463374607431768211454, ); assert_eq(127_i8.wrapping_mul(2), -2); assert_eq(32767_i16.wrapping_mul(2), -2); assert_eq(2147483647_i32.wrapping_mul(2), -2); assert_eq(9223372036854775807_i64.wrapping_mul(2), -2); assert_eq(2_Field.wrapping_mul(3), 6); } }}use crate::cmp::{Eq, Ord, Ordering};use crate::default::Default;use crate::hash::{Hash, Hasher};/// Represents a value of type T or its absence./// Use `Option::some(value)` to construct a value or `Option::none()` to record the absence of one.pub struct Option<T> { _is_some: bool, _value: T,}impl<T> Option<T> { /// Constructs a None value pub fn none() -> Self { Self { _is_some: false, _value: crate::mem::zeroed() } } /// Constructs a Some wrapper around the given value pub fn some(_value: T) -> Self { Self { _is_some: true, _value } } /// True if this Option is None pub fn is_none(&self) -> bool { !self._is_some } /// True if this Option is Some pub fn is_some(&self) -> bool { self._is_some } /// Asserts `self.is_some()` and returns the wrapped value. pub fn unwrap(self) -> T { assert(self._is_some); self._value } /// Returns the inner value without asserting `self.is_some()` /// Note that if `self` is `None`, there is no guarantee what value will be returned, /// only that it will be of type `T`. pub fn unwrap_unchecked(self) -> T { self._value } /// Returns the wrapped value if `self.is_some()`. Otherwise, returns the given default value. pub fn unwrap_or(self, default: T) -> T { if self._is_some { self._value } else { default } } /// Returns the wrapped value if `self.is_some()`. Otherwise, calls the given function to return /// a default value. pub fn unwrap_or_else<Env>(self, default: fn[Env]() -> T) -> T { if self._is_some { self._value } else { default() } } /// Asserts `self.is_some()` with a provided custom message and returns the contained `Some` value pub fn expect<let N: u32, MessageTypes>(self, message: fmtstr<N, MessageTypes>) -> T { assert(self.is_some(), message); self._value } /// If self is `Some(x)`, this returns `Some(f(x))`. Otherwise, this returns `None`. pub fn map<U, Env>(self, f: fn[Env](T) -> U) -> Option<U> { if self._is_some { Option::some(f(self._value)) } else { Option::none() } } /// If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns the given default value. pub fn map_or<U, Env>(self, default: U, f: fn[Env](T) -> U) -> U { if self._is_some { f(self._value) } else { default } } /// If self is `Some(x)`, this returns `f(x)`. Otherwise, this returns `default()`. pub fn map_or_else<U, Env1, Env2>(self, default: fn[Env1]() -> U, f: fn[Env2](T) -> U) -> U { if self._is_some { f(self._value) } else { default() } } /// Returns None if self is None. Otherwise, this returns `other`. pub fn and(self, other: Self) -> Self { if self.is_none() { Option::none() } else { other } } /// If self is None, this returns None. Otherwise, this calls the given function /// with the Some value contained within self, and returns the result of that call. /// /// In some languages this function is called `flat_map` or `bind`. pub fn and_then<U, Env>(self, f: fn[Env](T) -> Option<U>) -> Option<U> { if self._is_some { f(self._value) } else { Option::none() } } /// If self is Some, return self. Otherwise, return `other`. pub fn or(self, other: Self) -> Self { if self._is_some { self } else { other } } /// If self is Some, return self. Otherwise, return `default()`. pub fn or_else<Env>(self, default: fn[Env]() -> Self) -> Self { if self._is_some { self } else { default() } } // If only one of the two Options is Some, return that option. // Otherwise, if both options are Some or both are None, None is returned. pub fn xor(self, other: Self) -> Self { if self._is_some { if other._is_some { Option::none() } else { self } } else if other._is_some { other } else { Option::none() } } /// Returns `Some(x)` if self is `Some(x)` and `predicate(x)` is true. /// Otherwise, this returns `None` pub fn filter<Env>(self, predicate: fn[Env](T) -> bool) -> Self { if self._is_some { if predicate(self._value) { self } else { Option::none() } } else { Option::none() } } /// Flattens an Option<Option<T>> into a Option<T>. /// This returns None if the outer Option is None. Otherwise, this returns the inner Option. pub fn flatten(option: Option<Option<T>>) -> Option<T> { if option._is_some { option._value } else { Option::none() } }}impl<T> Default for Option<T> { fn default() -> Self { Option::none() }}impl<T> Eq for Option<T>where T: Eq,{ fn eq(self, other: Self) -> bool { if self._is_some == other._is_some { if self._is_some { self._value == other._value } else { true } } else { false } }}impl<T> Hash for Option<T>where T: Hash,{ fn hash<H>(self, state: &mut H) where H: Hasher, { self._is_some.hash(state); if self._is_some { self._value.hash(state); } }}// For this impl we're declaring Option::none < Option::someimpl<T> Ord for Option<T>where T: Ord,{ fn cmp(self, other: Self) -> Ordering { if self._is_some { if other._is_some { self._value.cmp(other._value) } else { Ordering::greater() } } else if other._is_some { Ordering::less() } else { Ordering::equal() } }}mod tests { use crate::cmp::Ord; use crate::cmp::Ordering; use crate::default::Default as _; use super::Option; #[test] fn some_and_none() { assert(Option::<u8>::none().is_none()); assert(!Option::<u8>::none().is_some()); assert(Option::some(1).is_some()); assert(!Option::some(1).is_none()); } #[test] fn unwrap_succeeds() { assert_eq(Option::some(1).unwrap(), 1); } #[test(should_fail)] fn unwrap_fails() { let _ = Option::<u8>::none().unwrap(); } #[test] fn unwrap_or() { assert_eq(Option::some(1).unwrap_or(2), 1); assert_eq(Option::none().unwrap_or(2), 2); } #[test] fn unwrap_or_else() { assert_eq(Option::some(1).unwrap_or_else(|| 2), 1); assert_eq(Option::none().unwrap_or_else(|| 2), 2); } #[test] fn expect_succeeds() { assert_eq(Option::some(1).expect(f"Should be there"), 1); } #[test(should_fail_with = "Should be there")] fn expect_fails() { let _ = Option::<u8>::none().expect(f"Should be there"); } #[test] fn map() { assert(Option::<u8>::none().map(|x| x + 1).is_none()); assert_eq(Option::some(1).map(|x| x + 1), Option::some(2)); } #[test] fn map_or() { assert_eq(Option::<u8>::none().map_or(0, |x| x + 1), 0); assert_eq(Option::some(1).map_or(0, |x| x + 1), 2); } #[test] fn map_or_else() { assert_eq(Option::<u8>::none().map_or_else(|| 0, |x| x + 1), 0); assert_eq(Option::some(1).map_or_else(|| 0, |x| x + 1), 2); } #[test] fn and() { assert_eq(Option::<u8>::none().and(Option::none()), Option::none()); assert_eq(Option::<u8>::none().and(Option::some(1)), Option::none()); assert_eq(Option::some(1).and(Option::some(2)), Option::some(2)); assert_eq(Option::some(1).and(Option::none()), Option::none()); } #[test] fn and_then() { assert_eq(Option::<u8>::none().and_then(|_| Option::<u8>::none()), Option::none()); assert_eq(Option::<u8>::none().and_then(|_| Option::some(1)), Option::none()); assert_eq(Option::some(1).and_then(|x| Option::some(x + 1)), Option::some(2)); assert_eq(Option::some(1).and_then(|_| Option::<u8>::none()), Option::none()); } #[test] fn or() { assert_eq(Option::<u8>::none().or(Option::none()), Option::none()); assert_eq(Option::<u8>::none().or(Option::some(1)), Option::some(1)); assert_eq(Option::some(1).or(Option::some(2)), Option::some(1)); assert_eq(Option::some(1).or(Option::none()), Option::some(1)); } #[test] fn or_else() { assert_eq(Option::<u8>::none().or_else(|| Option::none()), Option::none()); assert_eq(Option::<u8>::none().or_else(|| Option::some(1)), Option::some(1)); assert_eq(Option::some(1).or_else(|| Option::some(2)), Option::some(1)); assert_eq(Option::some(1).or_else(|| Option::none()), Option::some(1)); } #[test] fn xor() { assert_eq(Option::<u8>::none().xor(Option::none()), Option::none()); assert_eq(Option::<u8>::none().xor(Option::some(1)), Option::some(1)); assert_eq(Option::some(1).xor(Option::some(2)), Option::none()); assert_eq(Option::some(1).xor(Option::none()), Option::some(1)); } #[test] fn filter() { assert_eq(Option::<u8>::none().filter(|_| true), Option::none()); assert_eq(Option::some(1).filter(|x| x == 1), Option::some(1)); assert_eq(Option::some(1).filter(|x| x == 2), Option::none()); assert_eq(Option::some(1).filter(|x| x == 2), Option::none()); } #[test] fn flatten() { assert_eq(Option::<Option<u8>>::none().flatten(), Option::none()); assert_eq(Option::some(Option::<u8>::none()).flatten(), Option::none()); assert_eq(Option::some(Option::some(1)).flatten(), Option::some(1)); } #[test] fn default() { assert_eq(Option::<u8>::default(), Option::none()); } #[test] fn eq() { assert(Option::<u8>::none() == Option::none()); assert(Option::<u8>::some(1) != Option::none()); assert(Option::<u8>::none() != Option::some(1)); assert(Option::<u8>::some(1) == Option::some(1)); assert(Option::<u8>::some(1) != Option::some(2)); } #[test] fn cmp() { let none = Option::<u8>::none(); let one = Option::<u8>::some(1); let two = Option::<u8>::some(2); assert_eq(none.cmp(none), Ordering::equal()); assert_eq(none.cmp(one), Ordering::less()); assert_eq(one.cmp(none), Ordering::greater()); assert_eq(one.cmp(one), Ordering::equal()); assert_eq(one.cmp(two), Ordering::less()); assert_eq(two.cmp(one), Ordering::greater()); }}/// Halt the program at runtime with the given error message.////// The provided error message must be either a `str` or a `fmtstr`.pub fn panic<T, U>(message: T) -> Uwhere T: StringLike,{ assert(false, message); crate::mem::zeroed()}trait StringLike {}impl<let N: u32> StringLike for str<N> {}impl<let N: u32, T> StringLike for fmtstr<N, T> {}mod tests { use crate::prelude::panic; #[test(should_fail_with = "OH NO")] fn panics() { panic("OH NO"); }}//! AVM oracles.//!//! There are only available during public execution. Calling any of them from a private or utility function will//! result in runtime errors.use crate::protocol::address::{AztecAddress, EthAddress};pub unconstrained fn address() -> AztecAddress { address_opcode()}pub unconstrained fn sender() -> AztecAddress { sender_opcode()}pub unconstrained fn transaction_fee() -> Field { transaction_fee_opcode()}pub unconstrained fn chain_id() -> Field { chain_id_opcode()}pub unconstrained fn version() -> Field { version_opcode()}pub unconstrained fn block_number() -> u32 { block_number_opcode()}pub unconstrained fn timestamp() -> u64 { timestamp_opcode()}pub unconstrained fn min_fee_per_l2_gas() -> u128 { min_fee_per_l2_gas_opcode()}pub unconstrained fn min_fee_per_da_gas() -> u128 { min_fee_per_da_gas_opcode()}pub unconstrained fn l2_gas_left() -> u32 { l2_gas_left_opcode()}pub unconstrained fn da_gas_left() -> u32 { da_gas_left_opcode()}pub unconstrained fn is_static_call() -> bool { is_static_call_opcode()}pub unconstrained fn note_hash_exists(note_hash: Field, leaf_index: u64) -> bool { note_hash_exists_opcode(note_hash, leaf_index)}pub unconstrained fn emit_note_hash(note_hash: Field) { emit_note_hash_opcode(note_hash)}pub unconstrained fn nullifier_exists(siloed_nullifier: Field) -> bool { nullifier_exists_opcode(siloed_nullifier)}pub unconstrained fn emit_nullifier(nullifier: Field) { emit_nullifier_opcode(nullifier)}pub unconstrained fn emit_public_log(message: [Field]) { emit_public_log_opcode(message)}pub unconstrained fn l1_to_l2_msg_exists(msg_hash: Field, msg_leaf_index: u64) -> bool { l1_to_l2_msg_exists_opcode(msg_hash, msg_leaf_index)}pub unconstrained fn send_l2_to_l1_msg(recipient: EthAddress, content: Field) { send_l2_to_l1_msg_opcode(recipient, content)}pub unconstrained fn call<let N: u32>( l2_gas_allocation: u32, da_gas_allocation: u32, address: AztecAddress, args: [Field; N],) { call_opcode(l2_gas_allocation, da_gas_allocation, address, N, args)}pub unconstrained fn call_static<let N: u32>( l2_gas_allocation: u32, da_gas_allocation: u32, address: AztecAddress, args: [Field; N],) { call_static_opcode(l2_gas_allocation, da_gas_allocation, address, N, args)}pub unconstrained fn calldata_copy<let N: u32>(cdoffset: u32, copy_size: u32) -> [Field; N] { calldata_copy_opcode(cdoffset, copy_size)}/// `success_copy` is placed immediately after the CALL opcode to get the success valuepub unconstrained fn success_copy() -> bool { success_copy_opcode()}pub unconstrained fn returndata_size() -> u32 { returndata_size_opcode()}pub unconstrained fn returndata_copy(rdoffset: u32, copy_size: u32) -> [Field] { returndata_copy_opcode(rdoffset, copy_size)}/// The additional prefix is to avoid clashing with the `return` Noir keyword.pub unconstrained fn avm_return(returndata: [Field]) { return_opcode(returndata)}/// This opcode reverts using the exact data given. In general it should only be used to do rethrows, where the revert/// data is the same as the original revert data. For normal reverts, use Noir's `assert` which, on top of reverting,/// will also add an error selector to the revert data.pub unconstrained fn revert(revertdata: [Field]) { revert_opcode(revertdata)}pub unconstrained fn storage_read(storage_slot: Field, contract_address: Field) -> Field { storage_read_opcode(storage_slot, contract_address)}pub unconstrained fn storage_write(storage_slot: Field, value: Field) { storage_write_opcode(storage_slot, value);}#[oracle(aztec_avm_address)]unconstrained fn address_opcode() -> AztecAddress {}#[oracle(aztec_avm_sender)]unconstrained fn sender_opcode() -> AztecAddress {}#[oracle(aztec_avm_transactionFee)]unconstrained fn transaction_fee_opcode() -> Field {}#[oracle(aztec_avm_chainId)]unconstrained fn chain_id_opcode() -> Field {}#[oracle(aztec_avm_version)]unconstrained fn version_opcode() -> Field {}#[oracle(aztec_avm_blockNumber)]unconstrained fn block_number_opcode() -> u32 {}#[oracle(aztec_avm_timestamp)]unconstrained fn timestamp_opcode() -> u64 {}#[oracle(aztec_avm_minFeePerL2Gas)]unconstrained fn min_fee_per_l2_gas_opcode() -> u128 {}#[oracle(aztec_avm_minFeePerDaGas)]unconstrained fn min_fee_per_da_gas_opcode() -> u128 {}#[oracle(aztec_avm_l2GasLeft)]unconstrained fn l2_gas_left_opcode() -> u32 {}#[oracle(aztec_avm_daGasLeft)]unconstrained fn da_gas_left_opcode() -> u32 {}#[oracle(aztec_avm_isStaticCall)]unconstrained fn is_static_call_opcode() -> bool {}#[oracle(aztec_avm_noteHashExists)]unconstrained fn note_hash_exists_opcode(note_hash: Field, leaf_index: u64) -> bool {}#[oracle(aztec_avm_emitNoteHash)]unconstrained fn emit_note_hash_opcode(note_hash: Field) {}#[oracle(aztec_avm_nullifierExists)]unconstrained fn nullifier_exists_opcode(siloed_nullifier: Field) -> bool {}#[oracle(aztec_avm_emitNullifier)]unconstrained fn emit_nullifier_opcode(nullifier: Field) {}#[oracle(aztec_avm_emitPublicLog)]unconstrained fn emit_public_log_opcode(message: [Field]) {}#[oracle(aztec_avm_l1ToL2MsgExists)]unconstrained fn l1_to_l2_msg_exists_opcode(msg_hash: Field, msg_leaf_index: u64) -> bool {}#[oracle(aztec_avm_sendL2ToL1Msg)]unconstrained fn send_l2_to_l1_msg_opcode(recipient: EthAddress, content: Field) {}#[oracle(aztec_avm_calldataCopy)]unconstrained fn calldata_copy_opcode<let N: u32>(cdoffset: u32, copy_size: u32) -> [Field; N] {}#[oracle(aztec_avm_returndataSize)]unconstrained fn returndata_size_opcode() -> u32 {}#[oracle(aztec_avm_returndataCopy)]unconstrained fn returndata_copy_opcode(rdoffset: u32, copy_size: u32) -> [Field] {}#[oracle(aztec_avm_return)]unconstrained fn return_opcode(returndata: [Field]) {}#[oracle(aztec_avm_revert)]unconstrained fn revert_opcode(revertdata: [Field]) {}// While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode// level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take// that route.#[oracle(aztec_avm_call)]unconstrained fn call_opcode<let N: u32>( l2_gas_allocation: u32, da_gas_allocation: u32, address: AztecAddress, length: u32, args: [Field; N],) {}// While the length parameter might seem unnecessary given that we have N we keep it around because at the AVM bytecode// level, we want to support non-comptime-known lengths for such opcodes, even if Noir code will not generally take// that route.#[oracle(aztec_avm_staticCall)]unconstrained fn call_static_opcode<let N: u32>( l2_gas_allocation: u32, da_gas_allocation: u32, address: AztecAddress, length: u32, args: [Field; N],) {}#[oracle(aztec_avm_successCopy)]unconstrained fn success_copy_opcode() -> bool {}#[oracle(aztec_avm_storageRead)]unconstrained fn storage_read_opcode(storage_slot: Field, contract_address: Field) -> Field {}#[oracle(aztec_avm_storageWrite)]unconstrained fn storage_write_opcode(storage_slot: Field, value: Field) {}Calls and storage writes are recorded against the step they happened on. 86 of this recording's 459 steps carry a source position; the rest are compiler-generated code the artifact maps no line for.
This recording carries no variable names. The contract's artifact resolved and its debug symbols carry the source map, but their variable table is empty — Aztec publishes these contracts compiled without variable debug information, so there are no locals to name.