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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2020-2022 Parity Technologies (UK) Ltd.
//
// This program 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.
//
// This program 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 this program. If not, see <https://www.gnu.org/licenses/>.

#![allow(
	clippy::too_many_arguments,
	clippy::large_enum_variant,
	clippy::manual_range_contains,
	clippy::explicit_counter_loop,
	clippy::len_zero,
	clippy::new_without_default
)]
#![warn(unused_crate_dependencies)]

mod cache;
mod debug;
mod eth;
mod eth_pubsub;
mod net;
mod signer;
#[cfg(feature = "txpool")]
mod txpool;
mod web3;

#[cfg(feature = "txpool")]
pub use self::txpool::TxPool;
pub use self::{
	cache::{EthBlockDataCacheTask, EthTask},
	debug::Debug,
	eth::{format, pending, EstimateGasAdapter, Eth, EthConfig, EthFilter},
	eth_pubsub::{EthPubSub, EthereumSubIdProvider},
	net::Net,
	signer::{EthDevSigner, EthSigner},
	web3::Web3,
};
pub use ethereum::TransactionV2 as EthereumTransaction;
#[cfg(feature = "txpool")]
pub use fc_rpc_core::TxPoolApiServer;
pub use fc_rpc_core::{
	DebugApiServer, EthApiServer, EthFilterApiServer, EthPubSubApiServer, NetApiServer,
	Web3ApiServer,
};
pub use fc_storage::{
	OverrideHandle, RuntimeApiStorageOverride, SchemaV1Override, SchemaV2Override,
	SchemaV3Override, StorageOverride,
};

pub mod frontier_backend_client {
	use super::internal_err;

	use ethereum_types::{H160, H256, U256};
	use jsonrpsee::core::RpcResult;
	use scale_codec::Encode;
	// Substrate
	use sc_client_api::{
		backend::{Backend, StorageProvider},
		StorageKey,
	};
	use sp_blockchain::HeaderBackend;
	use sp_io::hashing::{blake2_128, twox_128};
	use sp_runtime::{
		generic::BlockId,
		traits::{Block as BlockT, HashingFor, UniqueSaturatedInto},
	};
	use sp_state_machine::OverlayedChanges;
	// Frontier
	use fc_rpc_core::types::BlockNumberOrHash;

	/// Implements a default runtime storage override.
	/// It assumes that the balances and nonces are stored in pallet `system.account`, and
	/// have `nonce: Index` = `u32` for  and `free: Balance` = `u128`.
	/// Uses IdentityAddressMapping for the address.
	pub struct SystemAccountId20StorageOverride<B, C, BE>(pub std::marker::PhantomData<(B, C, BE)>);
	impl<B, C, BE> fp_rpc::RuntimeStorageOverride<B, C> for SystemAccountId20StorageOverride<B, C, BE>
	where
		B: BlockT,
		C: StorageProvider<B, BE> + Send + Sync,
		BE: Backend<B>,
	{
		fn is_enabled() -> bool {
			true
		}

		fn set_overlayed_changes(
			client: &C,
			overlayed_changes: &mut OverlayedChanges<HashingFor<B>>,
			block: B::Hash,
			_version: u32,
			address: H160,
			balance: Option<U256>,
			nonce: Option<U256>,
		) {
			let mut key = [twox_128(b"System"), twox_128(b"Account")]
				.concat()
				.to_vec();
			let account_id = Self::into_account_id_bytes(address);
			key.extend(blake2_128(&account_id));
			key.extend(&account_id);

			if let Ok(Some(item)) = client.storage(block, &StorageKey(key.clone())) {
				let mut new_item = item.0;

				if let Some(nonce) = nonce {
					new_item.splice(0..4, nonce.low_u32().encode());
				}

				if let Some(balance) = balance {
					new_item.splice(16..32, balance.low_u128().encode());
				}

				overlayed_changes.set_storage(key, Some(new_item));
			}
		}

		fn into_account_id_bytes(address: H160) -> Vec<u8> {
			use pallet_evm::AddressMapping;
			let address: H160 = pallet_evm::IdentityAddressMapping::into_account_id(address);
			address.as_ref().to_owned()
		}
	}

