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

evm: Load state from genesis.json #2034

Merged
merged 8 commits into from
Jun 9, 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
1 change: 1 addition & 0 deletions lib/Cargo.lock

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

2 changes: 2 additions & 0 deletions lib/ain-cpp-imports/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,13 @@ pub mod ffi {
fn publishEthTransaction(data: Vec<u8>) -> String;
fn getAccounts() -> Vec<String>;
fn getDatadir() -> String;
fn getNetwork() -> String;
fn getDifficulty(_block_hash: [u8; 32]) -> u32;
fn getChainWork(_block_hash: [u8; 32]) -> [u8; 32];
fn getPoolTransactions() -> Vec<String>;
fn getNativeTxSize(data: Vec<u8>) -> u64;
fn getMinRelayTxFee() -> u64;
fn getEthPrivKey(key_id: [u8; 20]) -> [u8; 32];
fn getStateInputJSON() -> String;
}
}
19 changes: 19 additions & 0 deletions lib/ain-cpp-imports/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ mod ffi {
pub fn getDatadir() -> String {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getNetwork() -> String {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getDifficulty(_block_hash: [u8; 32]) -> u32 {
unimplemented!("{}", UNIMPL_MSG)
}
Expand All @@ -43,6 +46,9 @@ mod ffi {
pub fn getEthPrivKey(_key_id: [u8; 20]) -> [u8; 32] {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getStateInputJSON() -> String {
unimplemented!("{}", UNIMPL_MSG)
}
}

pub fn get_chain_id() -> Result<u64, Box<dyn Error>> {
Expand Down Expand Up @@ -70,6 +76,10 @@ pub fn get_datadir() -> Result<String, Box<dyn Error>> {
Ok(datadir)
}

pub fn get_network() -> String {
ffi::getNetwork()
}

pub fn get_difficulty(block_hash: [u8; 32]) -> Result<u32, Box<dyn Error>> {
let bits = ffi::getDifficulty(block_hash);
Ok(bits)
Expand Down Expand Up @@ -100,5 +110,14 @@ pub fn get_eth_priv_key(key_id: [u8; 20]) -> Result<[u8; 32], Box<dyn Error>> {
Ok(eth_key)
}

pub fn get_state_input_json() -> Option<String> {
let json_path = ffi::getStateInputJSON();
if json_path.is_empty() {
None
} else {
Some(json_path)
}
}

#[cfg(test)]
mod tests {}
1 change: 1 addition & 0 deletions lib/ain-evm/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ keccak-hash = "0.10.0"
serde = { version = "1.0", features = ["derive"] }
ethbloom = "0.13.0"
ethereum-types = "0.14.1"
serde_json = "1.0.96"
statrs = "0.16.0"

# Trie dependencies
Expand Down
2 changes: 1 addition & 1 deletion lib/ain-evm/src/backend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@ use sp_core::Blake2Hasher;
use vsdb_trie_db::MptOnce;

use crate::{
evm::TrieDBStore,
storage::{traits::BlockStorage, Storage},
traits::BridgeBackend,
transaction::SignedTx,
trie::TrieDBStore,
};

type Hasher = Blake2Hasher;
Expand Down
36 changes: 33 additions & 3 deletions lib/ain-evm/src/block.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
use ethereum::{BlockAny, TransactionAny};
use ethereum::{Block, BlockAny, PartialHeader, TransactionAny};
use keccak_hash::H256;
use log::debug;
use primitive_types::U256;

use statrs::statistics::{Data, OrderStatistics};
use std::cmp::{max, Ordering};
use std::sync::Arc;
use std::{fs, io::BufReader, path::PathBuf, sync::Arc};

use crate::storage::{traits::BlockStorage, Storage};
use crate::{
genesis::GenesisData,
storage::{traits::BlockStorage, Storage},
};

pub struct BlockHandler {
storage: Arc<Storage>,
Expand Down Expand Up @@ -259,3 +263,29 @@ impl BlockHandler {
base_fee + priority_fee
}
}

pub fn new_block_from_json(path: PathBuf, state_root: H256) -> Result<BlockAny, std::io::Error> {
let file = fs::File::open(path)?;
let reader = BufReader::new(file);
let genesis: GenesisData = serde_json::from_reader(reader)?;

Ok(Block::new(
PartialHeader {
state_root,
beneficiary: genesis.coinbase,
timestamp: genesis.timestamp,
difficulty: genesis.difficulty,
extra_data: genesis.extra_data,
number: U256::zero(),
parent_hash: Default::default(),
receipts_root: Default::default(),
logs_bloom: Default::default(),
gas_limit: Default::default(),
gas_used: Default::default(),
mix_hash: Default::default(),
nonce: Default::default(),
},
Vec::new(),
Vec::new(),
))
}
86 changes: 45 additions & 41 deletions lib/ain-evm/src/evm.rs
Original file line number Diff line number Diff line change
@@ -1,30 +1,26 @@
use crate::backend::{EVMBackend, EVMBackendError, InsufficientBalance, Vicinity};
use crate::executor::TxResponse;
use crate::fee::calculate_prepay_gas;
use crate::storage::traits::{BlockStorage, PersistentState, PersistentStateError};
use crate::storage::traits::{BlockStorage, PersistentStateError};
use crate::storage::Storage;
use crate::transaction::bridge::{BalanceUpdate, BridgeTx};
use crate::trie::TrieDBStore;
use crate::tx_queue::{QueueError, QueueTx, TransactionQueueMap};
use crate::{
executor::AinExecutor,
traits::{Executor, ExecutorContext},
transaction::SignedTx,
};
use anyhow::anyhow;
use ethereum::{AccessList, Account, Log, TransactionV2};
use ethereum_types::{Bloom, BloomInput};
use ethereum::{AccessList, Account, Block, Log, PartialHeader, TransactionV2};
use ethereum_types::{Bloom, BloomInput, H160, U256};

use hex::FromHex;
use log::debug;
use primitive_types::{H160, H256, U256};
use serde::{Deserialize, Serialize};
use std::error::Error;
use std::path::PathBuf;
use std::sync::Arc;
use vsdb_core::vsdb_set_base_dir;
use vsdb_trie_db::MptStore;

pub static TRIE_DB_STORE: &str = "trie_db_store.bin";

pub type NativeTxHash = [u8; 32];

Expand All @@ -34,34 +30,6 @@ pub struct EVMHandler {
storage: Arc<Storage>,
}

#[derive(Serialize, Deserialize)]
pub struct TrieDBStore {
pub trie_db: MptStore,
}

impl Default for TrieDBStore {
fn default() -> Self {
Self::new()
}
}

impl TrieDBStore {
pub fn new() -> Self {
debug!("Creating new trie store");
let trie_store = MptStore::new();
let mut trie = trie_store
.trie_create(&[0], None, false)
.expect("Error creating initial backend");
let state_root: H256 = trie.commit().into();
debug!("Initial state_root : {:#x}", state_root);
Self {
trie_db: trie_store,
}
}
}

impl PersistentState for TrieDBStore {}

fn init_vsdb() {
debug!(target: "vsdb", "Initializating VSDB");
let datadir = ain_cpp_imports::get_datadir().expect("Could not get imported datadir");
Expand All @@ -75,20 +43,56 @@ fn init_vsdb() {
}

impl EVMHandler {
pub fn new(storage: Arc<Storage>) -> Self {
pub fn restore(storage: Arc<Storage>) -> Self {
init_vsdb();

Self {
tx_queues: Arc::new(TransactionQueueMap::new()),
trie_store: Arc::new(
TrieDBStore::load_from_disk(TRIE_DB_STORE).expect("Error loading trie db store"),
),
trie_store: Arc::new(TrieDBStore::restore()),
storage,
}
}

pub fn new_from_json(storage: Arc<Storage>, path: PathBuf) -> Self {
debug!("Loading genesis state from {}", path.display());
init_vsdb();

let handler = Self {
tx_queues: Arc::new(TransactionQueueMap::new()),
trie_store: Arc::new(TrieDBStore::new()),
storage: Arc::clone(&storage),
};
let state_root =
TrieDBStore::genesis_state_root_from_json(&handler.trie_store, &handler.storage, path)
.expect("Error getting genesis state root from json");

let block: Block<TransactionV2> = Block::new(
PartialHeader {
state_root,
number: U256::zero(),
parent_hash: Default::default(),
beneficiary: Default::default(),
receipts_root: Default::default(),
logs_bloom: Default::default(),
difficulty: Default::default(),
gas_limit: Default::default(),
gas_used: Default::default(),
timestamp: Default::default(),
extra_data: Default::default(),
mix_hash: Default::default(),
nonce: Default::default(),
},
Vec::new(),
Vec::new(),
);
storage.put_latest_block(Some(&block));
storage.put_block(&block);

handler
}

pub fn flush(&self) -> Result<(), PersistentStateError> {
self.trie_store.save_to_disk(TRIE_DB_STORE)
self.trie_store.flush()
}

pub fn call(
Expand Down
33 changes: 33 additions & 0 deletions lib/ain-evm/src/genesis.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use ethereum_types::{H160, H256, H64, U256};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Debug, Serialize, Deserialize)]
struct Config {
chain_id: u32,
homestead_block: u32,
eip150_block: u32,
eip150_hash: String,
eip155_block: u32,
eip158_block: u32,
}

#[derive(Debug, Serialize, Deserialize)]
pub struct Alloc {
pub balance: U256,
pub code: Option<Vec<u8>>,
pub storage: Option<HashMap<H256, H256>>,
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GenesisData {
// config: Config,
pub coinbase: H160,
pub difficulty: U256,
pub extra_data: Vec<u8>,
pub gas_limit: U256,
pub nonce: H64,
pub timestamp: u64,
pub alloc: HashMap<H160, Alloc>,
}
56 changes: 40 additions & 16 deletions lib/ain-evm/src/handler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,39 +7,63 @@ use crate::storage::traits::BlockStorage;
use crate::storage::Storage;
use crate::traits::Executor;
use crate::transaction::bridge::{BalanceUpdate, BridgeTx};
use crate::trie::GENESIS_STATE_ROOT;
use crate::tx_queue::QueueTx;

use anyhow::anyhow;
use ethereum::{Block, PartialHeader, ReceiptV3};
use ethereum_types::{Bloom, H160, H64, U256};
use log::debug;
use primitive_types::H256;
use std::error::Error;
use std::path::PathBuf;
use std::sync::Arc;

const GENESIS_STATE_ROOT: &str =
"0xbc36789e7a1e281436464229828f817d6612f7b477d66591ff96a9e064bcc98a";

pub struct Handlers {
pub evm: EVMHandler,
pub block: BlockHandler,
pub receipt: ReceiptHandler,
pub storage: Arc<Storage>,
}

impl Default for Handlers {
fn default() -> Self {
Self::new()
}
}

impl Handlers {
pub fn new() -> Self {
let storage = Arc::new(Storage::new());
Self {
evm: EVMHandler::new(Arc::clone(&storage)),
block: BlockHandler::new(Arc::clone(&storage)),
receipt: ReceiptHandler::new(Arc::clone(&storage)),
storage,
/// Constructs a new Handlers instance. Depending on whether the defid -ethstartstate flag is set,
/// it either revives the storage from a previously saved state or initializes new storage using input from a JSON file.
/// This JSON-based initialization is exclusively reserved for regtest environments.
///
/// # Warning
///
/// Loading state from JSON will overwrite previous stored state
///
/// # Errors
///
/// This method will return an error if an attempt is made to load a genesis state from a JSON file outside of a regtest environment.
///
/// # Return
///
/// Returns an instance of the struct, either restored from storage or created from a JSON file.
pub fn new() -> Result<Self, anyhow::Error> {
if let Some(path) = ain_cpp_imports::get_state_input_json() {
if ain_cpp_imports::get_network() != "regtest" {
return Err(anyhow!(
"Loading a genesis from JSON file is restricted to regtest network"
));
}
let storage = Arc::new(Storage::new());
Ok(Self {
evm: EVMHandler::new_from_json(Arc::clone(&storage), PathBuf::from(path)),
block: BlockHandler::new(Arc::clone(&storage)),
receipt: ReceiptHandler::new(Arc::clone(&storage)),
storage,
})
} else {
let storage = Arc::new(Storage::restore());
Ok(Self {
evm: EVMHandler::restore(Arc::clone(&storage)),
block: BlockHandler::new(Arc::clone(&storage)),
receipt: ReceiptHandler::new(Arc::clone(&storage)),
storage,
})
}
}

Expand Down
2 changes: 2 additions & 0 deletions lib/ain-evm/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@ mod ecrecover;
pub mod evm;
pub mod executor;
mod fee;
mod genesis;
pub mod handler;
pub mod receipt;
pub mod runtime;
pub mod storage;
pub mod traits;
pub mod transaction;
mod trie;
mod tx_queue;
Loading