Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/develop' into feat/get-erc20-bal…
Browse files Browse the repository at this point in the history
…ance
  • Loading branch information
joshuajbouw committed Feb 1, 2023
2 parents 772794b + 60165ad commit 2ff79be
Show file tree
Hide file tree
Showing 14 changed files with 398 additions and 352 deletions.
591 changes: 322 additions & 269 deletions Cargo.lock

Large diffs are not rendered by default.

10 changes: 6 additions & 4 deletions engine-sdk/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,14 @@ autobenches = false

[dependencies]
aurora-engine-types = { path = "../engine-types", default-features = false }
borsh = { version = "0.9.3", default-features = false }
sha3 = { version = "0.10.2", default-features = false }
sha2 = { version = "0.10.2", default-features = false }

base64 = { version = "0.21", default-features = false, features = [ "alloc" ] }
borsh = { version = "0.9", default-features = false }
sha2 = { version = "0.10", default-features = false }
sha3 = { version = "0.10", default-features = false }

[features]
std = ["aurora-engine-types/std", "borsh/std", "sha3/std", "sha2/std"]
std = ["aurora-engine-types/std", "borsh/std", "sha3/std", "sha2/std", "base64/std" ]
contract = []
log = []
all-promise-actions = []
Expand Down
13 changes: 13 additions & 0 deletions engine-sdk/src/base64.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
use aurora_engine_types::{String, Vec};
pub use base64::DecodeError;
use base64::Engine;

/// Encode arbitrary octets as base64 using the standard `base64::Engine`.
pub fn encode<T: AsRef<[u8]>>(input: T) -> String {
base64::engine::general_purpose::STANDARD.encode(input)
}

/// Decode from string reference as octets using the standard `base64::Engine`.
pub fn decode<T: AsRef<[u8]>>(input: T) -> Result<Vec<u8>, DecodeError> {
base64::engine::general_purpose::STANDARD.decode(input)
}
2 changes: 1 addition & 1 deletion engine-sdk/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(not(feature = "std"), feature(alloc_error_handler))]

#[cfg(feature = "contract")]
use crate::prelude::{Address, Vec, U256};
use crate::prelude::{H256, STORAGE_PRICE_PER_BYTE};
pub use types::keccak;

