git.delta.rocks / unique-network / refs/commits / b44fe9bf17b6

difftreelog

feat calculate signature in compile time

Trubnikov Sergey2022-10-11parent: #4d4a023.patch.diff
in: master

11 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1096,6 +1096,26 @@
 checksum = "e4c78c047431fee22c1a7bb92e00ad095a02a983affe4d8a72e2a2c62c1b94f3"
 
 [[package]]
+name = "const_format"
+version = "0.2.26"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "939dc9e2eb9077e0679d2ce32de1ded8531779360b003b4a972a7a39ec263495"
+dependencies = [
+ "const_format_proc_macros",
+]
+
+[[package]]
+name = "const_format_proc_macros"
+version = "0.2.22"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ef196d5d972878a48da7decb7686eded338b4858fbabeed513d63a7c98b2b82d"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-xid",
+]
+
+[[package]]
 name = "constant_time_eq"
 version = "0.1.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
@@ -2353,6 +2373,7 @@
 version = "0.1.3"
 dependencies = [
  "concat-idents",
+ "const_format",
  "ethereum",
  "evm-coder-procedural",
  "evm-core 0.35.0 (git+https://github.com/uniquenetwork/evm?branch=unique-polkadot-v0.9.30)",
@@ -2362,6 +2383,7 @@
  "impl-trait-for-tuples",
  "pallet-evm 6.0.0-dev (git+https://github.com/uniquenetwork/frontier?branch=unique-polkadot-v0.9.27-fee-limit)",
  "primitive-types",
+ "sha3-const",
  "similar-asserts",
  "sp-std 4.0.0 (git+https://github.com/paritytech/substrate?branch=polkadot-v0.9.30)",
 ]
@@ -11085,6 +11107,12 @@
 ]
 
 [[package]]
+name = "sha3-const"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "af9625d558d174dbdc711248b479271c0fdca39e9d3d67f6e890b3d4251fbf8e"
+
+[[package]]
 name = "sharded-slab"
 version = "0.1.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
modifiedcrates/evm-coder/Cargo.tomldiffbeforeafterboth
--- a/crates/evm-coder/Cargo.toml
+++ b/crates/evm-coder/Cargo.toml
@@ -5,6 +5,10 @@
 edition = "2021"
 
 [dependencies]
+const_format = { version = "0.2.26", default-features = false }
+sha3-const = { version = "0.1.0", default-features = false }
+# Ethereum uses keccak (=sha3) for selectors
+# sha3 = "0.10.1"
 # evm-coder reexports those proc-macro
 evm-coder-procedural = { path = "./procedural" }
 # Evm uses primitive-types for H160, H256 and others
modifiedcrates/evm-coder/procedural/src/solidity_interface.rsdiffbeforeafterboth
--- a/crates/evm-coder/procedural/src/solidity_interface.rs
+++ b/crates/evm-coder/procedural/src/solidity_interface.rs
@@ -20,6 +20,7 @@
 // about Procedural Macros in Rust book:
 // https://doc.rust-lang.org/reference/procedural-macros.html
 
+use proc_macro2::{TokenStream, Group};
 use quote::{quote, ToTokens};
 use inflector::cases;
 use std::fmt::Write;
@@ -328,6 +329,7 @@
 	}
 }
 
+#[derive(Debug)]
 enum AbiType {
 	// type
 	Plain(Ident),
@@ -473,6 +475,7 @@
 	}
 }
 
+#[derive(Debug)]
 struct MethodArg {
 	name: Ident,
 	camel_name: String,
@@ -722,13 +725,25 @@
 		}
 	}
 
+	fn expand_selector(&self) -> proc_macro2::TokenStream {
+		let custom_signature = self.expand_custom_signature();
+		quote! {
+			 {
+				let a = ::evm_coder::sha3_const::Keccak256::new()
+					.update(#custom_signature.as_bytes())
+					.finalize();
+				[a[0], a[1], a[2], a[3]]
+			}
+		}
+	}
+
 	fn expand_const(&self) -> proc_macro2::TokenStream {
 		let screaming_name = &self.screaming_name;
-		let selector = u32::to_be_bytes(self.selector);
 		let selector_str = &self.selector_str;
+		let selector = &self.expand_selector();
 		quote! {
 			#[doc = #selector_str]
-			const #screaming_name: ::evm_coder::types::bytes4 = [#(#selector,)*];
+			const #screaming_name: ::evm_coder::types::bytes4 = #selector;
 		}
 	}
 
@@ -831,6 +846,59 @@
 		}
 	}
 
