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 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885
// Copyright 2019-2022 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam 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.
// Moonbeam 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 Moonbeam. If not, see <http://www.gnu.org/licenses/>.
use futures::StreamExt;
use jsonrpsee::core::{async_trait, RpcResult};
pub use moonbeam_rpc_core_debug::{DebugServer, TraceCallParams, TraceParams};
use tokio::{
self,
sync::{oneshot, Semaphore},
};
use ethereum_types::H256;
use fc_rpc::{frontier_backend_client, internal_err};
use fc_storage::StorageOverride;
use fp_rpc::EthereumRuntimeRPCApi;
use moonbeam_client_evm_tracing::{formatters::ResponseFormatter, types::single};
use moonbeam_rpc_core_types::{RequestBlockId, RequestBlockTag};
use moonbeam_rpc_primitives_debug::{DebugRuntimeApi, TracerInput};
use sc_client_api::backend::{Backend, StateBackend, StorageProvider};
use sc_utils::mpsc::TracingUnboundedSender;
use sp_api::{ApiExt, Core, ProvideRuntimeApi};
use sp_block_builder::BlockBuilder;
use sp_blockchain::{
Backend as BlockchainBackend, Error as BlockChainError, HeaderBackend, HeaderMetadata,
};
use sp_runtime::{
generic::BlockId,
traits::{BlakeTwo256, Block as BlockT, Header as HeaderT, UniqueSaturatedInto},
};
use std::{future::Future, marker::PhantomData, sync::Arc};
pub enum RequesterInput {
Call((RequestBlockId, TraceCallParams)),
Transaction(H256),
Block(RequestBlockId),
}
pub enum Response {
Single(single::TransactionTrace),
Block(Vec<single::TransactionTrace>),
}
pub type Responder = oneshot::Sender<RpcResult<Response>>;
pub type DebugRequester =
TracingUnboundedSender<((RequesterInput, Option<TraceParams>), Responder)>;
pub struct Debug {
pub requester: DebugRequester,
}
impl Debug {
pub fn new(requester: DebugRequester) -> Self {
Self { requester }
}
}
#[async_trait]
impl DebugServer for Debug {
/// Handler for `debug_traceTransaction` request. Communicates with the service-defined task
/// using channels.
async fn trace_transaction(
&self,
transaction_hash: H256,
params: Option<TraceParams>,
) -> RpcResult<single::TransactionTrace> {
let requester = self.requester.clone();
let (tx, rx) = oneshot::channel();
// Send a message from the rpc handler to the service level task.
requester
.unbounded_send(((RequesterInput::Transaction(transaction_hash), params), tx))
.map_err(|err| {
internal_err(format!(
"failed to send request to debug service : {:?}",
err
))
})?;
// Receive a message from the service level task and send the rpc response.
rx.await
.map_err(|err| internal_err(format!("debug service dropped the channel : {:?}", err)))?
.map(|res| match res {
Response::Single(res) => res,
_ => unreachable!(),
})
}
async fn trace_block(
&self,
id: RequestBlockId,
params: Option<TraceParams>,
) -> RpcResult<Vec<single::TransactionTrace>> {
let requester = self.requester.clone();
let (tx, rx) = oneshot::channel();
// Send a message from the rpc handler to the service level task.
requester
.unbounded_send(((RequesterInput::Block(id), params), tx))
.map_err(|err| {
internal_err(format!(
"failed to send request to debug service : {:?}",
err
))
})?;
// Receive a message from the service level task and send the rpc response.
rx.await
.map_err(|err| internal_err(format!("debug service dropped the channel : {:?}", err)))?
.map(|res| match res {
Response::Block(res) => res,
_ => unreachable!(),
})
}
/// Handler for `debug_traceCall` request. Communicates with the service-defined task
/// using channels.
async fn trace_call(
&self,
call_params: TraceCallParams,
id: RequestBlockId,
params: Option<TraceParams>,
) -> RpcResult<single::TransactionTrace> {
let requester = self.requester.clone();
let (tx, rx) = oneshot::channel();
// Send a message from the rpc handler to the service level task.
requester
.unbounded_send(((RequesterInput::Call((id, call_params)), params), tx))
.map_err(|err| {
internal_err(format!(
"failed to send request to debug service : {:?}",
err
))
})?;
// Receive a message from the service level task and send the rpc response.
rx.await
.map_err(|err| internal_err(format!("debug service dropped the channel : {:?}", err)))?
.map(|res| match res {
Response::Single(res) => res,
_ => unreachable!(),
})
}
}
pub struct DebugHandler<B: BlockT, C, BE>(PhantomData<(B, C, BE)>);
impl<B, C, BE> DebugHandler<B, C, BE>
where
BE: Backend<B> + 'static,
BE::State: StateBackend<BlakeTwo256>,
C: ProvideRuntimeApi<B>,
C: StorageProvider<B, BE>,
C: HeaderMetadata<B, Error = BlockChainError> + HeaderBackend<B>,
C: Send + Sync + 'static,
B: BlockT<Hash = H256> + Send + Sync + 'static,
C::Api: BlockBuilder<B>,
C::Api: DebugRuntimeApi<B>,
C::Api: EthereumRuntimeRPCApi<B>,
C::Api: ApiExt<B>,
{
/// Task spawned at service level that listens for messages on the rpc channel and spawns
/// blocking tasks using a permit pool.
pub fn task(
client: Arc<C>,
backend: Arc<BE>,
frontier_backend: Arc<dyn fc_api::Backend<B> + Send + Sync>,
permit_pool: Arc<Semaphore>,
storage_override: Arc<dyn StorageOverride<B>>,
raw_max_memory_usage: usize,
) -> (impl Future<Output = ()>, DebugRequester) {
let (tx, mut rx): (DebugRequester, _) =
sc_utils::mpsc::tracing_unbounded("debug-requester", 100_000);
let fut = async move {
loop {
match rx.next().await {
Some((
(RequesterInput::Transaction(transaction_hash), params),
response_tx,
)) => {
let client = client.clone();
let backend = backend.clone();
let frontier_backend = frontier_backend.clone();
let permit_pool = permit_pool.clone();
let storage_override = storage_override.clone();
tokio::task::spawn(async move {
let _ = response_tx.send(
async {
let _permit = permit_pool.acquire().await;
tokio::task::spawn_blocking(move || {
Self::handle_transaction_request(
client.clone(),
backend.clone(),
frontier_backend.clone(),
transaction_hash,
params,
storage_override.clone(),
raw_max_memory_usage,
)
})
.await
.map_err(|e| {
internal_err(format!(
"Internal error on spawned task : {:?}",
e
))
})?
}
.await,
);
});
}
Some((
(RequesterInput::Call((request_block_id, call_params)), params),
response_tx,
)) => {
let client = client.clone();
let frontier_backend = frontier_backend.clone();
let permit_pool = permit_pool.clone();
tokio::task::spawn(async move {
let _ = response_tx.send(
async {
let _permit = permit_pool.acquire().await;
tokio::task::spawn_blocking(move || {
Self::handle_call_request(
client.clone(),
frontier_backend.clone(),
request_block_id,
call_params,
params,
raw_max_memory_usage,
)
})
.await
.map_err(|e| {
internal_err(format!(
"Internal error on spawned task : {:?}",
e
))
})?
}
.await,
);
});
}
Some(((RequesterInput::Block(request_block_id), params), response_tx)) => {
let client = client.clone();
let backend = backend.clone();
let frontier_backend = frontier_backend.clone();
let permit_pool = permit_pool.clone();
let storage_override = storage_override.clone();
tokio::task::spawn(async move {
let _ = response_tx.send(
async {
let _permit = permit_pool.acquire().await;
tokio::task::spawn_blocking(move || {
Self::handle_block_request(
client.clone(),
backend.clone(),
frontier_backend.clone(),
request_block_id,
params,
storage_override.clone(),
)
})
.await
.map_err(|e| {
internal_err(format!(
"Internal error on spawned task : {:?}",
e
))
})?
}
.await,
);
});
}
_ => {}
}
}
};
(fut, tx)
}
fn handle_params(params: Option<TraceParams>) -> RpcResult<(TracerInput, single::TraceType)> {
// Set trace input and type
match params {
Some(TraceParams {
tracer: Some(tracer),
..
}) => {
const BLOCKSCOUT_JS_CODE_HASH: [u8; 16] =
hex_literal::hex!("94d9f08796f91eb13a2e82a6066882f7");
const BLOCKSCOUT_JS_CODE_HASH_V2: [u8; 16] =
hex_literal::hex!("89db13694675692951673a1e6e18ff02");
let hash = sp_io::hashing::twox_128(&tracer.as_bytes());
let tracer =
if hash == BLOCKSCOUT_JS_CODE_HASH || hash == BLOCKSCOUT_JS_CODE_HASH_V2 {
Some(TracerInput::Blockscout)
} else if tracer == "callTracer" {
Some(TracerInput::CallTracer)
} else {
None
};
if let Some(tracer) = tracer {
Ok((tracer, single::TraceType::CallList))
} else {
return Err(internal_err(format!(
"javascript based tracing is not available (hash :{:?})",
hash
)));
}
}
Some(params) => Ok((
TracerInput::None,
single::TraceType::Raw {
disable_storage: params.disable_storage.unwrap_or(false),
disable_memory: params.disable_memory.unwrap_or(false),
disable_stack: params.disable_stack.unwrap_or(false),
},
)),
_ => Ok((
TracerInput::None,
single::TraceType::Raw {
disable_storage: false,
disable_memory: false,
disable_stack: false,
},
)),
}
}
fn handle_block_request(
client: Arc<C>,
backend: Arc<BE>,
frontier_backend: Arc<dyn fc_api::Backend<B> + Send + Sync>,
request_block_id: RequestBlockId,
params: Option<TraceParams>,
storage_override: Arc<dyn StorageOverride<B>>,
) -> RpcResult<Response> {
let (tracer_input, trace_type) = Self::handle_params(params)?;
let reference_id: BlockId<B> = match request_block_id {
RequestBlockId::Number(n) => Ok(BlockId::Number(n.unique_saturated_into())),
RequestBlockId::Tag(RequestBlockTag::Latest) => {
Ok(BlockId::Number(client.info().best_number))
}
RequestBlockId::Tag(RequestBlockTag::Earliest) => {
Ok(BlockId::Number(0u32.unique_saturated_into()))
}
RequestBlockId::Tag(RequestBlockTag::Pending) => {
Err(internal_err("'pending' blocks are not supported"))
}
RequestBlockId::Hash(eth_hash) => {
match futures::executor::block_on(frontier_backend_client::load_hash::<B, C>(
client.as_ref(),
frontier_backend.as_ref(),
eth_hash,
)) {
Ok(Some(hash)) => Ok(BlockId::Hash(hash)),
Ok(_) => Err(internal_err("Block hash not found".to_string())),
Err(e) => Err(e),
}
}
}?;
// Get ApiRef. This handle allow to keep changes between txs in an internal buffer.
let api = client.runtime_api();
// Get Blockchain backend
let blockchain = backend.blockchain();
// Get the header I want to work with.
let Ok(hash) = client.expect_block_hash_from_id(&reference_id) else {
return Err(internal_err("Block header not found"));
};
let header = match client.header(hash) {
Ok(Some(h)) => h,
_ => return Err(internal_err("Block header not found")),
};
// Get parent blockid.
let parent_block_hash = *header.parent_hash();
let statuses = storage_override
.current_transaction_statuses(hash)
.unwrap_or_default();
// Known ethereum transaction hashes.
let eth_tx_hashes: Vec<_> = statuses.iter().map(|t| t.transaction_hash).collect();
// If there are no ethereum transactions in the block return empty trace right away.
if eth_tx_hashes.is_empty() {
return Ok(Response::Block(vec![]));
}
// Get block extrinsics.
let exts = blockchain
.body(hash)
.map_err(|e| internal_err(format!("Fail to read blockchain db: {:?}", e)))?
.unwrap_or_default();
// Get DebugRuntimeApi version
let trace_api_version = if let Ok(Some(api_version)) =
api.api_version::<dyn DebugRuntimeApi<B>>(parent_block_hash)
{
api_version
} else {
return Err(internal_err(
"Runtime api version call failed (trace)".to_string(),
));
};
// Trace the block.
let f = || -> RpcResult<_> {
let result = if trace_api_version >= 5 {
// The block is initialized inside "trace_block"
api.trace_block(parent_block_hash, exts, eth_tx_hashes, &header)
} else {
// Old "trace_block" api did not initialize block before applying transactions,
// so we need to do it here before calling "trace_block".
#[allow(deprecated)]
api.initialize_block_before_version_5(parent_block_hash, &header)
.map_err(|e| internal_err(format!("Runtime api access error: {:?}", e)))?;
#[allow(deprecated)]
api.trace_block_before_version_5(parent_block_hash, exts, eth_tx_hashes)
};
result
.map_err(|e| {
internal_err(format!(
"Blockchain error when replaying block {} : {:?}",
reference_id, e
))
})?
.map_err(|e| {
internal_err(format!(
"Internal runtime error when replaying block {} : {:?}",
reference_id, e
))
})?;
Ok(moonbeam_rpc_primitives_debug::Response::Block)
};
return match trace_type {
single::TraceType::CallList => {
let mut proxy = moonbeam_client_evm_tracing::listeners::CallList::default();
proxy.using(f)?;
proxy.finish_transaction();
let response = match tracer_input {
TracerInput::CallTracer => {
moonbeam_client_evm_tracing::formatters::CallTracer::format(proxy)
.ok_or("Trace result is empty.")
.map_err(|e| internal_err(format!("{:?}", e)))
}
_ => Err(internal_err(
"Bug: failed to resolve the tracer format.".to_string(),
)),
}?;
Ok(Response::Block(response))
}
_ => Err(internal_err(
"debug_traceBlock functions currently only support callList mode (enabled
by providing `{{'tracer': 'callTracer'}}` in the request)."
.to_string(),
)),
};
}
/// Replays a transaction in the Runtime at a given block height.
///
/// In order to succesfully reproduce the result of the original transaction we need a correct
/// state to replay over.
///
/// Substrate allows to apply extrinsics in the Runtime and thus creating an overlayed state.
/// This overlayed changes will live in-memory for the lifetime of the ApiRef.
fn handle_transaction_request(
client: Arc<C>,
backend: Arc<BE>,
frontier_backend: Arc<dyn fc_api::Backend<B> + Send + Sync>,
transaction_hash: H256,
params: Option<TraceParams>,
storage_override: Arc<dyn StorageOverride<B>>,
raw_max_memory_usage: usize,
) -> RpcResult<Response> {
let (tracer_input, trace_type) = Self::handle_params(params)?;
let (hash, index) =
match futures::executor::block_on(frontier_backend_client::load_transactions::<B, C>(
client.as_ref(),
frontier_backend.as_ref(),
transaction_hash,
false,
)) {
Ok(Some((hash, index))) => (hash, index as usize),
Ok(None) => return Err(internal_err("Transaction hash not found".to_string())),
Err(e) => return Err(e),
};
let reference_id =
match futures::executor::block_on(frontier_backend_client::load_hash::<B, C>(
client.as_ref(),
frontier_backend.as_ref(),
hash,
)) {
Ok(Some(hash)) => BlockId::Hash(hash),
Ok(_) => return Err(internal_err("Block hash not found".to_string())),
Err(e) => return Err(e),
};
// Get ApiRef. This handle allow to keep changes between txs in an internal buffer.
let api = client.runtime_api();
// Get Blockchain backend
let blockchain = backend.blockchain();
// Get the header I want to work with.
let Ok(reference_hash) = client.expect_block_hash_from_id(&reference_id) else {
return Err(internal_err("Block header not found"));
};
let header = match client.header(reference_hash) {
Ok(Some(h)) => h,
_ => return Err(internal_err("Block header not found")),
};
// Get parent blockid.
let parent_block_hash = *header.parent_hash();
// Get block extrinsics.
let exts = blockchain
.body(reference_hash)
.map_err(|e| internal_err(format!("Fail to read blockchain db: {:?}", e)))?
.unwrap_or_default();
// Get DebugRuntimeApi version
let trace_api_version = if let Ok(Some(api_version)) =
api.api_version::<dyn DebugRuntimeApi<B>>(parent_block_hash)
{
api_version
} else {
return Err(internal_err(
"Runtime api version call failed (trace)".to_string(),
));
};
let reference_block = storage_override.current_block(reference_hash);
// Get the actual ethereum transaction.
if let Some(block) = reference_block {
let transactions = block.transactions;
if let Some(transaction) = transactions.get(index) {
let f = || -> RpcResult<_> {
let result = if trace_api_version >= 5 {
// The block is initialized inside "trace_transaction"
api.trace_transaction(parent_block_hash, exts, &transaction, &header)
} else {
// Old "trace_transaction" api did not initialize block before applying transactions,
// so we need to do it here before calling "trace_transaction".
#[allow(deprecated)]
api.initialize_block_before_version_5(parent_block_hash, &header)
.map_err(|e| {
internal_err(format!("Runtime api access error: {:?}", e))
})?;
if trace_api_version == 4 {
#[allow(deprecated)]
api.trace_transaction_before_version_5(
parent_block_hash,
exts,
&transaction,
)
} else {
// Pre-london update, legacy transactions.
match transaction {
ethereum::TransactionV2::Legacy(tx) =>
{
#[allow(deprecated)]
api.trace_transaction_before_version_4(
parent_block_hash,
exts,
&tx,
)
}
_ => {
return Err(internal_err(
"Bug: pre-london runtime expects legacy transactions"
.to_string(),
))
}
}
}
};
result
.map_err(|e| {
internal_err(format!(
"Runtime api access error (version {:?}): {:?}",
trace_api_version, e
))
})?
.map_err(|e| internal_err(format!("DispatchError: {:?}", e)))?;
Ok(moonbeam_rpc_primitives_debug::Response::Single)
};
return match trace_type {
single::TraceType::Raw {
disable_storage,
disable_memory,
disable_stack,
} => {
let mut proxy = moonbeam_client_evm_tracing::listeners::Raw::new(
disable_storage,
disable_memory,
disable_stack,
raw_max_memory_usage,
);
proxy.using(f)?;
Ok(Response::Single(
moonbeam_client_evm_tracing::formatters::Raw::format(proxy).ok_or(
internal_err(
"replayed transaction generated too much data. \
try disabling memory or storage?",
),
)?,
))
}
single::TraceType::CallList => {
let mut proxy = moonbeam_client_evm_tracing::listeners::CallList::default();
proxy.using(f)?;
proxy.finish_transaction();
let response = match tracer_input {
TracerInput::Blockscout => {
moonbeam_client_evm_tracing::formatters::Blockscout::format(proxy)
.ok_or("Trace result is empty.")
.map_err(|e| internal_err(format!("{:?}", e)))
}
TracerInput::CallTracer => {
let mut res =
moonbeam_client_evm_tracing::formatters::CallTracer::format(
proxy,
)
.ok_or("Trace result is empty.")
.map_err(|e| internal_err(format!("{:?}", e)))?;
Ok(res.pop().expect("Trace result is empty."))
}
_ => Err(internal_err(
"Bug: failed to resolve the tracer format.".to_string(),
)),
}?;
Ok(Response::Single(response))
}
not_supported => Err(internal_err(format!(
"Bug: `handle_transaction_request` does not support {:?}.",
not_supported
))),
};
}
}
Err(internal_err("Runtime block call failed".to_string()))
}
fn handle_call_request(
client: Arc<C>,
frontier_backend: Arc<dyn fc_api::Backend<B> + Send + Sync>,
request_block_id: RequestBlockId,
call_params: TraceCallParams,
trace_params: Option<TraceParams>,
raw_max_memory_usage: usize,
) -> RpcResult<Response> {
let (tracer_input, trace_type) = Self::handle_params(trace_params)?;
let reference_id: BlockId<B> = match request_block_id {
RequestBlockId::Number(n) => Ok(BlockId::Number(n.unique_saturated_into())),
RequestBlockId::Tag(RequestBlockTag::Latest) => {
Ok(BlockId::Number(client.info().best_number))
}
RequestBlockId::Tag(RequestBlockTag::Earliest) => {
Ok(BlockId::Number(0u32.unique_saturated_into()))
}
RequestBlockId::Tag(RequestBlockTag::Pending) => {
Err(internal_err("'pending' blocks are not supported"))
}
RequestBlockId::Hash(eth_hash) => {
match futures::executor::block_on(frontier_backend_client::load_hash::<B, C>(
client.as_ref(),
frontier_backend.as_ref(),
eth_hash,
)) {
Ok(Some(hash)) => Ok(BlockId::Hash(hash)),
Ok(_) => Err(internal_err("Block hash not found".to_string())),
Err(e) => Err(e),
}
}
}?;
// Get ApiRef. This handle allow to keep changes between txs in an internal buffer.
let api = client.runtime_api();
// Get the header I want to work with.
let Ok(hash) = client.expect_block_hash_from_id(&reference_id) else {
return Err(internal_err("Block header not found"));
};
let header = match client.header(hash) {
Ok(Some(h)) => h,
_ => return Err(internal_err("Block header not found")),
};
// Get parent blockid.
let parent_block_hash = *header.parent_hash();
// Get DebugRuntimeApi version
let trace_api_version = if let Ok(Some(api_version)) =
api.api_version::<dyn DebugRuntimeApi<B>>(parent_block_hash)
{
api_version
} else {
return Err(internal_err(
"Runtime api version call failed (trace)".to_string(),
));
};
if trace_api_version <= 5 {
return Err(internal_err(
"debug_traceCall not supported with old runtimes".to_string(),
));
}
let TraceCallParams {
from,
to,
gas_price,
max_fee_per_gas,
max_priority_fee_per_gas,
gas,
value,
data,
nonce,
access_list,
..
} = call_params;
let (max_fee_per_gas, max_priority_fee_per_gas) =
match (gas_price, max_fee_per_gas, max_priority_fee_per_gas) {
(gas_price, None, None) => {
// Legacy request, all default to gas price.
// A zero-set gas price is None.
let gas_price = if gas_price.unwrap_or_default().is_zero() {
None
} else {
gas_price
};
(gas_price, gas_price)
}
(_, max_fee, max_priority) => {
// eip-1559
// A zero-set max fee is None.
let max_fee = if max_fee.unwrap_or_default().is_zero() {
None
} else {
max_fee
};
// Ensure `max_priority_fee_per_gas` is less or equal to `max_fee_per_gas`.
if let Some(max_priority) = max_priority {
let max_fee = max_fee.unwrap_or_default();
if max_priority > max_fee {
return Err(internal_err(
"Invalid input: `max_priority_fee_per_gas` greater than `max_fee_per_gas`",
));
}
}
(max_fee, max_priority)
}
};
let gas_limit = match gas {
Some(amount) => amount,
None => {
if let Some(block) = api
.current_block(parent_block_hash)
.map_err(|err| internal_err(format!("runtime error: {:?}", err)))?
{
block.header.gas_limit
} else {
return Err(internal_err(
"block unavailable, cannot query gas limit".to_string(),
));
}
}
};
let data = data.map(|d| d.0).unwrap_or_default();
let access_list = access_list.unwrap_or_default();
let f = || -> RpcResult<_> {
let _result = api
.trace_call(
parent_block_hash,
&header,
from.unwrap_or_default(),
to,
data,
value.unwrap_or_default(),
gas_limit,
max_fee_per_gas,
max_priority_fee_per_gas,
nonce,
Some(
access_list
.into_iter()
.map(|item| (item.address, item.storage_keys))
.collect(),
),
)
.map_err(|e| internal_err(format!("Runtime api access error: {:?}", e)))?
.map_err(|e| internal_err(format!("DispatchError: {:?}", e)))?;
Ok(moonbeam_rpc_primitives_debug::Response::Single)
};
return match trace_type {
single::TraceType::Raw {
disable_storage,
disable_memory,
disable_stack,
} => {
let mut proxy = moonbeam_client_evm_tracing::listeners::Raw::new(
disable_storage,
disable_memory,
disable_stack,
raw_max_memory_usage,
);
proxy.using(f)?;
Ok(Response::Single(
moonbeam_client_evm_tracing::formatters::Raw::format(proxy).ok_or(
internal_err(
"replayed transaction generated too much data. \
try disabling memory or storage?",
),
)?,
))
}
single::TraceType::CallList => {
let mut proxy = moonbeam_client_evm_tracing::listeners::CallList::default();
proxy.using(f)?;
proxy.finish_transaction();
let response = match tracer_input {
TracerInput::Blockscout => {
moonbeam_client_evm_tracing::formatters::Blockscout::format(proxy)
.ok_or("Trace result is empty.")
.map_err(|e| internal_err(format!("{:?}", e)))
}
TracerInput::CallTracer => {
let mut res =
moonbeam_client_evm_tracing::formatters::CallTracer::format(proxy)
.ok_or("Trace result is empty.")
.map_err(|e| internal_err(format!("{:?}", e)))?;
Ok(res.pop().expect("Trace result is empty."))
}
_ => Err(internal_err(
"Bug: failed to resolve the tracer format.".to_string(),
)),
}?;
Ok(Response::Single(response))
}
not_supported => Err(internal_err(format!(
"Bug: `handle_call_request` does not support {:?}.",
not_supported
))),
};
}
}