Skip to content

Commit

Permalink
Add tracing
Browse files Browse the repository at this point in the history
  • Loading branch information
pgherveou committed Dec 23, 2024
1 parent d27a12a commit e85fcb7
Show file tree
Hide file tree
Showing 27 changed files with 771 additions and 858 deletions.
24 changes: 12 additions & 12 deletions cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -949,11 +949,6 @@ parameter_types! {
pub CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(30);
}

type EventRecord = frame_system::EventRecord<
<Runtime as frame_system::Config>::RuntimeEvent,
<Runtime as frame_system::Config>::Hash,
>;

impl pallet_revive::Config for Runtime {
type Time = Timestamp;
type Currency = Balances;
Expand Down Expand Up @@ -2077,7 +2072,7 @@ impl_runtime_apis! {
}
}

impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber, EventRecord> for Runtime
impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber> for Runtime
{
fn balance(address: H160) -> U256 {
Revive::evm_balance(&address)
Expand All @@ -2102,6 +2097,7 @@ impl_runtime_apis! {
tx,
blockweights.max_block,
encoded_size,
pallet_revive::debug::Tracer::Disabled,
)
}

Expand All @@ -2112,7 +2108,7 @@ impl_runtime_apis! {
gas_limit: Option<Weight>,
storage_deposit_limit: Option<Balance>,
input_data: Vec<u8>,
) -> pallet_revive::ContractResult<pallet_revive::ExecReturnValue, Balance, EventRecord> {
) -> pallet_revive::ContractResult<pallet_revive::ExecReturnValue, Balance> {
let blockweights= <Runtime as frame_system::Config>::BlockWeights::get();
Revive::bare_call(
RuntimeOrigin::signed(origin),
Expand All @@ -2121,8 +2117,7 @@ impl_runtime_apis! {
gas_limit.unwrap_or(blockweights.max_block),
pallet_revive::DepositLimit::Balance(storage_deposit_limit.unwrap_or(u128::MAX)),
input_data,
pallet_revive::DebugInfo::UnsafeDebug,
pallet_revive::CollectEvents::UnsafeCollect,
pallet_revive::debug::Tracer::Disabled,
)
}

Expand All @@ -2134,7 +2129,7 @@ impl_runtime_apis! {
code: pallet_revive::Code,
data: Vec<u8>,
salt: Option<[u8; 32]>,
) -> pallet_revive::ContractResult<pallet_revive::InstantiateReturnValue, Balance, EventRecord>
) -> pallet_revive::ContractResult<pallet_revive::InstantiateReturnValue, Balance>
{
let blockweights= <Runtime as frame_system::Config>::BlockWeights::get();
Revive::bare_instantiate(
Expand All @@ -2145,8 +2140,7 @@ impl_runtime_apis! {
code,
data,
salt,
pallet_revive::DebugInfo::UnsafeDebug,
pallet_revive::CollectEvents::UnsafeCollect,
pallet_revive::debug::Tracer::Disabled,
)
}

Expand All @@ -2172,6 +2166,12 @@ impl_runtime_apis! {
key
)
}

fn trace_tx(
_tx: sp_core::H256
) -> Result<pallet_revive::evm::CallTrace, sp_runtime::DispatchError> {
todo!()
}
}
}

Expand Down
19 changes: 12 additions & 7 deletions substrate/bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3208,7 +3208,7 @@ impl_runtime_apis! {
}
}

impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber, EventRecord> for Runtime
impl pallet_revive::ReviveApi<Block, AccountId, Balance, Nonce, BlockNumber> for Runtime
{
fn balance(address: H160) -> U256 {
Revive::evm_balance(&address)
Expand All @@ -3233,6 +3233,7 @@ impl_runtime_apis! {
tx,
blockweights.max_block,
encoded_size,
pallet_revive::debug::Tracer::Disabled,
)
}

Expand All @@ -3243,16 +3244,15 @@ impl_runtime_apis! {
gas_limit: Option<Weight>,
storage_deposit_limit: Option<Balance>,
input_data: Vec<u8>,
) -> pallet_revive::ContractResult<pallet_revive::ExecReturnValue, Balance, EventRecord> {
) -> pallet_revive::ContractResult<pallet_revive::ExecReturnValue, Balance> {
Revive::bare_call(
RuntimeOrigin::signed(origin),
dest,
value,
gas_limit.unwrap_or(RuntimeBlockWeights::get().max_block),
pallet_revive::DepositLimit::Balance(storage_deposit_limit.unwrap_or(u128::MAX)),
input_data,
pallet_revive::DebugInfo::UnsafeDebug,
pallet_revive::CollectEvents::UnsafeCollect,
pallet_revive::debug::Tracer::Disabled,
)
}

Expand All @@ -3264,7 +3264,7 @@ impl_runtime_apis! {
code: pallet_revive::Code,
data: Vec<u8>,
salt: Option<[u8; 32]>,
) -> pallet_revive::ContractResult<pallet_revive::InstantiateReturnValue, Balance, EventRecord>
) -> pallet_revive::ContractResult<pallet_revive::InstantiateReturnValue, Balance>
{
Revive::bare_instantiate(
RuntimeOrigin::signed(origin),
Expand All @@ -3274,8 +3274,7 @@ impl_runtime_apis! {
code,
data,
salt,
pallet_revive::DebugInfo::UnsafeDebug,
pallet_revive::CollectEvents::UnsafeCollect,
pallet_revive::debug::Tracer::Disabled,
)
}

Expand All @@ -3301,6 +3300,12 @@ impl_runtime_apis! {
key
)
}

