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
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
// This file is part of Frontier.
//
// Copyright (c) 2023 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/>.

use std::{marker::PhantomData, sync::Arc};

use ethereum::EnvelopedEncodable;
use ethereum_types::H256;
use jsonrpsee::core::{async_trait, RpcResult};
use rlp::Encodable;
// Substrate
use sc_client_api::backend::{Backend, StorageProvider};
use sp_api::ProvideRuntimeApi;
use sp_blockchain::HeaderBackend;
use sp_runtime::traits::Block as BlockT;
// Frontier
use fc_rpc_core::{types::*, DebugApiServer};
use fc_storage::OverrideHandle;
use fp_rpc::EthereumRuntimeRPCApi;

use crate::{cache::EthBlockDataCacheTask, frontier_backend_client, internal_err};

/// Debug API implementation.
pub struct Debug<B: BlockT, C, BE> {
	client: Arc<C>,
	backend: Arc<dyn fc_api::Backend<B>>,
	overrides: Arc<OverrideHandle<B>>,
	block_data_cache: Arc<EthBlockDataCacheTask<B>>,
	_marker: PhantomData<BE>,
}

impl<B: BlockT, C, BE> Debug<B, C, BE> {
	pub fn new(
		client: Arc<C>,
		backend: Arc<dyn fc_api::Backend<B>>,
		overrides: Arc<OverrideHandle<B>>,
		block_data_cache: Arc<EthBlockDataCacheTask<B>>,
	) -> Self {
		Self {
			client,
			backend,
			overrides,
			block_data_cache,
			_marker: PhantomData,
		}
	}

	async fn block_by(&self, number: BlockNumberOrHash) -> RpcResult<Option<ethereum::BlockV2>>
	where
		C: HeaderBackend<B> + StorageProvider<B, BE> + 'static,
		BE: Backend<B>,
	{
		let id = match frontier_backend_client::native_block_id::<B, C>(
			self.client.as_ref(),
			self.backend.as_ref(),
			Some(number),
		)
		.await?
		{
			Some(id) => id,
			None => return Ok(None),
		};

		let substrate_hash = self
			.client
			.expect_block_hash_from_id(&id)
			.map_err(|_| internal_err(format!("Expect block number from id: {}", id)))?;
		let schema = fc_storage::onchain_storage_schema(self.client.as_ref(), substrate_hash);
		let block = self
			.block_data_cache
			.current_block(schema, substrate_hash)
			.await;
		Ok(block)
	}

	async fn transaction_by(
		&self,
		transaction_hash: H256,
	) -> RpcResult<Option<ethereum::TransactionV2>>
	where
		C: HeaderBackend<B> + StorageProvider<B, BE> + 'static,
		BE: Backend<B>,
	{
		let (eth_block_hash, index) = match frontier_backend_client::load_transactions::<B, C>(
			self.client.as_ref(),
			self.backend.as_ref(),
			transaction_hash,
			true,
		)
		.await?
		{
			Some((hash, index)) => (hash, index as usize),
			None => return Ok(None),
		};

		let substrate_hash = match frontier_backend_client::load_hash::<B, C>(
			self.client.as_ref(),
			self.backend.as_ref(),
			eth_block_hash,
		)
		.await?
		{
			Some(hash) => hash,
			None => return Ok(None),
		};

		let schema = fc_storage::onchain_storage_schema(self.client.as_ref(), substrate_hash);
		let block = self
			.block_data_cache
			.current_block(schema, substrate_hash)
			.await;
		if let Some(block) = block {
			Ok(Some(block.transactions[index].clone()))
		} else {
			Ok(None)
		}
	}

	async fn receipts_by(
		&self,
		number: BlockNumberOrHash,
	) -> RpcResult<Option<Vec<ethereum::ReceiptV3>>>
	where
		C: HeaderBackend<B> + StorageProvider<B, BE> + 'static,
		BE: Backend<B>,
	{
		let id = match frontier_backend_client::native_block_id::<B, C>(
			self.client.as_ref(),
			self.backend.as_ref(),
			Some(number),
		)
		.await?
		{
			Some(id) => id,
			None => return Ok(None),
		};

		let substrate_hash = self
			.client
			.expect_block_hash_from_id(&id)
			.map_err(|_| internal_err(format!("Expect block number from id: {}", id)))?;

		let schema = fc_storage::onchain_storage_schema(self.client.as_ref(), substrate_hash);
		let handler = self
			.overrides
			.schemas
			.get(&schema)
			.unwrap_or(&self.overrides.fallback);
		let receipts = handler.current_receipts(substrate_hash);
		Ok(receipts)
	}
}

#[async_trait]
impl<B, C, BE> DebugApiServer for Debug<B, C, BE>
where
	B: BlockT,
	C: ProvideRuntimeApi<B>,
	C::Api: EthereumRuntimeRPCApi<B>,
	C: HeaderBackend<B> + StorageProvider<B, BE> + 'static,
	BE: Backend<B> + 'static,
{
	async fn raw_header(&self, number: BlockNumberOrHash) -> RpcResult<Option<Bytes>> {
		let block = self.block_by(number).await?;
		Ok(block.map(|block| Bytes::new(block.header.rlp_bytes().to_vec())))
	}

	async fn raw_block(&self, number: BlockNumberOrHash) -> RpcResult<Option<Bytes>> {
		let block = self.block_by(number).await?;
		Ok(block.map(|block| Bytes::new(block.rlp_bytes().to_vec())))
	}

	async fn raw_transaction(&self, hash: H256) -> RpcResult<Option<Bytes>> {
		let transaction = self.transaction_by(hash).await?;
		Ok(transaction.map(|transaction| Bytes::new(transaction.encode().to_vec())))
	}

	async fn raw_receipts(&self, number: BlockNumberOrHash) -> RpcResult<Vec<Bytes>> {
		let receipts = self.receipts_by(number).await?.unwrap_or_default();
		Ok(receipts
			.into_iter()
			.map(|receipt| Bytes::new(receipt.encode().to_vec()))
			.collect::<Vec<_>>())
	}

	fn bad_blocks(&self, _number: BlockNumberOrHash) -> RpcResult<Vec<()>> {
		// `debug_getBadBlocks` wouldn't really be useful in a Substrate context.
		// The rationale for that is for debugging multi-client consensus issues, which we'll never face
		// (we may have multiple clients in the future, but for runtime it's only "multi-wasm-runtime", never "multi-EVM").
		// We can simply return empty array for this API.
		Ok(vec![])
	}
}