From 40316c072691355853bff3a00cda42bc28bdd669 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Fri, 27 Dec 2024 09:06:48 +0700 Subject: [PATCH] compiling --- Cargo.lock | 11 + Cargo.toml | 3 +- package.json | 3 +- packages/data-contracts/Cargo.toml | 1 + packages/data-contracts/src/error.rs | 18 ++ packages/data-contracts/src/lib.rs | 10 + .../rs-dpp/src/data_contract/accessors/mod.rs | 7 + .../src/data_contract/accessors/v1/mod.rs | 4 + .../token_configuration/mod.rs | 2 +- .../token_configuration/v0/mod.rs | 50 ++++ .../data_contract/change_control_rules/mod.rs | 5 +- .../change_control_rules/v0/mod.rs | 8 +- packages/rs-dpp/src/data_contract/mod.rs | 2 +- .../src/data_contract/v1/accessors/mod.rs | 11 + .../src/data_contract/v1/methods/schema.rs | 2 +- .../src/state_transition/serialization.rs | 4 +- .../batch_transition/json_conversion.rs | 9 + .../batch_transition/v1/value_conversion.rs | 4 +- .../batch_transition/value_conversion.rs | 29 ++- .../v0/mod.rs | 41 ++++ .../contract/insert/insert_contract/mod.rs | 16 +- .../contract/insert/insert_contract/v0/mod.rs | 2 +- .../contract/insert/insert_contract/v1/mod.rs | 187 +++++++++++++++ .../contract/update/update_contract/mod.rs | 34 ++- .../contract/update/update_contract/v0/mod.rs | 2 +- .../contract/update/update_contract/v1/mod.rs | 225 ++++++++++++++++++ .../rs-drive/src/drive/initialization/mod.rs | 4 +- .../src/drive/initialization/v0/mod.rs | 32 ++- .../src/drive/initialization/v1/mod.rs | 67 ++++++ .../fetch_identities_token_balances/v0/mod.rs | 16 +- .../rs-drive/src/drive/tokens/balance/mod.rs | 2 - .../src/drive/tokens/balance/prove.rs | 165 ------------- .../prove_identities_token_balances/v0/mod.rs | 225 ++++++++++++++++-- .../src/drive/tokens/balance/queries.rs | 2 +- packages/rs-drive/src/drive/tokens/mod.rs | 6 +- .../mod.rs | 30 ++- .../v0/mod.rs | 74 +++++- .../rs-drive/src/drive/tokens/system/mod.rs | 2 +- packages/rs-drive/src/fees/op.rs | 16 ++ .../batch_insert_empty_sum_tree/mod.rs | 46 ++++ .../batch_insert_empty_sum_tree/v0/mod.rs | 51 ++++ .../rs-drive/src/util/grove_operations/mod.rs | 3 + packages/rs-drive/src/verify/mod.rs | 1 + packages/rs-drive/src/verify/tokens/mod.rs | 1 + .../mod.rs | 81 +++++++ .../v0/mod.rs | 72 ++++++ .../drive_contract_method_versions/mod.rs | 1 + .../drive_contract_method_versions/v2.rs | 33 +++ .../drive_grove_method_versions/mod.rs | 1 + .../drive_grove_method_versions/v1.rs | 1 + .../drive_token_method_versions/mod.rs | 2 +- .../drive_token_method_versions/v1.rs | 2 +- .../drive_verify_method_versions/mod.rs | 7 + .../drive_verify_method_versions/v1.rs | 11 +- .../src/version/drive_versions/mod.rs | 1 + .../src/version/drive_versions/v3.rs | 102 ++++++++ .../rs-platform-version/src/version/mod.rs | 4 +- .../src/version/protocol_version.rs | 1 + .../rs-platform-version/src/version/v8.rs | 4 +- packages/token-history-contract/Cargo.toml | 4 +- .../wasm-dpp/src/document/document_facade.rs | 4 +- packages/wasm-dpp/src/document/factory.rs | 4 +- .../batched_transition/mod.rs | 18 ++ .../document_create_transition.rs | 0 .../document_delete_transition.rs | 0 .../document_replace_transition.rs | 0 .../document_transition/mod.rs | 0 .../mod.rs | 10 +- .../batch_transition/token_transition/mod.rs | 18 ++ .../validation/basic/find_duplicates_by_id.rs | 0 .../basic/find_duplicates_by_indices.rs | 0 .../validation/basic/mod.rs | 0 ...lidate_documents_batch_transition_basic.rs | 0 .../validate_partial_compound_indices.rs | 0 .../validation/mod.rs | 0 .../state/fetch_extended_documents.rs | 0 .../validation/state/mod.rs | 0 ...idate_documents_batch_transitions_state.rs | 0 ...alidate_documents_uniqueness_by_indices.rs | 0 .../src/document/state_transition/mod.rs | 2 +- .../src/errors/consensus/consensus_error.rs | 9 +- .../state_transition_factory.rs | 4 +- 82 files changed, 1550 insertions(+), 279 deletions(-) create mode 100644 packages/rs-drive/src/drive/contract/insert/insert_contract/v1/mod.rs create mode 100644 packages/rs-drive/src/drive/contract/update/update_contract/v1/mod.rs create mode 100644 packages/rs-drive/src/drive/initialization/v1/mod.rs delete mode 100644 packages/rs-drive/src/drive/tokens/balance/prove.rs rename packages/rs-drive/src/drive/tokens/system/{create_token_root_tree => create_token_trees}/mod.rs (78%) rename packages/rs-drive/src/drive/tokens/system/{create_token_root_tree => create_token_trees}/v0/mod.rs (63%) create mode 100644 packages/rs-drive/src/util/grove_operations/batch_insert_empty_sum_tree/mod.rs create mode 100644 packages/rs-drive/src/util/grove_operations/batch_insert_empty_sum_tree/v0/mod.rs create mode 100644 packages/rs-drive/src/verify/tokens/mod.rs create mode 100644 packages/rs-drive/src/verify/tokens/verify_token_balances_for_identity_ids/mod.rs create mode 100644 packages/rs-drive/src/verify/tokens/verify_token_balances_for_identity_ids/v0/mod.rs create mode 100644 packages/rs-platform-version/src/version/drive_versions/drive_contract_method_versions/v2.rs create mode 100644 packages/rs-platform-version/src/version/drive_versions/v3.rs create mode 100644 packages/wasm-dpp/src/document/state_transition/batch_transition/batched_transition/mod.rs rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/document_transition/document_create_transition.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/document_transition/document_delete_transition.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/document_transition/document_replace_transition.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/document_transition/mod.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/mod.rs (97%) create mode 100644 packages/wasm-dpp/src/document/state_transition/batch_transition/token_transition/mod.rs rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/basic/find_duplicates_by_id.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/basic/find_duplicates_by_indices.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/basic/mod.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/basic/validate_documents_batch_transition_basic.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/basic/validate_partial_compound_indices.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/mod.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/state/fetch_extended_documents.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/state/mod.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/state/validate_documents_batch_transitions_state.rs (100%) rename packages/wasm-dpp/src/document/state_transition/{document_batch_transition => batch_transition}/validation/state/validate_documents_uniqueness_by_indices.rs (100%) diff --git a/Cargo.lock b/Cargo.lock index d249acda8f8..9faea6603cc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1234,6 +1234,7 @@ dependencies = [ "platform-version", "serde_json", "thiserror 1.0.69", + "token-history-contract", "wallet-utils-contract", "withdrawals-contract", ] @@ -4894,6 +4895,16 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" +[[package]] +name = "token-history-contract" +version = "1.6.2" +dependencies = [ + "platform-value", + "platform-version", + "serde_json", + "thiserror 1.0.69", +] + [[package]] name = "tokio" version = "1.41.1" diff --git a/Cargo.toml b/Cargo.toml index 3b7b503758f..30f5e9d4f48 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -28,7 +28,8 @@ members = [ "packages/simple-signer", "packages/rs-json-schema-compatibility-validator", "packages/check-features", - "packages/wallet-utils-contract" + "packages/wallet-utils-contract", + "packages/token-history-contract" ] [workspace.package] diff --git a/package.json b/package.json index 16a30ea3df1..5471364e5f9 100644 --- a/package.json +++ b/package.json @@ -65,7 +65,8 @@ "packages/masternode-reward-shares-contract", "packages/dash-spv", "packages/wasm-dpp", - "packages/withdrawals-contract" + "packages/withdrawals-contract", + "packages/token-history-contract" ], "resolutions": { "elliptic": "6.5.7", diff --git a/packages/data-contracts/Cargo.toml b/packages/data-contracts/Cargo.toml index 1c011e3d109..74a5cb70d51 100644 --- a/packages/data-contracts/Cargo.toml +++ b/packages/data-contracts/Cargo.toml @@ -17,3 +17,4 @@ dashpay-contract = { path = "../dashpay-contract" } feature-flags-contract = { path = "../feature-flags-contract" } platform-value = { path = "../rs-platform-value" } wallet-utils-contract = { path = "../wallet-utils-contract" } +token-history-contract = { path = "../token-history-contract" } diff --git a/packages/data-contracts/src/error.rs b/packages/data-contracts/src/error.rs index 0550873b012..d2f33d32250 100644 --- a/packages/data-contracts/src/error.rs +++ b/packages/data-contracts/src/error.rs @@ -119,3 +119,21 @@ impl From for Error { } } } + +impl From for Error { + fn from(e: token_history_contract::Error) -> Self { + match e { + token_history_contract::Error::UnknownVersionMismatch { + method, + known_versions, + received, + } => Error::UnknownVersionMismatch { + method, + known_versions, + received, + }, + token_history_contract::Error::InvalidSchemaJson(e) => Error::InvalidSchemaJson(e), + } + } +} + diff --git a/packages/data-contracts/src/lib.rs b/packages/data-contracts/src/lib.rs index 65f324137fd..cf82480300f 100644 --- a/packages/data-contracts/src/lib.rs +++ b/packages/data-contracts/src/lib.rs @@ -11,6 +11,7 @@ use platform_value::Identifier; use platform_version::version::PlatformVersion; pub use wallet_utils_contract; pub use withdrawals_contract; +pub use token_history_contract; #[repr(u8)] #[derive(PartialEq, Eq, Clone, Copy, Debug, Ord, PartialOrd, Hash)] @@ -21,6 +22,7 @@ pub enum SystemDataContract { DPNS = 3, Dashpay = 4, WalletUtils = 5, + TokenHistory = 6, } pub struct DataContractSource { @@ -40,6 +42,7 @@ impl SystemDataContract { SystemDataContract::DPNS => dpns_contract::ID_BYTES, SystemDataContract::Dashpay => dashpay_contract::ID_BYTES, SystemDataContract::WalletUtils => wallet_utils_contract::ID_BYTES, + SystemDataContract::TokenHistory => token_history_contract::ID_BYTES, }; Identifier::new(bytes) } @@ -92,6 +95,13 @@ impl SystemDataContract { definitions: wallet_utils_contract::load_definitions(platform_version)?, document_schemas: wallet_utils_contract::load_documents_schemas(platform_version)?, }, + SystemDataContract::TokenHistory => DataContractSource { + id_bytes: token_history_contract::ID_BYTES, + owner_id_bytes: token_history_contract::OWNER_ID_BYTES, + version: platform_version.system_data_contracts.wallet as u32, + definitions: token_history_contract::load_definitions(platform_version)?, + document_schemas: token_history_contract::load_documents_schemas(platform_version)?, + }, }; Ok(data) diff --git a/packages/rs-dpp/src/data_contract/accessors/mod.rs b/packages/rs-dpp/src/data_contract/accessors/mod.rs index 52b1076c3a9..4d320e7a001 100644 --- a/packages/rs-dpp/src/data_contract/accessors/mod.rs +++ b/packages/rs-dpp/src/data_contract/accessors/mod.rs @@ -219,6 +219,13 @@ impl DataContractV1Getters for DataContract { DataContract::V1(v1) => Some(&mut v1.tokens), } } + + fn token_id(&self, position: TokenContractPosition) -> Option { + match self { + DataContract::V0(_) => None, + DataContract::V1(v1) => v1.token_id(position), + } + } } impl DataContractV1Setters for DataContract { diff --git a/packages/rs-dpp/src/data_contract/accessors/v1/mod.rs b/packages/rs-dpp/src/data_contract/accessors/v1/mod.rs index 9d23a0e8374..57a3212cef2 100644 --- a/packages/rs-dpp/src/data_contract/accessors/v1/mod.rs +++ b/packages/rs-dpp/src/data_contract/accessors/v1/mod.rs @@ -3,6 +3,7 @@ use crate::data_contract::associated_token::token_configuration::TokenConfigurat use crate::data_contract::group::{Group, GroupName}; use crate::data_contract::TokenContractPosition; use std::collections::BTreeMap; +use platform_value::Identifier; pub trait DataContractV1Getters: DataContractV0Getters { /// Returns a reference to the groups map. @@ -16,6 +17,9 @@ pub trait DataContractV1Getters: DataContractV0Getters { /// Returns a mutable reference to the tokens map. fn tokens_mut(&mut self) -> Option<&mut BTreeMap>; + + /// Returns the token id at a certain position + fn token_id(&self, position: TokenContractPosition) -> Option; } pub trait DataContractV1Setters: DataContractV0Setters { diff --git a/packages/rs-dpp/src/data_contract/associated_token/token_configuration/mod.rs b/packages/rs-dpp/src/data_contract/associated_token/token_configuration/mod.rs index 899fe85b0da..fa82163d4cc 100644 --- a/packages/rs-dpp/src/data_contract/associated_token/token_configuration/mod.rs +++ b/packages/rs-dpp/src/data_contract/associated_token/token_configuration/mod.rs @@ -7,7 +7,7 @@ use std::fmt; pub mod accessors; mod methods; -mod v0; +pub mod v0; #[derive(Serialize, Deserialize, Encode, Decode, Debug, Clone, PartialEq, Eq, From)] #[serde(tag = "$format_version")] diff --git a/packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/mod.rs b/packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/mod.rs index 55f8699692c..af7b3052212 100644 --- a/packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/mod.rs +++ b/packages/rs-dpp/src/data_contract/associated_token/token_configuration/v0/mod.rs @@ -8,6 +8,7 @@ use platform_value::Identifier; use serde::{Deserialize, Serialize}; use std::collections::{BTreeMap, BTreeSet}; use std::fmt; +use crate::data_contract::change_control_rules::v0::ChangeControlRulesV0; #[derive(Serialize, Deserialize, Decode, Encode, Debug, Clone, PartialEq, Eq)] #[serde(rename_all = "camelCase")] @@ -66,3 +67,52 @@ impl fmt::Display for TokenConfigurationV0 { ) } } + +impl TokenConfigurationV0 { + pub fn default_most_restrictive() -> Self { + Self { + conventions: TokenConfigurationConventionV0 { localizations: Default::default(), decimals: 8 }, + base_supply: 100000, + max_supply: None, + max_supply_change_rules: ChangeControlRulesV0 { + authorized_to_make_change: AuthorizedActionTakers::NoOne, + authorized_to_change_authorized_action_takers: AuthorizedActionTakers::NoOne, + changing_authorized_action_takers_to_no_one_allowed: false, + changing_authorized_action_takers_to_contract_owner_allowed: false, + }.into(), + new_tokens_destination_identity: None, + new_tokens_destination_identity_rules: ChangeControlRulesV0 { + authorized_to_make_change: AuthorizedActionTakers::NoOne, + authorized_to_change_authorized_action_takers: AuthorizedActionTakers::NoOne, + changing_authorized_action_takers_to_no_one_allowed: false, + changing_authorized_action_takers_to_contract_owner_allowed: false, + }.into(), + manual_minting_rules: ChangeControlRulesV0 { + authorized_to_make_change: AuthorizedActionTakers::NoOne, + authorized_to_change_authorized_action_takers: AuthorizedActionTakers::NoOne, + changing_authorized_action_takers_to_no_one_allowed: false, + changing_authorized_action_takers_to_contract_owner_allowed: false, + }.into(), + manual_burning_rules: ChangeControlRulesV0 { + authorized_to_make_change: AuthorizedActionTakers::NoOne, + authorized_to_change_authorized_action_takers: AuthorizedActionTakers::NoOne, + changing_authorized_action_takers_to_no_one_allowed: false, + changing_authorized_action_takers_to_contract_owner_allowed: false, + }.into(), + freeze_rules: ChangeControlRulesV0 { + authorized_to_make_change: AuthorizedActionTakers::NoOne, + authorized_to_change_authorized_action_takers: AuthorizedActionTakers::NoOne, + changing_authorized_action_takers_to_no_one_allowed: false, + changing_authorized_action_takers_to_contract_owner_allowed: false, + }.into(), + unfreeze_rules: ChangeControlRulesV0 { + authorized_to_make_change: AuthorizedActionTakers::NoOne, + authorized_to_change_authorized_action_takers: AuthorizedActionTakers::NoOne, + changing_authorized_action_takers_to_no_one_allowed: false, + changing_authorized_action_takers_to_contract_owner_allowed: false, + }.into(), + main_control_group: None, + main_control_group_can_be_modified: AuthorizedActionTakers::NoOne, + } + } +} diff --git a/packages/rs-dpp/src/data_contract/change_control_rules/mod.rs b/packages/rs-dpp/src/data_contract/change_control_rules/mod.rs index efa7304690a..756c507014f 100644 --- a/packages/rs-dpp/src/data_contract/change_control_rules/mod.rs +++ b/packages/rs-dpp/src/data_contract/change_control_rules/mod.rs @@ -1,14 +1,15 @@ pub mod authorized_action_takers; -mod v0; +pub mod v0; use crate::data_contract::change_control_rules::v0::ChangeControlRulesV0; use crate::data_contract::group::Group; use crate::multi_identity_events::ActionTaker; use bincode::{Decode, Encode}; +use derive_more::From; use platform_value::Identifier; use serde::{Deserialize, Serialize}; -#[derive(Serialize, Deserialize, Decode, Encode, Debug, Clone, PartialEq, Eq)] +#[derive(Serialize, Deserialize, Decode, Encode, Debug, Clone, PartialEq, Eq, From)] pub enum ChangeControlRules { V0(ChangeControlRulesV0), } diff --git a/packages/rs-dpp/src/data_contract/change_control_rules/v0/mod.rs b/packages/rs-dpp/src/data_contract/change_control_rules/v0/mod.rs index 2e4b3439b11..db59f7d7e63 100644 --- a/packages/rs-dpp/src/data_contract/change_control_rules/v0/mod.rs +++ b/packages/rs-dpp/src/data_contract/change_control_rules/v0/mod.rs @@ -8,13 +8,13 @@ use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Decode, Encode, Debug, Clone, PartialEq, Eq)] pub struct ChangeControlRulesV0 { /// This is who is authorized to make such a change - authorized_to_make_change: AuthorizedActionTakers, + pub authorized_to_make_change: AuthorizedActionTakers, /// This is who is authorized to make such a change to the people authorized to make a change - authorized_to_change_authorized_action_takers: AuthorizedActionTakers, + pub authorized_to_change_authorized_action_takers: AuthorizedActionTakers, /// Are we allowed to change to None in the future - changing_authorized_action_takers_to_no_one_allowed: bool, + pub changing_authorized_action_takers_to_no_one_allowed: bool, /// Are we allowed to change to None in the future - changing_authorized_action_takers_to_contract_owner_allowed: bool, + pub changing_authorized_action_takers_to_contract_owner_allowed: bool, } impl ChangeControlRulesV0 { diff --git a/packages/rs-dpp/src/data_contract/mod.rs b/packages/rs-dpp/src/data_contract/mod.rs index d609e535e34..b58bd46cce9 100644 --- a/packages/rs-dpp/src/data_contract/mod.rs +++ b/packages/rs-dpp/src/data_contract/mod.rs @@ -36,7 +36,7 @@ pub mod serialized_version; pub use methods::*; pub mod accessors; pub mod associated_token; -mod change_control_rules; +pub mod change_control_rules; pub mod config; mod group; pub mod storage_requirements; diff --git a/packages/rs-dpp/src/data_contract/v1/accessors/mod.rs b/packages/rs-dpp/src/data_contract/v1/accessors/mod.rs index 23d1be1113e..b84eefccf4f 100644 --- a/packages/rs-dpp/src/data_contract/v1/accessors/mod.rs +++ b/packages/rs-dpp/src/data_contract/v1/accessors/mod.rs @@ -13,6 +13,7 @@ use crate::data_contract::document_type::accessors::DocumentTypeV0Getters; use crate::data_contract::group::{Group, GroupName}; use platform_value::Identifier; use std::collections::BTreeMap; +use crate::util::hash::hash_double; impl DataContractV0Getters for DataContractV1 { fn id(&self) -> Identifier { @@ -158,6 +159,16 @@ impl DataContractV1Getters for DataContractV1 { fn tokens_mut(&mut self) -> Option<&mut BTreeMap> { Some(&mut self.tokens) } + + /// Returns the token id if a token exists at that position + fn token_id(&self, position: TokenContractPosition) -> Option { + self.tokens.get(&position).map(|_| { + let mut bytes = b"dash_token".to_vec(); + bytes.extend_from_slice(self.id().as_bytes()); + bytes.extend_from_slice(&position.to_be_bytes()); + hash_double(bytes).into() + }) + } } impl DataContractV1Setters for DataContractV1 { diff --git a/packages/rs-dpp/src/data_contract/v1/methods/schema.rs b/packages/rs-dpp/src/data_contract/v1/methods/schema.rs index 8173352e8fa..3b88cc59142 100644 --- a/packages/rs-dpp/src/data_contract/v1/methods/schema.rs +++ b/packages/rs-dpp/src/data_contract/v1/methods/schema.rs @@ -103,7 +103,7 @@ mod test { use super::*; use crate::data_contract::config::DataContractConfig; use crate::data_contract::serialized_version::v0::DataContractInSerializationFormatV0; - use crate::data_contract::v0::DataContractV1; + use crate::data_contract::v1::DataContractV1; use platform_value::{platform_value, Identifier}; #[test] diff --git a/packages/rs-dpp/src/state_transition/serialization.rs b/packages/rs-dpp/src/state_transition/serialization.rs index bea1ab72cfd..ff55d2653ab 100644 --- a/packages/rs-dpp/src/state_transition/serialization.rs +++ b/packages/rs-dpp/src/state_transition/serialization.rs @@ -29,7 +29,7 @@ mod tests { }; use crate::state_transition::batch_transition::batched_transition::document_transition_action_type::DocumentTransitionActionType; use crate::state_transition::batch_transition::{ - BatchTransition, BatchTransitionV0, + BatchTransition, BatchTransitionV1, }; use crate::state_transition::identity_create_transition::v0::IdentityCreateTransitionV0; use crate::state_transition::identity_create_transition::IdentityCreateTransition; @@ -342,7 +342,7 @@ mod tests { [(DocumentTransitionActionType::Create, documents)], &mut nonces, ); - let documents_batch_transition: BatchTransition = BatchTransitionV0 { + let documents_batch_transition: BatchTransition = BatchTransitionV1 { owner_id: data_contract.owner_id(), transitions, ..Default::default() diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/json_conversion.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/json_conversion.rs index f74b93740a6..80d5c5c7911 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/json_conversion.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/json_conversion.rs @@ -22,6 +22,15 @@ impl<'a> StateTransitionJsonConvert<'a> for BatchTransition { ); Ok(value) } + BatchTransition::V1(transition) => { + let mut value = transition.to_json(options)?; + let map_value = value.as_object_mut().expect("expected an object"); + map_value.insert( + STATE_TRANSITION_PROTOCOL_VERSION.to_string(), + JsonValue::Number(Number::from(1)), + ); + Ok(value) + } } } } diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/value_conversion.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/value_conversion.rs index 5438c1e2d09..53a75f0a890 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/value_conversion.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/value_conversion.rs @@ -1,4 +1,4 @@ -use crate::state_transition::batch_transition::BatchTransitionV0; +use crate::state_transition::batch_transition::BatchTransitionV1; use crate::state_transition::StateTransitionValueConvert; -impl<'a> StateTransitionValueConvert<'a> for BatchTransitionV0 {} +impl<'a> StateTransitionValueConvert<'a> for BatchTransitionV1 {} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/value_conversion.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/value_conversion.rs index 9df007a4e85..a53a64ff534 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/value_conversion.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/value_conversion.rs @@ -4,7 +4,7 @@ use platform_value::Value; use crate::ProtocolError; -use crate::state_transition::batch_transition::{BatchTransition, BatchTransitionV0}; +use crate::state_transition::batch_transition::{BatchTransition, BatchTransitionV0, BatchTransitionV1}; use crate::state_transition::state_transitions::batch_transition::fields::*; use crate::state_transition::StateTransitionValueConvert; @@ -19,6 +19,11 @@ impl<'a> StateTransitionValueConvert<'a> for BatchTransition { value.insert(STATE_TRANSITION_PROTOCOL_VERSION.to_string(), Value::U16(0))?; Ok(value) } + BatchTransition::V1(transition) => { + let mut value = transition.to_object(skip_signature)?; + value.insert(STATE_TRANSITION_PROTOCOL_VERSION.to_string(), Value::U16(1))?; + Ok(value) + } } } @@ -29,6 +34,11 @@ impl<'a> StateTransitionValueConvert<'a> for BatchTransition { value.insert(STATE_TRANSITION_PROTOCOL_VERSION.to_string(), Value::U16(0))?; Ok(value) } + BatchTransition::V1(transition) => { + let mut value = transition.to_canonical_object(skip_signature)?; + value.insert(STATE_TRANSITION_PROTOCOL_VERSION.to_string(), Value::U16(1))?; + Ok(value) + } } } @@ -39,6 +49,11 @@ impl<'a> StateTransitionValueConvert<'a> for BatchTransition { value.insert(STATE_TRANSITION_PROTOCOL_VERSION.to_string(), Value::U16(0))?; Ok(value) } + BatchTransition::V1(transition) => { + let mut value = transition.to_canonical_cleaned_object(skip_signature)?; + value.insert(STATE_TRANSITION_PROTOCOL_VERSION.to_string(), Value::U16(1))?; + Ok(value) + } } } @@ -49,6 +64,11 @@ impl<'a> StateTransitionValueConvert<'a> for BatchTransition { value.insert(STATE_TRANSITION_PROTOCOL_VERSION.to_string(), Value::U16(0))?; Ok(value) } + BatchTransition::V1(transition) => { + let mut value = transition.to_cleaned_object(skip_signature)?; + value.insert(STATE_TRANSITION_PROTOCOL_VERSION.to_string(), Value::U16(1))?; + Ok(value) + } } } @@ -69,8 +89,9 @@ impl<'a> StateTransitionValueConvert<'a> for BatchTransition { match version { 0 => Ok(BatchTransitionV0::from_object(raw_object, platform_version)?.into()), + 1 => Ok(BatchTransitionV1::from_object(raw_object, platform_version)?.into()), n => Err(ProtocolError::UnknownVersionError(format!( - "Unknown DataContractCreateTransition version {n}" + "Unknown contract_create_state_transition default_current_version {n}" ))), } } @@ -92,8 +113,9 @@ impl<'a> StateTransitionValueConvert<'a> for BatchTransition { match version { 0 => Ok(BatchTransitionV0::from_value_map(raw_value_map, platform_version)?.into()), + 1 => Ok(BatchTransitionV1::from_value_map(raw_value_map, platform_version)?.into()), n => Err(ProtocolError::UnknownVersionError(format!( - "Unknown DataContractCreateTransition version {n}" + "Unknown contract_create_state_transition default_current_version {n}" ))), } } @@ -105,6 +127,7 @@ impl<'a> StateTransitionValueConvert<'a> for BatchTransition { match version { 0 => BatchTransitionV0::clean_value(value), + 1 => BatchTransitionV1::clean_value(value), n => Err(ProtocolError::UnknownVersionError(format!( "Unknown DataContractCreateTransition version {n}" ))), diff --git a/packages/rs-drive-abci/src/execution/platform_events/protocol_upgrade/perform_events_on_first_block_of_protocol_change/v0/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/protocol_upgrade/perform_events_on_first_block_of_protocol_change/v0/mod.rs index d36250ea3e7..8bf290565d1 100644 --- a/packages/rs-drive-abci/src/execution/platform_events/protocol_upgrade/perform_events_on_first_block_of_protocol_change/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/platform_events/protocol_upgrade/perform_events_on_first_block_of_protocol_change/v0/mod.rs @@ -8,6 +8,7 @@ use dpp::data_contracts::SystemDataContract; use dpp::system_data_contracts::load_system_data_contract; use dpp::version::PlatformVersion; use dpp::version::ProtocolVersion; +use drive::drive::balances::TOTAL_TOKEN_SUPPLIES_STORAGE_KEY; use drive::drive::identity::key::fetch::{ IdentityKeysRequest, KeyIDIdentityPublicKeyPairBTreeMap, KeyRequestType, }; @@ -15,6 +16,7 @@ use drive::drive::identity::withdrawals::paths::{ get_withdrawal_root_path, WITHDRAWAL_TRANSACTIONS_BROADCASTED_KEY, WITHDRAWAL_TRANSACTIONS_SUM_AMOUNT_TREE_KEY, }; +use drive::drive::system::misc_path; use drive::grovedb::{Element, Transaction}; impl Platform { @@ -58,6 +60,10 @@ impl Platform { self.transition_to_version_6(block_info, transaction, platform_version)?; } + if previous_protocol_version < 8 && platform_version.protocol_version >= 8 { + self.transition_to_version_8(block_info, transaction, platform_version)?; + } + Ok(()) } @@ -86,6 +92,41 @@ impl Platform { Ok(()) } + /// Adds all trees needed for tokens, also adds the token history system data contract + /// + /// This function is called during the transition from protocol version 5 to protocol version 6 + /// and higher to set up the wallet contract in the platform. + fn transition_to_version_8( + &self, + block_info: &BlockInfo, + transaction: &Transaction, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + let path = misc_path(); + self.drive.grove_insert_if_not_exists( + (&path).into(), + TOTAL_TOKEN_SUPPLIES_STORAGE_KEY.as_slice(), + Element::empty_tree(), + Some(transaction), + None, + &platform_version.drive, + )?; + + let contract = + load_system_data_contract(SystemDataContract::TokenHistory, platform_version)?; + + self.drive.insert_contract( + &contract, + *block_info, + true, + Some(transaction), + platform_version, + )?; + + Ok(()) + } + + /// Initializes an empty sum tree for withdrawal transactions required for protocol version 4. /// /// This function is called during the transition to protocol version 4 to set up diff --git a/packages/rs-drive/src/drive/contract/insert/insert_contract/mod.rs b/packages/rs-drive/src/drive/contract/insert/insert_contract/mod.rs index 8b39715cbb7..cfae17fd1c2 100644 --- a/packages/rs-drive/src/drive/contract/insert/insert_contract/mod.rs +++ b/packages/rs-drive/src/drive/contract/insert/insert_contract/mod.rs @@ -1,4 +1,5 @@ mod v0; +mod v1; use crate::drive::Drive; use crate::error::drive::DriveError; @@ -51,9 +52,12 @@ impl Drive { 0 => { self.insert_contract_v0(contract, block_info, apply, transaction, platform_version) } + 1 => { + self.insert_contract_v1(contract, block_info, apply, transaction, platform_version) + } version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "insert_contract".to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, })), } @@ -103,9 +107,17 @@ impl Drive { drive_operations, platform_version, ), + 1 => self.insert_contract_add_operations_v1( + contract_element, + contract, + block_info, + estimated_costs_only_with_layer_info, + drive_operations, + platform_version, + ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "insert_contract_add_operations".to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, })), } diff --git a/packages/rs-drive/src/drive/contract/insert/insert_contract/v0/mod.rs b/packages/rs-drive/src/drive/contract/insert/insert_contract/v0/mod.rs index 207626f0641..635e315e86e 100644 --- a/packages/rs-drive/src/drive/contract/insert/insert_contract/v0/mod.rs +++ b/packages/rs-drive/src/drive/contract/insert/insert_contract/v0/mod.rs @@ -145,7 +145,7 @@ impl Drive { /// The operations for adding a contract. /// These operations add a contract to storage using `add_contract_to_storage` /// and insert the empty trees which will be necessary to later insert documents. - fn insert_contract_operations_v0( + pub(in crate::drive::contract::insert::insert_contract) fn insert_contract_operations_v0( &self, contract_element: Element, contract: &DataContract, diff --git a/packages/rs-drive/src/drive/contract/insert/insert_contract/v1/mod.rs b/packages/rs-drive/src/drive/contract/insert/insert_contract/v1/mod.rs new file mode 100644 index 00000000000..37d4ebd9fc3 --- /dev/null +++ b/packages/rs-drive/src/drive/contract/insert/insert_contract/v1/mod.rs @@ -0,0 +1,187 @@ +use crate::drive::Drive; +use crate::util::storage_flags::StorageFlags; + +use crate::error::Error; +use crate::fees::op::LowLevelDriveOperation; +use dpp::block::block_info::BlockInfo; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::config::v0::DataContractConfigGettersV0; +use dpp::data_contract::DataContract; +use dpp::fee::fee_result::FeeResult; + +use dpp::serialization::PlatformSerializableWithPlatformVersion; +use crate::error::contract::DataContractError; +use dpp::version::PlatformVersion; +use grovedb::batch::KeyInfoPath; +use grovedb::{Element, EstimatedLayerInformation, TransactionArg}; +use std::collections::HashMap; +use dpp::data_contract::accessors::v1::DataContractV1Getters; +use crate::drive::balances::total_tokens_root_supply_path; +use crate::drive::tokens::{TOKEN_BALANCES_KEY, token_path, tokens_root_path}; +use crate::util::grove_operations::BatchInsertTreeApplyType; +use crate::util::object_size_info::DriveKeyInfo; + +impl Drive { + /// Insert a contract. + #[inline(always)] + pub(super) fn insert_contract_v1( + &self, + contract: &DataContract, + block_info: BlockInfo, + apply: bool, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result { + let mut drive_operations: Vec = vec![]; + + let storage_flags = if contract.config().can_be_deleted() || !contract.config().readonly() { + Some(StorageFlags::new_single_epoch( + block_info.epoch.index, + Some(contract.owner_id().to_buffer()), + )) + } else { + None + }; + + let serialized_contract = + contract.serialize_to_bytes_with_platform_version(platform_version)?; + + if serialized_contract.len() as u64 > u32::MAX as u64 + || serialized_contract.len() as u32 + > platform_version.dpp.contract_versions.max_serialized_size + { + // This should normally be caught by DPP, but there is a rare possibility that the + // re-serialized size is bigger than the original serialized data contract. + return Err(Error::DataContract(DataContractError::ContractTooBig(format!("Trying to insert a data contract of size {} that is over the max allowed insertion size {}", serialized_contract.len(), platform_version.dpp.contract_versions.max_serialized_size)))); + } + + let contract_element = Element::Item( + serialized_contract, + StorageFlags::map_to_some_element_flags(storage_flags.as_ref()), + ); + + self.insert_contract_element_v1( + contract_element, + contract, + &block_info, + apply, + transaction, + &mut drive_operations, + platform_version, + )?; + + Drive::calculate_fee( + None, + Some(drive_operations), + &block_info.epoch, + self.config.epochs_per_era, + platform_version, + None, + ) + } + + /// Adds a contract to storage using `add_contract_to_storage` + /// and inserts the empty trees which will be necessary to later insert documents. + fn insert_contract_element_v1( + &self, + contract_element: Element, + contract: &DataContract, + block_info: &BlockInfo, + apply: bool, + transaction: TransactionArg, + drive_operations: &mut Vec, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + let mut estimated_costs_only_with_layer_info = if apply { + None::> + } else { + Some(HashMap::new()) + }; + let batch_operations = self.insert_contract_operations_v1( + contract_element, + contract, + block_info, + &mut estimated_costs_only_with_layer_info, + platform_version, + )?; + self.apply_batch_low_level_drive_operations( + estimated_costs_only_with_layer_info, + transaction, + batch_operations, + drive_operations, + &platform_version.drive, + ) + } + + /// The operations for adding a contract. + /// These operations add a contract to storage using `add_contract_to_storage` + /// and insert the empty trees which will be necessary to later insert documents. + #[inline(always)] + pub(super) fn insert_contract_add_operations_v1( + &self, + contract_element: Element, + contract: &DataContract, + block_info: &BlockInfo, + estimated_costs_only_with_layer_info: &mut Option< + HashMap, + >, + drive_operations: &mut Vec, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + let batch_operations = self.insert_contract_operations_v1( + contract_element, + contract, + block_info, + estimated_costs_only_with_layer_info, + platform_version, + )?; + drive_operations.extend(batch_operations); + Ok(()) + } + + /// The operations for adding a contract. + /// These operations add a contract to storage using `add_contract_to_storage` + /// and insert the empty trees which will be necessary to later insert documents. + fn insert_contract_operations_v1( + &self, + contract_element: Element, + contract: &DataContract, + block_info: &BlockInfo, + estimated_costs_only_with_layer_info: &mut Option< + HashMap, + >, + platform_version: &PlatformVersion, + ) -> Result, Error> { + let mut batch_operations: Vec = self.insert_contract_operations_v0(contract_element, contract, block_info, estimated_costs_only_with_layer_info, platform_version)?; + + for token_pos in contract.tokens().keys() { + let token_id = contract.token_id(*token_pos).ok_or(Error::DataContract(DataContractError::CorruptedDataContract(format!("data contract has a token at position {}, but can not find it", token_pos))))?; + + self.batch_insert_empty_tree( + tokens_root_path(), + DriveKeyInfo::KeyRef(token_id.as_bytes()), + None, + &mut batch_operations, + &platform_version.drive, + )?; + + self.batch_insert_empty_tree( + token_path(token_id.as_bytes()), + DriveKeyInfo::Key(vec![TOKEN_BALANCES_KEY]), + None, + &mut batch_operations, + &platform_version.drive, + )?; + + self.batch_insert_empty_tree( + total_tokens_root_supply_path(), + DriveKeyInfo::KeyRef(token_id.as_bytes()), + None, + &mut batch_operations, + &platform_version.drive, + )?; + } + + Ok(batch_operations) + } +} diff --git a/packages/rs-drive/src/drive/contract/update/update_contract/mod.rs b/packages/rs-drive/src/drive/contract/update/update_contract/mod.rs index 8d22fc40435..f9f682d74ac 100644 --- a/packages/rs-drive/src/drive/contract/update/update_contract/mod.rs +++ b/packages/rs-drive/src/drive/contract/update/update_contract/mod.rs @@ -1,4 +1,5 @@ mod v0; +mod v1; use crate::drive::Drive; use crate::error::drive::DriveError; @@ -64,9 +65,17 @@ impl Drive { platform_version, previous_fee_versions, ), + 1 => self.update_contract_v1( + contract, + block_info, + apply, + transaction, + platform_version, + previous_fee_versions, + ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "update_contract".to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, })), } @@ -125,9 +134,18 @@ impl Drive { drive_operations, platform_version, ), + 1 => self.update_contract_element_v1( + contract_element, + contract, + original_contract, + block_info, + transaction, + drive_operations, + platform_version, + ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "update_contract_element".to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, })), } @@ -192,9 +210,19 @@ impl Drive { drive_operations, platform_version, ), + 1 => self.update_contract_add_operations_v1( + contract_element, + contract, + original_contract, + block_info, + estimated_costs_only_with_layer_info, + transaction, + drive_operations, + platform_version, + ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "update_contract_add_operations".to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, })), } diff --git a/packages/rs-drive/src/drive/contract/update/update_contract/v0/mod.rs b/packages/rs-drive/src/drive/contract/update/update_contract/v0/mod.rs index d95decc3f96..ddec35b2bae 100644 --- a/packages/rs-drive/src/drive/contract/update/update_contract/v0/mod.rs +++ b/packages/rs-drive/src/drive/contract/update/update_contract/v0/mod.rs @@ -198,7 +198,7 @@ impl Drive { } /// operations for updating a contract. - fn update_contract_operations_v0( + pub(in crate::drive::contract::update::update_contract) fn update_contract_operations_v0( &self, contract_element: Element, contract: &DataContract, diff --git a/packages/rs-drive/src/drive/contract/update/update_contract/v1/mod.rs b/packages/rs-drive/src/drive/contract/update/update_contract/v1/mod.rs new file mode 100644 index 00000000000..fadf485b670 --- /dev/null +++ b/packages/rs-drive/src/drive/contract/update/update_contract/v1/mod.rs @@ -0,0 +1,225 @@ +use crate::drive::{contract_documents_path, Drive}; +use crate::error::drive::DriveError; +use crate::error::Error; +use crate::fees::op::LowLevelDriveOperation; +use crate::util::grove_operations::BatchInsertTreeApplyType; +use crate::util::object_size_info::DriveKeyInfo::KeyRef; +use crate::util::object_size_info::PathKeyInfo::{PathFixedSizeKey, PathFixedSizeKeyRef}; +use crate::util::storage_flags::StorageFlags; +use dpp::block::block_info::BlockInfo; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::config::v0::DataContractConfigGettersV0; +use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dpp::data_contract::DataContract; +use dpp::fee::fee_result::FeeResult; + +use dpp::data_contract::document_type::methods::DocumentTypeV0Methods; +use dpp::serialization::PlatformSerializableWithPlatformVersion; + +use dpp::fee::default_costs::CachedEpochIndexFeeVersions; +use dpp::version::PlatformVersion; +use grovedb::batch::KeyInfoPath; +use grovedb::{Element, EstimatedLayerInformation, TransactionArg}; +use std::collections::{HashMap, HashSet}; +use dpp::data_contract::accessors::v1::DataContractV1Getters; +use crate::drive::tokens::{TOKEN_BALANCES_KEY, token_path, tokens_root_path}; +use crate::error::contract::DataContractError; + +impl Drive { + /// Updates a data contract. + /// + /// This function updates a given data contract in the storage. The fee for updating + /// the contract is also calculated and returned. + /// + /// # Arguments + /// + /// * `contract` - A reference to the `DataContract` to be updated. + /// * `block_info` - A `BlockInfo` object containing information about the block where + /// the contract is being updated. + /// * `apply` - A boolean indicating whether the contract update should be applied (`true`) or not (`false`). Passing `false` would only tell the fees but won't interact with the state. + /// * `transaction` - A `TransactionArg` object representing the transaction to be used + /// for updating the contract. + /// + /// # Returns + /// + /// * `Result` - If successful, returns a `FeeResult` representing the fee + /// for updating the contract. If an error occurs during the contract update or fee calculation, + /// returns an `Error`. + /// + /// # Errors + /// + /// This function returns an error if the contract update or fee calculation fails. + #[inline(always)] + pub(super) fn update_contract_v1( + &self, + contract: &DataContract, + block_info: BlockInfo, + apply: bool, + transaction: TransactionArg, + platform_version: &PlatformVersion, + previous_fee_versions: Option<&CachedEpochIndexFeeVersions>, + ) -> Result { + if !apply { + return self.insert_contract( + contract, + block_info, + false, + transaction, + platform_version, + ); + } + + let mut drive_operations: Vec = vec![]; + + let contract_bytes = contract.serialize_to_bytes_with_platform_version(platform_version)?; + + // Since we can update the contract by definition it already has storage flags + let storage_flags = Some(StorageFlags::new_single_epoch( + block_info.epoch.index, + Some(contract.owner_id().to_buffer()), + )); + + let contract_element = Element::Item( + contract_bytes, + StorageFlags::map_to_some_element_flags(storage_flags.as_ref()), + ); + + let original_contract_fetch_info = self + .get_contract_with_fetch_info_and_add_to_operations( + contract.id().to_buffer(), + Some(&block_info.epoch), + true, + transaction, + &mut drive_operations, + platform_version, + )? + .ok_or(Error::Drive(DriveError::CorruptedCodeExecution( + "contract should exist", + )))?; + + if original_contract_fetch_info.contract.config().readonly() { + return Err(Error::Drive(DriveError::UpdatingReadOnlyImmutableContract( + "original contract is readonly", + ))); + } + + self.update_contract_element_v1( + contract_element, + contract, + &original_contract_fetch_info.contract, + &block_info, + transaction, + &mut drive_operations, + platform_version, + )?; + + // Update DataContracts cache with the new contract + let updated_contract_fetch_info = self + .fetch_contract_and_add_operations( + contract.id().to_buffer(), + Some(&block_info.epoch), + transaction, + &mut drive_operations, + platform_version, + )? + .ok_or(Error::Drive(DriveError::CorruptedCodeExecution( + "contract should exist", + )))?; + + self.cache + .data_contracts + .insert(updated_contract_fetch_info, transaction.is_some()); + + Drive::calculate_fee( + None, + Some(drive_operations), + &block_info.epoch, + self.config.epochs_per_era, + platform_version, + previous_fee_versions, + ) + } + + /// Updates a contract. + #[inline(always)] + pub(super) fn update_contract_element_v1( + &self, + contract_element: Element, + contract: &DataContract, + original_contract: &DataContract, + block_info: &BlockInfo, + transaction: TransactionArg, + drive_operations: &mut Vec, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + let mut estimated_costs_only_with_layer_info = + None::>; + let batch_operations = self.update_contract_operations_v1( + contract_element, + contract, + original_contract, + block_info, + &mut estimated_costs_only_with_layer_info, + transaction, + platform_version, + )?; + self.apply_batch_low_level_drive_operations( + estimated_costs_only_with_layer_info, + transaction, + batch_operations, + drive_operations, + &platform_version.drive, + ) + } + + /// Updates a contract. + #[inline(always)] + pub(super) fn update_contract_add_operations_v1( + &self, + contract_element: Element, + contract: &DataContract, + original_contract: &DataContract, + block_info: &BlockInfo, + estimated_costs_only_with_layer_info: &mut Option< + HashMap, + >, + transaction: TransactionArg, + drive_operations: &mut Vec, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + let batch_operations = self.update_contract_operations_v1( + contract_element, + contract, + original_contract, + block_info, + estimated_costs_only_with_layer_info, + transaction, + platform_version, + )?; + drive_operations.extend(batch_operations); + Ok(()) + } + + /// operations for updating a contract. + fn update_contract_operations_v1( + &self, + contract_element: Element, + contract: &DataContract, + original_contract: &DataContract, + block_info: &BlockInfo, + estimated_costs_only_with_layer_info: &mut Option< + HashMap, + >, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result, Error> { + let mut batch_operations: Vec = self.update_contract_operations_v0(contract_element, contract, original_contract, block_info, estimated_costs_only_with_layer_info, transaction, platform_version)?; + + for token_pos in contract.tokens().keys() { + let token_id = contract.token_id(*token_pos).ok_or(Error::DataContract(DataContractError::CorruptedDataContract(format!("data contract has a token at position {}, but can not find it", token_pos))))?; + + batch_operations.extend(self.create_token_trees_operations(token_id.to_buffer(), true, &mut None, estimated_costs_only_with_layer_info, transaction, platform_version)?); + } + Ok(batch_operations) + } +} diff --git a/packages/rs-drive/src/drive/initialization/mod.rs b/packages/rs-drive/src/drive/initialization/mod.rs index 97159a53ba9..2c673b90243 100644 --- a/packages/rs-drive/src/drive/initialization/mod.rs +++ b/packages/rs-drive/src/drive/initialization/mod.rs @@ -2,6 +2,7 @@ mod genesis_core_height; mod v0; +mod v1; use crate::drive::Drive; use crate::error::drive::DriveError; @@ -24,9 +25,10 @@ impl Drive { .create_initial_state_structure { 0 => self.create_initial_state_structure_0(transaction, platform_version), + 1 => self.create_initial_state_structure_1(transaction, platform_version), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "create_initial_state_structure".to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, })), } diff --git a/packages/rs-drive/src/drive/initialization/v0/mod.rs b/packages/rs-drive/src/drive/initialization/v0/mod.rs index b612aad5a2e..8736d42d25b 100644 --- a/packages/rs-drive/src/drive/initialization/v0/mod.rs +++ b/packages/rs-drive/src/drive/initialization/v0/mod.rs @@ -20,6 +20,24 @@ impl Drive { &self, transaction: TransactionArg, platform_version: &PlatformVersion, + ) -> Result<(), Error> { + let drive_version = &platform_version.drive; + self.create_initial_state_structure_top_level_0(transaction, platform_version)?; + + // On lower layers we can use batching + + let batch = self.create_initial_state_structure_lower_layers_operations_0(platform_version)?; + + self.grove_apply_batch(batch, false, transaction, drive_version)?; + + Ok(()) + } + + /// Creates the initial state structure. + pub(in crate::drive::initialization) fn create_initial_state_structure_top_level_0( + &self, + transaction: TransactionArg, + platform_version: &PlatformVersion, ) -> Result<(), Error> { let drive_version = &platform_version.drive; // We can not use batching to insert the root tree structure @@ -151,6 +169,14 @@ impl Drive { drive_version, )?; + Ok(()) + } + + /// Creates the initial state structure. + pub(in crate::drive::initialization) fn create_initial_state_structure_lower_layers_operations_0( + &self, + platform_version: &PlatformVersion, + ) -> Result { // On lower layers we can use batching let mut batch = GroveDbOpBatch::new(); @@ -180,10 +206,8 @@ impl Drive { // For the votes tree structure Drive::add_initial_vote_tree_main_structure_operations(&mut batch, platform_version)?; - - self.grove_apply_batch(batch, false, transaction, drive_version)?; - - Ok(()) + + Ok(batch) } } diff --git a/packages/rs-drive/src/drive/initialization/v1/mod.rs b/packages/rs-drive/src/drive/initialization/v1/mod.rs new file mode 100644 index 00000000000..d0d16a7962e --- /dev/null +++ b/packages/rs-drive/src/drive/initialization/v1/mod.rs @@ -0,0 +1,67 @@ +//! Drive Initialization + +use crate::drive::balances::TOTAL_TOKEN_SUPPLIES_STORAGE_KEY; +use crate::util::batch::GroveDbOpBatch; + +use crate::drive::system::misc_path_vec; +use crate::drive::Drive; +use crate::error::Error; +use crate::util::batch::grovedb_op_batch::GroveDbOpBatchV0Methods; + +use dpp::version::PlatformVersion; +use grovedb::{Element, TransactionArg}; +use crate::drive::identity::withdrawals::paths::{get_withdrawal_root_path_vec, WITHDRAWAL_TRANSACTIONS_BROADCASTED_KEY, WITHDRAWAL_TRANSACTIONS_SUM_AMOUNT_TREE_KEY}; + +impl Drive { + /// Creates the initial state structure. + pub(super) fn create_initial_state_structure_1( + &self, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result<(), Error> { + let drive_version = &platform_version.drive; + self.create_initial_state_structure_top_level_0(transaction, platform_version)?; + + // On lower layers we can use batching + + let mut batch = self.create_initial_state_structure_lower_layers_operations_0(platform_version)?; + + self.initial_state_structure_lower_layers_add_operations_1(&mut batch, platform_version)?; + + self.grove_apply_batch(batch, false, transaction, drive_version)?; + + Ok(()) + } + + /// Creates the initial state structure. + pub(in crate::drive::initialization) fn initial_state_structure_lower_layers_add_operations_1( + &self, + batch: &mut GroveDbOpBatch, + _platform_version: &PlatformVersion, + ) -> Result<(), Error> { + + // In Misc + batch.add_insert( + misc_path_vec(), + TOTAL_TOKEN_SUPPLIES_STORAGE_KEY.to_vec(), + Element::empty_tree(), + ); + + // We are adding the withdrawal transactions sum amount tree + let path = get_withdrawal_root_path_vec(); + + batch.add_insert( + path.clone(), + WITHDRAWAL_TRANSACTIONS_SUM_AMOUNT_TREE_KEY.to_vec(), + Element::empty_sum_tree(), + ); + + batch.add_insert( + path, + WITHDRAWAL_TRANSACTIONS_BROADCASTED_KEY.to_vec(), + Element::empty_tree(), + ); + + Ok(()) + } +} diff --git a/packages/rs-drive/src/drive/tokens/balance/fetch_identities_token_balances/v0/mod.rs b/packages/rs-drive/src/drive/tokens/balance/fetch_identities_token_balances/v0/mod.rs index c548c3f4d30..fd884c1eba1 100644 --- a/packages/rs-drive/src/drive/tokens/balance/fetch_identities_token_balances/v0/mod.rs +++ b/packages/rs-drive/src/drive/tokens/balance/fetch_identities_token_balances/v0/mod.rs @@ -1,4 +1,3 @@ -use crate::drive::tokens::token_balances_path_vec; use crate::drive::Drive; use crate::error::drive::DriveError; use crate::error::Error; @@ -6,7 +5,7 @@ use crate::fees::op::LowLevelDriveOperation; use dpp::balances::credits::TokenAmount; use dpp::version::PlatformVersion; use grovedb::Element::SumItem; -use grovedb::{PathQuery, Query, SizedQuery, TransactionArg}; +use grovedb::TransactionArg; use std::collections::BTreeMap; impl Drive { @@ -34,18 +33,7 @@ impl Drive { drive_operations: &mut Vec, platform_version: &PlatformVersion, ) -> Result>, Error> { - let tokens_root = token_balances_path_vec(token_id); - - let mut query = Query::new(); - - for identity_id in identity_ids { - query.insert_key(identity_id.to_vec()); - } - - let path_query = PathQuery::new( - tokens_root, - SizedQuery::new(query, Some(identity_ids.len() as u16), None), - ); + let path_query = Self::token_balances_for_identity_ids_query(token_id, identity_ids); self.grove_get_raw_path_query_with_optional( &path_query, diff --git a/packages/rs-drive/src/drive/tokens/balance/mod.rs b/packages/rs-drive/src/drive/tokens/balance/mod.rs index 8dbad4fc3d7..bc7bfa588f0 100644 --- a/packages/rs-drive/src/drive/tokens/balance/mod.rs +++ b/packages/rs-drive/src/drive/tokens/balance/mod.rs @@ -7,8 +7,6 @@ mod fetch_identities_token_balances; #[cfg(feature = "server")] mod fetch_identity_token_balances; #[cfg(feature = "server")] -mod prove; -#[cfg(feature = "server")] mod prove_identities_token_balances; #[cfg(feature = "server")] mod prove_identity_token_balances; diff --git a/packages/rs-drive/src/drive/tokens/balance/prove.rs b/packages/rs-drive/src/drive/tokens/balance/prove.rs deleted file mode 100644 index f2ce692e6a7..00000000000 --- a/packages/rs-drive/src/drive/tokens/balance/prove.rs +++ /dev/null @@ -1,165 +0,0 @@ -use crate::drive::Drive; -use crate::error::Error; - -use dpp::version::drive_versions::DriveVersion; - -use grovedb::TransactionArg; - -impl Drive { - /// Proves an Identity's token balance from the backing store - pub fn prove_identity_token_balance( - &self, - token_id: [u8; 32], - identity_id: [u8; 32], - transaction: TransactionArg, - drive_version: &DriveVersion, - ) -> Result, Error> { - let balance_query = Self::token_balance_for_identity_id_query(token_id, identity_id); - self.grove_get_proved_path_query(&balance_query, transaction, &mut vec![], drive_version) - } - - /// Proves multiple Identity token balances from the backing store - pub fn prove_many_identity_token_balances( - &self, - token_id: [u8; 32], - identity_ids: &[[u8; 32]], - transaction: TransactionArg, - drive_version: &DriveVersion, - ) -> Result, Error> { - let balance_query = Self::token_balances_for_identity_ids_query(token_id, identity_ids); - self.grove_get_proved_path_query(&balance_query, transaction, &mut vec![], drive_version) - } - - /// Proves multiple Identity balances from the backing store by range - pub fn prove_many_identity_token_balances_by_range( - &self, - token_id: [u8; 32], - start_at: Option<([u8; 32], bool)>, - ascending: bool, - limit: u16, - transaction: TransactionArg, - drive_version: &DriveVersion, - ) -> Result, Error> { - let balance_query = - Self::token_balances_for_range_query(token_id, start_at, ascending, limit); - self.grove_get_proved_path_query(&balance_query, transaction, &mut vec![], drive_version) - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::util::test_helpers::setup::setup_drive_with_initial_state_structure; - use dpp::block::block_info::BlockInfo; - use dpp::identity::Identity; - - mod prove_identity_token_balance { - use super::*; - use dpp::identity::accessors::IdentityGettersV0; - use dpp::version::PlatformVersion; - - #[test] - fn should_prove_a_single_identity_token_balance() { - let drive = setup_drive_with_initial_state_structure(None); - - let platform_version = PlatformVersion::first(); - - let identity = Identity::random_identity(3, Some(14), platform_version) - .expect("expected a platform identity"); - - let identity_id = identity.id().to_buffer(); - drive - .add_new_identity( - identity.clone(), - false, - &BlockInfo::default(), - true, - None, - platform_version, - ) - .expect("expected to add an identity"); - let proof = drive - .prove_identity_token_balance( - identity.id().to_buffer(), - None, - &platform_version.drive, - ) - .expect("should not error when proving an identity"); - - let (_, proved_identity_balance) = - Drive::verify_identity_token_balance_for_identity_id( - proof.as_slice(), - identity_id, - false, - platform_version, - ) - .expect("expect that this be verified"); - - assert_eq!(proved_identity_balance, Some(identity.balance())); - } - } - - mod prove_many_identity_token_balances { - use super::*; - use dpp::fee::Credits; - use dpp::identity::accessors::IdentityGettersV0; - use platform_version::version::PlatformVersion; - use rand::rngs::StdRng; - use rand::{Rng, SeedableRng}; - use std::collections::BTreeMap; - - #[test] - fn should_prove_multiple_identity_single_token_balances() { - let drive = setup_drive_with_initial_state_structure(None); - let platform_version = PlatformVersion::latest(); - let identities: BTreeMap<[u8; 32], Identity> = - Identity::random_identities(10, 3, Some(14), platform_version) - .expect("expected to get random identities") - .into_iter() - .map(|identity| (identity.id().to_buffer(), identity)) - .collect(); - - let mut rng = StdRng::seed_from_u64(293); - - let token_id: [u8; 32] = rng.gen(); - - drive.add_new_token(token_id); - - for identity in identities.values() { - drive - .add_new_identity( - identity.clone(), - false, - &BlockInfo::default(), - true, - None, - platform_version, - ) - .expect("expected to add an identity"); - } - let identity_ids = identities.keys().copied().collect::>(); - let identity_balances = identities - .into_iter() - .map(|(id, identity)| (id, Some(identity.balance()))) - .collect::>>(); - let proof = drive - .prove_many_identity_token_balances( - identity_ids.as_slice(), - None, - &platform_version.drive, - ) - .expect("should not error when proving an identity"); - - let (_, proved_identity_balances): ([u8; 32], BTreeMap<[u8; 32], Option>) = - Drive::verify_identity_balances_for_identity_ids( - proof.as_slice(), - false, - identity_ids.as_slice(), - platform_version, - ) - .expect("expect that this be verified"); - - assert_eq!(proved_identity_balances, identity_balances); - } - } -} diff --git a/packages/rs-drive/src/drive/tokens/balance/prove_identities_token_balances/v0/mod.rs b/packages/rs-drive/src/drive/tokens/balance/prove_identities_token_balances/v0/mod.rs index 58db6c0a537..b81eea97b95 100644 --- a/packages/rs-drive/src/drive/tokens/balance/prove_identities_token_balances/v0/mod.rs +++ b/packages/rs-drive/src/drive/tokens/balance/prove_identities_token_balances/v0/mod.rs @@ -1,9 +1,8 @@ -use crate::drive::tokens::token_balances_path_vec; use crate::drive::Drive; use crate::error::Error; use crate::fees::op::LowLevelDriveOperation; use dpp::version::PlatformVersion; -use grovedb::{PathQuery, Query, SizedQuery, TransactionArg}; +use grovedb::TransactionArg; impl Drive { pub(super) fn prove_identities_token_balances_v0( @@ -30,18 +29,7 @@ impl Drive { drive_operations: &mut Vec, platform_version: &PlatformVersion, ) -> Result, Error> { - let tokens_root = token_balances_path_vec(token_id); - - let mut query = Query::new(); - - for identity_id in identity_ids { - query.insert_key(identity_id.to_vec()); - } - - let path_query = PathQuery::new( - tokens_root, - SizedQuery::new(query, Some(identity_ids.len() as u16), None), - ); + let path_query = Self::token_balances_for_identity_ids_query(token_id, identity_ids); self.grove_get_proved_path_query( &path_query, @@ -51,3 +39,212 @@ impl Drive { ) } } + + +#[cfg(test)] +mod tests { + use std::collections::BTreeMap; + use dpp::balances::credits::TokenAmount; + use super::*; + use crate::util::test_helpers::setup::setup_drive_with_initial_state_structure; + use dpp::block::block_info::BlockInfo; + use dpp::data_contract::accessors::v1::DataContractV1Getters; + use dpp::data_contract::associated_token::token_configuration::TokenConfiguration; + use dpp::data_contract::associated_token::token_configuration::v0::{TokenConfigurationConventionV0, TokenConfigurationV0}; + use dpp::data_contract::config::DataContractConfig; + use dpp::data_contract::config::v0::DataContractConfigV0; + use dpp::data_contract::v1::DataContractV1; + use dpp::identity::Identity; + + use dpp::identity::accessors::IdentityGettersV0; + use dpp::prelude::DataContract; + use dpp::version::PlatformVersion; + + #[test] + fn should_prove_a_single_identity_token_balance() { + let drive = setup_drive_with_initial_state_structure(None); + + let platform_version = PlatformVersion::latest(); + + let identity = Identity::random_identity(3, Some(14), platform_version) + .expect("expected a platform identity"); + + let identity_id = identity.id().to_buffer(); + + let contract = DataContract::V1(DataContractV1 { + id: Default::default(), + version: 0, + owner_id: Default::default(), + document_types: Default::default(), + metadata: None, + config: DataContractConfig::V0(DataContractConfigV0 { + can_be_deleted: false, + readonly: false, + keeps_history: false, + documents_keep_history_contract_default: false, + documents_mutable_contract_default: false, + documents_can_be_deleted_contract_default: false, + requires_identity_encryption_bounded_key: None, + requires_identity_decryption_bounded_key: None, + }), + schema_defs: None, + groups: Default::default(), + tokens: BTreeMap::from([(0, TokenConfiguration::V0(TokenConfigurationV0::default_most_restrictive()))]), + }); + let token_id = contract.token_id(0).expect("expected token at position 0"); + drive + .add_new_identity( + identity.clone(), + false, + &BlockInfo::default(), + true, + None, + platform_version, + ) + .expect("expected to add an identity"); + + drive.insert_contract(&contract, BlockInfo::default(), true, None, platform_version).expect("expected to insert contract"); + + drive.token_mint(token_id.to_buffer(), identity.id().to_buffer(), 10000, true, &BlockInfo::default(), true, None, platform_version).expect("expected to mint token"); + let proof = drive + .prove_identities_token_balances_v0( + token_id.to_buffer(), + &vec![identity.id().to_buffer()], + None, + platform_version, + ) + .expect("should not error when proving an identity"); + + let proved_identity_balance: BTreeMap<[u8;32], Option> = + Drive::verify_token_balances_for_identity_ids( + proof.as_slice(), + token_id.to_buffer(), + &vec![identity.id().to_buffer()], + false, + platform_version, + ) + .expect("expect that this be verified").1; + + assert_eq!(proved_identity_balance, BTreeMap::from([(identity_id, Some(10000))])); + } + + #[test] + fn should_prove_a_single_identity_token_balance_does_not_exist() { + let drive = setup_drive_with_initial_state_structure(None); + + let platform_version = PlatformVersion::latest(); + + let identity = Identity::random_identity(3, Some(14), platform_version) + .expect("expected a platform identity"); + + let identity_id = identity.id().to_buffer(); + + let contract = DataContract::V1(DataContractV1 { + id: Default::default(), + version: 0, + owner_id: Default::default(), + document_types: Default::default(), + metadata: None, + config: DataContractConfig::V0(DataContractConfigV0 { + can_be_deleted: false, + readonly: false, + keeps_history: false, + documents_keep_history_contract_default: false, + documents_mutable_contract_default: false, + documents_can_be_deleted_contract_default: false, + requires_identity_encryption_bounded_key: None, + requires_identity_decryption_bounded_key: None, + }), + schema_defs: None, + groups: Default::default(), + tokens: BTreeMap::from([(0, TokenConfiguration::V0(TokenConfigurationV0::default_most_restrictive()))]), + }); + let token_id = contract.token_id(0).expect("expected token at position 0"); + drive + .add_new_identity( + identity.clone(), + false, + &BlockInfo::default(), + true, + None, + platform_version, + ) + .expect("expected to add an identity"); + + drive.insert_contract(&contract, BlockInfo::default(), true, None, platform_version).expect("expected to insert contract"); + let proof = drive + .prove_identities_token_balances_v0( + token_id.to_buffer(), + &vec![identity.id().to_buffer()], + None, + platform_version, + ) + .expect("should not error when proving an identity"); + + let proved_identity_balance: BTreeMap<[u8;32], Option> = + Drive::verify_token_balances_for_identity_ids( + proof.as_slice(), + token_id.to_buffer(), + &vec![identity.id().to_buffer()], + false, + platform_version, + ) + .expect("expect that this be verified").1; + + assert_eq!(proved_identity_balance, BTreeMap::from([(identity_id, None)])); + } + + // #[test] + // fn should_prove_multiple_identity_single_token_balances() { + // let drive = setup_drive_with_initial_state_structure(None); + // let platform_version = PlatformVersion::latest(); + // let identities: BTreeMap<[u8; 32], Identity> = + // Identity::random_identities(10, 3, Some(14), platform_version) + // .expect("expected to get random identities") + // .into_iter() + // .map(|identity| (identity.id().to_buffer(), identity)) + // .collect(); + // + // let mut rng = StdRng::seed_from_u64(293); + // + // let token_id: [u8; 32] = rng.gen(); + // + // drive.add_new_token(token_id); + // + // for identity in identities.values() { + // drive + // .add_new_identity( + // identity.clone(), + // false, + // &BlockInfo::default(), + // true, + // None, + // platform_version, + // ) + // .expect("expected to add an identity"); + // } + // let identity_ids = identities.keys().copied().collect::>(); + // let identity_balances = identities + // .into_iter() + // .map(|(id, identity)| (id, Some(identity.balance()))) + // .collect::>>(); + // let proof = drive + // .prove_many_identity_token_balances( + // identity_ids.as_slice(), + // None, + // &platform_version.drive, + // ) + // .expect("should not error when proving an identity"); + // + // let (_, proved_identity_balances): ([u8; 32], BTreeMap<[u8; 32], Option>) = + // Drive::verify_identity_balances_for_identity_ids( + // proof.as_slice(), + // false, + // identity_ids.as_slice(), + // platform_version, + // ) + // .expect("expect that this be verified"); + // + // assert_eq!(proved_identity_balances, identity_balances); + // } +} \ No newline at end of file diff --git a/packages/rs-drive/src/drive/tokens/balance/queries.rs b/packages/rs-drive/src/drive/tokens/balance/queries.rs index fc32d25e6a8..b02b5bb52a2 100644 --- a/packages/rs-drive/src/drive/tokens/balance/queries.rs +++ b/packages/rs-drive/src/drive/tokens/balance/queries.rs @@ -26,7 +26,7 @@ impl Drive { path: balance_path, query: SizedQuery { query, - limit: None, + limit: Some(identity_ids.len() as u16), offset: None, }, } diff --git a/packages/rs-drive/src/drive/tokens/mod.rs b/packages/rs-drive/src/drive/tokens/mod.rs index f19f64aad80..6b4a9f0b572 100644 --- a/packages/rs-drive/src/drive/tokens/mod.rs +++ b/packages/rs-drive/src/drive/tokens/mod.rs @@ -27,7 +27,7 @@ pub(crate) fn tokens_root_path_vec() -> Vec> { #[cfg(any(feature = "server", feature = "verify"))] pub(crate) fn token_path(token_id: &[u8; 32]) -> [&[u8]; 2] { [ - Into::<&[u8; 1]>::into(RootTree::DataContractDocuments), + Into::<&[u8; 1]>::into(RootTree::Tokens), token_id, ] } @@ -42,7 +42,7 @@ pub(crate) fn token_path_vec(token_id: [u8; 32]) -> Vec> { #[cfg(any(feature = "server", feature = "verify"))] pub(crate) fn token_balances_path(token_id: &[u8; 32]) -> [&[u8]; 3] { [ - Into::<&[u8; 1]>::into(RootTree::DataContractDocuments), + Into::<&[u8; 1]>::into(RootTree::Tokens), token_id, &[TOKEN_BALANCES_KEY], ] @@ -62,7 +62,7 @@ pub(crate) fn token_balances_path_vec(token_id: [u8; 32]) -> Vec> { #[cfg(any(feature = "server", feature = "verify"))] pub(crate) fn token_identity_infos_path(token_id: &[u8; 32]) -> [&[u8]; 3] { [ - Into::<&[u8; 1]>::into(RootTree::DataContractDocuments), + Into::<&[u8; 1]>::into(RootTree::Tokens), token_id, &[TOKEN_IDENTITY_INFO_KEY], ] diff --git a/packages/rs-drive/src/drive/tokens/system/create_token_root_tree/mod.rs b/packages/rs-drive/src/drive/tokens/system/create_token_trees/mod.rs similarity index 78% rename from packages/rs-drive/src/drive/tokens/system/create_token_root_tree/mod.rs rename to packages/rs-drive/src/drive/tokens/system/create_token_trees/mod.rs index 4833f51e092..4f2f6b1575e 100644 --- a/packages/rs-drive/src/drive/tokens/system/create_token_root_tree/mod.rs +++ b/packages/rs-drive/src/drive/tokens/system/create_token_trees/mod.rs @@ -14,9 +14,10 @@ use std::collections::HashMap; impl Drive { /// Adds a identity by inserting a new identity subtree structure to the `Identities` subtree. - pub fn create_token_root_tree( + pub fn create_token_trees( &self, token_id: [u8; 32], + allow_already_exists: bool, block_info: &BlockInfo, apply: bool, transaction: TransactionArg, @@ -27,17 +28,18 @@ impl Drive { .methods .token .update - .create_token_root_tree + .create_token_trees { - 0 => self.create_token_root_tree_v0( + 0 => self.create_token_trees_v0( token_id, + allow_already_exists, block_info, apply, transaction, platform_version, ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { - method: "create_token_root_tree".to_string(), + method: "create_token_trees".to_string(), known_versions: vec![0], received: version, })), @@ -45,9 +47,10 @@ impl Drive { } /// Adds identity creation operations to drive operations - pub fn create_token_root_tree_add_to_operations( + pub fn create_token_trees_add_to_operations( &self, token_id: [u8; 32], + allow_already_exists: bool, apply: bool, previous_batch_operations: &mut Option<&mut Vec>, transaction: TransactionArg, @@ -59,10 +62,11 @@ impl Drive { .methods .token .update - .create_token_root_tree + .create_token_trees { - 0 => self.create_token_root_tree_add_to_operations_v0( + 0 => self.create_token_trees_add_to_operations_v0( token_id, + allow_already_exists, apply, previous_batch_operations, transaction, @@ -70,7 +74,7 @@ impl Drive { platform_version, ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { - method: "create_token_root_tree_add_to_operations".to_string(), + method: "create_token_trees_add_to_operations".to_string(), known_versions: vec![0], received: version, })), @@ -78,9 +82,10 @@ impl Drive { } /// The operations needed to create an identity - pub fn create_token_root_tree_operations( + pub fn create_token_trees_operations( &self, token_id: [u8; 32], + allow_already_exists: bool, previous_batch_operations: &mut Option<&mut Vec>, estimated_costs_only_with_layer_info: &mut Option< HashMap, @@ -93,17 +98,18 @@ impl Drive { .methods .token .update - .create_token_root_tree + .create_token_trees { - 0 => self.create_token_root_tree_operations_v0( + 0 => self.create_token_trees_operations_v0( token_id, + allow_already_exists, previous_batch_operations, estimated_costs_only_with_layer_info, transaction, platform_version, ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { - method: "create_token_root_tree_operations".to_string(), + method: "create_token_trees_operations".to_string(), known_versions: vec![0], received: version, })), diff --git a/packages/rs-drive/src/drive/tokens/system/create_token_root_tree/v0/mod.rs b/packages/rs-drive/src/drive/tokens/system/create_token_trees/v0/mod.rs similarity index 63% rename from packages/rs-drive/src/drive/tokens/system/create_token_root_tree/v0/mod.rs rename to packages/rs-drive/src/drive/tokens/system/create_token_trees/v0/mod.rs index 2be68ed7350..2a16720d3e0 100644 --- a/packages/rs-drive/src/drive/tokens/system/create_token_root_tree/v0/mod.rs +++ b/packages/rs-drive/src/drive/tokens/system/create_token_trees/v0/mod.rs @@ -1,4 +1,4 @@ -use crate::drive::tokens::tokens_root_path; +use crate::drive::tokens::{TOKEN_BALANCES_KEY, token_path, tokens_root_path}; use crate::drive::Drive; use crate::error::drive::DriveError; use crate::error::Error; @@ -11,13 +11,15 @@ use grovedb::batch::KeyInfoPath; use grovedb::{EstimatedLayerInformation, TransactionArg}; use platform_version::version::PlatformVersion; use std::collections::HashMap; +use crate::drive::balances::total_tokens_root_supply_path; impl Drive { /// Creates a new token root subtree at `TokenBalances` keyed by `token_id`. /// This function applies the operations directly, calculates fees, and returns the fee result. - pub(super) fn create_token_root_tree_v0( + pub(super) fn create_token_trees_v0( &self, token_id: [u8; 32], + allow_already_exists: bool, block_info: &BlockInfo, apply: bool, transaction: TransactionArg, @@ -26,8 +28,9 @@ impl Drive { let mut drive_operations: Vec = vec![]; // Add operations to create the token root tree - self.create_token_root_tree_add_to_operations_v0( + self.create_token_trees_add_to_operations_v0( token_id, + allow_already_exists, apply, &mut None, transaction, @@ -50,9 +53,10 @@ impl Drive { /// Adds the token root creation operations to the provided `drive_operations` vector without /// calculating or returning fees. If `apply` is false, it will only estimate costs. - pub(super) fn create_token_root_tree_add_to_operations_v0( + pub(super) fn create_token_trees_add_to_operations_v0( &self, token_id: [u8; 32], + allow_already_exists: bool, apply: bool, previous_batch_operations: &mut Option<&mut Vec>, transaction: TransactionArg, @@ -66,8 +70,9 @@ impl Drive { }; // Get the operations required to create the token tree - let batch_operations = self.create_token_root_tree_operations_v0( + let batch_operations = self.create_token_trees_operations_v0( token_id, + allow_already_exists, previous_batch_operations, &mut estimated_costs_only_with_layer_info, transaction, @@ -86,9 +91,10 @@ impl Drive { /// Gathers the operations needed to create the token root subtree. If `apply` is false, it /// populates `estimated_costs_only_with_layer_info` instead of applying. - pub(super) fn create_token_root_tree_operations_v0( + pub(super) fn create_token_trees_operations_v0( &self, token_id: [u8; 32], + allow_already_exists: bool, previous_batch_operations: &mut Option<&mut Vec>, estimated_costs_only_with_layer_info: &mut Option< HashMap, @@ -99,35 +105,81 @@ impl Drive { let mut batch_operations: Vec = vec![]; // Decide if we're doing a stateful or stateless insert for cost estimation - let apply_type = if estimated_costs_only_with_layer_info.is_none() { + let non_sum_tree_apply_type = if estimated_costs_only_with_layer_info.is_none() { + BatchInsertTreeApplyType::StatefulBatchInsertTree + } else { + BatchInsertTreeApplyType::StatelessBatchInsertTree { + in_tree_using_sums: false, + is_sum_tree: false, + flags_len: 0, + } + }; + + let token_balance_tree_apply_type = if estimated_costs_only_with_layer_info.is_none() { BatchInsertTreeApplyType::StatefulBatchInsertTree } else { BatchInsertTreeApplyType::StatelessBatchInsertTree { in_tree_using_sums: false, is_sum_tree: true, - flags_len: 0, // No additional storage flags here + flags_len: 0, } }; // Insert an empty tree for this token if it doesn't exist let inserted = self.batch_insert_empty_tree_if_not_exists( PathFixedSizeKey((tokens_root_path(), token_id.to_vec())), - true, + false, None, // No storage flags - apply_type, + non_sum_tree_apply_type, transaction, previous_batch_operations, &mut batch_operations, &platform_version.drive, )?; - if !inserted { + if !inserted && !allow_already_exists { // The token root already exists. Depending on your logic, this might be allowed or should be treated as an error. return Err(Error::Drive(DriveError::CorruptedDriveState( "token root tree already exists".to_string(), ))); } + let inserted = self.batch_insert_empty_tree_if_not_exists( + PathFixedSizeKey((token_path(&token_id), vec![TOKEN_BALANCES_KEY])), + true, + None, + token_balance_tree_apply_type, + transaction, + &mut None, + &mut batch_operations, + &platform_version.drive, + )?; + + if !inserted && !allow_already_exists { + // The token root already exists. Depending on your logic, this might be allowed or should be treated as an error. + return Err(Error::Drive(DriveError::CorruptedDriveState( + "token balance tree already exists".to_string(), + ))); + } + + let inserted = self.batch_insert_empty_tree_if_not_exists( + PathFixedSizeKey((total_tokens_root_supply_path(), token_id.to_vec())), + false, + None, + non_sum_tree_apply_type, + transaction, + &mut None, + &mut batch_operations, + &platform_version.drive, + )?; + + if !inserted && !allow_already_exists { + // The token root already exists. Depending on your logic, this might be allowed or should be treated as an error. + return Err(Error::Drive(DriveError::CorruptedDriveState( + "sum tree tree already exists".to_string(), + ))); + } + Ok(batch_operations) } } diff --git a/packages/rs-drive/src/drive/tokens/system/mod.rs b/packages/rs-drive/src/drive/tokens/system/mod.rs index 7f760fc3cf3..8d0f456d613 100644 --- a/packages/rs-drive/src/drive/tokens/system/mod.rs +++ b/packages/rs-drive/src/drive/tokens/system/mod.rs @@ -1,3 +1,3 @@ mod add_to_token_total_supply; -mod create_token_root_tree; +mod create_token_trees; mod remove_from_token_total_supply; diff --git a/packages/rs-drive/src/fees/op.rs b/packages/rs-drive/src/fees/op.rs index c28ea60caa2..ecd1c605311 100644 --- a/packages/rs-drive/src/fees/op.rs +++ b/packages/rs-drive/src/fees/op.rs @@ -398,6 +398,22 @@ impl LowLevelDriveOperation { LowLevelDriveOperation::insert_for_estimated_path_key_element(path, key, tree) } + /// Sets `GroveOperation` for inserting an empty sum tree at the given path and key + pub fn for_estimated_path_key_empty_sum_tree( + path: KeyInfoPath, + key: KeyInfo, + storage_flags: Option<&StorageFlags>, + ) -> Self { + let tree = match storage_flags { + Some(storage_flags) => { + Element::empty_sum_tree_with_flags(storage_flags.to_some_element_flags()) + } + None => Element::empty_sum_tree(), + }; + + LowLevelDriveOperation::insert_for_estimated_path_key_element(path, key, tree) + } + /// Sets `GroveOperation` for inserting an element at the given path and key pub fn insert_for_known_path_key_element( path: Vec>, diff --git a/packages/rs-drive/src/util/grove_operations/batch_insert_empty_sum_tree/mod.rs b/packages/rs-drive/src/util/grove_operations/batch_insert_empty_sum_tree/mod.rs new file mode 100644 index 00000000000..113e8f40f10 --- /dev/null +++ b/packages/rs-drive/src/util/grove_operations/batch_insert_empty_sum_tree/mod.rs @@ -0,0 +1,46 @@ +mod v0; + +use crate::util::object_size_info::DriveKeyInfo; +use crate::util::storage_flags::StorageFlags; + +use crate::drive::Drive; +use crate::error::drive::DriveError; +use crate::error::Error; +use crate::fees::op::LowLevelDriveOperation; +use dpp::version::drive_versions::DriveVersion; + +impl Drive { + /// Pushes an "insert empty tree" operation to `drive_operations`. + /// + /// # Parameters + /// * `path`: The path to insert an empty tree. + /// * `key_info`: The key information of the document. + /// * `storage_flags`: Storage options for the operation. + /// * `drive_operations`: The vector containing low-level drive operations. + /// * `drive_version`: The drive version to select the correct function version to run. + /// + /// # Returns + /// * `Ok(())` if the operation was successful. + /// * `Err(DriveError::UnknownVersionMismatch)` if the drive version does not match known versions. + pub fn batch_insert_empty_sum_tree<'a, 'c, P>( + &'a self, + path: P, + key_info: DriveKeyInfo<'c>, + storage_flags: Option<&StorageFlags>, + drive_operations: &mut Vec, + drive_version: &DriveVersion, + ) -> Result<(), Error> + where + P: IntoIterator, +

