This repository was archived by the owner on Mar 13, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmock.rs
347 lines (310 loc) · 9.64 KB
/
mock.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
// This file is part of Darwinia.
//
// Copyright (C) 2018-2021 Darwinia Network
// SPDX-License-Identifier: GPL-3.0
//
// Darwinia is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Darwinia is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Darwinia. If not, see <https://www.gnu.org/licenses/>.
//! Test utilities
// --- crates.io ---
use codec::{Decode, Encode};
use ethereum::{TransactionAction, TransactionSignature};
use evm::{executor::PrecompileOutput, Context, ExitError};
use rlp::RlpStream;
// --- paritytech ---
use frame_support::{
traits::{FindAuthor, GenesisBuild},
ConsensusEngineId,
};
use frame_system::mocking::*;
use sp_core::{H160, H256, U256};
use sp_runtime::{
testing::Header,
traits::{BlakeTwo256, IdentityLookup},
AccountId32, Perbill, RuntimeDebug,
};
use sp_std::prelude::*;
// --- darwinia-network ---
use crate::{self as dvm_ethereum, account_basic::*, *};
use darwinia_evm::{runner::stack::Runner, AddressMapping, EnsureAddressTruncated, FeeCalculator};
use darwinia_evm_precompile_simple::{ECRecover, Identity, Ripemd160, Sha256};
use darwinia_evm_precompile_transfer::Transfer;
use dp_evm::{Precompile, PrecompileSet};
use sp_std::marker::PhantomData;
darwinia_support::impl_test_account_data! {}
type Block = MockBlock<Test>;
type UncheckedExtrinsic = MockUncheckedExtrinsic<Test>;
type Balance = u64;
frame_support::parameter_types! {
pub const BlockHashCount: u64 = 250;
pub const MaximumBlockWeight: Weight = 1024;
pub const MaximumBlockLength: u32 = 2 * 1024;
pub const AvailableBlockRatio: Perbill = Perbill::from_percent(75);
}
impl frame_system::Config for Test {
type BaseCallFilter = ();
type BlockWeights = ();
type BlockLength = ();
type DbWeight = ();
type Origin = Origin;
type Call = Call;
type Index = u64;
type BlockNumber = u64;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = AccountId32;
type Lookup = IdentityLookup<Self::AccountId>;
type Header = Header;
type Event = ();
type BlockHashCount = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
}
frame_support::parameter_types! {
// For weight estimation, we assume that the most locks on an individual account will be 50.
// This number may need to be adjusted in the future if this assumption no longer holds true.
pub const MaxLocks: u32 = 10;
pub const ExistentialDeposit: u64 = 500;
}
impl darwinia_balances::Config<RingInstance> for Test {
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type MaxLocks = ();
type OtherCurrencies = ();
type WeightInfo = ();
type Balance = Balance;
type Event = ();
type BalanceInfo = AccountData<Balance>;
}
impl darwinia_balances::Config<KtonInstance> for Test {
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type MaxLocks = ();
type OtherCurrencies = ();
type WeightInfo = ();
type Balance = Balance;
type Event = ();
type BalanceInfo = AccountData<Balance>;
}
frame_support::parameter_types! {
pub const MinimumPeriod: u64 = 6000 / 2;
}
impl pallet_timestamp::Config for Test {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
type WeightInfo = ();
}
pub struct FixedGasPrice;
impl FeeCalculator for FixedGasPrice {
fn min_gas_price() -> U256 {
1.into()
}
}
pub struct FindAuthorTruncated;
impl FindAuthor<H160> for FindAuthorTruncated {
fn find_author<'a, I>(_digests: I) -> Option<H160>
where
I: 'a + IntoIterator<Item = (ConsensusEngineId, &'a [u8])>,
{
Some(address_build(0).address)
}
}
pub struct HashedAddressMapping;
impl AddressMapping<AccountId32> for HashedAddressMapping {
fn into_account_id(address: H160) -> AccountId32 {
let mut raw_account = [0u8; 32];
raw_account[0..20].copy_from_slice(&address[..]);
raw_account.into()
}
}
frame_support::parameter_types! {
pub const TransactionByteFee: u64 = 1;
pub const ChainId: u64 = 42;
pub const BlockGasLimit: U256 = U256::MAX;
}
pub struct MockPrecompiles<R>(PhantomData<R>);
impl<R> PrecompileSet for MockPrecompiles<R>
where
R: darwinia_evm::Config,
{
fn execute(
address: H160,
input: &[u8],
target_gas: Option<u64>,
context: &Context,
) -> Option<Result<PrecompileOutput, ExitError>> {
let to_address = |n: u64| -> H160 { H160::from_low_u64_be(n) };
match address {
// Ethereum precompiles
_ if address == to_address(1) => Some(ECRecover::execute(input, target_gas, context)),
_ if address == to_address(2) => Some(Sha256::execute(input, target_gas, context)),
_ if address == to_address(3) => Some(Ripemd160::execute(input, target_gas, context)),
_ if address == to_address(4) => Some(Identity::execute(input, target_gas, context)),
// Darwinia precompiles
_ if address == to_address(21) => {
Some(<Transfer<R>>::execute(input, target_gas, context))
}
_ => None,
}
}
}
impl darwinia_evm::Config for Test {
type FeeCalculator = FixedGasPrice;
type GasWeightMapping = ();
type CallOrigin = EnsureAddressTruncated<Self::AccountId>;
type AddressMapping = HashedAddressMapping;
type Event = ();
type Precompiles = MockPrecompiles<Self>;
type ChainId = ChainId;
type BlockGasLimit = BlockGasLimit;
type FindAuthor = FindAuthorTruncated;
type BlockHashMapping = EthereumBlockHashMapping<Self>;
type Runner = Runner<Self>;
type RingAccountBasic = DvmAccountBasic<Self, Ring, RingRemainBalance>;
type KtonAccountBasic = DvmAccountBasic<Self, Kton, KtonRemainBalance>;
type IssuingHandler = ();
}
impl dvm_ethereum::Config for Test {
type Event = ();
type StateRoot = IntermediateStateRoot;
type RingCurrency = Ring;
type KtonCurrency = Kton;
}
frame_support::construct_runtime! {
pub enum Test where
Block = Block,
NodeBlock = Block,
UncheckedExtrinsic = UncheckedExtrinsic,
{
System: frame_system::{Pallet, Call, Config, Storage},
Timestamp: pallet_timestamp::{Pallet, Call, Storage},
Ring: darwinia_balances::<Instance1>::{Pallet, Call, Storage, Config<T>},
Kton: darwinia_balances::<Instance2>::{Pallet, Call, Storage},
EVM: darwinia_evm::{Pallet, Call, Storage, Config},
Ethereum: dvm_ethereum::{Pallet, Call, Storage, Config},
}
}
pub struct AccountInfo {
pub address: H160,
pub account_id: AccountId32,
pub private_key: H256,
}
pub struct UnsignedTransaction {
pub nonce: U256,
pub gas_price: U256,
pub gas_limit: U256,
pub action: TransactionAction,
pub value: U256,
pub input: Vec<u8>,
}
impl UnsignedTransaction {
fn signing_rlp_append(&self, s: &mut RlpStream) {
s.begin_list(9);
s.append(&self.nonce);
s.append(&self.gas_price);
s.append(&self.gas_limit);
s.append(&self.action);
s.append(&self.value);
s.append(&self.input);
s.append(&ChainId::get());
s.append(&0u8);
s.append(&0u8);
}
fn signing_hash(&self) -> H256 {
let mut stream = RlpStream::new();
self.signing_rlp_append(&mut stream);
H256::from_slice(&Keccak256::digest(&stream.out()).as_slice())
}
pub fn sign(&self, key: &H256) -> Transaction {
let hash = self.signing_hash();
let msg = libsecp256k1::Message::parse(hash.as_fixed_bytes());
let s = libsecp256k1::sign(
&msg,
&libsecp256k1::SecretKey::parse_slice(&key[..]).unwrap(),
);
let sig = s.0.serialize();
let sig = TransactionSignature::new(
s.1.serialize() as u64 % 2 + ChainId::get() * 2 + 35,
H256::from_slice(&sig[0..32]),
H256::from_slice(&sig[32..64]),
)
.unwrap();
Transaction {
nonce: self.nonce,
gas_price: self.gas_price,
gas_limit: self.gas_limit,
action: self.action,
value: self.value,
input: self.input.clone(),
signature: sig,
}
}
}
fn address_build(seed: u8) -> AccountInfo {
let raw_private_key = [seed + 1; 32];
let secret_key = libsecp256k1::SecretKey::parse_slice(&raw_private_key).unwrap();
let raw_public_key = &libsecp256k1::PublicKey::from_secret_key(&secret_key).serialize()[1..65];
let raw_address = {
let mut s = [0; 20];
s.copy_from_slice(&Keccak256::digest(raw_public_key)[12..]);
s
};
let raw_account = {
let mut s = [0; 32];
s[..20].copy_from_slice(&raw_address);
s
};
AccountInfo {
private_key: raw_private_key.into(),
account_id: raw_account.into(),
address: raw_address.into(),
}
}
// This function basically just builds a genesis storage key/value store according to
// our desired mockup.
pub fn new_test_ext(accounts_len: usize) -> (Vec<AccountInfo>, sp_io::TestExternalities) {
// sc_cli::init_logger("");
let mut ext = frame_system::GenesisConfig::default()
.build_storage::<Test>()
.unwrap();
let pairs = (0..accounts_len)
.map(|i| address_build(i as u8))
.collect::<Vec<_>>();
let balances: Vec<_> = (0..accounts_len)
.map(|i| (pairs[i].account_id.clone(), 100_000_000_000))
.collect();
darwinia_balances::GenesisConfig::<Test, RingInstance> { balances }
.assimilate_storage(&mut ext)
.unwrap();
(pairs, ext.into())
}
pub fn contract_address(sender: H160, nonce: u64) -> H160 {
let mut rlp = RlpStream::new_list(2);
rlp.append(&sender);
rlp.append(&nonce);
H160::from_slice(&Keccak256::digest(&rlp.out())[12..])
}
pub fn storage_address(sender: H160, slot: H256) -> H256 {
H256::from_slice(&Keccak256::digest(
[&H256::from(sender)[..], &slot[..]].concat().as_slice(),
))
}