diff --git a/book/src/contract-keywords/aggregates.md b/book/src/contract-keywords/aggregates.md index d2cd077d489..a75b7c3dbdf 100644 --- a/book/src/contract-keywords/aggregates.md +++ b/book/src/contract-keywords/aggregates.md @@ -159,6 +159,10 @@ A range total costs more on each write than a per-value total, since every node - Each `range*` flag has its prerequisite, as listed above. - The meta-schema refuses a malformed value (`JsonSchemaError`, 10101). +## Writes past a sum + +A sum holds a signed 64-bit integer, and each node of a sum tree keeps the total of its own value and its children's, so a write can take a sum out of range even when the type's values are each in range. A create, replace or transfer that would do so is refused when it is applied, as nothing checks the sums before. From protocol version 15 it is a paid error, `DocumentSumOverflowError` (40154): nothing of the write is stored, the identity contract nonce is bumped, and the signer pays the processing of the refused write as fee validation estimates it, with no storage fee. Bounding the summed property (`minimum` and `maximum`) to what the application needs keeps the sums out of reach. + ## Choosing what to set | The application needs | Set | diff --git a/book/src/error-handling/error-codes.md b/book/src/error-handling/error-codes.md index 9f1b3c0868e..1ad7e314aff 100644 --- a/book/src/error-handling/error-codes.md +++ b/book/src/error-handling/error-codes.md @@ -108,7 +108,7 @@ The fee category currently has a single code. The 30000 range is reserved for fu | Range | Category | Examples | |-------|----------|----------| | 40000-40009 | Data Contract | `DataContractAlreadyPresentError` (40000), `DataContractIsReadonlyError` (40001), `DataContractNotFoundError` (40008) | -| 40100-40199 | Documents | `DocumentAlreadyPresentError` (40100), `DocumentNotFoundError` (40101), `DuplicateUniqueIndexError` (40105), `DocumentActionFeeAgreementNotSetError` (40132), `DocumentActionFeeAgreementMismatchError` (40133), `DocumentActionFeeMultiplierNotToleratedError` (40134), `DocumentActionFeeModeratorsShareMismatchError` (40139), `DocumentExpiredError` (40140), `DocumentContestMaximumContendersReachedError` (40141), `ReferencedDocumentRequirementNotMetError` (40142), `ReferencedDocumentTypeNotModeratedError` (40143), `ReferencedDocumentTypeModeratedError` (40144), `ReferencedDocumentRemovedError` (40145), `ReferencedDocumentTypeIndexOnlyError` (40146), `DocumentDeleteConstraintViolatedError` (40147), `ReferencedDocumentRuleReadInvalidError` (40148), `ReferencedDocumentPrecededError` (40149), `ReferencedDocumentTypePrivateError` (40150), `ReferencedDocumentTypeRequirementNotMetError` (40153) | +| 40100-40199 | Documents | `DocumentAlreadyPresentError` (40100), `DocumentNotFoundError` (40101), `DuplicateUniqueIndexError` (40105), `DocumentActionFeeAgreementNotSetError` (40132), `DocumentActionFeeAgreementMismatchError` (40133), `DocumentActionFeeMultiplierNotToleratedError` (40134), `DocumentActionFeeModeratorsShareMismatchError` (40139), `DocumentExpiredError` (40140), `DocumentContestMaximumContendersReachedError` (40141), `ReferencedDocumentRequirementNotMetError` (40142), `ReferencedDocumentTypeNotModeratedError` (40143), `ReferencedDocumentTypeModeratedError` (40144), `ReferencedDocumentRemovedError` (40145), `ReferencedDocumentTypeIndexOnlyError` (40146), `DocumentDeleteConstraintViolatedError` (40147), `ReferencedDocumentRuleReadInvalidError` (40148), `ReferencedDocumentPrecededError` (40149), `ReferencedDocumentTypePrivateError` (40150), `ReferencedDocumentTypeRequirementNotMetError` (40153), `DocumentSumOverflowError` (40154) | | 40200-40217 | Identity | `IdentityAlreadyExistsError` (40200), `InvalidIdentityRevisionError` (40203), `IdentityInsufficientBalanceError` (40210) | | 40300-40308 | Voting | `MasternodeNotFoundError` (40300), `MasternodeVoteAlreadyPresentError` (40304), `VoteChoiceNotAllowedForVotePollError` (40307), `YesNoVotePollNotAvailableForVotingError` (40308) | | 40400-40401 | Prefunded Balances | `PrefundedSpecializedBalanceInsufficientError` (40400) | diff --git a/packages/rs-dpp/src/errors/consensus/codes.rs b/packages/rs-dpp/src/errors/consensus/codes.rs index bb3f52b8c71..c0be27e89e2 100644 --- a/packages/rs-dpp/src/errors/consensus/codes.rs +++ b/packages/rs-dpp/src/errors/consensus/codes.rs @@ -402,6 +402,7 @@ impl ErrorWithCode for StateError { Self::DocumentTypeNotPrivateError(_) => 40151, Self::PrivateDocumentEntrySizeMismatchError(_) => 40152, Self::ReferencedDocumentTypeRequirementNotMetError(_) => 40153, + Self::DocumentSumOverflowError(_) => 40154, // Identity Errors: 40200-40299 Self::IdentityAlreadyExistsError(_) => 40200, diff --git a/packages/rs-dpp/src/errors/consensus/state/document/document_sum_overflow_error.rs b/packages/rs-dpp/src/errors/consensus/state/document/document_sum_overflow_error.rs new file mode 100644 index 00000000000..9ef6a8731c1 --- /dev/null +++ b/packages/rs-dpp/src/errors/consensus/state/document/document_sum_overflow_error.rs @@ -0,0 +1,53 @@ +use crate::consensus::state::state_error::StateError; +use crate::consensus::ConsensusError; +use crate::ProtocolError; +use bincode::{Decode, DecodeUntrusted, Encode}; +use platform_serialization_derive::{ + PlatformDeserializeTrusted, PlatformDeserializeUntrusted, PlatformSerialize, +}; +use platform_value::Identifier; +use thiserror::Error; + +/// A document write to a data contract would take one of the sums its document types keep (an +/// index `summable` by a property, a `rangeSummable` index, or `documentsSummable`) past what a +/// sum holds, a signed 64 bit integer. The write is refused as a paid error from protocol +/// version 15: the identity contract nonce is bumped and nothing else of the write is stored. +#[derive( + Error, + Debug, + Clone, + PartialEq, + Eq, + Encode, + Decode, + PlatformSerialize, + PlatformDeserializeTrusted, + PlatformDeserializeUntrusted, + DecodeUntrusted, +)] +#[error("a document write to contract {contract_id} would take a document sum past the largest value a sum holds")] +#[platform_serialize(unversioned)] +pub struct DocumentSumOverflowError { + /* + + DO NOT CHANGE ORDER OF FIELDS WITHOUT INTRODUCING OF NEW VERSION + + */ + contract_id: Identifier, +} + +impl DocumentSumOverflowError { + pub fn new(contract_id: Identifier) -> Self { + Self { contract_id } + } + + pub fn contract_id(&self) -> &Identifier { + &self.contract_id + } +} + +impl From for ConsensusError { + fn from(err: DocumentSumOverflowError) -> Self { + Self::StateError(StateError::DocumentSumOverflowError(err)) + } +} diff --git a/packages/rs-dpp/src/errors/consensus/state/document/mod.rs b/packages/rs-dpp/src/errors/consensus/state/document/mod.rs index 1950a04597d..f2b582fbf8d 100644 --- a/packages/rs-dpp/src/errors/consensus/state/document/mod.rs +++ b/packages/rs-dpp/src/errors/consensus/state/document/mod.rs @@ -18,6 +18,7 @@ pub mod document_incorrect_purchase_price_error; pub mod document_not_for_sale_error; pub mod document_not_found_error; pub mod document_owner_id_mismatch_error; +pub mod document_sum_overflow_error; pub mod document_timestamp_window_violation_error; pub mod document_timestamps_are_equal_error; pub mod document_timestamps_mismatch_error; diff --git a/packages/rs-dpp/src/errors/consensus/state/state_error.rs b/packages/rs-dpp/src/errors/consensus/state/state_error.rs index e301828062f..bb1ee72aaea 100644 --- a/packages/rs-dpp/src/errors/consensus/state/state_error.rs +++ b/packages/rs-dpp/src/errors/consensus/state/state_error.rs @@ -86,6 +86,7 @@ use crate::consensus::state::document::referenced_document_type_index_only_error use crate::consensus::state::document::referenced_document_type_private_error::ReferencedDocumentTypePrivateError; use crate::consensus::state::document::referenced_document_type_requirement_not_met_error::ReferencedDocumentTypeRequirementNotMetError; use crate::consensus::state::document::document_type_not_private_error::DocumentTypeNotPrivateError; +use crate::consensus::state::document::document_sum_overflow_error::DocumentSumOverflowError; use crate::consensus::state::document::private_document_entry_size_mismatch_error::PrivateDocumentEntrySizeMismatchError; use crate::consensus::state::document::document_delete_constraint_violated_error::DocumentDeleteConstraintViolatedError; use crate::consensus::state::document::referenced_document_rule_read_invalid_error::ReferencedDocumentRuleReadInvalidError; @@ -777,6 +778,11 @@ pub enum StateError { // document type that does not meet its `documentTypeRequirements` (protocol version 15). #[error(transparent)] ReferencedDocumentTypeRequirementNotMetError(ReferencedDocumentTypeRequirementNotMetError), + + // A document write would take one of its contract's document sums past what a sum holds + // (protocol version 15). + #[error(transparent)] + DocumentSumOverflowError(DocumentSumOverflowError), } impl From for ConsensusError { @@ -1768,5 +1774,13 @@ mod tests { )), 181 ); + // A document write past one of its contract's document sums (protocol version 15): the + // tail of the enum. + assert_eq!( + discriminant_of(StateError::DocumentSumOverflowError( + DocumentSumOverflowError::new(identity_id) + )), + 182 + ); } } diff --git a/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/execute_event/v2/mod.rs b/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/execute_event/v2/mod.rs index 43d33c8588c..48f059eae9a 100644 --- a/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/execute_event/v2/mod.rs +++ b/packages/rs-drive-abci/src/execution/platform_events/state_transition_processing/execute_event/v2/mod.rs @@ -6,10 +6,14 @@ use crate::rpc::core::CoreRPCLike; use dpp::address_funds::PlatformAddress; use dpp::balances::credits::CreditOperation; use dpp::block::block_info::BlockInfo; +use dpp::consensus::state::document::document_sum_overflow_error::DocumentSumOverflowError; use dpp::consensus::ConsensusError; use dpp::fee::Credits; +use dpp::platform_value::Identifier; use dpp::version::PlatformVersion; +use drive::grovedb::Error as GroveError; use drive::grovedb::Transaction; +use drive::util::batch::{ContractModerationOperationType, DriveOperation, IdentityOperationType}; use std::collections::BTreeMap; impl Platform @@ -18,6 +22,22 @@ where { /// Generation 1, except that a gas sponsor who pays is named as the owner of the storage /// the batch's documents write, so the refunds of that storage go back to them. + /// + /// A document write whose operations would take a document sum past what a sum tree holds + /// (GroveDB refuses to apply them) is refused as a paid consensus error, + /// [`DocumentSumOverflowError`]: everything the attempt wrote is rolled back, and the event + /// is executed again as the nonce bump a refused state validation of the batch leaves + /// ([`SumOverflowRefusal`]). The signer pays for the bump, the work validation billed, and + /// the processing of the refused write as fee validation estimates it; no storage. Whether a + /// write overflows is a function of the state it is applied to, so every node refuses the + /// same writes. + /// + /// The rollback needs a savepoint on the block transaction, which stays on the transaction + /// when the write applies (RocksDB pops a savepoint only by rolling back to it). The genesis + /// height rewinds each re-proposal of its block to the one savepoint `init_chain` set, so no + /// savepoint is set there and a write overflowing a sum at the genesis height stays the + /// internal error it was. At every other height a savepoint left on the transaction is inert: + /// the block's transaction is committed or dropped as a whole. #[inline(always)] #[allow(clippy::too_many_arguments)] pub(super) fn execute_event_v2( @@ -26,19 +46,171 @@ where consensus_errors: Vec, block_info: &BlockInfo, transaction: &Transaction, - address_balances_in_update: Option<&mut BTreeMap>, + mut address_balances_in_update: Option<&mut BTreeMap>, block_credit_mints: &mut Credits, platform_version: &PlatformVersion, ) -> Result { - self.execute_event_v1_body( + // An event that already carries consensus errors is the nonce bump of a refused batch, + // which writes no document. + let refusal = if consensus_errors.is_empty() + && block_info.height != self.config.abci.genesis_height + { + SumOverflowRefusal::of(&event) + } else { + None + }; + let Some(refusal) = refusal else { + return self.execute_event_v1_body( + event, + consensus_errors, + block_info, + transaction, + address_balances_in_update, + block_credit_mints, + true, + platform_version, + ); + }; + + transaction.set_savepoint(); + match self.execute_event_v1_body( event, consensus_errors, block_info, transaction, - address_balances_in_update, + address_balances_in_update.as_deref_mut(), block_credit_mints, true, platform_version, - ) + ) { + Err(Error::Drive(error)) if error.is_sum_tree_overflow() => { + // Applying a write may take several GroveDB batches and direct writes (the + // clean-up of expired time range buckets before them), and only the refused + // batch is undone by GroveDB. Rolling back to the savepoint undoes the rest, so + // the state is as if the write had never been attempted. The fee and the + // balance changes are written only after the operations applied. + transaction + .rollback_to_savepoint() + .map_err(|error| Error::Drive(GroveError::StorageError(error).into()))?; + let SumOverflowRefusal { + event: refusal_event, + attempted_operations, + contract_id, + } = refusal; + let attempted_processing_fee = self + .drive + .apply_drive_operations( + attempted_operations, + false, + block_info, + Some(transaction), + platform_version, + ) + .map_err(Error::Drive)? + .processing_fee; + self.execute_event_v1_body( + refusal_event.with_additional_fixed_fee_cost(attempted_processing_fee), + vec![DocumentSumOverflowError::new(contract_id).into()], + block_info, + transaction, + address_balances_in_update, + block_credit_mints, + true, + platform_version, + ) + } + result => result, + } + } +} + +/// What an identity-paid document write is executed as when its operations would take a +/// document sum past what a sum tree holds. +struct SumOverflowRefusal<'a> { + /// The write's event with only the operations a refused state validation of the batch + /// leaves: the identity contract nonce bumps and the removal of a suspension that lapsed. + /// Nothing else of the write runs, so it moves no balance, owes no action fee and is never + /// sponsored, like any batch that failed. + event: ExecutionEvent<'a>, + /// The operations of the refused write, which price the processing it cost. + attempted_operations: Vec>, + /// The contract the write is to. + contract_id: Identifier, +} + +impl<'a> SumOverflowRefusal<'a> { + /// The refusal of `event`, when it is an identity-paid write of documents to a contract. + fn of(event: &ExecutionEvent<'a>) -> Option { + let ExecutionEvent::Paid { + identity, + operations, + execution_operations, + user_fee_increase, + signing_key_limits, + .. + } = event + else { + return None; + }; + if !operations + .iter() + .any(|operation| matches!(operation, DriveOperation::DocumentOperation(_))) + { + return None; + } + let contract_id = operations.iter().find_map(|operation| match operation { + DriveOperation::IdentityOperation( + IdentityOperationType::UpdateIdentityContractNonce { contract_id, .. }, + ) => Some(Identifier::new(*contract_id)), + _ => None, + })?; + let refused_operations = operations + .iter() + .filter(|operation| { + matches!( + operation, + DriveOperation::IdentityOperation( + IdentityOperationType::UpdateIdentityContractNonce { .. } + ) | DriveOperation::ContractModerationOperation( + ContractModerationOperationType::RemoveSuspension { .. } + ) + ) + }) + .cloned() + .collect(); + Some(Self { + event: ExecutionEvent::Paid { + identity: identity.clone(), + removed_balance: None, + added_to_balance_outputs: None, + operations: refused_operations, + execution_operations: execution_operations.clone(), + additional_fixed_fee_cost: None, + user_fee_increase: *user_fee_increase, + signing_key_limits: *signing_key_limits, + gas_sponsor: None, + action_fees: vec![], + }, + attempted_operations: operations.clone(), + contract_id, + }) + } +} + +impl ExecutionEvent<'_> { + /// The event with `fee` added to the processing fee it charges up front. + fn with_additional_fixed_fee_cost(mut self, fee: Credits) -> Self { + if let ExecutionEvent::Paid { + additional_fixed_fee_cost, + .. + } = &mut self + { + *additional_fixed_fee_cost = Some( + additional_fixed_fee_cost + .unwrap_or_default() + .saturating_add(fee), + ); + } + self } } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/mod.rs index ff256229b6f..02f1cb69913 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/mod.rs @@ -43,6 +43,7 @@ mod repeated_properties_update; mod replacement; mod required_since; mod stored_non_document_reference; +mod sum_overflow; mod system_agreement; mod token_cost_policy; mod token_market_orders; diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/sum_overflow.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/sum_overflow.rs new file mode 100644 index 00000000000..534d2d3a314 --- /dev/null +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/sum_overflow.rs @@ -0,0 +1,730 @@ +//! A document write whose summed value would take a document sum past what a sum tree holds: +//! a per-value sum (an index `summable` by the property), a range sum (`rangeSummable`, a +//! provable sum tree) and a document type's sum (`documentsSummable`), written by a create, a +//! replace or a transfer. + +use super::*; + +mod sum_overflow_tests { + use super::*; + use crate::execution::check_tx::CheckTxLevel; + use crate::platform_types::platform::PlatformRef; + use crate::rpc::core::MockCoreRPCLike; + use crate::test::helpers::setup::TempPlatform; + use dpp::consensus::codes::ErrorWithCode; + use dpp::data_contract::schema::DataContractSchemaMethodsV0; + use dpp::document::Document; + use dpp::fee::fee_result::FeeResult; + use dpp::identity::identity_nonce::IDENTITY_NONCE_VALUE_FILTER; + use dpp::identity::{Identity, IdentityPublicKey}; + use dpp::platform_value::platform_value; + use dpp::prelude::{DataContract, IdentityNonce}; + use dpp::state_transition::StateTransition; + use dpp::tests::fixtures::get_data_contract_fixture; + use drive::query::DriveDocumentQuery; + use drive::util::storage_flags::StorageFlags; + use rand::rngs::StdRng; + use rand::SeedableRng; + use simple_signer::signer::SimpleSigner; + use std::collections::BTreeMap; + + /// The document type whose per-owner index is `summable` by `amount`. + const PER_VALUE: &str = "perValue"; + /// The document type whose per-owner index is `rangeSummable` by `amount`. + const RANGED: &str = "ranged"; + /// The document type that is `documentsSummable` by `amount`. + const TYPED: &str = "typed"; + + /// A mutable, transferable type with a signed `amount` (which a sum takes up to + /// `i64::MAX`), declaring the sums `sums` adds to the schema. + fn summed_schema(sums: impl FnOnce(&mut Value)) -> Value { + let mut schema = platform_value!({ + "type": "object", + "documentsMutable": true, + "transferable": 1, + "properties": { + "amount": { + "type": "integer", + "minimum": -1000, + "maximum": i64::MAX, + "position": 0 + } + }, + "required": ["amount"], + "additionalProperties": false + }); + sums(&mut schema); + schema + } + + fn owner_index(range: bool) -> Value { + let mut index = platform_value!({ + "name": "byOwner", + "properties": [{ "$ownerId": "asc" }], + "summable": "amount" + }); + if range { + index + .insert("rangeSummable".to_string(), Value::Bool(true)) + .expect("expected a map"); + } + index + } + + type Writer = (Identity, SimpleSigner, IdentityPublicKey); + + /// Two identities and one contract with the three summed types. + struct SumFixture { + platform: TempPlatform, + platform_version: &'static PlatformVersion, + writers: Vec, + contract: DataContract, + next_nonces: BTreeMap, + block_info: BlockInfo, + /// Whether transitions are processed as the proposer builds its block, each in a + /// savepoint of its own, rather than as a validator checks a received one. + proposing: bool, + } + + /// What a transition did: what `check_tx` said, the block's result, and the writer's + /// identity contract nonce and balance before and after. + struct Outcome { + /// The identity contract nonce the transition carries. + transition_nonce: IdentityNonce, + check_tx_valid: bool, + result: StateTransitionExecutionResult, + nonce_before: Option, + nonce_after: Option, + balance_before: Credits, + balance_after: Credits, + } + + impl Outcome { + fn charged(&self) -> Credits { + self.balance_before.saturating_sub(self.balance_after) + } + } + + impl SumFixture { + fn new(protocol_version: u32) -> Self { + let platform_version = + PlatformVersion::get(protocol_version).expect("expected a known protocol version"); + let mut platform = TestPlatformBuilder::new() + .with_initial_protocol_version(protocol_version) + .build_with_mock_rpc() + .set_genesis_state(); + + let writers = vec![ + setup_identity(&mut platform, 6101, dash_to_credits!(1.0)), + setup_identity(&mut platform, 6102, dash_to_credits!(1.0)), + ]; + + let mut contract = + get_data_contract_fixture(Some(writers[0].0.id()), 0, protocol_version) + .data_contract_owned(); + let schemas = [ + ( + PER_VALUE, + summed_schema(|schema| { + schema + .insert( + "indices".to_string(), + Value::Array(vec![owner_index(false)]), + ) + .expect("expected a map") + }), + ), + ( + RANGED, + summed_schema(|schema| { + schema + .insert("indices".to_string(), Value::Array(vec![owner_index(true)])) + .expect("expected a map") + }), + ), + ( + TYPED, + summed_schema(|schema| { + schema + .insert( + "documentsSummable".to_string(), + Value::Text("amount".to_string()), + ) + .expect("expected a map") + }), + ), + ]; + for (name, schema) in schemas { + contract + .set_document_schema(name, schema, true, &mut Vec::new(), platform_version) + .expect("expected to add the document type"); + } + platform + .drive + .apply_contract( + &contract, + BlockInfo::default(), + true, + StorageFlags::optional_default_as_cow(), + None, + platform_version, + ) + .expect("expected to apply the contract"); + + Self { + platform, + platform_version, + writers, + contract, + next_nonces: BTreeMap::new(), + block_info: BlockInfo::default(), + proposing: false, + } + } + + fn latest() -> Self { + Self::new(PlatformVersion::latest().protocol_version) + } + + fn take_nonce(&mut self, writer: usize) -> IdentityNonce { + let next = self + .next_nonces + .entry(self.writers[writer].0.id()) + .or_insert(1); + let nonce = *next; + *next += 1; + nonce + } + + fn nonce(&self, writer: usize) -> Option { + self.platform + .drive + .fetch_identity_contract_nonce( + self.writers[writer].0.id().to_buffer(), + self.contract.id().to_buffer(), + true, + None, + self.platform_version, + ) + .expect("expected to fetch the nonce") + } + + fn balance(&self, writer: usize) -> Credits { + self.platform + .drive + .fetch_identity_balance( + self.writers[writer].0.id().to_buffer(), + None, + self.platform_version, + ) + .expect("expected to fetch the balance") + .expect("expected a balance") + } + + fn check_tx(&self, transition: &StateTransition) -> bool { + let state = self.platform.state.load(); + let platform_ref = PlatformRef { + drive: &self.platform.drive, + state: &state, + config: &self.platform.config, + core_rpc: &self.platform.core_rpc, + }; + let raw = transition + .serialize_to_bytes() + .expect("expected the transition to serialize"); + self.platform + .check_tx( + &raw, + CheckTxLevel::FirstTimeCheck, + &platform_ref, + self.platform_version, + ) + .expect("expected to check the transition") + .is_valid() + } + + fn run( + &self, + writer: usize, + transition_nonce: IdentityNonce, + transition: &StateTransition, + ) -> Outcome { + let check_tx_valid = self.check_tx(transition); + let nonce_before = self.nonce(writer); + let balance_before = self.balance(writer); + let platform_state = self.platform.state.load(); + let serialized = transition + .serialize_to_bytes() + .expect("expected the transition to serialize"); + let transaction = self.platform.drive.grove.start_transaction(); + let processing_result = self + .platform + .platform + .process_raw_state_transitions( + &[serialized], + &platform_state, + &self.block_info, + &transaction, + self.platform_version, + self.proposing, + None, + ) + .expect("expected to process the state transition"); + self.platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit the transaction"); + let result = processing_result.into_execution_results().remove(0); + Outcome { + transition_nonce, + check_tx_valid, + result, + nonce_before, + nonce_after: self.nonce(writer), + balance_before, + balance_after: self.balance(writer), + } + } + + /// A create by `writer` of a `document_type` document with `amount`, and the document. + async fn create( + &mut self, + writer: usize, + document_type: &str, + amount: i64, + ) -> (Outcome, Document) { + let platform_version = self.platform_version; + let nonce = self.take_nonce(writer); + let (identity, signer, key) = &self.writers[writer]; + let document_type_ref = self + .contract + .document_type_for_name(document_type) + .expect("expected the document type"); + let mut rng = StdRng::seed_from_u64(nonce * 31 + writer as u64); + let entropy = Bytes32::random_with_rng(&mut rng); + let mut document = document_type_ref + .random_document_with_identifier_and_entropy( + &mut rng, + identity.id(), + entropy, + DocumentFieldFillType::DoNotFillIfNotRequired, + DocumentFieldFillSize::AnyDocumentFillSize, + platform_version, + ) + .expect("expected a random document"); + document + .set_id_for_creation(document_type_ref, &entropy.0, nonce, platform_version) + .expect("expected to set the document id"); + document.set("amount", Value::I64(amount)); + let transition = BatchTransition::new_document_creation_transition_from_document( + document.clone(), + document_type_ref, + entropy.0, + key, + nonce, + 0, + None, + signer, + platform_version, + None, + ) + .await + .expect("expected the create transition"); + (self.run(writer, nonce, &transition), document) + } + + /// A replace by the owner `writer` of `document` with `amount`, and the replacement. + async fn replace( + &mut self, + writer: usize, + document_type: &str, + document: &Document, + amount: i64, + ) -> (Outcome, Document) { + let platform_version = self.platform_version; + let nonce = self.take_nonce(writer); + let (_, signer, key) = &self.writers[writer]; + let document_type_ref = self + .contract + .document_type_for_name(document_type) + .expect("expected the document type"); + let mut replacement = document.clone(); + replacement.set("amount", Value::I64(amount)); + replacement + .increment_revision() + .expect("expected the revision to increment"); + let transition = BatchTransition::new_document_replacement_transition_from_document( + replacement.clone(), + document_type_ref, + key, + nonce, + 0, + None, + signer, + platform_version, + None, + ) + .await + .expect("expected the replace transition"); + (self.run(writer, nonce, &transition), replacement) + } + + /// A transfer by the owner `writer` of `document` to `recipient`. + async fn transfer( + &mut self, + writer: usize, + document_type: &str, + document: &Document, + recipient: usize, + ) -> Outcome { + let platform_version = self.platform_version; + let nonce = self.take_nonce(writer); + let recipient_id = self.writers[recipient].0.id(); + let (_, signer, key) = &self.writers[writer]; + let document_type_ref = self + .contract + .document_type_for_name(document_type) + .expect("expected the document type"); + let mut transferred = document.clone(); + transferred + .increment_revision() + .expect("expected the revision to increment"); + let transition = BatchTransition::new_document_transfer_transition_from_document( + transferred, + document_type_ref, + recipient_id, + key, + nonce, + 0, + None, + signer, + platform_version, + None, + ) + .await + .expect("expected the transfer transition"); + self.run(writer, nonce, &transition) + } + + /// The stored documents of `document_type`, by id, with their owners and amounts. + fn stored(&self, document_type: &str) -> BTreeMap { + let query = DriveDocumentQuery::from_sql_expr( + &format!("select * from {document_type}"), + &self.contract, + Some(&self.platform.config.drive), + self.platform_version, + ) + .expect("expected a document query"); + self.platform + .drive + .query_documents(query, None, false, None, None) + .expect("expected a query result") + .documents() + .iter() + .map(|document| { + let amount = document + .get("amount") + .and_then(|value| value.to_integer::().ok()) + .expect("expected an amount"); + (document.id(), (document.owner_id(), amount)) + }) + .collect() + } + + /// Asserts `outcome` succeeded. + fn expect_success(outcome: &Outcome, what: &str) { + assert_matches!( + outcome.result, + StateTransitionExecutionResult::SuccessfulExecution { .. }, + "{what} must succeed" + ); + } + } + + /// Prints what a transition that would overflow a sum did, for the record. + fn report(what: &str, outcome: &Outcome) { + let result = match &outcome.result { + StateTransitionExecutionResult::SuccessfulExecution { .. } => "success".to_string(), + StateTransitionExecutionResult::PaidConsensusError { error, .. } => { + format!("paid consensus error {}", error.code()) + } + StateTransitionExecutionResult::UnpaidConsensusError(error) => { + format!("unpaid consensus error {}", error.code()) + } + StateTransitionExecutionResult::InternalError(error) => { + format!("internal error: {error}") + } + StateTransitionExecutionResult::NotExecuted(reason) => { + format!("not executed: {reason:?}") + } + }; + println!( + "{what}: check_tx valid {}, block: {result}, nonce {:?} -> {:?}, charged {}", + outcome.check_tx_valid, + outcome.nonce_before, + outcome.nonce_after, + outcome.charged() + ); + } + + /// Asserts a write that would overflow a sum ended as a paid consensus error that bumped + /// the writer's nonce and charged `expected_charge`, the fee the result reports, leaving + /// the documents as they were. + fn expect_paid_overflow( + fixture: &SumFixture, + what: &str, + outcome: &Outcome, + document_type: &str, + stored_before: &BTreeMap, + expected_charge: Credits, + ) { + report(what, outcome); + assert!(outcome.check_tx_valid, "{what}: check_tx admits the write"); + let StateTransitionExecutionResult::PaidConsensusError { + error, actual_fees, .. + } = &outcome.result + else { + panic!( + "{what}: expected a paid consensus error, got {:?}", + outcome.result + ); + }; + println!("{what}: fee {actual_fees:?}"); + assert_eq!(actual_fees.storage_fee, 0, "{what}: nothing is stored"); + assert_matches!( + error, + ConsensusError::StateError(StateError::DocumentSumOverflowError(_)), + "{what}" + ); + assert_eq!(error.code(), 40154, "{what}"); + assert_eq!( + outcome + .nonce_after + .map(|nonce| nonce & IDENTITY_NONCE_VALUE_FILTER), + Some(outcome.transition_nonce), + "{what}: the nonce is bumped to the transition's" + ); + assert_eq!( + outcome.charged(), + actual_fees.total_base_fee(), + "{what}: the writer pays the fee the result reports" + ); + assert_eq!( + outcome.charged(), + expected_charge, + "{what}: the nonce bump, the validation and the refused write's processing" + ); + assert_eq!( + &fixture.stored(document_type), + stored_before, + "{what}: the documents are as they were" + ); + } + + /// A create, then a replace, of a document whose amount takes the writer's or the type's + /// sum past `i64::MAX`, charged `create_charge` and `replace_charge`. + async fn create_and_replace_past_the_sum( + document_type: &str, + create_charge: Credits, + replace_charge: Credits, + ) { + let mut fixture = SumFixture::latest(); + let (outcome, _) = fixture.create(0, document_type, i64::MAX).await; + SumFixture::expect_success(&outcome, "the create of i64::MAX"); + + let stored_before = fixture.stored(document_type); + let (outcome, _) = fixture.create(0, document_type, 1).await; + expect_paid_overflow( + &fixture, + &format!("{document_type}: create of 1"), + &outcome, + document_type, + &stored_before, + create_charge, + ); + + let (outcome, zero) = fixture.create(0, document_type, 0).await; + SumFixture::expect_success(&outcome, "the create of 0"); + let stored_before = fixture.stored(document_type); + let (outcome, _) = fixture.replace(0, document_type, &zero, 1).await; + expect_paid_overflow( + &fixture, + &format!("{document_type}: replace of 0 by 1"), + &outcome, + document_type, + &stored_before, + replace_charge, + ); + + // The writer's next write within the sum still goes through. + let (outcome, _) = fixture.replace(0, document_type, &zero, -5).await; + SumFixture::expect_success(&outcome, "the replace of 0 by -5"); + } + + /// A transfer of a document of 1 to an owner whose sum is `i64::MAX`, the sender's sum + /// being 0 (it also owns a document of -1), charged `charge`. + async fn transfer_past_the_owner_sum(document_type: &str, charge: Credits) { + let mut fixture = SumFixture::latest(); + let (outcome, _) = fixture.create(0, document_type, i64::MAX).await; + SumFixture::expect_success(&outcome, "the create of i64::MAX"); + let (outcome, _) = fixture.create(1, document_type, -1).await; + SumFixture::expect_success(&outcome, "the create of -1"); + let (outcome, one) = fixture.create(1, document_type, 1).await; + SumFixture::expect_success(&outcome, "the create of 1"); + + let stored_before = fixture.stored(document_type); + let outcome = fixture.transfer(1, document_type, &one, 0).await; + expect_paid_overflow( + &fixture, + &format!("{document_type}: transfer of 1"), + &outcome, + document_type, + &stored_before, + charge, + ); + } + + #[tokio::test] + async fn should_refuse_a_create_or_replace_past_a_per_value_sum_as_a_paid_error() { + create_and_replace_past_the_sum(PER_VALUE, 16_362_120, 16_349_700).await; + } + + #[tokio::test] + async fn should_refuse_a_create_or_replace_past_a_range_sum_as_a_paid_error() { + create_and_replace_past_the_sum(RANGED, 16_593_960, 16_581_540).await; + } + + /// Each owner's sum fits, but the range sum over both owners would not: the write is + /// refused for the range sum alone. The same writes on a type summed per owner only go + /// through. + #[tokio::test] + async fn should_refuse_a_create_past_a_range_sum_that_no_owner_sum_exceeds() { + let mut fixture = SumFixture::latest(); + for document_type in [PER_VALUE, RANGED] { + let (outcome, _) = fixture.create(0, document_type, i64::MAX).await; + SumFixture::expect_success(&outcome, "the create of i64::MAX by writer 0"); + } + let (outcome, _) = fixture.create(1, PER_VALUE, 1).await; + SumFixture::expect_success(&outcome, "the create of 1 by writer 1 summed per owner"); + + let stored_before = fixture.stored(RANGED); + let (outcome, _) = fixture.create(1, RANGED, 1).await; + expect_paid_overflow( + &fixture, + "ranged: create of 1 by writer 1", + &outcome, + RANGED, + &stored_before, + 16_647_800, + ); + } + + #[tokio::test] + async fn should_refuse_a_create_or_replace_past_a_document_type_sum_as_a_paid_error() { + create_and_replace_past_the_sum(TYPED, 10_393_080, 10_380_520).await; + } + + #[tokio::test] + async fn should_refuse_a_transfer_past_a_per_value_sum_as_a_paid_error() { + transfer_past_the_owner_sum(PER_VALUE, 16_404_900).await; + } + + #[tokio::test] + async fn should_refuse_a_transfer_past_a_range_sum_as_a_paid_error() { + transfer_past_the_owner_sum(RANGED, 16_630_420).await; + } + + /// The proposer, which takes a savepoint per transition, refuses the write the same way. + #[tokio::test] + async fn should_refuse_a_create_past_a_sum_as_a_paid_error_when_proposing() { + let mut fixture = SumFixture::latest(); + fixture.proposing = true; + let (outcome, _) = fixture.create(0, PER_VALUE, i64::MAX).await; + SumFixture::expect_success(&outcome, "the create of i64::MAX"); + + let stored_before = fixture.stored(PER_VALUE); + let (outcome, _) = fixture.create(0, PER_VALUE, 1).await; + expect_paid_overflow( + &fixture, + "proposing: create of 1", + &outcome, + PER_VALUE, + &stored_before, + 16_362_120, + ); + let (outcome, _) = fixture.create(0, PER_VALUE, -1).await; + SumFixture::expect_success(&outcome, "the create of -1"); + } + + /// Protocol version 14 is unchanged: the write ends as an internal error, which neither + /// bumps the nonce nor charges a fee. + #[tokio::test] + async fn should_leave_a_create_past_a_sum_an_internal_error_at_protocol_version_14() { + let mut fixture = SumFixture::new(14); + let (outcome, _) = fixture.create(0, PER_VALUE, i64::MAX).await; + SumFixture::expect_success(&outcome, "the create of i64::MAX"); + + let stored_before = fixture.stored(PER_VALUE); + let (outcome, _) = fixture.create(0, PER_VALUE, 1).await; + report("protocol version 14: create of 1", &outcome); + assert!(outcome.check_tx_valid); + assert_matches!( + outcome.result, + StateTransitionExecutionResult::InternalError(_) + ); + assert_eq!(outcome.nonce_after, outcome.nonce_before); + assert_eq!(outcome.charged(), 0); + assert_eq!(fixture.stored(PER_VALUE), stored_before); + } + + /// The genesis height takes no savepoint (its re-proposals rewind to the one `init_chain` + /// set), so a write past a sum there stays an internal error. + #[tokio::test] + async fn should_leave_a_create_past_a_sum_an_internal_error_at_the_genesis_height() { + let mut fixture = SumFixture::latest(); + fixture.block_info.height = fixture.platform.config.abci.genesis_height; + let (outcome, _) = fixture.create(0, PER_VALUE, i64::MAX).await; + SumFixture::expect_success(&outcome, "the create of i64::MAX"); + + let (outcome, _) = fixture.create(0, PER_VALUE, 1).await; + assert_matches!( + outcome.result, + StateTransitionExecutionResult::InternalError(_) + ); + assert_eq!(outcome.nonce_after, outcome.nonce_before); + assert_eq!(outcome.charged(), 0); + } + + /// A write within the sums costs what it did before: the same writes at the genesis height, + /// where no refusal is prepared, and at another height are charged the same fees. + #[tokio::test] + async fn should_charge_a_write_within_the_sums_what_it_cost_before() { + async fn fees(at_genesis: bool) -> Vec { + let mut fixture = SumFixture::latest(); + if at_genesis { + fixture.block_info.height = fixture.platform.config.abci.genesis_height; + } + let mut fees = vec![]; + for document_type in [PER_VALUE, RANGED, TYPED] { + let (outcome, document) = fixture.create(0, document_type, 40).await; + fees.push(fee_of(&outcome)); + let (outcome, document) = fixture.replace(0, document_type, &document, -7).await; + fees.push(fee_of(&outcome)); + let outcome = fixture.transfer(0, document_type, &document, 1).await; + fees.push(fee_of(&outcome)); + } + fees + } + fn fee_of(outcome: &Outcome) -> FeeResult { + let StateTransitionExecutionResult::SuccessfulExecution { fee_result, .. } = + &outcome.result + else { + panic!("expected the write to succeed, got {:?}", outcome.result); + }; + fee_result.clone() + } + assert_eq!(fees(false).await, fees(true).await); + } +} diff --git a/packages/rs-drive/src/error/mod.rs b/packages/rs-drive/src/error/mod.rs index 0857e2639c3..0962024b2f2 100644 --- a/packages/rs-drive/src/error/mod.rs +++ b/packages/rs-drive/src/error/mod.rs @@ -76,6 +76,25 @@ pub enum Error { IOErrorWithInfoString(Box, String), } +impl Error { + /// Whether GroveDB refused to apply operations because an aggregate a sum (or count) tree + /// keeps would leave its integer's range: a merk node's value plus its children's + /// aggregates past `i64::MAX` (or below `i64::MIN`). Merk raises this as its `Overflow` + /// error when it computes the aggregates of the tree it commits. Merk's other `Overflow` + /// errors come from cost estimation and from merging the limits of an aggregate sum query, + /// neither of which applies a write. + pub fn is_sum_tree_overflow(&self) -> bool { + matches!( + self, + Self::GroveDB(error) + if matches!( + error.as_ref(), + grovedb::Error::MerkError(grovedb_merk::error::Error::Overflow(_)) + ) + ) + } +} + impl From for Error { fn from(value: ProtocolDataContractError) -> Self { Self::Protocol(Box::new(ProtocolError::DataContractError(value))) diff --git a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v11.rs b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v11.rs index 8df09f6713c..7ba61a6a574 100644 --- a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v11.rs +++ b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_method_versions/v11.rs @@ -175,7 +175,7 @@ pub const DRIVE_ABCI_METHOD_VERSIONS_V11: DriveAbciMethodVersions = DriveAbciMet ..DRIVE_ABCI_METHOD_VERSIONS_V10.withdrawals }, state_transition_processing: DriveAbciStateTransitionProcessingMethodVersions { - execute_event: 2, // changed in v15: a paying gas sponsor owns the storage its batch writes + execute_event: 2, // changed in v15: a paying gas sponsor owns the storage its batch writes, and a document write past a sum is refused as a paid error ..DRIVE_ABCI_METHOD_VERSIONS_V10.state_transition_processing }, ..DRIVE_ABCI_METHOD_VERSIONS_V10 diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index 2f606199f3a..494c7a1e17d 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -934,12 +934,25 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// defaults (1 s and 5 s). Only Tenderdash 2.0 and later follows such a chain. The /// emergency updates of consensus parameter update 2 force at least version 1 instead of /// exactly 1, so they never undo this. Protocol v14 and earlier keep version 1. +/// +/// 45. **A document write past a sum is a paid error**: a document create, replace or +/// transfer is held to no sum before it is written, and GroveDB refuses a write that +/// would take a sum tree's aggregate (a `summable`, `rangeSummable` or +/// `documentsSummable` sum) past `i64::MAX`, as merk computes it at each node. With +/// signed values no check on a total is exact, so the write is attempted. +/// `execute_event` 2 (`DRIVE_ABCI_METHOD_VERSIONS_V11`) rolls back what the attempt +/// wrote and refuses it as a paid `DocumentSumOverflowError` (40154, new): the identity +/// contract nonce is bumped, and the signer pays the bump, the validation work and the +/// processing of the refused write as fee validation estimates it, with no storage fee. +/// It is an internal error, which the block carries neither paid nor with its nonce +/// bumped, at the genesis height, which takes no savepoint, and at protocol v14 and +/// earlier, which keep `execute_event` 1 or 0. pub const PLATFORM_V15: PlatformVersion = PlatformVersion { protocol_version: PROTOCOL_VERSION_15, drive: DRIVE_VERSION_V10, // changed: calculate_fee 1 prices a refund at the storing epoch's rate (note 27); apply_contract_with_serialization 1 writes nothing for a contract whose format version 1 bytes match the stored one's (note 8); vote method versions v4: register_identity_vote 1 registers a yes/no vote, remove_all_votes_given_by_identities 1 also removes the yes/no votes of a masternode that left the list, every yes_no method and remove_vote_poll_end_date_query_operations Some(0) make yes/no polls active, add_vote_poll_end_date_query_operations 1 adds only the entry when the batch already queues the end date's tree with other storage flags, and verify methods v4 make the yes/no proof verifiers active (note 10) and verify_private_document_entries Some(0) a page of a private type's store (note 13); state transition method versions v5: document_create_transition 1 deletes a consumed document from what its lookup read (note 11); document method versions v5: insert_empty_private_document_store_operation Some(0) creates a private document type's store, and fetch_private_document_entries and prove_private_document_entries Some(0) read and prove a page of it (note 13); apply_drive_operations 2 resolves a batch's estimate, remove_reference_for_index_level_for_contract_operations 2, add_reference_for_index_level_for_contract_operations 1, stateless_delete_of_non_tree_for_costs 1 and for_total_system_credits_update 1 describe their layers as they are (note 14); fetch_core_fork_activation_height and store_core_fork_activation_height Some(0) keep the Core fork activations (note 18); document method versions v5: append_private_document_entries_operations Some(0) appends a private document create's entries (note 25); grove_version GROVE_V5 (note 26); verify methods v4: verify_proof_keep_serialized 1 verifies a document that may be contested (note 29); document method versions v5: single_document_path_query 1 selects the latest retained revision at or before a block time, and verify_proof_keep_serialized 1 verifies it (note 31); retained-history writers, readers, estimates and verifiers select the per-type revision layout (note 35); add_new_keys_to_masternode_identity 1 adds a masternode key whose hash the identity already holds a reference for (note 32); document method versions v5: insert.add_document_for_contract_operations 2, delete.delete_document_for_contract_operations 1, delete.remove_document_from_primary_storage 1 and its estimate 1, query.fetch_document_lifecycle Some(0), and the erase/lifecycle estimate and erase_refund_recipient_cost selectors Some(0); batch_operations.convert_drive_operations_to_grove_operations 2; state transition method versions v5: document_delete_transition 1 and document_erase_transition Some(0); verify methods v4: single_document.verify_proof 1 extend retained history (note 41); document method versions v5: add_indices_for_top_index_level_for_contract_operations 3 writes no entry in an expired time range bucket (note 36) drive_abci: DriveAbciVersion { structs: DRIVE_ABCI_STRUCTURE_VERSIONS_V2, - methods: DRIVE_ABCI_METHOD_VERSIONS_V11, // changed: perform_events_on_first_block_of_protocol_change 3 migrates retained history after operator-payout reconciliation and other activation work (note 35); the yes/no poll's tally, record, clean-up and finish hook are Some(0) (note 10); verify_chain_lock_locally 1 rejects a chain lock locally only when Platform holds the quorums active at its signing height, and verify_chain_lock_through_core 1 has Core's verifychainlock check the others before submitchainlock; consensus_params_update 2 installs the full evidence policy (note 16) and never lowers the Tenderdash consensus version on an emergency update (note 44); update_core_info 1 records the chain locked height at which Core's V24 is first seen active (note 18); build_untied_withdrawal_transactions_from_documents 1 emits asset unlock payload version 2 once V24 is recorded as active (note 20); update_voter_identity 1 re-enables the voter key of the address a masternode returns to (note 22); update_masternode_list 2 and update_operator_identity 1 make operator payouts and the operator identities' TRANSFER keys follow Core's diffs (note 32) + methods: DRIVE_ABCI_METHOD_VERSIONS_V11, // changed: perform_events_on_first_block_of_protocol_change 3 migrates retained history after operator-payout reconciliation and other activation work (note 35); the yes/no poll's tally, record, clean-up and finish hook are Some(0) (note 10); verify_chain_lock_locally 1 rejects a chain lock locally only when Platform holds the quorums active at its signing height, and verify_chain_lock_through_core 1 has Core's verifychainlock check the others before submitchainlock; consensus_params_update 2 installs the full evidence policy (note 16) and never lowers the Tenderdash consensus version on an emergency update (note 44); update_core_info 1 records the chain locked height at which Core's V24 is first seen active (note 18); build_untied_withdrawal_transactions_from_documents 1 emits asset unlock payload version 2 once V24 is recorded as active (note 20); update_voter_identity 1 re-enables the voter key of the address a masternode returns to (note 22); update_masternode_list 2 and update_operator_identity 1 make operator payouts and the operator identities' TRANSFER keys follow Core's diffs (note 32); execute_event 2 refuses a document write past a sum as a paid error (note 45) validation_and_processing: DRIVE_ABCI_VALIDATION_VERSIONS_V11, // changed: identity update advanced_structure 1 refuses unpaid an identity update whose added key's proof of possession does not verify (note 2); create_domain_data_trigger 2 (note 3); contract update transform_into_action 1 holds an update to the compiled size cap in check_tx (note 8); batch advanced_structure 2 refuses a token config update on a read-only contract (note 9); masternode vote transform_into_action 1 looks up a masternode's previous answer on a yes/no poll (note 10); document_reference_validation 1 keeps what a consumed commitment's lookup read (note 11); document create structure_validation 2 holds a decision proposal to its fund, rule and end date (note 12); data trigger bindings 3 drop the DashPay bindings (note 24); document create state_validation 3 keeps a create outside a contest off the values of a live one its index values do not decide (note 19); identity create basic_structure 1 checks the identity id before the asset lock proof and advanced_structure 2 no longer does (note 23); contract user moderation transform_into_action 1 writes a moderator's field change in the name of whoever holds the document's storage (note 28); validate_state_transition_identity_signed 2 refuses a contract create or update signed by a key with a budget or an expiry (note 34); batch_state_transition.document_delete_transition_structure_validation 2 and document_erase_transition_structure_validation/document_erase_transition_state_validation Some(0) admit the lifecycle (note 41) withdrawal_constants: DRIVE_ABCI_WITHDRAWAL_CONSTANTS_V3, query: DRIVE_ABCI_QUERY_VERSIONS_V3, // changed: getDocumentHistory accepts V1 only diff --git a/packages/wasm-dpp/src/errors/consensus/consensus_error.rs b/packages/wasm-dpp/src/errors/consensus/consensus_error.rs index ff2ef1c3839..974cfba61b9 100644 --- a/packages/wasm-dpp/src/errors/consensus/consensus_error.rs +++ b/packages/wasm-dpp/src/errors/consensus/consensus_error.rs @@ -86,6 +86,7 @@ use dpp::consensus::state::document::referenced_document_type_index_only_error:: use dpp::consensus::state::document::referenced_document_type_private_error::ReferencedDocumentTypePrivateError; use dpp::consensus::state::document::referenced_document_type_requirement_not_met_error::ReferencedDocumentTypeRequirementNotMetError; use dpp::consensus::state::document::document_type_not_private_error::DocumentTypeNotPrivateError; +use dpp::consensus::state::document::document_sum_overflow_error::DocumentSumOverflowError; use dpp::consensus::state::document::private_document_entry_size_mismatch_error::PrivateDocumentEntrySizeMismatchError; use dpp::consensus::basic::document::{ DuplicatePrivateDocumentEntryError, InvalidPrivateDocumentEntryCountError, @@ -840,6 +841,9 @@ pub fn from_state_error(state_error: &StateError) -> JsValue { StateError::ReferencedDocumentTypeRequirementNotMetError(e) => { generic_consensus_error!(ReferencedDocumentTypeRequirementNotMetError, e).into() } + StateError::DocumentSumOverflowError(e) => { + generic_consensus_error!(DocumentSumOverflowError, e).into() + } } }