From 5efb2ef6596fde926934b3c4201d797896b31e89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?dj8yf0=CE=BCl?= Date: Thu, 7 Sep 2023 16:16:02 +0300 Subject: [PATCH] chore: update `borsh` to 1.0.0-alpha.4 (a lot of `try_to_vec` deprecation) --- Cargo.lock | 60 ++++++++--------- Cargo.toml | 2 +- chain/chain/src/chain.rs | 24 +++---- chain/chain/src/store.rs | 14 ++-- chain/chain/src/store_validator/validate.rs | 4 +- chain/chain/src/test_utils/kv_runtime.rs | 13 ++-- chain/client/src/debug.rs | 4 +- chain/client/src/sync_jobs_actor.rs | 4 +- chain/client/src/tests/catching_up.rs | 8 +-- .../jsonrpc-tests/tests/rpc_transactions.rs | 12 ++-- chain/network/src/network_protocol/mod.rs | 4 +- .../src/network_protocol/proto_conv/crypto.rs | 6 +- .../src/network_protocol/proto_conv/net.rs | 10 +-- .../proto_conv/peer_message.rs | 14 ++-- chain/network/src/store/schema/tests.rs | 2 +- chain/network/src/types.rs | 4 +- chain/pool/src/lib.rs | 4 +- chain/rosetta-rpc/src/utils.rs | 4 +- core/account-id/fuzz/fuzz_targets/borsh.rs | 4 +- core/account-id/src/borsh.rs | 8 +-- core/crypto/src/signature.rs | 4 +- core/primitives-core/src/account.rs | 8 +-- core/primitives-core/src/profile.rs | 2 +- core/primitives/benches/serialization.rs | 14 ++-- core/primitives/src/action/delegate.rs | 6 +- core/primitives/src/block_header.rs | 66 +++++++++---------- core/primitives/src/sharding.rs | 14 ++-- core/primitives/src/signable_message.rs | 2 +- core/primitives/src/transaction.rs | 6 +- core/primitives/src/trie_key.rs | 2 +- core/primitives/src/views.rs | 2 +- core/store/src/cold_storage.rs | 8 +-- core/store/src/flat/inlining_migration.rs | 9 ++- core/store/src/flat/storage.rs | 4 +- core/store/src/genesis/state_applier.rs | 6 +- core/store/src/lib.rs | 8 +-- core/store/src/migrations.rs | 9 ++- core/store/src/trie/mod.rs | 4 +- core/store/src/trie/raw_node.rs | 2 +- core/store/src/trie/shard_tries.rs | 4 +- core/store/src/trie/split_state.rs | 6 +- .../genesis-populate/src/state_dump.rs | 4 +- .../src/tests/client/benchmarks.rs | 4 +- .../src/tests/client/challenges.rs | 24 +++---- .../client/features/zero_balance_account.rs | 8 +-- .../src/tests/client/process_blocks.rs | 10 +-- .../src/tests/client/sharding_upgrade.rs | 4 +- .../src/tests/client/state_dump.rs | 4 +- .../src/tests/nearcore/rpc_error_structs.rs | 4 +- .../src/tests/nearcore/rpc_nodes.rs | 14 ++-- .../src/tests/nearcore/sync_state_nodes.rs | 4 +- integration-tests/src/user/rpc_user.rs | 6 +- nearcore/src/entity_debug.rs | 24 +++---- nearcore/src/runtime/mod.rs | 7 +- nearcore/src/state_sync.rs | 4 +- .../src/logic/tests/gas_counter.rs | 7 +- .../src/logic/tests/promises.rs | 12 ++-- runtime/runtime/src/actions.rs | 21 +++--- runtime/runtime/src/verifier.rs | 6 +- runtime/runtime/tests/test_async_calls.rs | 10 +-- tools/amend-genesis/src/lib.rs | 4 +- tools/fork-network/src/cli.rs | 4 +- tools/fork-network/src/storage_mutator.rs | 6 +- tools/mirror/src/lib.rs | 14 ++-- tools/speedy_sync/src/main.rs | 2 +- tools/state-viewer/src/cli.rs | 4 +- tools/state-viewer/src/contract_accounts.rs | 4 +- tools/state-viewer/src/state_changes.rs | 4 +- tools/state-viewer/src/state_dump.rs | 4 +- 69 files changed, 303 insertions(+), 311 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 0584df1283b..bf628743c11 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -825,11 +825,11 @@ dependencies = [ [[package]] name = "borsh" -version = "1.0.0-alpha.3" +version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4a1acb549fd0db3b4150957daa838fa9bbd26c18f18b32f24c9678de4b8ca4f7" +checksum = "41898277107b0d3f027593697912977397eba6ac39a55bdd2eb02c1d5d5013b5" dependencies = [ - "borsh-derive 1.0.0-alpha.3", + "borsh-derive 1.0.0-alpha.4", "cfg_aliases", ] @@ -848,9 +848,9 @@ dependencies = [ [[package]] name = "borsh-derive" -version = "1.0.0-alpha.3" +version = "1.0.0-alpha.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8e6d4b2eff15f3f87c5d0844180621f6eb0688e68820d76cf17149a02eef1c78" +checksum = "413cb435569fe499e89235f758304e0e7198016baa351d8f5827ea0f40526ce0" dependencies = [ "once_cell", "proc-macro-crate 1.3.0", @@ -1224,7 +1224,7 @@ name = "cold-store-tool" version = "0.0.0" dependencies = [ "anyhow", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "clap 4.2.4", "near-chain-configs", "near-epoch-manager", @@ -2358,7 +2358,7 @@ dependencies = [ name = "genesis-populate" version = "0.0.0" dependencies = [ - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "clap 4.2.4", "indicatif", "near-chain", @@ -2776,7 +2776,7 @@ dependencies = [ "actix-rt", "anyhow", "assert_matches", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "chrono", "clap 4.2.4", "futures", @@ -3372,7 +3372,7 @@ version = "0.0.0" dependencies = [ "arbitrary", "bolero", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "serde", "serde_json", ] @@ -3381,7 +3381,7 @@ dependencies = [ name = "near-account-id-fuzz" version = "0.0.0" dependencies = [ - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "libfuzzer-sys", "near-account-id", "serde_json", @@ -3402,7 +3402,7 @@ name = "near-amend-genesis" version = "0.0.0" dependencies = [ "anyhow", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "clap 4.2.4", "near-chain", "near-chain-configs", @@ -3456,7 +3456,7 @@ dependencies = [ "actix", "ansi_term", "assert_matches", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "bytesize", "chrono", "crossbeam-channel", @@ -3523,7 +3523,7 @@ version = "0.0.0" dependencies = [ "actix", "assert_matches", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "chrono", "derive-enum-from-into", "derive_more", @@ -3567,7 +3567,7 @@ dependencies = [ "anyhow", "assert_matches", "async-trait", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "chrono", "cloud-storage", "delay-detector", @@ -3643,7 +3643,7 @@ name = "near-crypto" version = "0.0.0" dependencies = [ "blake2", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "bs58", "c2-chacha", "curve25519-dalek", @@ -3705,7 +3705,7 @@ dependencies = [ name = "near-epoch-manager" version = "0.0.0" dependencies = [ - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "chrono", "itertools", "near-cache", @@ -3728,7 +3728,7 @@ name = "near-flat-storage" version = "0.0.0" dependencies = [ "anyhow", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "clap 4.2.4", "near-chain", "near-chain-configs", @@ -3892,7 +3892,7 @@ version = "0.0.0" dependencies = [ "actix", "awc", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "futures", "near-actix-test-utils", "near-chain-configs", @@ -3926,7 +3926,7 @@ dependencies = [ "actix", "anyhow", "async-trait", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "bs58", "clap 4.2.4", "ed25519-dalek", @@ -3970,7 +3970,7 @@ dependencies = [ "arc-swap", "assert_matches", "async-trait", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "bytes", "bytesize", "chrono", @@ -4096,7 +4096,7 @@ dependencies = [ name = "near-pool" version = "0.0.0" dependencies = [ - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "near-crypto", "near-o11y", "near-primitives", @@ -4112,7 +4112,7 @@ dependencies = [ "assert_matches", "base64 0.21.0", "bencher", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "bytesize", "cfg-if 1.0.0", "chrono", @@ -4149,7 +4149,7 @@ version = "0.0.0" dependencies = [ "arbitrary", "base64 0.21.0", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "bs58", "derive_more", "enum-map", @@ -4254,7 +4254,7 @@ dependencies = [ "anyhow", "assert_matches", "bencher", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "bytesize", "crossbeam", "derive_more", @@ -4416,7 +4416,7 @@ dependencies = [ "assert_matches", "base64 0.21.0", "bolero", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "clap 4.2.4", "ed25519-dalek", "expect-test", @@ -4571,7 +4571,7 @@ dependencies = [ "anyhow", "awc", "bencher", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "chrono", "cloud-storage", "delay-detector", @@ -4704,7 +4704,7 @@ name = "node-runtime" version = "0.0.0" dependencies = [ "assert_matches", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "enum-map", "hex", "indicatif", @@ -5882,7 +5882,7 @@ name = "runtime-params-estimator" version = "0.0.0" dependencies = [ "anyhow", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "bs58", "bytesize", "cfg-if 1.0.0", @@ -6572,7 +6572,7 @@ dependencies = [ name = "speedy_sync" version = "0.0.0" dependencies = [ - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "clap 4.2.4", "near-chain", "near-chain-configs", @@ -6604,7 +6604,7 @@ dependencies = [ "actix", "ansi_term", "anyhow", - "borsh 1.0.0-alpha.3", + "borsh 1.0.0-alpha.4", "chrono", "clap 4.2.4", "cloud-storage", diff --git a/Cargo.toml b/Cargo.toml index 47a09dc637b..479bf6cdb76 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -111,7 +111,7 @@ bitflags = "1.2" blake2 = "0.9.1" bn = { package = "zeropool-bn", version = "0.5.11" } bolero = "0.8.0" -borsh = { version = "1.0.0-alpha.3", features = ["derive", "rc"] } +borsh = { version = "1.0.0-alpha.4", features = ["derive", "rc"] } bs58 = "0.4" bytes = "1" bytesize = { version = "1.1", features = ["serde"] } diff --git a/chain/chain/src/chain.rs b/chain/chain/src/chain.rs index af3d840b346..cc3010875e8 100644 --- a/chain/chain/src/chain.rs +++ b/chain/chain/src/chain.rs @@ -20,7 +20,7 @@ use crate::validate::{ }; use crate::{byzantine_assert, create_light_client_block_view, Doomslug}; use crate::{metrics, DoomslugThresholdMode}; -use borsh::BorshSerialize; + use chrono::Duration; use crossbeam_channel::{unbounded, Receiver, Sender}; use delay_detector::DelayDetector; @@ -1283,8 +1283,8 @@ impl Chain { let other_header = self.get_block_header(block_hashes.iter().next().unwrap())?; challenges.push(ChallengeBody::BlockDoubleSign(BlockDoubleSign { - left_block_header: header.try_to_vec().expect("Failed to serialize"), - right_block_header: other_header.try_to_vec().expect("Failed to serialize"), + left_block_header: borsh::to_vec(&header).expect("Failed to serialize"), + right_block_header: borsh::to_vec(&other_header).expect("Failed to serialize"), })); } } @@ -1629,7 +1629,7 @@ impl Chain { if let Some(encoded_chunk) = self.store.is_invalid_chunk(&chunk_header.chunk_hash())? { let merkle_paths = Block::compute_chunk_headers_root(block.chunks().iter()).1; let chunk_proof = ChunkProofs { - block_header: block.header().try_to_vec().expect("Failed to serialize"), + block_header: borsh::to_vec(&block.header()).expect("Failed to serialize"), merkle_proof: merkle_paths[shard_id].clone(), chunk: MaybeEncodedShardChunk::Encoded(EncodedShardChunk::clone( &encoded_chunk, @@ -3021,7 +3021,7 @@ impl Chain { sync_hash: CryptoHash, ) -> Result { // Check cache - let key = StateHeaderKey(shard_id, sync_hash).try_to_vec()?; + let key = borsh::to_vec(&StateHeaderKey(shard_id, sync_hash))?; if let Ok(Some(header)) = self.store.store().get_ser(DBCol::StateHeaders, &key) { return Ok(header); } @@ -3050,7 +3050,7 @@ impl Chain { %sync_hash) .entered(); // Check cache - let key = StatePartKey(sync_hash, shard_id, part_id).try_to_vec()?; + let key = borsh::to_vec(&StatePartKey(sync_hash, shard_id, part_id))?; if let Ok(Some(state_part)) = self.store.store().get(DBCol::StateParts, &key) { return Ok(state_part.into()); } @@ -3258,7 +3258,7 @@ impl Chain { // Saving the header data. let mut store_update = self.store.store().store_update(); - let key = StateHeaderKey(shard_id, sync_hash).try_to_vec()?; + let key = borsh::to_vec(&StateHeaderKey(shard_id, sync_hash))?; store_update.set_ser(DBCol::StateHeaders, &key, &shard_state_header)?; store_update.commit()?; @@ -3293,7 +3293,7 @@ impl Chain { // Saving the part data. let mut store_update = self.store.store().store_update(); - let key = StatePartKey(sync_hash, shard_id, part_id.idx).try_to_vec()?; + let key = borsh::to_vec(&StatePartKey(sync_hash, shard_id, part_id.idx))?; store_update.set(DBCol::StateParts, &key, data); store_update.commit()?; Ok(()) @@ -3752,8 +3752,8 @@ impl Chain { // .unwrap(); // let partial_state = apply_result.proof.unwrap().nodes; Ok(ChunkState { - prev_block_header: prev_block.header().try_to_vec()?, - block_header: block.header().try_to_vec()?, + prev_block_header: borsh::to_vec(&prev_block.header())?, + block_header: borsh::to_vec(&block.header())?, prev_merkle_proof: prev_merkle_proofs[chunk_shard_id as usize].clone(), merkle_proof: merkle_proofs[chunk_shard_id as usize].clone(), prev_chunk, @@ -3999,7 +3999,7 @@ impl Chain { if !validate_transactions_order(transactions) { let merkle_paths = Block::compute_chunk_headers_root(block.chunks().iter()).1; let chunk_proof = ChunkProofs { - block_header: block.header().try_to_vec().expect("Failed to serialize"), + block_header: borsh::to_vec(&block.header()).expect("Failed to serialize"), merkle_proof: merkle_paths[shard_id as usize].clone(), chunk: MaybeEncodedShardChunk::Decoded(chunk), }; @@ -4850,7 +4850,7 @@ impl Chain { shard_receipts .into_iter() .map(|(i, rs)| { - let bytes = (i, rs).try_to_vec().unwrap(); + let bytes = borsh::to_vec(&(i, rs)).unwrap(); hash(&bytes) }) .collect() diff --git a/chain/chain/src/store.rs b/chain/chain/src/store.rs index 586c08aee83..a500f072d82 100644 --- a/chain/chain/src/store.rs +++ b/chain/chain/src/store.rs @@ -881,7 +881,7 @@ impl ChainStore { shard_id: ShardId, block_hash: CryptoHash, ) -> Result { - let key = StateHeaderKey(shard_id, block_hash).try_to_vec()?; + let key = borsh::to_vec(&StateHeaderKey(shard_id, block_hash))?; match self.store.get_ser(DBCol::StateHeaders, &key) { Ok(Some(header)) => Ok(header), _ => Err(Error::Other("Cannot get shard_state_header".into())), @@ -2396,7 +2396,7 @@ impl<'a> ChainStoreUpdate<'a> { let state_num_parts = get_num_state_parts(shard_state_header.state_root_node().memory_usage); self.gc_col_state_parts(block_hash, shard_id, state_num_parts)?; - let key = StateHeaderKey(shard_id, block_hash).try_to_vec()?; + let key = borsh::to_vec(&StateHeaderKey(shard_id, block_hash))?; self.gc_col(DBCol::StateHeaders, &key); } } @@ -2496,7 +2496,7 @@ impl<'a> ChainStoreUpdate<'a> { let state_num_parts = get_num_state_parts(shard_state_header.state_root_node().memory_usage); self.gc_col_state_parts(block_hash, shard_id, state_num_parts)?; - let state_header_key = StateHeaderKey(shard_id, block_hash).try_to_vec()?; + let state_header_key = borsh::to_vec(&StateHeaderKey(shard_id, block_hash))?; self.gc_col(DBCol::StateHeaders, &state_header_key); } @@ -2606,7 +2606,7 @@ impl<'a> ChainStoreUpdate<'a> { num_parts: u64, ) -> Result<(), Error> { for part_id in 0..num_parts { - let key = StatePartKey(sync_hash, shard_id, part_id).try_to_vec()?; + let key = borsh::to_vec(&StatePartKey(sync_hash, shard_id, part_id))?; self.gc_col(DBCol::StateParts, &key); } Ok(()) @@ -3032,7 +3032,7 @@ impl<'a> ChainStoreUpdate<'a> { // Increase transaction refcounts for all included txs for tx in chunk.transactions().iter() { - let bytes = tx.try_to_vec().expect("Borsh cannot fail"); + let bytes = borsh::to_vec(&tx).expect("Borsh cannot fail"); store_update.increment_refcount( DBCol::Transactions, tx.get_hash().as_ref(), @@ -3042,7 +3042,7 @@ impl<'a> ChainStoreUpdate<'a> { // Increase receipt refcounts for all included receipts for receipt in chunk.receipts().iter() { - let bytes = receipt.try_to_vec().expect("Borsh cannot fail"); + let bytes = borsh::to_vec(&receipt).expect("Borsh cannot fail"); store_update.increment_refcount( DBCol::Receipts, receipt.get_hash().as_ref(), @@ -3112,7 +3112,7 @@ impl<'a> ChainStoreUpdate<'a> { )?; } for (receipt_id, shard_id) in self.chain_store_cache_update.receipt_id_to_shard_id.iter() { - let data = shard_id.try_to_vec()?; + let data = borsh::to_vec(&shard_id)?; store_update.increment_refcount(DBCol::ReceiptIdToShardId, receipt_id.as_ref(), &data); } for (block_hash, refcount) in self.chain_store_cache_update.block_refcounts.iter() { diff --git a/chain/chain/src/store_validator/validate.rs b/chain/chain/src/store_validator/validate.rs index 00b2bfc06a1..619be6926a4 100644 --- a/chain/chain/src/store_validator/validate.rs +++ b/chain/chain/src/store_validator/validate.rs @@ -1,5 +1,5 @@ use crate::StoreValidator; -use borsh::BorshSerialize; + use near_primitives::block::{Block, BlockHeader, Tip}; use near_primitives::epoch_manager::block_info::BlockInfo; use near_primitives::epoch_manager::epoch_info::EpochInfo; @@ -854,7 +854,7 @@ pub(crate) fn state_part_header_exists( ) -> Result<(), StoreValidatorError> { let StatePartKey(block_hash, shard_id, part_id) = *key; let state_header_key = unwrap_or_err!( - StateHeaderKey(shard_id, block_hash).try_to_vec(), + borsh::to_vec(&StateHeaderKey(shard_id, block_hash)), "Can't serialize StateHeaderKey" ); let header = unwrap_or_err_db!( diff --git a/chain/chain/src/test_utils/kv_runtime.rs b/chain/chain/src/test_utils/kv_runtime.rs index 9d199482c19..46f8fe0b0b2 100644 --- a/chain/chain/src/test_utils/kv_runtime.rs +++ b/chain/chain/src/test_utils/kv_runtime.rs @@ -349,7 +349,7 @@ impl KeyValueRuntime { receipt_nonces: HashSet::default(), tx_nonces: HashSet::default(), }; - let data = kv_state.try_to_vec().unwrap(); + let data = borsh::to_vec(&kv_state).unwrap(); let data_len = data.len() as u64; // StateRoot is actually faked here. // We cannot do any reasonable validations of it in test_utils. @@ -1157,7 +1157,7 @@ impl RuntimeAdapter for KeyValueRuntime { } } - let data = state.try_to_vec()?; + let data = borsh::to_vec(&state)?; let state_size = data.len() as u64; let state_root = hash(&data); self.state.write().unwrap().insert(state_root, state); @@ -1285,7 +1285,7 @@ impl RuntimeAdapter for KeyValueRuntime { return Ok(vec![]); } let state = self.state.read().unwrap().get(state_root).unwrap().clone(); - let data = state.try_to_vec().expect("should never fall"); + let data = borsh::to_vec(&state).expect("should never fall"); Ok(data) } @@ -1307,7 +1307,7 @@ impl RuntimeAdapter for KeyValueRuntime { } let state = KVState::try_from_slice(data).unwrap(); self.state.write().unwrap().insert(*state_root, state.clone()); - let data = state.try_to_vec()?; + let data = borsh::to_vec(&state)?; let state_size = data.len() as u64; self.state_size.write().unwrap().insert(*state_root, state_size); Ok(()) @@ -1319,14 +1319,13 @@ impl RuntimeAdapter for KeyValueRuntime { _block_hash: &CryptoHash, state_root: &StateRoot, ) -> Result { - let data = self + let data = borsh::to_vec(&self .state .read() .unwrap() .get(state_root) .unwrap() - .clone() - .try_to_vec() + .clone()) .expect("should never fall") .into(); let memory_usage = *self.state_size.read().unwrap().get(state_root).unwrap(); diff --git a/chain/client/src/debug.rs b/chain/client/src/debug.rs index b16d3d15f74..a24bf65b0ef 100644 --- a/chain/client/src/debug.rs +++ b/chain/client/src/debug.rs @@ -2,7 +2,7 @@ //! without backwards compatibility. use crate::ClientActor; use actix::{Context, Handler}; -use borsh::BorshSerialize; + use itertools::Itertools; use near_chain::crypto_hash_timer::CryptoHashTimer; use near_chain::{near_chain_primitives, Chain, ChainStoreAccess}; @@ -255,7 +255,7 @@ impl ClientActor { let state_header_exists: Vec = (0..block.chunks().len()) .map(|shard_id| { - let key = StateHeaderKey(shard_id as u64, *block.hash()).try_to_vec(); + let key = borsh::to_vec(&StateHeaderKey(shard_id as u64, *block.hash())); match key { Ok(key) => { matches!( diff --git a/chain/client/src/sync_jobs_actor.rs b/chain/client/src/sync_jobs_actor.rs index 8d401a6ea5b..c1e392b34c1 100644 --- a/chain/client/src/sync_jobs_actor.rs +++ b/chain/client/src/sync_jobs_actor.rs @@ -1,5 +1,5 @@ use crate::ClientActor; -use borsh::BorshSerialize; + use near_chain::chain::{ do_apply_chunks, ApplyStatePartsRequest, ApplyStatePartsResponse, BlockCatchUpRequest, BlockCatchUpResponse, @@ -48,7 +48,7 @@ impl SyncJobsActor { let shard_id = msg.shard_uid.shard_id as ShardId; for part_id in 0..msg.num_parts { - let key = StatePartKey(msg.sync_hash, shard_id, part_id).try_to_vec()?; + let key = borsh::to_vec(&StatePartKey(msg.sync_hash, shard_id, part_id))?; let part = store.get(DBCol::StateParts, &key)?.unwrap(); msg.runtime_adapter.apply_state_part( diff --git a/chain/client/src/tests/catching_up.rs b/chain/client/src/tests/catching_up.rs index 1e3b6cd501a..b3f36d81922 100644 --- a/chain/client/src/tests/catching_up.rs +++ b/chain/client/src/tests/catching_up.rs @@ -262,10 +262,10 @@ fn test_catchup_receipts_sync_common(wait_till: u64, send: u64, sync_hold: bool) target: target.clone(), }; if !seen_hashes_with_state - .contains(&hash_func(&srs.try_to_vec().unwrap())) + .contains(&hash_func(&borsh::to_vec(&srs).unwrap())) { seen_hashes_with_state - .insert(hash_func(&srs.try_to_vec().unwrap())); + .insert(hash_func(&borsh::to_vec(&srs).unwrap())); return (NetworkResponses::NoResponse.into(), false); } } @@ -285,10 +285,10 @@ fn test_catchup_receipts_sync_common(wait_till: u64, send: u64, sync_hold: bool) target: target.clone(), }; if !seen_hashes_with_state - .contains(&hash_func(&srs.try_to_vec().unwrap())) + .contains(&hash_func(&borsh::to_vec(&srs).unwrap())) { seen_hashes_with_state - .insert(hash_func(&srs.try_to_vec().unwrap())); + .insert(hash_func(&borsh::to_vec(&srs).unwrap())); return (NetworkResponses::NoResponse.into(), false); } } diff --git a/chain/jsonrpc/jsonrpc-tests/tests/rpc_transactions.rs b/chain/jsonrpc/jsonrpc-tests/tests/rpc_transactions.rs index 312a729e191..044053e2805 100644 --- a/chain/jsonrpc/jsonrpc-tests/tests/rpc_transactions.rs +++ b/chain/jsonrpc/jsonrpc-tests/tests/rpc_transactions.rs @@ -1,7 +1,7 @@ use std::sync::{Arc, Mutex}; use actix::{Actor, System}; -use borsh::BorshSerialize; + use futures::{future, FutureExt, TryFutureExt}; use near_actix_test_utils::run_actix; @@ -44,7 +44,7 @@ fn test_send_tx_async() { 100, block_hash, ); - let bytes = tx.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&tx).unwrap(); let tx_hash = tx.get_hash().to_string(); *tx_hash2_1.lock().unwrap() = Some(tx.get_hash()); client @@ -91,7 +91,7 @@ fn test_send_tx_commit() { 100, block_hash, ); - let bytes = tx.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&tx).unwrap(); let result = client.broadcast_tx_commit(to_base64(&bytes)).await.unwrap(); assert_eq!(result.status, FinalExecutionStatus::SuccessValue(Vec::new())); }); @@ -136,7 +136,7 @@ fn test_expired_tx() { 100, block_hash, ); - let bytes = tx.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&tx).unwrap(); actix::spawn( client .broadcast_tx_commit(to_base64(&bytes)) @@ -180,7 +180,7 @@ fn test_replay_protection() { 100, hash(&[1]), ); - let bytes = tx.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&tx).unwrap(); if let Ok(_) = client.broadcast_tx_commit(to_base64(&bytes)).await { panic!("transaction should not succeed"); } @@ -213,7 +213,7 @@ fn test_check_invalid_tx() { 100, hash(&[1]), ); - let bytes = tx.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&tx).unwrap(); match client.EXPERIMENTAL_check_tx(to_base64(&bytes)).await { Err(e) => { let s = serde_json::to_string(&e.data.unwrap()).unwrap(); diff --git a/chain/network/src/network_protocol/mod.rs b/chain/network/src/network_protocol/mod.rs index 03a46de6af7..bd0b40d4736 100644 --- a/chain/network/src/network_protocol/mod.rs +++ b/chain/network/src/network_protocol/mod.rs @@ -22,7 +22,7 @@ pub use _proto::network as proto; use crate::network_protocol::proto_conv::trace_context::{ extract_span_context, inject_trace_context, }; -use borsh::{BorshDeserialize as _, BorshSerialize as _}; +use borsh::{BorshDeserialize as _}; use near_async::time; use near_crypto::PublicKey; use near_crypto::Signature; @@ -442,7 +442,7 @@ impl PeerMessage { /// If the encoding is `Proto`, then also attaches current Span's context to the message. pub(crate) fn serialize(&self, enc: Encoding) -> Vec { match enc { - Encoding::Borsh => borsh_::PeerMessage::from(self).try_to_vec().unwrap(), + Encoding::Borsh => borsh::to_vec(&borsh_::PeerMessage::from(self)).unwrap(), Encoding::Proto => { let mut msg = proto::PeerMessage::from(self); let cx = Span::current().context(); diff --git a/chain/network/src/network_protocol/proto_conv/crypto.rs b/chain/network/src/network_protocol/proto_conv/crypto.rs index 8c45951fb64..f11f661330d 100644 --- a/chain/network/src/network_protocol/proto_conv/crypto.rs +++ b/chain/network/src/network_protocol/proto_conv/crypto.rs @@ -1,6 +1,6 @@ /// Conversion functions for messages representing crypto primitives. use crate::network_protocol::proto; -use borsh::{BorshDeserialize as _, BorshSerialize as _}; +use borsh::{BorshDeserialize as _}; use near_crypto::PublicKey; use near_primitives::hash::CryptoHash; use near_primitives::network::PeerId; @@ -30,7 +30,7 @@ pub type ParsePublicKeyError = std::io::Error; impl From<&PublicKey> for proto::PublicKey { fn from(x: &PublicKey) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Self::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Self::default() } } } @@ -60,7 +60,7 @@ pub type ParseSignatureError = std::io::Error; impl From<&near_crypto::Signature> for proto::Signature { fn from(x: &near_crypto::Signature) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Self::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Self::default() } } } diff --git a/chain/network/src/network_protocol/proto_conv/net.rs b/chain/network/src/network_protocol/proto_conv/net.rs index 92ea8e427a1..f4bd9d56e0c 100644 --- a/chain/network/src/network_protocol/proto_conv/net.rs +++ b/chain/network/src/network_protocol/proto_conv/net.rs @@ -4,7 +4,7 @@ use super::*; use crate::network_protocol::proto; use crate::network_protocol::PeerAddr; use crate::network_protocol::{Edge, PartialEdgeInfo, PeerInfo}; -use borsh::{BorshDeserialize as _, BorshSerialize as _}; +use borsh::{BorshDeserialize as _}; use near_primitives::network::AnnounceAccount; use protobuf::MessageField as MF; use std::net::{IpAddr, SocketAddr}; @@ -77,7 +77,7 @@ impl TryFrom<&proto::PeerAddr> for PeerAddr { impl From<&PeerInfo> for proto::PeerInfo { fn from(x: &PeerInfo) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Self::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Self::default() } } } @@ -96,7 +96,7 @@ pub type ParsePartialEdgeInfoError = std::io::Error; impl From<&PartialEdgeInfo> for proto::PartialEdgeInfo { fn from(x: &PartialEdgeInfo) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Self::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Self::default() } } } @@ -113,7 +113,7 @@ pub type ParseEdgeError = std::io::Error; impl From<&Edge> for proto::Edge { fn from(x: &Edge) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Self::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Self::default() } } } @@ -130,7 +130,7 @@ pub type ParseAnnounceAccountError = std::io::Error; impl From<&AnnounceAccount> for proto::AnnounceAccount { fn from(x: &AnnounceAccount) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Self::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Self::default() } } } diff --git a/chain/network/src/network_protocol/proto_conv/peer_message.rs b/chain/network/src/network_protocol/proto_conv/peer_message.rs index 3e33926fab9..e94929671e0 100644 --- a/chain/network/src/network_protocol/proto_conv/peer_message.rs +++ b/chain/network/src/network_protocol/proto_conv/peer_message.rs @@ -9,7 +9,7 @@ use crate::network_protocol::{ }; use crate::network_protocol::{RoutedMessage, RoutedMessageV2}; use crate::types::StateResponseInfo; -use borsh::{BorshDeserialize as _, BorshSerialize as _}; +use borsh::{BorshDeserialize as _}; use near_async::time::error::ComponentRange; use near_primitives::block::{Block, BlockHeader}; use near_primitives::challenge::Challenge; @@ -113,7 +113,7 @@ impl TryFrom<&proto::DistanceVector> for DistanceVector { impl From<&BlockHeader> for proto::BlockHeader { fn from(x: &BlockHeader) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Default::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Default::default() } } } @@ -130,7 +130,7 @@ impl TryFrom<&proto::BlockHeader> for BlockHeader { impl From<&Block> for proto::Block { fn from(x: &Block) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Default::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Default::default() } } } @@ -147,7 +147,7 @@ impl TryFrom<&proto::Block> for Block { impl From<&StateResponseInfo> for proto::StateResponseInfo { fn from(x: &StateResponseInfo) -> Self { - Self { borsh: x.try_to_vec().unwrap(), ..Default::default() } + Self { borsh: borsh::to_vec(&x).unwrap(), ..Default::default() } } } @@ -226,11 +226,11 @@ impl From<&PeerMessage> for proto::PeerMessage { ..Default::default() }), PeerMessage::Transaction(t) => ProtoMT::Transaction(proto::SignedTransaction { - borsh: t.try_to_vec().unwrap(), + borsh: borsh::to_vec(&t).unwrap(), ..Default::default() }), PeerMessage::Routed(r) => ProtoMT::Routed(proto::RoutedMessage { - borsh: r.msg.try_to_vec().unwrap(), + borsh: borsh::to_vec(&r.msg).unwrap(), created_at: MF::from_option(r.created_at.as_ref().map(utc_to_proto)), num_hops: r.num_hops, ..Default::default() @@ -240,7 +240,7 @@ impl From<&PeerMessage> for proto::PeerMessage { ..Default::default() }), PeerMessage::Challenge(r) => ProtoMT::Challenge(proto::Challenge { - borsh: r.try_to_vec().unwrap(), + borsh: borsh::to_vec(&r).unwrap(), ..Default::default() }), PeerMessage::StateRequestHeader(shard_id, sync_hash) => { diff --git a/chain/network/src/store/schema/tests.rs b/chain/network/src/store/schema/tests.rs index fc642e611c2..40c319fe750 100644 --- a/chain/network/src/store/schema/tests.rs +++ b/chain/network/src/store/schema/tests.rs @@ -9,5 +9,5 @@ fn borsh_wrapper_is_transparent() { let s1 = data::make_secret_key(rng); let s2 = data::make_secret_key(rng); let e = data::make_edge(&s1, &s2, 1); - assert_eq!(Borsh(e.clone()).try_to_vec().unwrap(), e.try_to_vec().unwrap()); + assert_eq!(borsh::to_vec(&Borsh(e.clone())).unwrap(), borsh::to_vec(&e).unwrap()); } diff --git a/chain/network/src/types.rs b/chain/network/src/types.rs index 2dd1c43f6da..3a2262c8abf 100644 --- a/chain/network/src/types.rs +++ b/chain/network/src/types.rs @@ -395,7 +395,7 @@ impl< mod tests { use super::*; use crate::network_protocol::{RawRoutedMessage, RoutedMessage, RoutedMessageBody}; - use borsh::BorshSerialize as _; + const ALLOWED_SIZE: usize = 1 << 20; const NOTIFY_SIZE: usize = 1024; @@ -455,7 +455,7 @@ mod tests { fn routed_message_body_compatibility_smoke_test() { #[track_caller] fn check(msg: RoutedMessageBody, expected: &[u8]) { - let actual = msg.try_to_vec().unwrap(); + let actual = borsh::to_vec(&msg).unwrap(); assert_eq!(actual.as_slice(), expected); } diff --git a/chain/pool/src/lib.rs b/chain/pool/src/lib.rs index 803feaf9d40..3d5e6fd3395 100644 --- a/chain/pool/src/lib.rs +++ b/chain/pool/src/lib.rs @@ -2,7 +2,7 @@ use std::collections::btree_map::Entry; use std::collections::{BTreeMap, HashMap, HashSet, VecDeque}; use crate::types::{PoolIterator, PoolKey, TransactionGroup}; -use borsh::BorshSerialize; + use near_crypto::PublicKey; use near_o11y::metrics::prometheus::core::{AtomicI64, GenericGauge}; use near_primitives::epoch_manager::RngSeed; @@ -72,7 +72,7 @@ impl TransactionPool { } fn key(&self, account_id: &AccountId, public_key: &PublicKey) -> PoolKey { - let mut v = public_key.try_to_vec().unwrap(); + let mut v = borsh::to_vec(&public_key).unwrap(); v.extend_from_slice(&self.key_seed); v.extend_from_slice(account_id.as_ref().as_bytes()); hash(&v) diff --git a/chain/rosetta-rpc/src/utils.rs b/chain/rosetta-rpc/src/utils.rs index 9b55f60af01..94d8965053c 100644 --- a/chain/rosetta-rpc/src/utils.rs +++ b/chain/rosetta-rpc/src/utils.rs @@ -8,7 +8,7 @@ use futures::StreamExt; use near_chain_configs::ProtocolConfigView; use near_client::ViewClientActor; use near_o11y::WithSpanContextExt; -use near_primitives::borsh::{BorshDeserialize, BorshSerialize}; +use near_primitives::borsh::{BorshDeserialize, BorshSerialize, self}; #[derive(Debug, Clone, PartialEq, derive_more::AsRef, derive_more::From)] pub(crate) struct BorshInHexString(T); @@ -40,7 +40,7 @@ where S: serde::Serializer, { serializer.serialize_str(&hex::encode( - self.0.try_to_vec().expect("borsh serialization should never fail"), + borsh::to_vec(&self.0).expect("borsh serialization should never fail"), )) } } diff --git a/core/account-id/fuzz/fuzz_targets/borsh.rs b/core/account-id/fuzz/fuzz_targets/borsh.rs index 168e9cfe18b..08267c76f6c 100644 --- a/core/account-id/fuzz/fuzz_targets/borsh.rs +++ b/core/account-id/fuzz/fuzz_targets/borsh.rs @@ -1,6 +1,6 @@ #![no_main] -use borsh::{BorshDeserialize, BorshSerialize}; +use borsh::{BorshDeserialize}; use libfuzzer_sys::fuzz_target; use near_account_id::AccountId; @@ -8,7 +8,7 @@ fuzz_target!(|bytes: &[u8]| { if let Ok(account_id) = AccountId::try_from_slice(bytes) { assert_eq!( account_id, - AccountId::try_from_slice(account_id.try_to_vec().unwrap().as_slice()).unwrap() + AccountId::try_from_slice(borsh::to_vec(&account_id).unwrap().as_slice()).unwrap() ); } }); diff --git a/core/account-id/src/borsh.rs b/core/account-id/src/borsh.rs index de56b52cbf4..69f485c0a3f 100644 --- a/core/account-id/src/borsh.rs +++ b/core/account-id/src/borsh.rs @@ -37,7 +37,7 @@ mod tests { panic!("Valid account id {:?} marked invalid: {}", account_id, err) }); - let str_serialized_account_id = account_id.try_to_vec().unwrap(); + let str_serialized_account_id = borsh::to_vec(&account_id).unwrap(); let deserialized_account_id = AccountId::try_from_slice(&str_serialized_account_id) .unwrap_or_else(|err| { @@ -46,14 +46,14 @@ mod tests { assert_eq!(deserialized_account_id, parsed_account_id); let serialized_account_id = - deserialized_account_id.try_to_vec().unwrap_or_else(|err| { + borsh::to_vec(&deserialized_account_id).unwrap_or_else(|err| { panic!("failed to serialize account ID {:?}: {}", account_id, err) }); assert_eq!(serialized_account_id, str_serialized_account_id); } for account_id in BAD_ACCOUNT_IDS.iter() { - let str_serialized_account_id = account_id.try_to_vec().unwrap(); + let str_serialized_account_id = borsh::to_vec(&account_id).unwrap(); assert!( AccountId::try_from_slice(&str_serialized_account_id).is_err(), @@ -69,7 +69,7 @@ mod tests { if let Ok(account_id) = AccountId::try_from_slice(input) { assert_eq!( account_id, - AccountId::try_from_slice(account_id.try_to_vec().unwrap().as_slice()).unwrap() + AccountId::try_from_slice(borsh::to_vec(&account_id).unwrap().as_slice()).unwrap() ); } }); diff --git a/core/crypto/src/signature.rs b/core/crypto/src/signature.rs index efc7c7e0a8b..966559c1fb5 100644 --- a/core/crypto/src/signature.rs +++ b/core/crypto/src/signature.rs @@ -817,11 +817,11 @@ mod tests { for key_type in [KeyType::ED25519, KeyType::SECP256K1] { let sk = SecretKey::from_seed(key_type, "test"); let pk = sk.public_key(); - let bytes = pk.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&pk).unwrap(); assert_eq!(PublicKey::try_from_slice(&bytes).unwrap(), pk); let signature = sk.sign(&data); - let bytes = signature.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&signature).unwrap(); assert_eq!(Signature::try_from_slice(&bytes).unwrap(), signature); assert!(PublicKey::try_from_slice(&[0]).is_err()); diff --git a/core/primitives-core/src/account.rs b/core/primitives-core/src/account.rs index 50a3a340d52..f57eed2ed9a 100644 --- a/core/primitives-core/src/account.rs +++ b/core/primitives-core/src/account.rs @@ -234,7 +234,7 @@ pub struct FunctionCallPermission { #[cfg(test)] mod tests { - use borsh::BorshSerialize; + use crate::hash::hash; @@ -243,7 +243,7 @@ mod tests { #[test] fn test_account_serialization() { let acc = Account::new(1_000_000, 1_000_000, CryptoHash::default(), 100); - let bytes = acc.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&acc).unwrap(); assert_eq!(hash(&bytes).to_string(), "EVk5UaxBe8LQ8r8iD5EAxVBs6TJcMDKqyH7PBuho6bBJ"); } @@ -255,14 +255,14 @@ mod tests { code_hash: CryptoHash::default(), storage_usage: 300, }; - let mut old_bytes = &old_account.try_to_vec().unwrap()[..]; + let mut old_bytes = &borsh::to_vec(&old_account).unwrap()[..]; let new_account = ::deserialize(&mut old_bytes).unwrap(); assert_eq!(new_account.amount, old_account.amount); assert_eq!(new_account.locked, old_account.locked); assert_eq!(new_account.code_hash, old_account.code_hash); assert_eq!(new_account.storage_usage, old_account.storage_usage); assert_eq!(new_account.version, AccountVersion::V1); - let mut new_bytes = &new_account.try_to_vec().unwrap()[..]; + let mut new_bytes = &borsh::to_vec(&new_account).unwrap()[..]; let deserialized_account = ::deserialize(&mut new_bytes).unwrap(); assert_eq!(deserialized_account, new_account); diff --git a/core/primitives-core/src/profile.rs b/core/primitives-core/src/profile.rs index 79589deb4e6..dfbf2f77dc6 100644 --- a/core/primitives-core/src/profile.rs +++ b/core/primitives-core/src/profile.rs @@ -310,7 +310,7 @@ mod test { for (i, cost) in ActionCosts::iter().enumerate() { profile_data.add_action_cost(cost, i as Gas + 1000); } - let buf = profile_data.try_to_vec().expect("failed serializing a normal profile"); + let buf = borsh::to_vec(&profile_data).expect("failed serializing a normal profile"); let restored: ProfileDataV3 = BorshDeserialize::deserialize(&mut buf.as_slice()) .expect("failed deserializing a normal profile"); diff --git a/core/primitives/benches/serialization.rs b/core/primitives/benches/serialization.rs index 6de717a58e7..e8a26978f8d 100644 --- a/core/primitives/benches/serialization.rs +++ b/core/primitives/benches/serialization.rs @@ -2,7 +2,7 @@ extern crate bencher; use bencher::{black_box, Bencher}; -use borsh::{BorshDeserialize, BorshSerialize}; +use borsh::{BorshDeserialize}; use near_primitives::static_clock::StaticClock; use near_crypto::{KeyType, PublicKey, Signature}; @@ -79,14 +79,14 @@ fn create_account() -> Account { fn serialize_tx(bench: &mut Bencher) { let t = create_transaction(); bench.iter(|| { - let bytes = t.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&t).unwrap(); assert!(!bytes.is_empty()); }); } fn deserialize_tx(bench: &mut Bencher) { let t = create_transaction(); - let bytes = t.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&t).unwrap(); bench.iter(|| { let nt = SignedTransaction::try_from_slice(&bytes).unwrap(); assert_eq!(nt, t); @@ -96,14 +96,14 @@ fn deserialize_tx(bench: &mut Bencher) { fn serialize_block(bench: &mut Bencher) { let b = create_block(); bench.iter(|| { - let bytes = b.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&b).unwrap(); assert!(!bytes.is_empty()); }); } fn deserialize_block(bench: &mut Bencher) { let b = create_block(); - let bytes = b.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&b).unwrap(); bench.iter(|| { let nb = Block::try_from_slice(&bytes).unwrap(); assert_eq!(nb, b); @@ -113,14 +113,14 @@ fn deserialize_block(bench: &mut Bencher) { fn serialize_account(bench: &mut Bencher) { let acc = create_account(); bench.iter(|| { - let bytes = acc.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&acc).unwrap(); assert!(!bytes.is_empty()); }); } fn deserialize_account(bench: &mut Bencher) { let acc = create_account(); - let bytes = acc.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&acc).unwrap(); bench.iter(|| { let nacc = Account::try_from_slice(&bytes).unwrap(); assert_eq!(nacc, acc); diff --git a/core/primitives/src/action/delegate.rs b/core/primitives/src/action/delegate.rs index 48458b690e5..7a8c2e7dee3 100644 --- a/core/primitives/src/action/delegate.rs +++ b/core/primitives/src/action/delegate.rs @@ -72,7 +72,7 @@ impl DelegateAction { /// For more details, see: [NEP-461](https://github.com/near/NEPs/pull/461) pub fn get_nep461_hash(&self) -> CryptoHash { let signable = SignableMessage::new(&self, SignableMessageType::DelegateAction); - let bytes = signable.try_to_vec().expect("Failed to deserialize"); + let bytes = borsh::to_vec(&signable).expect("Failed to deserialize"); hash(&bytes) } } @@ -174,7 +174,7 @@ mod tests { ); let delegate_action = create_delegate_action(Vec::::new()); - let serialized_non_delegate_action = delegate_action.try_to_vec().expect("Expect ok"); + let serialized_non_delegate_action = borsh::to_vec(&delegate_action).expect("Expect ok"); // Expected Action::Delegate has not been moved in enum Action assert_eq!(serialized_non_delegate_action[0], ACTION_DELEGATE_NUMBER); @@ -188,7 +188,7 @@ mod tests { let delegate_action = create_delegate_action(vec![Action::CreateAccount(CreateAccountAction {})]); - let serialized_delegate_action = delegate_action.try_to_vec().expect("Expect ok"); + let serialized_delegate_action = borsh::to_vec(&delegate_action).expect("Expect ok"); // Valid action assert_eq!( diff --git a/core/primitives/src/block_header.rs b/core/primitives/src/block_header.rs index 6514f822273..54f318f931c 100644 --- a/core/primitives/src/block_header.rs +++ b/core/primitives/src/block_header.rs @@ -253,7 +253,7 @@ impl Approval { } pub fn get_data_for_sig(inner: &ApprovalInner, target_height: BlockHeight) -> Vec { - [inner.try_to_vec().unwrap().as_ref(), target_height.to_le_bytes().as_ref()].concat() + [borsh::to_vec(&inner).unwrap().as_ref(), target_height.to_le_bytes().as_ref()].concat() } } @@ -285,8 +285,8 @@ impl BlockHeaderV1 { pub fn init(&mut self) { self.hash = BlockHeader::compute_hash( self.prev_hash, - &self.inner_lite.try_to_vec().expect("Failed to serialize"), - &self.inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&self.inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&self.inner_rest).expect("Failed to serialize"), ); } } @@ -353,8 +353,8 @@ impl BlockHeaderV2 { pub fn init(&mut self) { self.hash = BlockHeader::compute_hash( self.prev_hash, - &self.inner_lite.try_to_vec().expect("Failed to serialize"), - &self.inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&self.inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&self.inner_rest).expect("Failed to serialize"), ); } } @@ -363,8 +363,8 @@ impl BlockHeaderV3 { pub fn init(&mut self) { self.hash = BlockHeader::compute_hash( self.prev_hash, - &self.inner_lite.try_to_vec().expect("Failed to serialize"), - &self.inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&self.inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&self.inner_rest).expect("Failed to serialize"), ); } } @@ -373,8 +373,8 @@ impl BlockHeaderV4 { pub fn init(&mut self) { self.hash = BlockHeader::compute_hash( self.prev_hash, - &self.inner_lite.try_to_vec().expect("Failed to serialize"), - &self.inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&self.inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&self.inner_rest).expect("Failed to serialize"), ); } } @@ -471,8 +471,8 @@ impl BlockHeader { }; let (hash, signature) = signer.sign_block_header_parts( prev_hash, - &inner_lite.try_to_vec().expect("Failed to serialize"), - &inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&inner_rest).expect("Failed to serialize"), ); Self::BlockHeaderV1(Arc::new(BlockHeaderV1 { prev_hash, @@ -500,8 +500,8 @@ impl BlockHeader { }; let (hash, signature) = signer.sign_block_header_parts( prev_hash, - &inner_lite.try_to_vec().expect("Failed to serialize"), - &inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&inner_rest).expect("Failed to serialize"), ); Self::BlockHeaderV2(Arc::new(BlockHeaderV2 { prev_hash, @@ -532,8 +532,8 @@ impl BlockHeader { }; let (hash, signature) = signer.sign_block_header_parts( prev_hash, - &inner_lite.try_to_vec().expect("Failed to serialize"), - &inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&inner_rest).expect("Failed to serialize"), ); Self::BlockHeaderV3(Arc::new(BlockHeaderV3 { prev_hash, @@ -565,8 +565,8 @@ impl BlockHeader { }; let (hash, signature) = signer.sign_block_header_parts( prev_hash, - &inner_lite.try_to_vec().expect("Failed to serialize"), - &inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&inner_rest).expect("Failed to serialize"), ); Self::BlockHeaderV4(Arc::new(BlockHeaderV4 { prev_hash, @@ -626,8 +626,8 @@ impl BlockHeader { }; let hash = BlockHeader::compute_hash( CryptoHash::default(), - &inner_lite.try_to_vec().expect("Failed to serialize"), - &inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&inner_rest).expect("Failed to serialize"), ); Self::BlockHeaderV1(Arc::new(BlockHeaderV1 { prev_hash: CryptoHash::default(), @@ -655,8 +655,8 @@ impl BlockHeader { }; let hash = BlockHeader::compute_hash( CryptoHash::default(), - &inner_lite.try_to_vec().expect("Failed to serialize"), - &inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&inner_rest).expect("Failed to serialize"), ); Self::BlockHeaderV2(Arc::new(BlockHeaderV2 { prev_hash: CryptoHash::default(), @@ -687,8 +687,8 @@ impl BlockHeader { }; let hash = BlockHeader::compute_hash( CryptoHash::default(), - &inner_lite.try_to_vec().expect("Failed to serialize"), - &inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&inner_rest).expect("Failed to serialize"), ); Self::BlockHeaderV3(Arc::new(BlockHeaderV3 { prev_hash: CryptoHash::default(), @@ -720,8 +720,8 @@ impl BlockHeader { }; let hash = BlockHeader::compute_hash( CryptoHash::default(), - &inner_lite.try_to_vec().expect("Failed to serialize"), - &inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&inner_rest).expect("Failed to serialize"), ); Self::BlockHeaderV4(Arc::new(BlockHeaderV4 { prev_hash: CryptoHash::default(), @@ -1074,16 +1074,16 @@ impl BlockHeader { pub fn inner_lite_bytes(&self) -> Vec { match self { BlockHeader::BlockHeaderV1(header) => { - header.inner_lite.try_to_vec().expect("Failed to serialize") + borsh::to_vec(&header.inner_lite).expect("Failed to serialize") } BlockHeader::BlockHeaderV2(header) => { - header.inner_lite.try_to_vec().expect("Failed to serialize") + borsh::to_vec(&header.inner_lite).expect("Failed to serialize") } BlockHeader::BlockHeaderV3(header) => { - header.inner_lite.try_to_vec().expect("Failed to serialize") + borsh::to_vec(&header.inner_lite).expect("Failed to serialize") } BlockHeader::BlockHeaderV4(header) => { - header.inner_lite.try_to_vec().expect("Failed to serialize") + borsh::to_vec(&header.inner_lite).expect("Failed to serialize") } } } @@ -1091,16 +1091,16 @@ impl BlockHeader { pub fn inner_rest_bytes(&self) -> Vec { match self { BlockHeader::BlockHeaderV1(header) => { - header.inner_rest.try_to_vec().expect("Failed to serialize") + borsh::to_vec(&header.inner_rest).expect("Failed to serialize") } BlockHeader::BlockHeaderV2(header) => { - header.inner_rest.try_to_vec().expect("Failed to serialize") + borsh::to_vec(&header.inner_rest).expect("Failed to serialize") } BlockHeader::BlockHeaderV3(header) => { - header.inner_rest.try_to_vec().expect("Failed to serialize") + borsh::to_vec(&header.inner_rest).expect("Failed to serialize") } BlockHeader::BlockHeaderV4(header) => { - header.inner_rest.try_to_vec().expect("Failed to serialize") + borsh::to_vec(&header.inner_rest).expect("Failed to serialize") } } } diff --git a/core/primitives/src/sharding.rs b/core/primitives/src/sharding.rs index b2a8de533e6..b5d0de8d8a3 100644 --- a/core/primitives/src/sharding.rs +++ b/core/primitives/src/sharding.rs @@ -104,7 +104,7 @@ impl ShardChunkHeaderV2 { } pub fn compute_hash(inner: &ShardChunkHeaderInnerV1) -> ChunkHash { - let inner_bytes = inner.try_to_vec().expect("Failed to serialize"); + let inner_bytes = borsh::to_vec(&inner).expect("Failed to serialize"); let inner_hash = hash(&inner_bytes); ChunkHash(combine_hash(&inner_hash, &inner.encoded_merkle_root)) @@ -168,7 +168,7 @@ impl ShardChunkHeaderV3 { } pub fn compute_hash(inner: &ShardChunkHeaderInner) -> ChunkHash { - let inner_bytes = inner.try_to_vec().expect("Failed to serialize"); + let inner_bytes = borsh::to_vec(&inner).expect("Failed to serialize"); let inner_hash = hash(&inner_bytes); ChunkHash(combine_hash(&inner_hash, inner.encoded_merkle_root())) @@ -230,9 +230,9 @@ impl ShardChunkHeader { pub fn inner_header_hash(&self) -> CryptoHash { let inner_bytes = match self { - Self::V1(header) => header.inner.try_to_vec(), - Self::V2(header) => header.inner.try_to_vec(), - Self::V3(header) => header.inner.try_to_vec(), + Self::V1(header) => borsh::to_vec(&header.inner), + Self::V2(header) => borsh::to_vec(&header.inner), + Self::V3(header) => borsh::to_vec(&header.inner), }; hash(&inner_bytes.expect("Failed to serialize")) } @@ -417,7 +417,7 @@ impl ShardChunkHeaderV1 { } pub fn compute_hash(inner: &ShardChunkHeaderInnerV1) -> ChunkHash { - let inner_bytes = inner.try_to_vec().expect("Failed to serialize"); + let inner_bytes = borsh::to_vec(&inner).expect("Failed to serialize"); let inner_hash = hash(&inner_bytes); ChunkHash(inner_hash) @@ -940,7 +940,7 @@ impl EncodedShardChunk { outgoing_receipts: &[Receipt], ) -> Result<(Vec>>, u64), std::io::Error> { let mut bytes = - TransactionReceipt(transactions, outgoing_receipts.to_vec()).try_to_vec()?; + borsh::to_vec(&TransactionReceipt(transactions, outgoing_receipts.to_vec()))?; let mut parts = Vec::with_capacity(rs.total_shard_count()); let data_parts = rs.data_shard_count(); diff --git a/core/primitives/src/signable_message.rs b/core/primitives/src/signable_message.rs index db97eb1fdae..124eb4f6d53 100644 --- a/core/primitives/src/signable_message.rs +++ b/core/primitives/src/signable_message.rs @@ -95,7 +95,7 @@ impl<'a, T: BorshSerialize> SignableMessage<'a, T> { } pub fn sign(&self, signer: &dyn Signer) -> Signature { - let bytes = self.try_to_vec().expect("Failed to deserialize"); + let bytes = borsh::to_vec(&self).expect("Failed to deserialize"); let hash = hash(&bytes); signer.sign(hash.as_bytes()) } diff --git a/core/primitives/src/transaction.rs b/core/primitives/src/transaction.rs index ee2afe3c9de..a6f8aa2a70c 100644 --- a/core/primitives/src/transaction.rs +++ b/core/primitives/src/transaction.rs @@ -48,7 +48,7 @@ pub struct Transaction { impl Transaction { /// Computes a hash of the transaction for signing and size of serialized transaction pub fn get_hash_and_size(&self) -> (CryptoHash, u64) { - let bytes = self.try_to_vec().expect("Failed to deserialize"); + let bytes = borsh::to_vec(&self).expect("Failed to deserialize"); (hash(&bytes), bytes.len() as u64) } } @@ -313,7 +313,7 @@ mod tests { let invalid_keys = vec![wrong_public_key]; assert!(!verify_transaction_signature(&transaction, &invalid_keys)); - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); let decoded_tx = SignedTransaction::try_from_slice(&bytes).unwrap(); assert!(verify_transaction_signature(&decoded_tx, &valid_keys)); } @@ -362,7 +362,7 @@ mod tests { }; let signed_tx = SignedTransaction::new(Signature::empty(KeyType::ED25519), transaction); let new_signed_tx = - SignedTransaction::try_from_slice(&signed_tx.try_to_vec().unwrap()).unwrap(); + SignedTransaction::try_from_slice(&borsh::to_vec(&signed_tx).unwrap()).unwrap(); assert_eq!( new_signed_tx.get_hash().to_string(), diff --git a/core/primitives/src/trie_key.rs b/core/primitives/src/trie_key.rs index 6e1b3e6bf24..3dbdf9f04b3 100644 --- a/core/primitives/src/trie_key.rs +++ b/core/primitives/src/trie_key.rs @@ -163,7 +163,7 @@ impl TrieKey { buf.push(col::ACCESS_KEY); buf.extend(account_id.as_ref().as_bytes()); buf.push(col::ACCESS_KEY); - buf.extend(public_key.try_to_vec().unwrap()); + buf.extend(borsh::to_vec(&public_key).unwrap()); } TrieKey::ReceivedData { receiver_id, data_id } => { buf.push(col::RECEIVED_DATA); diff --git a/core/primitives/src/views.rs b/core/primitives/src/views.rs index b4db20805ba..e31614fa532 100644 --- a/core/primitives/src/views.rs +++ b/core/primitives/src/views.rs @@ -2035,7 +2035,7 @@ impl LightClientBlockLiteView { let block_header_inner_lite: BlockHeaderInnerLite = self.inner_lite.clone().into(); combine_hash( &combine_hash( - &hash(&block_header_inner_lite.try_to_vec().unwrap()), + &hash(&borsh::to_vec(&block_header_inner_lite).unwrap()), &self.inner_rest_hash, ), &self.prev_block_hash, diff --git a/core/store/src/cold_storage.rs b/core/store/src/cold_storage.rs index f567e8f3f64..03a49ce35c9 100644 --- a/core/store/src/cold_storage.rs +++ b/core/store/src/cold_storage.rs @@ -3,7 +3,7 @@ use crate::db::{ColdDB, COLD_HEAD_KEY, HEAD_KEY}; use crate::trie::TrieRefcountChange; use crate::{metrics, DBCol, DBTransaction, Database, Store, TrieChanges}; -use borsh::{BorshDeserialize, BorshSerialize}; +use borsh::{BorshDeserialize}; use near_primitives::block::{Block, BlockHeader, Tip}; use near_primitives::hash::CryptoHash; use near_primitives::shard_layout::ShardLayout; @@ -167,21 +167,21 @@ pub fn update_cold_head( // Write HEAD to the cold db. { let mut transaction = DBTransaction::new(); - transaction.set(DBCol::BlockMisc, HEAD_KEY.to_vec(), tip.try_to_vec()?); + transaction.set(DBCol::BlockMisc, HEAD_KEY.to_vec(), borsh::to_vec(&tip)?); cold_db.write(transaction)?; } // Write COLD_HEAD_KEY to the cold db. { let mut transaction = DBTransaction::new(); - transaction.set(DBCol::BlockMisc, COLD_HEAD_KEY.to_vec(), tip.try_to_vec()?); + transaction.set(DBCol::BlockMisc, COLD_HEAD_KEY.to_vec(), borsh::to_vec(&tip)?); cold_db.write(transaction)?; } // Write COLD_HEAD to the hot db. { let mut transaction = DBTransaction::new(); - transaction.set(DBCol::BlockMisc, COLD_HEAD_KEY.to_vec(), tip.try_to_vec()?); + transaction.set(DBCol::BlockMisc, COLD_HEAD_KEY.to_vec(), borsh::to_vec(&tip)?); hot_store.storage.write(transaction)?; crate::metrics::COLD_HEAD_HEIGHT.set(*height as i64); diff --git a/core/store/src/flat/inlining_migration.rs b/core/store/src/flat/inlining_migration.rs index 5b0c15c8919..7bb48cc4884 100644 --- a/core/store/src/flat/inlining_migration.rs +++ b/core/store/src/flat/inlining_migration.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use std::thread::JoinHandle; use std::time::Duration; -use borsh::{BorshDeserialize, BorshSerialize}; +use borsh::{BorshDeserialize}; use crossbeam::channel; use itertools::Itertools; use near_primitives::hash::CryptoHash; @@ -258,8 +258,7 @@ pub fn inline_flat_state_values( store_update.set( DBCol::FlatState, &key, - &FlatStateValue::inlined(value) - .try_to_vec() + &borsh::to_vec(&FlatStateValue::inlined(value)) .expect("borsh should not fail here"), ); inlined_batch_count += 1; @@ -313,7 +312,7 @@ mod tests { use crate::flat::store_helper::encode_flat_state_db_key; use crate::flat::{FlatStateValuesInliningMigrationHandle, FlatStorageManager}; use crate::{DBCol, NodeStorage, Store, TrieCachingStorage}; - use borsh::{BorshDeserialize, BorshSerialize}; + use borsh::{BorshDeserialize}; use near_o11y::testonly::init_test_logger; use near_primitives::hash::{hash, CryptoHash}; use near_primitives::shard_layout::{ShardLayout, ShardUId}; @@ -448,7 +447,7 @@ mod tests { TrieCachingStorage::get_key_from_shard_uid_and_hash(shard_uid, &hash(&value)); store_update.increment_refcount(DBCol::State, &trie_key, &value); let fs_key = encode_flat_state_db_key(shard_uid, &[i as u8]); - let fs_value = FlatStateValue::value_ref(&value).try_to_vec().unwrap(); + let fs_value = borsh::to_vec(&FlatStateValue::value_ref(&value)).unwrap(); store_update.set(DBCol::FlatState, &fs_key, &fs_value); } store_update.commit().unwrap(); diff --git a/core/store/src/flat/storage.rs b/core/store/src/flat/storage.rs index 68de1d3911b..64b354b42ae 100644 --- a/core/store/src/flat/storage.rs +++ b/core/store/src/flat/storage.rs @@ -492,7 +492,7 @@ mod tests { use crate::test_utils::create_test_store; use crate::StorageError; use assert_matches::assert_matches; - use borsh::BorshSerialize; + use near_o11y::testonly::init_test_logger; use near_primitives::hash::{hash, CryptoHash}; use near_primitives::shard_layout::ShardUId; @@ -513,7 +513,7 @@ mod tests { } fn block_hash(height: BlockHeight) -> CryptoHash { - hash(&height.try_to_vec().unwrap()) + hash(&borsh::to_vec(&height).unwrap()) } /// Build a chain with given set of heights and a function mapping block heights to heights of their parents. diff --git a/core/store/src/genesis/state_applier.rs b/core/store/src/genesis/state_applier.rs index 1f821d96b8e..fb4df538266 100644 --- a/core/store/src/genesis/state_applier.rs +++ b/core/store/src/genesis/state_applier.rs @@ -3,7 +3,7 @@ use crate::{ get_account, get_received_data, set, set_access_key, set_account, set_code, set_delayed_receipt, set_postponed_receipt, set_received_data, ShardTries, TrieUpdate, }; -use borsh::BorshSerialize; + use near_chain_configs::Genesis; use near_crypto::PublicKey; use near_primitives::account::{AccessKey, Account}; @@ -52,8 +52,8 @@ impl<'a> StorageComputer<'a> { let public_key: PublicKey = public_key.clone(); let access_key: AccessKey = access_key.clone(); let storage_usage = self.config.num_extra_bytes_record - + public_key.try_to_vec().unwrap().len() as u64 - + access_key.try_to_vec().unwrap().len() as u64; + + borsh::to_vec(&public_key).unwrap().len() as u64 + + borsh::to_vec(&access_key).unwrap().len() as u64; Some((account_id.clone(), storage_usage)) } StateRecord::PostponedReceipt(_) => None, diff --git a/core/store/src/lib.rs b/core/store/src/lib.rs index 7fa27eece92..6d8fd3bf3c8 100644 --- a/core/store/src/lib.rs +++ b/core/store/src/lib.rs @@ -444,7 +444,7 @@ impl StoreUpdate { value: &T, ) -> io::Result<()> { assert!(column.is_insert_only(), "can't insert_ser: {column}"); - let data = value.try_to_vec()?; + let data = borsh::to_vec(&value)?; self.insert(column, key, &data); Ok(()) } @@ -522,7 +522,7 @@ impl StoreUpdate { value: &T, ) -> io::Result<()> { assert!(!(column.is_rc() || column.is_insert_only()), "can't set_ser: {column}"); - let data = value.try_to_vec()?; + let data = borsh::to_vec(&value)?; self.set(column, key, &data); Ok(()) } @@ -661,7 +661,7 @@ pub fn get( /// Writes an object into Trie. pub fn set(state_update: &mut TrieUpdate, key: TrieKey, value: &T) { - let data = value.try_to_vec().expect("Borsh serializer is not expected to ever fail"); + let data = borsh::to_vec(&value).expect("Borsh serializer is not expected to ever fail"); state_update.set(key, data); } @@ -888,7 +888,7 @@ impl CompiledContractCache for StoreCompiledContractCache { // guarantee deterministic compilation, so, if we happen to compile the // same contract concurrently on two threads, the `value`s might differ, // but this doesn't matter. - update.set(DBCol::CachedContractCode, key.as_ref().to_vec(), value.try_to_vec().unwrap()); + update.set(DBCol::CachedContractCode, key.as_ref().to_vec(), borsh::to_vec(&value).unwrap()); self.db.write(update) } diff --git a/core/store/src/migrations.rs b/core/store/src/migrations.rs index a08475dc4e0..ad7e8006dac 100644 --- a/core/store/src/migrations.rs +++ b/core/store/src/migrations.rs @@ -45,7 +45,7 @@ impl<'a> BatchedStoreUpdate<'a> { value: &T, insert: bool, ) -> std::io::Result<()> { - let value_bytes = value.try_to_vec()?; + let value_bytes = borsh::to_vec(&value)?; let entry_size = key.as_ref().len() + value_bytes.len() + 8; self.batch_size += entry_size; self.total_size_written += entry_size as u64; @@ -193,14 +193,13 @@ pub fn migrate_36_to_37(store: &Store) -> anyhow::Result<()> { update.delete_all(DBCol::FlatStateChanges); for result in store.iter(DBCol::FlatStateChanges) { let (key, old_value) = result?; - let new_value = crate::flat::FlatStateChanges( + let new_value = borsh::to_vec(&crate::flat::FlatStateChanges( LegacyFlatStateChanges::try_from_slice(&old_value)? .0 .into_iter() .map(|(key, value_ref)| (key, value_ref.map(|v| FlatStateValue::Ref(v)))) .collect(), - ) - .try_to_vec()?; + ))?; update.set(DBCol::FlatStateChanges, &key, &new_value); } update.commit()?; @@ -225,7 +224,7 @@ pub fn migrate_37_to_38(store: &Store) -> anyhow::Result<()> { LegacyFlatStateDeltaMetadata::try_from_slice(&old_value)?; let new_value = crate::flat::FlatStateDeltaMetadata { block, prev_block_with_changes: None }; - update.set(DBCol::FlatStateDeltaMetadata, &key, &new_value.try_to_vec()?); + update.set(DBCol::FlatStateDeltaMetadata, &key, &borsh::to_vec(&new_value)?); } update.commit()?; Ok(()) diff --git a/core/store/src/trie/mod.rs b/core/store/src/trie/mod.rs index b20088d98d7..1a90a638967 100644 --- a/core/store/src/trie/mod.rs +++ b/core/store/src/trie/mod.rs @@ -1094,7 +1094,7 @@ impl TrieAccess for Trie { /// Methods used in the runtime-parameter-estimator for measuring trie internal /// operations. pub mod estimator { - use borsh::{BorshDeserialize, BorshSerialize}; + use borsh::{BorshDeserialize}; use near_primitives::hash::CryptoHash; /// Create an encoded extension node with the given value as the key. @@ -1103,7 +1103,7 @@ pub mod estimator { let hash = CryptoHash::hash_bytes(&key); let node = super::RawTrieNode::Extension(key, hash); let node = super::RawTrieNodeWithSize { node, memory_usage: 1 }; - node.try_to_vec().unwrap() + borsh::to_vec(&node).unwrap() } /// Decode am extension node and return its inner key. /// This serves no purpose other than for the estimator. diff --git a/core/store/src/trie/raw_node.rs b/core/store/src/trie/raw_node.rs index b896adf7a1d..427e25fc3d7 100644 --- a/core/store/src/trie/raw_node.rs +++ b/core/store/src/trie/raw_node.rs @@ -116,7 +116,7 @@ fn test_encode_decode() { #[track_caller] fn test(node: RawTrieNode, encoded: &[u8]) { let node = RawTrieNodeWithSize { node, memory_usage: 42 }; - let mut buf = node.try_to_vec().unwrap(); + let mut buf = borsh::to_vec(&node).unwrap(); assert_eq!(encoded, buf.as_slice()); assert_eq!(node, RawTrieNodeWithSize::try_from_slice(&buf).unwrap()); diff --git a/core/store/src/trie/shard_tries.rs b/core/store/src/trie/shard_tries.rs index a66193a2c54..d6d67124dbc 100644 --- a/core/store/src/trie/shard_tries.rs +++ b/core/store/src/trie/shard_tries.rs @@ -8,7 +8,7 @@ use crate::trie::{TrieRefcountChange, POISONED_LOCK_ERR}; use crate::Mode; use crate::{checkpoint_hot_storage_and_cleanup_columns, metrics, DBCol, NodeStorage, PrefetchApi}; use crate::{Store, StoreConfig, StoreUpdate, Trie, TrieChanges, TrieUpdate}; -use borsh::BorshSerialize; + use near_primitives::block::Block; use near_primitives::errors::EpochError; use near_primitives::errors::StorageError; @@ -825,7 +825,7 @@ impl WrappedTrieChanges { store_update.set( DBCol::StateChanges, storage_key.as_ref(), - &change_with_trie_key.try_to_vec().expect("Borsh serialize cannot fail"), + &borsh::to_vec(&change_with_trie_key).expect("Borsh serialize cannot fail"), ); } } diff --git a/core/store/src/trie/split_state.rs b/core/store/src/trie/split_state.rs index 63e427ffaf4..8eea5994b5d 100644 --- a/core/store/src/trie/split_state.rs +++ b/core/store/src/trie/split_state.rs @@ -324,7 +324,7 @@ mod tests { use crate::{set, ShardTries, ShardUId, Trie}; use near_primitives::account::id::AccountId; - use near_primitives::borsh::BorshSerialize; + use near_primitives::hash::hash; use near_primitives::receipt::{DelayedReceiptIndices, Receipt}; use near_primitives::trie_key::TrieKey; @@ -416,10 +416,10 @@ mod tests { let total_memory_use = receipts .iter() - .fold(0_u64, |sum, receipt| sum + receipt.try_to_vec().unwrap().len() as u64); + .fold(0_u64, |sum, receipt| sum + borsh::to_vec(&receipt).unwrap().len() as u64); let memory_use_without_last_receipt = receipts[..receipts.len() - 1] .iter() - .fold(0_u64, |sum, receipt| sum + receipt.try_to_vec().unwrap().len() as u64); + .fold(0_u64, |sum, receipt| sum + borsh::to_vec(&receipt).unwrap().len() as u64); assert!( total_memory_use >= memory_limit.as_u64() diff --git a/genesis-tools/genesis-populate/src/state_dump.rs b/genesis-tools/genesis-populate/src/state_dump.rs index 81b9b673acc..39fd22dc47a 100644 --- a/genesis-tools/genesis-populate/src/state_dump.rs +++ b/genesis-tools/genesis-populate/src/state_dump.rs @@ -1,4 +1,4 @@ -use borsh::{BorshDeserialize, BorshSerialize}; +use borsh::{BorshDeserialize}; use near_primitives::types::StateRoot; use near_store::db::TestDB; use near_store::Store; @@ -44,7 +44,7 @@ impl StateDump { let mut roots_files = dir; roots_files.push(GENESIS_ROOTS_FILE); let mut file = File::create(roots_files)?; - let data = self.roots.try_to_vec()?; + let data = borsh::to_vec(&self.roots)?; file.write_all(&data)?; } Ok(()) diff --git a/integration-tests/src/tests/client/benchmarks.rs b/integration-tests/src/tests/client/benchmarks.rs index 80113e435b3..e23cb30f46b 100644 --- a/integration-tests/src/tests/client/benchmarks.rs +++ b/integration-tests/src/tests/client/benchmarks.rs @@ -5,7 +5,7 @@ //! note the wall-clock time. use crate::tests::client::utils::TestEnvNightshadeSetupExt; -use borsh::BorshSerialize; + use near_chain::ChainGenesis; use near_chain_configs::Genesis; use near_client::test_utils::{create_chunk_on_height, TestEnv}; @@ -56,7 +56,7 @@ fn benchmark_large_chunk_production_time() { let (chunk, _, _) = create_chunk_on_height(&mut env.clients[0], 0); let time = t.elapsed(); - let size = chunk.try_to_vec().unwrap().len(); + let size = borsh::to_vec(&chunk).unwrap().len(); eprintln!("chunk size: {}kb", size / 1024); eprintln!("time to produce: {:0.2?}", time); diff --git a/integration-tests/src/tests/client/challenges.rs b/integration-tests/src/tests/client/challenges.rs index 03c070ac51a..87982b6e191 100644 --- a/integration-tests/src/tests/client/challenges.rs +++ b/integration-tests/src/tests/client/challenges.rs @@ -1,5 +1,5 @@ use assert_matches::assert_matches; -use borsh::BorshSerialize; + use near_async::messaging::CanSend; use near_network::shards_manager::ShardsManagerRequestFromNetwork; use near_primitives::test_utils::create_test_signer; @@ -47,8 +47,8 @@ fn test_block_with_challenges() { { let challenge_body = ChallengeBody::BlockDoubleSign(BlockDoubleSign { - left_block_header: genesis.header().try_to_vec().unwrap(), - right_block_header: genesis.header().try_to_vec().unwrap(), + left_block_header: borsh::to_vec(&genesis.header()).unwrap(), + right_block_header: borsh::to_vec(&genesis.header()).unwrap(), }); let challenge = Challenge::produce(challenge_body, &*signer); let challenges = vec![challenge]; @@ -139,8 +139,8 @@ fn test_verify_block_double_sign_challenge() { let epoch_id = b1.header().epoch_id().clone(); let valid_challenge = Challenge::produce( ChallengeBody::BlockDoubleSign(BlockDoubleSign { - left_block_header: b2.header().try_to_vec().unwrap(), - right_block_header: b1.header().try_to_vec().unwrap(), + left_block_header: borsh::to_vec(&b2.header()).unwrap(), + right_block_header: borsh::to_vec(&b1.header()).unwrap(), }), &signer, ); @@ -158,8 +158,8 @@ fn test_verify_block_double_sign_challenge() { ); let invalid_challenge = Challenge::produce( ChallengeBody::BlockDoubleSign(BlockDoubleSign { - left_block_header: b1.header().try_to_vec().unwrap(), - right_block_header: b1.header().try_to_vec().unwrap(), + left_block_header: borsh::to_vec(&b1.header()).unwrap(), + right_block_header: borsh::to_vec(&b1.header()).unwrap(), }), &signer, ); @@ -174,8 +174,8 @@ fn test_verify_block_double_sign_challenge() { let b3 = env.clients[0].produce_block(3).unwrap().unwrap(); let invalid_challenge = Challenge::produce( ChallengeBody::BlockDoubleSign(BlockDoubleSign { - left_block_header: b1.header().try_to_vec().unwrap(), - right_block_header: b3.header().try_to_vec().unwrap(), + left_block_header: borsh::to_vec(&b1.header()).unwrap(), + right_block_header: borsh::to_vec(&b3.header()).unwrap(), }), &signer, ); @@ -332,7 +332,7 @@ fn challenge( let merkle_paths = Block::compute_chunk_headers_root(block.chunks().iter()).1; let valid_challenge = Challenge::produce( ChallengeBody::ChunkProofs(ChunkProofs { - block_header: block.header().try_to_vec().unwrap(), + block_header: borsh::to_vec(&block.header()).unwrap(), chunk, merkle_proof: merkle_paths[shard_id].clone(), }), @@ -597,7 +597,7 @@ fn test_block_challenge() { let shard_id = chunk.cloned_header().shard_id(); let challenge = Challenge::produce( ChallengeBody::ChunkProofs(ChunkProofs { - block_header: block.header().try_to_vec().unwrap(), + block_header: borsh::to_vec(&block.header()).unwrap(), chunk: MaybeEncodedShardChunk::Encoded(chunk), merkle_proof: merkle_paths[shard_id as usize].clone(), }), @@ -649,7 +649,7 @@ fn test_fishermen_challenge() { let merkle_paths = Block::compute_chunk_headers_root(block.chunks().iter()).1; let shard_id = chunk.cloned_header().shard_id(); let challenge_body = ChallengeBody::ChunkProofs(ChunkProofs { - block_header: block.header().try_to_vec().unwrap(), + block_header: borsh::to_vec(&block.header()).unwrap(), chunk: MaybeEncodedShardChunk::Encoded(chunk), merkle_proof: merkle_paths[shard_id as usize].clone(), }); diff --git a/integration-tests/src/tests/client/features/zero_balance_account.rs b/integration-tests/src/tests/client/features/zero_balance_account.rs index 7721d7de046..8e13a1b12b0 100644 --- a/integration-tests/src/tests/client/features/zero_balance_account.rs +++ b/integration-tests/src/tests/client/features/zero_balance_account.rs @@ -1,6 +1,6 @@ use assert_matches::assert_matches; -use borsh::BorshSerialize; + use near_chain::ChainGenesis; use near_chain_configs::Genesis; use near_client::adapter::ProcessTxResponse; @@ -325,10 +325,10 @@ fn test_storage_usage_components() { const FUNCTION_ACCESS_PERMISSION_STORAGE_USAGE: usize = 98; let edwards_public_key = PublicKey::from_seed(KeyType::ED25519, "seed"); - assert_eq!(PUBLIC_KEY_STORAGE_USAGE, edwards_public_key.try_to_vec().unwrap().len()); + assert_eq!(PUBLIC_KEY_STORAGE_USAGE, borsh::to_vec(&edwards_public_key).unwrap().len()); let full_access_key = AccessKey::full_access(); - assert_eq!(FULL_ACCESS_PERMISSION_STORAGE_USAGE, full_access_key.try_to_vec().unwrap().len()); + assert_eq!(FULL_ACCESS_PERMISSION_STORAGE_USAGE, borsh::to_vec(&full_access_key).unwrap().len()); let fn_access_key = AccessKey { nonce: u64::MAX, @@ -338,7 +338,7 @@ fn test_storage_usage_components() { method_names: vec![], }), }; - assert_eq!(FUNCTION_ACCESS_PERMISSION_STORAGE_USAGE, fn_access_key.try_to_vec().unwrap().len()); + assert_eq!(FUNCTION_ACCESS_PERMISSION_STORAGE_USAGE, borsh::to_vec(&fn_access_key).unwrap().len()); let config_store = RuntimeConfigStore::new(None); let config = config_store.get_config(PROTOCOL_VERSION); diff --git a/integration-tests/src/tests/client/process_blocks.rs b/integration-tests/src/tests/client/process_blocks.rs index f7439cba042..11e46df3b85 100644 --- a/integration-tests/src/tests/client/process_blocks.rs +++ b/integration-tests/src/tests/client/process_blocks.rs @@ -2654,7 +2654,7 @@ fn test_catchup_gas_price_change() { } let rt = Arc::clone(&env.clients[1].runtime_adapter); let f = move |msg: ApplyStatePartsRequest| { - use borsh::BorshSerialize; + let store = rt.store(); let shard_id = msg.shard_uid.shard_id as ShardId; @@ -2664,7 +2664,7 @@ fn test_catchup_gas_price_change() { .remove_flat_storage_for_shard(msg.shard_uid) .unwrap()); for part_id in 0..msg.num_parts { - let key = StatePartKey(msg.sync_hash, shard_id, part_id).try_to_vec().unwrap(); + let key = borsh::to_vec(&StatePartKey(msg.sync_hash, shard_id, part_id)).unwrap(); let part = store.get(DBCol::StateParts, &key).unwrap().unwrap(); rt.apply_state_part( @@ -3358,7 +3358,7 @@ fn test_not_broadcast_block_on_accept() { #[test] fn test_header_version_downgrade() { init_test_logger(); - use borsh::ser::BorshSerialize; + let mut genesis = Genesis::test(vec!["test0".parse().unwrap(), "test1".parse().unwrap()], 1); genesis.config.epoch_length = 5; let chain_genesis = ChainGenesis::new(&genesis); @@ -3385,8 +3385,8 @@ fn test_header_version_downgrade() { header.inner_rest.latest_protocol_version = PROTOCOL_VERSION; let (hash, signature) = validator_signer.sign_block_header_parts( header.prev_hash, - &header.inner_lite.try_to_vec().expect("Failed to serialize"), - &header.inner_rest.try_to_vec().expect("Failed to serialize"), + &borsh::to_vec(&header.inner_lite).expect("Failed to serialize"), + &borsh::to_vec(&header.inner_rest).expect("Failed to serialize"), ); header.hash = hash; header.signature = signature; diff --git a/integration-tests/src/tests/client/sharding_upgrade.rs b/integration-tests/src/tests/client/sharding_upgrade.rs index 93627cd862d..4ffd9b2e7a1 100644 --- a/integration-tests/src/tests/client/sharding_upgrade.rs +++ b/integration-tests/src/tests/client/sharding_upgrade.rs @@ -1,4 +1,4 @@ -use borsh::BorshSerialize; + use near_client::{Client, ProcessTxResponse}; use near_primitives::epoch_manager::{AllEpochConfig, EpochConfig}; use near_primitives_core::num_rational::Rational32; @@ -920,7 +920,7 @@ fn gen_cross_contract_transaction( }, "id": 0 }, {"action_add_key_with_full_access": { "promise_index": 0, - "public_key": to_base64(&signer_new_account.public_key.try_to_vec().unwrap()), + "public_key": to_base64(&borsh::to_vec(&signer_new_account.public_key).unwrap()), "nonce": 0, }, "id": 0 } ], diff --git a/integration-tests/src/tests/client/state_dump.rs b/integration-tests/src/tests/client/state_dump.rs index 38dace0172b..e0b65febef9 100644 --- a/integration-tests/src/tests/client/state_dump.rs +++ b/integration-tests/src/tests/client/state_dump.rs @@ -1,5 +1,5 @@ use assert_matches::assert_matches; -use borsh::BorshSerialize; + use near_chain::near_chain_primitives::error::QueryError; use near_chain::types::RuntimeAdapter; use near_chain::{ChainGenesis, Provenance}; @@ -344,7 +344,7 @@ fn run_state_sync_with_dumped_parts( .unwrap()); for part_id in 0..num_parts { - let key = StatePartKey(sync_hash, 0, part_id).try_to_vec().unwrap(); + let key = borsh::to_vec(&StatePartKey(sync_hash, 0, part_id)).unwrap(); let part = client_0_store.get(DBCol::StateParts, &key).unwrap().unwrap(); runtime_client_1 diff --git a/integration-tests/src/tests/nearcore/rpc_error_structs.rs b/integration-tests/src/tests/nearcore/rpc_error_structs.rs index f1b36ef7cae..d6dcb9fbb10 100644 --- a/integration-tests/src/tests/nearcore/rpc_error_structs.rs +++ b/integration-tests/src/tests/nearcore/rpc_error_structs.rs @@ -1,7 +1,7 @@ use std::str::FromStr; use actix::{Actor, System}; -use borsh::BorshSerialize; + use futures::{future, FutureExt, TryFutureExt}; use crate::genesis_helpers::genesis_block; @@ -384,7 +384,7 @@ fn test_tx_invalid_tx_error() { if let Ok(Ok(block)) = res { if block.header.height > 10 { let client = new_client(&format!("http://{}", rpc_addrs_copy[2])); - let bytes = transaction_copy.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction_copy).unwrap(); spawn_interruptible( client .EXPERIMENTAL_broadcast_tx_sync(to_base64(&bytes)) diff --git a/integration-tests/src/tests/nearcore/rpc_nodes.rs b/integration-tests/src/tests/nearcore/rpc_nodes.rs index 4bcdf919f1d..48db32b172f 100644 --- a/integration-tests/src/tests/nearcore/rpc_nodes.rs +++ b/integration-tests/src/tests/nearcore/rpc_nodes.rs @@ -3,7 +3,7 @@ use crate::tests::nearcore::node_cluster::NodeCluster; use actix::clock::sleep; use actix::{Actor, System}; use assert_matches::assert_matches; -use borsh::BorshSerialize; + use futures::future::join_all; use futures::{future, FutureExt, TryFutureExt}; use near_actix_test_utils::spawn_interruptible; @@ -133,7 +133,7 @@ fn test_get_execution_outcome(is_tx_successful: bool) { WaitOrTimeoutActor::new( Box::new(move |_ctx| { let client = new_client(&format!("http://{}", rpc_addrs[0])); - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); let view_client1 = view_client.clone(); spawn_interruptible(client.broadcast_tx_commit(to_base64(&bytes)).then( move |res| { @@ -378,7 +378,7 @@ fn test_tx_not_enough_balance_must_return_error() { ); let client = new_client(&format!("http://{}", rpc_addrs[0])); - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); spawn_interruptible(async move { loop { @@ -443,7 +443,7 @@ fn test_send_tx_sync_returns_transaction_hash() { let client = new_client(&format!("http://{}", rpc_addrs[0])); let tx_hash = transaction.get_hash(); - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); spawn_interruptible(async move { loop { @@ -492,7 +492,7 @@ fn test_send_tx_sync_to_lightclient_must_be_routed() { let client = new_client(&format!("http://{}", rpc_addrs[1])); let tx_hash = transaction.get_hash(); - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); spawn_interruptible(async move { loop { @@ -552,7 +552,7 @@ fn test_check_unknown_tx_must_return_error() { let client = new_client(&format!("http://{}", rpc_addrs[0])); let tx_hash = transaction.get_hash(); - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); spawn_interruptible(async move { loop { @@ -609,7 +609,7 @@ fn test_check_tx_on_lightclient_must_return_does_not_track_shard() { ); let client = new_client(&format!("http://{}", rpc_addrs[1])); - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); spawn_interruptible(async move { loop { diff --git a/integration-tests/src/tests/nearcore/sync_state_nodes.rs b/integration-tests/src/tests/nearcore/sync_state_nodes.rs index a52fc574466..1d6b54b9f4a 100644 --- a/integration-tests/src/tests/nearcore/sync_state_nodes.rs +++ b/integration-tests/src/tests/nearcore/sync_state_nodes.rs @@ -695,7 +695,7 @@ fn test_dump_epoch_missing_chunk_in_last_block() { } let rt = Arc::clone(&env.clients[1].runtime_adapter); let f = move |msg: ApplyStatePartsRequest| { - use borsh::BorshSerialize; + let store = rt.store(); let shard_id = msg.shard_uid.shard_id as ShardId; @@ -707,7 +707,7 @@ fn test_dump_epoch_missing_chunk_in_last_block() { .unwrap()); for part_id in 0..msg.num_parts { - let key = StatePartKey(msg.sync_hash, shard_id, part_id).try_to_vec().unwrap(); + let key = borsh::to_vec(&StatePartKey(msg.sync_hash, shard_id, part_id)).unwrap(); let part = store.get(DBCol::StateParts, &key).unwrap().unwrap(); rt.apply_state_part( diff --git a/integration-tests/src/user/rpc_user.rs b/integration-tests/src/user/rpc_user.rs index fb2f2ce6a4a..6c14959403d 100644 --- a/integration-tests/src/user/rpc_user.rs +++ b/integration-tests/src/user/rpc_user.rs @@ -2,7 +2,7 @@ use std::sync::Arc; use std::thread; use std::time::Duration; -use borsh::BorshSerialize; + use futures::{Future, TryFutureExt}; use near_client::StatusResponse; @@ -116,7 +116,7 @@ impl User for RpcUser { } fn add_transaction(&self, transaction: SignedTransaction) -> Result<(), ServerError> { - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); let _ = self.actix(move |client| client.broadcast_tx_async(to_base64(&bytes))).map_err( |err| { serde_json::from_value::( @@ -132,7 +132,7 @@ impl User for RpcUser { &self, transaction: SignedTransaction, ) -> Result { - let bytes = transaction.try_to_vec().unwrap(); + let bytes = borsh::to_vec(&transaction).unwrap(); let result = self.actix(move |client| client.broadcast_tx_commit(to_base64(&bytes))); // Wait for one more block, to make sure all nodes actually apply the state transition. let height = self.get_best_height().unwrap(); diff --git a/nearcore/src/entity_debug.rs b/nearcore/src/entity_debug.rs index fb9ddbfccef..14b72f6ccc6 100644 --- a/nearcore/src/entity_debug.rs +++ b/nearcore/src/entity_debug.rs @@ -1,6 +1,6 @@ use crate::entity_debug_serializer::serialize_entity; use anyhow::anyhow; -use borsh::BorshSerialize; + use near_chain::types::RuntimeAdapter; use near_chain::{Block, BlockHeader}; use near_epoch_manager::EpochManagerAdapter; @@ -44,7 +44,7 @@ impl EntityDebugHandlerImpl { EntityQuery::BlockByHash { block_hash } => { let block = self .store - .get_ser::(DBCol::Block, &block_hash.try_to_vec().unwrap())? + .get_ser::(DBCol::Block, &borsh::to_vec(&block_hash).unwrap())? .ok_or_else(|| anyhow!("Block not found"))?; let author = self .epoch_manager @@ -54,21 +54,21 @@ impl EntityDebugHandlerImpl { EntityQuery::BlockHashByHeight { block_height } => { let block_hash = self .store - .get_ser::(DBCol::BlockHeight, &block_height.try_to_vec().unwrap())? + .get_ser::(DBCol::BlockHeight, &borsh::to_vec(&block_height).unwrap())? .ok_or_else(|| anyhow!("Block height not found"))?; Ok(serialize_entity(&block_hash)) } EntityQuery::BlockHeaderByHash { block_hash } => { let block_header = self .store - .get_ser::(DBCol::BlockHeader, &block_hash.try_to_vec().unwrap())? + .get_ser::(DBCol::BlockHeader, &borsh::to_vec(&block_hash).unwrap())? .ok_or_else(|| anyhow!("Block header not found"))?; Ok(serialize_entity(&BlockHeaderView::from(block_header))) } EntityQuery::ChunkByHash { chunk_hash } => { let chunk = self .store - .get_ser::(DBCol::Chunks, &chunk_hash.try_to_vec().unwrap())? + .get_ser::(DBCol::Chunks, &borsh::to_vec(&chunk_hash).unwrap())? .ok_or_else(|| anyhow!("Chunk not found"))?; let epoch_id = self.epoch_manager.get_epoch_id_from_prev_block(chunk.prev_block())?; @@ -99,7 +99,7 @@ impl EntityDebugHandlerImpl { .store .get_ser::( DBCol::FlatStateChanges, - &KeyForFlatStateDelta { block_hash, shard_uid }.try_to_vec().unwrap(), + &borsh::to_vec(&KeyForFlatStateDelta { block_hash, shard_uid }).unwrap(), )? .ok_or_else(|| anyhow!("Flat state changes not found"))?; let mut changes_view = Vec::new(); @@ -118,7 +118,7 @@ impl EntityDebugHandlerImpl { .store .get_ser::( DBCol::FlatStateDeltaMetadata, - &KeyForFlatStateDelta { block_hash, shard_uid }.try_to_vec().unwrap(), + &borsh::to_vec(&KeyForFlatStateDelta { block_hash, shard_uid }).unwrap(), )? .ok_or_else(|| anyhow!("Flat state delta metadata not found"))?; Ok(serialize_entity(&metadata)) @@ -128,7 +128,7 @@ impl EntityDebugHandlerImpl { .store .get_ser::( DBCol::FlatStorageStatus, - &shard_uid.try_to_vec().unwrap(), + &borsh::to_vec(&shard_uid).unwrap(), )? .ok_or_else(|| anyhow!("Flat storage status not found"))?; Ok(serialize_entity(&status)) @@ -139,7 +139,7 @@ impl EntityDebugHandlerImpl { .store .iter_prefix_ser::( DBCol::TransactionResultForBlock, - &outcome_id.try_to_vec().unwrap(), + &borsh::to_vec(&outcome_id).unwrap(), ) .next() .ok_or_else(|| anyhow!("Outcome not found"))??; @@ -162,7 +162,7 @@ impl EntityDebugHandlerImpl { EntityQuery::ReceiptById { receipt_id } => { let receipt = self .store - .get_ser::(DBCol::Receipts, &receipt_id.try_to_vec().unwrap())? + .get_ser::(DBCol::Receipts, &borsh::to_vec(&receipt_id).unwrap())? .ok_or_else(|| anyhow!("Receipt not found"))?; Ok(serialize_entity(&ReceiptView::from(receipt))) } @@ -209,7 +209,7 @@ impl EntityDebugHandlerImpl { .store .get_ser::( DBCol::Transactions, - &transaction_hash.try_to_vec().unwrap(), + &borsh::to_vec(&transaction_hash).unwrap(), )? .ok_or_else(|| anyhow!("Transaction not found"))?; Ok(serialize_entity(&SignedTransactionView::from(transaction))) @@ -313,7 +313,7 @@ impl EntityDebugHandlerImpl { EntityQuery::TrieRootByChunkHash { chunk_hash } => { let chunk = self .store - .get_ser::(DBCol::Chunks, &chunk_hash.try_to_vec().unwrap())? + .get_ser::(DBCol::Chunks, &borsh::to_vec(&chunk_hash).unwrap())? .ok_or_else(|| anyhow!("Chunk not found"))?; let shard_layout = self .epoch_manager diff --git a/nearcore/src/runtime/mod.rs b/nearcore/src/runtime/mod.rs index 64ab59d9b7e..7090eb9cce5 100644 --- a/nearcore/src/runtime/mod.rs +++ b/nearcore/src/runtime/mod.rs @@ -1,7 +1,7 @@ use crate::metrics; use crate::migrations::load_migration_data; use crate::NearConfig; -use borsh::ser::BorshSerialize; + use borsh::BorshDeserialize; use errors::FromStateViewerErrors; use near_chain::types::{ApplySplitStateResult, ApplyTransactionResult, RuntimeAdapter, Tip}; @@ -551,14 +551,13 @@ impl NightshadeRuntime { .tries .get_trie_with_block_hash_for_shard_from_snapshot(shard_uid, *state_root, &prev_hash) .map_err(|err| Error::Other(err.to_string()))?; - let state_part = match snapshot_trie.get_trie_nodes_for_part_with_flat_storage(part_id, partial_state, nibbles_begin, nibbles_end, &trie_with_state) { + let state_part = borsh::to_vec(&match snapshot_trie.get_trie_nodes_for_part_with_flat_storage(part_id, partial_state, nibbles_begin, nibbles_end, &trie_with_state) { Ok(partial_state) => partial_state, Err(err) => { error!(target: "runtime", ?err, part_id.idx, part_id.total, %prev_hash, %state_root, %shard_id, "Can't get trie nodes for state part"); return Err(err.into()); } - } - .try_to_vec() + }) .expect("serializer should not fail"); Ok(state_part) diff --git a/nearcore/src/state_sync.rs b/nearcore/src/state_sync.rs index 0e05a2a2f84..42648f39f7e 100644 --- a/nearcore/src/state_sync.rs +++ b/nearcore/src/state_sync.rs @@ -1,5 +1,5 @@ use crate::metrics; -use borsh::BorshSerialize; + use near_chain::types::RuntimeAdapter; use near_chain::{Chain, ChainGenesis, ChainStoreAccess, DoomslugThresholdMode, Error}; use near_chain_configs::{ClientConfig, ExternalStorageLocation}; @@ -466,7 +466,7 @@ fn obtain_and_store_state_part( PartId::new(part_id, num_parts), )?; - let key = StatePartKey(sync_hash, shard_id, part_id).try_to_vec()?; + let key = borsh::to_vec(&StatePartKey(sync_hash, shard_id, part_id))?; let mut store_update = chain.store().store().store_update(); store_update.set(DBCol::StateParts, &key, &state_part); store_update.commit()?; diff --git a/runtime/near-vm-runner/src/logic/tests/gas_counter.rs b/runtime/near-vm-runner/src/logic/tests/gas_counter.rs index 22838924b5c..b77f2f01277 100644 --- a/runtime/near-vm-runner/src/logic/tests/gas_counter.rs +++ b/runtime/near-vm-runner/src/logic/tests/gas_counter.rs @@ -3,7 +3,7 @@ use crate::logic::tests::vm_logic_builder::{TestVMLogic, VMLogicBuilder}; use crate::logic::types::Gas; use crate::logic::{Config, MemSlice}; use crate::logic::{HostError, VMLogicError}; -use borsh::BorshSerialize; + use expect_test::expect; use near_primitives_core::config::{ActionCosts, ExtCosts}; use near_primitives_core::runtime::fees::Fee; @@ -722,10 +722,9 @@ fn op_limit(gas_limit: Gas) -> u32 { } fn test_pk() -> Vec { - let pk = "ed25519:22W5rKuvbMRphnDoCj6nfrWhRKvh9Xf9SWXfGHaeXGde" + let pk = borsh::to_vec(&"ed25519:22W5rKuvbMRphnDoCj6nfrWhRKvh9Xf9SWXfGHaeXGde" .parse::() - .unwrap() - .try_to_vec() + .unwrap()) .unwrap(); pk } diff --git a/runtime/near-vm-runner/src/logic/tests/promises.rs b/runtime/near-vm-runner/src/logic/tests/promises.rs index 9c429fb1dc6..c82a1298679 100644 --- a/runtime/near-vm-runner/src/logic/tests/promises.rs +++ b/runtime/near-vm-runner/src/logic/tests/promises.rs @@ -2,7 +2,7 @@ use crate::logic::mocks::mock_external::MockedExternal; use crate::logic::tests::helpers::*; use crate::logic::tests::vm_logic_builder::VMLogicBuilder; use crate::logic::types::PromiseResult; -use borsh::BorshSerialize; + use near_crypto::PublicKey; use serde_json; @@ -365,10 +365,9 @@ fn test_promise_batch_action_stake() { let mut logic_builder = VMLogicBuilder::default(); let mut logic = logic_builder.build(); let index = promise_create(&mut logic, b"rick.test", 0, 0).expect("should create a promise"); - let key = "ed25519:5do5nkAEVhL8iteDvXNgxi4pWK78Y7DDadX11ArFNyrf" + let key = borsh::to_vec(&"ed25519:5do5nkAEVhL8iteDvXNgxi4pWK78Y7DDadX11ArFNyrf" .parse::() - .unwrap() - .try_to_vec() + .unwrap()) .unwrap(); let key = logic.internal_mem_write(&key); @@ -443,10 +442,9 @@ fn test_promise_batch_action_add_key_with_function_call() { let mut logic = logic_builder.build(); let index = promise_create(&mut logic, b"rick.test", 0, 0).expect("should create a promise"); let index_ptr = logic.internal_mem_write(&index.to_le_bytes()).ptr; - let key = "ed25519:5do5nkAEVhL8iteDvXNgxi4pWK78Y7DDadX11ArFNyrf" + let key = borsh::to_vec(&"ed25519:5do5nkAEVhL8iteDvXNgxi4pWK78Y7DDadX11ArFNyrf" .parse::() - .unwrap() - .try_to_vec() + .unwrap()) .unwrap(); let nonce = 1; let allowance = 999u128; diff --git a/runtime/runtime/src/actions.rs b/runtime/runtime/src/actions.rs index 4425be4f75d..58522416572 100644 --- a/runtime/runtime/src/actions.rs +++ b/runtime/runtime/src/actions.rs @@ -5,7 +5,7 @@ use crate::config::{ use crate::ext::{ExternalError, RuntimeExt}; use crate::receipt_manager::ReceiptManager; use crate::{metrics, ActionResult, ApplyState}; -use borsh::BorshSerialize; + use near_crypto::PublicKey; use near_primitives::account::{AccessKey, AccessKeyPermission, Account}; use near_primitives::action::delegate::{DelegateAction, SignedDelegateAction}; @@ -81,9 +81,8 @@ pub(crate) fn execute_function_call( let context = VMContext { current_account_id: runtime_ext.account_id().clone(), signer_account_id: action_receipt.signer_id.clone(), - signer_account_pk: action_receipt - .signer_public_key - .try_to_vec() + signer_account_pk: borsh::to_vec(&action_receipt + .signer_public_key) .expect("Failed to serialize"), predecessor_account_id: predecessor_id.clone(), input: function_call.args.clone(), @@ -462,7 +461,7 @@ pub(crate) fn action_implicit_account_creation_transfer( CryptoHash::default(), fee_config.storage_usage_config.num_bytes_account + public_key.len() as u64 - + access_key.try_to_vec().unwrap().len() as u64 + + borsh::to_vec(&access_key).unwrap().len() as u64 + fee_config.storage_usage_config.num_extra_bytes_record, )); @@ -560,12 +559,12 @@ pub(crate) fn action_delete_key( let storage_usage_config = &fee_config.storage_usage_config; let storage_usage = if current_protocol_version >= DELETE_KEY_STORAGE_USAGE_PROTOCOL_VERSION { - delete_key.public_key.try_to_vec().unwrap().len() as u64 - + access_key.try_to_vec().unwrap().len() as u64 + borsh::to_vec(&delete_key.public_key).unwrap().len() as u64 + + borsh::to_vec(&access_key).unwrap().len() as u64 + storage_usage_config.num_extra_bytes_record } else { - delete_key.public_key.try_to_vec().unwrap().len() as u64 - + Some(access_key).try_to_vec().unwrap().len() as u64 + borsh::to_vec(&delete_key.public_key).unwrap().len() as u64 + + borsh::to_vec(&Some(access_key)).unwrap().len() as u64 + storage_usage_config.num_extra_bytes_record }; // Remove access key @@ -615,8 +614,8 @@ pub(crate) fn action_add_key( account .storage_usage() .checked_add( - add_key.public_key.try_to_vec().unwrap().len() as u64 - + add_key.access_key.try_to_vec().unwrap().len() as u64 + borsh::to_vec(&add_key.public_key).unwrap().len() as u64 + + borsh::to_vec(&add_key.access_key).unwrap().len() as u64 + storage_config.num_extra_bytes_record, ) .ok_or_else(|| { diff --git a/runtime/runtime/src/verifier.rs b/runtime/runtime/src/verifier.rs index e9dacb4cae4..596517ca021 100644 --- a/runtime/runtime/src/verifier.rs +++ b/runtime/runtime/src/verifier.rs @@ -555,7 +555,7 @@ fn test_truncate_string() { mod tests { use std::sync::Arc; - use crate::near_primitives::borsh::BorshSerialize; + use near_crypto::{InMemorySigner, KeyType, PublicKey, Signature, Signer}; use near_primitives::account::{AccessKey, FunctionCallPermission}; use near_primitives::action::delegate::{DelegateAction, NonDelegateAction}; @@ -636,8 +636,8 @@ mod tests { initial_account .storage_usage() .checked_add( - public_key.try_to_vec().unwrap().len() as u64 - + access_key.try_to_vec().unwrap().len() as u64 + borsh::to_vec(&public_key).unwrap().len() as u64 + + borsh::to_vec(&access_key).unwrap().len() as u64 + 40, // storage_config.num_extra_bytes_record, ) .unwrap(), diff --git a/runtime/runtime/tests/test_async_calls.rs b/runtime/runtime/tests/test_async_calls.rs index 7890e2fb96b..cead94c01d2 100644 --- a/runtime/runtime/tests/test_async_calls.rs +++ b/runtime/runtime/tests/test_async_calls.rs @@ -1,5 +1,5 @@ use crate::runtime_group_tools::RuntimeGroup; -use borsh::ser::BorshSerialize; + use near_crypto::{InMemorySigner, KeyType}; use near_primitives::account::{AccessKeyPermission, FunctionCallPermission}; use near_primitives::hash::CryptoHash; @@ -614,7 +614,7 @@ fn test_create_account_with_transfer_and_full_key() { }, "id": 0 }, {"action_add_key_with_full_access": { "promise_index": 0, - "public_key": to_base64(&signer_new_account.public_key.try_to_vec().unwrap()), + "public_key": to_base64(&borsh::to_vec(&signer_new_account.public_key).unwrap()), "nonce": 0, }, "id": 0 } ]); @@ -687,7 +687,7 @@ fn test_account_factory() { }, "id": 0 }, {"action_add_key_with_function_call": { "promise_index": 0, - "public_key": to_base64(&signer_new_account.public_key.try_to_vec().unwrap()), + "public_key": to_base64(&borsh::to_vec(&signer_new_account.public_key).unwrap()), "nonce": 0, "allowance": (TESTING_INIT_BALANCE / 2).to_string(), "receiver_id": "near_1", @@ -844,7 +844,7 @@ fn test_create_account_add_key_call_delete_key_delete_account() { }, "id": 0 }, {"action_add_key_with_full_access": { "promise_index": 0, - "public_key": to_base64(&signer_new_account.public_key.try_to_vec().unwrap()), + "public_key": to_base64(&borsh::to_vec(&signer_new_account.public_key).unwrap()), "nonce": 1, }, "id": 0 }, {"action_deploy_contract": { @@ -868,7 +868,7 @@ fn test_create_account_add_key_call_delete_key_delete_account() { }, "id": 0 }, {"action_delete_key": { "promise_index": 0, - "public_key": to_base64(&signer_new_account.public_key.try_to_vec().unwrap()), + "public_key": to_base64(&borsh::to_vec(&signer_new_account.public_key).unwrap()), "nonce": 0, }, "id": 0 }, {"action_delete_account": { diff --git a/tools/amend-genesis/src/lib.rs b/tools/amend-genesis/src/lib.rs index 391745690b1..4ebd39d5846 100644 --- a/tools/amend-genesis/src/lib.rs +++ b/tools/amend-genesis/src/lib.rs @@ -1,5 +1,5 @@ use anyhow::Context; -use borsh::BorshSerialize; + use near_chain_configs::{Genesis, GenesisValidationMode}; use near_crypto::PublicKey; use near_primitives::hash::CryptoHash; @@ -107,7 +107,7 @@ impl AccountRecords { for (public_key, access_key) in self.keys { let storage_usage = account.storage_usage() + public_key.len() as u64 - + access_key.try_to_vec().unwrap().len() as u64 + + borsh::to_vec(&access_key).unwrap().len() as u64 + num_extra_bytes_record; account.set_storage_usage(storage_usage); diff --git a/tools/fork-network/src/cli.rs b/tools/fork-network/src/cli.rs index 3bf6dcbeef5..9cd8e4db72a 100644 --- a/tools/fork-network/src/cli.rs +++ b/tools/fork-network/src/cli.rs @@ -6,7 +6,7 @@ use near_primitives::account::AccessKey; use near_primitives::runtime::config_store::RuntimeConfigStore; use near_primitives::version::PROTOCOL_VERSION; use near_primitives::{ - account::Account, borsh::BorshSerialize, hash::CryptoHash, types::AccountInfo, + account::Account, borsh::{self}, hash::CryptoHash, types::AccountInfo, }; use near_store::{flat::FlatStorageStatus, DBCol, Mode, NodeStorage, HEAD_KEY}; use nearcore::{load_config, NightshadeRuntime, NEAR_BASE}; @@ -131,7 +131,7 @@ impl ForkNetworkCommand { let fork_head_block = store .get_ser::( DBCol::Block, - &fork_head.try_to_vec().unwrap(), + &borsh::to_vec(&fork_head).unwrap(), )? .unwrap(); diff --git a/tools/fork-network/src/storage_mutator.rs b/tools/fork-network/src/storage_mutator.rs index 029f572f68e..eeeff2076cf 100644 --- a/tools/fork-network/src/storage_mutator.rs +++ b/tools/fork-network/src/storage_mutator.rs @@ -5,7 +5,7 @@ use near_crypto::PublicKey; use near_epoch_manager::EpochManagerAdapter; use near_primitives::{ account::{AccessKey, Account}, - borsh::BorshSerialize, + borsh::{self}, hash::CryptoHash, trie_key::TrieKey, types::{AccountId, EpochId, StateRoot}, @@ -51,7 +51,7 @@ impl StorageMutator { pub fn set_account(&mut self, account_id: AccountId, value: Account) -> anyhow::Result<()> { let shard_id = self.epoch_manager.account_id_to_shard_id(&account_id, &self.epoch_id)?; - self.tries[shard_id as usize].set(TrieKey::Account { account_id }, value.try_to_vec()?); + self.tries[shard_id as usize].set(TrieKey::Account { account_id }, borsh::to_vec(&value)?); Ok(()) } @@ -63,7 +63,7 @@ impl StorageMutator { ) -> anyhow::Result<()> { let shard_id = self.epoch_manager.account_id_to_shard_id(&account_id, &self.epoch_id)?; self.tries[shard_id as usize] - .set(TrieKey::AccessKey { account_id, public_key }, access_key.try_to_vec()?); + .set(TrieKey::AccessKey { account_id, public_key }, borsh::to_vec(&access_key)?); Ok(()) } diff --git a/tools/mirror/src/lib.rs b/tools/mirror/src/lib.rs index b3c4dad8be5..6bc7112e5be 100644 --- a/tools/mirror/src/lib.rs +++ b/tools/mirror/src/lib.rs @@ -112,7 +112,7 @@ enum NonceUpdater { // returns bytes that serve as the key corresponding to this pair in the Nonces column fn nonce_col_key(account_id: &AccountId, public_key: &PublicKey) -> Vec { - (account_id.clone(), public_key.clone()).try_to_vec().unwrap() + borsh::to_vec(&(account_id.clone(), public_key.clone())).unwrap() } // this serves a similar purpose to `LatestTargetNonce`. The difference is @@ -163,7 +163,7 @@ fn put_target_nonce( ) -> anyhow::Result<()> { tracing::debug!(target: "mirror", "storing {:?} in DB for ({}, {:?})", &nonce, account_id, public_key); let db_key = nonce_col_key(account_id, public_key); - db.put_cf(db.cf_handle(DBCol::Nonces.name()).unwrap(), &db_key, &nonce.try_to_vec().unwrap())?; + db.put_cf(db.cf_handle(DBCol::Nonces.name()).unwrap(), &db_key, &borsh::to_vec(&nonce).unwrap())?; Ok(()) } @@ -179,7 +179,7 @@ fn read_pending_outcome( id: &CryptoHash, ) -> anyhow::Result>> { Ok(db - .get_cf(db.cf_handle(DBCol::AccessKeyOutcomes.name()).unwrap(), &id.try_to_vec().unwrap())? + .get_cf(db.cf_handle(DBCol::AccessKeyOutcomes.name()).unwrap(), &borsh::to_vec(&id).unwrap())? .map(|v| HashSet::try_from_slice(&v).unwrap())) } @@ -191,8 +191,8 @@ fn put_pending_outcome( tracing::debug!(target: "mirror", "storing {:?} in DB for {:?}", &access_keys, &id); Ok(db.put_cf( db.cf_handle(DBCol::AccessKeyOutcomes.name()).unwrap(), - &id.try_to_vec().unwrap(), - &access_keys.try_to_vec().unwrap(), + &borsh::to_vec(&id).unwrap(), + &borsh::to_vec(&access_keys).unwrap(), )?) } @@ -200,7 +200,7 @@ fn delete_pending_outcome(db: &DB, id: &CryptoHash) -> anyhow::Result<()> { tracing::debug!(target: "mirror", "deleting {:?} from DB", &id); Ok(db.delete_cf( db.cf_handle(DBCol::AccessKeyOutcomes.name()).unwrap(), - &id.try_to_vec().unwrap(), + &borsh::to_vec(&id).unwrap(), )?) } @@ -215,7 +215,7 @@ fn set_last_source_height(db: &DB, height: BlockHeight) -> anyhow::Result<()> { db.put_cf( db.cf_handle(DBCol::Misc.name()).unwrap(), "last_source_height", - height.try_to_vec().unwrap(), + borsh::to_vec(&height).unwrap(), )?; Ok(()) } diff --git a/tools/speedy_sync/src/main.rs b/tools/speedy_sync/src/main.rs index b98bf1f12ae..29109ce4bb3 100644 --- a/tools/speedy_sync/src/main.rs +++ b/tools/speedy_sync/src/main.rs @@ -187,7 +187,7 @@ fn create_snapshot(create_cmd: CreateCmd) { fs::write( Path::new(&create_cmd.destination_dir).join("snapshot.borsh"), - checkpoint.try_to_vec().unwrap(), + borsh::to_vec(&checkpoint).unwrap(), ) .expect("Failed writing to destination file"); diff --git a/tools/state-viewer/src/cli.rs b/tools/state-viewer/src/cli.rs index a09a0ecdf9e..6fbefafe05d 100644 --- a/tools/state-viewer/src/cli.rs +++ b/tools/state-viewer/src/cli.rs @@ -2,7 +2,7 @@ use crate::commands::*; use crate::contract_accounts::ContractAccountFilter; use crate::rocksdb_stats::get_rocksdb_stats; use crate::trie_iteration_benchmark::TrieIterationBenchmarkCmd; -use borsh::BorshSerialize; + use near_chain_configs::{GenesisChangeConfig, GenesisValidationMode}; use near_primitives::account::id::AccountId; use near_primitives::hash::CryptoHash; @@ -562,7 +562,7 @@ impl ScanDbColumnCmd { (None, Some(bytes), None) => { Some(bytes.split(",").map(|s| s.parse::().unwrap()).collect::>()) } - (None, None, Some(hash)) => Some(hash.try_to_vec().unwrap()), + (None, None, Some(hash)) => Some(borsh::to_vec(&hash).unwrap()), _ => panic!("Need to provide exactly one of bytes, str, or hash"), } } diff --git a/tools/state-viewer/src/contract_accounts.rs b/tools/state-viewer/src/contract_accounts.rs index 6d5cfadec86..c2b28ca406a 100644 --- a/tools/state-viewer/src/contract_accounts.rs +++ b/tools/state-viewer/src/contract_accounts.rs @@ -693,8 +693,8 @@ mod tests { ) -> (DBCol, Vec, Vec) { ( col, - borsh::ser::BorshSerialize::try_to_vec(key).unwrap(), - borsh::ser::BorshSerialize::try_to_vec(value).unwrap(), + borsh::to_vec(key).unwrap(), + borsh::to_vec(value).unwrap(), ) } diff --git a/tools/state-viewer/src/state_changes.rs b/tools/state-viewer/src/state_changes.rs index 37b04021fa9..2ed2b14b1c8 100644 --- a/tools/state-viewer/src/state_changes.rs +++ b/tools/state-viewer/src/state_changes.rs @@ -1,4 +1,4 @@ -use borsh::{BorshDeserialize, BorshSerialize}; +use borsh::{BorshDeserialize}; use near_chain::types::RuntimeAdapter; use near_chain::{ChainStore, ChainStoreAccess}; use near_epoch_manager::{EpochManager, EpochManagerAdapter}; @@ -112,7 +112,7 @@ fn dump_state_changes( let state_changes_for_block_range = StateChangesForBlockRange { blocks }; tracing::info!(target: "state-changes", ?file, "Writing state changes to a file"); - let data: Vec = state_changes_for_block_range.try_to_vec().unwrap(); + let data: Vec = borsh::to_vec(&state_changes_for_block_range).unwrap(); std::fs::write(&file, data).unwrap(); } diff --git a/tools/state-viewer/src/state_dump.rs b/tools/state-viewer/src/state_dump.rs index 34ee5341bf2..04337e7730b 100644 --- a/tools/state-viewer/src/state_dump.rs +++ b/tools/state-viewer/src/state_dump.rs @@ -1,4 +1,4 @@ -use borsh::BorshSerialize; + use chrono::Utc; use near_chain::types::RuntimeAdapter; use near_chain_configs::{Genesis, GenesisChangeConfig, GenesisConfig}; @@ -157,7 +157,7 @@ pub fn state_dump_redis( block_hash.as_ref(), block_height, )?; - let value = account.try_to_vec().unwrap(); + let value = borsh::to_vec(&account).unwrap(); redis_connection.set( [b"account-data:", redis_key, b":", block_hash.as_ref()].concat(), value,