1#![cfg(any(feature = "runtime-benchmarks", test))]
22#![cfg_attr(test, allow(dead_code))]
27
28#[cfg(all(test, feature = "runtime-benchmarks"))]
29mod tests;
30
31use crate::{
32 AccountInfo, BalanceOf, BalanceWithDust, Code, CodeInfoOf, Config, ContractBlob, ContractInfo,
33 Error, ExecConfig, ExecOrigin as Origin, OriginFor, Pallet as Contracts, PristineCode, Weight,
34 address::AddressMapper,
35 exec::{ExportedFunction, Key, PrecompileExt, Stack},
36 limits,
37 metering::{TransactionLimits, TransactionMeter},
38 transient_storage::MeterEntry,
39 vm::pvm::{PreparedCall, Runtime},
40};
41use alloc::{vec, vec::Vec};
42use frame_support::{storage::child, traits::fungible::Mutate};
43use frame_system::RawOrigin;
44use pallet_revive_fixtures::bench as bench_fixtures;
45use sp_core::{H160, H256, U256};
46use sp_io::hashing::keccak_256;
47use sp_runtime::traits::{Bounded, Hash};
48
49type StackExt<'a, T> = Stack<'a, T, ContractBlob<T>>;
50
51pub struct CallSetup<T: Config> {
53 contract: Contract<T>,
54 dest: T::AccountId,
55 origin: Origin<T>,
56 transaction_meter: TransactionMeter<T>,
57 value: BalanceOf<T>,
58 data: Vec<u8>,
59 transient_storage_size: u32,
60 exec_config: ExecConfig<T>,
61 read_only: bool,
62 delegate_call: bool,
63}
64
65impl<T> Default for CallSetup<T>
66where
67 T: Config,
68{
69 fn default() -> Self {
70 Self::new(VmBinaryModule::dummy())
71 }
72}
73
74impl<T> CallSetup<T>
75where
76 T: Config,
77{
78 pub fn new(module: VmBinaryModule) -> Self {
80 let contract = Contract::<T>::new(module, vec![]).unwrap();
81 let dest = contract.account_id.clone();
82 let origin = Origin::from_account_id(contract.caller.clone());
83
84 #[cfg(feature = "runtime-benchmarks")]
86 frame_benchmarking::benchmarking::add_to_whitelist(
87 crate::AccountInfoOf::<T>::hashed_key_for(&T::AddressMapper::to_address(
88 &contract.account_id,
89 ))
90 .into(),
91 );
92
93 Self {
94 contract,
95 dest,
96 origin,
97 transaction_meter: TransactionMeter::new(TransactionLimits::WeightAndDeposit {
98 weight_limit: Weight::MAX,
99 deposit_limit: default_deposit_limit::<T>(),
100 })
101 .unwrap(),
102 value: 0u32.into(),
103 data: vec![],
104 transient_storage_size: 0,
105 exec_config: ExecConfig::new_substrate_tx(),
106 read_only: false,
107 delegate_call: false,
108 }
109 }
110
111 pub fn set_storage_deposit_limit(&mut self, balance: BalanceOf<T>) {
113 self.transaction_meter = TransactionMeter::new(TransactionLimits::WeightAndDeposit {
114 weight_limit: Weight::MAX,
115 deposit_limit: balance,
116 })
117 .unwrap();
118 }
119
120 pub fn set_origin(&mut self, origin: Origin<T>) {
122 self.origin = origin;
123 }
124
125 pub fn set_balance(&mut self, value: impl Into<BalanceWithDust<BalanceOf<T>>>) {
127 self.contract.set_balance(value);
128 }
129
130 pub fn set_data(&mut self, value: Vec<u8>) {
132 self.data = value;
133 }
134
135 pub fn set_transient_storage_size(&mut self, size: u32) {
137 self.transient_storage_size = size;
138 }
139
140 pub fn set_read_only(&mut self, read_only: bool) {
142 self.read_only = read_only;
143 }
144
145 pub fn set_delegate_call(&mut self, delegate: bool) {
147 self.delegate_call = delegate;
148 }
149
150 pub fn data(&self) -> Vec<u8> {
152 self.data.clone()
153 }
154
155 pub fn contract(&self) -> Contract<T> {
157 self.contract.clone()
158 }
159
160 pub fn ext(&mut self) -> (StackExt<'_, T>, ContractBlob<T>) {
162 let mut ext = StackExt::bench_new_call(
163 T::AddressMapper::to_address(&self.dest),
164 self.origin.clone(),
165 &mut self.transaction_meter,
166 self.value,
167 &self.exec_config,
168 self.read_only,
169 self.delegate_call,
170 );
171 if self.transient_storage_size > 0 {
172 Self::with_transient_storage(&mut ext.0, self.transient_storage_size).unwrap();
173 }
174 ext
175 }
176
177 pub fn prepare_call<'a>(
179 ext: &'a mut StackExt<'a, T>,
180 module: ContractBlob<T>,
181 input: Vec<u8>,
182 ) -> PreparedCall<'a, StackExt<'a, T>> {
183 module.prepare_call(Runtime::new(ext, input), ExportedFunction::Call).unwrap()
184 }
185
186 fn with_transient_storage(ext: &mut StackExt<T>, size: u32) -> Result<(), &'static str> {
188 let &MeterEntry { amount, limit } = ext.transient_storage().meter().current();
189 ext.transient_storage().meter().current_mut().limit = size;
190 for i in 1u32.. {
191 let mut key_data = i.to_le_bytes().to_vec();
192 while key_data.last() == Some(&0) {
193 key_data.pop();
194 }
195 let key = Key::try_from_var(key_data).unwrap();
196 if let Err(e) = ext.set_transient_storage(&key, Some(Vec::new()), false) {
197 ext.transient_storage().meter().current_mut().limit = limit;
199 ext.transient_storage().meter().current_mut().amount = amount;
200 if e == Error::<T>::OutOfTransientStorage.into() {
201 break;
202 } else {
203 return Err("Initialization of the transient storage failed");
204 }
205 }
206 }
207 Ok(())
208 }
209}
210
211pub fn default_deposit_limit<T: Config>() -> BalanceOf<T> {
213 <BalanceOf<T>>::max_value()
214}
215
216pub fn caller_funding<T: Config>() -> BalanceOf<T> {
218 BalanceOf::<T>::max_value() / 10_000u32.into()
221}
222
223#[derive(Clone)]
225pub struct Contract<T: Config> {
226 pub caller: T::AccountId,
227 pub account_id: T::AccountId,
228 pub address: H160,
229}
230
231impl<T> Contract<T>
232where
233 T: Config,
234{
235 pub fn new(module: VmBinaryModule, data: Vec<u8>) -> Result<Contract<T>, &'static str> {
237 let caller = T::AddressMapper::to_fallback_account_id(&crate::test_utils::ALICE_ADDR);
238 Self::with_caller(caller, module, data)
239 }
240
241 #[cfg(feature = "runtime-benchmarks")]
243 pub fn with_index(
244 index: u32,
245 module: VmBinaryModule,
246 data: Vec<u8>,
247 ) -> Result<Contract<T>, &'static str> {
248 Self::with_caller(frame_benchmarking::account("instantiator", index, 0), module, data)
249 }
250
251 pub fn with_caller(
253 caller: T::AccountId,
254 module: VmBinaryModule,
255 data: Vec<u8>,
256 ) -> Result<Contract<T>, &'static str> {
257 T::Currency::set_balance(&caller, caller_funding::<T>());
258 let salt = Some([0xffu8; 32]);
259 let origin: OriginFor<T> = RawOrigin::Signed(caller.clone()).into();
260
261 Contracts::<T>::map_account(origin.clone()).ok();
263
264 #[cfg(feature = "runtime-benchmarks")]
265 frame_benchmarking::benchmarking::add_to_whitelist(
266 frame_system::Account::<T>::hashed_key_for(&caller).into(),
267 );
268
269 let outcome = Contracts::<T>::bare_instantiate(
270 origin,
271 U256::zero(),
272 TransactionLimits::WeightAndDeposit {
273 weight_limit: Weight::MAX,
274 deposit_limit: default_deposit_limit::<T>(),
275 },
276 Code::Upload(module.code),
277 data,
278 salt,
279 &ExecConfig::new_substrate_tx(),
280 );
281
282 let address = outcome.result?.addr;
283 let account_id = T::AddressMapper::to_fallback_account_id(&address);
284 let result = Contract { caller, address, account_id };
285
286 AccountInfo::<T>::insert_contract(&address, result.info()?);
287 Ok(result)
288 }
289
290 pub fn with_storage(
292 code: VmBinaryModule,
293 stor_num: u32,
294 stor_size: u32,
295 ) -> Result<Self, &'static str> {
296 let contract = Contract::<T>::new(code, vec![])?;
297 let storage_items = (0..stor_num)
298 .map(|i| {
299 let hash = T::Hashing::hash_of(&i)
300 .as_ref()
301 .try_into()
302 .map_err(|_| "Hash too big for storage key")?;
303 Ok((hash, vec![42u8; stor_size as usize]))
304 })
305 .collect::<Result<Vec<_>, &'static str>>()?;
306 contract.store(&storage_items)?;
307 Ok(contract)
308 }
309
310 pub fn store(&self, items: &Vec<([u8; 32], Vec<u8>)>) -> Result<(), &'static str> {
312 let info = self.info()?;
313 for item in items {
314 info.write(&Key::Fix(item.0), Some(item.1.clone()), None, false)
315 .map_err(|_| "Failed to write storage to restoration dest")?;
316 }
317
318 AccountInfo::<T>::insert_contract(&self.address, info);
319 Ok(())
320 }
321
322 pub fn with_unbalanced_storage_trie(
324 code: VmBinaryModule,
325 key: &[u8],
326 ) -> Result<Self, &'static str> {
327 const UNBALANCED_TRIE_LAYERS: u32 = 20;
329
330 if (key.len() as u32) < UNBALANCED_TRIE_LAYERS.div_ceil(2) {
331 return Err("Key size too small to create the specified trie");
332 }
333
334 let value = vec![16u8; limits::STORAGE_BYTES as usize];
335 let contract = Contract::<T>::new(code, vec![])?;
336 let info = contract.info()?;
337 let child_trie_info = info.child_trie_info();
338 child::put_raw(&child_trie_info, &key, &value);
339 for l in 0..UNBALANCED_TRIE_LAYERS {
340 let pos = l as usize / 2;
341 let mut key_new = key.to_vec();
342 for i in 0u8..16 {
343 key_new[pos] = if l % 2 == 0 {
344 (key_new[pos] & 0xF0) | i
345 } else {
346 (key_new[pos] & 0x0F) | (i << 4)
347 };
348
349 if key == &key_new {
350 continue;
351 }
352 child::put_raw(&child_trie_info, &key_new, &value);
353 }
354 }
355 Ok(contract)
356 }
357
358 pub fn address_info(addr: &T::AccountId) -> Result<ContractInfo<T>, &'static str> {
360 <AccountInfo<T>>::load_contract(&T::AddressMapper::to_address(addr))
361 .ok_or("Expected contract to exist at this point.")
362 }
363
364 pub fn info(&self) -> Result<ContractInfo<T>, &'static str> {
366 Self::address_info(&self.account_id)
367 }
368
369 pub fn set_balance(&self, value: impl Into<BalanceWithDust<BalanceOf<T>>>) {
371 let (value, dust) = value.into().deconstruct();
372 T::Currency::set_balance(&self.account_id, value);
373 crate::AccountInfoOf::<T>::mutate(&self.address, |account| {
374 account.as_mut().map(|a| a.dust = dust);
375 });
376 }
377
378 pub fn code_exists(hash: &sp_core::H256) -> bool {
380 <PristineCode<T>>::contains_key(hash) && <CodeInfoOf<T>>::contains_key(&hash)
381 }
382
383 pub fn code_removed(hash: &sp_core::H256) -> bool {
385 !<PristineCode<T>>::contains_key(hash) && !<CodeInfoOf<T>>::contains_key(&hash)
386 }
387}
388
389#[derive(Clone)]
391pub struct VmBinaryModule {
392 pub code: Vec<u8>,
393 pub hash: H256,
394}
395
396impl VmBinaryModule {
397 pub fn dummy() -> Self {
399 Self::new(bench_fixtures::dummy().to_vec())
400 }
401
402 fn new(code: Vec<u8>) -> Self {
403 let hash = keccak_256(&code);
404 Self { code, hash: H256(hash) }
405 }
406}
407
408#[cfg(any(test, feature = "runtime-benchmarks"))]
409impl VmBinaryModule {
410 pub fn evm_init_code_for_runtime_size(size: u32) -> Self {
414 use revm::bytecode::opcode::{PUSH1, PUSH3, RETURN};
415 assert!(size <= 0x00FF_FFFF, "size {size} exceeds PUSH3 max (16MiB - 1)");
416 let [_, b1, b2, b3] = size.to_be_bytes();
417 let code = vec![
418 PUSH3, b1, b2, b3, PUSH1, 0, RETURN, ];
422 Self::new(code)
423 }
424
425 pub fn evm_noop(size: u32) -> Self {
427 use revm::bytecode::opcode::JUMPDEST;
428
429 let code = vec![JUMPDEST; size as usize];
430 Self::new(code)
431 }
432}
433
434#[cfg(feature = "runtime-benchmarks")]
435impl VmBinaryModule {
436 pub fn dummy_unique(replace_with: u32) -> Self {
438 Self::new(bench_fixtures::dummy_unique(replace_with))
439 }
440
441 pub fn sized(size: u32) -> Self {
446 Self::with_num_instructions(size / 3)
449 }
450
451 pub fn with_num_instructions(num_instructions: u32) -> Self {
462 use alloc::{fmt::Write, string::ToString};
463 let mut text = "
464 pub @deploy:
465 ret
466 pub @call:
467 "
468 .to_string();
469 for i in 0..num_instructions {
470 match i {
471 0 => writeln!(text, "ecalli {}", crate::SENTINEL).unwrap(),
474 i if i % (limits::code::BASIC_BLOCK_SIZE - 1) == 0 => {
475 text.push_str("fallthrough\n")
476 },
477 _ => text.push_str("a0 = a1 + a2\n"),
478 }
479 }
480 text.push_str("ret\n");
481 Self::from_assembly(&text)
482 }
483
484 pub const BRANCH_BLOCKS: u32 = 16_000;
498
499 pub fn with_branch_blocks(b: u32) -> Self {
514 let mut text = alloc::string::String::from("pub @deploy:\nret\npub @call:\n");
515 for i in 0..Self::BRANCH_BLOCKS {
516 if i == b {
517 text.push_str(&alloc::format!("ecalli {}\n", crate::SENTINEL));
518 }
519 text.push_str(&alloc::format!("jump @next{i} if a0 == a0\n@next{i}:\n"));
520 }
521 if b == Self::BRANCH_BLOCKS {
522 text.push_str(&alloc::format!("ecalli {}\n", crate::SENTINEL));
523 }
524 text.push_str("ret\n");
525 Self::from_assembly(&text)
526 }
527
528 pub fn with_entry_block(n: u32) -> Self {
543 const FILLER: &str = "u64 [a0 + 0x12345678] = 0x12345678\n";
544 let mut text =
545 alloc::format!("pub @deploy:\nret\npub @call:\necalli {}\n", crate::SENTINEL);
546 for _ in 2..n {
547 text.push_str(FILLER);
548 }
549 text.push_str("fallthrough\n");
550 for _ in n..limits::code::BASIC_BLOCK_SIZE {
551 text.push_str(FILLER);
552 }
553 text.push_str("ret\n");
554 Self::from_assembly(&text)
555 }
556
557 pub const LOAD_CHAIN_SLOTS: u32 = 1024;
571
572 pub const LOAD_CHAIN_SLOT_BYTES: u32 = 128;
576
577 pub fn with_load_chain() -> Self {
586 let mut text = alloc::format!(
587 "%rw_data_size = {}\npub @deploy:\nret\npub @call:\n@loop:\njump @done if t0 == a1\n",
588 Self::LOAD_CHAIN_SLOTS * Self::LOAD_CHAIN_SLOT_BYTES,
589 );
590 for _ in 3..crate::metering::LOAD_CHAIN_GAS {
591 text.push_str("a0 = u64 [a0]\n");
592 }
593 text.push_str("t0 = t0 + 1\njump @loop\n@done:\nret\n");
594 Self::from_assembly(&text)
595 }
596
597 pub fn with_indirect_jump_cycle() -> Self {
630 use polkavm_common::{
631 abi::VM_CODE_ADDRESS_ALIGNMENT,
632 program::{Instruction, Reg},
633 writer::ProgramBlobBuilder,
634 };
635 use rand::{SeedableRng, seq::SliceRandom};
636
637 const DEPLOY: u32 = 0;
638 const ENTRY: u32 = 1;
639 const WARM_UP: u32 = 2;
640 const WARM_UP_DONE: u32 = 4;
641 const HEAD: u32 = 5;
642 const DONE: u32 = 7;
643 const CYCLE: u32 = 8;
644
645 let blocks = crate::metering::INDIRECT_JUMP_GAS - 3;
646 let address = |entry: u32| {
650 i32::try_from((entry + 1) * VM_CODE_ADDRESS_ALIGNMENT)
651 .expect("the jump table has fewer than 2^30 entries; qed")
652 };
653 let head = address(0);
654 let block = |i: u32| address(1 + i);
655 let warm_up = address(1 + blocks);
656 let step = block(0) - head;
657
658 let mut order: Vec<u32> = (0..blocks).collect();
659 order.shuffle(&mut rand_pcg::Pcg64::seed_from_u64(1337));
660 let lap: Vec<i32> = core::iter::once(head).chain(order.iter().map(|&i| block(i))).collect();
663 let two_ahead = |position: usize| lap[(position + 2) % lap.len()];
664
665 let a0 = Reg::A0.into();
666 let a1 = Reg::A1.into();
667 let t0 = Reg::T0.into();
668 let t1 = Reg::T1.into();
669 let ra = Reg::RA.into();
670 let mut code = vec![
671 Instruction::jump_indirect(ra, 0),
672 Instruction::load_imm(t1, head),
675 Instruction::fallthrough,
676 Instruction::add_imm_64(t1, t1, step),
677 Instruction::branch_eq_imm(t1, warm_up, WARM_UP_DONE),
678 Instruction::load_imm_and_jump_indirect(a0, t1, warm_up, 0),
679 Instruction::load_imm(a0, lap[1]),
680 Instruction::fallthrough,
681 Instruction::branch_eq(t0, a1, DONE),
682 Instruction::add_imm_64(t0, t0, 1),
683 Instruction::load_imm_and_jump_indirect(a0, a0, two_ahead(0), 0),
684 Instruction::jump_indirect(ra, 0),
685 ];
686 let mut cycle: Vec<(u32, Instruction)> = order
687 .iter()
688 .enumerate()
689 .map(|(k, &i)| {
690 (i, Instruction::load_imm_and_jump_indirect(a0, a0, two_ahead(1 + k), 0))
691 })
692 .collect();
693 cycle.sort_by_key(|(i, _)| *i);
694 code.extend(cycle.into_iter().map(|(_, instruction)| instruction));
695 let jump_table: Vec<u32> = core::iter::once(HEAD)
696 .chain((0..blocks).map(|i| CYCLE + i))
697 .chain(core::iter::once(WARM_UP))
698 .collect();
699
700 let mut builder =
701 ProgramBlobBuilder::new(polkavm_common::program::InstructionSetKind::ReviveV1);
702 builder.set_code(&code, &jump_table);
703 builder.add_export_by_basic_block(DEPLOY, b"deploy");
704 builder.add_export_by_basic_block(ENTRY, b"call");
705 Self::new(builder.into_vec().expect("the program built here is valid; qed"))
706 }
707
708 pub const MAX_CODE_BYTES: u32 = (limits::code::PURGABLE_MEMORY_LIMIT -
715 limits::code::INTERPRETER_CACHE_BYTES) /
716 polkavm_common::program::INTERPRETER_FLATMAP_ENTRY_SIZE -
717 limits::PAGE_SIZE;
718
719 pub fn with_code_bytes(code_bytes: u32) -> Self {
726 let mut text = alloc::format!(
727 "pub @deploy:\nret\npub @call:\necalli {}\nfallthrough\n",
728 crate::SENTINEL
729 );
730 for i in 0..code_bytes / 3 {
731 if i % limits::code::BASIC_BLOCK_SIZE == limits::code::BASIC_BLOCK_SIZE - 1 {
732 text.push_str("fallthrough\n");
733 } else {
734 text.push_str("a0 = a1 + a2\n");
735 }
736 }
737 text.push_str("ret\n");
738 Self::from_assembly(&text)
739 }
740
741 fn from_assembly(text: &str) -> Self {
743 let code = polkavm_common::assembler::assemble(
744 Some(polkavm_common::program::InstructionSetKind::ReviveV1),
745 text,
746 )
747 .expect("callers pass assembly text built in this module, which is valid; qed");
748 Self::new(code)
749 }
750
751 pub fn noop() -> Self {
753 Self::new(bench_fixtures::noop().to_vec())
754 }
755}