pub mod base64;
pub mod caching;
pub mod env;
pub mod error;
Expand Down
3 changes: 1 addition & 2 deletions engine-standalone-storage/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,13 @@ aurora-engine-types = { path = "../engine-types", default-features = false, feat
aurora-engine-sdk = { path = "../engine-sdk", default-features = false, features = ["std"] }
aurora-engine-transactions = { path = "../engine-transactions", default-features = false, features = ["std"] }
aurora-engine-precompiles = { path = "../engine-precompiles", default-features = false, features = ["std"] }
borsh = { version = "0.9.3" }
borsh = "0.9"
evm-core = { git = "https://github.com/aurora-is-near/sputnikvm.git", tag = "v0.37.4-aurora", default-features = false }
hex = "0.4.3"
rocksdb = { version = "0.19.0", default-features = false }
postgres = "0.19.2"
serde = "1.0.130"
serde_json = "1.0.72"
base64 = "0.13.0"

[features]
default = ["snappy", "lz4", "zstd", "zlib"]
Expand Down
12 changes: 7 additions & 5 deletions engine-standalone-storage/src/json_snapshot/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ pub fn initialize_engine_state(

let mut batch = rocksdb::WriteBatch::default();
for entry in snapshot.result.values {
let key = base64::decode(entry.key)?;
let value = base64::decode(entry.value)?;
let key = aurora_engine_sdk::base64::decode(entry.key)?;
let value = aurora_engine_sdk::base64::decode(entry.value)?;
let storage_key = crate::construct_engine_key(&key, block_height, transaction_position);
let storage_value = crate::diff::DiffValue::Modified(value);
batch.put(storage_key, storage_value.try_to_bytes()?);
Expand All @@ -26,15 +26,17 @@ pub fn initialize_engine_state(
}

pub mod error {
use aurora_engine_sdk::base64::DecodeError;

#[derive(Debug)]
pub enum Error {
Base64(base64::DecodeError),
Base64(DecodeError),
Rocksdb(rocksdb::Error),
Borsh(std::io::Error),
}

impl From<base64::DecodeError> for Error {
fn from(e: base64::DecodeError) -> Self {
impl From<DecodeError> for Error {
fn from(e: DecodeError) -> Self {
Self::Base64(e)
}
}
Expand Down
6 changes: 3 additions & 3 deletions engine-standalone-storage/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -315,11 +315,11 @@ impl Storage {

let value = if iter.valid() {
let bytes = iter.value().unwrap();
diff::DiffValue::try_from_bytes(bytes).unwrap_or_else(|e| {
DiffValue::try_from_bytes(bytes).unwrap_or_else(|e| {
panic!(
"Could not deserialize key={} value={} error={:?}",
base64::encode(&db_key),
base64::encode(bytes),
aurora_engine_sdk::base64::encode(&db_key),
aurora_engine_sdk::base64::encode(bytes),
e,
)
})
Expand Down
3 changes: 1 addition & 2 deletions engine-tests/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ evm = { git = "https://github.com/aurora-is-near/sputnikvm.git", tag = "v0.37.4-
evm-runtime = { git = "https://github.com/aurora-is-near/sputnikvm.git", tag = "v0.37.4-aurora", default-features = false, features = ["std", "tracing"] }
evm-gasometer = { git = "https://github.com/aurora-is-near/sputnikvm.git", tag = "v0.37.4-aurora", default-features = false, features = ["std", "tracing"] }
rlp = { version = "0.5.0", default-features = false }
base64 = "0.13.0"
bstr = "1.0.1"
byte-slice-cast = { version = "1.0", default-features = false }
ethabi = "18.0"
Expand All @@ -47,7 +46,7 @@ near-primitives = { git = "https://github.com/birchmd/nearcore.git", rev = "6033
libsecp256k1 = { version = "0.7.0", default-features = false }
rand = "0.8.5"
criterion = "0.4.0"
git2 = "0.15"
git2 = "0.16"
tempfile = "3.2.0"
walrus = "0.19"

Expand Down
4 changes: 2 additions & 2 deletions engine-tests/src/test_utils/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -248,8 +248,8 @@ impl AuroraRunner {
) {
let trie = &mut self.ext.underlying.fake_trie;
for entry in snapshot.result.values {
let key = base64::decode(entry.key).unwrap();
let value = base64::decode(entry.value).unwrap();
let key = aurora_engine_sdk::base64::decode(entry.key).unwrap();
let value = aurora_engine_sdk::base64::decode(entry.value).unwrap();
trie.insert(key, value);
}
}
Expand Down
60 changes: 31 additions & 29 deletions engine-tests/src/tests/sanity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,19 +150,19 @@ fn test_state_format() {
assert_eq!(hex::encode(state.try_to_vec().unwrap()), expected_hex);
}

fn generate_code(len: usize) -> Vec<u8> {
let mut rng = rand::thread_rng();
let mut buf = vec![0u8; len];
rng.fill_bytes(&mut buf);
buf
}

#[test]
fn test_deploy_contract() {
let (mut runner, mut signer, _) = initialize_transfer();

// Randomly generate some "contract code"
const LEN: usize = 567;
let code: Vec<u8> = {
let mut rng = rand::thread_rng();
let mut buf = vec![0u8; LEN];
rng.fill_bytes(&mut buf);
buf
};

let code = generate_code(567);
// Deploy that code
let result = runner
.submit_with_signer(&mut signer, |nonce| {
Expand All @@ -183,12 +183,7 @@ fn test_deploy_largest_contract() {
let (mut runner, mut signer, _) = initialize_transfer();

let len = evm::Config::berlin().create_contract_limit.unwrap();
let code: Vec<u8> = {
let mut rng = rand::thread_rng();
let mut buf = vec![0u8; len];
rng.fill_bytes(&mut buf);
buf
};
let code = generate_code(len);

// Deploy that code
let (result, profile) = runner
Expand Down Expand Up @@ -352,9 +347,7 @@ fn test_solidity_pure_bench() {
);

// Pure rust version of the same contract
let base_path = std::path::Path::new("../etc")
.join("tests")
.join("benchmark-contract");
let base_path = Path::new("../etc").join("tests").join("benchmark-contract");
let output_path =
base_path.join("target/wasm32-unknown-unknown/release/benchmark_contract.wasm");
test_utils::rust::compile(base_path);
Expand Down Expand Up @@ -404,7 +397,7 @@ fn test_revert_during_contract_deploy() {
.submit_transaction(&signer.secret_key, deploy_tx)
.unwrap();

let revert_bytes = crate::test_utils::unwrap_revert(submit_result);
let revert_bytes = test_utils::unwrap_revert(submit_result);
// First 4 bytes is a function selector with signature `Error(string)`
assert_eq!(&revert_bytes[0..4], &[8, 195, 121, 160]);
// Remaining data is an ABI-encoded string
Expand Down Expand Up @@ -562,9 +555,7 @@ fn test_override_state() {
))
.unwrap();
match result {
crate::prelude::parameters::TransactionStatus::Succeed(bytes) => {
Address::try_from_slice(&bytes[12..32]).unwrap()
}
TransactionStatus::Succeed(bytes) => Address::try_from_slice(&bytes[12..32]).unwrap(),
_ => panic!("tx failed"),
}
};
Expand Down Expand Up @@ -808,6 +799,8 @@ fn test_transfer_charging_gas_success() {

#[test]
fn test_eth_transfer_charging_gas_not_enough_balance() {
use near_vm_errors::{FunctionCallError, HostError, VMError};

let (mut runner, mut source_account, dest_address) = initialize_transfer();
let source_address = test_utils::address_from_secret_key(&source_account.secret_key);
let transaction = |nonce| {
Expand All @@ -829,10 +822,13 @@ fn test_eth_transfer_charging_gas_not_enough_balance() {
test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into());

// attempt transfer
let result = runner
let error = runner
.submit_with_signer(&mut source_account, transaction)
.unwrap();
assert_eq!(result.status, TransactionStatus::OutOfFund);
.unwrap_err();
assert!(matches!(error, VMError::FunctionCallError(
FunctionCallError::HostError(
HostError::GuestPanic { panic_msg })) if panic_msg == "ERR_OUT_OF_FUND"
));

// validate post-state
let relayer = sdk::types::near_account_to_evm_address(
Expand All @@ -843,8 +839,8 @@ fn test_eth_transfer_charging_gas_not_enough_balance() {
&runner,
source_address,
INITIAL_BALANCE,
// nonce is still incremented since the transaction was otherwise valid
(INITIAL_NONCE + 1).into(),
// nonce is still not incremented since the transaction was invalid
INITIAL_NONCE.into(),
);
test_utils::validate_address_balance_and_nonce(&runner, dest_address, Wei::zero(), 0.into());
test_utils::validate_address_balance_and_nonce(&runner, relayer, Wei::zero(), 0.into());
Expand Down Expand Up @@ -996,6 +992,8 @@ fn test_eth_transfer_insufficient_balance_sim() {
// Same as `test_eth_transfer_charging_gas_not_enough_balance` but run through `near-sdk-sim`.
#[test]
fn test_eth_transfer_charging_gas_not_enough_balance_sim() {
use near_primitives::{errors::TxExecutionError, transaction::ExecutionStatus};

let (aurora, mut signer, address) = initialize_evm_sim();

// Run transaction which will fail (not enough balance to cover gas)
Expand All @@ -1009,13 +1007,17 @@ fn test_eth_transfer_charging_gas_not_enough_balance_sim() {
&signer.secret_key,
);
let call_result = aurora.call("submit", rlp::encode(&signed_tx).as_ref());
let result: SubmitResult = call_result.unwrap_borsh();
assert_eq!(result.status, TransactionStatus::OutOfFund);
let outcome = call_result.outcome();
assert!(matches!(
&outcome.status,
ExecutionStatus::Failure(
TxExecutionError::ActionError(e)) if e.to_string().contains("ERR_OUT_OF_FUND")
));

// validate post-state
assert_eq!(
query_address_sim(&address, "get_nonce", &aurora),
U256::from(INITIAL_NONCE + 1),
INITIAL_NONCE.into(), // nonce hasn't been changed because an error occurs
);
assert_eq!(
query_address_sim(&address, "get_balance", &aurora),
Expand Down
12 changes: 6 additions & 6 deletions engine-tests/src/tests/standalone/json_snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ fn test_consume_snapshot() {
// check accounts to see they were written properly
runner.env.block_height = snapshot.result.block_height + 1;
for entry in snapshot.result.values {
let key = base64::decode(entry.key).unwrap();
let value = base64::decode(entry.value).unwrap();
let key = aurora_engine_sdk::base64::decode(entry.key).unwrap();
let value = aurora_engine_sdk::base64::decode(entry.value).unwrap();
if key.as_slice().starts_with(&NONCE_PREFIX) {
let address = address_from_key(&key);
let nonce = U256::from_big_endian(&value);
Expand Down Expand Up @@ -80,8 +80,8 @@ fn test_produce_snapshot() {

// Computed snapshot should exactly the same keys from initial snapshot
for entry in snapshot.result.values.iter() {
let key = base64::decode(&entry.key).unwrap();
let value = base64::decode(&entry.value).unwrap();
let key = aurora_engine_sdk::base64::decode(&entry.key).unwrap();
let value = aurora_engine_sdk::base64::decode(&entry.value).unwrap();
assert_eq!(computed_snapshot.remove(&key).unwrap(), value);
}
assert!(computed_snapshot.is_empty());
Expand All @@ -94,12 +94,12 @@ fn test_produce_snapshot() {

// New snapshot should still contain all keys from initial snapshot
for entry in snapshot.result.values {
let key = base64::decode(entry.key).unwrap();
let key = aurora_engine_sdk::base64::decode(entry.key).unwrap();
// skip the eth-connector keys; they were changed by minting the new account
if key[0..3] == [7, 6, 1] {
continue;
}
let value = base64::decode(entry.value).unwrap();
let value = aurora_engine_sdk::base64::decode(entry.value).unwrap();
assert_eq!(computed_snapshot.get(&key).unwrap(), &value);
}

Expand Down
3 changes: 1 addition & 2 deletions engine/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ aurora-engine-types = { path = "../engine-types", default-features = false }
aurora-engine-sdk = { path = "../engine-sdk", default-features = false }
aurora-engine-precompiles = { path = "../engine-precompiles", default-features = false }
aurora-engine-transactions = { path = "../engine-transactions", default-features = false }
base64 = { version = "0.13.0", default-features = false, features = ["alloc"] }
bitflags = { version = "1.3", default-features = false }
borsh = { version = "0.9.3", default-features = false }
byte-slice-cast = { version = "1.0", default-features = false }
Expand All @@ -42,7 +41,7 @@ digest = "0.10"

[features]
default = ["std"]
std = ["aurora-engine-types/std", "aurora-engine-sdk/std", "aurora-engine-precompiles/std", "aurora-engine-transactions/std", "base64/std", "borsh/std", "byte-slice-cast/std", "ethabi/std", "evm/std", "hex/std", "rjson/std", "rlp/std"]
std = ["aurora-engine-types/std", "aurora-engine-sdk/std", "aurora-engine-precompiles/std", "aurora-engine-transactions/std", "borsh/std", "byte-slice-cast/std", "ethabi/std", "evm/std", "hex/std", "rjson/std", "rlp/std"]
contract = ["aurora-engine-sdk/contract", "aurora-engine-precompiles/contract"]
evm_bully = []
log = ["aurora-engine-sdk/log", "aurora-engine-precompiles/log"]
Expand Down
29 changes: 3 additions & 26 deletions engine/src/engine.rs
Original file line number Diff line number Diff line change
Expand Up @@ -110,13 +110,6 @@ pub enum EngineErrorKind {
}

impl EngineErrorKind {
pub fn with_gas_used(self, gas_used: u64) -> EngineError {
EngineError {
kind: self,
gas_used,
}
}

pub fn as_bytes(&self) -> &[u8] {
use EngineErrorKind::*;
match self {
Expand Down Expand Up @@ -509,13 +502,7 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
};

let used_gas = executor.used_gas();
let status = match exit_reason.into_result(result) {
Ok(status) => status,
Err(e) => {
increment_nonce(&mut self.io, &origin);
return Err(e.with_gas_used(used_gas));
}
};
let status = exit_reason.into_result(result)?;

let (values, logs) = executor.into_state().deconstruct();
let logs = apply_actions_from_logs(&mut self.io, handler, logs, &self.current_account_id);
Expand Down Expand Up @@ -590,13 +577,7 @@ impl<'env, I: IO + Copy, E: Env> Engine<'env, I, E> {
);

let used_gas = executor.used_gas();
let status = match exit_reason.into_result(result) {
Ok(status) => status,
Err(e) => {
increment_nonce(&mut self.io, origin);
return Err(e.with_gas_used(used_gas));
}
};
let status = exit_reason.into_result(result)?;

let (values, logs) = executor.into_state().deconstruct();
let logs = apply_actions_from_logs(&mut self.io, handler, logs, &self.current_account_id);
Expand Down Expand Up @@ -923,11 +904,6 @@ pub fn submit<I: IO + Copy, E: Env, P: PromiseHandler>(
// TODO: Have GasToken derived from storage.
let prepaid_amount = match engine.charge_gas(&sender, &transaction, GasToken::Base) {
Ok(gas_result) => gas_result,
Err(GasPaymentError::OutOfFund) => {
increment_nonce(&mut io, &sender);
let result = SubmitResult::new(TransactionStatus::OutOfFund, 0, vec![]);
return Ok(result);
}
Err(err) => {
return Err(EngineErrorKind::GasPayment(err).into());
}
Expand Down Expand Up @@ -1261,6 +1237,7 @@ pub fn get_nonce<I: IO>(io: &I, address: &Address) -> U256 {
.unwrap_or_else(|_| U256::zero())
}

#[cfg(test)]
pub fn increment_nonce<I: IO>(io: &mut I, address: &Address) {
let account_nonce = get_nonce(io, address);
let new_nonce = account_nonce.saturating_add(U256::one());
Expand Down
Loading

0 comments on commit 2ff79be

Please sign in to comment.