	/// Implements a runtime storage override.
	/// It assumes that the balances and nonces are stored in pallet `system.account`, and
	/// have `nonce: Index` = `u32` for  and `free: Balance` = `u128`.
	/// USes HashedAddressMapping for the address.
	pub struct SystemAccountId32StorageOverride<B, C, BE>(pub std::marker::PhantomData<(B, C, BE)>);
	impl<B, C, BE> fp_rpc::RuntimeStorageOverride<B, C> for SystemAccountId32StorageOverride<B, C, BE>
	where
		B: BlockT,
		C: StorageProvider<B, BE> + Send + Sync,
		BE: Backend<B>,
	{
		fn is_enabled() -> bool {
			true
		}

		fn set_overlayed_changes(
			client: &C,
			overlayed_changes: &mut OverlayedChanges<HashingFor<B>>,
			block: B::Hash,
			_version: u32,
			address: H160,
			balance: Option<U256>,
			nonce: Option<U256>,
		) {
			let mut key = [twox_128(b"System"), twox_128(b"Account")]
				.concat()
				.to_vec();
			let account_id = Self::into_account_id_bytes(address);
			key.extend(blake2_128(&account_id));
			key.extend(&account_id);

			if let Ok(Some(item)) = client.storage(block, &StorageKey(key.clone())) {
				let mut new_item = item.0;

				if let Some(nonce) = nonce {
					new_item.splice(0..4, nonce.low_u32().encode());
				}

				if let Some(balance) = balance {
					new_item.splice(16..32, balance.low_u128().encode());
				}

				overlayed_changes.set_storage(key, Some(new_item));
			}
		}

		fn into_account_id_bytes(address: H160) -> Vec<u8> {
			use pallet_evm::AddressMapping;
			use sp_core::crypto::ByteArray;
			use sp_runtime::traits::BlakeTwo256;

			pallet_evm::HashedAddressMapping::<BlakeTwo256>::into_account_id(address)
				.as_slice()
				.to_owned()
		}
	}

	pub async fn native_block_id<B: BlockT, C>(
		client: &C,
		backend: &dyn fc_api::Backend<B>,
		number: Option<BlockNumberOrHash>,
	) -> RpcResult<Option<BlockId<B>>>
	where
		B: BlockT,
		C: HeaderBackend<B> + 'static,
	{
		Ok(match number.unwrap_or(BlockNumberOrHash::Latest) {
			BlockNumberOrHash::Hash { hash, .. } => {
				if let Ok(Some(hash)) = load_hash::<B, C>(client, backend, hash).await {
					Some(BlockId::Hash(hash))
				} else {
					None
				}
			}
			BlockNumberOrHash::Num(number) => Some(BlockId::Number(number.unique_saturated_into())),
			BlockNumberOrHash::Latest => Some(BlockId::Hash(client.info().best_hash)),
			BlockNumberOrHash::Earliest => Some(BlockId::Hash(client.info().genesis_hash)),
			BlockNumberOrHash::Pending => None,
			BlockNumberOrHash::Safe => Some(BlockId::Hash(client.info().finalized_hash)),
			BlockNumberOrHash::Finalized => Some(BlockId::Hash(client.info().finalized_hash)),
		})
	}

	pub async fn load_hash<B: BlockT, C>(
		client: &C,
		backend: &dyn fc_api::Backend<B>,
		hash: H256,
	) -> RpcResult<Option<B::Hash>>
	where
		B: BlockT,
		C: HeaderBackend<B> + 'static,
	{
		let substrate_hashes = backend
			.block_hash(&hash)
			.await
			.map_err(|err| internal_err(format!("fetch aux store failed: {:?}", err)))?;

		if let Some(substrate_hashes) = substrate_hashes {
			for substrate_hash in substrate_hashes {
				if is_canon::<B, C>(client, substrate_hash) {
					return Ok(Some(substrate_hash));
				}
			}
		}
		Ok(None)
	}

	pub fn is_canon<B: BlockT, C>(client: &C, target_hash: B::Hash) -> bool
	where
		B: BlockT,
		C: HeaderBackend<B> + 'static,
	{
		if let Ok(Some(number)) = client.number(target_hash) {
			if let Ok(Some(hash)) = client.hash(number) {
				return hash == target_hash;
			}
		}
		false
	}