+	fn expand_custom_signature(&self) -> proc_macro2::TokenStream {
+		let mut first_comma = true;
+		let mut custom_signature = TokenStream::new();
+		let mut template = self.camel_name.clone() + "(";
+		self.args
+			.iter()
+			.filter_map(|a| {
+				if a.is_special() {
+					return None;
+				};
+
+				match a.ty {
+					AbiType::Plain(ref ident) => Some(ident),
+					_ => None,
+				}
+			})
+			.for_each(|ident| {
+				if !first_comma {
+					custom_signature.extend(quote!(,));
+					template.push(',');
+				} else {
+					first_comma = false;
+				};
+				template.push_str("{}");
+				let ident_str = ident.to_string();
+				match ident_str.as_str() {
+					"address" | "uint8" | "uint16" | "uint32" | "uint64" | "uint128"
+					| "uint256" | "bytes4" | "topic" | "string" | "bytes" | "void" | "caller"
+					| "bool" | "" => {
+						custom_signature.extend(quote!(#ident_str));
+					}
+					_ => {
+						custom_signature.extend(quote! {
+							#ident::SIGNATURE_STRING
+						});
+					}
+				}
+			});
+
+		template.push(')');
+		let mut template = quote!(#template);
+		template.extend(quote!(,));
+		template.extend(custom_signature);
+		let custom_signature_group = Group::new(proc_macro2::Delimiter::Parenthesis, template);
+		let mut custom_signature = quote! {
+			::evm_coder::const_format::formatcp!
+		};
+		custom_signature.extend(custom_signature_group.to_token_stream());
+
+		// println!("!!!!! {}", custom_signature);
+		custom_signature
+	}
+
 	fn expand_solidity_function(&self) -> proc_macro2::TokenStream {
 		let camel_name = &self.camel_name;
 		let mutability = match self.mutability {
@@ -847,15 +915,17 @@
 			.map(MethodArg::expand_solidity_argument);
 		let docs = &self.docs;
 		let selector_str = &self.selector_str;
-		let selector = self.selector;
+		let selector = &self.expand_selector();
 		let hide = self.hide;
+		let custom_signature = self.expand_custom_signature();
 		let is_payable = self.has_value_args;
 		quote! {
 			SolidityFunction {
 				docs: &[#(#docs),*],
 				selector_str: #selector_str,
-				selector: #selector,
 				hide: #hide,
+				selector: u32::from_be_bytes(#selector),
+				custom_signature: #custom_signature,
 				name: #camel_name,
 				mutability: #mutability,
 				is_payable: #is_payable,
modifiedcrates/evm-coder/src/lib.rsdiffbeforeafterboth
before · crates/evm-coder/src/lib.rs
1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617#![doc = include_str!("../README.md")]18#![deny(missing_docs)]19#![cfg_attr(not(feature = "std"), no_std)]20#[cfg(not(feature = "std"))]21extern crate alloc;2223use abi::{AbiRead, AbiReader, AbiWriter};24pub use evm_coder_procedural::{event_topic, fn_selector};25pub mod abi;26pub use events::{ToLog, ToTopic};27use execution::DispatchInfo;28pub mod execution;2930/// Derives call enum implementing [`crate::Callable`], [`crate::Weighted`]31/// and [`crate::Call`] from impl block.32///33/// ## Macro syntax34///35/// `#[solidity_interface(name, is, inline_is, events)]`36/// - *name* - used in generated code, and for Call enum name37/// - *is* - used to provide inheritance in Solidity38/// - *inline_is* - same as `is`, but ERC165::SupportsInterface will work differently: For `is` SupportsInterface(A) will return true39///   if A is one of the interfaces the contract is inherited from (e.g. B is created as `is(A)`). If B is created as `inline_is(A)`40///   SupportsInterface(A) will internally create a new interface that combines all methods of A and B, so SupportsInterface(A) will return41///   false.42///43/// `#[weight(value)]`44/// Can be added to every method of impl block, used for deriving [`crate::Weighted`], which45/// is used by substrate bridge.46/// - *value*: expression, which evaluates to weight required to call this method.47/// This expression can use call arguments to calculate non-constant execution time.48/// This expression should evaluate faster than actual execution does, and may provide worse case49/// than one is called.50///51/// `#[solidity_interface(rename_selector)]`52/// - *rename_selector* - by default, selector name will be generated by transforming method name53/// from snake_case to camelCase. Use this option, if other naming convention is required.54/// I.e: method `token_uri` will be automatically renamed to `tokenUri` in selector, but name55/// required by ERC721 standard is `tokenURI`, thus we need to specify `rename_selector = "tokenURI"`56/// explicitly.57///58/// Both contract and contract methods may have doccomments, which will end up in a generated59/// solidity interface file, thus you should use [solidity syntax](https://docs.soliditylang.org/en/latest/natspec-format.html) for writing documentation in this macro60///61/// ## Example62///63/// ```ignore64/// struct SuperContract;65/// struct InlineContract;66/// struct Contract;67///68/// #[derive(ToLog)]69/// enum ContractEvents {70///     Event(#[indexed] uint32),71/// }72///73/// /// @dev This contract provides function to multiply two numbers74/// #[solidity_interface(name = MyContract, is(SuperContract), inline_is(InlineContract))]75/// impl Contract {76///     /// Multiply two numbers77///     /// @param a First number78///     /// @param b Second number79///     /// @return uint32 Product of two passed numbers80///     /// @dev This function returns error in case of overflow81///     #[weight(200 + a + b)]82///     #[solidity_interface(rename_selector = "mul")]83///     fn mul(&mut self, a: uint32, b: uint32) -> Result<uint32> {84///         Ok(a.checked_mul(b).ok_or("overflow")?)85///     }86/// }87/// ```88pub use evm_coder_procedural::solidity_interface;89/// See [`solidity_interface`]90pub use evm_coder_procedural::solidity;91/// See [`solidity_interface`]92pub use evm_coder_procedural::weight;9394/// Derives [`ToLog`] for enum95///96/// Selectors will be derived from variant names, there is currently no way to have custom naming97/// for them98///99/// `#[indexed]`100/// Marks this field as indexed, so it will appear in [`ethereum::Log`] topics instead of data101pub use evm_coder_procedural::ToLog;102103// Api of those modules shouldn't be consumed directly, it is only exported for usage in proc macros104#[doc(hidden)]105pub mod events;106#[doc(hidden)]107pub mod solidity;108109/// Solidity type definitions (aliases from solidity name to rust type)110/// To be used in [`solidity_interface`] definitions, to make sure there is no111/// type conflict between Rust code and generated definitions112pub mod types {113	#![allow(non_camel_case_types, missing_docs)]114115	#[cfg(not(feature = "std"))]116	use alloc::{vec::Vec};117	use pallet_evm::account::CrossAccountId;118	use primitive_types::{U256, H160, H256};119120	pub type address = H160;121122	pub type uint8 = u8;123	pub type uint16 = u16;124	pub type uint32 = u32;125	pub type uint64 = u64;126	pub type uint128 = u128;127	pub type uint256 = U256;128129	pub type bytes4 = [u8; 4];130131	pub type topic = H256;132133	#[cfg(not(feature = "std"))]134	pub type string = ::alloc::string::String;135	#[cfg(feature = "std")]136	pub type string = ::std::string::String;137138	#[derive(Default, Debug)]139	pub struct bytes(pub Vec<u8>);140141	/// Solidity doesn't have `void` type, however we have special implementation142	/// for empty tuple return type143	pub type void = ();144145	//#region Special types146	/// Makes function payable147	pub type value = U256;148	/// Makes function caller-sensitive149	pub type caller = address;150	//#endregion151152	/// Ethereum typed call message, similar to solidity153	/// `msg` object.154	pub struct Msg<C> {155		pub call: C,156		/// Address of user, which called this contract.157		pub caller: H160,158		/// Payment amount to contract.159		/// Contract should reject payment, if target call is not payable,160		/// and there is no `receiver()` function defined.161		pub value: U256,162	}163164	impl From<Vec<u8>> for bytes {165		fn from(src: Vec<u8>) -> Self {166			Self(src)167		}168	}169170	impl Into<Vec<u8>> for bytes {171		fn into(self) -> Vec<u8> {172			self.0173		}174	}175176	impl bytes {177		#[must_use]178		pub fn len(&self) -> usize {179			self.0.len()180		}181182		#[must_use]183		pub fn is_empty(&self) -> bool {184			self.len() == 0185		}186	}187188	#[derive(Debug)]189	pub struct EthCrossAccount {190		pub(crate) eth: address,191		pub(crate) sub: uint256,192	}193194	impl EthCrossAccount {195		pub fn from_sub_cross_account<T>(cross_account_id: &T::CrossAccountId) -> Self196		where197			T: pallet_evm::account::Config,198			T::AccountId: AsRef<[u8; 32]>,199		{200			if cross_account_id.is_canonical_substrate() {201				Self {202					eth: Default::default(),203					sub: convert_cross_account_to_uint256::<T>(cross_account_id),204				}205			} else {206				Self {207					eth: *cross_account_id.as_eth(),208					sub: Default::default(),209				}210			}211		}212213		pub fn into_sub_cross_account<T>(&self) -> crate::execution::Result<T::CrossAccountId>214		where215			T: pallet_evm::account::Config,216			T::AccountId: From<[u8; 32]>,217		{218			if self.eth == Default::default() && self.sub == Default::default() {219				Err("All fields of cross account is zeroed".into())220			} else if self.eth == Default::default() {221				Ok(convert_uint256_to_cross_account::<T>(self.sub))222			} else if self.sub == Default::default() {223				Ok(T::CrossAccountId::from_eth(self.eth))224			} else {225				Err("All fields of cross account is non zeroed".into())226			}227		}228	}229230	/// Convert `CrossAccountId` to `uint256`.231	pub fn convert_cross_account_to_uint256<T: pallet_evm::account::Config>(232		from: &T::CrossAccountId,233	) -> uint256234	where235		T::AccountId: AsRef<[u8; 32]>,236	{237		let slice = from.as_sub().as_ref();238		uint256::from_big_endian(slice)239	}240241	/// Convert `uint256` to `CrossAccountId`.242	pub fn convert_uint256_to_cross_account<T: pallet_evm::account::Config>(243		from: uint256,244	) -> T::CrossAccountId245	where246		T::AccountId: From<[u8; 32]>,247	{248		let mut new_admin_arr = [0_u8; 32];249		from.to_big_endian(&mut new_admin_arr);250		let account_id = T::AccountId::from(new_admin_arr);251		T::CrossAccountId::from_sub(account_id)252	}253}254255/// Parseable EVM call, this trait should be implemented with [`solidity_interface`] macro256pub trait Call: Sized {257	/// Parse call buffer into typed call enum258	fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>>;259}260261/// Intended to be used as `#[weight]` output type262/// Should be same between evm-coder and substrate to avoid confusion263///264/// Isn't same thing as gas, some mapping is required between those types265pub type Weight = frame_support::weights::Weight;266267/// In substrate, we have benchmarking, which allows268/// us to not rely on gas metering, but instead predict amount of gas to execute call269pub trait Weighted: Call {270	/// Predict weight of this call271	fn weight(&self) -> DispatchInfo;272}273274/// Type callable with ethereum message, may be implemented by [`solidity_interface`] macro275/// on interface implementation, or for externally-owned real EVM contract276pub trait Callable<C: Call> {277	/// Call contract using specified call data278	fn call(&mut self, call: types::Msg<C>) -> execution::ResultWithPostInfo<AbiWriter>;279}280281/// Implementation of ERC165 is implicitly generated for all interfaces in [`solidity_interface`],282/// this structure holds parsed data for ERC165Call subvariant283///284/// Note: no [`Callable`] implementation is provided, call implementation is inlined into every285/// implementing contract286///287/// See <https://eips.ethereum.org/EIPS/eip-165>288#[derive(Debug)]289pub enum ERC165Call {290	/// ERC165 provides single method, which returns true, if contract291	/// implements specified interface292	SupportsInterface {293		/// Requested interface294		interface_id: types::bytes4,295	},296}297298impl ERC165Call {299	/// ERC165 selector is provided by standard300	pub const INTERFACE_ID: types::bytes4 = u32::to_be_bytes(0x01ffc9a7);301}302303impl Call for ERC165Call {304	fn parse(selector: types::bytes4, input: &mut AbiReader) -> execution::Result<Option<Self>> {305		if selector != Self::INTERFACE_ID {306			return Ok(None);307		}308		Ok(Some(Self::SupportsInterface {309			interface_id: input.abi_read()?,310		}))311	}312}313314/// Generate "tests", which will generate solidity code on execution and print it to stdout315/// Script at .maintain/scripts/generate_api.sh can split this output from test runtime316///317/// This macro receives type usage as second argument, but you can use anything as generics,318/// because no bounds are implied319#[macro_export]320macro_rules! generate_stubgen {321	($name:ident, $decl:ty, $is_impl:literal) => {322		#[test]323		#[ignore]324		fn $name() {325			use evm_coder::solidity::TypeCollector;326			let mut out = TypeCollector::new();327			<$decl>::generate_solidity_interface(&mut out, $is_impl);328			println!("=== SNIP START ===");329			println!("// SPDX-License-Identifier: OTHER");330			println!("// This code is automatically generated");331			println!();332			println!("pragma solidity >=0.8.0 <0.9.0;");333			println!();334			for b in out.finish() {335				println!("{}", b);336			}337			println!("=== SNIP END ===");338		}339	};340}341342#[cfg(test)]343mod tests {344	use super::*;345346	#[test]347	fn function_selector_generation() {348		assert_eq!(fn_selector!(transfer(address, uint256)), 0xa9059cbb);349	}350351	#[test]352	fn event_topic_generation() {353		assert_eq!(354			hex::encode(&event_topic!(Transfer(address, address, uint256))[..]),355			"ddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef",356		);357	}358}
modifiedcrates/evm-coder/src/solidity.rsdiffbeforeafterboth
--- a/crates/evm-coder/src/solidity.rs
+++ b/crates/evm-coder/src/solidity.rs
@@ -35,6 +35,12 @@
 use crate::types::*;
 
 #[derive(Default)]
+pub struct FunctionSelectorMaker {
+	pub name: string,
+	pub args: Vec<fn() -> string>,
+}
+
+#[derive(Default)]
 pub struct TypeCollector {
 	/// Code => id
 	/// id ordering is required to perform topo-sort on the resulting data
@@ -482,11 +488,25 @@
 	View,
 	Mutable,
 }
+
+// fn fn_selector_str(input: &str) -> u32 {
+// 	use sha3::Digest;
+// 	let mut hasher = sha3::Keccak256::new();
+// 	hasher.update(input.as_bytes());
+// 	let result = hasher.finalize();
+
+// 	let mut selector_bytes = [0; 4];
+// 	selector_bytes.copy_from_slice(&result[0..4]);
+
+// 	u32::from_be_bytes(selector_bytes)
+// }
+
 pub struct SolidityFunction<A, R> {
 	pub docs: &'static [&'static str],
 	pub selector_str: &'static str,
 	pub selector: u32,
 	pub hide: bool,
+	pub custom_signature: &'static str,
 	pub name: &'static str,
 	pub args: A,
 	pub result: R,
@@ -512,7 +532,7 @@
 		writeln!(
 			writer,
 			"\t{hide_comment}///  or in textual repr: {}",
-			self.selector_str
+			self.custom_signature
 		)?;
 		write!(writer, "\t{hide_comment}function {}(", self.name)?;
 		self.args.solidity_name(writer, tc)?;
modifiedpallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth
--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -27,7 +27,7 @@
 evm-coder = { default-features = false, path = '../../crates/evm-coder' }
 pallet-common = { default-features = false, path = '../../pallets/common' }
 pallet-evm-coder-substrate = { default-features = false, path = '../../pallets/evm-coder-substrate' }
-pallet-evm-transaction-payment = {  default-features = false, path = '../../pallets/evm-transaction-payment' }
+pallet-evm-transaction-payment = { default-features = false, path = '../../pallets/evm-transaction-payment' }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs', features = [
     'serde1',
 ] }
modifiedpallets/evm-contract-helpers/src/eth.rsdiffbeforeafterboth
--- a/pallets/evm-contract-helpers/src/eth.rs
+++ b/pallets/evm-contract-helpers/src/eth.rs
@@ -16,6 +16,8 @@
 
 //! Implementation of magic contract
 
+extern crate alloc;
+use alloc::{format, string::ToString};
 use core::marker::PhantomData;
 use evm_coder::{
 	abi::AbiWriter, execution::Result, generate_stubgen, solidity_interface, types::*, ToLog,
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -16,6 +16,8 @@
 
 //! ERC-20 standart support implementation.
 
+extern crate alloc;
+use alloc::{format, string::ToString};
 use core::char::{REPLACEMENT_CHARACTER, decode_utf16};
 use core::convert::TryInto;
 use evm_coder::{ToLog, execution::*, generate_stubgen, solidity_interface, types::*, weight};
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -20,6 +20,7 @@
 //! Method implementations are mostly doing parameter conversion and calling Nonfungible Pallet methods.
 
 extern crate alloc;
+use alloc::{format, string::ToString};
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,
modifiedpallets/refungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/refungible/Cargo.toml
+++ b/pallets/refungible/Cargo.toml
@@ -26,7 +26,9 @@
 struct-versioning = { path = "../../crates/struct-versioning" }
 up-data-structs = { default-features = false, path = '../../primitives/data-structs' }
 ethereum = { version = "0.12.0", default-features = false }
-scale-info = { version = "2.0.1", default-features = false, features = ["derive",] }
+scale-info = { version = "2.0.1", default-features = false, features = [
+    "derive",
+] }
 derivative = { version = "2.2.0", features = ["use_core"] }
 
 [features]
modifiedpallets/refungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -21,6 +21,7 @@
 
 extern crate alloc;
 
+use alloc::{format, string::ToString};
 use core::{
 	char::{REPLACEMENT_CHARACTER, decode_utf16},
 	convert::TryInto,