Barretenberg
The ZK-SNARK library at the core of Aztec
Loading...
Searching...
No Matches
bytecode_manager.cpp
Go to the documentation of this file.
2
3#include <cassert>
4
12
13namespace bb::avm2::simulation {
14
42{
43 BB_BENCH_NAME("TxBytecodeManager::get_bytecode");
44 // Use shared ContractInstanceManager for contract instance retrieval and validation
45 // This handles nullifier checks, address derivation, and update validation
46 auto tree_states = merkle_db.get_tree_state();
48 // Emits ContractInstanceRetrievalEvent, see #[CONTRACT_INSTANCE_RETRIEVAL] in bc_retrieval.pil.
50
51 if (!maybe_instance.has_value()) {
52 // Emits BytecodeRetrievalEvent with contract instance not found error
53 retrieval_events.emit({
54 .bytecode_id = FF(0), // Use default ID for error cases
55 .address = address,
56 .current_class_id = FF(0), // Use default ID for error cases
57 .nullifier_root = tree_states.nullifier_tree.tree.root,
58 .public_data_tree_root = tree_states.public_data_tree.tree.root,
59 .retrieved_bytecodes_snapshot_before = before_snapshot,
60 .retrieved_bytecodes_snapshot_after = before_snapshot,
62 });
63 vinfo("Contract ", field_to_string(address), " is not deployed!");
64 throw BytecodeRetrievalError("Contract " + field_to_string(address) + " is not deployed");
65 }
66
67 ContractInstance instance = maybe_instance.value();
68 ContractClassId current_class_id = instance.current_contract_class_id;
69
70 // Emits RetrievedBytecodesTreeCheckEvent with write == false, see #[IS_NEW_CLASS_CHECK] in bc_retrieval.pil.
72
73 uint32_t retrieved_bytecodes_count = retrieved_bytecodes_tree_check.size();
74
75 if (is_new_class && retrieved_bytecodes_count >= MAX_PUBLIC_CALLS_TO_UNIQUE_CONTRACT_CLASS_IDS) {
76 // Emits BytecodeRetrievalEvent with too many bytecodes error
77 retrieval_events.emit({
78 .bytecode_id = FF(0), // Use default ID for error cases
79 .address = address,
80 .current_class_id = current_class_id,
81 .nullifier_root = tree_states.nullifier_tree.tree.root,
82 .public_data_tree_root = tree_states.public_data_tree.tree.root,
83 .retrieved_bytecodes_snapshot_before = before_snapshot,
84 .retrieved_bytecodes_snapshot_after = before_snapshot,
85 .is_new_class = is_new_class,
87 });
88 throw BytecodeRetrievalError("Can't retrieve more than " +
90 " bytecodes per tx");
91 }
92
93 // Emits RetrievedBytecodesTreeCheckEvent with write == true, see #[RETRIEVED_BYTECODES_INSERTION] in
94 // bc_retrieval.pil.
97
98 // Contract class retrieval and class ID validation
99
100 // Emits ClassIdDerivationEvent if the class exists, see #[CLASS_ID_DERIVATION] in bc_retrieval.pil. Note
101 // that this conditional emission works because if the class does not exist, we throw and do not process retrieval.
103 // Note: we don't need to silo and check the class id because the deployer contract guarantees
104 // that if a contract instance exists, the class has been registered.
105 BB_ASSERT(maybe_klass.has_value(), "Contract class not found");
106 auto& klass = maybe_klass.value(); // WARNING: this class has the whole bytecode.
107
108 // Bytecode hashing (bc_hashing.pil) and decomposition (bc_decomposition.pil)
109
111 // If we reach this point, class ID and instance both exist which means bytecode commitment must exist.
112 BB_ASSERT(maybe_bytecode_commitment.has_value(), "Bytecode commitment not found");
113 BytecodeId bytecode_id = maybe_bytecode_commitment.value();
114 debug("Bytecode for ", address, " successfully retrieved!");
115
116 retrieval_events.emit({
117 .bytecode_id = bytecode_id,
118 .address = address,
119 .current_class_id = current_class_id,
120 .contract_class = klass,
121 .nullifier_root = tree_states.nullifier_tree.tree.root,
122 .public_data_tree_root = tree_states.public_data_tree.tree.root,
123 .retrieved_bytecodes_snapshot_before = before_snapshot,
124 .retrieved_bytecodes_snapshot_after = snapshot_after,
125 .is_new_class = is_new_class,
126 });
127
128 // Check if we've already processed this bytecode by deduplicating by bytecode_id (=commitment). If so, don't do
129 // hashing and decomposition again!
130 if (bytecodes.contains(bytecode_id)) {
131 // Already processed this bytecode - just return
132 return bytecode_id;
133 }
134
135 // First time seeing this bytecode - perform hashing and decomposition.
136 // Emits BytecodeHashingEvent and corresponding Poseidon2HashEvent and Poseidon2PermutationEvent(s).
138 bytecode_id, klass.packed_bytecode, /*public_bytecode_commitment=*/bytecode_id);
139
140 // We convert the bytecode to a shared_ptr because it will be shared by some events.
141 auto shared_bytecode = std::make_shared<std::vector<uint8_t>>(std::move(klass.packed_bytecode));
142 // Emits BytecodeDecompositionEvent.
143 decomposition_events.emit({ .bytecode_id = bytecode_id, .bytecode = shared_bytecode });
144
145 // We now save the bytecode against its id so that we don't repeat this process.
146 bytecodes.emplace(bytecode_id, std::move(shared_bytecode));
147
148 return bytecode_id;
149}
150
152{
153 return read_instruction(bytecode_id, get_bytecode_data(bytecode_id), pc);
154}
155
157 std::shared_ptr<std::vector<uint8_t>> bytecode_ptr,
158 PC pc)
159{
160 BB_BENCH_NAME("TxBytecodeManager::read_instruction");
161
162 // We'll be filling in the event as we progress.
163 InstructionFetchingEvent instr_fetching_event;
164
165 instr_fetching_event.bytecode_id = bytecode_id;
166 instr_fetching_event.pc = pc;
167
168 const auto& bytecode = *bytecode_ptr;
169 instr_fetching_event.bytecode = std::move(bytecode_ptr);
170
171 // Keep full error for exception message, but only store enum in event
172 std::optional<InstrDeserializationError> deserialization_error;
173
174 try {
175 instr_fetching_event.instruction = deserialize_instruction(bytecode, pc);
176
177 // If the following code is executed, no error was thrown in deserialize_instruction().
178 if (!check_tag(instr_fetching_event.instruction)) {
180 };
181 } catch (const InstrDeserializationError& error) {
182 instr_fetching_event.error = error.type;
183 }
184
185 // We are showing whether bytecode_size > pc or not. If there is no fetching error,
186 // we always have bytecode_size > pc.
187 const auto bytecode_size = bytecode.size();
188 const uint128_t pc_diff = bytecode_size > pc ? bytecode_size - pc - 1 : pc - bytecode_size;
189 range_check.assert_range(pc_diff, AVM_PC_SIZE_IN_BITS);
190
191 // The event will be deduplicated internally.
192 fetching_events.emit(InstructionFetchingEvent(instr_fetching_event));
193
194 // Communicate error to the caller.
195 if (instr_fetching_event.error.has_value()) {
196 throw InstructionFetchingError("Instruction fetching error: " +
197 std::to_string(static_cast<int>(instr_fetching_event.error.value())));
198 }
199
200 return instr_fetching_event.instruction;
201}
202
204{
205 auto it = bytecodes.find(bytecode_id);
206 BB_ASSERT(it != bytecodes.end(), "Bytecode not found for the given bytecode_id");
207 return it->second;
208}
209
210} // namespace bb::avm2::simulation
#define BB_ASSERT(expression,...)
Definition assert.hpp:70
std::shared_ptr< Napi::ThreadSafeFunction > instance
std::shared_ptr< Napi::ThreadSafeFunction > bytecode
#define MAX_PUBLIC_CALLS_TO_UNIQUE_CONTRACT_CLASS_IDS
#define AVM_PC_SIZE_IN_BITS
#define BB_BENCH_NAME(name)
Definition bb_bench.hpp:225
virtual void assert_public_bytecode_commitment(const BytecodeId &bytecode_id, const std::vector< uint8_t > &bytecode, const FF &public_bytecode_commitment)=0
virtual std::optional< FF > get_bytecode_commitment(const ContractClassId &class_id) const =0
virtual std::optional< ContractClass > get_contract_class(const ContractClassId &class_id) const =0
virtual std::optional< ContractInstance > get_contract_instance(const FF &contract_address)=0
Retrieve and validate a contract instance.
virtual TreeStates get_tree_state() const =0
virtual void insert(const FF &class_id)=0
virtual bool contains(const FF &class_id)=0
virtual AppendOnlyTreeSnapshot get_snapshot() const =0
HighLevelMerkleDBInterface & merkle_db
Instruction read_instruction(const BytecodeId &bytecode_id, PC pc) override
EventEmitterInterface< BytecodeDecompositionEvent > & decomposition_events
RetrievedBytecodesTreeCheckInterface & retrieved_bytecodes_tree_check
EventEmitterInterface< BytecodeRetrievalEvent > & retrieval_events
EventEmitterInterface< InstructionFetchingEvent > & fetching_events
unordered_flat_map< BytecodeId, std::shared_ptr< std::vector< uint8_t > > > bytecodes
std::shared_ptr< std::vector< uint8_t > > get_bytecode_data(const BytecodeId &bytecode_id) override
BytecodeHashingInterface & bytecode_hasher
ContractInstanceManagerInterface & contract_instance_manager
BytecodeId get_bytecode(const AztecAddress &address) override
Retrieves and validates bytecode from the TxBytecodeManager's ContractDBInterface and emits a Bytecod...
#define vinfo(...)
Definition log.hpp:94
#define debug(...)
Definition log.hpp:99
AVM range check gadget for witness generation.
bool check_tag(const Instruction &instruction)
Check whether the instruction must have a tag operand and whether the operand value is in the value t...
Instruction deserialize_instruction(std::span< const uint8_t > bytecode, size_t pos)
Parsing of an instruction in the supplied bytecode at byte position pos. This checks that the WireOpC...
uint32_t PC
AvmFlavorSettings::FF FF
Definition field.hpp:10
FF ContractClassId
std::string field_to_string(const FF &ff)
Definition stringify.cpp:5
constexpr decltype(auto) get(::tuplet::tuple< T... > &&t) noexcept
Definition tuple.hpp:13
std::string to_string(bb::avm2::ValueTag tag)
unsigned __int128 uint128_t
Definition serialize.hpp:45
FF current_class_id
std::shared_ptr< std::vector< uint8_t > > bytecode
std::optional< InstrDeserializationEventError > error