	pub async fn load_transactions<B: BlockT, C>(
		client: &C,
		backend: &dyn fc_api::Backend<B>,
		transaction_hash: H256,
		only_canonical: bool,
	) -> RpcResult<Option<(H256, u32)>>
	where
		B: BlockT,
		C: HeaderBackend<B> + 'static,
	{
		let transaction_metadata = backend
			.transaction_metadata(&transaction_hash)
			.await
			.map_err(|err| internal_err(format!("fetch aux store failed: {:?}", err)))?;

		transaction_metadata
			.iter()
			.find(|meta| is_canon::<B, C>(client, meta.substrate_block_hash))
			.map_or_else(
				|| {
					if !only_canonical && transaction_metadata.len() > 0 {
						Ok(Some((
							transaction_metadata[0].ethereum_block_hash,
							transaction_metadata[0].ethereum_index,
						)))
					} else {
						Ok(None)
					}
				},
				|meta| Ok(Some((meta.ethereum_block_hash, meta.ethereum_index))),
			)
	}
}

pub fn err<T: ToString>(
	code: i32,
	message: T,
	data: Option<&[u8]>,
) -> jsonrpsee::types::error::ErrorObjectOwned {
	jsonrpsee::types::error::ErrorObject::owned(
		code,
		message.to_string(),
		data.map(|bytes| {
			jsonrpsee::core::to_json_raw_value(&format!("0x{}", hex::encode(bytes)))
				.expect("fail to serialize data")
		}),
	)
}

pub fn internal_err<T: ToString>(message: T) -> jsonrpsee::types::error::ErrorObjectOwned {
	err(jsonrpsee::types::error::INTERNAL_ERROR_CODE, message, None)
}

pub fn internal_err_with_data<T: ToString>(
	message: T,
	data: &[u8],
) -> jsonrpsee::types::error::ErrorObjectOwned {
	err(
		jsonrpsee::types::error::INTERNAL_ERROR_CODE,
		message,
		Some(data),
	)
}

pub fn public_key(transaction: &EthereumTransaction) -> Result<[u8; 64], sp_io::EcdsaVerifyError> {
	let mut sig = [0u8; 65];
	let mut msg = [0u8; 32];
	match transaction {
		EthereumTransaction::Legacy(t) => {
			sig[0..32].copy_from_slice(&t.signature.r()[..]);
			sig[32..64].copy_from_slice(&t.signature.s()[..]);
			sig[64] = t.signature.standard_v();
			msg.copy_from_slice(&ethereum::LegacyTransactionMessage::from(t.clone()).hash()[..]);
		}
		EthereumTransaction::EIP2930(t) => {
			sig[0..32].copy_from_slice(&t.r[..]);
			sig[32..64].copy_from_slice(&t.s[..]);
			sig[64] = t.odd_y_parity as u8;
			msg.copy_from_slice(&ethereum::EIP2930TransactionMessage::from(t.clone()).hash()[..]);
		}
		EthereumTransaction::EIP1559(t) => {
			sig[0..32].copy_from_slice(&t.r[..]);
			sig[32..64].copy_from_slice(&t.s[..]);
			sig[64] = t.odd_y_parity as u8;
			msg.copy_from_slice(&ethereum::EIP1559TransactionMessage::from(t.clone()).hash()[..]);
		}
	}
	sp_io::crypto::secp256k1_ecdsa_recover(&sig, &msg)
}

#[cfg(test)]
mod tests {
	use std::{path::PathBuf, sync::Arc};

	use futures::executor;
	use sc_block_builder::BlockBuilderBuilder;
	use sp_blockchain::HeaderBackend;
	use sp_consensus::BlockOrigin;
	use sp_runtime::{
		generic::{Block, Header},
		traits::{BlakeTwo256, Block as BlockT},
	};
	use substrate_test_runtime_client::{
		prelude::*, DefaultTestClientBuilderExt, TestClientBuilder,
	};
	use tempfile::tempdir;

	type OpaqueBlock =
		Block<Header<u64, BlakeTwo256>, substrate_test_runtime_client::runtime::Extrinsic>;

