Skip to content

Commit

Permalink
Add EVM stuff (#30)
Browse files Browse the repository at this point in the history
* Skeleton

* XCM configs

* Bump toolchain

* Code cleaning part.1

* Code cleaning part.2

* Update SS58

* Rename

* Update token decimals

* Format

* Extract darwinia core primitives

* Add frontier deps without fork!

* License

* Add pallets to runtime

* Benchmarks

* Append command part

* Extract constants

* Docs

* CI part.1

* Adjust the runtime pallets structure (#29)

* frame-system

* pallet-timestamp

* pallet-authorship

* pallet-balances

* pallet-transaction-payment

* pallet-parachain-system

* pallet-parachain-info

* pallet-aura-ext

* pallet-xcmp-queue

* pallet-dmp-queue

* pallet-session

* pallet-aura

* pallet-collator-selection

* format

* deal ambiguous name

* fix compile

* clear imports

* update visibility for pallets

* add license for pallets

* update darwinia comments

* Adapt main

* Delete duplicated consts

* Hack rpc

* Client compile fix

* Fix client

* Move to ethereum mod

* Add more precompile

* Fix some issue

* Solve conflict

* Merge issues

* Format

* Add basic code for precompiles

* Update EthRpcConfig

* Use Hashing type

* Foramt issue

* Adjust service config

* Add evm, ethereum feature

* Add missing features

* Move const

* Doc

* Format

* Format

* Format

* Format

* Format

* Safer truncated

* Clean importing

* Suppress warnings

* Remove empty line

* Clean importing

* Clean importing

* Format

* Clean importing

* Restructure

Co-authored-by: Xavier Lau <xavier@inv.cafe>
Co-authored-by: Guantong <04637@163.com>
  • Loading branch information
3 people authored Nov 14, 2022
1 parent 1aa4cc0 commit e5dfcd6
Show file tree
Hide file tree
Showing 17 changed files with 1,636 additions and 50 deletions.
614 changes: 600 additions & 14 deletions Cargo.lock

Large diffs are not rendered by default.

8 changes: 7 additions & 1 deletion core/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,11 @@ pub type BlockNumber = u32;
/// The address format for describing accounts.
pub type Address = sp_runtime::MultiAddress<AccountId, ()>;

/// Hashing type
pub type Hashing = sp_runtime::traits::BlakeTwo256;

/// Block header type.
pub type Header = sp_runtime::generic::Header<BlockNumber, sp_runtime::traits::BlakeTwo256>;
pub type Header = sp_runtime::generic::Header<BlockNumber, Hashing>;

/// Block type.
pub type Block = sp_runtime::generic::Block<Header, sp_runtime::OpaqueExtrinsic>;
Expand Down Expand Up @@ -94,3 +97,6 @@ pub const MWEI: Balance = 1_000 * KWEI;
pub const KWEI: Balance = 1_000 * WEI;
/// 1 wei — 1
pub const WEI: Balance = 1;

/// Darwinia EVM addresses specific prefix.
pub const EVM_ADDR_PREFIX: &[u8] = b"dvm:";
14 changes: 13 additions & 1 deletion node/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ substrate-build-script-utils = { git = "https://github.com/paritytech/substrate"
# crates.io
clap = { version = "3.2", features = ["derive"] }
codec = { package = "parity-scale-codec", version = "3.2" }
futures = { version = "0.3" }
jsonrpsee = { version = "0.15", features = ["server"] }
log = { version = "0.4" }
serde = { version = "1.0", features = ["derive"] }
Expand All @@ -37,12 +38,23 @@ cumulus-relay-chain-rpc-interface = { git = "https://github.com/paritytech
darwinia-runtime = { path = "../runtime" }
dc-primitives = { path = "../core/primitives" }

# frontier
fc-cli = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }
fc-consensus = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }
fc-db = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }
fc-mapping-sync = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }
fc-rpc = { features = ["rpc_binary_search_estimate"], git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }
fc-rpc-core = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }
fp-evm = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }
fp-rpc = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }
fp-storage = { git = "https://github.com/paritytech/frontier", branch = "polkadot-v0.9.30" }

