Skip to content

Commit

Permalink
fix: update vm and derive to 1.5.0 for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
loloicci committed Feb 9, 2024
1 parent a179310 commit 6a2929b
Show file tree
Hide file tree
Showing 9 changed files with 69 additions and 30 deletions.
4 changes: 2 additions & 2 deletions packages/derive/src/callable_point.rs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ pub fn make_callable_point(function: syn::ItemFn) -> (TokenStream, (String, bool
#[no_mangle]
extern "C" fn #function_name_ident(#(#renamed_param_defs),*) #typed_return {
#(let #vec_arg_idents: Vec<u8> = unsafe { cosmwasm_std::memory::consume_region(#ptr_idents as *mut cosmwasm_std::memory::Region)};)*
#(let #arg_idents: #arg_types = cosmwasm_std::from_slice(&#vec_arg_idents).unwrap();)*
#(let #arg_idents: #arg_types = cosmwasm_std::from_json(&#vec_arg_idents).unwrap();)*

#deps_def;

Expand Down Expand Up @@ -131,7 +131,7 @@ fn make_call_origin_and_return(
if has_return_value(return_type) {
quote! {
let result = #call_func;
let vec_result = cosmwasm_std::to_vec(&result).unwrap();
let vec_result = cosmwasm_std::to_json_vec(&result).unwrap();
cosmwasm_std::memory::release_buffer(vec_result) as u32
}
} else {
Expand Down
10 changes: 5 additions & 5 deletions packages/vm/benches/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use tempfile::TempDir;

use cosmwasm_std::{coins, Addr, Empty};
use cosmwasm_vm::testing::{
mock_backend, mock_env, mock_info, mock_instance, mock_instance_options, MockApi,
get_fe_mut, mock_backend, mock_env, mock_info, mock_instance, mock_instance_options, MockApi,
MockInstanceOptions, MockQuerier, MockStorage,
};
use cosmwasm_vm::{
Expand Down Expand Up @@ -318,7 +318,7 @@ fn prepare_dynamic_call_data<A: BackendApi + 'static>(
func_info: FunctionMetadata,
caller_instance: &mut Instance<A, MockStorage, MockQuerier>,
) -> u32 {
let mut fe_mut = caller_instance.get_fe_mut();
let mut fe_mut = get_fe_mut(caller_instance);
let (caller_env, mut caller_store) = fe_mut.data_and_store_mut();

let data = to_vec(&callee_address).unwrap();
Expand Down Expand Up @@ -371,7 +371,7 @@ fn bench_dynamic_link(c: &mut Criterion) {

b.iter(|| {
let _ = native_dynamic_link_trampoline_for_bench::<DummyApi, MockStorage, MockQuerier>(
dummy_instance.get_fe_mut(),
get_fe_mut(&mut dummy_instance),
&[Value::I32(address_region as i32)],
)
.unwrap();
Expand All @@ -390,7 +390,7 @@ fn bench_copy_region(c: &mut Criterion) {
let data: Vec<u8> = (0..length).map(|x| (x % 255) as u8).collect();
assert_eq!(data.len(), length as usize);
let mut instance = mock_instance(&CONTRACT, &[]);
let mut fe_mut = instance.get_fe_mut();
let mut fe_mut = get_fe_mut(&mut instance);
let (env, mut store) = fe_mut.data_and_store_mut();

let result = env
Expand All @@ -413,7 +413,7 @@ fn bench_copy_region(c: &mut Criterion) {
let data: Vec<u8> = (0..length).map(|x| (x % 255) as u8).collect();
assert_eq!(data.len(), length as usize);
let mut instance = mock_instance(&CONTRACT, &[]);
let mut fe_mut = instance.get_fe_mut();
let mut fe_mut = get_fe_mut(&mut instance);
let (env, mut store) = fe_mut.data_and_store_mut();

let result = env
Expand Down
15 changes: 9 additions & 6 deletions packages/vm/src/compatibility.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,12 +201,15 @@ fn check_wasm_imports(module: &ParsedWasm, supported_imports: &[&str]) -> VmResu
for required_import in &module.imports {
let full_name = full_import_name(required_import);
if !supported_imports.contains(&full_name.as_str()) {
let required_import_names: BTreeSet<_> =
module.imports.iter().map(full_import_name).collect();
return Err(VmError::static_validation_err(format!(
"Wasm contract requires unsupported import: \"{}\". Required imports: {}. Available imports: {:?}.",
full_name, required_import_names.to_string_limited(200), supported_imports
)));
let split_name: Vec<&str> = full_name.split('.').collect();
if split_name.len() != 2 || !split_name[0].starts_with("dynamiclinked_") {
let required_import_names: BTreeSet<_> =
module.imports.iter().map(full_import_name).collect();
return Err(VmError::static_validation_err(format!(
"Wasm contract requires unsupported import: \"{}\". Required imports: {}. Available imports: {:?}.",
full_name, required_import_names.to_string_limited(200), supported_imports
)));
}
}

match required_import.ty {
Expand Down
7 changes: 2 additions & 5 deletions packages/vm/src/dynamic_link.rs
Original file line number Diff line number Diff line change
Expand Up @@ -287,11 +287,8 @@ where
let contract_addr_raw = read_region(&env.memory(&store), address, MAX_ADDRESS_LENGTH)?;
let contract_addr: Addr = from_slice(&contract_addr_raw, MAX_ADDRESS_LENGTH)
.map_err(|_| RuntimeError::new("Invalid contract address to validate interface"))?;
let expected_interface_binary = read_region(
&env.memory(&store),
interface,
MAX_INTERFACE_REGIONS_LENGTH,
)?;
let expected_interface_binary =
read_region(&env.memory(&store), interface, MAX_INTERFACE_REGIONS_LENGTH)?;
let (result_data, gas_info) = env
.api
.validate_dynamic_link_interface(contract_addr.as_str(), &expected_interface_binary);
Expand Down
7 changes: 2 additions & 5 deletions packages/vm/src/imports.rs
Original file line number Diff line number Diff line change
Expand Up @@ -563,11 +563,8 @@ pub fn do_add_attributes<A: BackendApi + 'static, S: Storage + 'static, Q: Queri
) -> VmResult<u32> {
let (env, mut store) = fe.data_and_store_mut();

let attributes_data = read_region(
&env.memory(&store),
attributes_ptr,
MAX_LENGTH_EVENT_VALUES,
)?;
let attributes_data =
read_region(&env.memory(&store), attributes_ptr, MAX_LENGTH_EVENT_VALUES)?;
let attributes: Vec<Attribute> = match from_slice(&attributes_data, MAX_LENGTH_EVENT_VALUES) {
Ok(attributes) => attributes,
Err(_) => return write_to_contract(env, &mut store, b"Input is not valid Vec<Attribute>"),
Expand Down
5 changes: 2 additions & 3 deletions packages/vm/src/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,7 @@ where
}

/// Calls a function exported by the instance.
pub fn call_function(&mut self, name: &str, args: &[Value]) -> VmResult<Box<[Value]>> {
pub(crate) fn call_function(&mut self, name: &str, args: &[Value]) -> VmResult<Box<[Value]>> {
let mut fe_mut = self.fe.clone().into_mut(&mut self.store);
let (env, mut store) = fe_mut.data_and_store_mut();

Expand Down Expand Up @@ -549,8 +549,7 @@ where
env.set_serialized_env(serialized_env)
}

#[cfg(feature = "bench")]
pub fn get_fe_mut(&mut self) -> wasmer::FunctionEnvMut<Environment<A, S, Q>> {
pub(crate) fn get_fe_mut(&mut self) -> wasmer::FunctionEnvMut<Environment<A, S, Q>> {
self.fe.clone().into_mut(&mut self.store)
}
}
Expand Down
22 changes: 19 additions & 3 deletions packages/vm/src/testing/contract.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ pub struct Contract {
engine: Engine,
module: Module,
storage: MockStorage,
serialized_env: Vec<u8>,
}

/// representing a contract in integration test
Expand All @@ -32,6 +33,7 @@ pub struct Contract {
impl Contract {
pub fn from_code(
wasm: &[u8],
serialized_env: &[u8],
options: &MockInstanceOptions,
memory_limit: Option<Size>,
) -> TestingResult<Self> {
Expand All @@ -43,6 +45,7 @@ impl Contract {
engine,
module,
storage,
serialized_env: serialized_env.to_vec(),
};
Ok(contract)
}
Expand Down Expand Up @@ -81,7 +84,7 @@ impl Contract {
querier,
};
let store = Store::new(self.engine.clone());
let instance = Instance::from_module(
let mut instance = Instance::from_module(
store,
&self.module,
backend,
Expand All @@ -90,6 +93,7 @@ impl Contract {
None,
None,
)?;
instance.set_serialized_env(&self.serialized_env);
Ok(instance)
}

Expand All @@ -111,6 +115,11 @@ impl Contract {
pub fn raw_get(&self, key: &[u8]) -> Option<Vec<u8>> {
self.storage.get(key).0.unwrap()
}

/// get clone module
pub fn module(&self) -> Module {
self.module.clone()
}
}

#[cfg(test)]
Expand All @@ -119,7 +128,7 @@ mod test {
use super::*;
use crate::calls::{call_execute, call_instantiate, call_migrate, call_query};
use crate::testing::{mock_env, mock_info, MockInstanceOptions};
use cosmwasm_std::{QueryResponse, Response};
use cosmwasm_std::{to_json_vec, QueryResponse, Response};

static CONTRACT_WITHOUT_MIGRATE: &[u8] =
include_bytes!("../../testdata/queue_1.4.0_without_migrate.wasm");
Expand All @@ -131,12 +140,19 @@ mod test {
let options = MockInstanceOptions::default();
let api = MockApi::default();
let querier = MockQuerier::new(&[]);
let mut contract = Contract::from_code(CONTRACT_WITHOUT_MIGRATE, &options, None).unwrap();

// common env/info
let env = mock_env();
let info = mock_info("sender", &[]);

let mut contract = Contract::from_code(
CONTRACT_WITHOUT_MIGRATE,
&to_json_vec(&env).unwrap(),
&options,
None,
)
.unwrap();

// init
let mut instance = contract.generate_instance(api, querier, &options).unwrap();
let msg = "{}".as_bytes();
Expand Down
27 changes: 27 additions & 0 deletions packages/vm/src/testing/instance.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
//! use cosmwasm_vm::testing::X
use cosmwasm_std::Coin;
use std::collections::HashSet;
use wasmer::Value;

use crate::capabilities::capabilities_from_csv;
use crate::compatibility::check_wasm;
use crate::environment::Environment;
use crate::instance::{Instance, InstanceOptions};
use crate::size::Size;
use crate::VmResult;
use crate::{Backend, BackendApi, Querier, Storage};

use super::mock::{MockApi, MOCK_CONTRACT_ADDR};
Expand Down Expand Up @@ -202,3 +205,27 @@ where
}
}
}

pub fn call_function<A, S, Q>(
instance: &mut Instance<A, S, Q>,
name: &str,
args: &[Value],
) -> VmResult<Box<[Value]>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.call_function(name, args)
}

pub fn get_fe_mut<A, S, Q>(
instance: &mut Instance<A, S, Q>,
) -> wasmer::FunctionEnvMut<Environment<A, S, Q>>
where
A: BackendApi + 'static,
S: Storage + 'static,
Q: Querier + 'static,
{
instance.get_fe_mut()
}
2 changes: 1 addition & 1 deletion packages/vm/src/testing/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub use calls::{
};
pub use contract::Contract;
pub use instance::{
mock_instance, mock_instance_options, mock_instance_with_balances,
call_function, get_fe_mut, mock_instance, mock_instance_options, mock_instance_with_balances,
mock_instance_with_failing_api, mock_instance_with_gas_limit, mock_instance_with_options,
test_io, MockInstanceOptions,
};
Expand Down

0 comments on commit 6a2929b

Please sign in to comment.