referrerpolicy=no-referrer-when-downgrade

pallet_revive/
call_builder.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
18//! Types to build an environment that can be used to test and benchmark host function /
19//! pre-compiles.
20
21#![cfg(any(feature = "runtime-benchmarks", test))]
22// A lot of this code is only used in benchmarking but we also want to use the code for testing
23// pre-compiles eventually. For that we will probably export some of those types from the crate.
24// Until then we simply ignore the warnings that arise when compiling tests without runtime
25// benchmarks.
26#![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
51/// A builder used to prepare a contract call.
52pub 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	/// Setup a new call for the given module.
79	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		// The call that creates the frame already pays for the info.
85		#[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	/// Set the meter's storage deposit limit.
112	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	/// Set the call's origin.
121	pub fn set_origin(&mut self, origin: Origin<T>) {
122		self.origin = origin;
123	}
124
125	/// Set the contract's balance.
126	pub fn set_balance(&mut self, value: impl Into<BalanceWithDust<BalanceOf<T>>>) {
127		self.contract.set_balance(value);
128	}
129
130	/// Set the call's input data.
131	pub fn set_data(&mut self, value: Vec<u8>) {
132		self.data = value;
133	}
134
135	/// Set the transient storage size.
136	pub fn set_transient_storage_size(&mut self, size: u32) {
137		self.transient_storage_size = size;
138	}
139
140	/// Set the read-only flag on the call stack frame.
141	pub fn set_read_only(&mut self, read_only: bool) {
142		self.read_only = read_only;
143	}
144
145	/// Mark the call as a delegate call.
146	pub fn set_delegate_call(&mut self, delegate: bool) {
147		self.delegate_call = delegate;
148	}
149
150	/// Get the call's input data.
151	pub fn data(&self) -> Vec<u8> {
152		self.data.clone()
153	}
154
155	/// Get the call's contract.
156	pub fn contract(&self) -> Contract<T> {
157		self.contract.clone()
158	}
159
160	/// Build the call stack.
161	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	/// Prepare a call to the module.
178	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	/// Add transient_storage
187	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				// Restore previous settings.
198				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
211/// The deposit limit we use for benchmarks.
212pub fn default_deposit_limit<T: Config>() -> BalanceOf<T> {
213	<BalanceOf<T>>::max_value()
214}
215
216/// The funding that each account that either calls or instantiates contracts is funded with.
217pub fn caller_funding<T: Config>() -> BalanceOf<T> {
218	// Minting can overflow, so we can't abuse of the funding. This value happens to be big enough,
219	// but not too big to make the total supply overflow.
220	BalanceOf::<T>::max_value() / 10_000u32.into()
221}
222
223/// An instantiated and deployed contract.
224#[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	/// Create new contract and use a default account id as instantiator.
236	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	/// Create new contract and use an account id derived from the supplied index as instantiator.
242	#[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	/// Create new contract and use the supplied `caller` as instantiator.
252	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		// We ignore the error since we might also pass an already mapped account here.
262		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	/// Create a new contract with the supplied storage item count and size each.
291	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	/// Store the supplied storage items into this contracts storage.
311	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	/// Create a new contract with the specified unbalanced storage trie.
323	pub fn with_unbalanced_storage_trie(
324		code: VmBinaryModule,
325		key: &[u8],
326	) -> Result<Self, &'static str> {
327		/// Number of layers in a Radix16 unbalanced trie.
328		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	/// Get the `ContractInfo` of the `addr` or an error if it no longer exists.
359	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	/// Get the `ContractInfo` of this contract or an error if it no longer exists.
365	pub fn info(&self) -> Result<ContractInfo<T>, &'static str> {
366		Self::address_info(&self.account_id)
367	}
368
369	/// Set the balance of the contract to the supplied amount.
370	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	/// Returns `true` iff all storage entries related to code storage exist.
379	pub fn code_exists(hash: &sp_core::H256) -> bool {
380		<PristineCode<T>>::contains_key(hash) && <CodeInfoOf<T>>::contains_key(&hash)
381	}
382
383	/// Returns `true` iff no storage entry related to code storage exist.
384	pub fn code_removed(hash: &sp_core::H256) -> bool {
385		!<PristineCode<T>>::contains_key(hash) && !<CodeInfoOf<T>>::contains_key(&hash)
386	}
387}
388
389/// A vm binary module ready to be put on chain.
390#[derive(Clone)]
391pub struct VmBinaryModule {
392	pub code: Vec<u8>,
393	pub hash: H256,
394}
395
396impl VmBinaryModule {
397	/// Return a contract code that does nothing.
398	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	// Creates EVM init code that deploys `size` bytes of runtime code (all STOP opcodes).
411	// EVM memory is zero-initialized, so RETURN(0, size) produces `size` bytes of 0x00.
412	// The runtime code is what gets stored in PristineCode and loaded on every call.
413	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, // push runtime code size
419			PUSH1, 0,      // push memory offset 0
420			RETURN, // return `size` bytes from memory as runtime code
421		];
422		Self::new(code)
423	}
424
425	/// An evm contract that executes `size` JUMPDEST instructions.
426	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	/// Same as [`Self::dummy`] but uses `replace_with` to make the code unique.
437	pub fn dummy_unique(replace_with: u32) -> Self {
438		Self::new(bench_fixtures::dummy_unique(replace_with))
439	}
440
441	/// Same as as `with_num_instructions` but based on the blob size.
442	///
443	/// This is needed when we weigh a blob without knowing how much instructions it
444	/// contains.
445	pub fn sized(size: u32) -> Self {
446		// Due to variable length encoding of instructions this is not precise. But we only
447		// need rough numbers for our benchmarks.
448		Self::with_num_instructions(size / 3)
449	}
450
451	/// A contract code of specified number of instructions that uses all its bytes for instructions
452	/// but will return immediately.
453	///
454	/// All the basic blocks are maximum sized (only the first is important though). This is to
455	/// account for the fact that the interpreter will compile one basic block at a time even
456	/// when no code is executed. Hence this contract will trigger the compilation of a maximum
457	/// sized basic block and then return with its first instruction.
458	///
459	/// All the code will be put into the "call" export. Hence this code can be safely used for the
460	/// `instantiate_with_code` benchmark where no compilation of any block should be measured.
461	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				// return execution right away without breaking up basic block
472				// SENTINEL is a hard coded syscall that terminates execution
473				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	/// The number of branches in [`Self::with_branch_blocks`].
485	///
486	/// All blocks the contract enters must fit into the interpreter cache at the same time, or
487	/// the interpreter would reset the cache and compile blocks again. The cache holds
488	/// `INTERPRETER_CACHE_BYTES / 24` entries and keeps room for one block of
489	/// `BASIC_BLOCK_SIZE` instructions. A block of one instruction takes two entries: its gas
490	/// charge and the instruction. 16000 such blocks and the final block of two instructions
491	/// take 32003 entries, below the 42689 usable.
492	///
493	/// The cache entries are kept in vectors that double their capacity as they grow, up to
494	/// the cache limit. 32003 entries stay below a capacity of 32768. Above it the vectors would
495	/// be reallocated once more, which adds a copy of the whole cache to the largest values of
496	/// `b` and skews the linear fit.
497	pub const BRANCH_BLOCKS: u32 = 16_000;
498
499	/// A contract whose `call` export enters `b` basic blocks of one instruction and returns.
500	///
501	/// The code holds [`Self::BRANCH_BLOCKS`] branches, one `ecalli SENTINEL` and one `ret`.
502	/// Each branch ends a basic block, so each forms a block of its own, and it is always taken
503	/// to the next block. The `ecalli SENTINEL` comes after `b` of them: the call compiles and
504	/// runs `b` blocks of one branch each, then compiles the block of the `ecalli SENTINEL` and
505	/// the instruction after it, and stops at the `ecalli SENTINEL`. The code holds the same
506	/// instructions for every `b`, so its size does not depend on `b`.
507	///
508	/// The branch is a `branch_eq` of two registers. Of the instructions that end a basic block
509	/// and continue at another one, a register branch is the slowest to compile and run per
510	/// block, so the slope is an upper bound for the other terminators.
511	///
512	/// `b` is within `0..=BRANCH_BLOCKS`.
513	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	/// A contract whose `call` export compiles an entry block of `n` instructions and returns.
529	///
530	/// The entry block starts with an `ecalli SENTINEL`, which ends the execution but not the
531	/// basic block, so the interpreter compiles the whole block before running it. `n - 2`
532	/// fillers and a `fallthrough` follow. The remaining `BASIC_BLOCK_SIZE - n` fillers and a
533	/// `ret` form a second block, which is never entered. The code holds the same instructions
534	/// for every `n`, so its size does not depend on `n`.
535	///
536	/// The filler is a `store_imm_indirect_u64` with two 4 byte immediates. It never executes.
537	/// Of the instructions that do not end a basic block, the `store_imm_indirect` kinds are the
538	/// slowest to compile per instruction, with short immediates as well, so the slope is an
539	/// upper bound for the others.
540	///
541	/// `n` is within `2..=BASIC_BLOCK_SIZE`.
542	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	/// The number of slots in the chain of addresses of [`Self::with_load_chain`].
558	///
559	/// With slots [`Self::LOAD_CHAIN_SLOT_BYTES`] apart, the chain stays in the L2 but not in the
560	/// L1 data cache of the reference hardware: Intel Ice Lake (48 KiB L1D of 12 ways, 1.25 MiB
561	/// L2 of 20 ways) and AMD Zen 3 (32 KiB L1D of 8 ways, 512 KiB L2 of 8 ways), all with 64
562	/// byte lines, 64 L1D sets and 1024 L2 sets. A load touches one line, or two in the
563	/// benchmark variant where every load spans two lines. With slots two lines apart, the 1024
564	/// lines (64 KiB) of the other variants map to every other set and the 2048 lines (128 KiB)
565	/// of the spanning variant to every set. Either way each L1D set in use receives 32 lines
566	/// against at most 12 ways, and each L2 set 2 lines, a quarter of the Zen 3 ways. The L2 is
567	/// physically indexed, so 2 lines per set is an average that depends on where the 32 4 KiB
568	/// pages of the chain land. Every load also takes a DTLB lookup; the 32 pages fit the 64 entry
569	/// L1 DTLB of both.
570	pub const LOAD_CHAIN_SLOTS: u32 = 1024;
571
572	/// The distance between two slots of [`Self::with_load_chain`] in bytes.
573	///
574	/// Two 64 byte cache lines; see [`Self::LOAD_CHAIN_SLOTS`].
575	pub const LOAD_CHAIN_SLOT_BYTES: u32 = 128;
576
577	/// A contract whose `call` export runs `a1` iterations of `LOAD_CHAIN_GAS - 3` dependent
578	/// loads.
579	///
580	/// An iteration is the branch `jump @done if t0 == a1`, then one basic block of loads
581	/// `a0 = u64 [a0]`, `t0 = t0 + 1` and `jump @loop`. Each load reads the address of the next
582	/// one, so it cannot start before the previous load has finished. The contract declares
583	/// [`Self::LOAD_CHAIN_SLOTS`] slots of [`Self::LOAD_CHAIN_SLOT_BYTES`] as read-write data.
584	/// The caller writes the chain of addresses into it and sets `a0` to the first address.
585	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	/// A contract whose `call` export runs `a1` laps of a random cycle of indirect jumps.
598	///
599	/// The cycle has `INDIRECT_JUMP_GAS - 3` basic blocks of one instruction each. Every block
600	/// is a `load_imm_and_jump_indirect` that jumps to the address in `a0` and loads the address
601	/// of the block after the next one into `a0`. A lap starts and ends at a block with the
602	/// branch `jump @done if t0 == a1`, followed by `t0 = t0 + 1` and the jump into the cycle.
603	/// The order of the blocks in the cycle is a fixed random permutation, so consecutive
604	/// jumps go to unrelated code addresses.
605	///
606	/// Before the first lap, a warm-up loop enters every cycle block once in code order, with
607	/// `a0` holding the loop's own address so that the block jumps back to it. The interpreter
608	/// compiles a block when execution first enters it and appends its handlers to its cache,
609	/// so the cache holds the cycle blocks in code order. A lap visits them in the random order
610	/// of the cycle, so its reads of handlers and arguments are as scattered as its reads of the
611	/// jump table and the code map. The warm-up runs once per call whatever `a1` is.
612	///
613	/// The number of blocks keeps the interpreter data a lap reads in the L2 but not in the L1
614	/// data cache of the reference hardware (see [`Self::LOAD_CHAIN_SLOTS`]). A jump into a
615	/// block reads the block's 2 byte jump table entry, its 4 byte entry in the code map, and
616	/// the 8 byte handler and 16 byte arguments of its two compiled instructions: the gas charge
617	/// and the jump. The code map has one entry per code byte and a block is 5 bytes of code, so
618	/// the entries of consecutive blocks are 20 bytes apart and a lap reads every cache line of
619	/// the map: 20 bytes per block. Every block thus adds 2 + 20 + 2 * 24 = 70 bytes to the data
620	/// of a lap. The code itself is read only when a block is compiled. The
621	/// `INDIRECT_JUMP_GAS - 3 = 3000` blocks take 205 KiB, 4.3 times the Ice Lake L1D: each of
622	/// the 64 L1D sets receives about 51 lines against at most 12 ways. Each of the 1024 L2 sets
623	/// receives 3.2 lines, 40% of the Zen 3 ways. The L2 is physically indexed, so 3.2 lines per
624	/// set is an average that depends on where the pages land. The data spans four arrays of
625	/// 4 KiB pages, jump table 2 to 3, code map 15 to 16, handlers 12 to 13 and arguments 24 to
626	/// 25, so 53 to 57 pages plus the interpreter's own state. They fit the fully associative 64
627	/// entry L1 DTLB of Zen 3. The 64 entry L1 DTLB of Ice Lake is 4-way set associative, so some
628	/// of them may miss it and hit the second level TLB.
629	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		// Jump table entry 0 is `HEAD`, entry `1 + i` is cycle block `i` and entry `1 + blocks`
647		// is `WARM_UP`. A jump table entry `k` has the code address
648		// `(k + 1) * VM_CODE_ADDRESS_ALIGNMENT`.
649		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		// The lap visits `HEAD`, then the cycle blocks in `order`. Each block loads the address
661		// of the block two steps ahead.
662		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			// `t1` walks the addresses of the cycle blocks in code order. Each block is entered
673			// with `a0` holding the address of `WARM_UP`, so it jumps back.
674			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	/// The largest code section [`Self::with_code_bytes`] builds.
709	///
710	/// The interpreter keeps a map with one entry per byte of the code section. It counts
711	/// towards [`limits::code::PURGABLE_MEMORY_LIMIT`] next to the interpreter cache, which a
712	/// contract of this size fills. That allows at most 512 KiB of code. One page is left as a
713	/// margin for the code that [`Self::with_code_bytes`] adds.
714	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	/// A contract with a code section of about `code_bytes` bytes whose `call` export returns
720	/// at once.
721	///
722	/// The `call` export is a basic block of `ecalli SENTINEL` and `fallthrough`, which stops
723	/// the call. Blocks of `a0 = a1 + a2`, 3 bytes each, fill the rest of the code section and
724	/// never run. Only the size of the code section depends on `code_bytes`.
725	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	/// Assembles `text` into a contract for the instruction set contracts use.
742	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	/// A contract code that calls the "noop" host function in a loop depending in the input.
752	pub fn noop() -> Self {
753		Self::new(bench_fixtures::noop().to_vec())
754	}
755}