# polkadot
polkadot-cli = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.30" }
polkadot-parachain = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.30" }
polkadot-primitives = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.30" }
polkadot-service = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.30" }
xcm = { default-features = false, git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.30" }
xcm = { git = "https://github.com/paritytech/polkadot", branch = "release-v0.9.30" }

# substrate
frame-benchmarking = { git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.30" }
Expand Down
56 changes: 54 additions & 2 deletions node/src/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,21 @@

#![allow(clippy::derive_partial_eq_without_eq)]

// std
use std::{collections::BTreeMap, str::FromStr};
// crates.io
use serde::{Deserialize, Serialize};
// cumulus
use cumulus_primitives_core::ParaId;
// darwinia
use darwinia_runtime::{AuraId, EXISTENTIAL_DEPOSIT};
use darwinia_runtime::{AuraId, DarwiniaPrecompiles, EvmConfig, Runtime, EXISTENTIAL_DEPOSIT};
use dc_primitives::*;
// frontier
use fp_evm::GenesisAccount;
// substrate
use sc_chain_spec::{ChainSpecExtension, ChainSpecGroup};
use sc_service::ChainType;
use sp_core::{sr25519, Pair, Public};
use sp_core::{sr25519, Pair, Public, H160, U256};
use sp_runtime::traits::{IdentifyAccount, Verify};

/// Specialized `ChainSpec` for the normal parachain runtime.
Expand All @@ -37,6 +41,11 @@ pub type ChainSpec = sc_service::GenericChainSpec<darwinia_runtime::GenesisConfi
/// The default XCM version to set in genesis config.
const SAFE_XCM_VERSION: u32 = xcm::prelude::XCM_VERSION;

/// This is the simplest bytecode to revert without returning any data.
/// We will pre-deploy it under all of our precompiles to ensure they can be called from within
/// contracts. (PUSH1 0x00 PUSH1 0x00 REVERT)
pub const REVERT_BYTECODE: [u8; 5] = [0x60, 0x00, 0x60, 0x00, 0xFD];

/// Helper function to generate a crypto pair from seed
pub fn get_from_seed<TPublic: Public>(seed: &str) -> <TPublic::Pair as Pair>::Public {
TPublic::Pair::from_string(&format!("//{}", seed), None)
Expand Down Expand Up @@ -240,5 +249,48 @@ fn testnet_genesis(
polkadot_xcm: darwinia_runtime::PolkadotXcmConfig {
safe_xcm_version: Some(SAFE_XCM_VERSION),
},
ethereum: Default::default(),
evm: EvmConfig {
accounts: {
let mut map = BTreeMap::new();
map.insert(
// Testing account.
H160::from_str("0x6be02d1d3665660d22ff9624b7be0551ee1ac91b")
.expect("internal `H160` is valid; qed"),
GenesisAccount {
balance: U256::from_str("0xffffffffffffffffffffffffffffffff")
.expect("internal `U256` is valid; qed"),
code: Default::default(),
nonce: Default::default(),
storage: Default::default(),
},
);
map.insert(
// Benchmarking account.
H160::from_str("1000000000000000000000000000000000000001")
.expect("internal `H160` is valid; qed"),
GenesisAccount {
nonce: U256::from(1),
balance: U256::from(1_000_000_000_000_000_000_000_000_u128),
storage: Default::default(),
code: vec![0x00],
},
);

for precompile in DarwiniaPrecompiles::<Runtime>::used_addresses() {
map.insert(
precompile,
GenesisAccount {
nonce: Default::default(),
balance: Default::default(),
storage: Default::default(),
code: REVERT_BYTECODE.to_vec(),
},
);
}
map
},
},
base_fee: Default::default(),
}
}
49 changes: 49 additions & 0 deletions node/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@ pub enum Subcommand {
/// Export the genesis wasm of the parachain.
ExportGenesisWasm(cumulus_client_cli::ExportGenesisWasmCommand),

/// Db meta columns information.
FrontierDb(fc_cli::FrontierDbCmd),

/// Sub-commands concerned with benchmarking.
/// The pallet benchmarking moved to the `pallet` sub-command.
#[clap(subcommand)]
Expand Down Expand Up @@ -84,6 +87,9 @@ pub struct Cli {
/// Relay chain arguments
#[clap(raw = true)]
pub relay_chain_args: Vec<String>,

#[clap(flatten)]
pub eth_args: EthArgs,
}

#[derive(Debug)]
Expand All @@ -109,3 +115,46 @@ impl RelayChainCli {
Self { base_path, chain_id, base: clap::Parser::parse_from(relay_chain_args) }
}
}

#[derive(Debug, clap::Parser)]
pub struct EthArgs {
/// Size in bytes of the LRU cache for block data.
#[clap(long, default_value = "300000000")]
pub eth_log_block_cache: usize,

/// Size of the LRU cache for block data and their transaction statuses.
#[clap(long, default_value = "300000000")]
pub eth_statuses_cache: usize,

/// Maximum number of logs in a query.
#[clap(long, default_value = "10000")]
pub max_past_logs: u32,

/// Maximum fee history cache size.
#[clap(long, default_value = "2048")]
pub fee_history_limit: u64,
}
impl EthArgs {
pub fn build_eth_rpc_config(&self) -> EthRpcConfig {
EthRpcConfig {
eth_statuses_cache: self.eth_statuses_cache,
eth_log_block_cache: self.eth_log_block_cache,
max_past_logs: self.max_past_logs,
fee_history_limit: self.fee_history_limit,
}
}
}

pub struct EthRpcConfig {
/// Size in bytes of the LRU cache for block data.
pub eth_log_block_cache: usize,

/// Size in bytes of the LRU cache for transactions statuses data.
pub eth_statuses_cache: usize,

/// Maximum fee history cache size.
pub fee_history_limit: u64,

/// Maximum fee history cache size.
pub max_past_logs: u32,
}
36 changes: 33 additions & 3 deletions node/src/command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,12 @@ use cumulus_primitives_core::ParaId;
use crate::{
chain_spec,
cli::{Cli, RelayChainCli, Subcommand},
frontier_service,
service::{self, DarwiniaRuntimeExecutor},
};
use darwinia_runtime::{Block, RuntimeApi};
// frontier
use fc_db::frontier_database_dir;
// substrate
use frame_benchmarking_cli::{BenchmarkCmd, SUBSTRATE_REFERENCE_HARDWARE};
use sc_cli::{
Expand All @@ -38,7 +41,7 @@ use sc_cli::{
};
use sc_service::{
config::{BasePath, PrometheusConfig},
TaskManager,
DatabaseSource, TaskManager,
};
use sp_core::hexdisplay::HexDisplay;
use sp_runtime::traits::{AccountIdConversion, Block as BlockT};
Expand Down Expand Up @@ -311,11 +314,26 @@ pub fn run() -> Result<()> {
let runner = cli.create_runner(cmd)?;

runner.sync_run(|config| {
// Remove Frontier DB.
let db_config_dir = frontier_service::db_config_dir(&config);
let frontier_database_config = match config.database {
DatabaseSource::RocksDb { .. } => DatabaseSource::RocksDb {
path: frontier_database_dir(&db_config_dir, "db"),
cache_size: 0,
},
DatabaseSource::ParityDb { .. } => DatabaseSource::ParityDb {
path: frontier_database_dir(&db_config_dir, "paritydb"),
},
_ =>
return Err(format!("Cannot purge `{:?}` database", config.database).into()),
};

cmd.base.run(frontier_database_config)?;

let polkadot_cli = RelayChainCli::new(
&config,
[RelayChainCli::executable_name()].iter().chain(cli.relay_chain_args.iter()),
);

let polkadot_config = SubstrateCli::create_configuration(
&polkadot_cli,
&polkadot_cli,
Expand All @@ -341,6 +359,16 @@ pub fn run() -> Result<()> {
cmd.run(&*spec)
})
},
// TODO: https://github.com/darwinia-network/darwinia-2.0/issues/35
Some(Subcommand::FrontierDb(cmd)) => {
let runner = cli.create_runner(cmd)?;
runner.sync_run(|config| {
// let PartialComponents { client, other, .. } = service::new_partial(&config,
// &cli)?; let frontier_backend = other.2;
// cmd.run::<_, Block>(client, frontier_backend)
todo!();
})
},
Some(Subcommand::Benchmark(cmd)) => {
let runner = cli.create_runner(cmd)?;
// Switch on the concrete benchmark sub-command-
Expand Down Expand Up @@ -441,6 +469,8 @@ pub fn run() -> Result<()> {
SubstrateCli::create_configuration(&polkadot_cli, &polkadot_cli, tokio_handle)
.map_err(|err| format!("Relay chain argument error: {}", err))?;

let eth_rpc_config = cli.eth_args.build_eth_rpc_config();

info!("Parachain id: {:?}", id);
info!("Parachain Account: {}", parachain_account);
info!("Parachain genesis state: {}", genesis_state);
Expand All @@ -452,6 +482,7 @@ pub fn run() -> Result<()> {
collator_options,
id,
hwbench,
eth_rpc_config,
)
.await
.map(|r| r.0)
Expand All @@ -461,7 +492,6 @@ pub fn run() -> Result<()> {
}
}


fn load_spec(id: &str) -> std::result::Result<Box<dyn ChainSpec>, String> {
Ok(match id {
"dev" => Box::new(chain_spec::development_config()),
Expand Down
Loading

0 comments on commit e5dfcd6

Please sign in to comment.