::IntoIter: ExactSizeIterator + DoubleEndedIterator + Clone, + { + match drive_version.grove_methods.batch.batch_insert_empty_sum_tree { + 0 => self.batch_insert_empty_sum_tree_v0(path, key_info, storage_flags, drive_operations), + version => Err(Error::Drive(DriveError::UnknownVersionMismatch { + method: "batch_insert_empty_sum_tree".to_string(), + known_versions: vec![0], + received: version, + })), + } + } +} diff --git a/packages/rs-drive/src/util/grove_operations/batch_insert_empty_sum_tree/v0/mod.rs b/packages/rs-drive/src/util/grove_operations/batch_insert_empty_sum_tree/v0/mod.rs new file mode 100644 index 00000000000..7753b9f6729 --- /dev/null +++ b/packages/rs-drive/src/util/grove_operations/batch_insert_empty_sum_tree/v0/mod.rs @@ -0,0 +1,51 @@ +use crate::drive::Drive; +use crate::error::Error; +use crate::fees::op::LowLevelDriveOperation; +use crate::util::object_size_info::DriveKeyInfo; +use crate::util::object_size_info::DriveKeyInfo::{Key, KeyRef, KeySize}; +use crate::util::storage_flags::StorageFlags; +use grovedb::batch::KeyInfoPath; + +impl Drive { + /// Pushes an "insert empty tree" operation to `drive_operations`. + pub(crate) fn batch_insert_empty_sum_tree_v0<'a, 'c, P>( + &'a self, + path: P, + key_info: DriveKeyInfo<'c>, + storage_flags: Option<&StorageFlags>, + drive_operations: &mut Vec, + ) -> Result<(), Error> + where + P: IntoIterator, +

::IntoIter: ExactSizeIterator + DoubleEndedIterator + Clone, + { + match key_info { + KeyRef(key) => { + let path_items: Vec> = path.into_iter().map(Vec::from).collect(); + drive_operations.push(LowLevelDriveOperation::for_known_path_key_empty_sum_tree( + path_items, + key.to_vec(), + storage_flags, + )); + Ok(()) + } + KeySize(key) => { + drive_operations.push(LowLevelDriveOperation::for_estimated_path_key_empty_sum_tree( + KeyInfoPath::from_known_path(path), + key, + storage_flags, + )); + Ok(()) + } + Key(key) => { + let path_items: Vec> = path.into_iter().map(Vec::from).collect(); + drive_operations.push(LowLevelDriveOperation::for_known_path_key_empty_sum_tree( + path_items, + key, + storage_flags, + )); + Ok(()) + } + } + } +} diff --git a/packages/rs-drive/src/util/grove_operations/mod.rs b/packages/rs-drive/src/util/grove_operations/mod.rs index 41736ed442e..33f563a9304 100644 --- a/packages/rs-drive/src/util/grove_operations/mod.rs +++ b/packages/rs-drive/src/util/grove_operations/mod.rs @@ -57,6 +57,9 @@ pub mod grove_has_raw; /// Batch insert operation into empty tree pub mod batch_insert_empty_tree; +/// Batch insert operation into empty sum tree +pub mod batch_insert_empty_sum_tree; + /// Batch insert operation into empty tree, but only if it doesn't already exist pub mod batch_insert_empty_tree_if_not_exists; diff --git a/packages/rs-drive/src/verify/mod.rs b/packages/rs-drive/src/verify/mod.rs index b4c627718e2..f0a4dc388ba 100644 --- a/packages/rs-drive/src/verify/mod.rs +++ b/packages/rs-drive/src/verify/mod.rs @@ -13,6 +13,7 @@ pub mod system; /// Verifies that a state transition contents exist in the proof pub mod state_transition; pub mod voting; +mod tokens; /// Represents the root hash of the grovedb tree pub type RootHash = [u8; 32]; diff --git a/packages/rs-drive/src/verify/tokens/mod.rs b/packages/rs-drive/src/verify/tokens/mod.rs new file mode 100644 index 00000000000..1a9a9421a46 --- /dev/null +++ b/packages/rs-drive/src/verify/tokens/mod.rs @@ -0,0 +1 @@ +mod verify_token_balances_for_identity_ids; \ No newline at end of file diff --git a/packages/rs-drive/src/verify/tokens/verify_token_balances_for_identity_ids/mod.rs b/packages/rs-drive/src/verify/tokens/verify_token_balances_for_identity_ids/mod.rs new file mode 100644 index 00000000000..4303bf196a3 --- /dev/null +++ b/packages/rs-drive/src/verify/tokens/verify_token_balances_for_identity_ids/mod.rs @@ -0,0 +1,81 @@ +mod v0; + +use std::collections::BTreeMap; +use dpp::balances::credits::TokenAmount; +use crate::drive::Drive; + +use crate::error::drive::DriveError; + +use crate::error::Error; + +use crate::verify::RootHash; + +use dpp::version::PlatformVersion; + +impl Drive { + /// Verifies the token balances for a set of identity IDs. + /// + /// This function checks the token balances of multiple identities by verifying the provided + /// proof against the specified token ID and identity IDs. It also supports verifying a subset + /// of a larger proof if necessary. + /// + /// # Parameters + /// + /// - `proof`: A byte slice representing the proof of authentication from the user. This is used + /// to verify the validity of the identity and its associated balance. + /// - `token_id`: A 32-byte array representing the unique identifier for the token whose balance + /// is being verified. + /// - `identity_ids`: A slice of 32-byte arrays, each representing a unique identity ID. These + /// are the identities whose token balances are being verified. + /// - `verify_subset_of_proof`: A boolean flag indicating whether the proof being verified is a + /// subset of a larger proof. If `true`, the verification will consider only a part of the proof. + /// - `platform_version`: The version of the platform against which the identity token balances are + /// being verified. This ensures compatibility with the correct API version. + /// + /// # Returns + /// + /// - `Result<(RootHash, BTreeMap<[u8; 32], Option>), Error>`: If the verification is successful: + /// - `RootHash`: The root hash of the GroveDB, representing the state of the database. + /// - `BTreeMap<[u8; 32], Option>`: A map of identity IDs to their associated token balances. + /// The `Option` can be `Some(TokenAmount)` if a balance exists or `None` if no balance is found. + /// + /// # Errors + /// + /// The function will return an `Error` if any of the following occur: + /// + /// - The provided authentication proof is invalid. + /// - The provided identity ID does not correspond to a valid balance. + /// - The provided platform version is unknown or unsupported. + /// + pub fn verify_token_balances_for_identity_ids< + T: FromIterator<(I, Option)>, + I: From<[u8; 32]>, + >( + proof: &[u8], + token_id: [u8;32], + identity_ids: &[[u8; 32]], + verify_subset_of_proof: bool, + platform_version: &PlatformVersion, + ) -> Result<(RootHash, T), Error> { + match platform_version + .drive + .methods + .verify + .token + .verify_token_balances_for_identity_ids + { + 0 => Self::verify_token_balances_for_identity_ids_v0( + proof, + token_id, + identity_ids, + verify_subset_of_proof, + platform_version, + ), + version => Err(Error::Drive(DriveError::UnknownVersionMismatch { + method: "verify_token_balances_for_identity_ids".to_string(), + known_versions: vec![0], + received: version, + })), + } + } +} diff --git a/packages/rs-drive/src/verify/tokens/verify_token_balances_for_identity_ids/v0/mod.rs b/packages/rs-drive/src/verify/tokens/verify_token_balances_for_identity_ids/v0/mod.rs new file mode 100644 index 00000000000..c6e152e6413 --- /dev/null +++ b/packages/rs-drive/src/verify/tokens/verify_token_balances_for_identity_ids/v0/mod.rs @@ -0,0 +1,72 @@ +use crate::drive::Drive; + +use crate::error::proof::ProofError; +use crate::error::Error; + +use crate::verify::RootHash; + +use grovedb::GroveDb; +use dpp::balances::credits::TokenAmount; +use dpp::fee::Credits; +use platform_version::version::PlatformVersion; + +impl Drive { + pub(super) fn verify_token_balances_for_identity_ids_v0< + T: FromIterator<(I, Option)>, + I: From<[u8; 32]>, + >( + proof: &[u8], + token_id: [u8;32], + identity_ids: &[[u8; 32]], + verify_subset_of_proof: bool, + platform_version: &PlatformVersion, + ) -> Result<(RootHash, T), Error> { + let path_query = Self::token_balances_for_identity_ids_query(token_id, identity_ids); + let (root_hash, mut proved_key_values) = if verify_subset_of_proof { + GroveDb::verify_subset_query_with_absence_proof( + proof, + &path_query, + &platform_version.drive.grove_version, + )? + } else { + GroveDb::verify_query_with_absence_proof( + proof, + &path_query, + &platform_version.drive.grove_version, + )? + }; + if proved_key_values.len() == identity_ids.len() { + let values = proved_key_values + .into_iter() + .map(|proved_key_value| { + let key: [u8; 32] = proved_key_value + .1 + .try_into() + .map_err(|_| Error::Proof(ProofError::IncorrectValueSize("value size")))?; + let maybe_element = proved_key_value.2; + match maybe_element { + None => Ok((key.into(), None)), + Some(element) => { + let balance: Credits = element + .as_sum_item_value() + .map_err(Error::GroveDB)? + .try_into() + .map_err(|_| { + Error::Proof(ProofError::IncorrectValueSize( + "balance was negative", + )) + })?; + Ok((key.into(), Some(balance))) + } + } + }) + .collect::>()?; + Ok((root_hash, values)) + } else { + Err(Error::Proof(ProofError::WrongElementCount { + expected: identity_ids.len(), + got: proved_key_values.len(), + })) + } + } +} diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_contract_method_versions/mod.rs b/packages/rs-platform-version/src/version/drive_versions/drive_contract_method_versions/mod.rs index 18cf2d3a4f6..a216992f698 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_contract_method_versions/mod.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_contract_method_versions/mod.rs @@ -1,6 +1,7 @@ use versioned_feature_core::FeatureVersion; pub mod v1; +pub mod v2; #[derive(Clone, Debug, Default)] pub struct DriveContractMethodVersions { diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_contract_method_versions/v2.rs b/packages/rs-platform-version/src/version/drive_versions/drive_contract_method_versions/v2.rs new file mode 100644 index 00000000000..5197624ade2 --- /dev/null +++ b/packages/rs-platform-version/src/version/drive_versions/drive_contract_method_versions/v2.rs @@ -0,0 +1,33 @@ +use crate::version::drive_versions::drive_contract_method_versions::{ + DriveContractApplyMethodVersions, DriveContractCostsMethodVersions, + DriveContractGetMethodVersions, DriveContractInsertMethodVersions, DriveContractMethodVersions, + DriveContractProveMethodVersions, DriveContractUpdateMethodVersions, +}; + +pub const DRIVE_CONTRACT_METHOD_VERSIONS_V2: DriveContractMethodVersions = + DriveContractMethodVersions { + prove: DriveContractProveMethodVersions { + prove_contract: 0, + prove_contract_history: 0, + prove_contracts: 0, + }, + apply: DriveContractApplyMethodVersions { + apply_contract: 0, + apply_contract_with_serialization: 0, + }, + insert: DriveContractInsertMethodVersions { + add_contract_to_storage: 0, + insert_contract: 1, // <--- changed to v1 (for token insertion + }, + update: DriveContractUpdateMethodVersions { update_contract: 1 }, // <--- changed to v1 (for token insertion) + costs: DriveContractCostsMethodVersions { + add_estimation_costs_for_contract_insertion: 0, + }, + get: DriveContractGetMethodVersions { + fetch_contract: 0, + fetch_contract_with_history: 0, + get_cached_contract_with_fetch_info: 0, + get_contract_with_fetch_info: 0, + get_contracts_with_fetch_info: 0, + }, + }; diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_grove_method_versions/mod.rs b/packages/rs-platform-version/src/version/drive_versions/drive_grove_method_versions/mod.rs index c61b52f2504..5118c9093c4 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_grove_method_versions/mod.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_grove_method_versions/mod.rs @@ -51,6 +51,7 @@ pub struct DriveGroveBatchMethodVersions { pub batch_remove_raw: FeatureVersion, pub batch_delete_up_tree_while_empty: FeatureVersion, pub batch_refresh_reference: FeatureVersion, + pub batch_insert_empty_sum_tree: FeatureVersion, } #[derive(Clone, Debug, Default)] diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_grove_method_versions/v1.rs b/packages/rs-platform-version/src/version/drive_versions/drive_grove_method_versions/v1.rs index 6dc9b44503c..900a65673dd 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_grove_method_versions/v1.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_grove_method_versions/v1.rs @@ -42,6 +42,7 @@ pub const DRIVE_GROVE_METHOD_VERSIONS_V1: DriveGroveMethodVersions = DriveGroveM batch_remove_raw: 0, batch_delete_up_tree_while_empty: 0, batch_refresh_reference: 0, + batch_insert_empty_sum_tree: 0, }, apply: DriveGroveApplyMethodVersions { grove_apply_operation: 0, diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_token_method_versions/mod.rs b/packages/rs-platform-version/src/version/drive_versions/drive_token_method_versions/mod.rs index 66817c52fcd..8f47a00183c 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_token_method_versions/mod.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_token_method_versions/mod.rs @@ -23,7 +23,7 @@ pub struct DriveTokenProveMethodVersions { #[derive(Clone, Debug, Default)] pub struct DriveTokenUpdateMethodVersions { - pub create_token_root_tree: FeatureVersion, + pub create_token_trees: FeatureVersion, pub burn: FeatureVersion, pub mint: FeatureVersion, pub transfer: FeatureVersion, diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_token_method_versions/v1.rs b/packages/rs-platform-version/src/version/drive_versions/drive_token_method_versions/v1.rs index 43c1311c620..f021ede2b3b 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_token_method_versions/v1.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_token_method_versions/v1.rs @@ -13,7 +13,7 @@ pub const DRIVE_TOKEN_METHOD_VERSIONS_V1: DriveTokenMethodVersions = DriveTokenM identity_token_balances: 0, }, update: DriveTokenUpdateMethodVersions { - create_token_root_tree: 0, + create_token_trees: 0, burn: 0, mint: 0, transfer: 0, diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/mod.rs b/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/mod.rs index 39d42551360..f42756e4d5e 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/mod.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/mod.rs @@ -7,6 +7,7 @@ pub struct DriveVerifyMethodVersions { pub contract: DriveVerifyContractMethodVersions, pub document: DriveVerifyDocumentMethodVersions, pub identity: DriveVerifyIdentityMethodVersions, + pub token: DriveVerifyTokenMethodVersions, pub single_document: DriveVerifySingleDocumentMethodVersions, pub system: DriveVerifySystemMethodVersions, pub voting: DriveVerifyVoteMethodVersions, @@ -42,6 +43,12 @@ pub struct DriveVerifyIdentityMethodVersions { pub verify_identity_revision_for_identity_id: FeatureVersion, } +#[derive(Clone, Debug, Default)] +pub struct DriveVerifyTokenMethodVersions { + pub verify_token_balances_for_identity_ids: FeatureVersion, + pub verify_token_balances_for_identity_id: FeatureVersion, +} + #[derive(Clone, Debug, Default)] pub struct DriveVerifyVoteMethodVersions { pub verify_masternode_vote: FeatureVersion, diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/v1.rs b/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/v1.rs index 4c40371f83d..9604882fe69 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/v1.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/v1.rs @@ -1,9 +1,4 @@ -use crate::version::drive_versions::drive_verify_method_versions::{ - DriveVerifyContractMethodVersions, DriveVerifyDocumentMethodVersions, - DriveVerifyIdentityMethodVersions, DriveVerifyMethodVersions, - DriveVerifySingleDocumentMethodVersions, DriveVerifyStateTransitionMethodVersions, - DriveVerifySystemMethodVersions, DriveVerifyVoteMethodVersions, -}; +use crate::version::drive_versions::drive_verify_method_versions::{DriveVerifyContractMethodVersions, DriveVerifyDocumentMethodVersions, DriveVerifyIdentityMethodVersions, DriveVerifyMethodVersions, DriveVerifySingleDocumentMethodVersions, DriveVerifyStateTransitionMethodVersions, DriveVerifySystemMethodVersions, DriveVerifyTokenMethodVersions, DriveVerifyVoteMethodVersions}; pub const DRIVE_VERIFY_METHOD_VERSIONS_V1: DriveVerifyMethodVersions = DriveVerifyMethodVersions { contract: DriveVerifyContractMethodVersions { @@ -29,6 +24,10 @@ pub const DRIVE_VERIFY_METHOD_VERSIONS_V1: DriveVerifyMethodVersions = DriveVeri verify_identities_contract_keys: 0, verify_identity_revision_for_identity_id: 0, }, + token: DriveVerifyTokenMethodVersions { + verify_token_balances_for_identity_ids: 0, + verify_token_balances_for_identity_id: 0, + }, single_document: DriveVerifySingleDocumentMethodVersions { verify_proof: 0, verify_proof_keep_serialized: 0, diff --git a/packages/rs-platform-version/src/version/drive_versions/mod.rs b/packages/rs-platform-version/src/version/drive_versions/mod.rs index 2cadffa64f5..a1e68142678 100644 --- a/packages/rs-platform-version/src/version/drive_versions/mod.rs +++ b/packages/rs-platform-version/src/version/drive_versions/mod.rs @@ -23,6 +23,7 @@ pub mod drive_verify_method_versions; pub mod drive_vote_method_versions; pub mod v1; pub mod v2; +pub mod v3; #[derive(Clone, Debug, Default)] pub struct DriveVersion { diff --git a/packages/rs-platform-version/src/version/drive_versions/v3.rs b/packages/rs-platform-version/src/version/drive_versions/v3.rs new file mode 100644 index 00000000000..30d67ebfd7d --- /dev/null +++ b/packages/rs-platform-version/src/version/drive_versions/v3.rs @@ -0,0 +1,102 @@ +use crate::version::drive_versions::drive_contract_method_versions::v2::DRIVE_CONTRACT_METHOD_VERSIONS_V2; +use crate::version::drive_versions::drive_credit_pool_method_versions::v1::CREDIT_POOL_METHOD_VERSIONS_V1; +use crate::version::drive_versions::drive_document_method_versions::v1::DRIVE_DOCUMENT_METHOD_VERSIONS_V1; +use crate::version::drive_versions::drive_grove_method_versions::v1::DRIVE_GROVE_METHOD_VERSIONS_V1; +use crate::version::drive_versions::drive_identity_method_versions::v1::DRIVE_IDENTITY_METHOD_VERSIONS_V1; +use crate::version::drive_versions::drive_state_transition_method_versions::v1::DRIVE_STATE_TRANSITION_METHOD_VERSIONS_V1; +use crate::version::drive_versions::drive_structure_version::v1::DRIVE_STRUCTURE_V1; +use crate::version::drive_versions::drive_token_method_versions::v1::DRIVE_TOKEN_METHOD_VERSIONS_V1; +use crate::version::drive_versions::drive_verify_method_versions::v1::DRIVE_VERIFY_METHOD_VERSIONS_V1; +use crate::version::drive_versions::drive_vote_method_versions::v2::DRIVE_VOTE_METHOD_VERSIONS_V2; +use crate::version::drive_versions::{ + DriveAssetLockMethodVersions, DriveBalancesMethodVersions, DriveBatchOperationsMethodVersion, + DriveEstimatedCostsMethodVersions, DriveFeesMethodVersions, DriveFetchMethodVersions, + DriveInitializationMethodVersions, DriveMethodVersions, DriveOperationsMethodVersion, + DrivePlatformStateMethodVersions, DrivePlatformSystemMethodVersions, + DrivePrefundedSpecializedMethodVersions, DriveProtocolUpgradeVersions, + DriveProveMethodVersions, DriveSystemEstimationCostsMethodVersions, DriveVersion, +}; +use grovedb_version::version::v1::GROVE_V1; + +pub const DRIVE_VERSION_V3: DriveVersion = DriveVersion { + structure: DRIVE_STRUCTURE_V1, + methods: DriveMethodVersions { + initialization: DriveInitializationMethodVersions { + create_initial_state_structure: 1, // changed here to 1 to add token sum trees + }, + credit_pools: CREDIT_POOL_METHOD_VERSIONS_V1, + protocol_upgrade: DriveProtocolUpgradeVersions { + clear_version_information: 0, + fetch_versions_with_counter: 0, + fetch_proved_versions_with_counter: 0, + fetch_validator_version_votes: 0, + fetch_proved_validator_version_votes: 0, + remove_validators_proposed_app_versions: 0, + update_validator_proposed_app_version: 0, + }, + prove: DriveProveMethodVersions { + prove_elements: 0, + prove_multiple_state_transition_results: 0, + }, + balances: DriveBalancesMethodVersions { + add_to_system_credits: 0, + add_to_system_credits_operations: 0, + remove_from_system_credits: 0, + remove_from_system_credits_operations: 0, + calculate_total_credits_balance: 0, + }, + document: DRIVE_DOCUMENT_METHOD_VERSIONS_V1, + vote: DRIVE_VOTE_METHOD_VERSIONS_V2, + contract: DRIVE_CONTRACT_METHOD_VERSIONS_V2, // changed here to v2 + fees: DriveFeesMethodVersions { calculate_fee: 0 }, + estimated_costs: DriveEstimatedCostsMethodVersions { + add_estimation_costs_for_levels_up_to_contract: 0, + add_estimation_costs_for_levels_up_to_contract_document_type_excluded: 0, + add_estimation_costs_for_contested_document_tree_levels_up_to_contract: 0, + add_estimation_costs_for_contested_document_tree_levels_up_to_contract_document_type_excluded: 0, + }, + asset_lock: DriveAssetLockMethodVersions { + add_asset_lock_outpoint: 0, + add_estimation_costs_for_adding_asset_lock: 0, + fetch_asset_lock_outpoint_info: 0, + }, + verify: DRIVE_VERIFY_METHOD_VERSIONS_V1, + identity: DRIVE_IDENTITY_METHOD_VERSIONS_V1, + token: DRIVE_TOKEN_METHOD_VERSIONS_V1, + platform_system: DrivePlatformSystemMethodVersions { + estimation_costs: DriveSystemEstimationCostsMethodVersions { + for_total_system_credits_update: 0, + }, + }, + operations: DriveOperationsMethodVersion { + rollback_transaction: 0, + drop_cache: 0, + commit_transaction: 0, + apply_partial_batch_low_level_drive_operations: 0, + apply_partial_batch_grovedb_operations: 0, + apply_batch_low_level_drive_operations: 0, + apply_batch_grovedb_operations: 0, + }, + state_transitions: DRIVE_STATE_TRANSITION_METHOD_VERSIONS_V1, + batch_operations: DriveBatchOperationsMethodVersion { + convert_drive_operations_to_grove_operations: 0, + apply_drive_operations: 0, + }, + platform_state: DrivePlatformStateMethodVersions { + fetch_platform_state_bytes: 0, + store_platform_state_bytes: 0, + }, + fetch: DriveFetchMethodVersions { fetch_elements: 0 }, + prefunded_specialized_balances: DrivePrefundedSpecializedMethodVersions { + fetch_single: 0, + prove_single: 0, + add_prefunded_specialized_balance: 0, + add_prefunded_specialized_balance_operations: 0, + deduct_from_prefunded_specialized_balance: 0, + deduct_from_prefunded_specialized_balance_operations: 0, + estimated_cost_for_prefunded_specialized_balance_update: 0, + }, + }, + grove_methods: DRIVE_GROVE_METHOD_VERSIONS_V1, + grove_version: GROVE_V1, +}; diff --git a/packages/rs-platform-version/src/version/mod.rs b/packages/rs-platform-version/src/version/mod.rs index 49d59ca80c4..f060faae78c 100644 --- a/packages/rs-platform-version/src/version/mod.rs +++ b/packages/rs-platform-version/src/version/mod.rs @@ -1,6 +1,6 @@ mod protocol_version; -use crate::version::v7::PROTOCOL_VERSION_7; pub use protocol_version::*; +use crate::version::v8::PROTOCOL_VERSION_8; mod consensus_versions; pub mod dpp_versions; @@ -23,5 +23,5 @@ mod v8; pub type ProtocolVersion = u32; -pub const LATEST_VERSION: ProtocolVersion = PROTOCOL_VERSION_7; +pub const LATEST_VERSION: ProtocolVersion = PROTOCOL_VERSION_8; pub const INITIAL_PROTOCOL_VERSION: ProtocolVersion = 1; diff --git a/packages/rs-platform-version/src/version/protocol_version.rs b/packages/rs-platform-version/src/version/protocol_version.rs index d14f75c8bcf..520ceef97ad 100644 --- a/packages/rs-platform-version/src/version/protocol_version.rs +++ b/packages/rs-platform-version/src/version/protocol_version.rs @@ -46,6 +46,7 @@ pub const PLATFORM_VERSIONS: &[PlatformVersion] = &[ PLATFORM_V5, PLATFORM_V6, PLATFORM_V7, + PLATFORM_V8, ]; #[cfg(feature = "mock-versions")] diff --git a/packages/rs-platform-version/src/version/v8.rs b/packages/rs-platform-version/src/version/v8.rs index 2cd6f0772e2..3eb5de2b5dc 100644 --- a/packages/rs-platform-version/src/version/v8.rs +++ b/packages/rs-platform-version/src/version/v8.rs @@ -19,7 +19,7 @@ use crate::version::drive_abci_versions::drive_abci_structure_versions::v1::DRIV use crate::version::drive_abci_versions::drive_abci_validation_versions::v4::DRIVE_ABCI_VALIDATION_VERSIONS_V4; use crate::version::drive_abci_versions::drive_abci_withdrawal_constants::v2::DRIVE_ABCI_WITHDRAWAL_CONSTANTS_V2; use crate::version::drive_abci_versions::DriveAbciVersion; -use crate::version::drive_versions::v2::DRIVE_VERSION_V2; +use crate::version::drive_versions::v3::DRIVE_VERSION_V3; use crate::version::fee::v1::FEE_VERSION1; use crate::version::protocol_version::PlatformVersion; use crate::version::system_data_contract_versions::v1::SYSTEM_DATA_CONTRACT_VERSIONS_V1; @@ -32,7 +32,7 @@ pub const PROTOCOL_VERSION_8: ProtocolVersion = 8; //todo: make changes pub const PLATFORM_V8: PlatformVersion = PlatformVersion { protocol_version: PROTOCOL_VERSION_8, - drive: DRIVE_VERSION_V2, + drive: DRIVE_VERSION_V3, // changed (for data contract insert) drive_abci: DriveAbciVersion { structs: DRIVE_ABCI_STRUCTURE_VERSIONS_V1, methods: DRIVE_ABCI_METHOD_VERSIONS_V4, diff --git a/packages/token-history-contract/Cargo.toml b/packages/token-history-contract/Cargo.toml index b5ea373f76f..3625f97a47e 100644 --- a/packages/token-history-contract/Cargo.toml +++ b/packages/token-history-contract/Cargo.toml @@ -1,6 +1,6 @@ [package] -name = "wallet-utils-contract" -description = "Wallet data contract schema and tools" +name = "token-history-contract" +description = "Token history data contract schema and tools" version = "1.6.2" edition = "2021" rust-version.workspace = true diff --git a/packages/wasm-dpp/src/document/document_facade.rs b/packages/wasm-dpp/src/document/document_facade.rs index 609794eaa99..6255dfe2df9 100644 --- a/packages/wasm-dpp/src/document/document_facade.rs +++ b/packages/wasm-dpp/src/document/document_facade.rs @@ -4,7 +4,7 @@ use wasm_bindgen::{prelude::*, JsValue}; use crate::document::factory::DocumentFactoryWASM; use crate::{DataContractWasm, ExtendedDocumentWasm}; -use crate::document::state_transition::document_batch_transition::DocumentsBatchTransitionWasm; +use crate::document::state_transition::batch_transition::BatchTransitionWasm; #[derive(Clone)] #[wasm_bindgen(js_name=DocumentFacade)] @@ -96,7 +96,7 @@ impl DocumentFacadeWasm { &self, documents: &JsValue, nonce_counter_value: &js_sys::Object, //IdentityID/ContractID -> nonce - ) -> Result { + ) -> Result { self.factory .create_state_transition(documents, nonce_counter_value) } diff --git a/packages/wasm-dpp/src/document/factory.rs b/packages/wasm-dpp/src/document/factory.rs index 769b47c7ce5..639aaa2324a 100644 --- a/packages/wasm-dpp/src/document/factory.rs +++ b/packages/wasm-dpp/src/document/factory.rs @@ -18,7 +18,7 @@ use dpp::state_transition::batch_transition::batched_transition::document_transi use dpp::version::PlatformVersion; use std::convert::TryFrom; -use crate::document_batch_transition::DocumentsBatchTransitionWasm; +use crate::batch_transition::BatchTransitionWasm; use crate::entropy_generator::ExternalEntropyGenerator; use crate::{ identifier::identifier_from_js_value, @@ -109,7 +109,7 @@ impl DocumentFactoryWASM { &self, documents: &JsValue, nonce_counter_value: &js_sys::Object, //IdentityID/ContractID -> nonce - ) -> Result { + ) -> Result { let mut nonce_counter = BTreeMap::new(); let mut contract_ids_to_check = HashSet::<&Identifier>::new(); diff --git a/packages/wasm-dpp/src/document/state_transition/batch_transition/batched_transition/mod.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/batched_transition/mod.rs new file mode 100644 index 00000000000..c7c58b54719 --- /dev/null +++ b/packages/wasm-dpp/src/document/state_transition/batch_transition/batched_transition/mod.rs @@ -0,0 +1,18 @@ +use wasm_bindgen::prelude::wasm_bindgen; +use dpp::state_transition::batch_transition::batched_transition::BatchedTransition; + +#[wasm_bindgen(js_name=BatchedTransition)] +#[derive(Debug, Clone)] +pub struct BatchedTransitionWasm(BatchedTransition); + +impl From for BatchedTransitionWasm { + fn from(t: BatchedTransition) -> Self { + BatchedTransitionWasm(t) + } +} + +impl From for BatchedTransition { + fn from(t: BatchedTransitionWasm) -> Self { + t.0 + } +} diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_create_transition.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/document_transition/document_create_transition.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_create_transition.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/document_transition/document_create_transition.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_delete_transition.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/document_transition/document_delete_transition.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_delete_transition.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/document_transition/document_delete_transition.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_replace_transition.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/document_transition/document_replace_transition.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/document_replace_transition.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/document_transition/document_replace_transition.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/document_transition/mod.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/document_transition/mod.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/document_transition/mod.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/mod.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/mod.rs similarity index 97% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/mod.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/mod.rs index 402c5aa61cc..f0fc312bcbc 100644 --- a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/mod.rs +++ b/packages/wasm-dpp/src/document/state_transition/batch_transition/mod.rs @@ -32,8 +32,11 @@ use dpp::state_transition::batch_transition::batched_transition::BatchedTransiti use dpp::state_transition::batch_transition::methods::v0::DocumentsBatchTransitionMethodsV0; use dpp::state_transition::StateTransitionIdentitySigned; +use crate::batch_transition::batched_transition::BatchedTransitionWasm; pub mod document_transition; +mod token_transition; +mod batched_transition; // pub mod validation; #[derive(Clone, Debug)] @@ -103,10 +106,9 @@ impl BatchTransitionWasm { #[wasm_bindgen(js_name=getTransitions)] pub fn get_transitions(&self) -> js_sys::Array { let array = js_sys::Array::new(); - let transitions = self.0.document_transitions(); - for tr in transitions.iter().cloned() { - let transition: BatchTransitionWasm = tr.into(); + for tr in self.0.transitions_iter() { + let transition: BatchedTransitionWasm = tr.to_owned_transition().into(); array.push(&transition.into()); } @@ -118,7 +120,7 @@ impl BatchTransitionWasm { let mut transitions = vec![]; for js_transition in js_transitions.iter() { let transition: BatchedTransition = js_transition - .to_wasm::("BatchedTransition")? + .to_wasm::("BatchedTransition")? .to_owned() .into(); transitions.push(transition) diff --git a/packages/wasm-dpp/src/document/state_transition/batch_transition/token_transition/mod.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/token_transition/mod.rs new file mode 100644 index 00000000000..67b4b4bd885 --- /dev/null +++ b/packages/wasm-dpp/src/document/state_transition/batch_transition/token_transition/mod.rs @@ -0,0 +1,18 @@ +use wasm_bindgen::prelude::wasm_bindgen; +use dpp::state_transition::batch_transition::batched_transition::token_transition::TokenTransition; + +#[wasm_bindgen(js_name=TokenTransition)] +#[derive(Debug, Clone)] +pub struct TokenTransitionWasm(TokenTransition); + +impl From for TokenTransitionWasm { + fn from(t: TokenTransition) -> Self { + TokenTransitionWasm(t) + } +} + +impl From for TokenTransition { + fn from(t: TokenTransitionWasm) -> Self { + t.0 + } +} diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/find_duplicates_by_id.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/find_duplicates_by_id.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/find_duplicates_by_id.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/find_duplicates_by_id.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/find_duplicates_by_indices.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/find_duplicates_by_indices.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/find_duplicates_by_indices.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/find_duplicates_by_indices.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/mod.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/mod.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/mod.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/mod.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/validate_documents_batch_transition_basic.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/validate_documents_batch_transition_basic.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/validate_documents_batch_transition_basic.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/validate_documents_batch_transition_basic.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/validate_partial_compound_indices.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/validate_partial_compound_indices.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/basic/validate_partial_compound_indices.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/basic/validate_partial_compound_indices.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/mod.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/mod.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/mod.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/mod.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/state/fetch_extended_documents.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/state/fetch_extended_documents.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/state/fetch_extended_documents.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/state/fetch_extended_documents.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/state/mod.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/state/mod.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/state/mod.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/state/mod.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/state/validate_documents_batch_transitions_state.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/state/validate_documents_batch_transitions_state.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/state/validate_documents_batch_transitions_state.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/state/validate_documents_batch_transitions_state.rs diff --git a/packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/state/validate_documents_uniqueness_by_indices.rs b/packages/wasm-dpp/src/document/state_transition/batch_transition/validation/state/validate_documents_uniqueness_by_indices.rs similarity index 100% rename from packages/wasm-dpp/src/document/state_transition/document_batch_transition/validation/state/validate_documents_uniqueness_by_indices.rs rename to packages/wasm-dpp/src/document/state_transition/batch_transition/validation/state/validate_documents_uniqueness_by_indices.rs diff --git a/packages/wasm-dpp/src/document/state_transition/mod.rs b/packages/wasm-dpp/src/document/state_transition/mod.rs index 7db6d118e0a..03238bee69e 100644 --- a/packages/wasm-dpp/src/document/state_transition/mod.rs +++ b/packages/wasm-dpp/src/document/state_transition/mod.rs @@ -1 +1 @@ -pub mod document_batch_transition; +pub mod batch_transition; diff --git a/packages/wasm-dpp/src/errors/consensus/consensus_error.rs b/packages/wasm-dpp/src/errors/consensus/consensus_error.rs index 627b65a2674..85bbbc4e6b2 100644 --- a/packages/wasm-dpp/src/errors/consensus/consensus_error.rs +++ b/packages/wasm-dpp/src/errors/consensus/consensus_error.rs @@ -61,7 +61,7 @@ use dpp::consensus::state::data_trigger::DataTriggerError::{ DataTriggerConditionError, DataTriggerExecutionError, DataTriggerInvalidResultError, }; use wasm_bindgen::{JsError, JsValue}; -use dpp::consensus::basic::data_contract::{ContestedUniqueIndexOnMutableDocumentTypeError, ContestedUniqueIndexWithUniqueIndexError, InvalidDocumentTypeRequiredSecurityLevelError, UnknownDocumentCreationRestrictionModeError, UnknownSecurityLevelError, UnknownStorageKeyRequirementsError, UnknownTradeModeError, UnknownTransferableTypeError}; +use dpp::consensus::basic::data_contract::{ContestedUniqueIndexOnMutableDocumentTypeError, ContestedUniqueIndexWithUniqueIndexError, DataContractTokenConfigurationUpdateError, InvalidDocumentTypeRequiredSecurityLevelError, UnknownDocumentCreationRestrictionModeError, UnknownSecurityLevelError, UnknownStorageKeyRequirementsError, UnknownTradeModeError, UnknownTransferableTypeError}; use dpp::consensus::basic::document::{ContestedDocumentsTemporarilyNotAllowedError, DocumentCreationNotAllowedError, DocumentFieldMaxSizeExceededError, MaxDocumentsTransitionsExceededError, MissingPositionsInDocumentTypePropertiesError}; use dpp::consensus::basic::identity::{DataContractBoundsNotPresentError, DisablingKeyIdAlsoBeingAddedInSameTransitionError, InvalidIdentityCreditWithdrawalTransitionAmountError, InvalidIdentityUpdateTransitionDisableKeysError, InvalidIdentityUpdateTransitionEmptyError, TooManyMasterPublicKeyError, WithdrawalOutputScriptNotAllowedWhenSigningWithOwnerKeyError}; use dpp::consensus::basic::overflow_error::OverflowError; @@ -571,6 +571,13 @@ fn from_basic_error(basic_error: &BasicError) -> JsValue { ) .into() } + BasicError::DataContractTokenConfigurationUpdateError(e) => { + generic_consensus_error!( + DataContractTokenConfigurationUpdateError, + e + ) + .into() + } } } diff --git a/packages/wasm-dpp/src/state_transition/state_transition_factory.rs b/packages/wasm-dpp/src/state_transition/state_transition_factory.rs index f0ba5cde672..d57903a8dcb 100644 --- a/packages/wasm-dpp/src/state_transition/state_transition_factory.rs +++ b/packages/wasm-dpp/src/state_transition/state_transition_factory.rs @@ -1,5 +1,5 @@ use crate::data_contract::{DataContractCreateTransitionWasm, DataContractUpdateTransitionWasm}; -use crate::document_batch_transition::DocumentsBatchTransitionWasm; +use crate::batch_transition::BatchTransitionWasm; use crate::errors::from_dpp_err; use crate::identity::state_transition::{ IdentityCreateTransitionWasm, IdentityCreditTransferTransitionWasm, @@ -56,7 +56,7 @@ impl StateTransitionFactoryWasm { StateTransition::IdentityCreditWithdrawal(st) => { Ok(IdentityCreditWithdrawalTransitionWasm::from(st).into()) } - StateTransition::Batch(st) => Ok(DocumentsBatchTransitionWasm::from(st).into()), + StateTransition::Batch(st) => Ok(BatchTransitionWasm::from(st).into()), StateTransition::MasternodeVote(st) => { Ok(MasternodeVoteTransitionWasm::from(st).into()) }