	fn open_frontier_backend<Block: BlockT, C: HeaderBackend<Block>>(
		client: Arc<C>,
		path: PathBuf,
	) -> Result<Arc<fc_db::kv::Backend<Block>>, String> {
		Ok(Arc::new(fc_db::kv::Backend::<Block>::new(
			client,
			&fc_db::kv::DatabaseSettings {
				source: sc_client_db::DatabaseSource::RocksDb {
					path,
					cache_size: 0,
				},
			},
		)?))
	}

	#[test]
	fn substrate_block_hash_one_to_many_works() {
		let tmp = tempdir().expect("create a temporary directory");
		let (client, _) = TestClientBuilder::new()
			.build_with_native_executor::<substrate_test_runtime_client::runtime::RuntimeApi, _>(
			None,
		);

		let mut client = Arc::new(client);

		// Create a temporary frontier secondary DB.
		let backend = open_frontier_backend::<OpaqueBlock, _>(client.clone(), tmp.into_path())
			.expect("a temporary db was created");

		// A random ethereum block hash to use
		let ethereum_block_hash = sp_core::H256::random();

		// G -> A1.
		let chain = client.chain_info();
		let mut builder = BlockBuilderBuilder::new(&*client)
			.on_parent_block(chain.best_hash)
			.with_parent_block_number(chain.best_number)
			.build()
			.unwrap();
		builder.push_storage_change(vec![1], None).unwrap();
		let a1 = builder.build().unwrap().block;
		let a1_hash = a1.header.hash();
		executor::block_on(client.import(BlockOrigin::Own, a1)).unwrap();

		// A1 -> B1
		let mut builder = BlockBuilderBuilder::new(&*client)
			.on_parent_block(a1_hash)
			.fetch_parent_block_number(&*client)
			.unwrap()
			.build()
			.unwrap();
		builder.push_storage_change(vec![1], None).unwrap();
		let b1 = builder.build().unwrap().block;
		let b1_hash = b1.header.hash();
		executor::block_on(client.import(BlockOrigin::Own, b1)).unwrap();

		// Map B1
		let commitment = fc_db::kv::MappingCommitment::<OpaqueBlock> {
			block_hash: b1_hash,
			ethereum_block_hash,
			ethereum_transaction_hashes: vec![],
		};
		let _ = backend.mapping().write_hashes(commitment);

		// Expect B1 to be canon
		assert_eq!(
			futures::executor::block_on(super::frontier_backend_client::load_hash(
				client.as_ref(),
				backend.as_ref(),
				ethereum_block_hash
			))
			.unwrap()
			.unwrap(),
			b1_hash,
		);

		// A1 -> B2
		let mut builder = BlockBuilderBuilder::new(&*client)
			.on_parent_block(a1_hash)
			.fetch_parent_block_number(&*client)
			.unwrap()
			.build()
			.unwrap();
		builder.push_storage_change(vec![2], None).unwrap();
		let b2 = builder.build().unwrap().block;
		let b2_hash = b2.header.hash();
		executor::block_on(client.import(BlockOrigin::Own, b2)).unwrap();

		// Map B2 to same ethereum hash
		let commitment = fc_db::kv::MappingCommitment::<OpaqueBlock> {
			block_hash: b2_hash,
			ethereum_block_hash,
			ethereum_transaction_hashes: vec![],
		};
		let _ = backend.mapping().write_hashes(commitment);

		// Still expect B1 to be canon
		assert_eq!(
			futures::executor::block_on(super::frontier_backend_client::load_hash(
				client.as_ref(),
				backend.as_ref(),
				ethereum_block_hash
			))
			.unwrap()
			.unwrap(),
			b1_hash,
		);

		// B2 -> C1. B2 branch is now canon.
		let mut builder = BlockBuilderBuilder::new(&*client)
			.on_parent_block(b2_hash)
			.fetch_parent_block_number(&*client)
			.unwrap()
			.build()
			.unwrap();
		builder.push_storage_change(vec![1], None).unwrap();
		let c1 = builder.build().unwrap().block;
		executor::block_on(client.import(BlockOrigin::Own, c1)).unwrap();

		// Expect B2 to be new canon
		assert_eq!(
			futures::executor::block_on(super::frontier_backend_client::load_hash(
				client.as_ref(),
				backend.as_ref(),
				ethereum_block_hash
			))
			.unwrap()
			.unwrap(),
			b2_hash,
		);
	}
}