referrerpolicy=no-referrer-when-downgrade

pallet_revive_fixtures/
lib.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#![cfg_attr(not(feature = "std"), no_std)]
19
20extern crate alloc;
21
22// generated file that tells us where to find the fixtures
23include!(concat!(env!("OUT_DIR"), "/fixture_location.rs"));
24
25/// Enum for different fixture types
26#[derive(Debug, Clone, Copy, PartialEq, Eq)]
27pub enum FixtureType {
28	/// Polkavm (compiled Rust contracts)
29	Rust,
30	/// Resolc (compiled Solidity contracts to Polkavm)
31	Resolc,
32	/// Solc (compiled Solidity contracts to EVM bytecode)
33	Solc,
34}
35
36#[cfg(feature = "std")]
37impl FixtureType {
38	fn file_extension(&self) -> &'static str {
39		match self {
40			Self::Rust => ".polkavm",
41			Self::Resolc => ".resolc.polkavm",
42			Self::Solc => ".sol.bin",
43		}
44	}
45}
46
47/// Load a fixture module with the specified type and return binary contents along with its hash.
48#[cfg(feature = "std")]
49pub fn compile_module_with_type(
50	fixture_name: &str,
51	fixture_type: FixtureType,
52) -> anyhow::Result<(Vec<u8>, sp_core::H256)> {
53	use anyhow::Context;
54	let out_dir: std::path::PathBuf = FIXTURE_DIR.into();
55	let fixture_path = out_dir.join(format!("{fixture_name}{}", fixture_type.file_extension()));
56	let binary = std::fs::read(&fixture_path)
57		.with_context(|| format!("Failed to load fixture {fixture_path:?}"))?;
58	let code_hash = sp_io::hashing::keccak_256(&binary);
59	Ok((binary, sp_core::H256(code_hash)))
60}
61
62/// Load a given polkavm module and returns a polkavm binary contents along with its hash.
63#[cfg(feature = "std")]
64pub fn compile_module(fixture_name: &str) -> anyhow::Result<(Vec<u8>, sp_core::H256)> {
65	compile_module_with_type(fixture_name, FixtureType::Rust)
66}
67
68/// Fixtures used in runtime benchmarks.
69///
70/// We explicitly include those fixtures into the binary to make them
71/// available in no-std environments (runtime benchmarks).
72pub mod bench {
73	use alloc::vec::Vec;
74	pub const DUMMY: Option<&[u8]> = fixture!("dummy");
75	pub const NOOP: Option<&[u8]> = fixture!("noop");
76
77	pub fn dummy() -> &'static [u8] {
78		DUMMY.expect("`DUMMY` fixture not available, remove `SKIP_PALLET_REVIVE_FIXTURES` env variable to compile them.")
79	}
80
81	pub fn noop() -> &'static [u8] {
82		NOOP.expect("`NOOP` fixture not available, remove `SKIP_PALLET_REVIVE_FIXTURES` env variable to compile them.")
83	}
84
85	pub fn dummy_unique(replace_with: u32) -> Vec<u8> {
86		let mut dummy = dummy().to_vec();
87		let idx = dummy
88			.windows(4)
89			.position(|w| w == &[0xDE, 0xAD, 0xBE, 0xEF])
90			.expect("Benchmark fixture contains this pattern; qed");
91		dummy[idx..idx + 4].copy_from_slice(&replace_with.to_le_bytes());
92		dummy
93	}
94}
95
96#[cfg(test)]
97mod test {
98	#[test]
99	fn out_dir_should_have_compiled_mocks() {
100		let out_dir: std::path::PathBuf = crate::FIXTURE_DIR.into();
101		assert!(out_dir.join("dummy.polkavm").exists());
102	}
103}