From 9ce0cdce0b04e0738f88bd6b082d035987058885 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?dj8yf0=CE=BCl?= <26653921+dj8yfo@users.noreply.github.com> Date: Tue, 16 Jan 2024 21:54:58 +0200 Subject: [PATCH] chore!: update `nearcore` crates from `0.17` -> `0.20` (#1130) --- .github/workflows/test.yml | 11 +- README.md | 4 +- near-sdk/Cargo.toml | 14 +- near-sdk/src/environment/env.rs | 4 +- near-sdk/src/environment/mock/external.rs | 88 ---------- .../src/environment/mock/mocked_blockchain.rs | 141 +++++++--------- .../src/environment/mock/mocked_memory.rs | 2 +- near-sdk/src/environment/mock/mod.rs | 6 +- near-sdk/src/environment/mock/receipt.rs | 156 +++++++++++++++--- near-sdk/src/lib.rs | 4 +- near-sdk/src/promise.rs | 20 ++- near-sdk/src/test_utils/context.rs | 8 +- near-sdk/src/test_utils/mod.rs | 14 +- near-sdk/src/test_utils/test_env.rs | 8 +- near-sdk/src/types/primitives.rs | 2 +- near-sdk/src/types/public_key.rs | 34 ++++ near-sdk/src/types/vm_types.rs | 2 +- 17 files changed, 277 insertions(+), 241 deletions(-) delete mode 100644 near-sdk/src/environment/mock/external.rs diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index eab7d4661..96063203c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -13,7 +13,7 @@ jobs: strategy: matrix: platform: [ubuntu-latest, macos-latest] - toolchain: [stable, 1.69.0] + toolchain: [stable, 1.72.1] steps: - uses: actions/checkout@v3 - name: "${{ matrix.toolchain }} with rustfmt, and wasm32" @@ -23,15 +23,6 @@ jobs: toolchain: ${{ matrix.toolchain }} default: true target: wasm32-unknown-unknown - - name: downgrade `anstyle`,`anstyle-parse`,`anstyle-query`,`clap`,`clap_lex`, `home` crates to support older Rust toolchain - if: matrix.toolchain == '1.69.0' - run: | - cargo update -p anstyle --precise 1.0.2 - cargo update -p anstyle-query --precise 1.0.0 - cargo update -p anstyle-parse --precise 0.2.1 - cargo update -p clap --precise 4.3.24 - cargo update -p clap_lex --precise 0.5.0 - cargo update -p home --precise 0.5.5 - uses: Swatinem/rust-cache@v1 - name: Test run: cargo test --all --features unstable,legacy diff --git a/README.md b/README.md index 4e58b8e86..7cc43c6e6 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Crates.io version Download Reference Documentation - MSRV + MSRV Join the community on Discord GitHub Actions Build

@@ -260,7 +260,7 @@ State breaking changes (low-level serialization format of any data type) will be ### MSRV -The minimum supported Rust version is currently `1.69`. There are no guarantees that this will be upheld if a security patch release needs to come in that requires a Rust toolchain increase. +The minimum supported Rust version is currently `1.72`. There are no guarantees that this will be upheld if a security patch release needs to come in that requires a Rust toolchain increase. ## Contributing diff --git a/near-sdk/Cargo.toml b/near-sdk/Cargo.toml index d7fc4c5a1..a0ad45499 100644 --- a/near-sdk/Cargo.toml +++ b/near-sdk/Cargo.toml @@ -34,15 +34,17 @@ wee_alloc = { version = "0.4.5", default-features = false, optional = true } once_cell = { version = "1.17", default-features = false } near-abi = { version = "0.4.0", features = ["__chunked-entries"], optional = true } -near-account-id = { version="1.0.0-alpha.4", features = ["serde", "borsh"] } +near-account-id = { version="1.0.0", features = ["serde", "borsh"] } near-gas = { version = "0.2.3", features = ["serde", "borsh"] } near-token = { version = "0.2.0", features = ["serde", "borsh"] } + [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -near-vm-logic = { version = "0.17", optional = true } -near-primitives-core = { version = "0.17", optional = true } -near-primitives = { version = "0.17", optional = true } -near-crypto = { version = "0.17", optional = true } +near-vm-runner = { version = "0.20", optional = true } +near-primitives-core = { version = "0.20", optional = true } +near-primitives = { version = "0.20", optional = true } +near-crypto = { version = "0.20", optional = true } +near-parameters = { version = "0.20", optional = true } [dev-dependencies] rand = "0.8.4" @@ -63,7 +65,7 @@ expensive-debug = [] unstable = [] legacy = [] abi = ["borsh/unstable__schema", "near-abi", "schemars", "near-sdk-macros/abi", "near-account-id/abi", "near-gas/abi", "near-token/abi"] -unit-testing = ["near-vm-logic", "near-primitives-core", "near-primitives", "near-crypto"] +unit-testing = ["near-vm-runner", "near-primitives-core", "near-primitives", "near-crypto", "near-parameters"] __abi-embed = ["near-sdk-macros/__abi-embed"] __abi-generate = ["abi", "near-sdk-macros/__abi-generate"] diff --git a/near-sdk/src/environment/env.rs b/near-sdk/src/environment/env.rs index ea1e236a4..1e89fe9ad 100644 --- a/near-sdk/src/environment/env.rs +++ b/near-sdk/src/environment/env.rs @@ -79,9 +79,9 @@ pub(crate) unsafe fn read_register_fixed_64(register_id: u64) -> [u8; 64] { /// low-level blockchain interfacr that implements `BlockchainInterface` trait. In most cases you /// want to use `testing_env!` macro to set it. /// -/// ```no_run +/// ``` /// # let context = near_sdk::test_utils::VMContextBuilder::new().build(); -/// # let vm_config = near_sdk::VMConfig::test(); +/// # let vm_config = near_sdk::test_vm_config(); /// # let fees_config = near_sdk::RuntimeFeesConfig::test(); /// # let storage = Default::default(); /// # let validators = Default::default(); diff --git a/near-sdk/src/environment/mock/external.rs b/near-sdk/src/environment/mock/external.rs deleted file mode 100644 index 79a8802ce..000000000 --- a/near-sdk/src/environment/mock/external.rs +++ /dev/null @@ -1,88 +0,0 @@ -use near_primitives::types::TrieNodesCount; -use near_primitives_core::hash::{hash, CryptoHash}; -use near_primitives_core::types::{AccountId, Balance}; -use near_vm_logic::{External, StorageGetMode, ValuePtr}; -use std::collections::HashMap; - -type Result = ::core::result::Result; - -#[derive(Default, Clone)] -/// Emulates the trie and the mock handling code for the SDK. This is a modified version of -/// `MockedExternal` from `near_vm_logic`. -pub(crate) struct SdkExternal { - pub fake_trie: HashMap, Vec>, - pub validators: HashMap, - data_count: u64, -} - -pub struct MockedValuePtr { - value: Vec, -} - -impl ValuePtr for MockedValuePtr { - fn len(&self) -> u32 { - self.value.len() as u32 - } - - fn deref(&self) -> Result> { - Ok(self.value.clone()) - } -} - -impl SdkExternal { - pub fn new() -> Self { - Self::default() - } -} - -impl External for SdkExternal { - fn storage_set(&mut self, key: &[u8], value: &[u8]) -> Result<()> { - self.fake_trie.insert(key.to_vec(), value.to_vec()); - Ok(()) - } - - fn storage_get( - &self, - key: &[u8], - _storage_get_mode: StorageGetMode, - ) -> Result>> { - Ok(self - .fake_trie - .get(key) - .map(|value| Box::new(MockedValuePtr { value: value.clone() }) as Box<_>)) - } - - fn storage_remove(&mut self, key: &[u8]) -> Result<()> { - self.fake_trie.remove(key); - Ok(()) - } - - fn storage_remove_subtree(&mut self, prefix: &[u8]) -> Result<()> { - self.fake_trie.retain(|key, _| !key.starts_with(prefix)); - Ok(()) - } - - fn storage_has_key(&mut self, key: &[u8], _mode: StorageGetMode) -> Result { - Ok(self.fake_trie.contains_key(key)) - } - - fn generate_data_id(&mut self) -> CryptoHash { - // Generates some hash for the data ID to receive data. This hash should not be functionally - // used in any mocked contexts. - let data_id = hash(&self.data_count.to_le_bytes()); - self.data_count += 1; - data_id - } - - fn get_trie_nodes_count(&self) -> TrieNodesCount { - TrieNodesCount { db_reads: 0, mem_reads: 0 } - } - - fn validator_stake(&self, account_id: &AccountId) -> Result> { - Ok(self.validators.get(account_id).cloned()) - } - - fn validator_total_stake(&self) -> Result { - Ok(self.validators.values().sum()) - } -} diff --git a/near-sdk/src/environment/mock/mocked_blockchain.rs b/near-sdk/src/environment/mock/mocked_blockchain.rs index b1e2a7f62..9ede0f5b3 100644 --- a/near-sdk/src/environment/mock/mocked_blockchain.rs +++ b/near-sdk/src/environment/mock/mocked_blockchain.rs @@ -1,15 +1,15 @@ -use super::{Receipt, SdkExternal}; +use super::Receipt; +use crate::mock::MockAction; // TODO replace with near_vm_logic::mocks::mock_memory::MockedMemory after updating version from 0.17 use crate::mock::mocked_memory::MockedMemory; -use crate::mock::VmAction; use crate::test_utils::VMContextBuilder; use crate::types::{NearToken, PromiseResult}; -use crate::{CurveType, Gas, RuntimeFeesConfig}; -use crate::{PublicKey, VMContext}; -use near_crypto::PublicKey as VmPublicKey; -use near_primitives::transaction::Action as PrimitivesAction; -use near_vm_logic::types::PromiseResult as VmPromiseResult; -use near_vm_logic::{External, MemoryLike, VMConfig, VMLogic}; +use crate::VMContext; +use near_parameters::{RuntimeConfigStore, RuntimeFeesConfig}; +use near_primitives_core::version::PROTOCOL_VERSION; +use near_vm_runner::logic::mocks::mock_external::MockedExternal; +use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReceiptIndex}; +use near_vm_runner::logic::{External, MemoryLike, VMLogic}; use std::cell::RefCell; use std::collections::HashMap; @@ -25,11 +25,20 @@ pub struct MockedBlockchain { logic_fixture: LogicFixture, } +pub fn test_vm_config() -> near_parameters::vm::Config { + let store = RuntimeConfigStore::test(); + let config = store.get_config(PROTOCOL_VERSION).wasm_config.clone(); + near_parameters::vm::Config { + vm_kind: config.vm_kind.replace_with_wasmtime_if_unsupported(), + ..config + } +} + impl Default for MockedBlockchain { fn default() -> Self { MockedBlockchain::new( VMContextBuilder::new().build(), - VMConfig::test(), + test_vm_config(), RuntimeFeesConfig::test(), vec![], Default::default(), @@ -40,25 +49,25 @@ impl Default for MockedBlockchain { } struct LogicFixture { - ext: Box, + ext: Box, memory: Box, #[allow(clippy::box_collection)] promise_results: Box>, - config: Box, + config: Box, fees_config: Box, } impl MockedBlockchain { pub fn new( context: VMContext, - config: VMConfig, + config: near_parameters::vm::Config, fees_config: RuntimeFeesConfig, promise_results: Vec, storage: HashMap, Vec>, validators: HashMap, memory_opt: Option>, ) -> Self { - let mut ext = Box::new(SdkExternal::new()); + let mut ext = Box::new(MockedExternal::new()); let context = sdk_context_to_vm_context(context); ext.fake_trie = storage; ext.validators = @@ -71,14 +80,13 @@ impl MockedBlockchain { let mut logic_fixture = LogicFixture { ext, memory, promise_results, config, fees_config }; let logic = unsafe { - VMLogic::new_with_protocol_version( + VMLogic::new( &mut *(logic_fixture.ext.as_mut() as *mut dyn External), context, - &*(logic_fixture.config.as_mut() as *const VMConfig), + &*(logic_fixture.config.as_mut() as *const near_parameters::vm::Config), &*(logic_fixture.fees_config.as_mut() as *const RuntimeFeesConfig), &*(logic_fixture.promise_results.as_ref().as_slice() as *const [VmPromiseResult]), &mut *(logic_fixture.memory.as_mut() as *mut dyn MemoryLike), - u32::MAX, ) }; @@ -92,15 +100,39 @@ impl MockedBlockchain { /// Returns metadata about the receipts created pub fn created_receipts(&self) -> Vec { - self.logic - .borrow() - .action_receipts() - .iter() - .map(|(receiver, receipt)| { - let actions = receipt.actions.iter().map(action_to_sdk_action).collect(); - Receipt { receiver_id: receiver.as_str().parse().unwrap(), actions } + let action_log = &self.logic_fixture.ext.action_log; + let action_log: Vec = + action_log.clone().into_iter().map(>::from).collect(); + let create_receipts: Vec<(usize, MockAction)> = action_log + .clone() + .into_iter() + .enumerate() + .filter(|(_receipt_idx, action)| matches!(action, MockAction::CreateReceipt { .. })) + .collect(); + + let result = create_receipts + .into_iter() + .map(|(receipt_idx, create_receipt)| { + let (receiver_id, receipt_indices) = match create_receipt { + MockAction::CreateReceipt { receiver_id, receipt_indices } => { + (receiver_id, receipt_indices) + } + _ => panic!("not a CreateReceipt action!"), + }; + let actions: Vec = action_log + .iter() + .filter(|action| match action.receipt_index() { + None => false, + Some(action_receipt_idx) => { + action_receipt_idx == (receipt_idx as ReceiptIndex) + } + }) + .cloned() + .collect(); + Receipt { receiver_id, actions, receipt_indices } }) - .collect() + .collect(); + result } pub fn gas(&mut self, gas_amount: u32) { @@ -113,8 +145,8 @@ impl MockedBlockchain { } } -fn sdk_context_to_vm_context(context: VMContext) -> near_vm_logic::VMContext { - near_vm_logic::VMContext { +fn sdk_context_to_vm_context(context: VMContext) -> near_vm_runner::logic::VMContext { + near_vm_runner::logic::VMContext { current_account_id: context.current_account_id.as_str().parse().unwrap(), signer_account_id: context.signer_account_id.as_str().parse().unwrap(), signer_account_pk: context.signer_account_pk.into_bytes(), @@ -138,64 +170,9 @@ fn sdk_context_to_vm_context(context: VMContext) -> near_vm_logic::VMContext { } } -fn action_to_sdk_action(action: &PrimitivesAction) -> VmAction { - match action { - PrimitivesAction::CreateAccount(_) => VmAction::CreateAccount, - PrimitivesAction::DeployContract(c) => VmAction::DeployContract { code: c.code.clone() }, - PrimitivesAction::FunctionCall(f) => VmAction::FunctionCall { - function_name: f.method_name.clone(), - args: f.args.clone(), - gas: Gas::from_gas(f.gas), - deposit: NearToken::from_yoctonear(f.deposit), - }, - PrimitivesAction::Transfer(t) => { - VmAction::Transfer { deposit: NearToken::from_yoctonear(t.deposit) } - } - PrimitivesAction::Stake(s) => VmAction::Stake { - stake: NearToken::from_yoctonear(s.stake), - public_key: pub_key_conversion(&s.public_key), - }, - PrimitivesAction::AddKey(k) => match &k.access_key.permission { - near_primitives::account::AccessKeyPermission::FunctionCall(f) => { - VmAction::AddKeyWithFunctionCall { - public_key: pub_key_conversion(&k.public_key), - nonce: k.access_key.nonce, - allowance: f.allowance.map(NearToken::from_yoctonear), - receiver_id: f.receiver_id.parse().unwrap(), - function_names: f.method_names.clone(), - } - } - near_primitives::account::AccessKeyPermission::FullAccess => { - VmAction::AddKeyWithFullAccess { - public_key: pub_key_conversion(&k.public_key), - nonce: k.access_key.nonce, - } - } - }, - PrimitivesAction::DeleteKey(k) => { - VmAction::DeleteKey { public_key: pub_key_conversion(&k.public_key) } - } - PrimitivesAction::DeleteAccount(a) => { - VmAction::DeleteAccount { beneficiary_id: a.beneficiary_id.parse().unwrap() } - } - PrimitivesAction::Delegate(_d) => { - panic!("Unimplemented") - } - } -} - -fn pub_key_conversion(key: &VmPublicKey) -> PublicKey { - let curve_type = match key.key_type() { - near_crypto::KeyType::ED25519 => CurveType::ED25519, - near_crypto::KeyType::SECP256K1 => CurveType::SECP256K1, - }; - PublicKey::from_parts(curve_type, key.key_data().to_vec()).unwrap() -} - #[cfg(not(target_arch = "wasm32"))] mod mock_chain { - use near_vm_logic::{VMLogic, VMLogicError}; - + use near_vm_runner::logic::{errors::VMLogicError, VMLogic}; fn with_mock_interface(f: F) -> R where F: FnOnce(&mut VMLogic) -> Result, diff --git a/near-sdk/src/environment/mock/mocked_memory.rs b/near-sdk/src/environment/mock/mocked_memory.rs index 96f2a0011..a949722e3 100644 --- a/near-sdk/src/environment/mock/mocked_memory.rs +++ b/near-sdk/src/environment/mock/mocked_memory.rs @@ -1,5 +1,5 @@ //!This file is to be removed once near-vm-logic is updated from version 0.17 and MockedMemory size can be customized -use near_vm_logic::{MemSlice, MemoryLike}; +use near_vm_runner::logic::{MemSlice, MemoryLike}; #[derive(Default)] pub struct MockedMemory {} diff --git a/near-sdk/src/environment/mock/mod.rs b/near-sdk/src/environment/mock/mod.rs index 948030cb2..b9cd6b2df 100644 --- a/near-sdk/src/environment/mock/mod.rs +++ b/near-sdk/src/environment/mock/mod.rs @@ -1,11 +1,11 @@ -mod external; mod mocked_blockchain; mod mocked_memory; mod receipt; -pub(crate) use self::external::SdkExternal; +pub use mocked_blockchain::test_vm_config; + pub use self::mocked_blockchain::MockedBlockchain; -pub use self::receipt::{Receipt, VmAction}; +pub use self::receipt::{MockAction, Receipt}; use core::cell::RefCell; thread_local! { diff --git a/near-sdk/src/environment/mock/receipt.rs b/near-sdk/src/environment/mock/receipt.rs index 3ac37cf8a..a41cc2c5b 100644 --- a/near-sdk/src/environment/mock/receipt.rs +++ b/near-sdk/src/environment/mock/receipt.rs @@ -1,47 +1,161 @@ -use crate::{AccountId, Gas, NearToken, PublicKey}; +use near_primitives_core::types::GasWeight; +use near_vm_runner::logic::mocks::mock_external::MockAction as LogicMockAction; +use near_vm_runner::logic::types::ReceiptIndex; + +use crate::{AccountId, Gas, NearToken}; #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] pub struct Receipt { pub receiver_id: AccountId, - pub actions: Vec, + pub receipt_indices: Vec, + pub actions: Vec, } -#[derive(Clone, Debug, PartialEq, Eq)] -#[non_exhaustive] -pub enum VmAction { - CreateAccount, +#[derive(serde::Serialize)] +#[serde(remote = "GasWeight")] +struct GasWeightSer(u64); + +#[derive(Debug, Clone, serde::Serialize, PartialEq, Eq)] +pub enum MockAction { + CreateReceipt { + receipt_indices: Vec, + receiver_id: AccountId, + }, + CreateAccount { + receipt_index: ReceiptIndex, + }, DeployContract { + receipt_index: ReceiptIndex, code: Vec, }, - FunctionCall { - function_name: String, + FunctionCallWeight { + receipt_index: ReceiptIndex, + method_name: Vec, args: Vec, - gas: Gas, - deposit: NearToken, + attached_deposit: NearToken, + prepaid_gas: Gas, + #[serde(with = "GasWeightSer")] + gas_weight: GasWeight, }, Transfer { + receipt_index: ReceiptIndex, deposit: NearToken, }, Stake { + receipt_index: ReceiptIndex, stake: NearToken, - public_key: PublicKey, + public_key: near_crypto::PublicKey, }, - AddKeyWithFullAccess { - public_key: PublicKey, - nonce: u64, + DeleteAccount { + receipt_index: ReceiptIndex, + beneficiary_id: AccountId, + }, + DeleteKey { + receipt_index: ReceiptIndex, + public_key: near_crypto::PublicKey, }, AddKeyWithFunctionCall { - public_key: PublicKey, + receipt_index: ReceiptIndex, + public_key: near_crypto::PublicKey, nonce: u64, allowance: Option, receiver_id: AccountId, - function_names: Vec, - }, - DeleteKey { - public_key: PublicKey, + method_names: Vec, }, - DeleteAccount { - beneficiary_id: AccountId, + AddKeyWithFullAccess { + receipt_index: ReceiptIndex, + public_key: near_crypto::PublicKey, + nonce: u64, }, } + +impl MockAction { + pub fn receipt_index(&self) -> Option { + match self { + MockAction::CreateReceipt { .. } => None, + MockAction::CreateAccount { receipt_index } => Some(*receipt_index), + MockAction::DeployContract { receipt_index, .. } => Some(*receipt_index), + MockAction::FunctionCallWeight { receipt_index, .. } => Some(*receipt_index), + MockAction::Transfer { receipt_index, .. } => Some(*receipt_index), + MockAction::Stake { receipt_index, .. } => Some(*receipt_index), + MockAction::DeleteAccount { receipt_index, .. } => Some(*receipt_index), + MockAction::DeleteKey { receipt_index, .. } => Some(*receipt_index), + MockAction::AddKeyWithFunctionCall { receipt_index, .. } => Some(*receipt_index), + Self::AddKeyWithFullAccess { receipt_index, .. } => Some(*receipt_index), + } + } +} + +fn map_vec_str(vec_str: Vec>) -> Vec { + vec_str + .into_iter() + .map(|element| { + let string: String = String::from_utf8(element).unwrap(); + string + }) + .collect() +} + +impl From for MockAction { + fn from(value: LogicMockAction) -> Self { + match value { + LogicMockAction::CreateReceipt { receipt_indices, receiver_id } => { + Self::CreateReceipt { receipt_indices, receiver_id } + } + LogicMockAction::CreateAccount { receipt_index } => { + Self::CreateAccount { receipt_index } + } + LogicMockAction::DeployContract { receipt_index, code } => { + Self::DeployContract { receipt_index, code } + } + LogicMockAction::FunctionCallWeight { + receipt_index, + method_name, + args, + attached_deposit, + prepaid_gas, + gas_weight, + } => Self::FunctionCallWeight { + receipt_index, + method_name, + args, + attached_deposit: NearToken::from_yoctonear(attached_deposit), + prepaid_gas: Gas::from_gas(prepaid_gas), + gas_weight, + }, + LogicMockAction::Transfer { receipt_index, deposit } => { + MockAction::Transfer { receipt_index, deposit: NearToken::from_yoctonear(deposit) } + } + LogicMockAction::Stake { receipt_index, stake, public_key } => MockAction::Stake { + receipt_index, + stake: NearToken::from_yoctonear(stake), + public_key, + }, + LogicMockAction::DeleteAccount { receipt_index, beneficiary_id } => { + Self::DeleteAccount { receipt_index, beneficiary_id } + } + LogicMockAction::DeleteKey { receipt_index, public_key } => { + Self::DeleteKey { receipt_index, public_key } + } + LogicMockAction::AddKeyWithFunctionCall { + receipt_index, + public_key, + nonce, + allowance, + receiver_id, + method_names, + } => Self::AddKeyWithFunctionCall { + receipt_index, + public_key, + nonce, + allowance: allowance.map(NearToken::from_yoctonear), + receiver_id, + method_names: map_vec_str(method_names), + }, + LogicMockAction::AddKeyWithFullAccess { receipt_index, public_key, nonce } => { + Self::AddKeyWithFullAccess { receipt_index, public_key, nonce } + } + } + } +} diff --git a/near-sdk/src/lib.rs b/near-sdk/src/lib.rs index 0f9beab8b..5042b7533 100644 --- a/near-sdk/src/lib.rs +++ b/near-sdk/src/lib.rs @@ -39,11 +39,11 @@ pub use crate::types::*; #[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))] pub use environment::mock; #[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))] +pub use environment::mock::test_vm_config; +#[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))] // Re-export to avoid breakages pub use environment::mock::MockedBlockchain; #[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))] -pub use near_vm_logic::VMConfig; -#[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))] pub use test_utils::context::VMContext; pub mod utils; diff --git a/near-sdk/src/promise.rs b/near-sdk/src/promise.rs index 9bc1dfc2f..4fd436ea9 100644 --- a/near-sdk/src/promise.rs +++ b/near-sdk/src/promise.rs @@ -619,7 +619,7 @@ impl schemars::JsonSchema for PromiseOrValue { #[cfg(not(target_arch = "wasm32"))] #[cfg(test)] mod tests { - use crate::mock::VmAction; + use crate::mock::MockAction; use crate::test_utils::get_created_receipts; use crate::test_utils::test_env::{alice, bob}; use crate::{ @@ -631,17 +631,18 @@ mod tests { "ed25519:6E8sCci9badyRkXb3JoRpBj5p8C6Tw41ELDZoiihKEtp".parse().unwrap() } - fn get_actions() -> std::vec::IntoIter { + fn get_actions() -> std::vec::IntoIter { let receipts = get_created_receipts(); let first_receipt = receipts.into_iter().next().unwrap(); first_receipt.actions.into_iter() } fn has_add_key_with_full_access(public_key: PublicKey, nonce: Option) -> bool { + let public_key = near_crypto::PublicKey::try_from(public_key).unwrap(); get_actions().any(|el| { matches!( el, - VmAction::AddKeyWithFullAccess { public_key: p, nonce: n } + MockAction::AddKeyWithFullAccess { public_key: p, nonce: n, receipt_index: _, } if p == public_key && (nonce.is_none() || Some(n) == nonce) ) @@ -655,20 +656,22 @@ mod tests { function_names: String, nonce: Option, ) -> bool { + let public_key = near_crypto::PublicKey::try_from(public_key).unwrap(); get_actions().any(|el| { matches!( el, - VmAction::AddKeyWithFunctionCall { + MockAction::AddKeyWithFunctionCall { public_key: p, allowance: a, receiver_id: r, - function_names: f, - nonce: n + method_names, + nonce: n, + receipt_index: _, } if p == public_key && a.unwrap() == NearToken::from_yoctonear(allowance) && r == receiver_id - && f == function_names.split(',').collect::>() + && method_names.clone() == function_names.split(',').collect::>() && (nonce.is_none() || Some(n) == nonce) ) }) @@ -831,11 +834,12 @@ mod tests { .add_full_access_key(public_key.clone()) .delete_key(public_key.clone()); } + let public_key = near_crypto::PublicKey::try_from(public_key).unwrap(); let has_action = get_actions().any(|el| { matches!( el, - VmAction::DeleteKey { public_key: p } if p == public_key + MockAction::DeleteKey { public_key: p , receipt_index: _, } if p == public_key ) }); assert!(has_action); diff --git a/near-sdk/src/test_utils/context.rs b/near-sdk/src/test_utils/context.rs index e48d6e6df..07766d6f4 100644 --- a/near-sdk/src/test_utils/context.rs +++ b/near-sdk/src/test_utils/context.rs @@ -1,9 +1,9 @@ use crate::mock::MockedBlockchain; use crate::test_utils::test_env::*; -use crate::AccountId; +use crate::{test_vm_config, AccountId}; use crate::{BlockHeight, EpochHeight, Gas, NearToken, PromiseResult, PublicKey, StorageUsage}; -use near_primitives_core::runtime::fees::RuntimeFeesConfig; -use near_vm_logic::{VMConfig, ViewConfig}; +use near_parameters::RuntimeFeesConfig; +use near_primitives_core::config::ViewConfig; use std::convert::TryInto; /// Returns a pre-defined account_id from a list of 6. @@ -194,7 +194,7 @@ pub fn testing_env_with_promise_results(context: VMContext, promise_result: Prom //? Might be a good time to remove this utility function altogether crate::env::set_blockchain_interface(MockedBlockchain::new( context, - VMConfig::test(), + test_vm_config(), RuntimeFeesConfig::test(), vec![promise_result], storage, diff --git a/near-sdk/src/test_utils/mod.rs b/near-sdk/src/test_utils/mod.rs index 08422086b..aae576724 100644 --- a/near-sdk/src/test_utils/mod.rs +++ b/near-sdk/src/test_utils/mod.rs @@ -15,7 +15,7 @@ pub use context::{accounts, testing_env_with_promise_results, VMContextBuilder}; /// [`MockedBlockchain`], in this order: /// - `context`: [`VMContext`] which contains some core information about /// the blockchain and message data which can be used from the smart contract. -/// - `config` (optional): [`VMConfig`] which contains some additional information +/// - `config` (optional): [`vm::Config`] which contains some additional information /// about the VM to configure parameters not directly related to the transaction being executed. /// - `fee_config`(optional): [`RuntimeFeesConfig`] which configures the /// fees for execution and storage of transactions. @@ -29,9 +29,9 @@ pub use context::{accounts, testing_env_with_promise_results, VMContextBuilder}; /// # Example use /// /// ``` -/// use near_sdk::testing_env; +/// use near_sdk::{testing_env, test_vm_config}; /// use near_sdk::test_utils::{accounts, VMContextBuilder}; -/// use near_sdk::{VMConfig, RuntimeFeesConfig}; +/// use near_parameters::RuntimeFeesConfig; /// use std::collections::HashMap; /// /// # fn main() { @@ -44,7 +44,7 @@ pub use context::{accounts, testing_env_with_promise_results, VMContextBuilder}; /// // Or include arguments up to the five optional /// testing_env!( /// context, -/// VMConfig::test(), +/// test_vm_config(), /// RuntimeFeesConfig::test(), /// HashMap::default(), /// Vec::default(), @@ -54,8 +54,8 @@ pub use context::{accounts, testing_env_with_promise_results, VMContextBuilder}; /// /// [`MockedBlockchain`]: crate::mock::MockedBlockchain /// [`VMContext`]: crate::VMContext -/// [`VMConfig`]: crate::VMConfig -/// [`RuntimeFeesConfig`]: crate::RuntimeFeesConfig +/// [`vm::Config`]: near_parameters::vm::Config +/// [`RuntimeFeesConfig`]: near_parameters::RuntimeFeesConfig /// [`AccountId`]: crate::AccountId /// [`Balance`]: crate::Balance /// [`PromiseResult`]: crate::PromiseResult @@ -84,7 +84,7 @@ macro_rules! testing_env { $crate::testing_env!($context, $config, $crate::RuntimeFeesConfig::test()) }; ($context:expr) => { - $crate::testing_env!($context, $crate::VMConfig::test()) + $crate::testing_env!($context, $crate::test_vm_config()) }; } diff --git a/near-sdk/src/test_utils/test_env.rs b/near-sdk/src/test_utils/test_env.rs index 338907f18..15b789fcd 100644 --- a/near-sdk/src/test_utils/test_env.rs +++ b/near-sdk/src/test_utils/test_env.rs @@ -1,5 +1,5 @@ use crate::test_utils::VMContextBuilder; -use crate::{testing_env, AccountId, VMConfig}; +use crate::{test_vm_config, testing_env, AccountId}; pub fn alice() -> AccountId { "alice.near".parse().unwrap() @@ -18,7 +18,7 @@ pub fn carol() -> AccountId { since = "4.0.0", note = "Use `testing_env!` macro to initialize with specific VMConfig" )] -pub fn setup_with_config(vm_config: VMConfig) { +pub fn setup_with_config(vm_config: near_parameters::vm::Config) { testing_env!(VMContextBuilder::new().build(), vm_config) } @@ -34,5 +34,7 @@ pub fn setup() { /// free == effectively unlimited gas /// Sets up the blockchain interface with a [`VMConfig`] which sets the gas costs to zero. pub fn setup_free() { - crate::testing_env!(VMContextBuilder::new().build(), VMConfig::free()) + let mut config = test_vm_config(); + config.make_free(); + crate::testing_env!(VMContextBuilder::new().build(), config) } diff --git a/near-sdk/src/types/primitives.rs b/near-sdk/src/types/primitives.rs index fc85056ba..363089b30 100644 --- a/near-sdk/src/types/primitives.rs +++ b/near-sdk/src/types/primitives.rs @@ -2,7 +2,7 @@ use near_primitives_core::hash::CryptoHash; #[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))] -pub use near_primitives_core::runtime::fees::RuntimeFeesConfig; +pub use near_parameters::RuntimeFeesConfig; //* Type aliases from near_primitives_core diff --git a/near-sdk/src/types/public_key.rs b/near-sdk/src/types/public_key.rs index 3266fe667..e504ae329 100644 --- a/near-sdk/src/types/public_key.rs +++ b/near-sdk/src/types/public_key.rs @@ -43,6 +43,40 @@ impl std::str::FromStr for CurveType { } } +#[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))] +#[cfg(test)] +impl TryFrom for near_crypto::PublicKey { + type Error = ParsePublicKeyError; + + fn try_from(public_key: PublicKey) -> Result { + let curve_type = CurveType::from_u8(public_key.data[0])?; + let expected_len = curve_type.data_len(); + + let key_bytes = public_key.into_bytes(); + if key_bytes.len() != expected_len + 1 { + return Err(ParsePublicKeyError { + kind: ParsePublicKeyErrorKind::InvalidLength(key_bytes.len()), + }); + } + + let data = &key_bytes.as_slice()[1..]; + match curve_type { + CurveType::ED25519 => { + let public_key = near_crypto::PublicKey::ED25519( + near_crypto::ED25519PublicKey::try_from(data).unwrap(), + ); + Ok(public_key) + } + CurveType::SECP256K1 => { + let public_key = near_crypto::PublicKey::SECP256K1( + near_crypto::Secp256K1PublicKey::try_from(data).unwrap(), + ); + Ok(public_key) + } + } + } +} + /// Public key in a binary format with base58 string serialization with human-readable curve. /// The key types currently supported are `secp256k1` and `ed25519`. /// diff --git a/near-sdk/src/types/vm_types.rs b/near-sdk/src/types/vm_types.rs index 9f6d714c4..f26fc0fb0 100644 --- a/near-sdk/src/types/vm_types.rs +++ b/near-sdk/src/types/vm_types.rs @@ -1,5 +1,5 @@ #[cfg(all(not(target_arch = "wasm32"), feature = "unit-testing"))] -pub use near_vm_logic::types::{PromiseResult as VmPromiseResult, ReturnData}; +pub use near_vm_runner::logic::types::{PromiseResult as VmPromiseResult, ReturnData}; //* Types from near_vm_logic /// Promise index that is computed only once.