From 4906890021573dad6ee324f23961ce16b938690d Mon Sep 17 00:00:00 2001 From: Bowen Wang Date: Thu, 6 Aug 2020 10:15:23 -0700 Subject: [PATCH 1/3] fix(runtime): use correct random value for random seed --- chain/chain/src/chain.rs | 5 ++++ chain/chain/src/test_utils.rs | 2 ++ chain/chain/src/types.rs | 4 +++ chain/chain/src/validate.rs | 1 + core/primitives/src/version.rs | 4 ++- neard/src/runtime.rs | 9 ++++++ pytest/tests/sanity/upgradable.py | 26 ++++++++++++++---- .../tests/res/test_contract_rs.wasm | Bin 83692 -> 83830 bytes .../tests/test-contract-rs/src/lib.rs | 9 ++++++ .../runtime-params-estimator/src/testbed.rs | 2 ++ runtime/runtime-standalone/src/lib.rs | 2 ++ runtime/runtime/src/actions.rs | 8 +++++- runtime/runtime/src/lib.rs | 13 +++++++-- .../runtime/tests/runtime_group_tools/mod.rs | 2 ++ test-utils/state-viewer/src/main.rs | 1 + test-utils/testlib/src/user/runtime_user.rs | 2 ++ 16 files changed, 80 insertions(+), 10 deletions(-) diff --git a/chain/chain/src/chain.rs b/chain/chain/src/chain.rs index 91a21ae0c5a..3075b48d73c 100644 --- a/chain/chain/src/chain.rs +++ b/chain/chain/src/chain.rs @@ -2612,6 +2612,7 @@ impl<'a> ChainUpdate<'a> { prev_block.header().gas_price(), prev_chunk.header.inner.gas_limit, &challenges_result, + *block.header().random_value(), true, ) .unwrap(); @@ -2738,6 +2739,7 @@ impl<'a> ChainUpdate<'a> { prev_block.header().gas_price(), chunk.header.inner.gas_limit, &block.header().challenges_result(), + *block.header().random_value(), ) .map_err(|e| ErrorKind::Other(e.to_string()))?; @@ -2803,6 +2805,7 @@ impl<'a> ChainUpdate<'a> { block.header().gas_price(), new_extra.gas_limit, &block.header().challenges_result(), + *block.header().random_value(), ) .map_err(|e| ErrorKind::Other(e.to_string()))?; @@ -3399,6 +3402,7 @@ impl<'a> ChainUpdate<'a> { block_header.gas_price(), chunk.header.inner.gas_limit, &block_header.challenges_result(), + *block_header.random_value(), )?; let (outcome_root, outcome_proofs) = @@ -3480,6 +3484,7 @@ impl<'a> ChainUpdate<'a> { block_header.gas_price(), chunk_extra.gas_limit, &block_header.challenges_result(), + *block_header.random_value(), )?; self.chain_store_update.save_trie_changes(apply_result.trie_changes); diff --git a/chain/chain/src/test_utils.rs b/chain/chain/src/test_utils.rs index fd396bd54dd..31d568db5d4 100644 --- a/chain/chain/src/test_utils.rs +++ b/chain/chain/src/test_utils.rs @@ -499,6 +499,7 @@ impl RuntimeAdapter for KeyValueRuntime { gas_price: Balance, _gas_limit: Gas, _challenges: &ChallengesResult, + _random_seed: CryptoHash, generate_storage_proof: bool, ) -> Result { assert!(!generate_storage_proof); @@ -677,6 +678,7 @@ impl RuntimeAdapter for KeyValueRuntime { _gas_price: Balance, _gas_limit: Gas, _challenges: &ChallengesResult, + _random_value: CryptoHash, ) -> Result { unimplemented!(); } diff --git a/chain/chain/src/types.rs b/chain/chain/src/types.rs index 0142df9fe74..42d6e12d7b0 100644 --- a/chain/chain/src/types.rs +++ b/chain/chain/src/types.rs @@ -436,6 +436,7 @@ pub trait RuntimeAdapter: Send + Sync { gas_price: Balance, gas_limit: Gas, challenges_result: &ChallengesResult, + random_seed: CryptoHash, ) -> Result { self.apply_transactions_with_optional_storage_proof( shard_id, @@ -450,6 +451,7 @@ pub trait RuntimeAdapter: Send + Sync { gas_price, gas_limit, challenges_result, + random_seed, false, ) } @@ -468,6 +470,7 @@ pub trait RuntimeAdapter: Send + Sync { gas_price: Balance, gas_limit: Gas, challenges_result: &ChallengesResult, + random_seed: CryptoHash, generate_storage_proof: bool, ) -> Result; @@ -486,6 +489,7 @@ pub trait RuntimeAdapter: Send + Sync { gas_price: Balance, gas_limit: Gas, challenges_result: &ChallengesResult, + random_value: CryptoHash, ) -> Result; /// Query runtime with given `path` and `data`. diff --git a/chain/chain/src/validate.rs b/chain/chain/src/validate.rs index 1b19f352afb..b37c404f7bb 100644 --- a/chain/chain/src/validate.rs +++ b/chain/chain/src/validate.rs @@ -311,6 +311,7 @@ fn validate_chunk_state_challenge( prev_block_header.gas_price(), chunk_state.prev_chunk.header.inner.gas_limit, &ChallengesResult::default(), + *block_header.random_value(), ) .map_err(|_| Error::from(ErrorKind::MaliciousChallenge))?; let outcome_root = ApplyTransactionResult::compute_outcomes_proof(&result.outcomes).0; diff --git a/core/primitives/src/version.rs b/core/primitives/src/version.rs index fb9a92db6d7..cdd7ed09068 100644 --- a/core/primitives/src/version.rs +++ b/core/primitives/src/version.rs @@ -18,7 +18,7 @@ pub const DB_VERSION: DbVersion = 5; pub type ProtocolVersion = u32; /// Current latest version of the protocol. -pub const PROTOCOL_VERSION: ProtocolVersion = 32; +pub const PROTOCOL_VERSION: ProtocolVersion = 33; pub const FIRST_BACKWARD_COMPATIBLE_PROTOCOL_VERSION: ProtocolVersion = 29; @@ -29,3 +29,5 @@ pub const MIN_PROTOCOL_VERSION_NEP_92: ProtocolVersion = 31; /// Minimum gas price proposed in NEP 92 (fixed) and the associated protocol version pub const MIN_GAS_PRICE_NEP_92_FIX: Balance = 100_000_000; pub const MIN_PROTOCOL_VERSION_NEP_92_FIX: ProtocolVersion = 32; + +pub const CORRECT_RANDOM_VALUE_PROTOCOL_VERSION: ProtocolVersion = 33; diff --git a/neard/src/runtime.rs b/neard/src/runtime.rs index 10b48638feb..cff7fea67b5 100644 --- a/neard/src/runtime.rs +++ b/neard/src/runtime.rs @@ -325,6 +325,7 @@ impl NightshadeRuntime { gas_price: Balance, gas_limit: Gas, challenges_result: &ChallengesResult, + random_seed: CryptoHash, ) -> Result { let validator_accounts_update = { let mut epoch_manager = self.epoch_manager.as_ref().write().expect(POISONED_LOCK_ERR); @@ -394,6 +395,7 @@ impl NightshadeRuntime { let epoch_height = self.get_epoch_height_from_prev_block(prev_block_hash)?; let epoch_id = self.get_epoch_id_from_prev_block(prev_block_hash)?; + let current_protocol_version = self.get_epoch_protocol_version(&epoch_id)?; let apply_state = ApplyState { block_index: block_height, @@ -403,6 +405,8 @@ impl NightshadeRuntime { gas_price, block_timestamp, gas_limit: Some(gas_limit), + random_seed, + current_protocol_version, }; let apply_result = self @@ -949,6 +953,7 @@ impl RuntimeAdapter for NightshadeRuntime { gas_price: Balance, gas_limit: Gas, challenges: &ChallengesResult, + random_seed: CryptoHash, generate_storage_proof: bool, ) -> Result { let trie = self.get_trie_for_shard(shard_id); @@ -967,6 +972,7 @@ impl RuntimeAdapter for NightshadeRuntime { gas_price, gas_limit, challenges, + random_seed, ) { Ok(result) => Ok(result), Err(e) => match e.kind() { @@ -993,6 +999,7 @@ impl RuntimeAdapter for NightshadeRuntime { gas_price: Balance, gas_limit: Gas, challenges: &ChallengesResult, + random_value: CryptoHash, ) -> Result { let trie = Trie::from_recorded_storage(partial_storage); self.process_state_update( @@ -1009,6 +1016,7 @@ impl RuntimeAdapter for NightshadeRuntime { gas_price, gas_limit, challenges, + random_value, ) } @@ -1414,6 +1422,7 @@ mod test { gas_price, gas_limit, challenges, + CryptoHash::default(), ) .unwrap(); let mut store_update = self.store.store_update(); diff --git a/pytest/tests/sanity/upgradable.py b/pytest/tests/sanity/upgradable.py index 64f96d15816..3c8fc8bf2b5 100644 --- a/pytest/tests/sanity/upgradable.py +++ b/pytest/tests/sanity/upgradable.py @@ -16,8 +16,8 @@ import branches import cluster -from utils import wait_for_blocks_or_timeout -from transaction import sign_payment_tx +from utils import wait_for_blocks_or_timeout, load_binary_file +from transaction import sign_deploy_contract_tx, sign_function_call_tx def main(): @@ -64,10 +64,20 @@ def main(): time.sleep(2) - # send a transaction to make sure that the execution result is consistent across nodes. + # deploy a contract status = nodes[0].get_status() - tx = sign_payment_tx(nodes[0].signer_key, 'test1', 100, 1, - base58.b58decode(status['sync_info']['latest_block_hash'].encode('utf8'))) + hash = status['sync_info']['latest_block_hash'] + tx = sign_deploy_contract_tx( + nodes[0].signer_key, + load_binary_file( + '../runtime/near-vm-runner/tests/res/test_contract_rs.wasm'), 1, base58.b58decode(hash.encode('utf8'))) + res = nodes[0].send_tx_and_wait(tx, timeout=20) + assert 'error' not in res, res + + # write some random value + tx = sign_function_call_tx(nodes[0].signer_key, nodes[0].signer_key.account_id, + 'write_random_value', [], 100000000000, 0, 2, + base58.b58decode(hash.encode('utf8'))) res = nodes[0].send_tx_and_wait(tx, timeout=20) assert 'error' not in res, res @@ -92,6 +102,12 @@ def main(): assert gas_price < 1000000000, gas_price assert gas_price > 100000000, gas_price + # write some random value again + tx = sign_function_call_tx(nodes[0].signer_key, nodes[0].signer_key.account_id, + 'write_random_value', [], 100000000000, 0, 3, + base58.b58decode(hash.encode('utf8'))) + res = nodes[0].send_tx_and_wait(tx, timeout=20) + assert 'error' not in res, res if __name__ == "__main__": main() diff --git a/runtime/near-vm-runner/tests/res/test_contract_rs.wasm b/runtime/near-vm-runner/tests/res/test_contract_rs.wasm index 3fc230ced3cd3bb6e1a3f7de6ec4cc173cb19a23..b3882682ced81e019d06246233a11cebe1aa2b40 100755 GIT binary patch delta 5711 zcmd5=dsr0Z8lQJ|7lGw6iXs=40j2bqf)_G7k4FbHv-BxFovx?0Wp~6~VHb86(~i0* z-n)Rj3W8h&(L}spV_qr~HO|&il>o!l<3+IsbL=@tb*n@9({S z-^};TUVPbb?G;1gZiq0t%nqwF+vJvIE2mf9hLt?J_3LzV_}Q3b$ic;iH+5GHz476o z$Gx4NciB9$$!{^moRueYMG)$e%~q37S`6V?&P)d7EdF z=>^&4o8Y56YI^ZgZy0ErBQ>YM$tkT_*C9$?TUxuq)4D^2lxv2PG(UNa$M% z5$?QfpS8`Aljq@>?T&b-V? zTqPKoy@RWQ2%Ez#Q*v&Pi-NhiYKXAPSu)iaKvqBpmu$&%xn-^f1e=3$bC|PC0jw6n zop~OUbD}9*&UU({aVwz%Ye3%JgSk2gvzW88yrvwNGuuWE>Y<}Nl?C%9n5Wjg86p{& zk>#{ZHrX6jc`ElhM72X68+FKI&d%YsKp2Db+_Ke_X?Am4eU>>cImc}CLEC(gc1pK< zA&!|5%_>`{*-n?qY_T}=93GR+%Dn;MOzXB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lo-^jhciRG!<;TQ6wcPcXk>}txEA8ka6`1u7EhH*2F$?|7u!Iw zeEnhxP_9LnCdZYqfT6J*+nrrGLDWCS7LhPdj=Y=>@T)9dNdwyN&a18Ig+Bjk4MAP5 zi8?y$>_0{D^didtc@V6@_kW%j{u*`r;H|Bf)SVq7nN}SXZ2) z%cOn7uF_;9tj2XWh8C=1J~IEHe=TOw8$~Oq0ijNbp!Y>kn8xD&z@itPv3PoF5VgVz z#VnXj#VwCysN|`NNA7XTFYO8xy7Gh6AH7)+@~5QX^XjAds|q;xsrDcEwN4Cjs zrVmR2T?y&hsk}`knPnKzPa|2K)pU}RRCIC|bY*g_dAURnjKS;8A=sS?C zo|=v%r>gj!3J73B6v*}-lG&OF$oG=0o}SJms}qVLIaS4vC0Xq+j%2mJc#_rrS|t#` j9IA(ZdS15wAt diff --git a/runtime/near-vm-runner/tests/test-contract-rs/src/lib.rs b/runtime/near-vm-runner/tests/test-contract-rs/src/lib.rs index 67c277f2cd3..24a34a4c9d1 100644 --- a/runtime/near-vm-runner/tests/test-contract-rs/src/lib.rs +++ b/runtime/near-vm-runner/tests/test-contract-rs/src/lib.rs @@ -254,6 +254,15 @@ pub unsafe fn write_block_height() { storage_write(key.len() as _, key.as_ptr() as _, value.len() as _, value.as_ptr() as _, 0); } +#[no_mangle] +pub unsafe fn write_random_value() { + random_seed(0); + let data = [0u8; 32]; + read_register(0, data.as_ptr() as u64); + let value = b"hello"; + storage_write(data.len() as _, data.as_ptr() as _, value.len() as _, value.as_ptr() as _, 1); +} + #[no_mangle] pub unsafe fn read_value() { input(0); diff --git a/runtime/runtime-params-estimator/src/testbed.rs b/runtime/runtime-params-estimator/src/testbed.rs index 2fb5f1a10f5..74a27b3413e 100644 --- a/runtime/runtime-params-estimator/src/testbed.rs +++ b/runtime/runtime-params-estimator/src/testbed.rs @@ -83,6 +83,8 @@ impl RuntimeTestbed { gas_price: 0, block_timestamp: 0, gas_limit: None, + random_seed: Default::default(), + current_protocol_version: 0, }; Self { workdir, diff --git a/runtime/runtime-standalone/src/lib.rs b/runtime/runtime-standalone/src/lib.rs index fdf2fe6feba..3bfb2e41c6a 100644 --- a/runtime/runtime-standalone/src/lib.rs +++ b/runtime/runtime-standalone/src/lib.rs @@ -211,8 +211,10 @@ impl RuntimeStandalone { block_timestamp: self.cur_block.block_timestamp, gas_limit: None, // not used + random_seed: Default::default(), last_block_hash: CryptoHash::default(), epoch_id: EpochId::default(), + current_protocol_version: 0, }; let apply_result = self.runtime.apply( diff --git a/runtime/runtime/src/actions.rs b/runtime/runtime/src/actions.rs index b51cbb89ea0..ddf05d35c3d 100644 --- a/runtime/runtime/src/actions.rs +++ b/runtime/runtime/src/actions.rs @@ -28,6 +28,7 @@ use crate::ext::RuntimeExt; use crate::{ActionResult, ApplyState}; use near_crypto::PublicKey; use near_primitives::errors::{ActionError, ActionErrorKind, ExternalError, RuntimeError}; +use near_primitives::version::CORRECT_RANDOM_VALUE_PROTOCOL_VERSION; use near_runtime_configs::AccountCreationConfig; use near_vm_errors::{CompilationError, FunctionCallError}; use near_vm_runner::VMError; @@ -144,7 +145,12 @@ pub(crate) fn action_function_call( storage_usage: account.storage_usage, attached_deposit: function_call.deposit, prepaid_gas: function_call.gas, - random_seed: action_hash.as_ref().to_vec(), + random_seed: if apply_state.current_protocol_version < CORRECT_RANDOM_VALUE_PROTOCOL_VERSION + { + action_hash.as_ref().to_vec() + } else { + apply_state.random_seed.as_ref().to_vec() + }, is_view: false, output_data_receivers, }; diff --git a/runtime/runtime/src/lib.rs b/runtime/runtime/src/lib.rs index 9795fa428a7..5a23132e583 100644 --- a/runtime/runtime/src/lib.rs +++ b/runtime/runtime/src/lib.rs @@ -38,6 +38,7 @@ use crate::config::{ }; use crate::verifier::validate_receipt; pub use crate::verifier::{validate_transaction, verify_and_charge_transaction}; +use near_primitives::version::ProtocolVersion; use std::rc::Rc; mod actions; @@ -70,6 +71,10 @@ pub struct ApplyState { /// Gas limit for a given chunk. /// If None is given, assumes there is no gas limit. pub gas_limit: Option, + /// Current random seed (from current block vrf output). + pub random_seed: CryptoHash, + /// Current Protocol version when we apply the state transition + pub current_protocol_version: ProtocolVersion, } /// Contains information to update validators accounts at the first block of a new epoch. @@ -284,7 +289,7 @@ impl Runtime { receipt: &Receipt, action_receipt: &ActionReceipt, promise_results: &[PromiseResult], - action_hash: CryptoHash, + action_hash: &CryptoHash, is_last_action: bool, epoch_info_provider: &dyn EpochInfoProvider, ) -> Result { @@ -337,7 +342,7 @@ impl Runtime { &mut result, account_id, function_call, - &action_hash, + action_hash, &self.config, is_last_action, epoch_info_provider, @@ -469,7 +474,7 @@ impl Runtime { receipt, action_receipt, &promise_results, - create_nonce_with_nonce( + &create_nonce_with_nonce( &receipt.receipt_id, u64::max_value() - action_index as u64, ), @@ -1448,6 +1453,8 @@ mod tests { gas_price: GAS_PRICE, block_timestamp: 100, gas_limit: Some(gas_limit), + random_seed: Default::default(), + current_protocol_version: 0, }; (runtime, tries, root, apply_state, signer, MockEpochInfoProvider::default()) diff --git a/runtime/runtime/tests/runtime_group_tools/mod.rs b/runtime/runtime/tests/runtime_group_tools/mod.rs index 2108565c434..c24277f0e16 100644 --- a/runtime/runtime/tests/runtime_group_tools/mod.rs +++ b/runtime/runtime/tests/runtime_group_tools/mod.rs @@ -63,6 +63,8 @@ impl StandaloneRuntime { gas_price: 100, block_timestamp: 0, gas_limit: None, + random_seed: Default::default(), + current_protocol_version: 0, }; Self { diff --git a/test-utils/state-viewer/src/main.rs b/test-utils/state-viewer/src/main.rs index 9e5c2b721df..f393a24bc7d 100644 --- a/test-utils/state-viewer/src/main.rs +++ b/test-utils/state-viewer/src/main.rs @@ -238,6 +238,7 @@ fn apply_block_at_height( prev_block.header().gas_price(), chunk.header.inner.gas_limit, &block.header().challenges_result(), + *block.header().random_value(), ) .unwrap(); let (outcome_root, _) = ApplyTransactionResult::compute_outcomes_proof(&apply_result.outcomes); diff --git a/test-utils/testlib/src/user/runtime_user.rs b/test-utils/testlib/src/user/runtime_user.rs index 1e1c142f85b..cc2fde1258e 100644 --- a/test-utils/testlib/src/user/runtime_user.rs +++ b/test-utils/testlib/src/user/runtime_user.rs @@ -125,7 +125,9 @@ impl RuntimeUser { epoch_height: 0, gas_price: MIN_GAS_PRICE, gas_limit: None, + random_seed: Default::default(), epoch_id: Default::default(), + current_protocol_version: 0, } } From 1232395f0586fad9ef03e510d5021696e0cfb7b8 Mon Sep 17 00:00:00 2001 From: Bowen Wang Date: Fri, 7 Aug 2020 10:45:45 -0700 Subject: [PATCH 2/3] fix --- neard/res/genesis_config.json | 2 +- runtime/near-vm-runner/tests/test_rs_contract.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/neard/res/genesis_config.json b/neard/res/genesis_config.json index 897ef2f20d3..24bd5817bd0 100644 --- a/neard/res/genesis_config.json +++ b/neard/res/genesis_config.json @@ -1,5 +1,5 @@ { - "protocol_version": 32, + "protocol_version": 33, "genesis_time": "1970-01-01T00:00:00.000000000Z", "chain_id": "sample", "genesis_height": 0, diff --git a/runtime/near-vm-runner/tests/test_rs_contract.rs b/runtime/near-vm-runner/tests/test_rs_contract.rs index 78698966569..03992423e79 100644 --- a/runtime/near-vm-runner/tests/test_rs_contract.rs +++ b/runtime/near-vm-runner/tests/test_rs_contract.rs @@ -170,7 +170,7 @@ def_test_ext!(ext_block_index, b"ext_block_index", &10u64.to_le_bytes()); def_test_ext!(ext_block_timestamp, b"ext_block_timestamp", &42u64.to_le_bytes()); def_test_ext!(ext_storage_usage, b"ext_storage_usage", &12u64.to_le_bytes()); // TODO: mock used_gas -def_test_ext!(ext_used_gas, b"ext_used_gas", &[184, 50, 70, 79, 4, 0, 0, 0]); +def_test_ext!(ext_used_gas, b"ext_used_gas", &[132, 156, 14, 81, 4, 0, 0, 0]); def_test_ext!( ext_sha256, b"ext_sha256", From d6bca09a06a95b9c990be404239978a8fa6969bb Mon Sep 17 00:00:00 2001 From: Bowen Wang Date: Fri, 7 Aug 2020 14:06:36 -0700 Subject: [PATCH 3/3] address comment --- .../runtime-params-estimator/src/testbed.rs | 3 +- runtime/runtime-standalone/src/lib.rs | 29 ++++++++++--------- .../runtime/tests/runtime_group_tools/mod.rs | 3 +- test-utils/testlib/src/user/runtime_user.rs | 3 +- 4 files changed, 21 insertions(+), 17 deletions(-) diff --git a/runtime/runtime-params-estimator/src/testbed.rs b/runtime/runtime-params-estimator/src/testbed.rs index 74a27b3413e..f9df04011fc 100644 --- a/runtime/runtime-params-estimator/src/testbed.rs +++ b/runtime/runtime-params-estimator/src/testbed.rs @@ -8,6 +8,7 @@ use near_primitives::receipt::Receipt; use near_primitives::test_utils::MockEpochInfoProvider; use near_primitives::transaction::{ExecutionStatus, SignedTransaction}; use near_primitives::types::{Gas, MerkleHash, StateRoot}; +use near_primitives::version::PROTOCOL_VERSION; use near_store::{create_store, ColState, ShardTries}; use near_vm_logic::VMLimitConfig; use neard::get_store_path; @@ -84,7 +85,7 @@ impl RuntimeTestbed { block_timestamp: 0, gas_limit: None, random_seed: Default::default(), - current_protocol_version: 0, + current_protocol_version: PROTOCOL_VERSION, }; Self { workdir, diff --git a/runtime/runtime-standalone/src/lib.rs b/runtime/runtime-standalone/src/lib.rs index 3bfb2e41c6a..0637b211f6d 100644 --- a/runtime/runtime-standalone/src/lib.rs +++ b/runtime/runtime-standalone/src/lib.rs @@ -1,25 +1,26 @@ +use std::collections::HashMap; +use std::sync::Arc; + use near_crypto::{InMemorySigner, KeyType, PublicKey, Signer}; use near_pool::{types::PoolIterator, TransactionPool}; +use near_primitives::account::{AccessKey, Account}; +use near_primitives::errors::RuntimeError; +use near_primitives::hash::CryptoHash; +use near_primitives::receipt::Receipt; +use near_primitives::state_record::StateRecord; +use near_primitives::test_utils::account_new; use near_primitives::test_utils::MockEpochInfoProvider; -use near_primitives::types::{AccountInfo, EpochId, EpochInfoProvider}; -use near_primitives::{account::AccessKey, test_utils::account_new}; -use near_primitives::{ - account::Account, - errors::RuntimeError, - hash::CryptoHash, - receipt::Receipt, - state_record::StateRecord, - transaction::{ExecutionOutcome, ExecutionStatus, SignedTransaction}, - types::AccountId, - types::{Balance, BlockHeight, EpochHeight, Gas, StateChangeCause}, +use near_primitives::transaction::{ExecutionOutcome, ExecutionStatus, SignedTransaction}; +use near_primitives::types::{ + AccountId, AccountInfo, Balance, BlockHeight, EpochHeight, EpochId, EpochInfoProvider, Gas, + StateChangeCause, }; +use near_primitives::version::PROTOCOL_VERSION; use near_runtime_configs::RuntimeConfig; use near_store::{ get_access_key, get_account, set_account, test_utils::create_test_store, ShardTries, Store, }; use node_runtime::{state_viewer::TrieViewer, ApplyState, Runtime}; -use std::collections::HashMap; -use std::sync::Arc; const DEFAULT_EPOCH_LENGTH: u64 = 3; @@ -214,7 +215,7 @@ impl RuntimeStandalone { random_seed: Default::default(), last_block_hash: CryptoHash::default(), epoch_id: EpochId::default(), - current_protocol_version: 0, + current_protocol_version: PROTOCOL_VERSION, }; let apply_result = self.runtime.apply( diff --git a/runtime/runtime/tests/runtime_group_tools/mod.rs b/runtime/runtime/tests/runtime_group_tools/mod.rs index c24277f0e16..9ab2dd169ef 100644 --- a/runtime/runtime/tests/runtime_group_tools/mod.rs +++ b/runtime/runtime/tests/runtime_group_tools/mod.rs @@ -6,6 +6,7 @@ use near_primitives::state_record::StateRecord; use near_primitives::test_utils::MockEpochInfoProvider; use near_primitives::transaction::{ExecutionOutcomeWithId, SignedTransaction}; use near_primitives::types::Balance; +use near_primitives::version::PROTOCOL_VERSION; use near_store::test_utils::create_tries; use near_store::ShardTries; use node_runtime::{ApplyState, Runtime}; @@ -64,7 +65,7 @@ impl StandaloneRuntime { block_timestamp: 0, gas_limit: None, random_seed: Default::default(), - current_protocol_version: 0, + current_protocol_version: PROTOCOL_VERSION, }; Self { diff --git a/test-utils/testlib/src/user/runtime_user.rs b/test-utils/testlib/src/user/runtime_user.rs index cc2fde1258e..c4c5ea44986 100644 --- a/test-utils/testlib/src/user/runtime_user.rs +++ b/test-utils/testlib/src/user/runtime_user.rs @@ -9,6 +9,7 @@ use near_primitives::hash::CryptoHash; use near_primitives::receipt::Receipt; use near_primitives::transaction::SignedTransaction; use near_primitives::types::{AccountId, BlockHeightDelta, MerkleHash}; +use near_primitives::version::PROTOCOL_VERSION; use near_primitives::views::{ AccessKeyView, AccountView, BlockView, ExecutionOutcomeView, ExecutionOutcomeWithIdView, ExecutionStatusView, ViewStateResult, @@ -127,7 +128,7 @@ impl RuntimeUser { gas_limit: None, random_seed: Default::default(), epoch_id: Default::default(), - current_protocol_version: 0, + current_protocol_version: PROTOCOL_VERSION, } }