Skip to content

Commit

Permalink
EVM: Refactor FFI from rust strings to passing byte arrays (#2733)
Browse files Browse the repository at this point in the history
* Switch lib from string to byte array

* Shift all exposed ffi and ffi calls to use byte arrays directly

* Fix bugs

* Resolve failing tests from td

* Resolve td test

* Fix lint

* Switch to XAddress

* Better refactor for dest to XAddress

* Better refactor for byte vector conversions

* Switch res to XHash

* Fix td native addresses

* Remove unused func
  • Loading branch information
sieniven authored Jan 16, 2024
1 parent e825ec3 commit ce178e6
Show file tree
Hide file tree
Showing 27 changed files with 236 additions and 225 deletions.
2 changes: 1 addition & 1 deletion lib/ain-cpp-imports/src/bridge.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ pub mod ffi {
fn getPoolTransactions() -> Vec<TransactionData>;
fn getNativeTxSize(data: Vec<u8>) -> u64;
fn getMinRelayTxFee() -> u64;
fn getEthPrivKey(key: String) -> [u8; 32];
fn getEthPrivKey(key: [u8; 20]) -> [u8; 32];
fn getStateInputJSON() -> String;
fn getEthSyncStatus() -> [i64; 2];
fn getAttributeValues(mnview_ptr: usize) -> Attributes;
Expand Down
4 changes: 2 additions & 2 deletions lib/ain-cpp-imports/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ mod ffi {
pub fn getMinRelayTxFee() -> u64 {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getEthPrivKey(_key: String) -> [u8; 32] {
pub fn getEthPrivKey(_key: [u8; 20]) -> [u8; 32] {
unimplemented!("{}", UNIMPL_MSG)
}
pub fn getStateInputJSON() -> String {
Expand Down Expand Up @@ -208,7 +208,7 @@ pub fn get_min_relay_tx_fee() -> Result<u64, Box<dyn Error>> {
}

/// Gets the private key for the given pubkey string.
pub fn get_eth_priv_key(key: String) -> Result<[u8; 32], Box<dyn Error>> {
pub fn get_eth_priv_key(key: [u8; 20]) -> Result<[u8; 32], Box<dyn Error>> {
let eth_key = ffi::getEthPrivKey(key);
Ok(eth_key)
}
Expand Down
22 changes: 7 additions & 15 deletions lib/ain-evm/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ use crate::{
EVMError, Result,
};

pub type XHash = String;
pub type XHash = [u8; 32];
pub type XAddress = [u8; 20];

#[derive(Clone, Debug)]
pub struct ExecutionStep {
Expand Down Expand Up @@ -71,8 +72,8 @@ pub struct EthCallArgs<'a> {
}

pub struct TransferDomainTxInfo {
pub from: String,
pub to: String,
pub from: XAddress,
pub to: XAddress,
pub native_address: String,
pub direction: bool,
pub value: u64,
Expand Down Expand Up @@ -396,10 +397,7 @@ impl EVMCoreService {
}

// Validate tx sender with transferdomain sender
let sender = context
.from
.parse::<H160>()
.map_err(|_| "Invalid address")?;
let sender = H160::from(context.from);
if signed_tx.sender != sender {
return Err(format_err!(
"[validate_raw_transferdomain_tx] invalid sender, signed_tx.sender : {:#?}, transferdomain sender : {:#?}",
Expand Down Expand Up @@ -449,17 +447,11 @@ impl EVMCoreService {

let (from_address, to_address) = if context.direction {
// EvmIn
let to_address = context
.to
.parse::<H160>()
.map_err(|_| "failed to parse to address")?;
let to_address = H160::from(context.to);
(fixed_address, to_address)
} else {
// EvmOut
let from_address = context
.from
.parse::<H160>()
.map_err(|_| "failed to parse from address")?;
let from_address = H160::from(context.from);
(from_address, fixed_address)
};
let value = try_from_satoshi(U256::from(context.value))?.0;
Expand Down
2 changes: 1 addition & 1 deletion lib/ain-evm/src/evm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ impl EVMServices {
.collect(),
Vec::new(),
);
let block_hash = format!("{:?}", block.header.hash());
let block_hash = block.header.hash().to_fixed_bytes();
let receipts = self.receipt.generate_receipts(
&all_transactions,
receipts_v3.clone(),
Expand Down
10 changes: 5 additions & 5 deletions lib/ain-grpc/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,9 +72,9 @@ pub fn init_services() {
let _ = &*SERVICES;
}

pub fn init_network_json_rpc_service(addr: &str) -> Result<()> {
pub fn init_network_json_rpc_service(addr: String) -> Result<()> {
info!("Starting JSON RPC server at {}", addr);
let addr = addr.parse::<SocketAddr>()?;
let addr = addr.as_str().parse::<SocketAddr>()?;
let max_connections = ain_cpp_imports::get_max_connections();
let max_response_size = ain_cpp_imports::get_max_response_byte_size();
let runtime = &SERVICES;
Expand Down Expand Up @@ -112,7 +112,7 @@ pub fn init_network_json_rpc_service(addr: &str) -> Result<()> {
Ok(())
}

pub fn init_network_grpc_service(_addr: &str) -> Result<()> {
pub fn init_network_grpc_service(_addr: String) -> Result<()> {
// log::info!("Starting gRPC server at {}", addr);
// Commented out for now as nothing to serve
// let runtime = &SERVICES;
Expand All @@ -122,9 +122,9 @@ pub fn init_network_grpc_service(_addr: &str) -> Result<()> {
Ok(())
}

pub fn init_network_subscriptions_service(addr: &str) -> Result<()> {
pub fn init_network_subscriptions_service(addr: String) -> Result<()> {
info!("Starting WebSockets server at {}", addr);
let addr = addr.parse::<SocketAddr>()?;
let addr = addr.as_str().parse::<SocketAddr>()?;
let max_connections = ain_cpp_imports::get_max_connections();
let max_response_size = ain_cpp_imports::get_max_response_byte_size();
let runtime = &SERVICES;
Expand Down
4 changes: 2 additions & 2 deletions lib/ain-grpc/src/rpc/eth.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1137,8 +1137,8 @@ impl MetachainRPCServer for MetachainRPCModule {

fn sign(address: H160, message: TransactionMessage) -> RpcResult<TransactionV2> {
debug!(target: "rpc", "sign address {:#x}", address);
let key = format!("{address:?}");
let priv_key = get_eth_priv_key(key).map_err(|_| to_custom_err("Invalid private key"))?;
let priv_key = get_eth_priv_key(address.to_fixed_bytes())
.map_err(|_| to_custom_err("Invalid private key"))?;
let secret_key = SecretKey::parse(&priv_key)
.map_err(|e| to_custom_err(format!("Error parsing SecretKey {e}")))?;

Expand Down
6 changes: 3 additions & 3 deletions lib/ain-rs-exports/src/core.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,21 +20,21 @@ pub fn ain_rs_stop_core_services(result: &mut CrossBoundaryResult) {
cross_boundary_success(result);
}

pub fn ain_rs_init_network_json_rpc_service(result: &mut CrossBoundaryResult, addr: &str) {
pub fn ain_rs_init_network_json_rpc_service(result: &mut CrossBoundaryResult, addr: String) {
match ain_grpc::init_network_json_rpc_service(addr) {
Ok(()) => cross_boundary_success(result),
Err(e) => cross_boundary_error_return(result, e.to_string()),
}
}

pub fn ain_rs_init_network_grpc_service(result: &mut CrossBoundaryResult, addr: &str) {
pub fn ain_rs_init_network_grpc_service(result: &mut CrossBoundaryResult, addr: String) {
match ain_grpc::init_network_grpc_service(addr) {
Ok(()) => cross_boundary_success(result),
Err(e) => cross_boundary_error_return(result, e.to_string()),
}
}

pub fn ain_rs_init_network_subscriptions_service(result: &mut CrossBoundaryResult, addr: &str) {
pub fn ain_rs_init_network_subscriptions_service(result: &mut CrossBoundaryResult, addr: String) {
match ain_grpc::init_network_subscriptions_service(addr) {
Ok(()) => cross_boundary_success(result),
Err(e) => cross_boundary_error_return(result, e.to_string()),
Expand Down
Loading

0 comments on commit ce178e6

Please sign in to comment.