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

refactor: initialize chain without user-provided genesis transactions file #1450

Merged
merged 1 commit into from
Sep 26, 2023
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
74 changes: 9 additions & 65 deletions common/config-parser/src/types/spec.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,4 @@
use std::{
ffi::OsStr,
fmt,
fs::File,
io::{self, Read as _},
path::PathBuf,
};
use std::{ffi::OsStr, fmt, fs::File, io::Read as _, path::PathBuf};

use clap::{
builder::{StringValueParser, TypedValueParser, ValueParserFactory},
Expand All @@ -16,10 +10,7 @@ use strum_macros::EnumIter;
use common_crypto::Secp256k1RecoverablePrivateKey;
use protocol::{
codec::{decode_256bits_key, deserialize_address, ProtocolCodec},
types::{
Block, ExtraData, HardforkInfoInner, Header, Key256Bits, Metadata, RichBlock,
SignedTransaction, H160, H256, U256,
},
types::{ExtraData, HardforkInfoInner, Header, Key256Bits, Metadata, H160, H256, U256},
};

use crate::parse_file;
Expand All @@ -44,11 +35,6 @@ pub struct Genesis {
pub hardforks: Vec<HardforkName>,
pub base_fee_per_gas: U256,
pub chain_id: u64,

#[serde(rename = "transactions")]
pub txs_file: Option<PathBuf>,
#[serde(skip)]
pub txs: Vec<SignedTransaction>,
}

#[derive(Clone, Debug, Deserialize)]
Expand Down Expand Up @@ -101,41 +87,14 @@ impl TypedValueParser for ChainSpecValueParser {
let file_path = StringValueParser::new()
.parse_ref(cmd, arg, value)
.map(PathBuf::from)?;
let dir_path = file_path.parent().ok_or_else(|| {
let err = {
let kind = io::ErrorKind::Other;
let msg = format!("no parent directory of {}", file_path.display());
io::Error::new(kind, msg)
};
parse_file(&file_path, false).map_err(|err| {
let kind = clap::error::ErrorKind::InvalidValue;
clap::Error::raw(kind, err)
})?;
parse_file(&file_path, false)
.map_err(|err| {
let kind = clap::error::ErrorKind::InvalidValue;
let msg = format!(
"failed to parse chain spec file {} since {err}",
file_path.display()
);
clap::Error::raw(kind, msg)
})
.and_then(|mut spec: Self::Value| {
if let Some(ref mut f) = spec.genesis.txs_file {
let txs_file = dir_path.join(&f);
let txs: Vec<SignedTransaction> =
parse_file(&txs_file, true).map_err(|err| {
let kind = clap::error::ErrorKind::InvalidValue;
let msg = format!(
"failed to parse transactions json file {} since {err}",
txs_file.display()
);
clap::Error::raw(kind, msg)
})?;
*f = txs_file;
spec.genesis.txs = txs;
}
Ok(spec)
})
let msg = format!(
"failed to parse chain spec file {} since {err}",
file_path.display()
);
clap::Error::raw(kind, msg)
})
}
}

Expand Down Expand Up @@ -241,21 +200,6 @@ impl TypedValueParser for PrivateKeyFileValueParser {
}

impl Genesis {
/// Build a `RichBlock` of the genesis block from the user provided
/// parameters.
pub fn build_rich_block(&self) -> RichBlock {
let block = self.build_block();
let txs = self.txs.clone();
RichBlock { block, txs }
}

/// Build a `Block` of the genesis block from the user provided parameters.
pub fn build_block(&self) -> Block {
let header = self.build_header();
let tx_hashes = self.txs.iter().map(|tx| tx.transaction.hash).collect();
Block { header, tx_hashes }
}

/// Build a `Header` of the genesis block from the user provided parameters.
pub fn build_header(&self) -> Header {
Header {
Expand Down
60 changes: 38 additions & 22 deletions core/run/src/components/chain_spec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ use ethers_core::abi::AbiEncode;

use common_config_parser::types::spec::ChainSpec;
use common_crypto::{PrivateKey as _, Secp256k1RecoverablePrivateKey, Signature};
use core_executor::system_contract::metadata::metadata_abi::{
AppendMetadataCall, MetadataContractCalls,
use core_executor::system_contract::{
metadata::metadata_abi::{AppendMetadataCall, MetadataContractCalls},
METADATA_CONTRACT_ADDRESS,
};

use protocol::types::{
Hasher, Metadata, RichBlock, SignedTransaction, UnsignedTransaction, UnverifiedTransaction,
Block, Eip1559Transaction, Hasher, Metadata, RichBlock, SignedTransaction, TransactionAction,
UnsignedTransaction, UnverifiedTransaction, BASE_FEE_PER_GAS,
};

pub(crate) trait ChainSpecExt {
Expand All @@ -28,31 +30,45 @@ impl ChainSpecExt for ChainSpec {
let data_0 = encode_metadata(metadata_0);
let data_1 = encode_metadata(metadata_1);

let mut genesis = self.genesis.build_rich_block();
for (idx, tx) in genesis.txs.iter_mut().enumerate() {
let mut utx = tx.transaction.unsigned.clone();
let chain_id = self.genesis.chain_id;

if idx == 0 {
utx.set_data(data_0.clone().into());
} else if idx == 1 {
utx.set_data(data_1.clone().into())
}
let txs: Vec<_> = [data_0, data_1]
.into_iter()
.enumerate()
.map(|(index, data)| {
let nonce = index as u64;
let action = TransactionAction::Call(METADATA_CONTRACT_ADDRESS);
let utx = build_unverified_transaction(nonce, action, data);
build_transaction(&genesis_key, utx, chain_id)
})
.collect();

let new_tx = build_transaction(&genesis_key, utx, genesis.block.header.chain_id);
*tx = new_tx;
}
let header = self.genesis.build_header();
let tx_hashes = txs.iter().map(|tx| tx.transaction.hash).collect::<Vec<_>>();
let block = Block { header, tx_hashes };

let hashes = genesis
.txs
.iter()
.map(|tx| tx.transaction.hash)
.collect::<Vec<_>>();
genesis.block.tx_hashes = hashes;

genesis
RichBlock { block, txs }
}
}

fn build_unverified_transaction(
nonce: u64,
action: TransactionAction,
data: Vec<u8>,
) -> UnsignedTransaction {
let tx = Eip1559Transaction {
nonce: nonce.into(),
max_priority_fee_per_gas: BASE_FEE_PER_GAS.into(),
gas_price: 0u64.into(),
gas_limit: 30000000u64.into(),
value: 0u64.into(),
data: data.into(),
access_list: vec![],
action,
};
UnsignedTransaction::Eip1559(tx)
}

fn build_transaction(
priv_key: &Secp256k1RecoverablePrivateKey,
tx: UnsignedTransaction,
Expand Down
2 changes: 0 additions & 2 deletions devtools/chain/specs/multi_nodes/chain-spec.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ timestamp = 1680249207
base_fee_per_gas = "0x539"
# The default chain id is the hexadecimal of ASCII string "Axon".
chain_id = 0x41786f6e
# A JSON file which includes all transactions in the genesis block.
transactions = "genesis_transactions.json"
hardforks = []

#
Expand Down
Loading