From a46ea4252dbd799ab1679dc8df30408e211faf17 Mon Sep 17 00:00:00 2001 From: jouzo Date: Wed, 19 Apr 2023 11:02:21 +0100 Subject: [PATCH 1/2] Resolve datadir through FFI --- lib/Cargo.lock | 2 ++ lib/ain-cpp-imports/src/lib.rs | 6 +++++ lib/ain-evm/Cargo.toml | 3 +++ lib/ain-evm/src/block.rs | 46 ++-------------------------------- lib/ain-evm/src/evm.rs | 30 +++------------------- lib/ain-evm/src/traits.rs | 43 +++++++++++++++++++++++++++---- src/defid.cpp | 2 +- src/ffi/ffiexports.cpp | 4 +++ src/ffi/ffiexports.h | 1 + 9 files changed, 61 insertions(+), 76 deletions(-) diff --git a/lib/Cargo.lock b/lib/Cargo.lock index c1ec6cd877..f2e27a4e55 100644 --- a/lib/Cargo.lock +++ b/lib/Cargo.lock @@ -34,6 +34,7 @@ dependencies = [ name = "ain-evm" version = "0.1.0" dependencies = [ + "ain-cpp-imports", "anyhow", "bincode", "ethereum", @@ -50,6 +51,7 @@ dependencies = [ "primitive-types", "rand", "rlp", + "serde", "sha3", "tokio", ] diff --git a/lib/ain-cpp-imports/src/lib.rs b/lib/ain-cpp-imports/src/lib.rs index 8e57ce8df9..28dcf0920c 100644 --- a/lib/ain-cpp-imports/src/lib.rs +++ b/lib/ain-cpp-imports/src/lib.rs @@ -9,6 +9,7 @@ mod ffi { fn isMining() -> bool; fn publishEthTransaction(data: Vec) -> bool; fn getAccounts() -> Vec; + fn getDatadir() -> String; } } @@ -31,3 +32,8 @@ pub fn get_accounts() -> Result, Box> { let accounts = ffi::getAccounts(); Ok(accounts) } + +pub fn get_datadir() -> Result> { + let datadir = ffi::getDatadir(); + Ok(datadir) +} diff --git a/lib/ain-evm/Cargo.toml b/lib/ain-evm/Cargo.toml index e5ce20f505..1c7fe9b155 100644 --- a/lib/ain-evm/Cargo.toml +++ b/lib/ain-evm/Cargo.toml @@ -4,6 +4,8 @@ version = "0.1.0" edition = "2021" [dependencies] +ain-cpp-imports = { path = "../ain-cpp-imports" } + evm = { version = "0.37", default-features = false, features = ["with-serde"] } primitive-types = { version = "0.12", default-features = false, features = ["serde"] } log = "0.4" @@ -16,6 +18,7 @@ hex-literal = "0.3.4" anyhow = "1.0" bincode = "1.3.3" rand = "0.8.5" +serde = { version = "1.0", features = ["derive"] } # Runtime dependencies lazy_static = "1.4" diff --git a/lib/ain-evm/src/block.rs b/lib/ain-evm/src/block.rs index 549cdece78..d8d3496fec 100644 --- a/lib/ain-evm/src/block.rs +++ b/lib/ain-evm/src/block.rs @@ -3,10 +3,6 @@ use ethereum::BlockAny; use primitive_types::H256; use std::collections::HashMap; use std::error::Error; -use std::fs::File; -use std::io::{Read, Write}; - -use std::path::Path; use std::sync::{Arc, RwLock}; pub static BLOCK_MAP_PATH: &str = "block_map.bin"; @@ -20,47 +16,9 @@ pub struct BlockHandler { pub blocks: Arc>, } -impl PersistentState for BlockHashtoBlock { - fn save_to_disk(&self, path: &str) -> Result<(), PersistentStateError> { - let serialized_state = bincode::serialize(self)?; - let mut file = File::create(path)?; - file.write_all(&serialized_state)?; - Ok(()) - } - - fn load_from_disk(path: &str) -> Result { - if Path::new(path).exists() { - let mut file = File::open(path)?; - let mut data = Vec::new(); - file.read_to_end(&mut data)?; - let new_state: HashMap = bincode::deserialize(&data)?; - Ok(new_state) - } else { - Ok(Self::new()) - } - } -} +impl PersistentState for BlockHashtoBlock {} -impl PersistentState for Blocks { - fn save_to_disk(&self, path: &str) -> Result<(), PersistentStateError> { - let serialized_state = bincode::serialize(self)?; - let mut file = File::create(path)?; - file.write_all(&serialized_state)?; - Ok(()) - } - - fn load_from_disk(path: &str) -> Result { - if Path::new(path).exists() { - let mut file = File::open(path)?; - let mut data = Vec::new(); - file.read_to_end(&mut data)?; - let new_state: Vec = bincode::deserialize(&data)?; - Ok(new_state) - } else { - Ok(Self::new()) - } - } -} +impl PersistentState for Blocks {} impl Default for BlockHandler { fn default() -> Self { diff --git a/lib/ain-evm/src/evm.rs b/lib/ain-evm/src/evm.rs index 7c9f2a5041..7e4f43bdac 100644 --- a/lib/ain-evm/src/evm.rs +++ b/lib/ain-evm/src/evm.rs @@ -12,12 +12,9 @@ use hex::FromHex; use primitive_types::{H160, H256, U256}; use std::collections::BTreeMap; use std::error::Error; -use std::fs::File; -use std::io::{Read, Write}; -use std::path::Path; use std::sync::{Arc, RwLock}; -pub static EVM_STATE_PATH: &str = "evm_state.bin"; +pub static EVM_STATE_FILE: &str = "evm_state.bin"; pub type EVMState = BTreeMap; @@ -27,26 +24,7 @@ pub struct EVMHandler { pub tx_queues: Arc, } -impl PersistentState for EVMState { - fn save_to_disk(&self, path: &str) -> Result<(), PersistentStateError> { - let serialized_state = bincode::serialize(self)?; - let mut file = File::create(path)?; - file.write_all(&serialized_state)?; - Ok(()) - } - - fn load_from_disk(path: &str) -> Result { - if Path::new(path).exists() { - let mut file = File::open(path)?; - let mut data = Vec::new(); - file.read_to_end(&mut data)?; - let new_state: BTreeMap = bincode::deserialize(&data)?; - Ok(new_state) - } else { - Ok(Self::new()) - } - } -} +impl PersistentState for EVMState {} impl Default for EVMHandler { fn default() -> Self { @@ -58,14 +36,14 @@ impl EVMHandler { pub fn new() -> Self { Self { state: Arc::new(RwLock::new( - EVMState::load_from_disk(EVM_STATE_PATH).expect("Error loading state"), + EVMState::load_from_disk(EVM_STATE_FILE).expect("Error loading state"), )), tx_queues: Arc::new(TransactionQueueMap::new()), } } pub fn flush(&self) -> Result<(), PersistentStateError> { - self.state.write().unwrap().save_to_disk(EVM_STATE_PATH) + self.state.write().unwrap().save_to_disk(EVM_STATE_FILE) } pub fn call( diff --git a/lib/ain-evm/src/traits.rs b/lib/ain-evm/src/traits.rs index 9f84177566..57e4fa7fe1 100644 --- a/lib/ain-evm/src/traits.rs +++ b/lib/ain-evm/src/traits.rs @@ -1,8 +1,8 @@ +use crate::{executor::TxResponse, transaction::SignedTx}; use ethereum::AccessList; use evm::Config; use primitive_types::{H160, U256}; - -use crate::{executor::TxResponse, transaction::SignedTx}; +use std::fs::File; pub trait Executor { const CONFIG: Config = Config::london(); @@ -22,14 +22,47 @@ pub trait Executor { } pub trait PersistentState { - fn save_to_disk(&self, path: &str) -> Result<(), PersistentStateError>; - fn load_from_disk(path: &str) -> Result + fn save_to_disk(&self, file_path: &str) -> Result<(), PersistentStateError> + where + Self: serde::ser::Serialize, + { + // Automatically resolves from datadir for now + let path = match ain_cpp_imports::get_datadir() { + Ok(path) => PathBuf::from(path).join("evm").join(file_path), + _ => PathBuf::from(file_path), + }; + + let serialized_state = bincode::serialize(self)?; + let mut file = File::create(path)?; + file.write_all(&serialized_state)?; + Ok(()) + } + + fn load_from_disk(file_path: &str) -> Result where - Self: Sized; + Self: Sized + serde::de::DeserializeOwned + Default, + { + // Automatically resolves from datadir for now + let path = match ain_cpp_imports::get_datadir() { + Ok(path) => PathBuf::from(path).join("evm").join(file_path), + _ => PathBuf::from(file_path), + }; + + if Path::new(&path).exists() { + let file = File::open(path)?; + let new_state: Self = bincode::deserialize_from(file)?; + Ok(new_state) + } else { + Ok(Self::default()) + } + } } use std::fmt; use std::io; +use std::io::Write; +use std::path::Path; +use std::path::PathBuf; #[derive(Debug)] pub enum PersistentStateError { diff --git a/src/defid.cpp b/src/defid.cpp index 3dbd10ab2b..ed979091ae 100644 --- a/src/defid.cpp +++ b/src/defid.cpp @@ -66,7 +66,6 @@ static bool AppInit(int argc, char* argv[]) bool fRet = false; util::ThreadRename("init"); - init_runtime(); // // Parameters @@ -112,6 +111,7 @@ static bool AppInit(int argc, char* argv[]) } // Start GRPC after BaseParams() has been initialised + init_runtime(); int grpc_port = gArgs.GetArg("-grpcport", BaseParams().GRPCPort()); start_servers("127.0.0.1:" + std::to_string(grpc_port), "127.0.0.1:" + std::to_string(grpc_port + 1)); diff --git a/src/ffi/ffiexports.cpp b/src/ffi/ffiexports.cpp index 6333ab0c0e..39851bbcc2 100644 --- a/src/ffi/ffiexports.cpp +++ b/src/ffi/ffiexports.cpp @@ -62,3 +62,7 @@ rust::vec getAccounts() { } return addresses; } + +rust::string getDatadir() { + return GetDataDir().c_str(); +} diff --git a/src/ffi/ffiexports.h b/src/ffi/ffiexports.h index 5518b7e88b..4e3843a2c1 100644 --- a/src/ffi/ffiexports.h +++ b/src/ffi/ffiexports.h @@ -8,5 +8,6 @@ uint64_t getChainId(); bool isMining(); bool publishEthTransaction(rust::Vec rawTransaction); rust::vec getAccounts(); +rust::string getDatadir(); #endif // DEFI_EVM_FFI_H From df53079b1dfe8834118507cd3fdff1348e70875c Mon Sep 17 00:00:00 2001 From: jouzo Date: Wed, 19 Apr 2023 11:38:51 +0100 Subject: [PATCH 2/2] Fix format --- lib/ain-rs-exports/src/lib.rs | 13 ++++--------- 1 file changed, 4 insertions(+), 9 deletions(-) diff --git a/lib/ain-rs-exports/src/lib.rs b/lib/ain-rs-exports/src/lib.rs index 62d7f8dfc8..e90838576f 100644 --- a/lib/ain-rs-exports/src/lib.rs +++ b/lib/ain-rs-exports/src/lib.rs @@ -6,8 +6,8 @@ use std::error::Error; use primitive_types::H160; -pub const WEI_TO_GWEI : u64 = 1000000000; -pub const GWEI_TO_SATS : u64 = 10; +pub const WEI_TO_GWEI: u64 = 1000000000; +pub const GWEI_TO_SATS: u64 = 10; #[cxx::bridge] mod ffi { @@ -43,14 +43,9 @@ mod ffi { } } -pub fn evm_get_balance( - address: &str, -) -> Result> { +pub fn evm_get_balance(address: &str) -> Result> { let account = address.parse()?; - let mut balance = RUNTIME - .handlers - .evm - .get_balance(account); + let mut balance = RUNTIME.handlers.evm.get_balance(account); balance /= WEI_TO_GWEI; balance /= GWEI_TO_SATS; Ok(balance.as_u64())