Skip to content

Commit

Permalink
Add tracing features
Browse files Browse the repository at this point in the history
  • Loading branch information
pgherveou committed Jan 13, 2025
1 parent 68fd6d5 commit 2c8d27d
Show file tree
Hide file tree
Showing 43 changed files with 1,117 additions and 1,143 deletions.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 3 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 @@ -953,11 +953,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 @@ -2073,7 +2068,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 Down Expand Up @@ -2108,7 +2103,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 @@ -2117,8 +2112,6 @@ 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,
)
}

Expand All @@ -2130,7 +2123,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 @@ -2141,8 +2134,6 @@ impl_runtime_apis! {
code,
data,
salt,
pallet_revive::DebugInfo::UnsafeDebug,
pallet_revive::CollectEvents::UnsafeCollect,
)
}

Expand Down
10 changes: 3 additions & 7 deletions substrate/bin/node/runtime/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3212,7 +3212,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 Down Expand Up @@ -3247,16 +3247,14 @@ 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,
)
}

Expand All @@ -3268,7 +3266,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 @@ -3278,8 +3276,6 @@ impl_runtime_apis! {
code,
data,
salt,
pallet_revive::DebugInfo::UnsafeDebug,
pallet_revive::CollectEvents::UnsafeCollect,
)
}

Expand Down
2 changes: 1 addition & 1 deletion substrate/frame/revive/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ frame-support = { workspace = true }
frame-system = { workspace = true }
pallet-revive-fixtures = { workspace = true, optional = true }
pallet-revive-proc-macro = { workspace = true }
pallet-revive-uapi = { workspace = true, features = ["scale"] }
pallet-revive-uapi = { workspace = true, features = ["scale", "serde"] }
pallet-transaction-payment = { workspace = true }
sp-api = { workspace = true }
sp-arithmetic = { workspace = true }
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

This file was deleted.

33 changes: 0 additions & 33 deletions substrate/frame/revive/fixtures/contracts/debug_message_works.rs

This file was deleted.

78 changes: 78 additions & 0 deletions substrate/frame/revive/fixtures/contracts/tracing.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
// 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();

api::deposit_event(&[], b"before");

// 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();

api::deposit_event(&[], b"after");

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();
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,11 @@
// 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.

//! Emit a debug message with an invalid utf-8 code.
#![no_std]
#![no_main]

extern crate common;
use uapi::{HostFn, HostFnImpl as api};
use uapi::{HostFn, HostFnImpl as api, StorageFlags};

#[no_mangle]
#[polkavm_derive::polkavm_export]
Expand All @@ -29,5 +27,7 @@ pub extern "C" fn deploy() {}
#[no_mangle]
#[polkavm_derive::polkavm_export]
pub extern "C" fn call() {
api::debug_message(b"\xFC").unwrap();
// Burn some PoV, clear_storage consumes some PoV as in order to clear the storage we need to we
// need to read its size first.
api::clear_storage(StorageFlags::empty(), b"");
}
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
1 change: 1 addition & 0 deletions substrate/frame/revive/rpc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,4 @@ pallet-revive-fixtures = { workspace = true, default-features = true }
static_init = { workspace = true }
substrate-cli-test-utils = { workspace = true }
subxt-signer = { workspace = true, features = ["unstable-eth"] }

53 changes: 53 additions & 0 deletions substrate/frame/revive/rpc/examples/js/contracts/Tracing.sol
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;

contract TracingCaller {
event TraceEvent(uint256 value, string message);
address public callee;

constructor(address _callee) {
require(_callee != address(0), "Callee address cannot be zero");
callee = _callee;
}

function start(uint256 counter) external {
if (counter == 0) {
// uint256 a = 1;
// uint256 b = 0;
// uint256 c = a / b;
return;
}

emit TraceEvent(counter, "before");
TracingCallee(callee).consumeGas();
emit TraceEvent(counter, "after");

try TracingCallee(callee).failingFunction() {
} catch {
}

try TracingCallee(callee).consumeGas{gas: 100}() {
} catch {
}

this.start(counter - 1);
}
}

contract TracingCallee {
event GasConsumed(address indexed caller);

function consumeGas() external {
// burn some gas
for (uint256 i = 0; i < 10; i++) {
uint256(keccak256(abi.encodePacked(i)));
}

emit GasConsumed(msg.sender);
}

function failingFunction() external pure {
require(false, "This function always fails");
}
}

Loading

0 comments on commit 2c8d27d

Please sign in to comment.