Skip to main content

domain_test_utils/
test_ethereum_tx.rs

1//! Code in this file is copied from the frontier repository. Full path is:
2//! <https://github.com/subspace/frontier/blob/1c667eb43c3d087ac66dc9ed0aa44128373f5b0a/frame/ethereum/src/mock.rs>
3//! If monorepo points to new commit, this file need to be in sync.
4//!
5//! Minor changes were made to comments, derives, visibility, and the address_build() seed size.
6
7pub use ethereum::{
8    AccessListItem, BlockV2 as Block, LegacyTransactionMessage, Log, ReceiptV3 as Receipt,
9    TransactionAction, TransactionV2 as Transaction,
10};
11use frame_support::parameter_types;
12use rlp::RlpStream;
13use sp_core::crypto::AccountId32;
14use sp_core::{H160, H256, U256};
15use sp_crypto_hashing::keccak_256;
16
17parameter_types! {
18    // `870` is the genesis evm domain chain id
19    pub const ChainId: u64 = 870;
20}
21
22#[derive(Clone, Debug, Eq, PartialEq)]
23pub struct AccountInfo {
24    pub address: H160,
25    pub account_id: AccountId32,
26    pub private_key: H256,
27}
28
29/// Returns an AccountInfo struct with a deterministic address and private key.
30/// Seed zero produces an invalid private key, so we add one to the supplied seed.
31pub fn address_build(mut seed: u128) -> AccountInfo {
32    seed += 1;
33
34    let mut seed_bytes = [0u8; 32];
35    seed_bytes[0..16].copy_from_slice(&seed.to_be_bytes());
36    let private_key = H256::from_slice(&seed_bytes);
37    // The above lines were modified from this original code:
38    //let private_key = H256::from_slice(&[(seed as u8 + 1); 32]); //H256::from_low_u64_be((i + 1) as u64);
39
40    let secret_key = libsecp256k1::SecretKey::parse_slice(&private_key[..]).unwrap();
41    let public_key = &libsecp256k1::PublicKey::from_secret_key(&secret_key).serialize()[1..65];
42    let address = H160::from(H256::from(keccak_256(public_key)));
43
44    let mut data = [0u8; 32];
45    data[0..20].copy_from_slice(&address[..]);
46
47    AccountInfo {
48        private_key,
49        account_id: AccountId32::from(Into::<[u8; 32]>::into(data)),
50        address,
51    }
52}
53
54/// Returns the contract address for the given sender and nonce.
55/// Use `U256::as_u64()` to convert the nonce to `u64`.
56pub fn contract_address(sender: H160, nonce: u64) -> H160 {
57    let mut rlp = RlpStream::new_list(2);
58    rlp.append(&sender);
59    rlp.append(&nonce);
60
61    H160::from_slice(&keccak_256(&rlp.out())[12..])
62}
63
64pub struct LegacyUnsignedTransaction {
65    pub nonce: U256,
66    pub gas_price: U256,
67    pub gas_limit: U256,
68    pub action: TransactionAction,
69    pub value: U256,
70    pub input: Vec<u8>,
71}
72
73impl LegacyUnsignedTransaction {
74    fn signing_rlp_append(&self, s: &mut RlpStream) {
75        s.begin_list(9);
76        s.append(&self.nonce);
77        s.append(&self.gas_price);
78        s.append(&self.gas_limit);
79        s.append(&self.action);
80        s.append(&self.value);
81        s.append(&self.input);
82        s.append(&ChainId::get());
83        s.append(&0u8);
84        s.append(&0u8);
85    }
86
87    fn signing_hash(&self) -> H256 {
88        let mut stream = RlpStream::new();
89        self.signing_rlp_append(&mut stream);
90        H256::from(keccak_256(&stream.out()))
91    }
92
93    pub fn sign(&self, key: &H256) -> Transaction {
94        self.sign_with_chain_id(key, ChainId::get())
95    }
96
97    pub fn sign_with_chain_id(&self, key: &H256, chain_id: u64) -> Transaction {
98        let hash = self.signing_hash();
99        let msg = libsecp256k1::Message::parse(hash.as_fixed_bytes());
100        let s = libsecp256k1::sign(
101            &msg,
102            &libsecp256k1::SecretKey::parse_slice(&key[..]).unwrap(),
103        );
104        let sig = s.0.serialize();
105
106        let sig = ethereum::legacy::TransactionSignature::new(
107            s.1.serialize() as u64 % 2 + chain_id * 2 + 35,
108            H256::from_slice(&sig[0..32]),
109            H256::from_slice(&sig[32..64]),
110        )
111        .unwrap();
112
113        Transaction::Legacy(ethereum::LegacyTransaction {
114            nonce: self.nonce,
115            gas_price: self.gas_price,
116            gas_limit: self.gas_limit,
117            action: self.action,
118            value: self.value,
119            input: self.input.clone(),
120            signature: sig,
121        })
122    }
123}
124
125pub struct EIP2930UnsignedTransaction {
126    pub nonce: U256,
127    pub gas_price: U256,
128    pub gas_limit: U256,
129    pub action: TransactionAction,
130    pub value: U256,
131    pub input: Vec<u8>,
132}
133
134impl EIP2930UnsignedTransaction {
135    pub fn sign(&self, secret: &H256, chain_id: Option<u64>) -> Transaction {
136        let secret = {
137            let mut sk: [u8; 32] = [0u8; 32];
138            sk.copy_from_slice(&secret[0..]);
139            libsecp256k1::SecretKey::parse(&sk).unwrap()
140        };
141        let chain_id = chain_id.unwrap_or(ChainId::get());
142        let msg = ethereum::EIP2930TransactionMessage {
143            chain_id,
144            nonce: self.nonce,
145            gas_price: self.gas_price,
146            gas_limit: self.gas_limit,
147            action: self.action,
148            value: self.value,
149            input: self.input.clone(),
150            access_list: vec![],
151        };
152        let signing_message = libsecp256k1::Message::parse_slice(&msg.hash()[..]).unwrap();
153
154        let (signature, recid) = libsecp256k1::sign(&signing_message, &secret);
155        let rs = signature.serialize();
156        let r = H256::from_slice(&rs[0..32]);
157        let s = H256::from_slice(&rs[32..64]);
158        let signature =
159            ethereum::eip2930::TransactionSignature::new(recid.serialize() != 0, r, s).unwrap();
160        Transaction::EIP2930(ethereum::EIP2930Transaction {
161            chain_id: msg.chain_id,
162            nonce: msg.nonce,
163            gas_price: msg.gas_price,
164            gas_limit: msg.gas_limit,
165            action: msg.action,
166            value: msg.value,
167            input: msg.input.clone(),
168            access_list: msg.access_list,
169            signature,
170        })
171    }
172}
173
174pub struct EIP1559UnsignedTransaction {
175    pub nonce: U256,
176    pub max_priority_fee_per_gas: U256,
177    pub max_fee_per_gas: U256,
178    pub gas_limit: U256,
179    pub action: TransactionAction,
180    pub value: U256,
181    pub input: Vec<u8>,
182}
183
184impl EIP1559UnsignedTransaction {
185    pub fn sign(&self, secret: &H256, chain_id: Option<u64>) -> Transaction {
186        let secret = {
187            let mut sk: [u8; 32] = [0u8; 32];
188            sk.copy_from_slice(&secret[0..]);
189            libsecp256k1::SecretKey::parse(&sk).unwrap()
190        };
191        let chain_id = chain_id.unwrap_or(ChainId::get());
192        let msg = ethereum::EIP1559TransactionMessage {
193            chain_id,
194            nonce: self.nonce,
195            max_priority_fee_per_gas: self.max_priority_fee_per_gas,
196            max_fee_per_gas: self.max_fee_per_gas,
197            gas_limit: self.gas_limit,
198            action: self.action,
199            value: self.value,
200            input: self.input.clone(),
201            access_list: vec![],
202        };
203        let signing_message = libsecp256k1::Message::parse_slice(&msg.hash()[..]).unwrap();
204
205        let (signature, recid) = libsecp256k1::sign(&signing_message, &secret);
206        let rs = signature.serialize();
207        let r = H256::from_slice(&rs[0..32]);
208        let s = H256::from_slice(&rs[32..64]);
209        let signature =
210            ethereum::eip1559::TransactionSignature::new(recid.serialize() != 0, r, s).unwrap();
211        Transaction::EIP1559(ethereum::EIP1559Transaction {
212            chain_id: msg.chain_id,
213            nonce: msg.nonce,
214            max_priority_fee_per_gas: msg.max_priority_fee_per_gas,
215            max_fee_per_gas: msg.max_fee_per_gas,
216            gas_limit: msg.gas_limit,
217            action: msg.action,
218            value: msg.value,
219            input: msg.input.clone(),
220            access_list: msg.access_list,
221            signature,
222        })
223    }
224}