Skip to content

Commit

Permalink
Eth Address cleanup (#387)
Browse files Browse the repository at this point in the history
  • Loading branch information
mrLSD authored and birchmd committed Feb 16, 2022
1 parent 77eb97d commit 0b124d6
Show file tree
Hide file tree
Showing 56 changed files with 646 additions and 452 deletions.
2 changes: 1 addition & 1 deletion engine-precompiles/src/blake2.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use evm::{Context, ExitError};

use crate::prelude::types::EthGas;
use crate::prelude::{mem, Address, Borrowed, TryInto};
use crate::prelude::{mem, types::Address, Borrowed, TryInto};
use crate::{EvmPrecompileResult, Precompile, PrecompileOutput};

/// Blake2 costs.
Expand Down
4 changes: 2 additions & 2 deletions engine-precompiles/src/bn128.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::prelude::types::EthGas;
use crate::prelude::{Address, Borrowed, PhantomData, Vec};
use crate::prelude::types::{Address, EthGas};
use crate::prelude::{Borrowed, PhantomData, Vec};
use crate::{Byzantium, EvmPrecompileResult, HardFork, Istanbul, Precompile, PrecompileOutput};
use evm::{Context, ExitError};

Expand Down
4 changes: 2 additions & 2 deletions engine-precompiles/src/hash.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#[cfg(feature = "contract")]
use crate::prelude::sdk;
use crate::prelude::types::EthGas;
use crate::prelude::{vec, Address};
use crate::prelude::types::{Address, EthGas};
use crate::prelude::vec;
use crate::{EvmPrecompileResult, Precompile, PrecompileOutput};
use evm::{Context, ExitError};

Expand Down
3 changes: 1 addition & 2 deletions engine-precompiles/src/identity.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
use crate::prelude::types::EthGas;
use crate::prelude::Address;
use crate::prelude::types::{Address, EthGas};
use crate::{EvmPrecompileResult, Precompile, PrecompileOutput};
use evm::{Context, ExitError};

Expand Down
34 changes: 18 additions & 16 deletions engine-precompiles/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,10 @@ use crate::identity::Identity;
use crate::modexp::ModExp;
use crate::native::{ExitToEthereum, ExitToNear};
use crate::prelude::types::EthGas;
use crate::prelude::{Vec, H256};
use crate::prelude::{Vec, H160, H256};
use crate::random::RandomSeed;
use crate::secp256k1::ECRecover;
use aurora_engine_types::{account_id::AccountId, vec, Address, BTreeMap, Box};
use aurora_engine_types::{account_id::AccountId, types::Address, vec, BTreeMap, Box};
use evm::backend::Log;
use evm::executor;
use evm::{Context, ExitError, ExitSucceed};
Expand Down Expand Up @@ -106,20 +106,20 @@ pub struct Precompiles(pub prelude::BTreeMap<Address, Box<dyn Precompile>>);
impl executor::PrecompileSet for Precompiles {
fn execute(
&self,
address: prelude::Address,
address: prelude::H160,
input: &[u8],
gas_limit: Option<u64>,
context: &Context,
is_static: bool,
) -> Option<Result<executor::PrecompileOutput, executor::PrecompileFailure>> {
self.0.get(&address).map(|p| {
self.0.get(&Address::new(address)).map(|p| {
p.run(input, gas_limit.map(EthGas::new), context, is_static)
.map_err(|exit_status| executor::PrecompileFailure::Error { exit_status })
})
}

fn is_precompile(&self, address: prelude::Address) -> bool {
self.0.contains_key(&address)
fn is_precompile(&self, address: prelude::H160) -> bool {
self.0.contains_key(&Address::new(address))
}
}

Expand Down Expand Up @@ -259,13 +259,13 @@ impl Precompiles {
}
}

/// const fn for making an address by concatenating the bytes from two given numbers,
/// fn for making an address by concatenating the bytes from two given numbers,
/// Note that 32 + 128 = 160 = 20 bytes (the length of an address). This function is used
/// as a convenience for specifying the addresses of the various precompiles.
pub const fn make_address(x: u32, y: u128) -> prelude::Address {
pub const fn make_address(x: u32, y: u128) -> prelude::types::Address {
let x_bytes = x.to_be_bytes();
let y_bytes = y.to_be_bytes();
prelude::Address([
prelude::types::Address::new(H160([
x_bytes[0],
x_bytes[1],
x_bytes[2],
Expand All @@ -286,7 +286,7 @@ pub const fn make_address(x: u32, y: u128) -> prelude::Address {
y_bytes[13],
y_bytes[14],
y_bytes[15],
])
]))
}

const fn make_h256(x: u128, y: u128) -> prelude::H256 {
Expand Down Expand Up @@ -330,7 +330,9 @@ const fn make_h256(x: u128, y: u128) -> prelude::H256 {

#[cfg(test)]
mod tests {
use crate::prelude::H160;
use crate::{prelude, Byzantium, Istanbul};
use prelude::types::Address;
use rand::Rng;

#[test]
Expand All @@ -354,25 +356,25 @@ mod tests {

let mut rng = rand::thread_rng();
for _ in 0..u8::MAX {
let address: prelude::Address = prelude::Address(rng.gen());
let address = Address::new(H160(rng.gen()));
let (x, y) = split_address(address);
assert_eq!(address, super::make_address(x, y))
}
}

fn u8_to_address(x: u8) -> prelude::Address {
fn u8_to_address(x: u8) -> Address {
let mut bytes = [0u8; 20];
bytes[19] = x;
prelude::Address(bytes)
Address::new(H160(bytes))
}

// Inverse function of `super::make_address`.
fn split_address(a: prelude::Address) -> (u32, u128) {
fn split_address(a: Address) -> (u32, u128) {
let mut x_bytes = [0u8; 4];
let mut y_bytes = [0u8; 16];

x_bytes.copy_from_slice(&a[0..4]);
y_bytes.copy_from_slice(&a[4..20]);
x_bytes.copy_from_slice(&a.raw()[0..4]);
y_bytes.copy_from_slice(&a.raw()[4..20]);

(u32::from_be_bytes(x_bytes), u128::from_be_bytes(y_bytes))
}
Expand Down
4 changes: 2 additions & 2 deletions engine-precompiles/src/modexp.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::prelude::{Address, PhantomData, Vec, U256};
use crate::prelude::{PhantomData, Vec, U256};
use crate::{Berlin, Byzantium, EvmPrecompileResult, HardFork, Precompile, PrecompileOutput};

use crate::prelude::types::EthGas;
use crate::prelude::types::{Address, EthGas};
use evm::{Context, ExitError};
use num::{BigUint, Integer};

Expand Down
47 changes: 24 additions & 23 deletions engine-precompiles/src/native.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@ use crate::prelude::{
sdk,
storage::{bytes_to_key, KeyPrefix},
types::Yocto,
vec, BorshSerialize, Cow, String, ToString, TryFrom, TryInto, Vec, H160, U256,
vec, BorshSerialize, Cow, String, ToString, TryFrom, TryInto, Vec, U256,
};
#[cfg(all(feature = "error_refund", feature = "contract"))]
use crate::prelude::{
parameters::{PromiseWithCallbackArgs, RefundCallArgs},
types,
};

use crate::prelude::types::EthGas;
use crate::prelude::Address;
use crate::prelude::types::{Address, EthGas};
use crate::PrecompileOutput;
use aurora_engine_types::account_id::AccountId;
#[cfg(feature = "contract")]
Expand Down Expand Up @@ -45,7 +44,7 @@ mod costs {
}

pub mod events {
use crate::prelude::{vec, Address, String, ToString, H256, U256};
use crate::prelude::{types::Address, vec, String, ToString, H160, H256, U256};

/// Derived from event signature (see tests::test_exit_signatures)
pub const EXIT_TO_NEAR_SIGNATURE: H256 = crate::make_h256(
Expand All @@ -62,7 +61,7 @@ pub mod events {
/// which ERC-20 token is being withdrawn. However, ETH is not an ERC-20 token
/// So we need to have some other address to fill this field. This constant is
/// used for this purpose.
pub const ETH_ADDRESS: Address = Address([0; 20]);
pub const ETH_ADDRESS: Address = Address::new(H160([0; 20]));

/// ExitToNear(
/// Address indexed sender,
Expand Down Expand Up @@ -128,7 +127,7 @@ pub mod events {

fn encode_address(a: Address) -> H256 {
let mut result = [0u8; 32];
result[12..].copy_from_slice(a.as_ref());
result[12..].copy_from_slice(a.as_bytes());
H256(result)
}

Expand Down Expand Up @@ -253,7 +252,7 @@ impl Precompile for ExitToNear {
) -> EvmPrecompileResult {
#[cfg(feature = "error_refund")]
fn parse_input(input: &[u8]) -> (Address, &[u8]) {
let refund_address = Address::from_slice(&input[1..21]);
let refund_address = Address::from_array(&input[1..21]);
(refund_address, &input[21..])
}
#[cfg(not(feature = "error_refund"))]
Expand Down Expand Up @@ -302,7 +301,7 @@ impl Precompile for ExitToNear {
context.apparent_value.as_u128()
),
events::ExitToNear {
sender: context.caller,
sender: Address::new(context.caller),
erc20_address: events::ETH_ADDRESS,
dest: dest_account.to_string(),
amount: context.apparent_value,
Expand Down Expand Up @@ -346,8 +345,8 @@ impl Precompile for ExitToNear {
amount.as_u128()
),
events::ExitToNear {
sender: erc20_address,
erc20_address,
sender: Address::new(erc20_address),
erc20_address: Address::new(erc20_address),
dest: receiver_account_id.to_string(),
amount,
},
Expand All @@ -365,11 +364,11 @@ impl Precompile for ExitToNear {
let erc20_address = if flag == 0 {
None
} else {
Some(exit_event.erc20_address.0)
Some(exit_event.erc20_address)
};
#[cfg(feature = "error_refund")]
let refund_args = RefundCallArgs {
recipient_address: refund_address.0,
recipient_address: refund_address,
erc20_address,
amount: types::u256_to_arr(&exit_event.amount),
};
Expand Down Expand Up @@ -398,13 +397,13 @@ impl Precompile for ExitToNear {
let promise = PromiseArgs::Create(transfer_promise);

let promise_log = Log {
address: Self::ADDRESS,
address: Self::ADDRESS.raw(),
topics: Vec::new(),
data: promise.try_to_vec().unwrap(),
};
let exit_event_log = exit_event.encode();
let exit_event_log = Log {
address: Self::ADDRESS,
address: Self::ADDRESS.raw(),
topics: exit_event_log.topics,
data: exit_event_log.data,
};
Expand Down Expand Up @@ -489,7 +488,7 @@ impl Precompile for ExitToEthereum {
//
// Input slice format:
// eth_recipient (20 bytes) - the address of recipient which will receive ETH on Ethereum
let recipient_address = input
let recipient_address: Address = input
.try_into()
.map_err(|_| ExitError::Other(Cow::from("ERR_INVALID_RECIPIENT_ADDRESS")))?;
(
Expand All @@ -503,9 +502,9 @@ impl Precompile for ExitToEthereum {
.try_to_vec()
.map_err(|_| ExitError::Other(Cow::from("ERR_INVALID_AMOUNT")))?,
events::ExitToEth {
sender: context.caller,
sender: Address::new(context.caller),
erc20_address: events::ETH_ADDRESS,
dest: H160(recipient_address),
dest: recipient_address,
amount: context.apparent_value,
},
)
Expand Down Expand Up @@ -536,7 +535,9 @@ impl Precompile for ExitToEthereum {
// Parse ethereum address in hex
let eth_recipient: String = hex::encode(input.to_vec());
// unwrap cannot fail since we checked the length already
let recipient_address = input.try_into().unwrap();
let recipient_address = Address::try_from_slice(input).map_err(|_| {
ExitError::Other(crate::prelude::Cow::from("ERR_WRONG_ADDRESS"))
})?;

(
nep141_address,
Expand All @@ -550,9 +551,9 @@ impl Precompile for ExitToEthereum {
.as_bytes()
.to_vec(),
events::ExitToEth {
sender: erc20_address,
erc20_address,
dest: H160(recipient_address),
sender: Address::new(erc20_address),
erc20_address: Address::new(erc20_address),
dest: recipient_address,
amount,
},
)
Expand All @@ -577,13 +578,13 @@ impl Precompile for ExitToEthereum {

let promise = PromiseArgs::Create(withdraw_promise).try_to_vec().unwrap();
let promise_log = Log {
address: Self::ADDRESS,
address: Self::ADDRESS.raw(),
topics: Vec::new(),
data: promise,
};
let exit_event_log = exit_event.encode();
let exit_event_log = Log {
address: Self::ADDRESS,
address: Self::ADDRESS.raw(),
topics: exit_event_log.topics,
data: exit_event_log.data,
};
Expand Down
4 changes: 2 additions & 2 deletions engine-precompiles/src/random.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use super::{EvmPrecompileResult, Precompile};
use crate::prelude::types::EthGas;
use crate::prelude::{Address, H256};
use crate::prelude::types::{Address, EthGas};
use crate::prelude::H256;
use crate::PrecompileOutput;
use evm::{Context, ExitError};

Expand Down
12 changes: 7 additions & 5 deletions engine-precompiles/src/secp256k1.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
use crate::prelude::types::EthGas;
use crate::prelude::types::{Address, EthGas};
use crate::prelude::{sdk, vec, Borrowed, H256};
use crate::{EvmPrecompileResult, Precompile, PrecompileOutput};
use ethabi::Address;
use evm::{Context, ExitError};

mod costs {
Expand Down Expand Up @@ -45,7 +44,8 @@ fn internal_impl(hash: H256, signature: &[u8]) -> Result<Address, ExitError> {
if let Ok(public_key) = secp256k1::recover(&hash, &signature, &recovery_id) {
// recover returns a 65-byte key, but addresses come from the raw 64-byte key
let r = sha3::Keccak256::digest(&public_key.serialize()[1..]);
return Ok(Address::from_slice(&r[12..]));
return Address::try_from_slice(&r[12..])
.map_err(|_| ExitError::Other(Borrowed("ERR_INCORRECT_ADDRESS")));
}
}

Expand Down Expand Up @@ -132,8 +132,10 @@ mod tests {
let signature =
&hex::decode("b9f0bb08640d3c1c00761cdd0121209268f6fd3816bc98b9e6f3cc77bf82b69812ac7a61788a0fdc0e19180f14c945a8e1088a27d92a74dce81c0981fb6447441b")
.unwrap();
let signer =
Address::from_slice(&hex::decode("1563915e194D8CfBA1943570603F7606A3115508").unwrap());
let signer = Address::try_from_slice(
&hex::decode("1563915e194D8CfBA1943570603F7606A3115508").unwrap(),
)
.unwrap();
assert!(ecverify(hash, &signature, signer));
}

Expand Down
2 changes: 1 addition & 1 deletion engine-sdk/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ pub fn ecrecover(hash: H256, signature: &[u8]) -> Result<Address, ECRecoverErr>
exports::keccak256(u64::MAX, RECOVER_REGISTER_ID, KECCACK_REGISTER_ID);
let keccak_hash_bytes = [0u8; 32];
exports::read_register(KECCACK_REGISTER_ID, keccak_hash_bytes.as_ptr() as u64);
Ok(Address::from_slice(&keccak_hash_bytes[12..]))
Ok(Address::try_from_slice(&keccak_hash_bytes[12..]).map_err(|_| ECRecoverErr)?)
} else {
Err(ECRecoverErr)
}
Expand Down
4 changes: 2 additions & 2 deletions engine-sdk/src/prelude.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
pub use aurora_engine_types::types::{NearGas, PromiseResult, STORAGE_PRICE_PER_BYTE};
pub use aurora_engine_types::{vec, Address, Vec, H256};
pub use aurora_engine_types::types::{Address, NearGas, PromiseResult, STORAGE_PRICE_PER_BYTE};
pub use aurora_engine_types::{vec, Vec, H256};
pub use borsh::{BorshDeserialize, BorshSerialize};
2 changes: 1 addition & 1 deletion engine-sdk/src/types.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ pub fn keccak(data: &[u8]) -> H256 {
}

pub fn near_account_to_evm_address(addr: &[u8]) -> Address {
Address::from_slice(&keccak(addr)[12..])
Address::try_from_slice(&keccak(addr)[12..]).unwrap()
}

#[cfg(feature = "contract")]
Expand Down
Loading

0 comments on commit 0b124d6

Please sign in to comment.