precompile_utils/testing/
account.rs

1// This file is part of Frontier.
2
3// Copyright (c) Moonsong Labs.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: Apache-2.0
6
7// Licensed under the Apache License, Version 2.0 (the "License");
8// you may not use this file except in compliance with the License.
9// You may obtain a copy of the License at
10//
11// 	http://www.apache.org/licenses/LICENSE-2.0
12//
13// Unless required by applicable law or agreed to in writing, software
14// distributed under the License is distributed on an "AS IS" BASIS,
15// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16// See the License for the specific language governing permissions and
17// limitations under the License.
18
19use pallet_evm::AddressMapping;
20use scale_info::TypeInfo;
21use serde::{Deserialize, Serialize};
22use sp_core::{keccak_256, Decode, DecodeWithMemTracking, Encode, MaxEncodedLen, H160, H256};
23
24#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Debug)]
25#[derive(Serialize, Deserialize, derive_more::Display)]
26#[derive(Encode, Decode, DecodeWithMemTracking, MaxEncodedLen, TypeInfo)]
27pub struct MockAccount(pub H160);
28
29impl MockAccount {
30	pub fn from_u64(v: u64) -> Self {
31		H160::from_low_u64_be(v).into()
32	}
33
34	pub fn zero() -> Self {
35		H160::zero().into()
36	}
37
38	pub fn has_prefix(&self, prefix: &[u8]) -> bool {
39		&self.0[0..4] == prefix
40	}
41
42	pub fn has_prefix_u32(&self, prefix: u32) -> bool {
43		self.0[0..4] == prefix.to_be_bytes()
44	}
45
46	pub fn without_prefix(&self) -> u128 {
47		u128::from_be_bytes(<[u8; 16]>::try_from(&self.0[4..20]).expect("slice have len 16"))
48	}
49}
50
51impl From<MockAccount> for H160 {
52	fn from(account: MockAccount) -> H160 {
53		account.0
54	}
55}
56
57impl From<MockAccount> for [u8; 20] {
58	fn from(account: MockAccount) -> [u8; 20] {
59		let x: H160 = account.into();
60		x.into()
61	}
62}
63
64impl From<MockAccount> for H256 {
65	fn from(x: MockAccount) -> H256 {
66		let x: H160 = x.into();
67		x.into()
68	}
69}
70
71impl From<H160> for MockAccount {
72	fn from(address: H160) -> MockAccount {
73		MockAccount(address)
74	}
75}
76
77impl From<[u8; 20]> for MockAccount {
78	fn from(address: [u8; 20]) -> MockAccount {
79		let x: H160 = address.into();
80		MockAccount(x)
81	}
82}
83
84impl From<u64> for MockAccount {
85	fn from(address: u64) -> MockAccount {
86		MockAccount::from_u64(address)
87	}
88}
89
90impl AddressMapping<MockAccount> for MockAccount {
91	fn into_account_id(address: H160) -> MockAccount {
92		address.into()
93	}
94}
95
96impl sp_runtime::traits::Convert<H160, MockAccount> for MockAccount {
97	fn convert(address: H160) -> MockAccount {
98		address.into()
99	}
100}
101
102#[derive(
103	Eq,
104	PartialEq,
105	Clone,
106	Encode,
107	Decode,
108	DecodeWithMemTracking,
109	sp_core::RuntimeDebug,
110	TypeInfo,
111	Serialize,
112	Deserialize
113)]
114pub struct MockSignature(sp_core::ecdsa::Signature);
115
116impl From<sp_core::ecdsa::Signature> for MockSignature {
117	fn from(x: sp_core::ecdsa::Signature) -> Self {
118		MockSignature(x)
119	}
120}
121
122impl From<sp_runtime::MultiSignature> for MockSignature {
123	fn from(signature: sp_runtime::MultiSignature) -> Self {
124		match signature {
125			sp_runtime::MultiSignature::Ed25519(_) => {
126				panic!("Ed25519 not supported for MockSignature")
127			}
128			sp_runtime::MultiSignature::Sr25519(_) => {
129				panic!("Sr25519 not supported for MockSignature")
130			}
131			sp_runtime::MultiSignature::Ecdsa(sig) => Self(sig),
132		}
133	}
134}
135
136impl sp_runtime::traits::Verify for MockSignature {
137	type Signer = MockSigner;
138	fn verify<L: sp_runtime::traits::Lazy<[u8]>>(&self, mut msg: L, signer: &MockAccount) -> bool {
139		let mut m = [0u8; 32];
140		m.copy_from_slice(keccak_256(msg.get()).as_slice());
141		match sp_io::crypto::secp256k1_ecdsa_recover(self.0.as_ref(), &m) {
142			Ok(pubkey) => {
143				MockAccount(sp_core::H160::from_slice(
144					&keccak_256(&pubkey).as_slice()[12..32],
145				)) == *signer
146			}
147			Err(sp_io::EcdsaVerifyError::BadRS) => {
148				log::error!(target: "evm", "Error recovering: Incorrect value of R or S");
149				false
150			}
151			Err(sp_io::EcdsaVerifyError::BadV) => {
152				log::error!(target: "evm", "Error recovering: Incorrect value of V");
153				false
154			}
155			Err(sp_io::EcdsaVerifyError::BadSignature) => {
156				log::error!(target: "evm", "Error recovering: Invalid signature");
157				false
158			}
159		}
160	}
161}
162
163/// Public key for an Ethereum compatible account
164#[derive(
165	Eq,
166	PartialEq,
167	Ord,
168	PartialOrd,
169	Clone,
170	Encode,
171	Decode,
172	DecodeWithMemTracking,
173	sp_core::RuntimeDebug,
174	TypeInfo
175)]
176#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
177pub struct MockSigner([u8; 20]);
178
179impl sp_runtime::traits::IdentifyAccount for MockSigner {
180	type AccountId = MockAccount;
181	fn into_account(self) -> MockAccount {
182		MockAccount(self.0.into())
183	}
184}
185
186impl From<[u8; 20]> for MockSigner {
187	fn from(x: [u8; 20]) -> Self {
188		MockSigner(x)
189	}
190}
191
192#[macro_export]
193macro_rules! mock_account {
194	($name:ident, $convert:expr) => {
195		pub struct $name;
196		mock_account!(# $name, $convert);
197	};
198	($name:ident ( $($field:ty),* ), $convert:expr) => {
199		pub struct $name($(pub $field),*);
200		mock_account!(# $name, $convert);
201	};
202	(# $name:ident, $convert:expr) => {
203		impl From<$name> for MockAccount {
204			fn from(value: $name) -> MockAccount {
205				#[allow(clippy::redundant_closure_call)]
206				$convert(value)
207			}
208		}
209
210		impl From<$name> for sp_core::H160 {
211			fn from(value: $name) -> sp_core::H160 {
212				MockAccount::from(value).into()
213			}
214		}
215
216		impl From<$name> for sp_core::H256 {
217			fn from(value: $name) -> sp_core::H256 {
218				MockAccount::from(value).into()
219			}
220		}
221	};
222}
223
224mock_account!(Zero, |_| MockAccount::zero());
225mock_account!(Alice, |_| H160::repeat_byte(0xAA).into());
226mock_account!(Bob, |_| H160::repeat_byte(0xBB).into());
227mock_account!(Charlie, |_| H160::repeat_byte(0xCC).into());
228mock_account!(David, |_| H160::repeat_byte(0xDD).into());
229
230mock_account!(Precompile1, |_| MockAccount::from_u64(1));
231
232mock_account!(CryptoAlith, |_| H160::from(hex_literal::hex!(
233	"f24FF3a9CF04c71Dbc94D0b566f7A27B94566cac"
234))
235.into());
236mock_account!(CryptoBaltathar, |_| H160::from(hex_literal::hex!(
237	"3Cd0A705a2DC65e5b1E1205896BaA2be8A07c6e0"
238))
239.into());
240mock_account!(CryptoCarleth, |_| H160::from(hex_literal::hex!(
241	"798d4Ba9baf0064Ec19eB4F0a1a45785ae9D6DFc"
242))
243.into());
244
245mock_account!(
246	AddressInPrefixedSet(u32, u128),
247	|value: AddressInPrefixedSet| {
248		let prefix: u32 = value.0;
249		let index: u128 = value.1;
250
251		let mut buffer = Vec::with_capacity(20); // 160 bits
252
253		buffer.extend_from_slice(&prefix.to_be_bytes());
254		buffer.extend_from_slice(&index.to_be_bytes());
255
256		assert_eq!(buffer.len(), 20, "address buffer should have len of 20");
257
258		H160::from_slice(&buffer).into()
259	}
260);
261
262pub fn alith_secret_key() -> [u8; 32] {
263	hex_literal::hex!("5fb92d6e98884f76de468fa3f6278f8807c48bebc13595d45af5bdc4da702133")
264}
265
266pub fn baltathar_secret_key() -> [u8; 32] {
267	hex_literal::hex!("8075991ce870b93a8870eca0c0f91913d12f47948ca0fd25b49c6fa7cdbeee8b")
268}
269
270pub fn charleth_secret_key() -> [u8; 32] {
271	hex_literal::hex!("0b6e18cafb6ed99687ec547bd28139cafdd2bffe70e6b688025de6b445aa5c5b")
272}