diff --git a/Cargo.lock b/Cargo.lock index 96cdca17d62a6..f7cfedfd0f41d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -757,6 +757,7 @@ dependencies = [ "futures", "hex", "itertools", + "move-deps", "netcore", "network", "rand 0.8.4", diff --git a/api/src/accounts.rs b/api/src/accounts.rs index a853056106b33..b106f7df1f010 100644 --- a/api/src/accounts.rs +++ b/api/src/accounts.rs @@ -20,12 +20,12 @@ use aptos_types::{ }; use anyhow::Result; -use aptos_types::{account_state_blob::AccountStateBlob, account_view::AccountView}; +use aptos_types::account_view::AccountView; use move_core_types::{ identifier::Identifier, language_storage::StructTag, move_resource::MoveStructType, value::MoveValue, }; -use std::convert::{TryFrom, TryInto}; +use std::convert::TryInto; use warp::{filters::BoxedFilter, Filter, Rejection, Reply}; // GET /accounts/
@@ -38,16 +38,6 @@ pub fn get_account(context: Context) -> BoxedFilter<(impl Reply,)> { .boxed() } -// GET /accounts/
/blob -pub fn get_account_state_blob(context: Context) -> BoxedFilter<(impl Reply,)> { - warp::path!("accounts" / AddressParam / "blob") - .and(warp::get()) - .and(context.filter()) - .and_then(handle_get_account_state_blob) - .with(metrics("get_account_state_blob")) - .boxed() -} - // GET /accounts/
/resources pub fn get_account_resources(context: Context) -> BoxedFilter<(impl Reply,)> { warp::path!("accounts" / AddressParam / "resources") @@ -82,14 +72,6 @@ async fn handle_get_account( Ok(Account::new(None, address, context)?.account()?) } -async fn handle_get_account_state_blob( - address: AddressParam, - context: Context, -) -> Result { - fail_point("endpoint_get_account_state_blob")?; - Ok(Account::new(None, address, context)?.account_state_blob()?) -} - async fn handle_get_account_resources( ledger_version: Option, address: AddressParam, @@ -152,15 +134,6 @@ impl Account { Response::new(self.latest_ledger_info, &account) } - pub fn account_state_blob(self) -> Result { - let state = self - .context - .get_account_state(self.address.into(), self.ledger_version)? - .ok_or_else(|| self.account_not_found())?; - let blob: Vec = AccountStateBlob::try_from(&state)?.into(); - Response::new(self.latest_ledger_info, &blob) - } - pub fn resources(self) -> Result { let resources = self .context diff --git a/api/src/index.rs b/api/src/index.rs index 6b426f0975b1f..7e0a29cdf6b2e 100644 --- a/api/src/index.rs +++ b/api/src/index.rs @@ -31,7 +31,6 @@ pub fn routes(context: Context) -> impl Filter String { format!("/accounts/{}/resources", address) } -fn account_blob(address: &str) -> String { - format!("/accounts/{}/blob", address) -} - fn account_resources_with_ledger_version(address: &str, ledger_version: i128) -> String { format!("{}?version={}", account_resources(address), ledger_version) } diff --git a/config/management/operational/Cargo.toml b/config/management/operational/Cargo.toml index 931dbcf0e917b..31402b5320207 100644 --- a/config/management/operational/Cargo.toml +++ b/config/management/operational/Cargo.toml @@ -39,6 +39,7 @@ aptos-transaction-builder = { path = "../../../sdk/transaction-builder" } aptos-types = { path = "../../../types" } aptos-workspace-hack = { path = "../../../crates/aptos-workspace-hack" } fallible = { path = "../../../crates/fallible" } +move-deps = { path = "../../../aptos-move/move-deps", features = ["address32"] } netcore = { path = "../../../network/netcore" } network = { path = "../../../network" } diff --git a/config/management/operational/src/rest_client.rs b/config/management/operational/src/rest_client.rs index ff5c71228f404..bacf870e58849 100644 --- a/config/management/operational/src/rest_client.rs +++ b/config/management/operational/src/rest_client.rs @@ -5,12 +5,16 @@ use crate::{TransactionContext, TransactionStatus}; use aptos_management::error::Error; use aptos_rest_client::Client; use aptos_types::{ - account_address::AccountAddress, account_config, account_config::AccountResource, - account_state::AccountState, account_state_blob::AccountStateBlob, account_view::AccountView, - transaction::SignedTransaction, validator_config::ValidatorConfig, + account_address::AccountAddress, + account_config, + account_config::AccountResource, + on_chain_config::{access_path_for_config, OnChainConfig}, + transaction::SignedTransaction, + validator_config::ValidatorConfig, validator_info::ValidatorInfo, }; -use std::convert::TryFrom; +use move_deps::move_core_types::move_resource::MoveStructType; +use serde::de::DeserializeOwned; /// A wrapper around JSON RPC for error handling pub struct RestClient { @@ -36,28 +40,29 @@ impl RestClient { )) } - pub async fn account_state(&self, account: AccountAddress) -> Result { - let result = self.client.get_account_state_blob(account).await; - let account_state_blob: AccountStateBlob = result - .map_err(|e| Error::RestReadError("account-state", e.to_string()))? - .inner() - .clone() - .into(); - - AccountState::try_from(&account_state_blob) - .map_err(|e| Error::RestReadError("account-state", e.to_string())) + pub async fn get_resource( + &self, + address: AccountAddress, + resource_type: &str, + ) -> Result { + Ok(self + .client + .get_resource(address, resource_type) + .await + .map_err(|e| Error::RestReadError("get_resource", e.to_string()))? + .into_inner()) } pub async fn validator_config( &self, account: AccountAddress, ) -> Result { - resource( - "validator-config-resource", - self.account_state(account) - .await? - .get_validator_config_resource(), - ) + let access_path = ValidatorConfig::struct_tag().access_vector(); + let resource_type = std::str::from_utf8(&access_path) + .map_err(|e| Error::UnableToParse("Unable to form resource type", e.to_string()))?; + + let validator_config: ValidatorConfig = self.get_resource(account, resource_type).await?; + resource("validator-config-resource", Ok(Some(validator_config))) } /// This method returns all validator infos currently registered in the validator set of the @@ -68,45 +73,44 @@ impl RestClient { account: Option, ) -> Result, Error> { let validator_set_account = account_config::validator_set_address(); - let validator_set = self - .account_state(validator_set_account) - .await? - .get_validator_set(); - - match validator_set { - Ok(Some(validator_set)) => { - let mut validator_infos = vec![]; - for validator_info in validator_set.payload() { - if let Some(account) = account { - if validator_info.account_address() == &account { - validator_infos.push(validator_info.clone()); - } - } else { - validator_infos.push(validator_info.clone()); - } - } + let access_path = + access_path_for_config(aptos_types::on_chain_config::ValidatorSet::CONFIG_ID).path; + let resource_type = std::str::from_utf8(&access_path) + .map_err(|e| Error::RestReadError("Unable to form resource type", e.to_string()))?; + + let validator_set: aptos_types::on_chain_config::ValidatorSet = self + .get_resource(validator_set_account, resource_type) + .await?; - if validator_infos.is_empty() { - return Err(Error::UnexpectedError( - "No validator sets were found!".to_string(), - )); + let mut validator_infos = vec![]; + for validator_info in validator_set.payload() { + if let Some(account) = account { + if validator_info.account_address() == &account { + validator_infos.push(validator_info.clone()); } - Ok(validator_infos) + } else { + validator_infos.push(validator_info.clone()); } - Ok(None) => Err(Error::RestReadError( - "validator-set", - "not present".to_string(), - )), - Err(e) => Err(Error::RestReadError("validator-set", e.to_string())), } + + if validator_infos.is_empty() { + return Err(Error::UnexpectedError( + "No validator sets were found!".to_string(), + )); + } + Ok(validator_infos) } pub async fn account_resource( &self, account: AccountAddress, ) -> Result { - let account_state = self.account_state(account).await?; - resource("account-resource", account_state.get_account_resource()) + let access_path = AccountResource::struct_tag().access_vector(); + let resource_type = std::str::from_utf8(&access_path) + .map_err(|e| Error::UnableToParse("Unable to form resource type", e.to_string()))?; + + let account_resource: AccountResource = self.get_resource(account, resource_type).await?; + resource("account-resource", Ok(Some(account_resource))) } pub async fn sequence_number(&self, account: AccountAddress) -> Result { diff --git a/config/seed-peer-generator/src/utils.rs b/config/seed-peer-generator/src/utils.rs index bcb2478d97b9d..807c087142524 100644 --- a/config/seed-peer-generator/src/utils.rs +++ b/config/seed-peer-generator/src/utils.rs @@ -3,16 +3,15 @@ #![forbid(unsafe_code)] -use std::convert::TryFrom; - use anyhow::Error; use aptos_config::config::{Peer, PeerRole, PeerSet}; use aptos_logger::prelude::*; use aptos_rest_client::Client; use aptos_types::{ - account_config::aptos_root_address, account_state::AccountState, - account_state_blob::AccountStateBlob, account_view::AccountView, - network_address::NetworkAddress, on_chain_config::ValidatorSet, validator_info::ValidatorInfo, + account_config::aptos_root_address, + network_address::NetworkAddress, + on_chain_config::{access_path_for_config, OnChainConfig, ValidatorSet}, + validator_info::ValidatorInfo, PeerId, }; @@ -39,14 +38,11 @@ pub(crate) fn to_fullnode_addresses( fn get_validator_set(client_endpoint: String) -> anyhow::Result { let client = Client::new(url::Url::parse(&client_endpoint)?); let rt = tokio::runtime::Runtime::new().unwrap(); - let blob = rt.block_on(client.get_account_state_blob(aptos_root_address()))?; - let account_state_blob: AccountStateBlob = blob.inner().clone().into(); - let account_state = AccountState::try_from(&account_state_blob)?; - if let Some(val) = account_state.get_validator_set()? { - Ok(val) - } else { - Err(Error::msg("No validator set")) - } + let validator_set_response = rt.block_on(client.get_resource::( + aptos_root_address(), + std::str::from_utf8(&access_path_for_config(ValidatorSet::CONFIG_ID).path)?, + ))?; + Ok(validator_set_response.inner().clone()) } // TODO: Merge with OnchainDiscovery diff --git a/crates/aptos-rest-client/src/lib.rs b/crates/aptos-rest-client/src/lib.rs index dfd06e4016302..5e5aaac3de471 100644 --- a/crates/aptos-rest-client/src/lib.rs +++ b/crates/aptos-rest-client/src/lib.rs @@ -15,6 +15,7 @@ use serde_json::{json, Value}; use state::State; use std::time::Duration; use url::Url; + pub mod error; pub mod faucet; pub use faucet::FaucetClient; @@ -242,18 +243,6 @@ impl Client { self.json(response).await } - pub async fn get_account_state_blob( - &self, - address: AccountAddress, - ) -> Result>> { - let url = self.base_url.join(&format!("accounts/{}/blob", address))?; - - let response = self.inner.get(url).send().await?; - let (response, state) = self.check_response(response).await?; - let blob = response.json().await?; - Ok(Response::new(blob, state)) - } - pub async fn get_account_resources( &self, address: AccountAddress, diff --git a/documentation/specifications/common/authenticated_data_structures.md b/documentation/specifications/common/authenticated_data_structures.md index 929de0cbcd058..15db7d0480c5b 100644 --- a/documentation/specifications/common/authenticated_data_structures.md +++ b/documentation/specifications/common/authenticated_data_structures.md @@ -286,9 +286,9 @@ The previous section described Merkle accumulator and sparse Merkle tree that fo ### Ledger State -The ledger state represents the ground truth about the Aptos ecosystem, including the quantity of coins held by each user at a given version. Each validator must know the ledger state at the latest version in order to execute new transactions. Specifically, the ledger state is a map from `AccountAddress` to a binary blob `AccountStateBlob` that represents the state of an account. +The ledger state represents the ground truth about the Aptos ecosystem, including the quantity of coins held by each user at a given version. Each validator must know the ledger state at the latest version in order to execute new transactions. Specifically, the ledger state is a map from `StateKey` to a `StateValue` that represents a resource associated with an account. -Each `AccountAddress` is hashed to a 256-bit `HashValue`. Then each `(hash(address), account_state_blob)` tuple is inserted into a sparse Merkle tree as a key-value pair. Based on the properties of cryptographic hash functions, we can assume that the resulting sparse Merkle tree is balanced no matter how the addresses are generated. This sparse Merkle tree represents the entire ledger state and the root hash of this tree is the state root hash, which means the state root hash is the authenticator for any account state at the same version. +Each `StateKey` is hashed to a 256-bit `HashValue`. Then each `(hash(state_key), state_value)` tuple is inserted into a sparse Merkle tree as a key-value pair. Based on the properties of cryptographic hash functions, we can assume that the resulting sparse Merkle tree is balanced no matter how the addresses are generated. This sparse Merkle tree represents the entire ledger state and the root hash of this tree is the state root hash, which means the state root hash is the authenticator for any resource at the same version. ```rust type LedgerState = SparseMerkleTree; @@ -300,7 +300,7 @@ When the state tree is updated after the execution of a transaction and a new tr #### Accounts -At the logical level, an account is a collection of Move resources and modules. At the physical level, an account is an ordered map of access paths to byte array values. TODO: link to definition of access path. When an account is stored in the ledger state, the ordered map is serialized using Binary Canonical Serialization (BCS) to create a binary blob `AccountStateBlob` that gets inserted into a sparse Merkle tree. +At the logical level, an account is a collection of Move resources and modules. At the physical level, an account is an ordered map of state key to state values. TODO: link to definition of access path. When an account is stored in the ledger state, individual resource in the account is serialized using Binary Canonical Serialization (BCS) to create a `StateValue` that gets inserted into a sparse Merkle tree. ```rust type Path = Vec; @@ -312,17 +312,22 @@ struct AccessPath { type AccountState = BTreeMap>; -struct AccountStateBlob { - blob: Vec, +pub enum StateKey { + AccessPath(AccessPath), + TableItem { + handle: u128, + key: Vec, + }, + // Only used for testing + Raw(Vec), } -impl From for AccountStateBlob { - fn from(account_state: AccountState) -> Self { - Self { - blob: bcs::to_bytes(&account_state), - } - } +pub struct StateValue { + pub maybe_bytes: Option>, + hash: HashValue, } + + ``` ### Transaction and Transaction Output diff --git a/documentation/specifications/db_backup/spec.md b/documentation/specifications/db_backup/spec.md index df91680cf60cd..b5912647d188b 100644 --- a/documentation/specifications/db_backup/spec.md +++ b/documentation/specifications/db_backup/spec.md @@ -111,7 +111,7 @@ pub struct StateSnapshotChunk { /// key of the last account in this chunk. pub last_key: HashValue, /// Repeated `len(record) + record` where `record` is BCS serialized tuple - /// `(key, account_state_blob)` + /// `(key, state_value)` pub blobs: FileHandle, /// BCS serialized `SparseMerkleRangeProof` that proves this chunk adds up to the root hash /// indicated in the backup (`StateSnapshotBackup::root_hash`). diff --git a/storage/backup/backup-cli/src/backup_types/state_snapshot/manifest.rs b/storage/backup/backup-cli/src/backup_types/state_snapshot/manifest.rs index d79d815767c86..7b3379c6d4723 100644 --- a/storage/backup/backup-cli/src/backup_types/state_snapshot/manifest.rs +++ b/storage/backup/backup-cli/src/backup_types/state_snapshot/manifest.rs @@ -19,7 +19,7 @@ pub struct StateSnapshotChunk { /// key of the last account in this chunk. pub last_key: HashValue, /// Repeated `len(record) + record` where `record` is BCS serialized tuple - /// `(key, account_state_blob)` + /// `(key, state_value)` pub blobs: FileHandle, /// BCS serialized `SparseMerkleRangeProof` that proves this chunk adds up to the root hash /// indicated in the backup (`StateSnapshotBackup::root_hash`). diff --git a/storage/jellyfish-merkle/src/lib.rs b/storage/jellyfish-merkle/src/lib.rs index ffaa4ac838844..bf5177a12d2e0 100644 --- a/storage/jellyfish-merkle/src/lib.rs +++ b/storage/jellyfish-merkle/src/lib.rs @@ -141,17 +141,12 @@ pub trait Value: Clone + CryptoHash + Serialize + DeserializeOwned + Send + Sync #[cfg(any(test, feature = "fuzzing"))] pub trait TestValue: Value + Arbitrary + std::fmt::Debug + Eq + PartialEq + 'static {} -// This crate still depends on types for a few things, therefore we implement `Value` and -// `TestValue` for `AccountStateBlob` here. Ideally the module that defines the specific value like -// `AccountStateBlob` should import the `Value` trait and implement it there. -impl Value for aptos_types::account_state_blob::AccountStateBlob {} - impl Value for StateValue {} impl Value for StateKeyAndValue {} #[cfg(any(test, feature = "fuzzing"))] -impl TestValue for aptos_types::account_state_blob::AccountStateBlob {} +impl TestValue for StateValue {} /// Node batch that will be written into db atomically with other batches. pub type NodeBatch = BTreeMap>; diff --git a/storage/scratchpad/benches/sparse_merkle.rs b/storage/scratchpad/benches/sparse_merkle.rs index 0114218017bfe..5450e7f9381df 100644 --- a/storage/scratchpad/benches/sparse_merkle.rs +++ b/storage/scratchpad/benches/sparse_merkle.rs @@ -2,30 +2,30 @@ // SPDX-License-Identifier: Apache-2.0 use aptos_crypto::{hash::SPARSE_MERKLE_PLACEHOLDER_HASH, HashValue}; -use aptos_types::account_state_blob::AccountStateBlob; +use aptos_types::state_store::state_value::StateValue; use criterion::{criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion, Throughput}; use itertools::zip_eq; use rand::{distributions::Standard, prelude::StdRng, seq::IteratorRandom, Rng, SeedableRng}; use scratchpad::{test_utils::naive_smt::NaiveSmt, SparseMerkleTree}; use std::collections::HashSet; -type ProofReader = scratchpad::test_utils::proof_reader::ProofReader; +type ProofReader = scratchpad::test_utils::proof_reader::ProofReader; struct Block { - smt: SparseMerkleTree, - updates: Vec>, + smt: SparseMerkleTree, + updates: Vec>, proof_reader: ProofReader, } impl Block { - fn updates(&self) -> Vec> { + fn updates(&self) -> Vec> { self.updates .iter() .map(|small_batch| small_batch.iter().map(|(k, v)| (*k, v)).collect()) .collect() } - fn updates_flat_batch(&self) -> Vec<(HashValue, &AccountStateBlob)> { + fn updates_flat_batch(&self) -> Vec<(HashValue, &StateValue)> { self.updates().iter().flatten().cloned().collect() } } @@ -50,7 +50,7 @@ impl Group { b.iter_batched( || small_batches.clone(), // return the resulting smt so the cost of Dropping it is not counted - |small_batches| -> SparseMerkleTree { + |small_batches| -> SparseMerkleTree { block .smt .serial_update(small_batches, &block.proof_reader) @@ -64,7 +64,7 @@ impl Group { b.iter_batched( || one_large_batch.clone(), // return the resulting smt so the cost of Dropping it is not counted - |one_large_batch| -> SparseMerkleTree { + |one_large_batch| -> SparseMerkleTree { block .smt .batch_update(one_large_batch, &block.proof_reader) @@ -174,17 +174,17 @@ impl Benches { rng: &mut StdRng, keys: &[HashValue], block_size: usize, - ) -> Vec> { + ) -> Vec> { std::iter::repeat_with(|| vec![Self::gen_update(rng, keys), Self::gen_update(rng, keys)]) .take(block_size) .collect() } - fn gen_update(rng: &mut StdRng, keys: &[HashValue]) -> (HashValue, AccountStateBlob) { + fn gen_update(rng: &mut StdRng, keys: &[HashValue]) -> (HashValue, StateValue) { (*keys.iter().choose(rng).unwrap(), Self::gen_value(rng)) } - fn gen_value(rng: &mut StdRng) -> AccountStateBlob { + fn gen_value(rng: &mut StdRng) -> StateValue { rng.sample_iter(&Standard) .take(100) .collect::>() @@ -193,7 +193,7 @@ impl Benches { fn gen_proof_reader( naive_smt: &mut NaiveSmt, - updates: &[Vec<(HashValue, AccountStateBlob)>], + updates: &[Vec<(HashValue, StateValue)>], ) -> ProofReader { let proofs = updates .iter() diff --git a/storage/scratchpad/src/sparse_merkle/sparse_merkle_test.rs b/storage/scratchpad/src/sparse_merkle/sparse_merkle_test.rs index e4cde10d85201..62247914ffa80 100644 --- a/storage/scratchpad/src/sparse_merkle/sparse_merkle_test.rs +++ b/storage/scratchpad/src/sparse_merkle/sparse_merkle_test.rs @@ -11,8 +11,8 @@ use aptos_crypto::{ HashValue, }; use aptos_types::{ - account_state_blob::AccountStateBlob, proof::{SparseMerkleLeafNode, SparseMerkleProof}, + state_store::state_value::StateValue, }; use once_cell::sync::Lazy; use proptest::prelude::*; @@ -32,8 +32,8 @@ fn hash_leaf(key: HashValue, value_hash: HashValue) -> HashValue { SparseMerkleLeafNode::new(key, value_hash).hash() } -type SparseMerkleTree = super::SparseMerkleTree; -type SubTree = super::SubTree; +type SparseMerkleTree = super::SparseMerkleTree; +type SubTree = super::SubTree; #[test] fn test_replace_in_mem_leaf() { @@ -42,7 +42,7 @@ fn test_replace_in_mem_leaf() { let leaf = SubTree::new_leaf_with_value_hash(key, value_hash, 0 /* generation */); let smt = SparseMerkleTree::new_with_root(leaf); - let new_value: AccountStateBlob = vec![1, 2, 3].into(); + let new_value: StateValue = vec![1, 2, 3].into(); let root_hash = hash_leaf(key, new_value.hash()); let updated = smt .batch_update(vec![(key, &new_value)], &ProofReader::default()) @@ -58,7 +58,7 @@ fn test_split_in_mem_leaf() { let smt = SparseMerkleTree::new_with_root(leaf1); let key2 = HashValue::from_slice(&[0xff; 32]).unwrap(); - let value2: AccountStateBlob = vec![1, 2, 3].into(); + let value2: StateValue = vec![1, 2, 3].into(); let root_hash = hash_internal(hash_leaf(key1, value1_hash), hash_leaf(key2, value2.hash())); let updated = smt @@ -75,7 +75,7 @@ fn test_insert_at_in_mem_empty() { let value2_hash = b"world".test_only_hash(); let key3 = update_byte(&key1, 0, 0b10000000); - let value3: AccountStateBlob = vec![1, 2, 3].into(); + let value3: StateValue = vec![1, 2, 3].into(); let internal = SubTree::new_internal( SubTree::new_leaf_with_value_hash(key1, value1_hash, 0 /* generation */), @@ -102,7 +102,7 @@ fn test_replace_persisted_leaf() { let proof_reader = ProofReader::new(vec![(key, proof)]); let smt = SparseMerkleTree::new(leaf.hash()); - let new_value: AccountStateBlob = vec![1, 2, 3].into(); + let new_value: StateValue = vec![1, 2, 3].into(); let root_hash = hash_leaf(key, new_value.hash()); let updated = smt .batch_update(vec![(key, &new_value)], &proof_reader) @@ -119,7 +119,7 @@ fn test_split_persisted_leaf() { let smt = SparseMerkleTree::new(leaf1.hash()); let key2 = HashValue::from_slice(&[0xff; 32]).unwrap(); - let value2: AccountStateBlob = vec![1, 2, 3].into(); + let value2: StateValue = vec![1, 2, 3].into(); let proof = SparseMerkleProof::new(Some(leaf1), Vec::new()); let proof_reader = ProofReader::new(vec![(key2, proof)]); @@ -138,7 +138,7 @@ fn test_insert_at_persisted_empty() { let value2_hash = b"world".test_only_hash(); let key3 = update_byte(&key1, 0, 0b10000000); - let value3: AccountStateBlob = vec![1, 2, 3].into(); + let value3: StateValue = vec![1, 2, 3].into(); let sibling_hash = hash_internal(hash_leaf(key1, value1_hash), hash_leaf(key2, value2_hash)); let proof = SparseMerkleProof::new(None, vec![sibling_hash]); @@ -174,10 +174,10 @@ fn test_update_256_siblings_in_proof() { HashValue::from_slice(&buf).unwrap() }; - let blob1 = AccountStateBlob::from(b"value1".to_vec()); - let blob2 = AccountStateBlob::from(b"value2".to_vec()); - let value1_hash = blob1.hash(); - let value2_hash = blob2.hash(); + let value1 = StateValue::from(String::from("test_val1").into_bytes()); + let value2 = StateValue::from(String::from("test_val2").into_bytes()); + let value1_hash = value1.hash(); + let value2_hash = value2.hash(); let leaf1_hash = hash_leaf(key1, value1_hash); let leaf2_hash = hash_leaf(key2, value2_hash); @@ -195,18 +195,18 @@ fn test_update_256_siblings_in_proof() { hash_internal(previous_hash, *hash) }); assert!(proof_of_key1 - .verify(old_root_hash, key1, Some(&blob1)) + .verify(old_root_hash, key1, Some(&value1)) .is_ok()); - let new_blob1 = AccountStateBlob::from(b"value1111111111111".to_vec()); + let new_value1 = StateValue::from(String::from("test_val1111").into_bytes()); let proof_reader = ProofReader::new(vec![(key1, proof_of_key1)]); let smt = SparseMerkleTree::new(old_root_hash); let new_smt = smt - .batch_update(vec![(key1, &new_blob1)], &proof_reader) + .batch_update(vec![(key1, &new_value1)], &proof_reader) .unwrap(); - let new_blob1_hash = new_blob1.hash(); - let new_leaf1_hash = hash_leaf(key1, new_blob1_hash); + let new_value1_hash = new_value1.hash(); + let new_leaf1_hash = hash_leaf(key1, new_value1_hash); let new_root_hash = siblings.iter().fold(new_leaf1_hash, |previous_hash, hash| { hash_internal(previous_hash, *hash) }); @@ -214,7 +214,7 @@ fn test_update_256_siblings_in_proof() { assert_eq!( new_smt.get(key1), - StateStoreStatus::ExistsInScratchPad(new_blob1) + StateStoreStatus::ExistsInScratchPad(new_value1) ); assert_eq!(new_smt.get(key2), StateStoreStatus::Unknown); } @@ -251,16 +251,17 @@ fn test_update() { assert_eq!(key1[0], 0b0000_0100); assert_eq!(key2[0], 0b0010_0100); assert_eq!(key3[0], 0b1110_0111); - let value1 = AccountStateBlob::from(b"value1".to_vec()); + let value1 = StateValue::from(String::from("test_val1").into_bytes()); + let value2 = StateValue::from(String::from("test_val2").into_bytes()); + let value3 = StateValue::from(String::from("test_val3").into_bytes()); let value1_hash = value1.hash(); - let value2_hash = AccountStateBlob::from(b"value2".to_vec()).hash(); - let value3_hash = AccountStateBlob::from(b"value3".to_vec()).hash(); + let value2_hash = value2.hash(); + let value3_hash = value3.hash(); // A new key at the "placeholder" position. let key4 = b"d".test_only_hash(); assert_eq!(key4[0], 0b0100_1100); - let value4 = AccountStateBlob::from(b"value".to_vec()); - + let value4 = StateValue::from(String::from("test_val4").into_bytes()); // Create a proof for this new key. let leaf1 = SparseMerkleLeafNode::new(key1, value1_hash); let leaf1_hash = leaf1.hash(); @@ -313,7 +314,7 @@ fn test_update() { ); assert!(proof.verify(old_root_hash, key1, Some(&value1)).is_ok()); - let value1 = AccountStateBlob::from(b"value11111".to_vec()); + let value1 = StateValue::from(String::from("test_val1111").into_bytes()); let proof_reader = ProofReader::new(vec![(key1, proof)]); let smt2 = smt1 .batch_update(vec![(key1, &value1)], &proof_reader) @@ -347,7 +348,8 @@ fn test_update() { assert_eq_pointee(&smt2.get_oldest_ancestor(), &smt1); // We now try to create another branch on top of smt1. - let value4 = AccountStateBlob::from(b"new value 4444444444".to_vec()); + let value4 = StateValue::from(String::from("test_val4444").into_bytes()); + // key4 already exists in the tree. let proof_reader = ProofReader::default(); let smt22 = smt1 @@ -397,10 +399,11 @@ fn test_update() { } static KEY: Lazy = Lazy::new(|| b"aaaaa".test_only_hash()); -static VALUE: Lazy = Lazy::new(|| AccountStateBlob::from(b"value1".to_vec())); +static VALUE: Lazy = + Lazy::new(|| StateValue::from(String::from("test_val").into_bytes())); static LEAF: Lazy = Lazy::new(|| SparseMerkleLeafNode::new(*KEY, VALUE.hash())); -static PROOF_READER: Lazy> = Lazy::new(|| { +static PROOF_READER: Lazy> = Lazy::new(|| { let proof = SparseMerkleProof::new(Some(*LEAF), vec![]); ProofReader::new(vec![(*KEY, proof)]) }); @@ -542,7 +545,10 @@ fn test_drop() { for _ in 0..100000 { smt = smt .batch_update( - vec![(HashValue::zero(), &AccountStateBlob::from(b"zero".to_vec()))], + vec![( + HashValue::zero(), + &StateValue::from(String::from("test_val").into_bytes()), + )], &proof_reader, ) .unwrap() diff --git a/storage/scratchpad/src/sparse_merkle/test_utils/proptest_helpers.rs b/storage/scratchpad/src/sparse_merkle/test_utils/proptest_helpers.rs index a3a6ba4582b26..60a6a05e285b5 100644 --- a/storage/scratchpad/src/sparse_merkle/test_utils/proptest_helpers.rs +++ b/storage/scratchpad/src/sparse_merkle/test_utils/proptest_helpers.rs @@ -7,7 +7,7 @@ use crate::{ SparseMerkleTree, }; use aptos_crypto::{hash::SPARSE_MERKLE_PLACEHOLDER_HASH, HashValue}; -use aptos_types::account_state_blob::AccountStateBlob; +use aptos_types::state_store::state_value::StateValue; use proptest::{ collection::{hash_set, vec}, prelude::*, @@ -15,7 +15,7 @@ use proptest::{ }; use std::{collections::VecDeque, sync::Arc}; -type TxnOutput = Vec<(HashValue, AccountStateBlob)>; +type TxnOutput = Vec<(HashValue, StateValue)>; type BlockOutput = Vec; #[derive(Debug)] @@ -69,7 +69,7 @@ pub fn arb_smt_correctness_case() -> impl Strategy> { pub fn test_smt_correctness_impl(input: Vec) { let mut naive_q = VecDeque::new(); - naive_q.push_back(NaiveSmt::new::(&[])); + naive_q.push_back(NaiveSmt::new::(&[])); let mut serial_q = VecDeque::new(); serial_q.push_back(SparseMerkleTree::new(*SPARSE_MERKLE_PLACEHOLDER_HASH)); let mut updater_q = VecDeque::new(); diff --git a/testsuite/aptos-fuzzer/src/fuzz_targets/proof.rs b/testsuite/aptos-fuzzer/src/fuzz_targets/proof.rs index 244c970fd7998..1cc246cdbdbc8 100644 --- a/testsuite/aptos-fuzzer/src/fuzz_targets/proof.rs +++ b/testsuite/aptos-fuzzer/src/fuzz_targets/proof.rs @@ -5,7 +5,6 @@ use crate::{corpus_from_strategy, fuzz_data_to_value, FuzzTargetImpl}; use aptos_crypto::HashValue; use aptos_proptest_helpers::ValueGenerator; use aptos_types::{ - account_state_blob::AccountStateBlob, ledger_info::LedgerInfo, proof::{ EventProof, SparseMerkleProof, StateStoreValueProof, TestAccumulatorProof, @@ -54,10 +53,10 @@ pub struct SparseMerkleProofFuzzer; #[derive(Debug, Arbitrary)] struct SparseMerkleProofFuzzerInput { - proof: SparseMerkleProof, + proof: SparseMerkleProof, expected_root_hash: HashValue, element_key: HashValue, - element_blob: Option, + element_blob: Option, } impl FuzzTargetImpl for SparseMerkleProofFuzzer { @@ -148,8 +147,8 @@ struct AccountStateProofFuzzerInput { proof: StateStoreValueProof, ledger_info: LedgerInfo, state_version: Version, - account_address_hash: HashValue, - account_state_blob: Option, + state_key_hash: HashValue, + state_value: Option, } impl FuzzTargetImpl for AccountStateProofFuzzer { @@ -166,8 +165,8 @@ impl FuzzTargetImpl for AccountStateProofFuzzer { let _res = input.proof.verify( &input.ledger_info, input.state_version, - input.account_address_hash, - input.account_state_blob.map(StateValue::from).as_ref(), + input.state_key_hash, + input.state_value.as_ref(), ); } } diff --git a/testsuite/aptos-fuzzer/src/fuzz_targets/storage.rs b/testsuite/aptos-fuzzer/src/fuzz_targets/storage.rs index 3800eceda9330..8d11e28e50e34 100644 --- a/testsuite/aptos-fuzzer/src/fuzz_targets/storage.rs +++ b/testsuite/aptos-fuzzer/src/fuzz_targets/storage.rs @@ -14,7 +14,7 @@ use aptos_jellyfish_merkle::test_helper::{ test_get_with_proof_with_distinct_last_nibble, }; use aptos_proptest_helpers::ValueGenerator; -use aptos_types::account_state_blob::AccountStateBlob; +use aptos_types::state_store::state_value::StateValue; use aptosdb::{ schema::fuzzing::fuzz_decode, test_helper::{arb_blocks_to_commit, test_save_blocks_impl}, @@ -77,14 +77,14 @@ impl FuzzTargetImpl for JellyfishGetWithProof { fn generate(&self, _idx: usize, _gen: &mut ValueGenerator) -> Option> { Some(corpus_from_strategy( - arb_existent_kvs_and_nonexistent_keys::(1000, 100), + arb_existent_kvs_and_nonexistent_keys::(1000, 100), )) } fn fuzz(&self, data: &[u8]) { let input = fuzz_data_to_value( data, - arb_existent_kvs_and_nonexistent_keys::(1000, 100), + arb_existent_kvs_and_nonexistent_keys::(1000, 100), ); test_get_with_proof(input); } @@ -100,15 +100,12 @@ impl FuzzTargetImpl for JellyfishGetWithProofWithDistinctLastNibble { fn generate(&self, _idx: usize, _gen: &mut ValueGenerator) -> Option> { Some(corpus_from_strategy( - arb_kv_pair_with_distinct_last_nibble::(), + arb_kv_pair_with_distinct_last_nibble::(), )) } fn fuzz(&self, data: &[u8]) { - let input = fuzz_data_to_value( - data, - arb_kv_pair_with_distinct_last_nibble::(), - ); + let input = fuzz_data_to_value(data, arb_kv_pair_with_distinct_last_nibble::()); test_get_with_proof_with_distinct_last_nibble(input); } } @@ -122,13 +119,11 @@ impl FuzzTargetImpl for JellyfishGetRangeProof { } fn generate(&self, _idx: usize, _gen: &mut ValueGenerator) -> Option> { - Some(corpus_from_strategy( - arb_tree_with_index::(100), - )) + Some(corpus_from_strategy(arb_tree_with_index::(100))) } fn fuzz(&self, data: &[u8]) { - let input = fuzz_data_to_value(data, arb_tree_with_index::(100)); + let input = fuzz_data_to_value(data, arb_tree_with_index::(100)); test_get_range_proof(input); } } diff --git a/testsuite/smoke-test/src/operational_tooling.rs b/testsuite/smoke-test/src/operational_tooling.rs index 7e5adbb3c9cd4..bb7bcff6891ac 100644 --- a/testsuite/smoke-test/src/operational_tooling.rs +++ b/testsuite/smoke-test/src/operational_tooling.rs @@ -31,17 +31,16 @@ use aptos_operational_tool::{ test_helper::OperationalTool, }; use aptos_rest_client::Client as RestClient; +use aptos_sdk::move_types::move_resource::MoveResource; use aptos_secure_storage::{CryptoStorage, KVStorage, Storage}; use aptos_temppath::TempPath; use aptos_types::{ account_address::{from_identity_public_key, AccountAddress}, - account_state::AccountState, - account_state_blob::AccountStateBlob, - account_view::AccountView, block_info::BlockInfo, ledger_info::LedgerInfo, network_address::NetworkAddress, transaction::authenticator::AuthenticationKey, + validator_config::ValidatorOperatorConfigResource, waypoint::Waypoint, }; use forge::{LocalNode, LocalSwarm, Node, NodeExt, SwarmExt}; @@ -341,19 +340,7 @@ async fn test_set_operator_and_add_new_validator() { .import_private_key(OWNER_KEY, validator_key) .unwrap(); - // Verify no validator operator - let account_state_data = client - .get_account_state_blob(validator_account) - .await - .unwrap(); - let account_state_blob: AccountStateBlob = account_state_data.inner().clone().into(); - let account_state = AccountState::try_from(&account_state_blob).unwrap(); - let _val_config_resource = account_state - .get_validator_config_resource() - .unwrap() - .unwrap(); - // assert!(val_config_resource.delegated_account.is_none()); - // assert!(val_config_resource.validator_config.is_none()); + // TODO: Add check to Verify no validator operator when this test is enabled // Set the validator operator let txn_ctx = op_tool @@ -367,23 +354,6 @@ async fn test_set_operator_and_add_new_validator() { .await .unwrap(); - // Verify the operator has been set correctly - let account_state_data = client - .get_account_state_blob(validator_account) - .await - .unwrap(); - let account_state_blob: AccountStateBlob = account_state_data.inner().clone().into(); - let account_state = AccountState::try_from(&account_state_blob).unwrap(); - let _val_config_resource = account_state - .get_validator_config_resource() - .unwrap() - .unwrap(); - // assert_eq!( - // operator_account, - // val_config_resource.delegated_account.unwrap() - // ); - // assert!(val_config_resource.validator_config.is_none()); - // Overwrite the keys in storage to execute the command from the new operator's perspective storage.set(OPERATOR_ACCOUNT, operator_account).unwrap(); storage @@ -409,6 +379,8 @@ async fn test_set_operator_and_add_new_validator() { .await .unwrap(); + // TODO: Add check to verify the operator has been set correctly when this test is enabled + // Check the validator set size let validator_set_infos = op_tool.validator_set(None, Some(&backend)).await.unwrap(); assert_eq!(num_nodes, validator_set_infos.len()); @@ -1167,7 +1139,7 @@ async fn create_operator_with_file_writer( let client = validator.rest_client(); // Verify the corresponding account doesn't exist on-chain client - .get_account_state_blob(operator_account) + .get_account_resources(operator_account) .await .unwrap_err(); @@ -1190,16 +1162,14 @@ async fn create_operator_with_file_writer( assert!(txn_ctx.execution_result.unwrap().success); // Verify the operator account now exists on-chain - let account_state_data = client - .get_account_state_blob(operator_account) + let val_config_resource_response = client + .get_resource::( + operator_account, + std::str::from_utf8(&ValidatorOperatorConfigResource::resource_path()).unwrap(), + ) .await .unwrap(); - let account_state_blob: AccountStateBlob = account_state_data.inner().clone().into(); - let account_state = AccountState::try_from(&account_state_blob).unwrap(); - let op_config_resource = account_state - .get_validator_operator_config_resource() - .unwrap() - .unwrap(); + let op_config_resource = val_config_resource_response.inner().clone(); assert_eq!(op_human_name.as_bytes(), op_config_resource.human_name); } @@ -1219,7 +1189,7 @@ async fn create_validator_with_file_writer( let client = validator.rest_client(); // Verify the corresponding account doesn't exist on-chain client - .get_account_state_blob(validator_account) + .get_account_resources(validator_account) .await .unwrap_err(); @@ -1254,19 +1224,15 @@ async fn create_validator_with_file_writer( assert!(txn_ctx.execution_result.unwrap().success); // Verify the validator account now exists on-chain - let account_state_data = client - .get_account_state_blob(validator_account) + let val_config_resource_response = client + .get_resource::( + validator_account, + std::str::from_utf8(&aptos_types::validator_config::ValidatorConfig::resource_path()) + .unwrap(), + ) .await .unwrap(); - let account_state_blob: AccountStateBlob = account_state_data.inner().clone().into(); - let account_state = AccountState::try_from(&account_state_blob).unwrap(); - let _val_config_resource = account_state - .get_validator_config_resource() - .unwrap() - .unwrap(); - // assert_eq!(val_human_name.as_bytes(), val_config_resource.human_name); - // assert!(val_config_resource.delegated_account.is_none()); - // assert!(val_config_resource.validator_config.is_none()); + let _val_config_resource = val_config_resource_response.inner().clone(); } /// Launches a validator swarm of a specified size, connects an operational diff --git a/types/src/account_state.rs b/types/src/account_state.rs index 790aa1e852220..b07d6f6a05bf8 100644 --- a/types/src/account_state.rs +++ b/types/src/account_state.rs @@ -5,7 +5,6 @@ use crate::{ access_path::Path, account_address::AccountAddress, account_config::{AccountResource, BalanceResource}, - account_state_blob::AccountStateBlob, account_view::AccountView, state_store::{state_key::StateKey, state_value::StateValue}, }; @@ -132,14 +131,6 @@ impl TryFrom<&StateValue> for AccountState { } } -impl TryFrom<&AccountStateBlob> for AccountState { - type Error = Error; - - fn try_from(account_state_blob: &AccountStateBlob) -> Result { - bcs::from_bytes(&account_state_blob.blob).map_err(Into::into) - } -} - impl TryFrom<&Vec> for AccountState { type Error = Error; diff --git a/types/src/account_state_blob.rs b/types/src/account_state_blob.rs deleted file mode 100644 index 9040071604108..0000000000000 --- a/types/src/account_state_blob.rs +++ /dev/null @@ -1,196 +0,0 @@ -// Copyright (c) Aptos -// SPDX-License-Identifier: Apache-2.0 - -use crate::{ - account_config::{AccountResource, BalanceResource}, - account_state::AccountState, - account_view::AccountView, - state_store::state_value::StateValue, -}; -use anyhow::{anyhow, format_err, Error, Result}; -use aptos_crypto::{ - hash::{CryptoHash, CryptoHasher}, - HashValue, -}; -use aptos_crypto_derive::CryptoHasher; -#[cfg(any(test, feature = "fuzzing"))] -use proptest::{arbitrary::Arbitrary, prelude::*}; -use serde::{Deserialize, Deserializer, Serialize}; -use std::{convert::TryFrom, fmt}; - -#[derive(Clone, Eq, PartialEq, Serialize, CryptoHasher)] -pub struct AccountStateBlob { - pub blob: Vec, - #[serde(skip)] - hash: HashValue, -} - -impl<'de> Deserialize<'de> for AccountStateBlob { - fn deserialize(deserializer: D) -> Result - where - D: Deserializer<'de>, - { - #[derive(Deserialize)] - #[serde(rename = "AccountStateBlob")] - struct RawBlob { - blob: Vec, - } - let blob = RawBlob::deserialize(deserializer)?; - - Ok(Self::new(blob.blob)) - } -} - -impl AccountStateBlob { - fn new(blob: Vec) -> Self { - let mut hasher = AccountStateBlobHasher::default(); - hasher.update(&blob); - let hash = hasher.finish(); - Self { blob, hash } - } -} - -impl fmt::Debug for AccountStateBlob { - fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { - let decoded = bcs::from_bytes(&self.blob) - .map(|account_state: AccountState| format!("{:#?}", account_state)) - .unwrap_or_else(|_| String::from("[fail]")); - - write!( - f, - "AccountStateBlob {{ \n \ - Raw: 0x{} \n \ - Decoded: {} \n \ - }}", - hex::encode(&self.blob), - decoded, - ) - } -} - -impl AsRef<[u8]> for AccountStateBlob { - fn as_ref(&self) -> &[u8] { - &self.blob - } -} - -impl From<&AccountStateBlob> for Vec { - fn from(account_state_blob: &AccountStateBlob) -> Vec { - account_state_blob.blob.clone() - } -} - -impl From for Vec { - fn from(account_state_blob: AccountStateBlob) -> Vec { - Self::from(&account_state_blob) - } -} - -impl From> for AccountStateBlob { - fn from(blob: Vec) -> AccountStateBlob { - AccountStateBlob::new(blob) - } -} - -impl TryFrom<&AccountState> for AccountStateBlob { - type Error = Error; - - fn try_from(account_state: &AccountState) -> Result { - Ok(Self::new(bcs::to_bytes(account_state)?)) - } -} - -impl TryFrom for AccountStateBlob { - type Error = Error; - - fn try_from(state_value: StateValue) -> Result { - let bytes = state_value - .maybe_bytes - .ok_or_else(|| format_err!("Empty state value passed"))?; - Ok(AccountStateBlob::from(bytes)) - } -} - -impl TryFrom<(&AccountResource, &BalanceResource)> for AccountStateBlob { - type Error = Error; - - fn try_from( - (account_resource, balance_resource): (&AccountResource, &BalanceResource), - ) -> Result { - Self::try_from(&AccountState::try_from(( - account_resource, - balance_resource, - ))?) - } -} - -impl TryFrom<&AccountStateBlob> for AccountResource { - type Error = Error; - - fn try_from(account_state_blob: &AccountStateBlob) -> Result { - AccountState::try_from(account_state_blob)? - .get_account_resource()? - .ok_or_else(|| anyhow!("AccountResource not found.")) - } -} - -impl CryptoHash for AccountStateBlob { - type Hasher = AccountStateBlobHasher; - - fn hash(&self) -> HashValue { - self.hash - } -} - -#[cfg(any(test, feature = "fuzzing"))] -prop_compose! { - fn account_state_blob_strategy()(account_resource in any::(), balance_resource in any::()) -> AccountStateBlob { - AccountStateBlob::try_from((&account_resource, &balance_resource)).unwrap() - } -} - -#[cfg(any(test, feature = "fuzzing"))] -impl Arbitrary for AccountStateBlob { - type Parameters = (); - fn arbitrary_with(_args: Self::Parameters) -> Self::Strategy { - account_state_blob_strategy().boxed() - } - - type Strategy = BoxedStrategy; -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::state_store::state_value::StateValueWithProof; - use bcs::test_helpers::assert_canonical_encode_decode; - use proptest::collection::vec; - - fn hash_blob(blob: &[u8]) -> HashValue { - let mut hasher = AccountStateBlobHasher::default(); - hasher.update(blob); - hasher.finish() - } - - proptest! { - #[test] - fn account_state_blob_hash(blob in vec(any::(), 1..100)) { - prop_assert_eq!(hash_blob(&blob), AccountStateBlob::from(blob).hash()); - } - - #[test] - fn account_state_blob_bcs_roundtrip(account_state_blob in any::()) { - assert_canonical_encode_decode(account_state_blob); - } - - #[test] - fn account_state_with_proof_bcs_roundtrip(account_state_with_proof in any::()) { - assert_canonical_encode_decode(account_state_with_proof); - } - } - - #[test] - fn test_debug_does_not_panic() { - format!("{:#?}", AccountStateBlob::from(vec![1u8, 2u8, 3u8])); - } -} diff --git a/types/src/lib.rs b/types/src/lib.rs index 60245cffaee7f..ef2ee21bd6434 100644 --- a/types/src/lib.rs +++ b/types/src/lib.rs @@ -7,7 +7,6 @@ pub mod access_path; pub mod account_address; pub mod account_config; pub mod account_state; -pub mod account_state_blob; pub mod block_info; pub mod block_metadata; pub mod chain_id; diff --git a/types/src/proof/definition.rs b/types/src/proof/definition.rs index 3ebaa0eeb606b..14f1ee3e44229 100644 --- a/types/src/proof/definition.rs +++ b/types/src/proof/definition.rs @@ -749,7 +749,7 @@ impl StateStoreValueProof { } /// Verifies that the state of an account at version `state_version` is correct using the - /// provided proof. If `account_state_blob` is present, we expect the account to exist, + /// provided proof. If `state_value` is present, we expect the account to exist, /// otherwise we expect the account to not exist. pub fn verify( &self, diff --git a/types/src/proof/unit_tests/proof_conversion_test.rs b/types/src/proof/unit_tests/proof_conversion_test.rs index d2f12ff8153f9..05f8af9b2e8dc 100644 --- a/types/src/proof/unit_tests/proof_conversion_test.rs +++ b/types/src/proof/unit_tests/proof_conversion_test.rs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ - account_state_blob::AccountStateBlob, proof::{ definition::{ EventProof, StateStoreValueProof, TransactionInfoListWithProof, @@ -11,11 +10,12 @@ use crate::{ AccumulatorConsistencyProof, SparseMerkleRangeProof, TestAccumulatorProof, TestAccumulatorRangeProof, }, + state_store::state_value::StateValue, }; use bcs::test_helpers::assert_canonical_encode_decode; use proptest::prelude::*; -type SparseMerkleProof = crate::proof::SparseMerkleProof; +type SparseMerkleProof = crate::proof::SparseMerkleProof; proptest! { diff --git a/types/src/proptest_types.rs b/types/src/proptest_types.rs index c3eee74336c5d..8078f46f88a4d 100644 --- a/types/src/proptest_types.rs +++ b/types/src/proptest_types.rs @@ -6,7 +6,6 @@ use crate::{ account_address::{self, AccountAddress}, account_config::{AccountResource, BalanceResource}, account_state::AccountState, - account_state_blob::AccountStateBlob, block_info::{BlockInfo, Round}, block_metadata::BlockMetadata, chain_id::ChainId, @@ -670,22 +669,18 @@ impl BalanceResourceGen { } #[derive(Arbitrary, Debug)] -pub struct AccountStateBlobGen { +pub struct AccountStateGen { balance_resource_gen: BalanceResourceGen, account_resource_gen: AccountResourceGen, } -impl AccountStateBlobGen { - pub fn materialize( - self, - account_index: Index, - universe: &AccountInfoUniverse, - ) -> AccountStateBlob { +impl AccountStateGen { + pub fn materialize(self, account_index: Index, universe: &AccountInfoUniverse) -> AccountState { let account_resource = self .account_resource_gen .materialize(account_index, universe); let balance_resource = self.balance_resource_gen.materialize(); - AccountStateBlob::try_from((&account_resource, &balance_resource)).unwrap() + AccountState::try_from((&account_resource, &balance_resource)).unwrap() } } @@ -762,7 +757,7 @@ pub struct TransactionToCommitGen { /// State updates: account and the blob. /// N.B. the transaction sender and event owners must be updated to reflect information such as /// sequence numbers so that test data generated through this is more realistic and logical. - account_state_gens: Vec<(Index, AccountStateBlobGen)>, + account_state_gens: Vec<(Index, AccountStateGen)>, /// Write set write_set: WriteSet, /// Gas used. @@ -784,7 +779,7 @@ impl TransactionToCommitGen { .collect(); // Account states must be materialized last, to reflect the latest account and event // sequence numbers. - let account_states: HashMap = self + let account_states: HashMap = self .account_state_gens .into_iter() .map(|(index, blob_gen)| { @@ -796,16 +791,13 @@ impl TransactionToCommitGen { .collect(); let mut state_updates = HashMap::new(); - for (account_address, blob) in account_states { - AccountState::try_from(&blob) - .unwrap() - .iter() - .for_each(|(key, value)| { - state_updates.insert( - StateKey::AccessPath(AccessPath::new(account_address, key.clone())), - StateValue::from(value.clone()), - ); - }); + for (account_address, account_state) in account_states { + account_state.iter().for_each(|(key, value)| { + state_updates.insert( + StateKey::AccessPath(AccessPath::new(account_address, key.clone())), + StateValue::from(value.clone()), + ); + }); } TransactionToCommit::new( @@ -826,18 +818,18 @@ impl Arbitrary for TransactionToCommitGen { ( ( any::(), - any::(), + any::(), any::(), ), vec( ( any::(), - any::(), + any::(), any::(), ), 0..=2, ), - vec((any::(), any::()), 0..=1), + vec((any::(), any::()), 0..=1), any::(), any::(), any::(), diff --git a/types/src/state_store/state_value.rs b/types/src/state_store/state_value.rs index b78c7598d16b9..0b733bb058ce2 100644 --- a/types/src/state_store/state_value.rs +++ b/types/src/state_store/state_value.rs @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 use crate::{ - account_state_blob::AccountStateBlob, ledger_info::LedgerInfo, proof::{SparseMerkleRangeProof, StateStoreValueProof}, state_store::state_key::StateKey, @@ -52,12 +51,6 @@ impl StateValue { } } -impl From for StateValue { - fn from(account_state_blob: AccountStateBlob) -> Self { - StateValue::new(Some(account_state_blob.blob)) - } -} - impl From> for StateValue { fn from(bytes: Vec) -> Self { StateValue::new(Some(bytes))