fn trace_tx(
_tx: sp_core::H256
) -> Result<pallet_revive::evm::CallTrace, sp_runtime::DispatchError> {
todo!()
}
}

impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentApi<
Expand Down
23 changes: 0 additions & 23 deletions substrate/frame/revive/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,29 +49,6 @@ This module executes PolkaVM smart contracts. These can potentially be written i
RISC-V. For now, the only officially supported languages are Solidity (via [`revive`](https://github.com/xermicus/revive))
and Rust (check the `fixtures` directory for Rust examples).

## Debugging

Contracts can emit messages to the client when called as RPC through the
[`debug_message`](https://paritytech.github.io/substrate/master/pallet_revive/trait.SyscallDocs.html#tymethod.debug_message)
API.

Those messages are gathered into an internal buffer and sent to the RPC client. It is up to the individual client if
and how those messages are presented to the user.

This buffer is also printed as a debug message. In order to see these messages on the node console the log level for the
`runtime::revive` target needs to be raised to at least the `debug` level. However, those messages are easy to
overlook because of the noise generated by block production. A good starting point for observing them on the console is
using this command line in the root directory of the Substrate repository:

```bash
cargo run --release -- --dev -lerror,runtime::revive=debug
```

This raises the log level of `runtime::revive` to `debug` and all other targets to `error` in order to prevent them
from spamming the console.

`--dev`: Use a dev chain spec `--tmp`: Use temporary storage for chain data (the chain state is deleted on exit)

## Host function tracing

For contract authors, it can be a helpful debugging tool to see which host functions are called, with which arguments,
Expand Down
74 changes: 74 additions & 0 deletions substrate/frame/revive/fixtures/contracts/tracing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! This fixture calls itself as many times as passed as argument.
#![no_std]
#![no_main]

use common::input;
use uapi::{HostFn, HostFnImpl as api};

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn deploy() {}

#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn call() {
input!(calls_left: u32, callee_addr: &[u8; 20],);

let next_input = (calls_left - 1).to_le_bytes();

// Call the callee
api::call(
uapi::CallFlags::empty(),
callee_addr,
0u64, // How much ref_time to devote for the execution. 0 = all.
0u64, // How much proof_size to devote for the execution. 0 = all.
None, // No deposit limit.
&[0u8; 32], // Value transferred to the contract.
&next_input,
None,
)
.unwrap();

if calls_left == 0 {
return
}

// own address
let mut addr = [0u8; 20];
api::address(&mut addr);
let mut input = [0u8; 24];

input[..4].copy_from_slice(&next_input);
input[4..24].copy_from_slice(&callee_addr[..20]);

// recurse
api::call(
uapi::CallFlags::ALLOW_REENTRY,
&addr,
0u64, // How much ref_time to devote for the execution. 0 = all.
0u64, // How much deposit_limit to devote for the execution. 0 = all.
None, // No deposit limit.
&[0u8; 32], // Value transferred to the contract.
&input,
None,
)
.unwrap();
}
8 changes: 1 addition & 7 deletions substrate/frame/revive/proc-macro/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -510,13 +510,7 @@ fn expand_functions(def: &EnvDef) -> TokenStream2 {
quote! {
// wrap body in closure to make sure the tracing is always executed
let result = (|| #body)();
if ::log::log_enabled!(target: "runtime::revive::strace", ::log::Level::Trace) {
use core::fmt::Write;
let mut w = sp_std::Writer::default();
let _ = core::write!(&mut w, #trace_fmt_str, #( #trace_fmt_args, )* result);
let msg = core::str::from_utf8(&w.inner()).unwrap_or_default();
self.ext().append_debug_buffer(msg);
}
::log::trace!(target: "runtime::revive::strace", #trace_fmt_str, #( #trace_fmt_args, )* result);
result
}
};
Expand Down
5 changes: 5 additions & 0 deletions substrate/frame/revive/rpc/src/apis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
mod debug_apis;
pub use debug_apis::*;

mod execution_apis;
pub use execution_apis::*;
35 changes: 35 additions & 0 deletions substrate/frame/revive/rpc/src/apis/debug_apis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
use crate::*;
use jsonrpsee::{core::RpcResult, proc_macros::rpc};

/// Debug Ethererum JSON-RPC apis.
#[rpc(server, client)]
pub trait DebugRpc {
/// Returns the tracing of the execution of a specific block using its number.
///
/// ## References
///
/// - https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtraceblockbynumber
/// - https://docs.alchemy.com/reference/what-is-trace_block
/// - https://docs.chainstack.com/reference/ethereum-traceblockbynumber
#[method(name = "debug_traceBlockByNumber")]
async fn trace_block_by_number(
&self,
block: Option<BlockNumberOrTag>,
tracer: Tracer,
) -> RpcResult<Vec<TransactionTrace>>;

/// Returns a transaction's traces by replaying it. This method provides a detailed
/// breakdown of every step in the execution of a transaction
///
/// ## References
///
/// - https://geth.ethereum.org/docs/interacting-with-geth/rpc/ns-debug#debugtracetransaction
/// - https://docs.alchemy.com/reference/debug-tracetransaction
/// - https://docs.chainstack.com/reference/ethereum-tracetransaction
#[method(name = "debug_traceTransaction")]
async fn trace_transaction(
&self,
transaction_hash: H256,
tracer: Tracer,
) -> RpcResult<CallTrace>;
}
Loading

0 comments on commit e85fcb7

Please sign in to comment.