Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#188 Added EVM RPC to the node #198

Merged
merged 9 commits into from
May 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
512 changes: 503 additions & 9 deletions evm-template/Cargo.lock

Large diffs are not rendered by default.

10 changes: 10 additions & 0 deletions evm-template/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ sc-chain-spec = { git = "https://github.com/paritytech/polkadot-sdk", default-fe
sc-cli = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-v1.7.0" }
sc-client-api = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-v1.7.0" }
sc-consensus = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-v1.7.0" }
sc-consensus-aura = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-v1.7.0" }
sc-executor = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-v1.7.0" }
sc-network = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-v1.7.0" }
sc-network-sync = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-v1.7.0" }
Expand Down Expand Up @@ -129,9 +130,18 @@ parachain-info = { package = "staging-parachain-info", git = "https://github.com
parachains-common = { git = "https://github.com/paritytech/polkadot-sdk", default-features = false, tag = "polkadot-v1.7.0" }

# EVM
fc-api = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fc-consensus = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fc-db = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fc-mapping-sync = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fc-rpc = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fc-rpc-core = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fc-storage = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fp-account = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false, features = [ "serde" ] }
fp-dynamic-fee = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fp-evm = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fp-rpc = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
fp-self-contained = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
pallet-base-fee = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false }
pallet-ethereum = { git = "https://github.com/OpenZeppelin/frontier", branch = "polkadot-v1.7.0", default-features = false, features = [
"forbid-evm-reentrancy",
Expand Down
13 changes: 13 additions & 0 deletions evm-template/node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ sc-chain-spec = { workspace = true }
sc-cli = { workspace = true }
sc-client-api = { workspace = true }
sc-consensus = { workspace = true }
sc-consensus-aura = { workspace = true }
sc-executor = { workspace = true }
sc-network = { workspace = true }
sc-network-sync = { workspace = true }
Expand All @@ -46,6 +47,7 @@ sp-block-builder = { workspace = true }
sp-blockchain = { workspace = true }
sp-consensus-aura = { workspace = true }
sp-core = { workspace = true }
sp-inherents = { workspace = true }
sp-io = { workspace = true }
sp-keystore = { workspace = true }
sp-runtime = { workspace = true }
Expand All @@ -70,6 +72,17 @@ cumulus-primitives-core = { workspace = true }
cumulus-primitives-parachain-inherent = { workspace = true }
cumulus-relay-chain-interface = { workspace = true }

# Frontier
fc-api = { workspace = true }
fc-consensus = { workspace = true }
fc-db = { workspace = true, features = [ "rocksdb" ] }
fc-mapping-sync = { workspace = true, features = [ "sql" ] }
fc-rpc = { workspace = true }
fc-rpc-core = { workspace = true }
fc-storage = { workspace = true }
fp-dynamic-fee = { workspace = true, features = [ "std" ] }
fp-rpc = { workspace = true }

[build-dependencies]
substrate-build-script-utils = { workspace = true }

Expand Down
3 changes: 3 additions & 0 deletions evm-template/node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,9 @@ fn testnet_genesis(
.collect::<Vec<_>>(),
},
"treasury": {},
"evmChainId": {
"chainId": 9999
},
"polkadotXcm": {
"safeXcmVersion": Some(SAFE_XCM_VERSION),
},
Expand Down
5 changes: 5 additions & 0 deletions evm-template/node/src/cli.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
use std::path::PathBuf;

use crate::eth::EthConfiguration;

/// Sub-commands supported by the collator.
#[derive(Debug, clap::Subcommand)]
pub enum Subcommand {
Expand Down Expand Up @@ -84,6 +86,9 @@ pub struct Cli {
/// Relay chain arguments
#[arg(raw = true)]
pub relay_chain_args: Vec<String>,

#[command(flatten)]
pub eth: EthConfiguration,
}

#[derive(Debug)]
Expand Down
10 changes: 6 additions & 4 deletions evm-template/node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,9 @@ impl SubstrateCli for RelayChainCli {
macro_rules! construct_async_run {
(|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{
let runner = $cli.create_runner($cmd)?;
let eth = $cli.eth.clone();
runner.async_run(|$config| {
let $components = new_partial(&$config)?;
let $components = new_partial(&$config, &eth)?;
let task_manager = $components.task_manager;
{ $( $code )* }.map(|v| (v, task_manager))
})
Expand Down Expand Up @@ -163,7 +164,7 @@ pub fn run() -> Result<()> {
Some(Subcommand::ExportGenesisHead(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| {
let partials = new_partial(&config)?;
let partials = new_partial(&config, &cli.eth)?;

cmd.run(partials.client)
})
Expand All @@ -188,7 +189,7 @@ pub fn run() -> Result<()> {
.into())
},
BenchmarkCmd::Block(cmd) => runner.sync_run(|config| {
let partials = new_partial(&config)?;
let partials = new_partial(&config, &cli.eth)?;
cmd.run(partials.client)
}),
#[cfg(not(feature = "runtime-benchmarks"))]
Expand All @@ -200,7 +201,7 @@ pub fn run() -> Result<()> {
)),
#[cfg(feature = "runtime-benchmarks")]
BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| {
let partials = new_partial(&config)?;
let partials = new_partial(&config, &cli.eth)?;
let db = partials.backend.expose_db();
let storage = partials.backend.expose_storage();
cmd.run(config, partials.client.clone(), db, storage)
Expand Down Expand Up @@ -254,6 +255,7 @@ pub fn run() -> Result<()> {
config,
polkadot_config,
collator_options,
&cli.eth,
id,
hwbench,
)
Expand Down
208 changes: 208 additions & 0 deletions evm-template/node/src/eth.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,208 @@
use std::{
collections::BTreeMap,
path::PathBuf,
sync::{Arc, Mutex},
time::Duration,
};

use fc_rpc::{EthTask, OverrideHandle};
pub use fc_rpc_core::types::{FeeHistoryCache, FeeHistoryCacheLimit, FilterPool};
use futures::{future, prelude::*};
// Local
use parachain_template_runtime::opaque::Block;
// Substrate
use sc_client_api::BlockchainEvents;
use sc_executor::{NativeElseWasmExecutor, NativeExecutionDispatch};
use sc_network_sync::SyncingService;
use sc_service::{error::Error as ServiceError, Configuration, TaskManager};
use sp_api::ConstructRuntimeApi;

/// Full backend.
pub type FullBackend = sc_service::TFullBackend<Block>;
/// Full client.
pub type FullClient<RuntimeApi, Executor> =
sc_service::TFullClient<Block, RuntimeApi, NativeElseWasmExecutor<Executor>>;

/// Frontier DB backend type.
pub type FrontierBackend = fc_db::Backend<Block>;

pub fn db_config_dir(config: &Configuration) -> PathBuf {
config.base_path.config_dir(config.chain_spec.id())
}

/// Avalailable frontier backend types.
#[derive(Debug, Copy, Clone, Default, clap::ValueEnum)]
pub enum BackendType {
/// Either RocksDb or ParityDb as per inherited from the global backend settings.
#[default]
KeyValue,
/// Sql database with custom log indexing.
Sql,
}

/// The ethereum-compatibility configuration used to run a node.
#[derive(Clone, Debug, clap::Parser)]
pub struct EthConfiguration {
/// Maximum number of logs in a query.
#[arg(long, default_value = "10000")]
pub max_past_logs: u32,

/// Maximum fee history cache size.
#[arg(long, default_value = "2048")]
pub fee_history_limit: u64,

#[arg(long)]
pub enable_dev_signer: bool,

/// The dynamic-fee pallet target gas price set by block author
#[arg(long, default_value = "1")]
pub target_gas_price: u64,

/// Maximum allowed gas limit will be `block.gas_limit * execute_gas_limit_multiplier`
/// when using eth_call/eth_estimateGas.
#[arg(long, default_value = "10")]
pub execute_gas_limit_multiplier: u64,

/// Size in bytes of the LRU cache for block data.
#[arg(long, default_value = "50")]
pub eth_log_block_cache: usize,

/// Size in bytes of the LRU cache for transactions statuses data.
#[arg(long, default_value = "50")]
pub eth_statuses_cache: usize,

/// Sets the frontier backend type (KeyValue or Sql)
#[arg(long, value_enum, ignore_case = true, default_value_t = BackendType::default())]
pub frontier_backend_type: BackendType,

// Sets the SQL backend's pool size.
#[arg(long, default_value = "100")]
pub frontier_sql_backend_pool_size: u32,

/// Sets the SQL backend's query timeout in number of VM ops.
#[arg(long, default_value = "10000000")]
pub frontier_sql_backend_num_ops_timeout: u32,

/// Sets the SQL backend's auxiliary thread limit.
#[arg(long, default_value = "4")]
pub frontier_sql_backend_thread_count: u32,

/// Sets the SQL backend's query timeout in number of VM ops.
/// Default value is 200MB.
#[arg(long, default_value = "209715200")]
pub frontier_sql_backend_cache_size: u64,
}

pub struct FrontierPartialComponents {
pub filter_pool: Option<FilterPool>,
pub fee_history_cache: FeeHistoryCache,
pub fee_history_cache_limit: FeeHistoryCacheLimit,
}

pub fn new_frontier_partial(
config: &EthConfiguration,
) -> Result<FrontierPartialComponents, ServiceError> {
Ok(FrontierPartialComponents {
filter_pool: Some(Arc::new(Mutex::new(BTreeMap::new()))),
fee_history_cache: Arc::new(Mutex::new(BTreeMap::new())),
fee_history_cache_limit: config.fee_history_limit,
})
}

/// A set of APIs that ethereum-compatible runtimes must implement.
pub trait EthCompatRuntimeApiCollection:
sp_api::ApiExt<Block>
+ fp_rpc::ConvertTransactionRuntimeApi<Block>
+ fp_rpc::EthereumRuntimeRPCApi<Block>
{
}

impl<Api> EthCompatRuntimeApiCollection for Api where
Api: sp_api::ApiExt<Block>
+ fp_rpc::ConvertTransactionRuntimeApi<Block>
+ fp_rpc::EthereumRuntimeRPCApi<Block>
{
}

pub async fn spawn_frontier_tasks<RuntimeApi, Executor>(
task_manager: &TaskManager,
client: Arc<FullClient<RuntimeApi, Executor>>,
backend: Arc<FullBackend>,
frontier_backend: FrontierBackend,
filter_pool: Option<FilterPool>,
overrides: Arc<OverrideHandle<Block>>,
fee_history_cache: FeeHistoryCache,
fee_history_cache_limit: FeeHistoryCacheLimit,
sync: Arc<SyncingService<Block>>,
pubsub_notification_sinks: Arc<
fc_mapping_sync::EthereumBlockNotificationSinks<
fc_mapping_sync::EthereumBlockNotification<Block>,
>,
>,
) where
RuntimeApi: ConstructRuntimeApi<Block, FullClient<RuntimeApi, Executor>>,
RuntimeApi: Send + Sync + 'static,
RuntimeApi::RuntimeApi: EthCompatRuntimeApiCollection,
Executor: NativeExecutionDispatch + 'static,
{
// Spawn main mapping sync worker background task.
match frontier_backend {
fc_db::Backend::KeyValue(b) => {
task_manager.spawn_essential_handle().spawn(
"frontier-mapping-sync-worker",
Some("frontier"),
fc_mapping_sync::kv::MappingSyncWorker::new(
client.import_notification_stream(),
Duration::new(6, 0),
client.clone(),
backend,
overrides.clone(),
Arc::new(b),
3,
0,
fc_mapping_sync::SyncStrategy::Normal,
sync,
pubsub_notification_sinks,
)
.for_each(|()| future::ready(())),
);
}
fc_db::Backend::Sql(b) => {
task_manager.spawn_essential_handle().spawn_blocking(
"frontier-mapping-sync-worker",
Some("frontier"),
fc_mapping_sync::sql::SyncWorker::run(
client.clone(),
backend,
Arc::new(b),
client.import_notification_stream(),
fc_mapping_sync::sql::SyncWorkerConfig {
read_notification_timeout: Duration::from_secs(10),
check_indexed_blocks_interval: Duration::from_secs(60),
},
fc_mapping_sync::SyncStrategy::Parachain,
sync,
pubsub_notification_sinks,
),
);
}
}

// Spawn Frontier EthFilterApi maintenance task.
if let Some(filter_pool) = filter_pool {
// Each filter is allowed to stay in the pool for 100 blocks.
const FILTER_RETAIN_THRESHOLD: u64 = 100;
task_manager.spawn_essential_handle().spawn(
"frontier-filter-pool",
Some("frontier"),
EthTask::filter_pool_task(client.clone(), filter_pool, FILTER_RETAIN_THRESHOLD),
);
}

// Spawn Frontier FeeHistory cache maintenance task.
task_manager.spawn_essential_handle().spawn(
"frontier-fee-history",
Some("frontier"),
EthTask::fee_history_task(client, overrides, fee_history_cache, fee_history_cache_limit),
);
}
1 change: 1 addition & 0 deletions evm-template/node/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ mod chain_spec;
mod service;
mod cli;
mod command;
mod eth;
mod rpc;

fn main() -> sc_cli::Result<()> {
Expand Down
Loading
Loading