referrerpolicy=no-referrer-when-downgrade

pallet_revive/vm/pvm/
env.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18use super::*;
19
20use crate::{
21	AccountIdOf, CodeInfo, Config, ContractBlob, ContractLogTopics, Error, SENTINEL, Weight,
22	address::AddressMapper,
23	debug::DebugSettings,
24	exec::Ext,
25	limits,
26	metering::EngineMeter,
27	primitives::ExecReturnValue,
28	vm::{
29		BytecodeType, ExportedFunction, RuntimeCosts, StipendAndProtections, calculate_code_deposit,
30	},
31};
32use alloc::vec::Vec;
33use core::mem;
34use frame_support::traits::Get;
35use pallet_revive_proc_macro::define_env;
36use pallet_revive_uapi::{CallFlags, ReturnErrorCode, ReturnFlags};
37use sp_core::U256;
38use sp_io::hashing::keccak_256;
39use sp_runtime::{DispatchError, SaturatedConversion};
40
41impl<T: Config> ContractBlob<T> {
42	/// Compile and instantiate contract.
43	///
44	/// With the interpreter backend the instance starts with the frame's gas plus a credit for
45	/// the first allocation of the interpreter's map of compiled blocks:
46	/// `ceil(code_section_bytes * per_code_byte_millis / 1000)`, the gas the interpreter charges
47	/// for it. The caller pays for that allocation with the code load of stored code, or with the
48	/// code length slope of `instantiate_with_code` or `eth_instantiate_with_code` for code the
49	/// transaction uploads. The frame's meter keeps accounting against the gas it handed over, so
50	/// the credit is not counted as the callee's consumption. Other backends do not charge for the
51	/// map and get no credit.
52	pub fn prepare_call<E: Ext<T = T>>(
53		self,
54		mut runtime: Runtime<E, polkavm::RawInstance>,
55		entry_point: ExportedFunction,
56	) -> Result<PreparedCall<E>, ExecError> {
57		let mut config = polkavm::Config::default();
58		// Log filtering by level with log::enabled! returns always true,
59		// passing all logs through impacting performance \
60		// (more details: https://github.com/paritytech/polkadot-sdk/issues/8760#issuecomment-3499548774)
61		// By default, disable polkavm logging unless pvm_logs debug setting is enabled.
62		let pvm_logs_enabled = DebugSettings::is_pvm_logs_enabled::<T>();
63		config.set_imperfect_logger_filtering_workaround(!pvm_logs_enabled);
64		config.set_backend(Some(polkavm::BackendKind::Interpreter));
65		config.set_cache_enabled(false);
66		#[cfg(feature = "std")]
67		if std::env::var_os("REVIVE_USE_COMPILER").is_some() {
68			log::warn!(target: LOG_TARGET, "Using PolkaVM compiler backend because env var REVIVE_USE_COMPILER is set");
69			config.set_backend(Some(polkavm::BackendKind::Compiler));
70		}
71		let engine = polkavm::Engine::new(&config).expect(
72			"on-chain (no_std) use of interpreter is hard coded.
73				interpreter is available on all platforms; qed",
74		);
75
76		let compilation_cost = EngineMeter::<T>::interpreter_compilation_cost();
77		let mut module_config = polkavm::ModuleConfig::new();
78		module_config.set_page_size(limits::PAGE_SIZE);
79		module_config.set_gas_metering(Some(polkavm::GasMeteringKind::Sync));
80		module_config.set_interpreter_compilation_cost(Some(compilation_cost));
81		let blob = polkavm::ProgramBlob::parse(self.code.into()).map_err(|err| {
82			log::debug!(target: LOG_TARGET, "failed to parse polkavm blob: {err:?}");
83			Error::<T>::CodeRejected
84		})?;
85		let charges_code_map = engine.backend() == polkavm::BackendKind::Interpreter;
86		let code_map_credit: polkavm::Gas = if charges_code_map {
87			let code_section_bytes: u64 = blob.code().len().saturated_into();
88			code_section_bytes
89				.saturating_mul(compilation_cost.per_code_byte_millis.into())
90				.div_ceil(1000)
91				.saturated_into()
92		} else {
93			0
94		};
95		let module = polkavm::Module::from_blob(&engine, &module_config, blob).map_err(|err| {
96			log::debug!(target: LOG_TARGET, "failed to create polkavm module: {err:?}");
97			Error::<T>::CodeRejected
98		})?;
99
100		let entry_program_counter = module
101			.exports()
102			.find(|export| export.symbol().as_bytes() == entry_point.identifier().as_bytes())
103			.ok_or_else(|| <Error<T>>::CodeRejected)?
104			.program_counter();
105
106		let gas_limit_polkavm: polkavm::Gas = runtime.ext().frame_meter_mut().sync_to_executor();
107
108		let mut instance = module.instantiate().map_err(|err| {
109			log::debug!(target: LOG_TARGET, "failed to instantiate polkavm module: {err:?}");
110			Error::<T>::CodeRejected
111		})?;
112
113		instance.set_gas(gas_limit_polkavm.saturating_add(code_map_credit));
114		instance
115			.set_interpreter_cache_size_limit(Some(polkavm::SetCacheSizeLimitArgs {
116				max_block_size: limits::code::BASIC_BLOCK_SIZE,
117				max_cache_size_bytes: limits::code::INTERPRETER_CACHE_BYTES
118					.try_into()
119					.map_err(|_| Error::<T>::CodeRejected)?,
120			}))
121			.map_err(|_| Error::<T>::CodeRejected)?;
122		instance.prepare_call_untyped(entry_program_counter, &[]);
123
124		Ok(PreparedCall { module, instance, runtime })
125	}
126}
127
128impl<T: Config> ContractBlob<T> {
129	/// We only check for size and nothing else when the code is uploaded.
130	pub fn from_pvm_code(code: Vec<u8>, owner: AccountIdOf<T>) -> Result<Self, DispatchError> {
131		// We do validation only when new code is deployed. This allows us to increase
132		// the limits later without affecting already deployed code.
133		let code = limits::code::enforce::<T>(code)?;
134
135		let code_len = code.len() as u32;
136		let deposit = calculate_code_deposit::<T>(code_len);
137
138		let code_info = CodeInfo {
139			owner,
140			deposit,
141			refcount: 0,
142			code_len,
143			code_type: BytecodeType::Pvm,
144			behaviour_version: Default::default(),
145		};
146		let code_hash = H256(sp_io::hashing::keccak_256(&code));
147		Ok(ContractBlob { code, code_info, code_hash })
148	}
149}
150
151impl<'a, E: Ext, M: PolkaVmInstance<E::T>> Runtime<'a, E, M> {
152	pub fn handle_interrupt(
153		&mut self,
154		interrupt: Result<polkavm::InterruptKind, polkavm::Error>,
155		module: &polkavm::Module,
156		instance: &mut M,
157	) -> Option<ExecResult> {
158		use polkavm::InterruptKind::*;
159
160		match interrupt {
161			Err(error) => {
162				// in contrast to the other returns this "should" not happen: log level error
163				log::error!(target: LOG_TARGET, "polkavm execution error: {error}");
164				Some(Err(Error::<E::T>::ExecutionFailed.into()))
165			},
166			Ok(Finished) => {
167				Some(Ok(ExecReturnValue { flags: ReturnFlags::empty(), data: Vec::new() }))
168			},
169			Ok(Trap) => Some(Err(Error::<E::T>::ContractTrapped.into())),
170			Ok(Segfault(_)) => Some(Err(Error::<E::T>::ExecutionFailed.into())),
171			Ok(NotEnoughGas) => Some(Err(Error::<E::T>::OutOfGas.into())),
172			Ok(Step) => None,
173			Ok(Ecalli(idx)) => {
174				// This is a special hard coded syscall index which is used by benchmarks
175				// to abort contract execution. It is used to terminate the execution without
176				// breaking up a basic block. The fixed index is used so that the benchmarks
177				// don't have to deal with import tables.
178				if cfg!(feature = "runtime-benchmarks") && idx == SENTINEL {
179					return Some(Ok(ExecReturnValue {
180						flags: ReturnFlags::empty(),
181						data: Vec::new(),
182					}));
183				}
184				let Some(syscall_symbol) = module.imports().get(idx) else {
185					return Some(Err(<Error<E::T>>::InvalidSyscall.into()));
186				};
187				match self.handle_ecall(instance, syscall_symbol.as_bytes()) {
188					Ok(None) => None,
189					Ok(Some(return_value)) => {
190						instance.write_output(return_value);
191						None
192					},
193					Err(TrapReason::Return(ReturnData { flags, data })) => {
194						match ReturnFlags::from_bits(flags) {
195							None => Some(Err(Error::<E::T>::InvalidCallFlags.into())),
196							Some(flags) => Some(Ok(ExecReturnValue { flags, data })),
197						}
198					},
199					Err(TrapReason::Termination) => Some(Ok(Default::default())),
200					Err(TrapReason::SupervisorError(error)) => Some(Err(error.into())),
201				}
202			},
203		}
204	}
205}
206
207// This is the API exposed to contracts.
208//
209// # Note
210//
211// Any input that leads to a out of bound error (reading or writing) or failing to decode
212// data passed to the supervisor will lead to a trap. This is not documented explicitly
213// for every function.
214#[define_env]
215pub mod env {
216	/// Noop function used to benchmark the time it takes to execute an empty function.
217	#[cfg(feature = "runtime-benchmarks")]
218	fn noop(&mut self, memory: &mut M) -> Result<(), TrapReason> {
219		Ok(())
220	}
221
222	/// Set the value at the given key in the contract storage.
223	/// See [`pallet_revive_uapi::HostFn::set_storage`]
224	#[mutating]
225	fn set_storage(
226		&mut self,
227		memory: &mut M,
228		flags: u32,
229		key_ptr: u32,
230		key_len: u32,
231		value_ptr: u32,
232		value_len: u32,
233	) -> Result<u32, TrapReason> {
234		self.set_storage(
235			memory,
236			flags,
237			key_ptr,
238			key_len,
239			StorageValue::Memory { ptr: value_ptr, len: value_len },
240		)
241	}
242
243	/// Sets the storage at a fixed 256-bit key with a fixed 256-bit value.
244	/// See [`pallet_revive_uapi::HostFn::set_storage_or_clear`].
245	#[mutating]
246	fn set_storage_or_clear(
247		&mut self,
248		memory: &mut M,
249		flags: u32,
250		key_ptr: u32,
251		value_ptr: u32,
252	) -> Result<u32, TrapReason> {
253		let value = memory.read(value_ptr, 32)?;
254
255		if value.iter().all(|&b| b == 0) {
256			self.clear_storage(memory, flags, key_ptr, SENTINEL)
257		} else {
258			self.set_storage(memory, flags, key_ptr, SENTINEL, StorageValue::Value(value))
259		}
260	}
261
262	/// Retrieve the value under the given key from storage.
263	/// See [`pallet_revive_uapi::HostFn::get_storage`]
264	fn get_storage(
265		&mut self,
266		memory: &mut M,
267		flags: u32,
268		key_ptr: u32,
269		key_len: u32,
270		out_ptr: u32,
271		out_len_ptr: u32,
272	) -> Result<ReturnErrorCode, TrapReason> {
273		self.get_storage(
274			memory,
275			flags,
276			key_ptr,
277			key_len,
278			out_ptr,
279			StorageReadMode::VariableOutput { output_len_ptr: out_len_ptr },
280		)
281	}
282
283	/// Reads the storage at a fixed 256-bit key and writes back a fixed 256-bit value.
284	/// See [`pallet_revive_uapi::HostFn::get_storage_or_zero`].
285	fn get_storage_or_zero(
286		&mut self,
287		memory: &mut M,
288		flags: u32,
289		key_ptr: u32,
290		out_ptr: u32,
291	) -> Result<(), TrapReason> {
292		let _ = self.get_storage(
293			memory,
294			flags,
295			key_ptr,
296			SENTINEL,
297			out_ptr,
298			StorageReadMode::FixedOutput32,
299		)?;
300
301		Ok(())
302	}
303
304	/// Make a call to another contract.
305	/// See [`pallet_revive_uapi::HostFn::call`].
306	fn call(
307		&mut self,
308		memory: &mut M,
309		flags_and_callee: u64,
310		ref_time_limit: u64,
311		proof_size_limit: u64,
312		deposit_and_value: u64,
313		input_data: u64,
314		output_data: u64,
315	) -> Result<ReturnErrorCode, TrapReason> {
316		let (flags, callee_ptr) = extract_hi_lo(flags_and_callee);
317		let (deposit_ptr, value_ptr) = extract_hi_lo(deposit_and_value);
318		let (input_data_len, input_data_ptr) = extract_hi_lo(input_data);
319		let (output_len_ptr, output_ptr) = extract_hi_lo(output_data);
320		let weight = Weight::from_parts(ref_time_limit, proof_size_limit);
321
322		self.charge_gas(RuntimeCosts::CopyFromContract(32))?;
323		let deposit_limit = memory.read_u256(deposit_ptr)?;
324
325		self.call(
326			memory,
327			CallFlags::from_bits(flags).ok_or(Error::<E::T>::InvalidCallFlags)?,
328			CallType::Call { value_ptr, stipend_limited: false },
329			callee_ptr,
330			&CallResources::from_weight_and_deposit(weight, deposit_limit),
331			input_data_ptr,
332			input_data_len,
333			output_ptr,
334			output_len_ptr,
335		)
336	}
337
338	/// Make a call to another contract.
339	/// See [`pallet_revive_uapi::HostFn::call_evm`].
340	fn call_evm(
341		&mut self,
342		memory: &mut M,
343		flags: u32,
344		callee: u32,
345		value_ptr: u32,
346		gas: u64,
347		input_data: u64,
348		output_data: u64,
349	) -> Result<ReturnErrorCode, TrapReason> {
350		let call_flags = CallFlags::from_bits(flags);
351		let (input_data_len, input_data_ptr) = extract_hi_lo(input_data);
352		let (output_len_ptr, output_ptr) = extract_hi_lo(output_data);
353		let (resources, stipend_limited) = if gas == u64::MAX {
354			(CallResources::NoLimits, false)
355		} else {
356			self.charge_gas(RuntimeCosts::CopyFromContract(32))?;
357			let value = memory.read_u256(value_ptr)?;
358			let read_only = call_flags.is_some_and(|flags| flags.contains(CallFlags::READ_ONLY));
359			let stipend_and_protections = StipendAndProtections::new(value, Some(gas), read_only);
360			(
361				CallResources::from_ethereum_gas(
362					gas.into(),
363					stipend_and_protections.gets_stipend(),
364				),
365				stipend_and_protections.is_stipend_limited(),
366			)
367		};
368
369		self.call(
370			memory,
371			call_flags.ok_or(Error::<E::T>::InvalidCallFlags)?,
372			CallType::Call { value_ptr, stipend_limited },
373			callee,
374			&resources,
375			input_data_ptr,
376			input_data_len,
377			output_ptr,
378			output_len_ptr,
379		)
380	}
381
382	/// Execute code in the context (storage, caller, value) of the current contract.
383	/// See [`pallet_revive_uapi::HostFn::delegate_call`].
384	fn delegate_call(
385		&mut self,
386		memory: &mut M,
387		flags_and_callee: u64,
388		ref_time_limit: u64,
389		proof_size_limit: u64,
390		deposit_ptr: u32,
391		input_data: u64,
392		output_data: u64,
393	) -> Result<ReturnErrorCode, TrapReason> {
394		let (flags, address_ptr) = extract_hi_lo(flags_and_callee);
395		let (input_data_len, input_data_ptr) = extract_hi_lo(input_data);
396		let (output_len_ptr, output_ptr) = extract_hi_lo(output_data);
397		let weight = Weight::from_parts(ref_time_limit, proof_size_limit);
398
399		self.charge_gas(RuntimeCosts::CopyFromContract(32))?;
400		let deposit_limit = memory.read_u256(deposit_ptr)?;
401
402		self.call(
403			memory,
404			CallFlags::from_bits(flags).ok_or(Error::<E::T>::InvalidCallFlags)?,
405			CallType::DelegateCall { stipend_limited: false },
406			address_ptr,
407			&CallResources::from_weight_and_deposit(weight, deposit_limit),
408			input_data_ptr,
409			input_data_len,
410			output_ptr,
411			output_len_ptr,
412		)
413	}
414
415	/// Same as `delegate_call` but with EVM gas.
416	/// See [`pallet_revive_uapi::HostFn::delegate_call_evm`].
417	fn delegate_call_evm(
418		&mut self,
419		memory: &mut M,
420		flags: u32,
421		callee: u32,
422		gas: u64,
423		input_data: u64,
424		output_data: u64,
425	) -> Result<ReturnErrorCode, TrapReason> {
426		let (input_data_len, input_data_ptr) = extract_hi_lo(input_data);
427		let (output_len_ptr, output_ptr) = extract_hi_lo(output_data);
428		let (resources, stipend_limited) = if gas == u64::MAX {
429			(CallResources::NoLimits, false)
430		} else {
431			let stipend_and_protections =
432				StipendAndProtections::new(U256::zero(), Some(gas), false);
433			(
434				CallResources::from_ethereum_gas(
435					gas.into(),
436					stipend_and_protections.gets_stipend(),
437				),
438				stipend_and_protections.is_stipend_limited(),
439			)
440		};
441
442		self.call(
443			memory,
444			CallFlags::from_bits(flags).ok_or(Error::<E::T>::InvalidCallFlags)?,
445			CallType::DelegateCall { stipend_limited },
446			callee,
447			&resources,
448			input_data_ptr,
449			input_data_len,
450			output_ptr,
451			output_len_ptr,
452		)
453	}
454
455	/// Instantiate a contract with the specified code hash.
456	/// See [`pallet_revive_uapi::HostFn::instantiate`].
457	#[mutating]
458	fn instantiate(
459		&mut self,
460		memory: &mut M,
461		ref_time_limit: u64,
462		proof_size_limit: u64,
463		deposit_and_value: u64,
464		input_data: u64,
465		output_data: u64,
466		address_and_salt: u64,
467	) -> Result<ReturnErrorCode, TrapReason> {
468		self.ext.ensure_not_stipend_limited()?;
469		let (deposit_ptr, value_ptr) = extract_hi_lo(deposit_and_value);
470		let (input_data_len, code_hash_ptr) = extract_hi_lo(input_data);
471		let (output_len_ptr, output_ptr) = extract_hi_lo(output_data);
472		let (address_ptr, salt_ptr) = extract_hi_lo(address_and_salt);
473		let Some(input_data_ptr) = code_hash_ptr.checked_add(32) else {
474			return Err(Error::<E::T>::OutOfBounds.into());
475		};
476		let Some(input_data_len) = input_data_len.checked_sub(32) else {
477			return Err(Error::<E::T>::OutOfBounds.into());
478		};
479
480		self.instantiate(
481			memory,
482			code_hash_ptr,
483			Weight::from_parts(ref_time_limit, proof_size_limit),
484			deposit_ptr,
485			value_ptr,
486			input_data_ptr,
487			input_data_len,
488			address_ptr,
489			output_ptr,
490			output_len_ptr,
491			salt_ptr,
492		)
493	}
494
495	/// Returns the total size of the contract call input data.
496	/// See [`pallet_revive_uapi::HostFn::call_data_size `].
497	fn call_data_size(&mut self, memory: &mut M) -> Result<u64, TrapReason> {
498		self.charge_gas(RuntimeCosts::CallDataSize)?;
499		Ok(self
500			.input_data
501			.as_ref()
502			.map(|input| input.len().try_into().expect("usize fits into u64; qed"))
503			.unwrap_or_default())
504	}
505
506	/// Stores the input passed by the caller into the supplied buffer.
507	/// See [`pallet_revive_uapi::HostFn::call_data_copy`].
508	fn call_data_copy(
509		&mut self,
510		memory: &mut M,
511		out_ptr: u32,
512		out_len: u32,
513		offset: u32,
514	) -> Result<(), TrapReason> {
515		self.charge_gas(RuntimeCosts::CallDataCopy(out_len))?;
516
517		let Some(input) = self.input_data.as_ref() else {
518			return Err(Error::<E::T>::InputForwarded.into());
519		};
520
521		let start = offset as usize;
522		if start >= input.len() {
523			memory.zero(out_ptr, out_len)?;
524			return Ok(());
525		}
526
527		let end = start.saturating_add(out_len as usize).min(input.len());
528		memory.write(out_ptr, &input[start..end])?;
529
530		let bytes_written = (end - start) as u32;
531		memory.zero(out_ptr.saturating_add(bytes_written), out_len - bytes_written)?;
532
533		Ok(())
534	}
535
536	/// Stores the U256 value at given call input `offset` into the supplied buffer.
537	/// See [`pallet_revive_uapi::HostFn::call_data_load`].
538	fn call_data_load(
539		&mut self,
540		memory: &mut M,
541		out_ptr: u32,
542		offset: u32,
543	) -> Result<(), TrapReason> {
544		self.charge_gas(RuntimeCosts::CallDataLoad)?;
545
546		let Some(input) = self.input_data.as_ref() else {
547			return Err(Error::<E::T>::InputForwarded.into());
548		};
549
550		let mut data = [0; 32];
551		let start = offset as usize;
552		let data = if start >= input.len() {
553			data // Any index is valid to request; OOB offsets return zero.
554		} else {
555			let end = start.saturating_add(32).min(input.len());
556			data[..end - start].copy_from_slice(&input[start..end]);
557			data.reverse();
558			data // Solidity expects right-padded data
559		};
560
561		self.write_fixed_sandbox_output(memory, out_ptr, &data, false, already_charged)?;
562
563		Ok(())
564	}
565
566	/// Cease contract execution and save a data buffer as a result of the execution.
567	/// See [`pallet_revive_uapi::HostFn::return_value`].
568	fn seal_return(
569		&mut self,
570		memory: &mut M,
571		flags: u32,
572		data_ptr: u32,
573		data_len: u32,
574	) -> Result<(), TrapReason> {
575		self.charge_gas(RuntimeCosts::CopyFromContract(data_len))?;
576		if data_len > limits::CALLDATA_BYTES {
577			Err(<Error<E::T>>::ReturnDataTooLarge)?;
578		}
579		Err(TrapReason::Return(ReturnData { flags, data: memory.read(data_ptr, data_len)? }))
580	}
581
582	/// Stores the address of the caller into the supplied buffer.
583	/// See [`pallet_revive_uapi::HostFn::caller`].
584	fn caller(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
585		self.charge_gas(RuntimeCosts::Caller)?;
586		let caller = <E::T as Config>::AddressMapper::to_address(self.ext.caller().account_id()?);
587		Ok(self.write_fixed_sandbox_output(
588			memory,
589			out_ptr,
590			caller.as_bytes(),
591			false,
592			already_charged,
593		)?)
594	}
595
596	/// Stores the address of the call stack origin into the supplied buffer.
597	/// See [`pallet_revive_uapi::HostFn::origin`].
598	fn origin(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
599		self.charge_gas(RuntimeCosts::Origin)?;
600		let origin = <E::T as Config>::AddressMapper::to_address(self.ext.origin().account_id()?);
601		Ok(self.write_fixed_sandbox_output(
602			memory,
603			out_ptr,
604			origin.as_bytes(),
605			false,
606			already_charged,
607		)?)
608	}
609
610	/// Retrieve the code hash for a specified contract address.
611	/// See [`pallet_revive_uapi::HostFn::code_hash`].
612	fn code_hash(&mut self, memory: &mut M, addr_ptr: u32, out_ptr: u32) -> Result<(), TrapReason> {
613		self.charge_gas(RuntimeCosts::CodeHash)?;
614		let address = memory.read_h160(addr_ptr)?;
615		Ok(self.write_fixed_sandbox_output(
616			memory,
617			out_ptr,
618			&self.ext.code_hash(&address).as_bytes(),
619			false,
620			already_charged,
621		)?)
622	}
623
624	/// Retrieve the code size for a given contract address.
625	/// See [`pallet_revive_uapi::HostFn::code_size`].
626	fn code_size(&mut self, memory: &mut M, addr_ptr: u32) -> Result<u64, TrapReason> {
627		self.charge_gas(RuntimeCosts::CodeSize)?;
628		let address = memory.read_h160(addr_ptr)?;
629		Ok(self.ext.code_size(&address))
630	}
631
632	/// Stores the address of the current contract into the supplied buffer.
633	/// See [`pallet_revive_uapi::HostFn::address`].
634	fn address(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
635		self.charge_gas(RuntimeCosts::Address)?;
636		let address = self.ext.address();
637		Ok(self.write_fixed_sandbox_output(
638			memory,
639			out_ptr,
640			address.as_bytes(),
641			false,
642			already_charged,
643		)?)
644	}
645
646	/// Stores the immutable data into the supplied buffer.
647	/// See [`pallet_revive_uapi::HostFn::get_immutable_data`].
648	fn get_immutable_data(
649		&mut self,
650		memory: &mut M,
651		out_ptr: u32,
652		out_len_ptr: u32,
653	) -> Result<(), TrapReason> {
654		// `immutable_data_len` is exact for a frame executing its own code and the
655		// `IMMUTABLE_BYTES` cap when the code (and so the data) belongs to another account —
656		// delegate calls, and calls to EIP-7702 delegated EOAs. Charge it, then settle on the
657		// actual length.
658		let charge_len = self.ext.immutable_data_len();
659		let charged = self.charge_gas(RuntimeCosts::GetImmutableData(charge_len))?;
660		let data = self.ext.get_immutable_data()?;
661		self.adjust_gas(charged, RuntimeCosts::GetImmutableData(data.len() as u32));
662		self.write_sandbox_output(memory, out_ptr, out_len_ptr, &data, false, already_charged)?;
663		Ok(())
664	}
665
666	/// Attaches the supplied immutable data to the currently executing contract.
667	/// See [`pallet_revive_uapi::HostFn::set_immutable_data`].
668	fn set_immutable_data(&mut self, memory: &mut M, ptr: u32, len: u32) -> Result<(), TrapReason> {
669		if len > limits::IMMUTABLE_BYTES {
670			return Err(Error::<E::T>::OutOfBounds.into());
671		}
672		self.charge_gas(RuntimeCosts::SetImmutableData(len))?;
673		let buf = memory.read(ptr, len)?;
674		let data = buf.try_into().expect("bailed out earlier; qed");
675		self.ext.set_immutable_data(data)?;
676		Ok(())
677	}
678
679	/// Stores the *free* balance of the current account into the supplied buffer.
680	/// See [`pallet_revive_uapi::HostFn::balance`].
681	fn balance(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
682		self.charge_gas(RuntimeCosts::Balance)?;
683		Ok(self.write_fixed_sandbox_output(
684			memory,
685			out_ptr,
686			&self.ext.balance().to_little_endian(),
687			false,
688			already_charged,
689		)?)
690	}
691
692	/// Stores the *free* balance of the supplied address into the supplied buffer.
693	/// See [`pallet_revive_uapi::HostFn::balance`].
694	fn balance_of(
695		&mut self,
696		memory: &mut M,
697		addr_ptr: u32,
698		out_ptr: u32,
699	) -> Result<(), TrapReason> {
700		let address = memory.read_h160(addr_ptr)?;
701		let balance = if address == self.ext.address() {
702			self.charge_gas(RuntimeCosts::Balance)?;
703			self.ext.balance()
704		} else {
705			self.charge_gas(RuntimeCosts::BalanceOf)?;
706			self.ext.balance_of(&address)
707		};
708		Ok(self.write_fixed_sandbox_output(
709			memory,
710			out_ptr,
711			&balance.to_little_endian(),
712			false,
713			already_charged,
714		)?)
715	}
716
717	/// Returns the chain ID.
718	/// See [`pallet_revive_uapi::HostFn::chain_id`].
719	fn chain_id(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
720		Ok(self.write_fixed_sandbox_output(
721			memory,
722			out_ptr,
723			&U256::from(<E::T as Config>::ChainId::get()).to_little_endian(),
724			false,
725			|_| Some(RuntimeCosts::CopyToContract(32)),
726		)?)
727	}
728
729	/// Returns the block ref_time limit.
730	/// See [`pallet_revive_uapi::HostFn::gas_limit`].
731	fn gas_limit(&mut self, memory: &mut M) -> Result<u64, TrapReason> {
732		self.charge_gas(RuntimeCosts::GasLimit)?;
733		Ok(self.ext.gas_limit())
734	}
735
736	/// Stores the value transferred along with this call/instantiate into the supplied buffer.
737	/// See [`pallet_revive_uapi::HostFn::value_transferred`].
738	fn value_transferred(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
739		self.charge_gas(RuntimeCosts::ValueTransferred)?;
740		Ok(self.write_fixed_sandbox_output(
741			memory,
742			out_ptr,
743			&self.ext.value_transferred().to_little_endian(),
744			false,
745			already_charged,
746		)?)
747	}
748
749	/// Returns the simulated ethereum `GASPRICE` value.
750	/// See [`pallet_revive_uapi::HostFn::gas_price`].
751	fn gas_price(&mut self, memory: &mut M) -> Result<u64, TrapReason> {
752		self.charge_gas(RuntimeCosts::GasPrice)?;
753		Ok(self.ext.effective_gas_price().saturated_into())
754	}
755
756	/// Returns the simulated ethereum `BASEFEE` value.
757	/// See [`pallet_revive_uapi::HostFn::base_fee`].
758	fn base_fee(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
759		self.charge_gas(RuntimeCosts::BaseFee)?;
760		Ok(self.write_fixed_sandbox_output(
761			memory,
762			out_ptr,
763			&Pallet::<E::T>::evm_base_fee().to_little_endian(),
764			false,
765			already_charged,
766		)?)
767	}
768
769	/// Load the latest block timestamp into the supplied buffer
770	/// See [`pallet_revive_uapi::HostFn::now`].
771	fn now(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
772		self.charge_gas(RuntimeCosts::Now)?;
773		Ok(self.write_fixed_sandbox_output(
774			memory,
775			out_ptr,
776			&self.ext.now().to_little_endian(),
777			false,
778			already_charged,
779		)?)
780	}
781
782	/// Deposit a contract event with the data buffer and optional list of topics.
783	/// See [pallet_revive_uapi::HostFn::deposit_event]
784	#[mutating]
785	fn deposit_event(
786		&mut self,
787		memory: &mut M,
788		topics_ptr: u32,
789		num_topic: u32,
790		data_ptr: u32,
791		data_len: u32,
792	) -> Result<(), TrapReason> {
793		self.charge_gas(RuntimeCosts::DepositEvent { num_topic, len: data_len })?;
794
795		if num_topic > limits::NUM_EVENT_TOPICS {
796			return Err(Error::<E::T>::TooManyTopics.into());
797		}
798
799		if data_len > limits::EVENT_BYTES {
800			return Err(Error::<E::T>::ValueTooLarge.into());
801		}
802
803		let topics: Vec<H256> = match num_topic {
804			0 => Vec::new(),
805			_ => {
806				let mut v = Vec::with_capacity(num_topic as usize);
807				let topics_len = num_topic * H256::len_bytes() as u32;
808				let buf = memory.read(topics_ptr, topics_len)?;
809				for chunk in buf.chunks_exact(H256::len_bytes()) {
810					v.push(H256::from_slice(chunk));
811				}
812				v
813			},
814		};
815		let topics =
816			ContractLogTopics::try_from(topics).map_err(|_| Error::<E::T>::TooManyTopics)?;
817
818		let event_data = memory.read(data_ptr, data_len)?;
819		self.ext.deposit_event(topics, event_data)?;
820		Ok(())
821	}
822
823	/// Stores the current block number of the current contract into the supplied buffer.
824	/// See [`pallet_revive_uapi::HostFn::block_number`].
825	fn block_number(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
826		self.charge_gas(RuntimeCosts::BlockNumber)?;
827		Ok(self.write_fixed_sandbox_output(
828			memory,
829			out_ptr,
830			&self.ext.block_number().to_little_endian(),
831			false,
832			already_charged,
833		)?)
834	}
835
836	/// Stores the block hash at given block height into the supplied buffer.
837	/// See [`pallet_revive_uapi::HostFn::block_hash`].
838	fn block_hash(
839		&mut self,
840		memory: &mut M,
841		block_number_ptr: u32,
842		out_ptr: u32,
843	) -> Result<(), TrapReason> {
844		self.charge_gas(RuntimeCosts::BlockHash)?;
845		let block_number = memory.read_u256(block_number_ptr)?;
846		let block_hash = self.ext.block_hash(block_number).unwrap_or(H256::zero());
847		Ok(self.write_fixed_sandbox_output(
848			memory,
849			out_ptr,
850			&block_hash.as_bytes(),
851			false,
852			already_charged,
853		)?)
854	}
855
856	/// Stores the current block author into the supplied buffer.
857	/// See [`pallet_revive_uapi::HostFn::block_author`].
858	fn block_author(&mut self, memory: &mut M, out_ptr: u32) -> Result<(), TrapReason> {
859		self.charge_gas(RuntimeCosts::BlockAuthor)?;
860		let block_author = self.ext.block_author();
861
862		Ok(self.write_fixed_sandbox_output(
863			memory,
864			out_ptr,
865			&block_author.as_bytes(),
866			false,
867			already_charged,
868		)?)
869	}
870
871	/// Computes the KECCAK 256-bit hash on the given input buffer.
872	/// See [`pallet_revive_uapi::HostFn::hash_keccak_256`].
873	fn hash_keccak_256(
874		&mut self,
875		memory: &mut M,
876		input_ptr: u32,
877		input_len: u32,
878		output_ptr: u32,
879	) -> Result<(), TrapReason> {
880		self.charge_gas(RuntimeCosts::HashKeccak256(input_len))?;
881		Ok(self.compute_hash_on_intermediate_buffer(
882			memory, keccak_256, input_ptr, input_len, output_ptr,
883		)?)
884	}
885
886	/// Stores the length of the data returned by the last call into the supplied buffer.
887	/// See [`pallet_revive_uapi::HostFn::return_data_size`].
888	fn return_data_size(&mut self, memory: &mut M) -> Result<u64, TrapReason> {
889		self.charge_gas(RuntimeCosts::ReturnDataSize)?;
890		Ok(self
891			.ext
892			.last_frame_output()
893			.data
894			.len()
895			.try_into()
896			.expect("usize fits into u64; qed"))
897	}
898
899	/// Stores data returned by the last call, starting from `offset`, into the supplied buffer.
900	/// See [`pallet_revive_uapi::HostFn::return_data_copy`].
901	fn return_data_copy(
902		&mut self,
903		memory: &mut M,
904		out_ptr: u32,
905		out_len_ptr: u32,
906		offset: u32,
907	) -> Result<(), TrapReason> {
908		let output = mem::take(self.ext.last_frame_output_mut());
909		let result = if offset as usize > output.data.len() {
910			Err(Error::<E::T>::OutOfBounds.into())
911		} else {
912			self.write_sandbox_output(
913				memory,
914				out_ptr,
915				out_len_ptr,
916				&output.data[offset as usize..],
917				false,
918				|len| Some(RuntimeCosts::CopyToContract(len)),
919			)
920		};
921		*self.ext.last_frame_output_mut() = output;
922		Ok(result?)
923	}
924
925	/// Returns the amount of evm gas left.
926	///
927	/// The name is only for historical reasons as renaming functions
928	/// would be a breaking change.
929	///
930	/// See [`pallet_revive_uapi::HostFn::gas_left`].
931	fn ref_time_left(&mut self, memory: &mut M) -> Result<u64, TrapReason> {
932		self.charge_gas(RuntimeCosts::RefTimeLeft)?;
933		Ok(self.ext.gas_left())
934	}
935
936	/// Reverts the execution without data and cedes all remaining gas.
937	///
938	/// See [`pallet_revive_uapi::HostFn::consume_all_gas`].
939	fn consume_all_gas(&mut self, memory: &mut M) -> Result<(), TrapReason> {
940		self.ext.frame_meter_mut().consume_all_weight();
941		Err(TrapReason::Return(ReturnData {
942			flags: ReturnFlags::REVERT.bits(),
943			data: Default::default(),
944		}))
945	}
946
947	/// Calculates Ethereum address from the ECDSA compressed public key and stores
948	/// See `uapi/sol/ISystem.sol`.
949	fn ecdsa_to_eth_address(
950		&mut self,
951		memory: &mut M,
952		key_ptr: u32,
953		out_ptr: u32,
954	) -> Result<ReturnErrorCode, TrapReason> {
955		self.charge_gas(RuntimeCosts::EcdsaToEthAddress)?;
956		let mut compressed_key: [u8; 33] = [0; 33];
957		memory.read_into_buf(key_ptr, &mut compressed_key)?;
958		let result = self.ext.ecdsa_to_eth_address(&compressed_key);
959		match result {
960			Ok(eth_address) => {
961				memory.write(out_ptr, eth_address.as_ref())?;
962				Ok(ReturnErrorCode::Success)
963			},
964			Err(_) => Ok(ReturnErrorCode::EcdsaRecoveryFailed),
965		}
966	}
967
968	/// Verify a sr25519 signature
969	/// See `uapi/sol/ISystem.sol`.
970	fn sr25519_verify(
971		&mut self,
972		memory: &mut M,
973		signature_ptr: u32,
974		pub_key_ptr: u32,
975		message_len: u32,
976		message_ptr: u32,
977	) -> Result<ReturnErrorCode, TrapReason> {
978		self.charge_gas(RuntimeCosts::Sr25519Verify(message_len))?;
979
980		let mut signature: [u8; 64] = [0; 64];
981		memory.read_into_buf(signature_ptr, &mut signature)?;
982
983		let mut pub_key: [u8; 32] = [0; 32];
984		memory.read_into_buf(pub_key_ptr, &mut pub_key)?;
985
986		let message: Vec<u8> = memory.read(message_ptr, message_len)?;
987
988		if self.ext.sr25519_verify(&signature, &message, &pub_key) {
989			Ok(ReturnErrorCode::Success)
990		} else {
991			Ok(ReturnErrorCode::Sr25519VerifyFailed)
992		}
993	}
994
995	/// Remove the calling account and transfer remaining balance:
996	/// **total** balance if code is deleted from storage, else **free** balance only.
997	/// See [`pallet_revive_uapi::HostFn::terminate`].
998	#[mutating]
999	fn terminate(&mut self, memory: &mut M, beneficiary_ptr: u32) -> Result<(), TrapReason> {
1000		self.ext.ensure_not_stipend_limited()?;
1001		let charged = self.charge_gas(RuntimeCosts::Terminate { code_removed: true })?;
1002		let beneficiary = memory.read_h160(beneficiary_ptr)?;
1003		if matches!(self.ext.terminate_if_same_tx(&beneficiary)?, crate::CodeRemoved::No) {
1004			self.adjust_gas(charged, RuntimeCosts::Terminate { code_removed: false });
1005		}
1006		Err(TrapReason::Termination)
1007	}
1008}
1009
1010#[cfg(test)]
1011mod tests {
1012	use super::*;
1013	use pallet_revive_types::runtime_api::*;
1014	use strum::VariantArray;
1015
1016	#[test]
1017	fn wire_has_all_syscalls() {
1018		let wire_syscalls = PolkavmSyscallV1::VARIANTS
1019			.iter()
1020			.copied()
1021			.map(<&'static str>::from)
1022			.collect::<Vec<_>>();
1023		let canonical_syscalls = list_trace_ops()
1024			.iter()
1025			.map(|bytes| str::from_utf8(bytes).unwrap())
1026			.collect::<Vec<_>>();
1027
1028		assert_eq!(
1029			wire_syscalls, canonical_syscalls,
1030			"There is a difference between the syscalls defined for the wire and the syscalls \
1031			available in the system. Wire = {wire_syscalls:?}. Available = {canonical_syscalls:?}"
1032		)
1033	}
1034}