diff --git a/CHANGELOG.md b/CHANGELOG.md index 348c4c85324..a006ab16577 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,23 @@ ### Changed +- **dpp, drive (Rust API):** `DataContractUpdateTransition` gains version 1, the delta form, + which carries only what an update changes (protocol v15 note 33). An exhaustive match on + the transition or on `DataContractUpdateTransitionAction` needs a `V1` arm. + `DataContractUpdateTransitionAccessorsV0::data_contract()` returns + `Option<&DataContractInSerializationFormat>`, `None` for a delta, which embeds no contract, + and `set_data_contract` returns a `Result`; `data_contract_id()` is new and reads either + version. `new_from_data_contract`, which has only the new contract, always builds version + 0; the new `new_from_contract_update(old_contract, new_contract, ...)` and + `from_contract_update` build the version the platform version defaults to, a delta from + protocol version 15. A delta's execution proof is verified against the contract as it was + before the update, and fails with `ProofError::MissingContextRequirement` without it: the + Rust SDK's new `wait_for_data_contract_update(sdk, &transition, &pre_update_contract, + settings)` takes that contract with the wait, where the context provider, which keeps + only the latest version of a contract, may no longer hold it. New consensus errors: 10283, + 10284, 40010, 40011; the three that name a delta's entry (10283, 40010, 40011) carry at + most 256 bytes of its name. + - **drive, dpp (Rust API):** `Drive::calculate_fee` is now a method and no longer takes `epochs_per_era` or `previous_fee_versions`: `drive.calculate_fee(base_operations, drive_operations, &epoch, platform_version)`. diff --git a/book/src/data-model/data-contracts.md b/book/src/data-model/data-contracts.md index 71647d66de5..fc5e703fd71 100644 --- a/book/src/data-model/data-contracts.md +++ b/book/src/data-model/data-contracts.md @@ -215,6 +215,38 @@ This intermediate format is important because serialization versions and code st There is also `versioned_limit_deserialize`, which imposes a size limit and always performs full validation -- this is used for data coming from untrusted sources (anything not from Drive's own storage). +## Updating a Contract: the Whole Contract or a Delta + +A `DataContractUpdateTransition` has two versions, and a contract owner may send either. + +**Version 0 carries the whole contract.** The node compares it with the stored contract and stores it. Because a state transition is capped at `max_state_transition_size` (20,480 bytes), well below the `max_serialized_size` a contract may take (65,000 bytes), an update of this form cannot grow a contract past what one transition carries. It also pays the registration cost of the whole contract again, whatever it changes. + +**Version 1 carries a delta** (`DataContractUpdateTransitionV1`, from protocol version 15, where it is the form built by default). It names the contract, its owner and the version it produces, and carries only what changes: + +| Field | Meaning | +|-------|---------| +| `new_document_schemas`, `updated_document_schemas` | Document types to add, and new schemas for existing ones | +| `new_schema_defs`, `updated_schema_defs` | `$defs` definitions to add, and new schemas for existing ones | +| `new_groups`, `new_tokens` | Groups and tokens to add, at the positions after the stored ones | +| `add_keywords`, `remove_keywords` | Keywords to add after the stored ones that stay, and keywords to remove | +| `description` | `Keep`, `Clear` or `Set(text)` | +| `config` | A replacement config, or none to keep the stored one | + +A delta has no way to remove a document type, a definition, a group or a token, or to change a group or a token, as no contract update may. + +The node reads the stored contract, merges the delta onto it (`DataContract::apply_update`), and validates the update carrying the whole merged contract with the code that validates version 0. A delta is therefore held to every rule of a version 0 update, and the two cannot drift apart. What only a delta can get wrong is refused with its own errors: an entry named in two sections that cannot both apply (`DataContractUpdateOverlappingEntriesError`, 10283, without a fee), an entry to add that the contract already has (`DataContractUpdateEntryAlreadyExistsError`, 40010), and an entry to replace or remove that it does not have (`DataContractUpdateEntryNotFoundError`, 40011). + +Two things differ from version 0: + +- **Fee.** A delta pays the registration cost of what it registers alone: its new and replaced document types with their indexes, its new tokens and its added keywords. It pays the processing of validating the whole merged contract as version 0 does. +- **Size.** A delta grows a contract a transition at a time, up to `max_serialized_size`. A contract that would take more is refused with `DataContractMaxSizeExceededError` (10284). + +Build either form with `DataContractUpdateTransition::new_from_contract_update(old_contract, new_contract, ...)`, which computes the delta between the stored contract and the wanted one and refuses a change a delta cannot express. `new_from_data_contract`, which has only the new contract, always builds version 0. + +**Verifying a delta's execution proof needs the contract it was built on.** The proof of a contract update holds the contract as it is after the update. Version 0 is compared with it directly. A delta is first merged, by the same `apply_update`, onto the contract as it was before the update, which the verifier takes from its contract lookup; the proved contract must be the result, and a lookup that does not hold that version fails with `ProofError::MissingContextRequirement`. + +In the Rust SDK, wait for a delta with `wait_for_data_contract_update(sdk, &transition, &pre_update_contract, settings)`. It makes the pre-update contract known for that one verification and leaves the SDK's context provider as it is. Registering the pre-update contract with the context provider instead is not reliable: a provider keeps the latest version of each contract, so once the update is committed, any other operation may give it the updated contract before the proof is verified, and an update that executed is then reported as failed. + ## Evolving a Contract: Adding Required Fields Contract updates are deliberately conservative: existing documents must stay valid and their stored bytes must stay readable, so most schema changes that would break either are rejected. Historically that froze the `required` set of a document type in both directions — requiredness is baked into the document wire format (required properties serialize raw, optional ones carry a presence flag), so changing it would desynchronize every stored document's bytes from the schema used to read them. diff --git a/book/src/error-handling/error-codes.md b/book/src/error-handling/error-codes.md index 0544e632bce..31ccfc17c92 100644 --- a/book/src/error-handling/error-codes.md +++ b/book/src/error-handling/error-codes.md @@ -50,7 +50,7 @@ Error codes are organized into ranges that correspond to error categories and su |-------|----------|----------| | 10000-10099 | Versioning | `UnsupportedVersionError` (10000), `ProtocolVersionParsingError` (10001), `IncompatibleProtocolVersionError` (10004) | | 10100-10199 | Structure | `JsonSchemaCompilationError` (10100), `InvalidIdentifierError` (10102), `ValueError` (10103) | -| 10200-10277 | Data Contract | `DataContractMaxDepthExceedError` (10200), `DuplicateIndexError` (10201), `InvalidDataContractIdError` (10204), `DataContractInvalidRequiredFieldsUpdateError` (10276), `PreProgrammedDistributionAmountOverLimitError` (10277) | +| 10200-10284 | Data Contract | `DataContractMaxDepthExceedError` (10200), `DuplicateIndexError` (10201), `InvalidDataContractIdError` (10204), `DataContractInvalidRequiredFieldsUpdateError` (10276), `PreProgrammedDistributionAmountOverLimitError` (10277), `DataContractCompiledMaxSizeExceededError` (10282), `DataContractUpdateOverlappingEntriesError` (10283), `DataContractMaxSizeExceededError` (10284) | | 10350-10359 | Groups | `GroupPositionDoesNotExistError` (10350), `GroupExceedsMaxMembersError` (10354) | | 10360-10367 | Contract Groups | `ContractGroupMembershipsOverLimitError` (10360), `InvalidContractGroupAdminsError` (10364), `InvalidContractGroupDescriptionLengthError` (10367); 10365 unassigned | | 10400-10425 | Documents | `DataContractNotPresentError` (10400), `DuplicateDocumentTransitionsWithIdsError` (10401), `DocumentPropertyNotDistinctError` (10419), `InvalidEncryptedPropertyShapeError` (10420), `DocumentPropertyMaxBytesExceededError` (10421), `DocumentPropertyConstraintViolatedError` (10422), `DocumentReferencePreimageInvalidError` (10423), `DocumentPropertyNotGeneratedError` (10424), `DocumentTypePrivateError` (10425) | @@ -107,7 +107,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) | +| 40000-40011 | Data Contract | `DataContractAlreadyPresentError` (40000), `DataContractIsReadonlyError` (40001), `DataContractNotFoundError` (40008), `DataContractUpdateEntryAlreadyExistsError` (40010), `DataContractUpdateEntryNotFoundError` (40011), which carry at most 256 bytes of the entry's name, as `DataContractUpdateOverlappingEntriesError` (10283) does | | 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) | | 40200-40217 | Identity | `IdentityAlreadyExistsError` (40200), `InvalidIdentityRevisionError` (40203), `IdentityInsufficientBalanceError` (40210) | | 40300-40308 | Voting | `MasternodeNotFoundError` (40300), `MasternodeVoteAlreadyPresentError` (40304), `VoteChoiceNotAllowedForVotePollError` (40307), `YesNoVotePollNotAvailableForVotingError` (40308) | diff --git a/book/src/state-transitions/transform-into-action.md b/book/src/state-transitions/transform-into-action.md index 3fe2973b2c2..7bac875f081 100644 --- a/book/src/state-transitions/transform-into-action.md +++ b/book/src/state-transitions/transform-into-action.md @@ -208,7 +208,11 @@ depends on `ValidationMode` -- `CheckTx` mode skips full schema validation for s **DataContractUpdate:** Fetches the existing contract from Drive to compare against the proposed update. Validates that schema changes are backward-compatible (e.g., you -can add fields but not remove required ones). +can add fields but not remove required ones). A delta update (version 1 of the +transition, from protocol version 15) carries only what changes: it is first merged onto +the existing contract, and the update carrying the whole merged contract is validated in +its place, so both forms run the same checks. See +[Updating a Contract](../data-model/data-contracts.md#updating-a-contract-the-whole-contract-or-a-delta). **Batch (Documents):** This is the most complex transformation. For each document sub-transition in the batch, the platform must: diff --git a/book/src/versioning/platform-version.md b/book/src/versioning/platform-version.md index 32e7db207f5..9afb9eccf70 100644 --- a/book/src/versioning/platform-version.md +++ b/book/src/versioning/platform-version.md @@ -59,19 +59,19 @@ function version so that execution is deterministic. ## The Version Array Each protocol version gets its own constant, defined in a separate file. At -the time of writing, the platform has fourteen versions: +the time of writing, the platform has fifteen versions: ```rust // packages/rs-platform-version/src/version/mod.rs pub type ProtocolVersion = u32; -pub const LATEST_VERSION: ProtocolVersion = PROTOCOL_VERSION_14; +pub const LATEST_VERSION: ProtocolVersion = PROTOCOL_VERSION_15; pub const INITIAL_PROTOCOL_VERSION: ProtocolVersion = 1; pub const ALL_VERSIONS: RangeInclusive = 1..=LATEST_VERSION; ``` -These fourteen snapshots are collected into a single static array in +These fifteen snapshots are collected into a single static array in `protocol_version.rs`: ```rust @@ -90,22 +90,23 @@ pub const PLATFORM_VERSIONS: &[PlatformVersion] = &[ PLATFORM_V12, PLATFORM_V13, PLATFORM_V14, + PLATFORM_V15, ]; -pub const LATEST_PLATFORM_VERSION: &PlatformVersion = &PLATFORM_V14; +pub const LATEST_PLATFORM_VERSION: &PlatformVersion = &PLATFORM_V15; pub const DESIRED_PLATFORM_VERSION: &PlatformVersion = LATEST_PLATFORM_VERSION; ``` The array is indexed by protocol version number minus one (since versions are -1-indexed). `PLATFORM_V1` sits at index 0, `PLATFORM_V14` at index 13. This +1-indexed). `PLATFORM_V1` sits at index 0, `PLATFORM_V15` at index 14. This simple layout is what makes the `get` function so fast. -One file, one protocol version. `v14.rs` was created when the first consensus -change after version 13 shipped needed somewhere to live, and every later -change destined for version 14 amends that same file. The day version 14 is +One file, one protocol version. `v15.rs` was created when the first consensus +change after version 14 shipped needed somewhere to live, and every later +change destined for version 15 amends that same file. The day version 15 is released the file freezes: from then on it is part of the chain's historical -record, and the next consensus change creates `v15.rs`. There is never a -`v14.rs` that means one thing on a node built last month and another on a node +record, and the next consensus change creates `v16.rs`. There is never a +`v15.rs` that means one thing on a node built last month and another on a node built today. ## What a Version Snapshot Looks Like @@ -153,7 +154,7 @@ pub const PLATFORM_V1: PlatformVersion = PlatformVersion { }; ``` -Now compare with `PLATFORM_V14`, the latest at the time of writing. By +Now compare with `PLATFORM_V14`, a snapshot that bumped many slots at once. By convention, each sub-constant slot that was bumped carries a trailing `// changed:` comment saying what changed. The `protocol_version` field is the snapshot's identity and is never annotated. One bumped slot in this snapshot, @@ -278,8 +279,8 @@ impl PlatformVersion { } ``` -This is a simple array lookup. Protocol version 1 maps to index 0, version 14 -to index 13. If the version number is out of range, you get a clear error. No +This is a simple array lookup. Protocol version 1 maps to index 0, version 15 +to index 14. If the version number is out of range, you get a clear error. No hash maps, no runtime registration, no dynamic dispatch -- just a static array of compile-time constants. @@ -425,7 +426,7 @@ version 14 means. every node that was there at the time. - Never add a new field to `PlatformVersion` without also updating every `PLATFORM_V*` constant. The compiler will enforce this, but be aware that - the fix is updating fourteen files, not one. + the fix is updating fifteen files, not one. - Never use `PlatformVersion::latest()` in consensus-critical code paths. Always use the version from the current platform state, obtained via `platform_state.current_platform_version()`. The "latest" version is what diff --git a/book/src/versioning/versioned-dispatch.md b/book/src/versioning/versioned-dispatch.md index 906281d2545..e28d63f414c 100644 --- a/book/src/versioning/versioned-dispatch.md +++ b/book/src/versioning/versioned-dispatch.md @@ -529,7 +529,7 @@ meaningfully. This is a lot of steps, but each one is mechanical and the compiler guides you through most of it. If you add a field to a version struct and forget to set it -in one of the fourteen platform version constants, the build fails. +in one of the fifteen platform version constants, the build fails. ## Passing Version References diff --git a/packages/rs-dpp/src/data_contract/methods/apply_update/mod.rs b/packages/rs-dpp/src/data_contract/methods/apply_update/mod.rs new file mode 100644 index 00000000000..3b83d6a298d --- /dev/null +++ b/packages/rs-dpp/src/data_contract/methods/apply_update/mod.rs @@ -0,0 +1,49 @@ +mod v0; + +use crate::data_contract::serialized_version::DataContractInSerializationFormat; +use crate::data_contract::update_values::DataContractUpdateValues; +use crate::data_contract::DataContract; +use crate::validation::ConsensusValidationResult; +use crate::ProtocolError; +use platform_version::version::feature_initial_protocol_versions::DATA_CONTRACT_UPDATE_V1_INITIAL_PROTOCOL_VERSION; +use platform_version::version::PlatformVersion; + +impl DataContract { + /// Merges a delta contract update onto this contract, the stored one, and returns the + /// contract the update asks for, in the format state transitions carry. + /// + /// This is the one definition of what a delta means. Block execution runs it on the + /// contract it reads from state and then holds the result to every rule of an update that + /// carries the whole contract; the verification of a delta's execution proof runs it on + /// the contract the client held before the update and compares the result with the proved + /// contract. Both dispatch on `contract_versions.methods.apply_update`, so they always + /// merge alike. + /// + /// Only what the shape of a delta makes checkable is checked here: the submitter owns the + /// contract, an entry to replace or remove exists, and an entry to add does not. The + /// merged contract keeps this contract's time fields; the caller stamps the update's. + /// + /// # Returns + /// - The merged contract, or the consensus error that says why the delta does not fit this + /// contract. + /// - `Err(ProtocolError)` when `platform_version` predates delta contract updates (the + /// slot is `None`) or selects a generation this build does not know. + pub fn apply_update( + &self, + update_values: DataContractUpdateValues<'_>, + platform_version: &PlatformVersion, + ) -> Result, ProtocolError> { + match platform_version.dpp.contract_versions.methods.apply_update { + None => Err(ProtocolError::UnknownVersionError(format!( + "DataContract::apply_update is not active at protocol version {}, delta contract updates activate with protocol version {}", + platform_version.protocol_version, DATA_CONTRACT_UPDATE_V1_INITIAL_PROTOCOL_VERSION + ))), + Some(0) => Ok(self.apply_update_v0(update_values)), + Some(version) => Err(ProtocolError::UnknownVersionMismatch { + method: "DataContract::apply_update".to_string(), + known_versions: vec![0], + received: version, + }), + } + } +} diff --git a/packages/rs-dpp/src/data_contract/methods/apply_update/v0/mod.rs b/packages/rs-dpp/src/data_contract/methods/apply_update/v0/mod.rs new file mode 100644 index 00000000000..60a58b087c8 --- /dev/null +++ b/packages/rs-dpp/src/data_contract/methods/apply_update/v0/mod.rs @@ -0,0 +1,149 @@ +use crate::consensus::basic::data_contract::DataContractUpdateEntryKind; +use crate::consensus::state::data_contract::data_contract_update_entry_already_exists_error::DataContractUpdateEntryAlreadyExistsError; +use crate::consensus::state::data_contract::data_contract_update_entry_not_found_error::DataContractUpdateEntryNotFoundError; +use crate::consensus::state::data_contract::data_contract_update_permission_error::DataContractUpdatePermissionError; +use crate::consensus::ConsensusError; +use crate::data_contract::accessors::v0::DataContractV0Getters; +use crate::data_contract::accessors::v1::DataContractV1Getters; +use crate::data_contract::schema::DataContractSchemaMethodsV0; +use crate::data_contract::serialized_version::v1::DataContractInSerializationFormatV1; +use crate::data_contract::serialized_version::DataContractInSerializationFormat; +use crate::data_contract::update_values::{DataContractUpdateValues, DescriptionUpdate}; +use crate::data_contract::{DataContract, DocumentName}; +use crate::validation::ConsensusValidationResult; +use platform_value::Value; +use std::collections::BTreeMap; + +impl DataContract { + /// Generation 0 of the merge, which builds the contract in format version 1, the format + /// state transitions carry at the protocol versions that select it. + #[inline(always)] + pub(super) fn apply_update_v0( + &self, + update_values: DataContractUpdateValues<'_>, + ) -> ConsensusValidationResult { + match self.merge_update_v0(update_values) { + Ok(merged) => ConsensusValidationResult::new_with_data(merged.into()), + Err(error) => ConsensusValidationResult::new_with_error(error), + } + } + + fn merge_update_v0( + &self, + update_values: DataContractUpdateValues<'_>, + ) -> Result { + let contract_id = self.id(); + + // A delta names its owner, as it embeds no contract to read one from + if update_values.owner_id != self.owner_id() { + return Err(DataContractUpdatePermissionError::new( + contract_id, + update_values.owner_id, + ) + .into()); + } + + let not_found = |kind: DataContractUpdateEntryKind, name: String| { + Err(DataContractUpdateEntryNotFoundError::new(contract_id, kind, name).into()) + }; + let already_exists = |kind: DataContractUpdateEntryKind, name: String| { + Err(DataContractUpdateEntryAlreadyExistsError::new(contract_id, kind, name).into()) + }; + + let mut document_schemas: BTreeMap = self + .document_schemas() + .into_iter() + .map(|(name, schema)| (name, schema.clone())) + .collect(); + for (name, schema) in update_values.updated_document_schemas { + match document_schemas.get_mut(name) { + Some(existing) => *existing = schema.clone(), + None => return not_found(DataContractUpdateEntryKind::DocumentType, name.clone()), + } + } + for (name, schema) in update_values.new_document_schemas { + if document_schemas + .insert(name.clone(), schema.clone()) + .is_some() + { + return already_exists(DataContractUpdateEntryKind::DocumentType, name.clone()); + } + } + + let mut schema_defs = self.schema_defs().cloned(); + for (name, definition) in update_values.updated_schema_defs { + match schema_defs + .as_mut() + .and_then(|definitions| definitions.get_mut(name)) + { + Some(existing) => *existing = definition.clone(), + None => return not_found(DataContractUpdateEntryKind::SchemaDef, name.clone()), + } + } + for (name, definition) in update_values.new_schema_defs { + if schema_defs + .get_or_insert_with(BTreeMap::new) + .insert(name.clone(), definition.clone()) + .is_some() + { + return already_exists(DataContractUpdateEntryKind::SchemaDef, name.clone()); + } + } + + let mut groups = self.groups().clone(); + for (position, group) in update_values.new_groups { + if groups.insert(*position, group.clone()).is_some() { + return already_exists(DataContractUpdateEntryKind::Group, position.to_string()); + } + } + + let mut tokens = self.tokens().clone(); + for (position, token) in update_values.new_tokens { + if tokens.insert(*position, token.clone()).is_some() { + return already_exists(DataContractUpdateEntryKind::Token, position.to_string()); + } + } + + // The stored keywords that stay keep their order, and the added ones follow them + let mut keywords = self.keywords().clone(); + for keyword in update_values.remove_keywords { + match keywords.iter().position(|existing| existing == keyword) { + Some(index) => { + keywords.remove(index); + } + None => return not_found(DataContractUpdateEntryKind::Keyword, keyword.clone()), + } + } + for keyword in update_values.add_keywords { + if keywords.contains(keyword) { + return already_exists(DataContractUpdateEntryKind::Keyword, keyword.clone()); + } + keywords.push(keyword.clone()); + } + + let description = match update_values.description { + DescriptionUpdate::Keep => self.description().cloned(), + DescriptionUpdate::Clear => None, + DescriptionUpdate::Set(description) => Some(description.clone()), + }; + + Ok(DataContractInSerializationFormatV1 { + id: contract_id, + config: update_values.config.unwrap_or(self.config()).clone(), + version: update_values.version, + owner_id: self.owner_id(), + schema_defs, + document_schemas, + created_at: self.created_at(), + updated_at: self.updated_at(), + created_at_block_height: self.created_at_block_height(), + updated_at_block_height: self.updated_at_block_height(), + created_at_epoch: self.created_at_epoch(), + updated_at_epoch: self.updated_at_epoch(), + groups, + tokens, + keywords, + description, + }) + } +} diff --git a/packages/rs-dpp/src/data_contract/methods/mod.rs b/packages/rs-dpp/src/data_contract/methods/mod.rs index 04f79db8876..c09783d6d61 100644 --- a/packages/rs-dpp/src/data_contract/methods/mod.rs +++ b/packages/rs-dpp/src/data_contract/methods/mod.rs @@ -1,3 +1,4 @@ +mod apply_update; mod equal_ignoring_time_based_fields; mod registration_cost; pub mod schema; diff --git a/packages/rs-dpp/src/data_contract/mod.rs b/packages/rs-dpp/src/data_contract/mod.rs index e2c7736ab6f..153a0de7169 100644 --- a/packages/rs-dpp/src/data_contract/mod.rs +++ b/packages/rs-dpp/src/data_contract/mod.rs @@ -51,6 +51,7 @@ pub mod change_control_rules; pub mod config; pub mod group; pub mod storage_requirements; +pub mod update_values; use crate::data_contract::serialized_version::{ DataContractInSerializationFormat, CONTRACT_DESERIALIZATION_LIMIT, @@ -58,7 +59,9 @@ use crate::data_contract::serialized_version::{ use crate::util::hash::hash_double_to_vec; #[cfg(feature = "validation")] -use crate::consensus::basic::data_contract::DataContractCompiledMaxSizeExceededError; +use crate::consensus::basic::data_contract::{ + DataContractCompiledMaxSizeExceededError, DataContractMaxSizeExceededError, +}; #[cfg(feature = "validation")] use crate::validation::operations::ProtocolValidationOperation; #[cfg(feature = "validation")] @@ -79,7 +82,7 @@ use platform_versioning::PlatformVersioned; pub use serde_json::Value as JsonValue; type JsonSchema = JsonValue; -type DefinitionName = String; +pub type DefinitionName = String; pub type DocumentName = String; pub type TokenName = String; pub type GroupContractPosition = u16; @@ -205,6 +208,13 @@ impl DataContract { /// `max_serialized_size`. The compile and serialization it takes is recorded in /// `validation_operations`, charged per compiled byte. Refuses, compiles and records /// nothing where contracts are not stored compiled. + /// + /// There it also refuses a contract whose bytes in the format transitions carry are over + /// `max_serialized_size`, with a [`DataContractMaxSizeExceededError`]: Drive refuses to + /// store one, and from the protocol version that stores contracts compiled a contract can + /// reach that cap, as a delta contract update grows a contract past what one state + /// transition can carry. The compile measures those bytes, so the check takes no other + /// work. It runs first, as the cap every contract had before the compiled one. #[cfg(feature = "validation")] pub fn validate_compiled_size( &self, @@ -223,10 +233,19 @@ impl DataContract { if !stored_compiled { return Ok(SimpleConsensusValidationResult::new()); } - let compiled_size = self.serialize_to_storage_bytes(platform_version)?.len() as u64; + let (compiled, serialized_size) = + self.serialize_to_storage_bytes_with_carried_size(platform_version)?; + let compiled_size = compiled.len() as u64; validation_operations.extend(std::iter::once( ProtocolValidationOperation::ContractCompiledSizeValidation(compiled_size), )); + let max_serialized_size = platform_version.dpp.contract_versions.max_serialized_size; + if serialized_size as u64 > u64::from(max_serialized_size) { + return Ok(SimpleConsensusValidationResult::new_with_error( + DataContractMaxSizeExceededError::new(serialized_size as u64, max_serialized_size) + .into(), + )); + } if compiled_size > u64::from(max_compiled_size) { return Ok(SimpleConsensusValidationResult::new_with_error( DataContractCompiledMaxSizeExceededError::new(compiled_size, max_compiled_size) @@ -795,4 +814,68 @@ mod compiled_size_tests { .expect("expected nothing refused at protocol version 14"); assert!(operations.is_empty()); } + + /// Where contracts are stored compiled, the bytes transitions carry are capped by a + /// consensus error too: Drive refuses to store a contract over `max_serialized_size`, and a + /// delta contract update can grow one that far. The size is the one Drive measures, and + /// the compile that measures it is charged whatever the verdict. + #[test] + fn should_refuse_a_contract_over_the_serialized_size_cap() { + let latest = PlatformVersion::latest(); + let contract = fixture_contract(); + let (compiled, serialized_size) = contract + .serialize_to_storage_bytes_with_carried_size(latest) + .expect("expected the contract to compile"); + assert_eq!( + serialized_size, + contract + .serialize_to_bytes_with_platform_version(latest) + .expect("expected the contract to serialize") + .len() + ); + let serialized_size = serialized_size as u32; + + for (cap, refused) in [(serialized_size - 1, true), (serialized_size, false)] { + let mut platform_version = latest.clone(); + platform_version.dpp.contract_versions.max_serialized_size = cap; + let mut operations = vec![]; + let result = contract + .validate_compiled_size(&mut operations, &platform_version) + .expect("expected the sizes to be measured"); + if refused { + assert!( + matches!( + result.errors.as_slice(), + [ConsensusError::BasicError( + BasicError::DataContractMaxSizeExceededError(error) + )] if error.serialized_size() == u64::from(serialized_size) + && error.max_serialized_size() == cap + ), + "{:?}", + result.errors + ); + } else { + assert!(result.is_valid(), "{:?}", result.errors); + } + assert_eq!( + operations, + vec![ProtocolValidationOperation::ContractCompiledSizeValidation( + compiled.len() as u64 + )] + ); + } + + // Where contracts are not stored compiled no contract can reach the cap, and nothing + // is measured + let mut platform_version = PlatformVersion::get(14) + .expect("expected protocol version 14") + .clone(); + platform_version.dpp.contract_versions.max_serialized_size = 1; + let mut operations = vec![]; + assert!(contract + .validate_compiled_size(&mut operations, &platform_version) + .expect("expected nothing measured at protocol version 14") + .is_valid()); + assert!(operations.is_empty()); + } } diff --git a/packages/rs-dpp/src/data_contract/serialized_version/mod.rs b/packages/rs-dpp/src/data_contract/serialized_version/mod.rs index cb981d41814..39717bcfd96 100644 --- a/packages/rs-dpp/src/data_contract/serialized_version/mod.rs +++ b/packages/rs-dpp/src/data_contract/serialized_version/mod.rs @@ -34,6 +34,9 @@ pub(in crate::data_contract) mod v0; pub(in crate::data_contract) mod v1; pub(in crate::data_contract) mod v2; +#[cfg(feature = "serde-conversion")] +pub(crate) use v1::{deserialize_u16_group_map, deserialize_u16_token_configuration_map}; + pub mod property_names { pub const ID: &str = "id"; pub const OWNER_ID: &str = "ownerId"; diff --git a/packages/rs-dpp/src/data_contract/serialized_version/v1/mod.rs b/packages/rs-dpp/src/data_contract/serialized_version/v1/mod.rs index 974eac8a382..ed6a7afab51 100644 --- a/packages/rs-dpp/src/data_contract/serialized_version/v1/mod.rs +++ b/packages/rs-dpp/src/data_contract/serialized_version/v1/mod.rs @@ -74,7 +74,7 @@ pub struct DataContractInSerializationFormatV1 { pub description: Option, } -fn deserialize_u16_group_map<'de, D>( +pub(crate) fn deserialize_u16_group_map<'de, D>( deserializer: D, ) -> Result, D::Error> where @@ -89,7 +89,7 @@ where }) .collect() } -fn deserialize_u16_token_configuration_map<'de, D>( +pub(crate) fn deserialize_u16_token_configuration_map<'de, D>( deserializer: D, ) -> Result, D::Error> where diff --git a/packages/rs-dpp/src/data_contract/update_values.rs b/packages/rs-dpp/src/data_contract/update_values.rs new file mode 100644 index 00000000000..2d4f401bb8c --- /dev/null +++ b/packages/rs-dpp/src/data_contract/update_values.rs @@ -0,0 +1,137 @@ +//! What a delta contract update changes in a stored contract. +//! +//! Version 1 of the +//! [`DataContractUpdateTransition`](crate::state_transition::data_contract_update_transition::DataContractUpdateTransition) +//! carries only what an update changes. [`DataContractUpdateValues`] is the borrowed view of +//! that delta which [`DataContract::apply_update`](crate::data_contract::DataContract::apply_update) +//! merges onto the stored contract. + +use crate::data_contract::associated_token::token_configuration::TokenConfiguration; +use crate::data_contract::config::DataContractConfig; +use crate::data_contract::group::Group; +use crate::data_contract::serialized_version::v1::DataContractInSerializationFormatV1; +use crate::data_contract::serialized_version::DataContractInSerializationFormat; +use crate::data_contract::{ + DefinitionName, DocumentName, GroupContractPosition, TokenContractPosition, +}; +use crate::fee::Credits; +use crate::ProtocolError; +use bincode::{Decode, DecodeUntrusted, Encode}; +use platform_value::{Identifier, Value}; +use platform_version::version::PlatformVersion; +#[cfg(feature = "serde-conversion")] +use serde::{Deserialize, Serialize}; +use std::collections::BTreeMap; + +#[cfg(feature = "json-conversion")] +use crate::serialization::JsonSafeFields; + +/// What a contract update does to the contract's description. +/// +/// An `Option>` does not survive a JSON round trip (`None` and `Some(None)` +/// both serialize as `null`), so the three cases are spelled out. +#[derive(Debug, Clone, PartialEq, Eq, Default, Encode, Decode, DecodeUntrusted)] +#[cfg_attr( + feature = "serde-conversion", + derive(Serialize, Deserialize), + serde(rename_all = "camelCase") +)] +pub enum DescriptionUpdate { + /// Leave the description as it is. + #[default] + Keep, + /// Remove the description. + Clear, + /// Replace the description. + Set(String), +} + +#[cfg(feature = "json-conversion")] +impl JsonSafeFields for DescriptionUpdate {} + +/// A borrowed view of what a delta contract update changes. +/// +/// Every section adds entries or replaces a named entry in place. A contract update may not +/// remove a document type, a schema definition, a group or a token, nor change a group or a +/// token, so a delta has no way to say so. +#[derive(Debug, Clone, Copy)] +pub struct DataContractUpdateValues<'a> { + /// The identity submitting the update. It must own the stored contract. + pub owner_id: Identifier, + /// The contract version the update produces. + pub version: u32, + /// A replacement config, or `None` to keep the stored one. + pub config: Option<&'a DataContractConfig>, + /// New schemas for existing shared `$defs` definitions. + pub updated_schema_defs: &'a BTreeMap, + /// Shared `$defs` definitions to add. + pub new_schema_defs: &'a BTreeMap, + /// New schemas for existing document types. + pub updated_document_schemas: &'a BTreeMap, + /// Document types to add. + pub new_document_schemas: &'a BTreeMap, + /// Groups to add. + pub new_groups: &'a BTreeMap, + /// Tokens to add. + pub new_tokens: &'a BTreeMap, + /// Keywords to add, after the stored ones that stay. + pub add_keywords: &'a [String], + /// Keywords to remove. + pub remove_keywords: &'a [String], + /// What to do with the description. + pub description: &'a DescriptionUpdate, +} + +impl DataContractUpdateValues<'_> { + /// The registration cost of what this delta registers. + /// + /// An update that carries the whole contract pays the registration cost of the whole + /// contract again. A delta registers only its new and replaced document types (with their + /// indexes), its new tokens and its added keywords, so it pays for those alone: the + /// registration cost of a contract holding only them, less that of a contract holding + /// nothing, which is the fee of registering a contract. Both are priced by + /// [`DataContractInSerializationFormat::registration_cost`], so a delta follows every + /// generation of the registration cost. + pub fn registration_cost( + &self, + platform_version: &PlatformVersion, + ) -> Result { + let contract_registering = |document_schemas, tokens, keywords| { + DataContractConfig::default_for_version(platform_version).map(|config| { + DataContractInSerializationFormat::V1(DataContractInSerializationFormatV1 { + id: Identifier::default(), + config, + version: self.version, + owner_id: self.owner_id, + schema_defs: None, + document_schemas, + created_at: None, + updated_at: None, + created_at_block_height: None, + updated_at_block_height: None, + created_at_epoch: None, + updated_at_epoch: None, + groups: BTreeMap::new(), + tokens, + keywords, + description: None, + }) + }) + }; + + let registered = contract_registering( + self.new_document_schemas + .iter() + .chain(self.updated_document_schemas) + .map(|(name, schema)| (name.clone(), schema.clone())) + .collect(), + self.new_tokens.clone(), + self.add_keywords.to_vec(), + )? + .registration_cost(platform_version)?; + let nothing_registered = contract_registering(BTreeMap::new(), BTreeMap::new(), vec![])? + .registration_cost(platform_version)?; + + Ok(registered.saturating_sub(nothing_registered)) + } +} diff --git a/packages/rs-dpp/src/errors/consensus/basic/basic_error.rs b/packages/rs-dpp/src/errors/consensus/basic/basic_error.rs index b21ad1a639d..83239b09dad 100644 --- a/packages/rs-dpp/src/errors/consensus/basic/basic_error.rs +++ b/packages/rs-dpp/src/errors/consensus/basic/basic_error.rs @@ -47,6 +47,9 @@ use crate::consensus::basic::data_contract::{ UnknownSecurityLevelError, UnknownStorageKeyRequirementsError, UnknownTradeModeError, UnknownTransferableTypeError, }; +use crate::consensus::basic::data_contract::{ + DataContractMaxSizeExceededError, DataContractUpdateOverlappingEntriesError, +}; use crate::consensus::basic::data_contract::{ InvalidJsonSchemaRefError, TokenPaymentByBurningOnlyAllowedOnInternalTokenError, UnknownDocumentActionTokenEffectError, @@ -903,6 +906,16 @@ pub enum BasicError { #[error(transparent)] DuplicatePrivateDocumentEntryError(DuplicatePrivateDocumentEntryError), + + // A delta contract update (protocol version 15) naming one entry in two sections that + // cannot both apply. + #[error(transparent)] + DataContractUpdateOverlappingEntriesError(DataContractUpdateOverlappingEntriesError), + + // A contract whose bytes in the format transitions carry would be over + // `max_serialized_size`, which delta contract updates (protocol version 15) can reach. + #[error(transparent)] + DataContractMaxSizeExceededError(DataContractMaxSizeExceededError), } impl From for ConsensusError { @@ -914,6 +927,7 @@ impl From for ConsensusError { #[cfg(test)] mod tests { use super::*; + use crate::consensus::basic::data_contract::DataContractUpdateEntryKind; use crate::consensus::basic::document::PropertyConstraintViolation; use platform_value::Identifier; @@ -1169,6 +1183,23 @@ mod tests { )), 213 ); + // Delta contract updates (protocol version 15): the tail of the enum. + assert_eq!( + discriminant_of(BasicError::DataContractUpdateOverlappingEntriesError( + DataContractUpdateOverlappingEntriesError::new( + Identifier::from([1; 32]), + DataContractUpdateEntryKind::Keyword, + "keyword".to_string(), + ) + )), + 214 + ); + assert_eq!( + discriminant_of(BasicError::DataContractMaxSizeExceededError( + DataContractMaxSizeExceededError::new(0, 0) + )), + 215 + ); } /// The variants that shipped in 4.1 keep the discriminants they were released with, so an diff --git a/packages/rs-dpp/src/errors/consensus/basic/data_contract/data_contract_max_size_exceeded_error.rs b/packages/rs-dpp/src/errors/consensus/basic/data_contract/data_contract_max_size_exceeded_error.rs new file mode 100644 index 00000000000..267503923b4 --- /dev/null +++ b/packages/rs-dpp/src/errors/consensus/basic/data_contract/data_contract_max_size_exceeded_error.rs @@ -0,0 +1,64 @@ +use crate::consensus::basic::BasicError; +use crate::errors::ProtocolError; +use platform_serialization_derive::{ + PlatformDeserializeTrusted, PlatformDeserializeUntrusted, PlatformSerialize, +}; +use thiserror::Error; + +use crate::consensus::ConsensusError; + +use bincode::{Decode, DecodeUntrusted, Encode}; + +/// A contract whose bytes in the format state transitions carry would be over +/// `max_serialized_size`. A contract update that carries the whole contract cannot reach the +/// cap, as a state transition is capped well below it; one that carries only what it changes +/// (protocol version 15) grows a contract a transition at a time, up to the cap. +#[derive( + Error, + Debug, + Clone, + PartialEq, + Eq, + Encode, + Decode, + PlatformSerialize, + PlatformDeserializeTrusted, + PlatformDeserializeUntrusted, + DecodeUntrusted, +)] +#[error( + "Data contract takes {serialized_size} bytes, over the maximum of {max_serialized_size} bytes a contract may take" +)] +#[platform_serialize(unversioned)] +pub struct DataContractMaxSizeExceededError { + /* + + DO NOT CHANGE ORDER OF FIELDS WITHOUT INTRODUCING OF NEW VERSION + + */ + serialized_size: u64, + max_serialized_size: u32, +} + +impl DataContractMaxSizeExceededError { + pub fn new(serialized_size: u64, max_serialized_size: u32) -> Self { + Self { + serialized_size, + max_serialized_size, + } + } + + pub fn serialized_size(&self) -> u64 { + self.serialized_size + } + + pub fn max_serialized_size(&self) -> u32 { + self.max_serialized_size + } +} + +impl From for ConsensusError { + fn from(err: DataContractMaxSizeExceededError) -> Self { + Self::BasicError(BasicError::DataContractMaxSizeExceededError(err)) + } +} diff --git a/packages/rs-dpp/src/errors/consensus/basic/data_contract/data_contract_update_overlapping_entries_error.rs b/packages/rs-dpp/src/errors/consensus/basic/data_contract/data_contract_update_overlapping_entries_error.rs new file mode 100644 index 00000000000..149915f9bad --- /dev/null +++ b/packages/rs-dpp/src/errors/consensus/basic/data_contract/data_contract_update_overlapping_entries_error.rs @@ -0,0 +1,205 @@ +use crate::consensus::basic::BasicError; +use crate::consensus::ConsensusError; +use crate::errors::ProtocolError; +use bincode::{Decode, DecodeUntrusted, Encode}; +use platform_serialization_derive::{ + PlatformDeserializeTrusted, PlatformDeserializeUntrusted, PlatformSerialize, +}; +use platform_value::Identifier; +use std::fmt; +use thiserror::Error; + +/// The kind of contract entry a delta-based contract update names. +/// +/// A V1 data contract update transition carries additive and in-place +/// changes per entry kind rather than a whole contract, so validation +/// errors report which section of the delta a name came from. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Encode, Decode, DecodeUntrusted)] +pub enum DataContractUpdateEntryKind { + /// A document type, keyed by its name. + DocumentType, + /// A shared `$defs` sub-schema, keyed by its definition name. + SchemaDef, + /// A group, keyed by its contract position. + Group, + /// A token, keyed by its contract position. + Token, + /// A search keyword. + Keyword, +} + +impl fmt::Display for DataContractUpdateEntryKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let name = match self { + DataContractUpdateEntryKind::DocumentType => "document type", + DataContractUpdateEntryKind::SchemaDef => "schema definition", + DataContractUpdateEntryKind::Group => "group", + DataContractUpdateEntryKind::Token => "token", + DataContractUpdateEntryKind::Keyword => "keyword", + }; + f.write_str(name) + } +} + +/// The most bytes of an entry's name an error about a delta contract update carries. +/// +/// A delta names the entries it changes, so a name in one is as long as a state transition +/// lets it be, while a consensus error is serialized in at most 2,000 bytes and cannot be +/// reported past that. A name over this bound is cut to it, so each of these errors is +/// reported whatever the delta names. A document type's name takes 64 characters at most +/// and a keyword 50, so a name the contract can hold is carried whole. +pub const MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES: usize = 256; + +/// `name`, cut to [`MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES`] bytes where it is longer, +/// at the last character that fits whole. +pub(crate) fn bounded_entry_name(mut name: String) -> String { + if name.len() > MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES { + let mut end = MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES; + while !name.is_char_boundary(end) { + end -= 1; + } + name.truncate(end); + } + name +} + +/// A delta-based contract update names the same entry in two sections +/// that cannot both apply: a document type or schema definition listed +/// as both new and updated, or a keyword listed as both added and removed. +#[derive( + Error, + Debug, + Clone, + PartialEq, + Eq, + Encode, + Decode, + DecodeUntrusted, + PlatformSerialize, + PlatformDeserializeTrusted, + PlatformDeserializeUntrusted, +)] +#[error( + "Data Contract {data_contract_id} update names {entry_kind} '{name}' in two conflicting sections" +)] +#[platform_serialize(unversioned)] +pub struct DataContractUpdateOverlappingEntriesError { + /* + + DO NOT CHANGE ORDER OF FIELDS WITHOUT INTRODUCING OF NEW VERSION + + */ + data_contract_id: Identifier, + entry_kind: DataContractUpdateEntryKind, + name: String, +} + +impl DataContractUpdateOverlappingEntriesError { + pub fn new( + data_contract_id: Identifier, + entry_kind: DataContractUpdateEntryKind, + name: String, + ) -> Self { + Self { + data_contract_id, + entry_kind, + name: bounded_entry_name(name), + } + } + + pub fn data_contract_id(&self) -> &Identifier { + &self.data_contract_id + } + + pub fn entry_kind(&self) -> DataContractUpdateEntryKind { + self.entry_kind + } + + /// The entry's name, cut to [`MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES`] bytes. + pub fn name(&self) -> &str { + &self.name + } +} + +impl From for ConsensusError { + fn from(err: DataContractUpdateOverlappingEntriesError) -> Self { + Self::BasicError(BasicError::DataContractUpdateOverlappingEntriesError(err)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::consensus::state::data_contract::data_contract_update_entry_already_exists_error::DataContractUpdateEntryAlreadyExistsError; + use crate::consensus::state::data_contract::data_contract_update_entry_not_found_error::DataContractUpdateEntryNotFoundError; + use crate::serialization::{ + PlatformDeserializableUntrusted, PlatformSerializableWithPlatformVersion, + }; + use platform_version::version::PlatformVersion; + + /// The most bytes a serialized consensus error takes: the limit `ConsensusError` is + /// serialized and deserialized with. + const CONSENSUS_ERROR_BYTES: usize = 2_000; + + #[test] + fn should_carry_a_name_within_the_bound_whole() { + let name = "n".repeat(MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES); + + assert_eq!(bounded_entry_name(name.clone()), name); + } + + #[test] + fn should_cut_a_longer_name_at_the_last_character_that_fits_whole() { + // One byte, then characters of two bytes: the bound falls inside one of them + let name = format!( + "n{}", + "\u{e9}".repeat(MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES) + ); + + let bounded = bounded_entry_name(name.clone()); + + assert_eq!(bounded.len(), MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES - 1); + assert!(name.starts_with(&bounded)); + } + + #[test] + fn should_report_an_error_about_a_name_longer_than_a_consensus_error() { + let platform_version = PlatformVersion::latest(); + let contract_id = Identifier::new([7; 32]); + // A state transition has room for this name, and a consensus error has not + let name = "n".repeat(3_000); + assert!(name.len() > CONSENSUS_ERROR_BYTES); + + let errors: [ConsensusError; 3] = [ + DataContractUpdateOverlappingEntriesError::new( + contract_id, + DataContractUpdateEntryKind::Keyword, + name.clone(), + ) + .into(), + DataContractUpdateEntryAlreadyExistsError::new( + contract_id, + DataContractUpdateEntryKind::SchemaDef, + name.clone(), + ) + .into(), + DataContractUpdateEntryNotFoundError::new( + contract_id, + DataContractUpdateEntryKind::DocumentType, + name.clone(), + ) + .into(), + ]; + + for error in errors { + let bytes = error + .serialize_to_bytes_with_platform_version(platform_version) + .expect("expected the error to fit a consensus error"); + assert!(bytes.len() <= CONSENSUS_ERROR_BYTES); + + let decoded = ConsensusError::deserialize_from_bytes_untrusted(&bytes) + .expect("expected the error to be read back"); + assert_eq!(decoded, error); + } + } +} diff --git a/packages/rs-dpp/src/errors/consensus/basic/data_contract/mod.rs b/packages/rs-dpp/src/errors/consensus/basic/data_contract/mod.rs index db8bf67ed28..7fc6392e1ab 100644 --- a/packages/rs-dpp/src/errors/consensus/basic/data_contract/mod.rs +++ b/packages/rs-dpp/src/errors/consensus/basic/data_contract/mod.rs @@ -6,8 +6,10 @@ mod data_contract_immutable_properties_update_error; mod data_contract_invalid_index_definition_update_error; mod data_contract_invalid_required_fields_update_error; pub mod data_contract_max_depth_exceed_error; +mod data_contract_max_size_exceeded_error; mod data_contract_token_configuration_update_error; mod data_contract_unique_indices_changed_error; +mod data_contract_update_overlapping_entries_error; mod document_types_are_missing_error; mod duplicate_index_error; mod duplicate_index_name_error; @@ -71,8 +73,10 @@ pub use data_contract_have_new_unique_index_error::*; pub use data_contract_immutable_properties_update_error::*; pub use data_contract_invalid_index_definition_update_error::*; pub use data_contract_invalid_required_fields_update_error::*; +pub use data_contract_max_size_exceeded_error::*; pub use data_contract_token_configuration_update_error::*; pub use data_contract_unique_indices_changed_error::*; +pub use data_contract_update_overlapping_entries_error::*; pub use document_types_are_missing_error::*; pub use duplicate_index_error::*; pub use duplicate_index_name_error::*; diff --git a/packages/rs-dpp/src/errors/consensus/codes.rs b/packages/rs-dpp/src/errors/consensus/codes.rs index 9b3326f5a4c..0aad68850f7 100644 --- a/packages/rs-dpp/src/errors/consensus/codes.rs +++ b/packages/rs-dpp/src/errors/consensus/codes.rs @@ -127,6 +127,8 @@ impl ErrorWithCode for BasicError { Self::NonTransferableTokenPaymentMustBurnError(_) => 10280, Self::NonTransferableTokenTradeableError(_) => 10281, Self::DataContractCompiledMaxSizeExceededError(_) => 10282, + Self::DataContractUpdateOverlappingEntriesError(_) => 10283, + Self::DataContractMaxSizeExceededError(_) => 10284, // Group Errors: 10350-10399 Self::GroupPositionDoesNotExistError(_) => 10350, @@ -345,6 +347,8 @@ impl ErrorWithCode for StateError { Self::IdentityMemberOfGroupNotFoundError(_) => 40007, Self::DataContractNotFoundError(_) => 40008, Self::InvalidTokenPositionStateError(_) => 40009, + Self::DataContractUpdateEntryAlreadyExistsError(_) => 40010, + Self::DataContractUpdateEntryNotFoundError(_) => 40011, // Document Errors: 40100-40199 Self::DocumentAlreadyPresentError { .. } => 40100, diff --git a/packages/rs-dpp/src/errors/consensus/state/data_contract/data_contract_update_entry_already_exists_error.rs b/packages/rs-dpp/src/errors/consensus/state/data_contract/data_contract_update_entry_already_exists_error.rs new file mode 100644 index 00000000000..5eabb4c002e --- /dev/null +++ b/packages/rs-dpp/src/errors/consensus/state/data_contract/data_contract_update_entry_already_exists_error.rs @@ -0,0 +1,76 @@ +use crate::consensus::basic::data_contract::bounded_entry_name; +use crate::consensus::basic::data_contract::DataContractUpdateEntryKind; +use crate::consensus::state::state_error::StateError; +use crate::consensus::ConsensusError; +use crate::errors::ProtocolError; +use bincode::{Decode, DecodeUntrusted, Encode}; +use platform_serialization_derive::{ + PlatformDeserializeTrusted, PlatformDeserializeUntrusted, PlatformSerialize, +}; +use platform_value::Identifier; +use thiserror::Error; + +/// A delta-based contract update adds an entry under a name or position the +/// stored contract already uses. Existing document types and schema +/// definitions change through the update sections, and existing groups, +/// tokens and keywords cannot be replaced at all. +#[derive( + Error, + Debug, + Clone, + PartialEq, + Eq, + Encode, + Decode, + DecodeUntrusted, + PlatformSerialize, + PlatformDeserializeTrusted, + PlatformDeserializeUntrusted, +)] +#[error("Data Contract {data_contract_id} already has {entry_kind} '{name}', it can not be added")] +#[platform_serialize(unversioned)] +pub struct DataContractUpdateEntryAlreadyExistsError { + /* + + DO NOT CHANGE ORDER OF FIELDS WITHOUT INTRODUCING OF NEW VERSION + + */ + data_contract_id: Identifier, + entry_kind: DataContractUpdateEntryKind, + name: String, +} + +impl DataContractUpdateEntryAlreadyExistsError { + pub fn new( + data_contract_id: Identifier, + entry_kind: DataContractUpdateEntryKind, + name: String, + ) -> Self { + Self { + data_contract_id, + entry_kind, + name: bounded_entry_name(name), + } + } + + pub fn data_contract_id(&self) -> &Identifier { + &self.data_contract_id + } + + pub fn entry_kind(&self) -> DataContractUpdateEntryKind { + self.entry_kind + } + + /// The entry's name, cut to + /// [`MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES`](crate::consensus::basic::data_contract::MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES) + /// bytes. + pub fn name(&self) -> &str { + &self.name + } +} + +impl From for ConsensusError { + fn from(err: DataContractUpdateEntryAlreadyExistsError) -> Self { + Self::StateError(StateError::DataContractUpdateEntryAlreadyExistsError(err)) + } +} diff --git a/packages/rs-dpp/src/errors/consensus/state/data_contract/data_contract_update_entry_not_found_error.rs b/packages/rs-dpp/src/errors/consensus/state/data_contract/data_contract_update_entry_not_found_error.rs new file mode 100644 index 00000000000..360496cbb69 --- /dev/null +++ b/packages/rs-dpp/src/errors/consensus/state/data_contract/data_contract_update_entry_not_found_error.rs @@ -0,0 +1,75 @@ +use crate::consensus::basic::data_contract::bounded_entry_name; +use crate::consensus::basic::data_contract::DataContractUpdateEntryKind; +use crate::consensus::state::state_error::StateError; +use crate::consensus::ConsensusError; +use crate::errors::ProtocolError; +use bincode::{Decode, DecodeUntrusted, Encode}; +use platform_serialization_derive::{ + PlatformDeserializeTrusted, PlatformDeserializeUntrusted, PlatformSerialize, +}; +use platform_value::Identifier; +use thiserror::Error; + +/// A delta-based contract update changes or removes an entry the stored +/// contract does not have: an updated document type or schema definition +/// that was never registered, or a removed keyword that is not present. +#[derive( + Error, + Debug, + Clone, + PartialEq, + Eq, + Encode, + Decode, + DecodeUntrusted, + PlatformSerialize, + PlatformDeserializeTrusted, + PlatformDeserializeUntrusted, +)] +#[error("Data Contract {data_contract_id} has no {entry_kind} '{name}' to update")] +#[platform_serialize(unversioned)] +pub struct DataContractUpdateEntryNotFoundError { + /* + + DO NOT CHANGE ORDER OF FIELDS WITHOUT INTRODUCING OF NEW VERSION + + */ + data_contract_id: Identifier, + entry_kind: DataContractUpdateEntryKind, + name: String, +} + +impl DataContractUpdateEntryNotFoundError { + pub fn new( + data_contract_id: Identifier, + entry_kind: DataContractUpdateEntryKind, + name: String, + ) -> Self { + Self { + data_contract_id, + entry_kind, + name: bounded_entry_name(name), + } + } + + pub fn data_contract_id(&self) -> &Identifier { + &self.data_contract_id + } + + pub fn entry_kind(&self) -> DataContractUpdateEntryKind { + self.entry_kind + } + + /// The entry's name, cut to + /// [`MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES`](crate::consensus::basic::data_contract::MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES) + /// bytes. + pub fn name(&self) -> &str { + &self.name + } +} + +impl From for ConsensusError { + fn from(err: DataContractUpdateEntryNotFoundError) -> Self { + Self::StateError(StateError::DataContractUpdateEntryNotFoundError(err)) + } +} diff --git a/packages/rs-dpp/src/errors/consensus/state/data_contract/mod.rs b/packages/rs-dpp/src/errors/consensus/state/data_contract/mod.rs index 30b88ad8af3..23b7af77b89 100644 --- a/packages/rs-dpp/src/errors/consensus/state/data_contract/mod.rs +++ b/packages/rs-dpp/src/errors/consensus/state/data_contract/mod.rs @@ -3,5 +3,7 @@ pub mod data_contract_config_update_error; pub mod data_contract_is_readonly_error; pub mod data_contract_not_found_error; pub mod data_contract_update_action_not_allowed_error; +pub mod data_contract_update_entry_already_exists_error; +pub mod data_contract_update_entry_not_found_error; pub mod data_contract_update_permission_error; pub mod document_type_update_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 2d07f7c7f9d..6cf4b00db32 100644 --- a/packages/rs-dpp/src/errors/consensus/state/state_error.rs +++ b/packages/rs-dpp/src/errors/consensus/state/state_error.rs @@ -65,6 +65,8 @@ use crate::consensus::state::identity::{IdentityAlreadyExistsError, IdentityInsu use crate::consensus::ConsensusError; use crate::consensus::state::data_contract::data_contract_not_found_error::DataContractNotFoundError; use crate::consensus::state::data_contract::data_contract_update_action_not_allowed_error::DataContractUpdateActionNotAllowedError; +use crate::consensus::state::data_contract::data_contract_update_entry_already_exists_error::DataContractUpdateEntryAlreadyExistsError; +use crate::consensus::state::data_contract::data_contract_update_entry_not_found_error::DataContractUpdateEntryNotFoundError; use crate::consensus::state::data_contract::data_contract_update_permission_error::DataContractUpdatePermissionError; use crate::consensus::state::data_contract::document_type_update_error::DocumentTypeUpdateError; use crate::consensus::state::document::document_contest_currently_locked_error::DocumentContestCurrentlyLockedError; @@ -771,6 +773,14 @@ pub enum StateError { #[error(transparent)] PrivateDocumentEntrySizeMismatchError(PrivateDocumentEntrySizeMismatchError), + + // A delta contract update (protocol version 15) adding an entry the stored contract + // already has, or changing or removing one it does not have. + #[error(transparent)] + DataContractUpdateEntryAlreadyExistsError(DataContractUpdateEntryAlreadyExistsError), + + #[error(transparent)] + DataContractUpdateEntryNotFoundError(DataContractUpdateEntryNotFoundError), } impl From for ConsensusError { @@ -783,6 +793,7 @@ impl From for ConsensusError { mod tests { use super::*; use crate::block::block_info::BlockInfo; + use crate::consensus::basic::data_contract::DataContractUpdateEntryKind; use crate::consensus::basic::document::PropertyConstraintViolation; use crate::consensus::state::contract_moderation::ContractModerationCounterpartyRole; use crate::consensus::state::identity::identity_public_key_limit_not_set_error::KeyLimit; @@ -1750,5 +1761,26 @@ mod tests { )), 180 ); + // Delta contract updates (protocol version 15): the tail of the enum. + assert_eq!( + discriminant_of(StateError::DataContractUpdateEntryAlreadyExistsError( + DataContractUpdateEntryAlreadyExistsError::new( + identity_id, + DataContractUpdateEntryKind::DocumentType, + "note".to_string(), + ) + )), + 181 + ); + assert_eq!( + discriminant_of(StateError::DataContractUpdateEntryNotFoundError( + DataContractUpdateEntryNotFoundError::new( + identity_id, + DataContractUpdateEntryKind::DocumentType, + "note".to_string(), + ) + )), + 182 + ); } } diff --git a/packages/rs-dpp/src/state_transition/mod.rs b/packages/rs-dpp/src/state_transition/mod.rs index df55059a7b5..5cc6f23d08c 100644 --- a/packages/rs-dpp/src/state_transition/mod.rs +++ b/packages/rs-dpp/src/state_transition/mod.rs @@ -20,6 +20,7 @@ use platform_serialization_derive::{ PlatformDeserializeTrusted, PlatformDeserializeUntrusted, PlatformSerialize, PlatformSignable, }; use platform_version::version::feature_initial_protocol_versions::{ + DATA_CONTRACT_UPDATE_V1_INITIAL_PROTOCOL_VERSION, PRIVATE_DOCUMENT_CREATE_FROM_SHIELDED_POOL_INITIAL_PROTOCOL_VERSION, YES_NO_VOTE_POLL_INITIAL_PROTOCOL_VERSION, }; @@ -1245,7 +1246,13 @@ impl StateTransition { } } StateTransition::DataContractUpdate(data_contract_update_transition) => { - active_version_range_for_contract(data_contract_update_transition.data_contract()) + match data_contract_update_transition.data_contract() { + Some(contract) => active_version_range_for_contract(contract), + // Version 1, the delta form, embeds no contract and exists from protocol + // version 15. Binaries from before it cannot decode one, so an earlier + // version rejects it without charging, exactly as they do. + None => DATA_CONTRACT_UPDATE_V1_INITIAL_PROTOCOL_VERSION..=LATEST_VERSION, + } } StateTransition::Batch(batch_transition) => { // Version 2 of the document base (the action fee agreement) exists from diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/accessors/mod.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/accessors/mod.rs index a928d77b220..58aafa7c134 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/accessors/mod.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/accessors/mod.rs @@ -4,26 +4,45 @@ use crate::data_contract::serialized_version::DataContractInSerializationFormat; use crate::prelude::IdentityNonce; use crate::state_transition::data_contract_update_transition::DataContractUpdateTransition; +use crate::ProtocolError; +use platform_value::Identifier; pub use v0::*; impl DataContractUpdateTransitionAccessorsV0 for DataContractUpdateTransition { - fn data_contract(&self) -> &DataContractInSerializationFormat { + fn data_contract(&self) -> Option<&DataContractInSerializationFormat> { match self { - DataContractUpdateTransition::V0(transition) => &transition.data_contract, + DataContractUpdateTransition::V0(transition) => Some(&transition.data_contract), + DataContractUpdateTransition::V1(_) => None, } } - fn set_data_contract(&mut self, data_contract: DataContractInSerializationFormat) { + fn set_data_contract( + &mut self, + data_contract: DataContractInSerializationFormat, + ) -> Result<(), ProtocolError> { match self { DataContractUpdateTransition::V0(transition) => { - transition.data_contract = data_contract + transition.data_contract = data_contract; + Ok(()) } + DataContractUpdateTransition::V1(_) => Err(ProtocolError::Generic( + "a delta-based data contract update transition embeds no contract to replace" + .to_string(), + )), } } fn identity_contract_nonce(&self) -> IdentityNonce { match self { DataContractUpdateTransition::V0(transition) => transition.identity_contract_nonce, + DataContractUpdateTransition::V1(transition) => transition.identity_contract_nonce, + } + } + + fn data_contract_id(&self) -> Identifier { + match self { + DataContractUpdateTransition::V0(transition) => transition.data_contract.id(), + DataContractUpdateTransition::V1(transition) => transition.data_contract_id, } } } diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/accessors/v0/mod.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/accessors/v0/mod.rs index 49907ccd405..2949276c791 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/accessors/v0/mod.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/accessors/v0/mod.rs @@ -1,9 +1,22 @@ use crate::data_contract::serialized_version::DataContractInSerializationFormat; use crate::prelude::IdentityNonce; +use crate::ProtocolError; +use platform_value::Identifier; pub trait DataContractUpdateTransitionAccessorsV0 { - fn data_contract(&self) -> &DataContractInSerializationFormat; - fn set_data_contract(&mut self, data_contract: DataContractInSerializationFormat); + /// The full contract a V0 update embeds. A delta-based V1 update carries + /// none: the updated contract only exists once the delta is merged onto + /// the stored one. + fn data_contract(&self) -> Option<&DataContractInSerializationFormat>; + /// Replaces the embedded contract of a V0 update. A V1 update has no + /// embedded contract to replace, and returns an error. + fn set_data_contract( + &mut self, + data_contract: DataContractInSerializationFormat, + ) -> Result<(), ProtocolError>; fn identity_contract_nonce(&self) -> IdentityNonce; + + /// The contract this update targets. + fn data_contract_id(&self) -> Identifier; } diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/identity_signed.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/identity_signed.rs index 50c8cb9ce4f..e98ac09f8fa 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/identity_signed.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/identity_signed.rs @@ -7,6 +7,7 @@ impl StateTransitionIdentitySigned for DataContractUpdateTransition { fn signature_public_key_id(&self) -> KeyID { match self { DataContractUpdateTransition::V0(transition) => transition.signature_public_key_id(), + DataContractUpdateTransition::V1(transition) => transition.signature_public_key_id(), } } @@ -15,6 +16,9 @@ impl StateTransitionIdentitySigned for DataContractUpdateTransition { DataContractUpdateTransition::V0(transition) => { transition.set_signature_public_key_id(key_id) } + DataContractUpdateTransition::V1(transition) => { + transition.set_signature_public_key_id(key_id) + } } } @@ -23,6 +27,9 @@ impl StateTransitionIdentitySigned for DataContractUpdateTransition { DataContractUpdateTransition::V0(transition) => { transition.security_level_requirement(purpose) } + DataContractUpdateTransition::V1(transition) => { + transition.security_level_requirement(purpose) + } } } } diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/methods/mod.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/methods/mod.rs index c34881479ea..5ad9400abdf 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/methods/mod.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/methods/mod.rs @@ -6,7 +6,7 @@ use crate::data_contract::DataContract; use crate::identity::signer::Signer; use crate::identity::{IdentityPublicKey, KeyID, PartialIdentity}; use crate::state_transition::data_contract_update_transition::{ - DataContractUpdateTransition, DataContractUpdateTransitionV0, + DataContractUpdateTransition, DataContractUpdateTransitionV0, DataContractUpdateTransitionV1, }; use crate::state_transition::StateTransition; use crate::version::FeatureVersion; @@ -16,6 +16,10 @@ use crate::prelude::{IdentityNonce, UserFeeIncrease}; use platform_version::version::PlatformVersion; impl DataContractUpdateTransitionMethodsV0 for DataContractUpdateTransition { + /// Always builds a full-contract (V0) transition: a lone contract can + /// not become a delta. Callers holding the stored contract should use + /// [`DataContractUpdateTransition::new_from_contract_update`], which + /// picks the form the platform version defaults to. async fn new_from_data_contract>( data_contract: DataContract, identity: &PartialIdentity, @@ -25,6 +29,48 @@ impl DataContractUpdateTransitionMethodsV0 for DataContractUpdateTransition { signer: &S, platform_version: &PlatformVersion, feature_version: Option, + ) -> Result { + match feature_version.unwrap_or(0) { + 0 => { + DataContractUpdateTransitionV0::new_from_data_contract( + data_contract, + identity, + key_id, + identity_contract_nonce, + user_fee_increase, + signer, + platform_version, + feature_version, + ) + .await + } + 1 => Err(ProtocolError::Generic( + "a delta-based (V1) data contract update needs the stored contract, use new_from_contract_update" + .to_string(), + )), + v => Err(ProtocolError::UnknownVersionError(format!( + "Unknown DataContractUpdateTransition version for new_from_data_contract {v}" + ))), + } + } +} + +impl DataContractUpdateTransition { + /// Builds and signs the update that turns `old_contract` into + /// `new_contract`, in the form `feature_version` names or, when it is + /// `None`, the form the platform version defaults to: a full-contract + /// V0 transition, or a delta-based V1 one. + #[allow(clippy::too_many_arguments)] + pub async fn new_from_contract_update>( + old_contract: &DataContract, + new_contract: &DataContract, + identity: &PartialIdentity, + key_id: KeyID, + identity_contract_nonce: IdentityNonce, + user_fee_increase: UserFeeIncrease, + signer: &S, + platform_version: &PlatformVersion, + feature_version: Option, ) -> Result { match feature_version.unwrap_or( platform_version @@ -35,7 +81,7 @@ impl DataContractUpdateTransitionMethodsV0 for DataContractUpdateTransition { ) { 0 => { DataContractUpdateTransitionV0::new_from_data_contract( - data_contract, + new_contract.clone(), identity, key_id, identity_contract_nonce, @@ -46,8 +92,20 @@ impl DataContractUpdateTransitionMethodsV0 for DataContractUpdateTransition { ) .await } + 1 => { + DataContractUpdateTransitionV1::new_from_contract_update( + old_contract, + new_contract, + identity, + key_id, + identity_contract_nonce, + user_fee_increase, + signer, + ) + .await + } v => Err(ProtocolError::UnknownVersionError(format!( - "Unknown DataContractUpdateTransition version for new_from_data_contract {v}" + "Unknown DataContractUpdateTransition version for new_from_contract_update {v}" ))), } } diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/mod.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/mod.rs index 9fb871aadf9..473a8c7eb0f 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/mod.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/mod.rs @@ -23,6 +23,7 @@ mod serialize; mod state_transition_estimated_fee_validation; mod state_transition_like; mod v0; +mod v1; mod version; pub use fields::*; @@ -34,8 +35,9 @@ use crate::data_contract::DataContract; use crate::identity::state_transition::OptionallyAssetLockProved; use crate::prelude::IdentityNonce; pub use v0::*; +pub use v1::*; -pub type DataContractUpdateTransitionLatest = DataContractUpdateTransitionV0; +pub type DataContractUpdateTransitionLatest = DataContractUpdateTransitionV1; #[cfg_attr( all(feature = "json-conversion", feature = "serde-conversion"), @@ -68,8 +70,13 @@ pub type DataContractUpdateTransitionLatest = DataContractUpdateTransitionV0; pub enum DataContractUpdateTransition { #[cfg_attr(feature = "serde-conversion", serde(rename = "0"))] V0(DataContractUpdateTransitionV0), + #[cfg_attr(feature = "serde-conversion", serde(rename = "1"))] + V1(DataContractUpdateTransitionV1), } +/// A lone contract can only become a full-contract (V0) update: the delta +/// form needs the stored contract too, see +/// [`DataContractUpdateTransition::from_contract_update`]. impl TryFromPlatformVersioned<(DataContract, IdentityNonce)> for DataContractUpdateTransition { type Error = ProtocolError; @@ -77,6 +84,22 @@ impl TryFromPlatformVersioned<(DataContract, IdentityNonce)> for DataContractUpd value: (DataContract, IdentityNonce), platform_version: &PlatformVersion, ) -> Result { + let data_contract_update_transition: DataContractUpdateTransitionV0 = + value.try_into_platform_versioned(platform_version)?; + Ok(data_contract_update_transition.into()) + } +} + +impl DataContractUpdateTransition { + /// Builds the unsigned update that turns `old_contract` into + /// `new_contract`, in the form the platform version defaults to: a + /// full-contract V0 transition, or a delta-based V1 one. + pub fn from_contract_update( + old_contract: &DataContract, + new_contract: &DataContract, + identity_contract_nonce: IdentityNonce, + platform_version: &PlatformVersion, + ) -> Result { match platform_version .dpp .state_transition_serialization_versions @@ -85,13 +108,19 @@ impl TryFromPlatformVersioned<(DataContract, IdentityNonce)> for DataContractUpd { 0 => { let data_contract_update_transition: DataContractUpdateTransitionV0 = - value.try_into_platform_versioned(platform_version)?; + (new_contract.clone(), identity_contract_nonce) + .try_into_platform_versioned(platform_version)?; Ok(data_contract_update_transition.into()) } + 1 => Ok(DataContractUpdateTransitionV1::from_contract_update( + old_contract, + new_contract, + identity_contract_nonce, + )? + .into()), version => Err(ProtocolError::UnknownVersionMismatch { - method: "DataContractUpdateTransition::try_from_platform_versioned(DataContract)" - .to_string(), - known_versions: vec![0], + method: "DataContractUpdateTransition::from_contract_update".to_string(), + known_versions: vec![0, 1], received: version, }), } @@ -125,7 +154,7 @@ mod test { use platform_version::version::PlatformVersion; use super::*; - use crate::data_contract::accessors::v0::DataContractV0Getters; + use crate::data_contract::accessors::v0::{DataContractV0Getters, DataContractV0Setters}; use crate::state_transition::{StateTransitionLike, StateTransitionOwned, StateTransitionType}; struct TestData { @@ -152,7 +181,7 @@ mod test { fn should_return_protocol_version() { let data = get_test_data(); assert_eq!( - LATEST_PLATFORM_VERSION + PlatformVersion::first() .dpp .state_transition_serialization_versions .contract_update_state_transition @@ -161,6 +190,38 @@ mod test { ) } + #[test] + fn should_build_a_delta_by_default_at_the_latest_platform_version() { + let platform_version = PlatformVersion::latest(); + let old_contract = get_data_contract_fixture(None, 0, platform_version.protocol_version) + .data_contract_owned(); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + + let state_transition = DataContractUpdateTransition::from_contract_update( + &old_contract, + &new_contract, + 1, + platform_version, + ) + .expect("expected a delta-based update transition"); + + assert_eq!( + LATEST_PLATFORM_VERSION + .dpp + .state_transition_serialization_versions + .contract_update_state_transition + .default_current_version, + state_transition.state_transition_protocol_version() + ); + assert!(matches!( + state_transition, + DataContractUpdateTransition::V1(_) + )); + assert_eq!(state_transition.data_contract_id(), old_contract.id()); + assert_eq!(state_transition.owner_id(), old_contract.owner_id()); + } + #[test] fn should_return_transition_type() { let data = get_test_data(); @@ -176,7 +237,10 @@ mod test { let data = get_test_data(); assert_eq!( - data.state_transition.data_contract().clone(), + data.state_transition + .data_contract() + .expect("a V0 update embeds its contract") + .clone(), data.data_contract .try_into_platform_versioned(PlatformVersion::first()) .unwrap() @@ -269,7 +333,9 @@ pub(crate) mod json_convertible_tests { } fn assert_v0_fields(t: &DataContractUpdateTransition) { - let DataContractUpdateTransition::V0(rec) = t; + let DataContractUpdateTransition::V0(rec) = t else { + panic!("expected a V0 update transition"); + }; assert_eq!(rec.identity_contract_nonce, 8, "identity_contract_nonce"); assert_eq!(rec.user_fee_increase, 5, "user_fee_increase"); assert_eq!(rec.signature_public_key_id, 1, "signature_public_key_id"); @@ -302,6 +368,131 @@ pub(crate) mod json_convertible_tests { assert_eq!(json["$formatVersion"], "0"); } + /// A delta holding each kind of field its two serialized forms write differently: the + /// nonce, identifiers, a group keyed by its position and members keyed by identity. + fn delta_fixture() -> DataContractUpdateTransition { + use crate::data_contract::group::v0::GroupV0; + use crate::data_contract::group::Group; + use crate::data_contract::update_values::DescriptionUpdate; + use crate::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; + use platform_value::Identifier; + use std::collections::BTreeMap; + + DataContractUpdateTransition::V1(DataContractUpdateTransitionV1 { + identity_contract_nonce: 8, + data_contract_id: Identifier::new([1; 32]), + owner_id: Identifier::new([2; 32]), + version: 2, + config: None, + updated_schema_defs: BTreeMap::new(), + new_schema_defs: BTreeMap::new(), + updated_document_schemas: BTreeMap::new(), + new_document_schemas: BTreeMap::new(), + new_groups: BTreeMap::from([( + 0, + Group::V0(GroupV0 { + members: BTreeMap::from([ + (Identifier::new([3; 32]), 1), + (Identifier::new([4; 32]), 1), + ]), + required_power: 2, + }), + )]), + new_tokens: BTreeMap::new(), + add_keywords: vec!["wallet".to_string()], + remove_keywords: vec![], + description: DescriptionUpdate::Set("a described contract".to_string()), + user_fee_increase: 5, + signature_public_key_id: 1, + signature: BinaryData::new(vec![0xff; 65]), + }) + } + + /// The JSON form of a delta, which the WASM bindings hand to JavaScript as it is: the + /// nonce a number while it is a safe integer, identifiers as base58 text, a group a + /// plain record under its position. + #[test] + fn should_write_a_delta_as_json_with_text_identifiers_and_a_numeric_nonce() { + use crate::serialization::JsonConvertible; + use platform_value::string_encoding::Encoding; + use platform_value::Identifier; + use serde_json::json; + + let original = delta_fixture(); + let json = JsonConvertible::to_json(&original).expect("to_json"); + + assert_eq!(json["$formatVersion"], "1"); + assert_eq!(json["$identity-contract-nonce"], json!(8)); + assert_eq!( + json["dataContractId"], + json!(Identifier::new([1; 32]).to_string(Encoding::Base58)) + ); + assert_eq!( + json["ownerId"], + json!(Identifier::new([2; 32]).to_string(Encoding::Base58)) + ); + assert_eq!(json["version"], json!(2)); + // A delta that keeps the stored config writes a null, not an absent field + assert_eq!(json.get("config"), Some(&serde_json::Value::Null)); + assert_eq!(json["newGroups"]["0"]["requiredPower"], json!(2)); + assert_eq!( + json["newGroups"]["0"]["members"][Identifier::new([3; 32]).to_string(Encoding::Base58)], + json!(1) + ); + assert_eq!(json["addKeywords"], json!(["wallet"])); + assert_eq!(json["description"], json!({"set": "a described contract"})); + + let recovered = + ::from_json(json).expect("from_json"); + assert_eq!(recovered, original); + } + + /// The object form of a delta, which the WASM bindings turn into a JavaScript object + /// value by value: identifiers are identifier values (bytes there, not wrapper + /// instances), the nonce an integer of 64 bits (a bigint there), a group a plain map. + /// A group's position is an integer key here; the bindings write and read it as text, + /// the form the group and token maps are read back in, as a contract's are. + #[test] + fn should_write_a_delta_as_an_object_with_byte_identifiers_and_a_plain_group() { + use crate::serialization::ValueConvertible; + use platform_value::{Identifier, Value}; + + let original = delta_fixture(); + let object = ValueConvertible::to_object(&original).expect("to_object"); + fn field_of<'a>(object: &'a Value, name: &'a str) -> &'a Value { + object + .get(name) + .expect("expected a map") + .unwrap_or_else(|| panic!("expected the field {name}")) + } + let field = |name: &'static str| field_of(&object, name); + + assert_eq!(field("$formatVersion"), &Value::Text("1".to_string())); + assert_eq!(field("$identity-contract-nonce"), &Value::U64(8)); + assert_eq!( + field("dataContractId"), + &Value::Identifier(Identifier::new([1; 32]).to_buffer()) + ); + assert_eq!( + field("ownerId"), + &Value::Identifier(Identifier::new([2; 32]).to_buffer()) + ); + let Value::Map(groups) = field("newGroups") else { + panic!("expected the new groups as a map"); + }; + let [(position, Value::Map(group))] = groups.as_slice() else { + panic!("expected one group, a plain map: {groups:?}"); + }; + assert_eq!( + position.to_integer::().expect("expected a position"), + 0 + ); + assert!(group.iter().any( + |(key, value)| key == &Value::Text("requiredPower".to_string()) + && value.to_integer::().ok() == Some(2) + )); + } + #[test] fn value_round_trip_with_envelope_wire_shape() { use crate::serialization::ValueConvertible; diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/state_transition_estimated_fee_validation.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/state_transition_estimated_fee_validation.rs index 26066ee8ee2..9cb2dccfc23 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/state_transition_estimated_fee_validation.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/state_transition_estimated_fee_validation.rs @@ -1,6 +1,5 @@ use crate::consensus::state::identity::IdentityInsufficientBalanceError; use crate::fee::Credits; -use crate::state_transition::data_contract_update_transition::accessors::DataContractUpdateTransitionAccessorsV0; use crate::state_transition::data_contract_update_transition::DataContractUpdateTransition; use crate::state_transition::{ StateTransitionEstimatedFeeValidation, StateTransitionIdentityEstimatedFeeValidation, @@ -20,7 +19,14 @@ impl StateTransitionEstimatedFeeValidation for DataContractUpdateTransition { .state_transition_min_fees .contract_update; - let registration_cost = self.data_contract().registration_cost(platform_version)?; + let registration_cost = match self { + DataContractUpdateTransition::V0(transition) => transition + .data_contract + .registration_cost(platform_version)?, + DataContractUpdateTransition::V1(transition) => { + transition.registration_cost(platform_version)? + } + }; Ok(base_fee.saturating_add(registration_cost)) } diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/state_transition_like.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/state_transition_like.rs index 9adfe22c523..fe816fd5948 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/state_transition_like.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/state_transition_like.rs @@ -12,24 +12,28 @@ impl StateTransitionLike for DataContractUpdateTransition { fn modified_data_ids(&self) -> Vec { match self { DataContractUpdateTransition::V0(transition) => transition.modified_data_ids(), + DataContractUpdateTransition::V1(transition) => transition.modified_data_ids(), } } fn state_transition_protocol_version(&self) -> FeatureVersion { match self { DataContractUpdateTransition::V0(_) => 0, + DataContractUpdateTransition::V1(_) => 1, } } /// returns the type of State Transition fn state_transition_type(&self) -> StateTransitionType { match self { DataContractUpdateTransition::V0(transition) => transition.state_transition_type(), + DataContractUpdateTransition::V1(transition) => transition.state_transition_type(), } } fn unique_identifiers(&self) -> Vec { match self { DataContractUpdateTransition::V0(transition) => transition.unique_identifiers(), + DataContractUpdateTransition::V1(transition) => transition.unique_identifiers(), } } } @@ -38,6 +42,7 @@ impl StateTransitionHasUserFeeIncrease for DataContractUpdateTransition { fn user_fee_increase(&self) -> UserFeeIncrease { match self { DataContractUpdateTransition::V0(transition) => transition.user_fee_increase(), + DataContractUpdateTransition::V1(transition) => transition.user_fee_increase(), } } @@ -46,6 +51,9 @@ impl StateTransitionHasUserFeeIncrease for DataContractUpdateTransition { DataContractUpdateTransition::V0(transition) => { transition.set_user_fee_increase(user_fee_increase) } + DataContractUpdateTransition::V1(transition) => { + transition.set_user_fee_increase(user_fee_increase) + } } } } @@ -55,12 +63,14 @@ impl StateTransitionSingleSigned for DataContractUpdateTransition { fn signature(&self) -> &BinaryData { match self { DataContractUpdateTransition::V0(transition) => transition.signature(), + DataContractUpdateTransition::V1(transition) => transition.signature(), } } /// set a new signature fn set_signature(&mut self, signature: BinaryData) { match self { DataContractUpdateTransition::V0(transition) => transition.set_signature(signature), + DataContractUpdateTransition::V1(transition) => transition.set_signature(signature), } } @@ -69,6 +79,9 @@ impl StateTransitionSingleSigned for DataContractUpdateTransition { DataContractUpdateTransition::V0(transition) => { transition.set_signature_bytes(signature) } + DataContractUpdateTransition::V1(transition) => { + transition.set_signature_bytes(signature) + } } } } @@ -77,6 +90,7 @@ impl StateTransitionOwned for DataContractUpdateTransition { fn owner_id(&self) -> Identifier { match self { DataContractUpdateTransition::V0(transition) => transition.owner_id(), + DataContractUpdateTransition::V1(transition) => transition.owner_id(), } } } diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/identity_signed.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/identity_signed.rs new file mode 100644 index 00000000000..ebceb709e93 --- /dev/null +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/identity_signed.rs @@ -0,0 +1,18 @@ +use crate::identity::SecurityLevel::CRITICAL; +use crate::identity::{KeyID, Purpose, SecurityLevel}; +use crate::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; +use crate::state_transition::StateTransitionIdentitySigned; + +impl StateTransitionIdentitySigned for DataContractUpdateTransitionV1 { + fn signature_public_key_id(&self) -> KeyID { + self.signature_public_key_id + } + + fn set_signature_public_key_id(&mut self, key_id: KeyID) { + self.signature_public_key_id = key_id + } + + fn security_level_requirement(&self, _purpose: Purpose) -> Vec { + vec![CRITICAL] + } +} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/mod.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/mod.rs new file mode 100644 index 00000000000..5f0db7125d9 --- /dev/null +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/mod.rs @@ -0,0 +1,898 @@ +mod identity_signed; +mod overlapping_entry; +mod registration_cost; +mod state_transition_like; +mod types; +pub(super) mod v1_methods; +mod version; + +use std::collections::BTreeMap; + +#[cfg(feature = "json-conversion")] +use crate::serialization::json_safe_fields; +use bincode::{Decode, DecodeUntrusted, Encode}; +use platform_serialization_derive::PlatformSignable; +use platform_value::{BinaryData, Identifier, Value}; +#[cfg(feature = "serde-conversion")] +use serde::{Deserialize, Serialize}; + +use crate::data_contract::accessors::v0::DataContractV0Getters; +use crate::data_contract::accessors::v1::DataContractV1Getters; +use crate::data_contract::associated_token::token_configuration::TokenConfiguration; +use crate::data_contract::config::DataContractConfig; +use crate::data_contract::group::Group; +use crate::data_contract::schema::DataContractSchemaMethodsV0; +#[cfg(feature = "serde-conversion")] +use crate::data_contract::serialized_version::{ + deserialize_u16_group_map, deserialize_u16_token_configuration_map, +}; +use crate::data_contract::update_values::{DataContractUpdateValues, DescriptionUpdate}; +use crate::data_contract::{ + DataContract, DefinitionName, DocumentName, GroupContractPosition, TokenContractPosition, +}; +use crate::identity::KeyID; +use crate::prelude::{IdentityNonce, UserFeeIncrease}; +use crate::state_transition::data_contract_update_transition::{ + DataContractUpdateTransition, DataContractUpdateTransitionV0, +}; +use crate::state_transition::StateTransition; +use crate::validation::ConsensusValidationResult; +use crate::{NonConsensusError, ProtocolError}; +use platform_version::version::PlatformVersion; + +/// A delta contract update: version 1 of the data contract update transition, from protocol +/// version 15. +/// +/// Version 0 carries the whole contract. This one carries only what the update changes: new +/// and replaced document schemas and shared definitions, new groups and tokens, added and +/// removed keywords, and optionally a description or a config. A node reads the stored +/// contract, merges the delta onto it with +/// [`DataContract::apply_update`](crate::data_contract::DataContract::apply_update), and holds +/// the result to every rule of an update that carries the whole contract. +/// +/// As a transition is capped well below the size a contract may take, version 0 cannot grow a +/// contract past the transition cap. A delta can, a transition at a time, up to +/// `max_serialized_size`. +/// +/// The contract id and the owner are fields of their own because nothing else in the +/// transition carries them; the owner must be the stored contract's owner. +#[cfg_attr(feature = "json-conversion", json_safe_fields)] +#[derive(Debug, Clone, Encode, Decode, DecodeUntrusted, PartialEq, PlatformSignable)] +#[cfg_attr( + feature = "serde-conversion", + derive(Serialize, Deserialize), + serde(rename_all = "camelCase") +)] +pub struct DataContractUpdateTransitionV1 { + #[cfg_attr( + feature = "serde-conversion", + serde(rename = "$identity-contract-nonce") + )] + pub identity_contract_nonce: IdentityNonce, + /// The contract being updated. + pub data_contract_id: Identifier, + /// The identity submitting the update; it must own the contract. + pub owner_id: Identifier, + /// The contract version this update produces: the stored version plus one. + pub version: u32, + /// A replacement config, or `None` to keep the stored one. + #[cfg_attr(feature = "serde-conversion", serde(default))] + pub config: Option, + /// New schemas for existing shared `$defs` definitions. + #[cfg_attr(feature = "serde-conversion", serde(default))] + pub updated_schema_defs: BTreeMap, + /// Shared `$defs` definitions to add. + #[cfg_attr(feature = "serde-conversion", serde(default))] + pub new_schema_defs: BTreeMap, + /// New schemas for existing document types. + #[cfg_attr(feature = "serde-conversion", serde(default))] + pub updated_document_schemas: BTreeMap, + /// Document types to add. + #[cfg_attr(feature = "serde-conversion", serde(default))] + pub new_document_schemas: BTreeMap, + /// Groups to add; positions continue the stored ones. + #[cfg_attr( + feature = "serde-conversion", + serde(default, deserialize_with = "deserialize_u16_group_map") + )] + pub new_groups: BTreeMap, + /// Tokens to add; positions continue the stored ones. + #[cfg_attr( + feature = "serde-conversion", + serde(default, deserialize_with = "deserialize_u16_token_configuration_map") + )] + pub new_tokens: BTreeMap, + /// Keywords to add. + #[cfg_attr(feature = "serde-conversion", serde(default))] + pub add_keywords: Vec, + /// Keywords to remove. + #[cfg_attr(feature = "serde-conversion", serde(default))] + pub remove_keywords: Vec, + /// What to do with the description. + #[cfg_attr(feature = "serde-conversion", serde(default))] + pub description: DescriptionUpdate, + pub user_fee_increase: UserFeeIncrease, + #[platform_signable(exclude_from_sig_hash)] + pub signature_public_key_id: KeyID, + #[platform_signable(exclude_from_sig_hash)] + pub signature: BinaryData, +} + +impl From for StateTransition { + fn from(value: DataContractUpdateTransitionV1) -> Self { + let transition: DataContractUpdateTransition = value.into(); + transition.into() + } +} + +impl From<&DataContractUpdateTransitionV1> for StateTransition { + fn from(value: &DataContractUpdateTransitionV1) -> Self { + let transition: DataContractUpdateTransition = value.clone().into(); + transition.into() + } +} + +impl<'a> From<&'a DataContractUpdateTransitionV1> for DataContractUpdateValues<'a> { + fn from(transition: &'a DataContractUpdateTransitionV1) -> Self { + DataContractUpdateValues { + owner_id: transition.owner_id, + version: transition.version, + config: transition.config.as_ref(), + updated_schema_defs: &transition.updated_schema_defs, + new_schema_defs: &transition.new_schema_defs, + updated_document_schemas: &transition.updated_document_schemas, + new_document_schemas: &transition.new_document_schemas, + new_groups: &transition.new_groups, + new_tokens: &transition.new_tokens, + add_keywords: &transition.add_keywords, + remove_keywords: &transition.remove_keywords, + description: &transition.description, + } + } +} + +impl DataContractUpdateTransitionV1 { + /// The update carrying the whole contract that this delta stands for on `stored_contract`: + /// the delta merged onto it by [`DataContract::apply_update`], under the delta's nonce, + /// fee increase and signature. A node validates that update in the delta's place, so a + /// delta is held to every rule of an update that carries the whole contract. Its signature + /// is the delta's, which signs the delta and not this update, and is checked on the delta. + /// + /// # Returns + /// - The update, or the consensus error that says why the delta does not fit the stored + /// contract. + /// - `Err(ProtocolError)` when `platform_version` predates delta contract updates. + pub fn to_full_contract_update( + &self, + stored_contract: &DataContract, + platform_version: &PlatformVersion, + ) -> Result, ProtocolError> { + Ok(stored_contract + .apply_update(self.into(), platform_version)? + .map(|data_contract| DataContractUpdateTransitionV0 { + identity_contract_nonce: self.identity_contract_nonce, + data_contract, + user_fee_increase: self.user_fee_increase, + signature_public_key_id: self.signature_public_key_id, + signature: self.signature.clone(), + })) + } +} + +fn not_expressible(what: String) -> ProtocolError { + ProtocolError::NonConsensusError(NonConsensusError::StateTransitionCreationError(format!( + "a delta contract update cannot express this change: {what}" + ))) +} + +impl DataContractUpdateTransitionV1 { + /// Computes the delta that turns `old_contract`, the stored contract, into `new_contract`. + /// + /// The result is unsigned, with a zero key id and fee increase. A change a delta cannot + /// express is refused here: a removed document type, schema definition, group or token, a + /// changed group or token, another contract id (none of which a contract update may make + /// in either form), reordered keywords, or an empty `$defs` map that appears or + /// disappears. + /// + /// A document schema or schema definition is left out of the delta only when it is + /// exactly the stored value, which keeps the delta merged onto `old_contract` equal to + /// `new_contract`. A value says how each of its integers is typed, and JSON does not: a + /// schema that went through JSON may hold a 64-bit integer where the stored one holds a + /// 32-bit one, and it then counts as replaced, sent again and paid for again. A caller + /// that assembles `new_contract` from JSON keeps the stored value of every schema it + /// does not change. + pub fn from_contract_update( + old_contract: &DataContract, + new_contract: &DataContract, + identity_contract_nonce: IdentityNonce, + ) -> Result { + if old_contract.id() != new_contract.id() { + return Err(not_expressible(format!( + "contract id {} differs from {}", + new_contract.id(), + old_contract.id() + ))); + } + + let old_document_schemas = old_contract.document_schemas(); + let new_document_schemas_all = new_contract.document_schemas(); + let mut updated_document_schemas = BTreeMap::new(); + let mut new_document_schemas = BTreeMap::new(); + for (name, schema) in &new_document_schemas_all { + match old_document_schemas.get(name) { + Some(old_schema) if *old_schema == *schema => {} + Some(_) => { + updated_document_schemas.insert(name.clone(), (*schema).clone()); + } + None => { + new_document_schemas.insert(name.clone(), (*schema).clone()); + } + } + } + if let Some(removed) = old_document_schemas + .keys() + .find(|name| !new_document_schemas_all.contains_key(*name)) + { + return Err(not_expressible(format!( + "document type '{removed}' was removed" + ))); + } + + // `$defs` is optional, and an absent map is not the contract an empty one is. The + // merge creates the map with the first definition it adds and never removes it, so a + // delta can neither add an empty map nor drop one. A validated contract never holds an + // empty one, so only an unvalidated input gets here. + if old_contract.schema_defs().is_none() != new_contract.schema_defs().is_none() + && new_contract.schema_defs().is_none_or(BTreeMap::is_empty) + { + return Err(not_expressible( + "the presence of the schema definitions map changed without a definition being added" + .to_string(), + )); + } + + let empty_definitions = BTreeMap::new(); + let old_schema_defs = old_contract.schema_defs().unwrap_or(&empty_definitions); + let new_schema_defs_all = new_contract.schema_defs().unwrap_or(&empty_definitions); + let mut updated_schema_defs = BTreeMap::new(); + let mut new_schema_defs = BTreeMap::new(); + for (name, definition) in new_schema_defs_all { + match old_schema_defs.get(name) { + Some(old_definition) if old_definition == definition => {} + Some(_) => { + updated_schema_defs.insert(name.clone(), definition.clone()); + } + None => { + new_schema_defs.insert(name.clone(), definition.clone()); + } + } + } + if let Some(removed) = old_schema_defs + .keys() + .find(|name| !new_schema_defs_all.contains_key(*name)) + { + return Err(not_expressible(format!( + "schema definition '{removed}' was removed" + ))); + } + + let mut new_groups = BTreeMap::new(); + for (position, group) in new_contract.groups() { + match old_contract.groups().get(position) { + Some(old_group) if old_group == group => {} + Some(_) => { + return Err(not_expressible(format!( + "group at position {position} was changed" + ))) + } + None => { + new_groups.insert(*position, group.clone()); + } + } + } + if let Some(removed) = old_contract + .groups() + .keys() + .find(|position| !new_contract.groups().contains_key(*position)) + { + return Err(not_expressible(format!( + "group at position {removed} was removed" + ))); + } + + let mut new_tokens = BTreeMap::new(); + for (position, token) in new_contract.tokens() { + match old_contract.tokens().get(position) { + Some(old_token) if old_token == token => {} + Some(_) => { + return Err(not_expressible(format!( + "token at position {position} was changed" + ))) + } + None => { + new_tokens.insert(*position, token.clone()); + } + } + } + if let Some(removed) = old_contract + .tokens() + .keys() + .find(|position| !new_contract.tokens().contains_key(*position)) + { + return Err(not_expressible(format!( + "token at position {removed} was removed" + ))); + } + + let remove_keywords: Vec = old_contract + .keywords() + .iter() + .filter(|keyword| !new_contract.keywords().contains(*keyword)) + .cloned() + .collect(); + let add_keywords: Vec = new_contract + .keywords() + .iter() + .filter(|keyword| !old_contract.keywords().contains(*keyword)) + .cloned() + .collect(); + // The merge keeps the stored order of the keywords it leaves in place and appends the + // added ones, so any other order in the new contract would be silently lost + let mut applied_keywords: Vec = old_contract + .keywords() + .iter() + .filter(|keyword| !remove_keywords.contains(*keyword)) + .cloned() + .collect(); + applied_keywords.extend(add_keywords.iter().cloned()); + if applied_keywords != *new_contract.keywords() { + return Err(not_expressible( + "keywords were reordered; a delta keeps the stored order of the keywords it \ + leaves in place and appends the ones it adds" + .to_string(), + )); + } + + let description = match (old_contract.description(), new_contract.description()) { + (old, new) if old == new => DescriptionUpdate::Keep, + (_, None) => DescriptionUpdate::Clear, + (_, Some(new)) => DescriptionUpdate::Set(new.clone()), + }; + + let config = + (old_contract.config() != new_contract.config()).then(|| new_contract.config().clone()); + + Ok(DataContractUpdateTransitionV1 { + identity_contract_nonce, + data_contract_id: new_contract.id(), + owner_id: new_contract.owner_id(), + version: new_contract.version(), + config, + updated_schema_defs, + new_schema_defs, + updated_document_schemas, + new_document_schemas, + new_groups, + new_tokens, + add_keywords, + remove_keywords, + description, + user_fee_increase: 0, + signature_public_key_id: 0, + signature: Default::default(), + }) + } +} + +#[cfg(all(test, feature = "validation"))] +mod tests { + use super::*; + use crate::consensus::basic::data_contract::DataContractUpdateEntryKind; + use crate::consensus::state::state_error::StateError; + use crate::consensus::ConsensusError; + use crate::data_contract::accessors::v0::DataContractV0Setters; + use crate::data_contract::accessors::v1::DataContractV1Setters; + use crate::data_contract::group::v0::GroupV0; + use crate::data_contract::serialized_version::{ + DataContractInSerializationFormat, DataContractMismatch, + }; + use crate::serialization::{PlatformDeserializableUntrusted, PlatformSerializable}; + use crate::tests::fixtures::get_data_contract_fixture; + use assert_matches::assert_matches; + use platform_value::platform_value; + use platform_version::TryIntoPlatformVersioned; + + fn contracts() -> (DataContract, DataContract, &'static PlatformVersion) { + let platform_version = PlatformVersion::latest(); + let old_contract = get_data_contract_fixture(None, 0, platform_version.protocol_version) + .data_contract_owned(); + let new_contract = old_contract.clone(); + (old_contract, new_contract, platform_version) + } + + fn new_document_schema() -> Value { + platform_value!({ + "type": "object", + "properties": { + "name": { + "type": "string", + "position": 0 + } + }, + "additionalProperties": false + }) + } + + fn delta_between( + old_contract: &DataContract, + new_contract: &DataContract, + ) -> DataContractUpdateTransitionV1 { + DataContractUpdateTransitionV1::from_contract_update(old_contract, new_contract, 1) + .expect("expected the update to be expressible as a delta") + } + + fn merge( + old_contract: &DataContract, + delta: &DataContractUpdateTransitionV1, + ) -> ConsensusValidationResult { + old_contract + .apply_update(delta.into(), PlatformVersion::latest()) + .expect("expected the merge to be active at the latest protocol version") + } + + fn merged( + old_contract: &DataContract, + delta: &DataContractUpdateTransitionV1, + ) -> DataContractInSerializationFormat { + let result = merge(old_contract, delta); + assert!(result.is_valid(), "unexpected errors: {:?}", result.errors); + result.into_data().expect("expected the merged contract") + } + + fn format(contract: &DataContract) -> DataContractInSerializationFormat { + contract + .clone() + .try_into_platform_versioned(PlatformVersion::latest()) + .expect("expected the contract in the format transitions carry") + } + + /// The fixture contract with one document type that references no definition and the + /// given `$defs`, built without validation, which a contract holding an empty `$defs` map + /// does not pass. + fn contract_with_schema_defs( + base: &DataContract, + schema_defs: Option>, + ) -> DataContract { + let platform_version = PlatformVersion::latest(); + let DataContractInSerializationFormat::V1(mut v1) = format(base) else { + panic!("expected the latest protocol version to carry contracts in format version 1"); + }; + v1.document_schemas = BTreeMap::from([("note".to_string(), new_document_schema())]); + v1.schema_defs = schema_defs; + DataContract::try_from_platform_versioned( + DataContractInSerializationFormat::V1(v1), + false, + &mut vec![], + platform_version, + ) + .expect("expected an unvalidated contract with the given schema definitions") + } + + fn assert_not_expressible( + result: Result, + reason: &str, + ) { + assert_matches!( + result, + Err(ProtocolError::NonConsensusError( + NonConsensusError::StateTransitionCreationError(message) + )) if message.contains(reason) + ); + } + + #[test] + fn should_build_an_empty_delta_for_a_version_bump() { + let (old_contract, mut new_contract, _) = contracts(); + new_contract.increment_version(); + + let delta = + DataContractUpdateTransitionV1::from_contract_update(&old_contract, &new_contract, 5) + .expect("expected a delta"); + + assert_eq!(delta.identity_contract_nonce, 5); + assert_eq!(delta.data_contract_id, old_contract.id()); + assert_eq!(delta.owner_id, old_contract.owner_id()); + assert_eq!(delta.version, new_contract.version()); + assert!(delta.config.is_none()); + assert!(delta.updated_schema_defs.is_empty()); + assert!(delta.new_schema_defs.is_empty()); + assert!(delta.updated_document_schemas.is_empty()); + assert!(delta.new_document_schemas.is_empty()); + assert!(delta.new_groups.is_empty()); + assert!(delta.new_tokens.is_empty()); + assert!(delta.add_keywords.is_empty()); + assert!(delta.remove_keywords.is_empty()); + assert_eq!(delta.description, DescriptionUpdate::Keep); + } + + #[test] + fn should_merge_into_the_contract_the_delta_was_built_from() { + let (old_contract, mut new_contract, platform_version) = contracts(); + new_contract.increment_version(); + new_contract + .set_document_schema( + "newType", + new_document_schema(), + true, + &mut vec![], + platform_version, + ) + .expect("expected to add a document type"); + let mut replaced_schema = old_contract + .document_schemas() + .get("niceDocument") + .cloned() + .cloned() + .expect("expected the fixture's niceDocument type"); + replaced_schema + .set_value("description", Value::Text("a nicer document".to_string())) + .expect("expected to describe the type"); + new_contract + .set_document_schema( + "niceDocument", + replaced_schema, + true, + &mut vec![], + platform_version, + ) + .expect("expected to replace a document type"); + new_contract.add_group( + 0, + Group::V0(GroupV0 { + members: [(old_contract.owner_id(), 1), (Identifier::random(), 1)] + .into_iter() + .collect(), + required_power: 2, + }), + ); + new_contract.set_keywords(vec!["alpha".to_string(), "beta".to_string()]); + new_contract.set_description(Some("a described contract".to_string())); + + let delta = delta_between(&old_contract, &new_contract); + + assert_eq!( + delta.new_document_schemas.keys().collect::>(), + ["newType"] + ); + assert_eq!( + delta.updated_document_schemas.keys().collect::>(), + ["niceDocument"] + ); + assert_eq!(delta.new_groups.len(), 1); + assert_eq!(delta.add_keywords, ["alpha", "beta"]); + assert_eq!( + delta.description, + DescriptionUpdate::Set("a described contract".to_string()) + ); + assert_eq!( + merged(&old_contract, &delta).first_mismatch(&format(&new_contract)), + None + ); + } + + /// The merge leaves the time fields to its caller: a block stamps the update's, and the + /// verification of an execution proof does not compare them. + #[test] + fn should_keep_the_stored_time_fields_when_merged() { + let (mut old_contract, _, _) = contracts(); + old_contract.set_created_at(Some(1_700_000_000_000)); + old_contract.set_updated_at(Some(1_700_000_100_000)); + old_contract.set_created_at_block_height(Some(40)); + old_contract.set_updated_at_block_height(Some(41)); + old_contract.set_created_at_epoch(Some(2)); + old_contract.set_updated_at_epoch(Some(3)); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + + let DataContractInSerializationFormat::V1(merged) = + merged(&old_contract, &delta_between(&old_contract, &new_contract)) + else { + panic!("expected generation 0 of the merge to build format version 1"); + }; + + assert_eq!(merged.version, new_contract.version()); + assert_eq!(merged.created_at, Some(1_700_000_000_000)); + assert_eq!(merged.updated_at, Some(1_700_000_100_000)); + assert_eq!(merged.created_at_block_height, Some(40)); + assert_eq!(merged.updated_at_block_height, Some(41)); + assert_eq!(merged.created_at_epoch, Some(2)); + assert_eq!(merged.updated_at_epoch, Some(3)); + } + + #[test] + fn should_express_removed_keywords_and_a_cleared_description() { + let (mut old_contract, _, _) = contracts(); + old_contract.set_keywords(vec!["alpha".to_string(), "beta".to_string()]); + old_contract.set_description(Some("old description".to_string())); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + new_contract.set_keywords(vec!["beta".to_string(), "gamma".to_string()]); + new_contract.set_description(None); + + let delta = delta_between(&old_contract, &new_contract); + + assert_eq!(delta.remove_keywords, ["alpha"]); + assert_eq!(delta.add_keywords, ["gamma"]); + assert_eq!(delta.description, DescriptionUpdate::Clear); + let merged = merged(&old_contract, &delta); + assert_eq!(merged.first_mismatch(&format(&new_contract)), None); + // the stored contract is not what the delta asks for + assert_eq!( + merged.first_mismatch(&format(&old_contract)), + Some(DataContractMismatch::Version) + ); + } + + #[test] + fn should_keep_the_stored_keyword_order_and_append_the_added_ones() { + let (mut old_contract, _, _) = contracts(); + old_contract.set_keywords(vec![ + "one".to_string(), + "two".to_string(), + "three".to_string(), + ]); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + new_contract.set_keywords(vec![ + "one".to_string(), + "three".to_string(), + "four".to_string(), + ]); + + let delta = delta_between(&old_contract, &new_contract); + + assert_eq!(delta.remove_keywords, ["two"]); + assert_eq!(delta.add_keywords, ["four"]); + assert_eq!( + merged(&old_contract, &delta).keywords(), + new_contract.keywords() + ); + } + + #[test] + fn should_refuse_to_build_a_delta_that_reorders_keywords() { + let (mut old_contract, _, _) = contracts(); + old_contract.set_keywords(vec!["one".to_string(), "two".to_string()]); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + new_contract.set_keywords(vec!["two".to_string(), "one".to_string()]); + + assert_not_expressible( + DataContractUpdateTransitionV1::from_contract_update(&old_contract, &new_contract, 1), + "keywords were reordered", + ); + } + + #[test] + fn should_refuse_to_build_a_delta_that_removes_a_document_type() { + let (mut old_contract, new_contract, platform_version) = contracts(); + old_contract + .set_document_schema( + "extraType", + new_document_schema(), + true, + &mut vec![], + platform_version, + ) + .expect("expected to add a document type"); + + assert_not_expressible( + DataContractUpdateTransitionV1::from_contract_update(&old_contract, &new_contract, 1), + "document type 'extraType' was removed", + ); + } + + #[test] + fn should_express_the_first_schema_definition_of_a_contract() { + let (base, _, _) = contracts(); + let old_contract = contract_with_schema_defs(&base, None); + let definitions = + BTreeMap::from([("label".to_string(), platform_value!({"type": "string"}))]); + let mut new_contract = contract_with_schema_defs(&base, Some(definitions.clone())); + new_contract.increment_version(); + + let delta = delta_between(&old_contract, &new_contract); + + assert_eq!(delta.new_schema_defs, definitions); + assert!(delta.updated_schema_defs.is_empty()); + assert_eq!( + merged(&old_contract, &delta).first_mismatch(&format(&new_contract)), + None + ); + } + + /// A delta creates `$defs` with the first definition it adds and never removes it, so an + /// empty map can neither appear nor disappear. Without the refusal the delta would be + /// empty and merge into another contract than the one asked for. + #[test] + fn should_refuse_to_build_a_delta_that_adds_or_drops_an_empty_schema_definitions_map() { + let (base, _, _) = contracts(); + for (old_definitions, new_definitions) in + [(None, Some(BTreeMap::new())), (Some(BTreeMap::new()), None)] + { + let old_contract = contract_with_schema_defs(&base, old_definitions); + let mut new_contract = contract_with_schema_defs(&base, new_definitions); + new_contract.increment_version(); + + assert_not_expressible( + DataContractUpdateTransitionV1::from_contract_update( + &old_contract, + &new_contract, + 1, + ), + "presence of the schema definitions map", + ); + } + } + + #[test] + fn should_not_merge_a_delta_of_an_identity_that_does_not_own_the_contract() { + let (old_contract, mut new_contract, _) = contracts(); + new_contract.increment_version(); + let mut delta = delta_between(&old_contract, &new_contract); + delta.owner_id = Identifier::random(); + + let result = merge(&old_contract, &delta); + + assert_matches!( + result.errors.as_slice(), + [ConsensusError::StateError(StateError::DataContractUpdatePermissionError(e))] + if *e.data_contract_id() == old_contract.id() && *e.identity_id() == delta.owner_id + ); + } + + #[test] + fn should_not_merge_a_new_entry_the_contract_already_has() { + let (mut old_contract, _, _) = contracts(); + old_contract.set_keywords(vec!["alpha".to_string()]); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + let delta = delta_between(&old_contract, &new_contract); + + let mut with_document_type = delta.clone(); + with_document_type + .new_document_schemas + .insert("niceDocument".to_string(), new_document_schema()); + let mut with_keyword = delta; + with_keyword.add_keywords.push("alpha".to_string()); + + for (delta, kind, name) in [ + ( + with_document_type, + DataContractUpdateEntryKind::DocumentType, + "niceDocument", + ), + (with_keyword, DataContractUpdateEntryKind::Keyword, "alpha"), + ] { + assert_matches!( + merge(&old_contract, &delta).errors.as_slice(), + [ConsensusError::StateError(StateError::DataContractUpdateEntryAlreadyExistsError(e))] + if e.entry_kind() == kind && e.name() == name + ); + } + } + + #[test] + fn should_not_merge_a_replaced_or_removed_entry_the_contract_does_not_have() { + let (old_contract, mut new_contract, _) = contracts(); + new_contract.increment_version(); + let delta = delta_between(&old_contract, &new_contract); + + let mut with_document_type = delta.clone(); + with_document_type + .updated_document_schemas + .insert("missingType".to_string(), new_document_schema()); + let mut with_definition = delta.clone(); + with_definition.updated_schema_defs.insert( + "missingDefinition".to_string(), + platform_value!({"type": "string"}), + ); + let mut with_keyword = delta; + with_keyword.remove_keywords.push("ghost".to_string()); + + for (delta, kind, name) in [ + ( + with_document_type, + DataContractUpdateEntryKind::DocumentType, + "missingType", + ), + ( + with_definition, + DataContractUpdateEntryKind::SchemaDef, + "missingDefinition", + ), + (with_keyword, DataContractUpdateEntryKind::Keyword, "ghost"), + ] { + assert_matches!( + merge(&old_contract, &delta).errors.as_slice(), + [ConsensusError::StateError(StateError::DataContractUpdateEntryNotFoundError(e))] + if e.entry_kind() == kind && e.name() == name + ); + } + } + + #[test] + fn should_not_merge_before_protocol_version_15() { + let (old_contract, mut new_contract, _) = contracts(); + new_contract.increment_version(); + let delta = delta_between(&old_contract, &new_contract); + let platform_version_14 = + PlatformVersion::get(14).expect("expected protocol version 14 to exist"); + + assert_matches!( + old_contract.apply_update((&delta).into(), platform_version_14), + Err(ProtocolError::UnknownVersionError(message)) if message.contains("not active") + ); + } + + #[test] + fn should_round_trip_through_the_wire_format() { + let (old_contract, mut new_contract, platform_version) = contracts(); + new_contract.increment_version(); + new_contract + .set_document_schema( + "newType", + new_document_schema(), + true, + &mut vec![], + platform_version, + ) + .expect("expected to add a document type"); + new_contract.set_keywords(vec!["alpha".to_string()]); + new_contract.set_description(Some("a described contract".to_string())); + + let delta = delta_between(&old_contract, &new_contract); + let state_transition: StateTransition = delta.clone().into(); + + let bytes = state_transition + .serialize_to_bytes() + .expect("expected to serialize the delta"); + let recovered = StateTransition::deserialize_from_bytes_untrusted(&bytes) + .expect("expected to deserialize the delta"); + + assert_matches!( + recovered, + StateTransition::DataContractUpdate(DataContractUpdateTransition::V1(recovered)) + if recovered == delta + ); + } + + /// A delta is refused at decode before protocol version 15, without a fee, as software + /// that predates it refuses it. + #[test] + fn should_be_active_from_protocol_version_15_only() { + let (old_contract, mut new_contract, _) = contracts(); + new_contract.increment_version(); + let state_transition: StateTransition = delta_between(&old_contract, &new_contract).into(); + let bytes = state_transition + .serialize_to_bytes() + .expect("expected to serialize the delta"); + + assert_matches!( + StateTransition::deserialize_from_bytes_untrusted_in_version( + &bytes, + PlatformVersion::get(14).expect("expected protocol version 14 to exist"), + ), + Err(ProtocolError::StateTransitionError(_)) + ); + assert_matches!( + StateTransition::deserialize_from_bytes_untrusted_in_version( + &bytes, + PlatformVersion::get(15).expect("expected protocol version 15 to exist"), + ), + Ok(StateTransition::DataContractUpdate( + DataContractUpdateTransition::V1(_) + )) + ); + } +} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/overlapping_entry.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/overlapping_entry.rs new file mode 100644 index 00000000000..8634e815e55 --- /dev/null +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/overlapping_entry.rs @@ -0,0 +1,123 @@ +use crate::consensus::basic::data_contract::{ + DataContractUpdateEntryKind, DataContractUpdateOverlappingEntriesError, +}; +use crate::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; +use std::collections::BTreeSet; + +impl DataContractUpdateTransitionV1 { + /// Names the first entry this delta lists in two sections that can not + /// both apply: a document type or schema definition that is both new + /// and updated, or a keyword that is both added and removed. + /// + /// Basic structure validation rejects such a delta with this error and + /// proof verification refuses to verify one, so one check answers both. + /// + /// Basic structure validation runs before a transition's signature is + /// checked, on lists as long as a state transition lets them be, so the + /// work here grows with the size of the delta and not with its square. + pub fn overlapping_entry(&self) -> Option { + let contract_id = self.data_contract_id; + + if let Some(name) = self + .updated_document_schemas + .keys() + .find(|name| self.new_document_schemas.contains_key(*name)) + { + return Some(DataContractUpdateOverlappingEntriesError::new( + contract_id, + DataContractUpdateEntryKind::DocumentType, + name.clone(), + )); + } + + if let Some(name) = self + .updated_schema_defs + .keys() + .find(|name| self.new_schema_defs.contains_key(*name)) + { + return Some(DataContractUpdateOverlappingEntriesError::new( + contract_id, + DataContractUpdateEntryKind::SchemaDef, + name.clone(), + )); + } + + // The removed keywords are looked up in a set: scanning their list for every + // added keyword would cost the product of the two lengths, millions of + // comparisons for lists that fit one transition. The added keywords are still + // read in order, so the first of them that is also removed is the one named. + let removed_keywords: BTreeSet<&String> = self.remove_keywords.iter().collect(); + if let Some(keyword) = self + .add_keywords + .iter() + .find(|keyword| removed_keywords.contains(keyword)) + { + return Some(DataContractUpdateOverlappingEntriesError::new( + contract_id, + DataContractUpdateEntryKind::Keyword, + keyword.clone(), + )); + } + + None + } +} + +#[cfg(test)] +mod tests { + use super::*; + use platform_value::Identifier; + + fn delta( + add_keywords: Vec, + remove_keywords: Vec, + ) -> DataContractUpdateTransitionV1 { + DataContractUpdateTransitionV1 { + identity_contract_nonce: 1, + data_contract_id: Identifier::new([1; 32]), + owner_id: Identifier::new([2; 32]), + version: 2, + config: None, + updated_schema_defs: Default::default(), + new_schema_defs: Default::default(), + updated_document_schemas: Default::default(), + new_document_schemas: Default::default(), + new_groups: Default::default(), + new_tokens: Default::default(), + add_keywords, + remove_keywords, + description: Default::default(), + user_fee_increase: 0, + signature_public_key_id: 0, + signature: Default::default(), + } + } + + /// As many keywords of one byte as fit in a state transition, twice over. + const MANY: usize = 5_000; + + #[test] + fn should_find_no_overlap_between_long_lists_of_repeated_keywords() { + let delta = delta(vec!["a".to_string(); MANY], vec!["b".to_string(); MANY]); + + assert_eq!(delta.overlapping_entry(), None); + } + + #[test] + fn should_name_the_first_added_keyword_that_is_also_removed() { + let mut add_keywords = vec!["a".to_string(); MANY]; + add_keywords.push("second".to_string()); + add_keywords.push("first".to_string()); + // The removed list names them in the other order + let mut remove_keywords = vec!["b".to_string(); MANY]; + remove_keywords.push("first".to_string()); + remove_keywords.push("second".to_string()); + + let overlap = delta(add_keywords, remove_keywords) + .overlapping_entry() + .expect("expected an overlap"); + + assert_eq!(overlap.entry_kind(), DataContractUpdateEntryKind::Keyword); + assert_eq!(overlap.name(), "second"); + } +} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/registration_cost.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/registration_cost.rs new file mode 100644 index 00000000000..b1bdbe31220 --- /dev/null +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/registration_cost.rs @@ -0,0 +1,147 @@ +use crate::data_contract::update_values::DataContractUpdateValues; +use crate::fee::Credits; +use crate::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; +use crate::ProtocolError; +use platform_version::version::PlatformVersion; + +impl DataContractUpdateTransitionV1 { + /// The registration cost of what this delta registers: its new and replaced document + /// types (with their indexes), its new tokens and its added keywords, without the fee of + /// registering a contract. See [`DataContractUpdateValues::registration_cost`]. + pub fn registration_cost( + &self, + platform_version: &PlatformVersion, + ) -> Result { + DataContractUpdateValues::from(self).registration_cost(platform_version) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::data_contract::accessors::v0::DataContractV0Setters; + use crate::data_contract::accessors::v1::DataContractV1Setters; + use crate::data_contract::schema::DataContractSchemaMethodsV0; + use crate::data_contract::DataContract; + use crate::tests::fixtures::get_data_contract_fixture; + use platform_value::platform_value; + + fn contract() -> DataContract { + get_data_contract_fixture(None, 0, PlatformVersion::latest().protocol_version) + .data_contract_owned() + } + + fn delta_between( + old_contract: &DataContract, + new_contract: &DataContract, + ) -> DataContractUpdateTransitionV1 { + DataContractUpdateTransitionV1::from_contract_update(old_contract, new_contract, 1) + .expect("expected the update to be expressible as a delta") + } + + #[test] + fn should_cost_nothing_to_register_nothing() { + let old_contract = contract(); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + new_contract.set_description(Some("a described contract".to_string())); + + assert_eq!( + delta_between(&old_contract, &new_contract) + .registration_cost(PlatformVersion::latest()) + .expect("expected a registration cost"), + 0 + ); + } + + /// A delta pays for what it registers and nothing else: the whole contract's registration + /// cost rises by exactly the delta's. + #[test] + fn should_cost_what_the_registration_cost_of_the_contract_rises_by() { + let platform_version = PlatformVersion::latest(); + let fees = &platform_version.fee_version.data_contract_registration; + let old_contract = contract(); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + new_contract + .set_document_schema( + "note", + platform_value!({ + "type": "object", + "properties": { + "label": {"type": "string", "maxLength": 63, "position": 0} + }, + "indices": [ + {"name": "byLabel", "properties": [{"label": "asc"}], "unique": true}, + {"name": "byOwner", "properties": [{"$ownerId": "asc"}]} + ], + "additionalProperties": false + }), + true, + &mut vec![], + platform_version, + ) + .expect("expected to add a document type"); + new_contract.set_keywords(vec!["alpha".to_string(), "beta".to_string()]); + + let cost = delta_between(&old_contract, &new_contract) + .registration_cost(platform_version) + .expect("expected a registration cost"); + + assert_eq!( + cost, + fees.document_type_registration_fee + + fees.document_type_base_unique_index_registration_fee + + fees.document_type_base_non_unique_index_registration_fee + + 2 * fees.search_keyword_fee + ); + assert_eq!( + cost, + new_contract + .registration_cost(platform_version) + .expect("expected a registration cost") + - old_contract + .registration_cost(platform_version) + .expect("expected a registration cost") + ); + } + + /// A replaced document type is registered again, as an update carrying the whole contract + /// registers every type again. + #[test] + fn should_cost_a_replaced_document_type_as_a_registered_one() { + let platform_version = PlatformVersion::latest(); + let fees = &platform_version.fee_version.data_contract_registration; + let old_contract = contract(); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + let mut replaced_schema = old_contract + .document_schemas() + .get("niceDocument") + .cloned() + .cloned() + .expect("expected the fixture's niceDocument type"); + replaced_schema + .set_value( + "description", + platform_value::Value::Text("a nicer document".to_string()), + ) + .expect("expected to describe the type"); + new_contract + .set_document_schema( + "niceDocument", + replaced_schema, + true, + &mut vec![], + platform_version, + ) + .expect("expected to replace a document type"); + + assert_eq!( + delta_between(&old_contract, &new_contract) + .registration_cost(platform_version) + .expect("expected a registration cost"), + fees.document_type_registration_fee + ); + } +} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/state_transition_like.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/state_transition_like.rs new file mode 100644 index 00000000000..c19ff69240d --- /dev/null +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/state_transition_like.rs @@ -0,0 +1,71 @@ +use base64::prelude::BASE64_STANDARD; +use base64::Engine; +use platform_value::BinaryData; + +use crate::prelude::UserFeeIncrease; +use crate::state_transition::StateTransitionHasUserFeeIncrease; +use crate::{ + prelude::Identifier, + state_transition::{StateTransitionLike, StateTransitionOwned, StateTransitionType}, +}; + +use crate::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; +use crate::state_transition::StateTransitionSingleSigned; +use crate::state_transition::StateTransitionType::DataContractUpdate; +use crate::version::FeatureVersion; + +impl StateTransitionLike for DataContractUpdateTransitionV1 { + /// Returns ID of the updated contract + fn modified_data_ids(&self) -> Vec { + vec![self.data_contract_id] + } + + fn state_transition_protocol_version(&self) -> FeatureVersion { + 1 + } + /// returns the type of State Transition + fn state_transition_type(&self) -> StateTransitionType { + DataContractUpdate + } + + fn unique_identifiers(&self) -> Vec { + vec![format!( + "{}-{}-{:x}", + BASE64_STANDARD.encode(self.owner_id), + BASE64_STANDARD.encode(self.data_contract_id), + self.identity_contract_nonce + )] + } +} + +impl StateTransitionHasUserFeeIncrease for DataContractUpdateTransitionV1 { + fn user_fee_increase(&self) -> UserFeeIncrease { + self.user_fee_increase + } + + fn set_user_fee_increase(&mut self, user_fee_increase: UserFeeIncrease) { + self.user_fee_increase = user_fee_increase + } +} + +impl StateTransitionSingleSigned for DataContractUpdateTransitionV1 { + /// returns the signature as a byte-array + fn signature(&self) -> &BinaryData { + &self.signature + } + /// set a new signature + fn set_signature(&mut self, signature: BinaryData) { + self.signature = signature + } + + fn set_signature_bytes(&mut self, signature: Vec) { + self.signature = BinaryData::new(signature) + } +} + +impl StateTransitionOwned for DataContractUpdateTransitionV1 { + /// Get owner ID + fn owner_id(&self) -> Identifier { + self.owner_id + } +} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/types.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/types.rs new file mode 100644 index 00000000000..c30f6851a6c --- /dev/null +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/types.rs @@ -0,0 +1,19 @@ +use crate::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; +use crate::state_transition::state_transitions::common_fields::property_names::{ + SIGNATURE, SIGNATURE_PUBLIC_KEY_ID, +}; +use crate::state_transition::StateTransitionFieldTypes; + +impl StateTransitionFieldTypes for DataContractUpdateTransitionV1 { + fn signature_property_paths() -> Vec<&'static str> { + vec![SIGNATURE, SIGNATURE_PUBLIC_KEY_ID] + } + + fn identifiers_property_paths() -> Vec<&'static str> { + vec![] + } + + fn binary_property_paths() -> Vec<&'static str> { + vec![SIGNATURE] + } +} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/v1_methods.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/v1_methods.rs new file mode 100644 index 00000000000..a5d9170f405 --- /dev/null +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/v1_methods.rs @@ -0,0 +1,56 @@ +use crate::data_contract::DataContract; +use crate::identity::signer::Signer; +use crate::identity::{IdentityPublicKey, KeyID, PartialIdentity}; +use crate::serialization::Signable; + +use crate::prelude::{IdentityNonce, UserFeeIncrease}; +use crate::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; +use crate::state_transition::StateTransition; +use crate::{NonConsensusError, ProtocolError}; + +impl DataContractUpdateTransitionV1 { + /// Builds and signs the delta that turns `old_contract` into + /// `new_contract`. + /// + /// # Arguments + /// + /// * `old_contract` - The contract as it is currently stored. + /// * `new_contract` - The contract the update should produce. + /// * `identity` - The `PartialIdentity` holding the signing key. + /// * `key_id` - The key to sign with. + /// * `identity_contract_nonce` - The next identity contract nonce. + /// * `user_fee_increase` - The fee increase for priority processing. + /// * `signer` - The `Signer` producing the signature. + #[allow(clippy::too_many_arguments)] + pub async fn new_from_contract_update>( + old_contract: &DataContract, + new_contract: &DataContract, + identity: &PartialIdentity, + key_id: KeyID, + identity_contract_nonce: IdentityNonce, + user_fee_increase: UserFeeIncrease, + signer: &S, + ) -> Result { + let mut transition = DataContractUpdateTransitionV1::from_contract_update( + old_contract, + new_contract, + identity_contract_nonce, + )?; + transition.user_fee_increase = user_fee_increase; + transition.signature_public_key_id = key_id; + + let mut state_transition: StateTransition = transition.into(); + let value = state_transition.signable_bytes()?; + let public_key = + identity + .loaded_public_keys + .get(&key_id) + .ok_or(ProtocolError::NonConsensusError( + NonConsensusError::StateTransitionCreationError( + "public key did not exist".to_string(), + ), + ))?; + state_transition.set_signature(signer.sign(public_key, &value).await?); + Ok(state_transition) + } +} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/version.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/version.rs new file mode 100644 index 00000000000..fbcbc011f3e --- /dev/null +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/v1/version.rs @@ -0,0 +1,9 @@ +use crate::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; +use crate::state_transition::FeatureVersioned; +use crate::version::FeatureVersion; + +impl FeatureVersioned for DataContractUpdateTransitionV1 { + fn feature_version(&self) -> FeatureVersion { + 1 + } +} diff --git a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/version.rs b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/version.rs index a49b3c55b66..e7c29397e91 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/version.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/contract/data_contract_update_transition/version.rs @@ -6,6 +6,7 @@ impl FeatureVersioned for DataContractUpdateTransition { fn feature_version(&self) -> FeatureVersion { match self { DataContractUpdateTransition::V0(v0) => v0.feature_version(), + DataContractUpdateTransition::V1(v1) => v1.feature_version(), } } } diff --git a/packages/rs-drive-abci/src/execution/check_tx/v0/mod.rs b/packages/rs-drive-abci/src/execution/check_tx/v0/mod.rs index 98364ed8658..f2f13d29799 100644 --- a/packages/rs-drive-abci/src/execution/check_tx/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/check_tx/v0/mod.rs @@ -2255,6 +2255,234 @@ mod tests { )); } + #[test] + fn data_contract_update_check_tx_latest_protocol_version_delta() { + let platform_config = PlatformConfig { + testing_configs: PlatformTestConfig { + disable_instant_lock_signature_verification: true, + ..Default::default() + }, + ..Default::default() + }; + + let platform = TestPlatformBuilder::new() + .with_config(platform_config) + .build_with_mock_rpc(); + + let platform_state = platform.state.load(); + let protocol_version = platform_state.current_protocol_version_in_consensus(); + let platform_version = PlatformVersion::get(protocol_version).unwrap(); + + let platform_ref = PlatformRef { + drive: &platform.drive, + state: &platform_state, + config: &platform.config, + core_rpc: &platform.core_rpc, + }; + + let (key, private_key) = IdentityPublicKey::random_ecdsa_critical_level_authentication_key( + 1, + Some(1), + platform_version, + ) + .expect("expected to get key pair"); + + platform + .drive + .create_initial_state_structure(None, platform_version) + .expect("expected to create state structure"); + let identity: Identity = IdentityV0 { + id: Identifier::new([ + 158, 113, 180, 126, 91, 83, 62, 44, 83, 54, 97, 88, 240, 215, 84, 139, 167, 156, + 166, 203, 222, 4, 64, 31, 215, 199, 149, 151, 190, 246, 251, 44, + ]), + public_keys: BTreeMap::from([(1, key.clone())]), + balance: 100_000_000_000, // 1.0 Dash + revision: 0, + } + .into(); + + let dashpay_created_contract = + get_dashpay_contract_fixture(Some(identity.id()), 1, protocol_version); + let mut modified_dashpay_contract = dashpay_created_contract.data_contract().clone(); + let mut create_contract_state_transition: StateTransition = dashpay_created_contract + .clone() + .try_into_platform_versioned(platform_version) + .expect("expected a state transition"); + create_contract_state_transition + .sign(&key, private_key.as_slice(), &NativeBlsModule) + .expect("expected to sign transition"); + let serialized = create_contract_state_transition + .serialize_to_bytes() + .expect("serialized state transition"); + platform + .drive + .add_new_identity( + identity.clone(), + false, + &BlockInfo::default(), + true, + None, + platform_version, + ) + .expect("expected to insert identity"); + + let transaction = platform.drive.grove.start_transaction(); + + let processing_result = platform + .platform + .process_raw_state_transitions( + std::slice::from_ref(&serialized), + &platform_state, + &BlockInfo::default(), + &transaction, + platform_version, + false, + None, + ) + .expect("expected to process state transition"); + + assert_eq!( + processing_result.aggregated_fees().processing_fee, + // the create of `data_contract_update_check_tx_latest_protocol_version` + 26005728080 + ); + + platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit"); + + // Now let's do the data contract update + let _dashpay_id = modified_dashpay_contract.id(); + // we need to alter dashpay to make it invalid + + modified_dashpay_contract.set_version(2); + + let document_types = modified_dashpay_contract.document_types_mut(); + + let dpns_contract = + get_dpns_data_contract_fixture(Some(identity.id()), 1, protocol_version) + .data_contract_owned(); + + document_types.insert( + "preorder".to_string(), + dpns_contract + .document_type_for_name("preorder") + .expect("expected document type") + .to_owned_document_type(), + ); + + // The latest protocol version builds a delta by default: the transition carries the + // new document type alone + let update_transition = DataContractUpdateTransition::from_contract_update( + dashpay_created_contract.data_contract(), + &modified_dashpay_contract, + 2, + platform_version, + ) + .expect("expected a state transition"); + assert!(matches!( + update_transition, + DataContractUpdateTransition::V1(_) + )); + let mut update_contract_state_transition: StateTransition = update_transition.into(); + + update_contract_state_transition + .sign(&key, private_key.as_slice(), &NativeBlsModule) + .expect("expected to sign transition"); + let serialized_update = update_contract_state_transition + .serialize_to_bytes() + .expect("serialized state transition"); + + let validation_result = platform + .check_tx( + serialized_update.as_slice(), + FirstTimeCheck, + &platform_ref, + platform_version, + ) + .expect("expected to check tx"); + + assert_eq!(validation_result.errors.as_slice(), &[]); + + let check_result = platform + .check_tx( + serialized_update.as_slice(), + Recheck, + &platform_ref, + platform_version, + ) + .expect("expected to check tx"); + + assert!(check_result.is_valid()); + + let transaction = platform.drive.grove.start_transaction(); + + let update_processing_result = platform + .platform + .process_raw_state_transitions( + std::slice::from_ref(&serialized_update), + &platform_state, + &BlockInfo::default(), + &transaction, + platform_version, + false, + None, + ) + .expect("expected to process state transition"); + + // The delta is valid and paid for + assert_eq!(update_processing_result.valid_count(), 1); + + assert_eq!( + update_processing_result.aggregated_fees().processing_fee, + // The same update as `data_contract_update_check_tx_latest_protocol_version`, which + // embeds the whole contract and pays 31006514040: the registration cost of the + // whole contract again. The delta registers the preorder type and its three + // indexes alone (0.05 Dash), and pays the processing of validating the whole merged + // contract as that update does, with one more billed read of the stored contract, + // the one the delta is merged onto + 5006731420 + ); + + let check_result = platform + .check_tx( + serialized_update.as_slice(), + Recheck, + &platform_ref, + platform_version, + ) + .expect("expected to check tx"); + + assert!(check_result.is_valid()); // it should still be valid, because we didn't commit the transaction + + platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit"); + + let check_result = platform + .check_tx( + serialized_update.as_slice(), + Recheck, + &platform_ref, + platform_version, + ) + .expect("expected to check tx"); + + assert!(!check_result.is_valid()); // it should no longer be valid, because of the nonce check + + assert!(matches!( + check_result.errors.first().expect("expected an error"), + ConsensusError::StateError(StateError::InvalidIdentityNonceError(_)) + )); + } + #[test] fn data_contract_update_check_tx_for_invalid_update_first_protocol_version() { let platform_config = PlatformConfig { diff --git a/packages/rs-drive-abci/src/execution/types/execution_event/mod.rs b/packages/rs-drive-abci/src/execution/types/execution_event/mod.rs index 6d33f4ed4c7..2f39d2c012d 100644 --- a/packages/rs-drive-abci/src/execution/types/execution_event/mod.rs +++ b/packages/rs-drive-abci/src/execution/types/execution_event/mod.rs @@ -375,11 +375,10 @@ impl ExecutionEvent<'_> { } StateTransitionAction::DataContractUpdateAction(data_contract_update_action) => { let user_fee_increase = action.user_fee_increase(); - // The update cost pays for the whole contract again, that's fine for now. - // It would be a lot of work to fix this, so we'll just go with this for now. - let registration_cost = data_contract_update_action - .data_contract_ref() - .registration_cost(platform_version)?; + // A full-contract (V0) update pays for the whole contract again; + // a delta-based (V1) update only pays for what it adds. + let registration_cost = + data_contract_update_action.registration_cost(platform_version)?; let operations = action.into_high_level_drive_operations(epoch, platform_version)?; if let Some(identity) = identity { diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/processor/traits/is_allowed.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/processor/traits/is_allowed.rs index 9fc1c20a620..0af74fb94fb 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/processor/traits/is_allowed.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/processor/traits/is_allowed.rs @@ -1,8 +1,11 @@ use crate::error::execution::ExecutionError; use crate::error::Error; use dpp::consensus::basic::state_transition::StateTransitionNotActiveError; -use dpp::data_contract::associated_token::token_configuration::validate_token_configurations; +use dpp::data_contract::associated_token::token_configuration::{ + validate_token_configurations, TokenConfiguration, +}; use dpp::data_contract::associated_token::token_configuration_item::TokenConfigurationChangeItem; +use dpp::data_contract::TokenContractPosition; use dpp::prelude::ConsensusValidationResult; use dpp::state_transition::batch_transition::accessors::DocumentsBatchTransitionAccessorsV0; use dpp::state_transition::batch_transition::batched_transition::document_transition::DocumentTransitionV0Methods; @@ -14,7 +17,7 @@ use dpp::state_transition::batch_transition::batched_transition::BatchedTransiti use dpp::state_transition::batch_transition::document_base_transition::v1::v1_methods::DocumentBaseTransitionV1Methods; use dpp::state_transition::batch_transition::token_config_update_transition::v0::v0_methods::TokenConfigUpdateTransitionV0Methods; use dpp::state_transition::data_contract_create_transition::accessors::DataContractCreateTransitionAccessorsV0; -use dpp::state_transition::data_contract_update_transition::accessors::DataContractUpdateTransitionAccessorsV0; +use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; use dpp::state_transition::StateTransition; use dpp::tokens::token_payment_info::v1::v1_accessors::TokenPaymentInfoAccessorsV1; use dpp::version::feature_initial_protocol_versions::{ @@ -27,6 +30,18 @@ use dpp::version::feature_initial_protocol_versions::{ TOKEN_MARKETPLACE_INITIAL_PROTOCOL_VERSION, TOKEN_SHIELDED_POOL_INITIAL_PROTOCOL_VERSION, }; use dpp::version::PlatformVersion; +use std::collections::BTreeMap; + +/// The token configurations a contract update carries: the contract's, when the update embeds +/// its contract, and the ones a delta adds, as a delta carries only what it changes. +fn tokens_carried_by_update( + update: &DataContractUpdateTransition, +) -> &BTreeMap { + match update { + DataContractUpdateTransition::V0(update) => update.data_contract.tokens(), + DataContractUpdateTransition::V1(delta) => &delta.new_tokens, + } +} /// A trait for validating state transitions within a blockchain. pub(crate) trait StateTransitionIsAllowedValidationV0 { @@ -81,9 +96,7 @@ impl StateTransitionIsAllowedValidationV0 for StateTransition { .tokens() .values() .any(|configuration| configuration.needs_activation_check())), - StateTransition::DataContractUpdate(st) => Ok(st - .data_contract() - .tokens() + StateTransition::DataContractUpdate(st) => Ok(tokens_carried_by_update(st) .values() .any(|configuration| configuration.needs_activation_check())), StateTransition::IdentityCreate(_) @@ -99,18 +112,15 @@ impl StateTransitionIsAllowedValidationV0 for StateTransition { &self, platform_version: &PlatformVersion, ) -> Result, Error> { - let contract = match self { - StateTransition::DataContractCreate(st) => Some(st.data_contract()), - StateTransition::DataContractUpdate(st) => Some(st.data_contract()), + let tokens = match self { + StateTransition::DataContractCreate(st) => Some(st.data_contract().tokens()), + StateTransition::DataContractUpdate(st) => Some(tokens_carried_by_update(st)), _ => None, }; - if let Some(contract) = contract { + if let Some(tokens) = tokens { // The pre-activation gate: a token configuration format the protocol version does // not admit is refused unpaid, whatever the frozen basic structure generations do. - return Ok(validate_token_configurations( - contract.tokens(), - platform_version, - )); + return Ok(validate_token_configurations(tokens, platform_version)); } match self { StateTransition::Batch(st) => { diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_common/contract_structure_test_harness.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_common/contract_structure_test_harness.rs index 4e769201c17..a59d4696c88 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_common/contract_structure_test_harness.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_common/contract_structure_test_harness.rs @@ -220,9 +220,14 @@ pub(in crate::execution) async fn resign_with_contract( create.set_data_contract(serialized_contract); } StateTransition::DataContractUpdate(update) => { - let mut serialized_contract = update.data_contract().clone(); + let mut serialized_contract = update + .data_contract() + .expect("expected an update that embeds its contract") + .clone(); edit_contract(&mut serialized_contract); - update.set_data_contract(serialized_contract); + update + .set_data_contract(serialized_contract) + .expect("expected an update that embeds its contract"); } _ => panic!("expected a data contract create or update transition"), } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/mod.rs index 4598692d1d6..1b391a4bcc9 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/mod.rs @@ -1,3 +1,4 @@ pub(crate) mod v0; pub(crate) mod v1; pub(crate) mod v2; +pub(crate) mod v3; diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v0/mod.rs index 0f95b20d133..6035ac5db96 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v0/mod.rs @@ -1,3 +1,4 @@ +use crate::error::execution::ExecutionError; use crate::error::Error; use dpp::consensus::basic::data_contract::{ InvalidTokenBaseSupplyError, NewTokensDestinationIdentityOptionRequiredError, @@ -30,7 +31,15 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV0 for DataContrac network_type: Network, platform_version: &PlatformVersion, ) -> Result { - let groups = self.data_contract().groups(); + // Edited in place: the accessor returns no contract for a delta contract update, which + // the dispatcher refuses before this generation, so an update that embeds its contract + // is judged as it was + let Some(data_contract) = self.data_contract() else { + return Err(Error::Execution(ExecutionError::CorruptedCodeExecution( + "a delta contract update reached a generation that validates updates embedding their contract", + ))); + }; + let groups = data_contract.groups(); if !groups.is_empty() { let validation_result = DataContract::validate_groups(groups, platform_version)?; @@ -40,7 +49,7 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV0 for DataContrac } for (expected_position, (token_contract_position, token_configuration)) in - self.data_contract().tokens().iter().enumerate() + data_contract.tokens().iter().enumerate() { if expected_position as TokenContractPosition != *token_contract_position { return Ok(SimpleConsensusValidationResult::new_with_error( @@ -65,10 +74,8 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV0 for DataContrac return Ok(validation_result); } - let validation_result = token_configuration.validate_token_config_groups_exist( - self.data_contract().groups(), - platform_version, - )?; + let validation_result = token_configuration + .validate_token_config_groups_exist(data_contract.groups(), platform_version)?; if !validation_result.is_valid() { return Ok(validation_result); } @@ -128,7 +135,7 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV0 for DataContrac { return Ok(SimpleConsensusValidationResult::new_with_error( NewTokensDestinationIdentityOptionRequiredError::new( - self.data_contract().id(), + data_contract.id(), *token_contract_position, ) .into(), diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v1/mod.rs index 4d416a5ebf0..487fa388b01 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v1/mod.rs @@ -1,3 +1,4 @@ +use crate::error::execution::ExecutionError; use crate::error::Error; use dpp::consensus::state::data_contract::data_contract_config_update_error::DataContractConfigUpdateError; use dpp::dashcore::Network; @@ -23,6 +24,14 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV1 for DataContrac network_type: Network, platform_version: &PlatformVersion, ) -> Result { + // Edited in place: the accessor returns no contract for a delta contract update, which + // the dispatcher refuses before this generation, so an update that embeds its contract + // is judged as it was + let Some(data_contract) = self.data_contract() else { + return Err(Error::Execution(ExecutionError::CorruptedCodeExecution( + "a delta contract update reached a generation that validates updates embedding their contract", + ))); + }; // First run all v0 validations let v0_result = self.validate_basic_structure_v0(network_type, platform_version)?; if !v0_result.is_valid() { @@ -33,13 +42,13 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV1 for DataContrac // Since protocol version 12, V0 config is no longer accepted because it lacks // sized_integer_types support. let config_min_version = platform_version.dpp.contract_versions.config.min_version; - if (self.data_contract().config().version() as FeatureVersion) < config_min_version { + if (data_contract.config().version() as FeatureVersion) < config_min_version { return Ok(SimpleConsensusValidationResult::new_with_error( DataContractConfigUpdateError::new( - self.data_contract().id(), + data_contract.id(), format!( "config version {} is not supported, minimum version is {}", - self.data_contract().config().version(), + data_contract.config().version(), config_min_version ), ) diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v2/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v2/mod.rs index f7fb8557737..904bc4dc92b 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v2/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v2/mod.rs @@ -1,3 +1,4 @@ +use crate::error::execution::ExecutionError; use crate::error::Error; use dpp::consensus::basic::contract_moderation::DocumentActionFeesWithoutModerationError; use dpp::dashcore::Network; @@ -36,9 +37,18 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV2 for DataContrac return Ok(v1_result); } - if let Some(moderation) = self.data_contract().config().moderation() { + // Edited in place: the accessor returns no contract for a delta contract update, which + // the dispatcher refuses before this generation, so an update that embeds its contract + // is judged as it was + let Some(data_contract) = self.data_contract() else { + return Err(Error::Execution(ExecutionError::CorruptedCodeExecution( + "a delta contract update reached a generation that validates updates embedding their contract", + ))); + }; + + if let Some(moderation) = data_contract.config().moderation() { let result = moderation.validate( - self.data_contract().document_schemas(), + data_contract.document_schemas(), network_type, platform_version, )?; @@ -49,10 +59,10 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV2 for DataContrac // Document action fees: a document type may only charge for the moderators when the // contract declares moderation, since the moderation team is who that pot is for. - if self.data_contract().config().moderation().is_none() { + if data_contract.config().moderation().is_none() { if let Some(document_type_name) = DocumentActionFees::first_document_type_charging_moderators( - self.data_contract().document_schemas(), + data_contract.document_schemas(), ) { return Ok(SimpleConsensusValidationResult::new_with_error( @@ -66,7 +76,7 @@ impl DataContractUpdateStateTransitionBasicStructureValidationV2 for DataContrac // pool must leave its freeze, unfreeze and destroy-frozen-funds rules unassigned, // since notes in a pool have no owner to freeze. Ok(validate_token_configurations( - self.data_contract().tokens(), + data_contract.tokens(), platform_version, )) } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v3/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v3/mod.rs new file mode 100644 index 00000000000..6f1f1cf661e --- /dev/null +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/basic_structure/v3/mod.rs @@ -0,0 +1,43 @@ +use crate::error::Error; +use dpp::dashcore::Network; +use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; +use dpp::validation::SimpleConsensusValidationResult; +use dpp::version::PlatformVersion; + +use super::v2::DataContractUpdateStateTransitionBasicStructureValidationV2; + +pub(in crate::execution::validation::state_transition::state_transitions::data_contract_update) trait DataContractUpdateStateTransitionBasicStructureValidationV3 +{ + fn validate_basic_structure_v3( + &self, + network_type: Network, + platform_version: &PlatformVersion, + ) -> Result; +} + +impl DataContractUpdateStateTransitionBasicStructureValidationV3 for DataContractUpdateTransition { + /// Generation 3 (protocol version 15): generation 2 for an update that embeds its + /// contract, and a delta, which carries only what it changes, is admitted. + /// + /// A delta is refused here, without a fee, only when it names an entry in two sections + /// that cannot both apply: the one thing a delta says about itself. Everything else is a + /// rule about the contract the delta merges into, which exists only once the stored + /// contract is read. State validation, and check_tx's transformation, merge the delta + /// onto it and hold the update embedding the result to generation 2 of this validation, + /// so a delta is held to every structure rule of an update that embeds its contract, in + /// a block as a paid nonce bump. + fn validate_basic_structure_v3( + &self, + network_type: Network, + platform_version: &PlatformVersion, + ) -> Result { + let DataContractUpdateTransition::V1(delta) = self else { + return self.validate_basic_structure_v2(network_type, platform_version); + }; + + Ok(match delta.overlapping_entry() { + Some(error) => SimpleConsensusValidationResult::new_with_error(error.into()), + None => SimpleConsensusValidationResult::new(), + }) + } +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/delta.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/delta.rs new file mode 100644 index 00000000000..48bb0f9901e --- /dev/null +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/delta.rs @@ -0,0 +1,147 @@ +//! A delta contract update (version 1 of the transition, from protocol version 15), merged +//! onto the stored contract. +//! +//! A delta carries only what an update changes, so nothing can be said of the contract it +//! asks for until the stored contract is read. Block execution (state validation) and +//! check_tx (the transformation into an action) both start here: the stored contract is read, +//! the delta is merged onto it, and what comes back is the update embedding the whole merged +//! contract, which the caller then validates with the generations such an update runs. A +//! delta is therefore held to every rule of an update that embeds its contract, by the code +//! that holds that update to them. + +use dpp::block::block_info::BlockInfo; +use dpp::consensus::basic::document::DataContractNotPresentError; +use dpp::consensus::basic::BasicError; +use dpp::consensus::ConsensusError; +use dpp::fee::Credits; +use dpp::prelude::ConsensusValidationResult; +use dpp::state_transition::data_contract_update_transition::{ + DataContractUpdateTransition, DataContractUpdateTransitionV1, +}; +use dpp::version::PlatformVersion; +use drive::grovedb::TransactionArg; +use drive::state_transition_action::system::bump_identity_data_contract_nonce_action::BumpIdentityDataContractNonceAction; +use drive::state_transition_action::StateTransitionAction; + +use crate::error::execution::ExecutionError; +use crate::error::Error; +use crate::execution::types::execution_operation::ValidationOperation; +use crate::execution::types::state_transition_execution_context::{ + StateTransitionExecutionContext, StateTransitionExecutionContextMethodsV0, +}; +use crate::execution::validation::state_transition::state_transitions::data_contract_update::basic_structure::v2::DataContractUpdateStateTransitionBasicStructureValidationV2; +use crate::execution::validation::state_transition::ValidationMode; +use crate::platform_types::platform::PlatformRef; +use crate::rpc::core::CoreRPCLike; + +/// What became of a delta once the stored contract was read. +pub(in crate::execution::validation::state_transition::state_transitions::data_contract_update) +enum MergedDelta { + /// The delta is refused: the result holds the nonce bump and the errors. + Refused(ConsensusValidationResult), + /// The delta merged onto the stored contract. + Merged { + /// The update embedding the whole merged contract, under the delta's nonce and fee + /// increase. + full_contract_update: DataContractUpdateTransition, + /// The registration cost of what the delta registers, which its action pays in place + /// of the whole contract's. + registration_cost: Credits, + }, +} + +fn refused(transition: &DataContractUpdateTransition, errors: Vec) -> MergedDelta { + MergedDelta::Refused(ConsensusValidationResult::new_with_data_and_errors( + StateTransitionAction::BumpIdentityDataContractNonceAction( + BumpIdentityDataContractNonceAction::from_borrowed_data_contract_update_transition( + transition, + ), + ), + errors, + )) +} + +/// Reads the contract `delta` names and merges the delta onto it. +/// +/// The read is billed whether or not the contract exists, as the read of an update that embeds +/// its contract is. A contract that does not exist, a delta that does not fit the stored +/// contract (another owner, an entry to replace or remove that it does not have, an entry to +/// add that it has), and a merged contract that breaks a structure rule are refused with a +/// nonce bump, never with an execution error. The structure rules are those basic structure +/// generation 2 holds an update that embeds its contract to, run here on the update embedding +/// the merged contract, as basic structure cannot read the stored contract. +/// +/// `transition` is the delta as a transition, which the nonce bump is built from. +#[allow(clippy::too_many_arguments)] +pub(in crate::execution::validation::state_transition::state_transitions::data_contract_update) fn merge_delta_onto_stored_contract< + C: CoreRPCLike, +>( + transition: &DataContractUpdateTransition, + delta: &DataContractUpdateTransitionV1, + platform: &PlatformRef, + block_info: &BlockInfo, + validation_mode: ValidationMode, + execution_context: &mut StateTransitionExecutionContext, + tx: TransactionArg, + platform_version: &PlatformVersion, +) -> Result { + let (fee, contract_fetch_info) = platform.drive.get_contract_with_fetch_info_and_fee( + delta.data_contract_id.to_buffer(), + Some(&block_info.epoch), + validation_mode.can_alter_cache(), + tx, + platform_version, + )?; + let fee = fee.ok_or(Error::Execution(ExecutionError::CorruptedCodeExecution( + "the read of the contract a delta contract update names must return its fee", + )))?; + execution_context.add_operation(ValidationOperation::PrecalculatedOperation(fee)); + + let Some(contract_fetch_info) = contract_fetch_info else { + return Ok(refused( + transition, + vec![ + BasicError::DataContractNotPresentError(DataContractNotPresentError::new( + delta.data_contract_id, + )) + .into(), + ], + )); + }; + + let merged = delta.to_full_contract_update(&contract_fetch_info.contract, platform_version)?; + if !merged.is_valid() { + return Ok(refused(transition, merged.errors)); + } + let full_contract_update: DataContractUpdateTransition = merged.into_data()?.into(); + + let structure_result = full_contract_update + .validate_basic_structure_v2(platform.config.network, platform_version)?; + if !structure_result.is_valid() { + return Ok(refused(transition, structure_result.errors)); + } + + Ok(MergedDelta::Merged { + full_contract_update, + registration_cost: delta.registration_cost(platform_version)?, + }) +} + +/// The result of validating the update embedding a merged delta, as the delta's: its action +/// pays `registration_cost`, the cost of what the delta registers, in place of the whole +/// contract's. A nonce bump is the delta's as it is, since the update carries the delta's +/// owner, contract, nonce and fee increase. +pub(in crate::execution::validation::state_transition::state_transitions::data_contract_update) fn as_delta_result( + mut result: ConsensusValidationResult, + registration_cost: Credits, +) -> ConsensusValidationResult { + result.data = result.data.map(|action| match action { + StateTransitionAction::DataContractUpdateAction(action) => { + StateTransitionAction::DataContractUpdateAction( + action.into_delta_action(registration_cost), + ) + } + action => action, + }); + result +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/mod.rs index 3a7913785ce..7e880521467 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/mod.rs @@ -7,10 +7,13 @@ use crate::error::Error; use crate::error::execution::ExecutionError; use crate::execution::types::state_transition_execution_context::StateTransitionExecutionContext; use crate::execution::validation::state_transition::data_contract_update::identity_contract_nonce::v0::DataContractUpdateStateTransitionIdentityContractNonceV0; +use crate::execution::validation::state_transition::data_contract_update::identity_contract_nonce::v1::DataContractUpdateStateTransitionIdentityContractNonceV1; +use crate::execution::validation::state_transition::data_contract_update::unsupported_delta_error; use crate::execution::validation::state_transition::processor::identity_nonces::StateTransitionIdentityNonceValidationV0; use crate::platform_types::platform::{PlatformStateRef}; pub(crate) mod v0; +pub(crate) mod v1; impl StateTransitionIdentityNonceValidationV0 for DataContractUpdateTransition { fn validate_identity_nonces( @@ -21,13 +24,22 @@ impl StateTransitionIdentityNonceValidationV0 for DataContractUpdateTransition { execution_context: &mut StateTransitionExecutionContext, platform_version: &PlatformVersion, ) -> Result { - match platform_version + let version = platform_version .drive_abci .validation_and_processing .state_transitions .contract_update_state_transition - .nonce - { + .nonce; + // Generation 0 reads the owner and the contract id from the contract an update + // embeds. A delta, which embeds none, is not active at the protocol versions that + // select it and is refused at decode there; one that got here anyway is refused as an + // unsupported version, a consensus error, before it runs + if matches!(self, DataContractUpdateTransition::V1(_)) && version == Some(0) { + return Ok(SimpleConsensusValidationResult::new_with_error( + unsupported_delta_error(self, platform_version), + )); + } + match version { Some(0) => self.validate_identity_contract_nonce_v0( platform, block_info, @@ -35,10 +47,17 @@ impl StateTransitionIdentityNonceValidationV0 for DataContractUpdateTransition { execution_context, platform_version, ), + Some(1) => self.validate_identity_contract_nonce_v1( + platform, + block_info, + tx, + execution_context, + platform_version, + ), Some(version) => Err(Error::Execution(ExecutionError::UnknownVersionMismatch { method: "data contract update transition: validate_identity_contract_nonce" .to_string(), - known_versions: vec![0], + known_versions: vec![0, 1], received: version, })), None => Err(Error::Execution(ExecutionError::VersionNotActive { diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/v0/mod.rs index 2f012f5a0c4..fb93e6409da 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/v0/mod.rs @@ -1,3 +1,4 @@ +use crate::error::execution::ExecutionError; use crate::error::Error; use dpp::block::block_info::BlockInfo; use dpp::consensus::basic::document::NonceOutOfBoundsError; @@ -39,6 +40,14 @@ impl DataContractUpdateStateTransitionIdentityContractNonceV0 for DataContractUp execution_context: &mut StateTransitionExecutionContext, platform_version: &PlatformVersion, ) -> Result { + // Edited in place: the accessor returns no contract for a delta contract update, which + // the dispatcher refuses before this generation, so an update that embeds its contract + // is judged as it was + let Some(data_contract) = self.data_contract() else { + return Err(Error::Execution(ExecutionError::CorruptedCodeExecution( + "a delta contract update reached a generation that validates updates embedding their contract", + ))); + }; let revision_nonce = self.identity_contract_nonce(); if revision_nonce & MISSING_IDENTITY_REVISIONS_FILTER > 0 { @@ -48,8 +57,8 @@ impl DataContractUpdateStateTransitionIdentityContractNonceV0 for DataContractUp )); } - let identity_id = self.data_contract().owner_id(); - let contract_id = self.data_contract().id(); + let identity_id = data_contract.owner_id(); + let contract_id = data_contract.id(); let (existing_nonce, fee) = platform.drive.fetch_identity_contract_nonce_with_fees( identity_id.to_buffer(), contract_id.to_buffer(), diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/v1/mod.rs new file mode 100644 index 00000000000..12e8adde552 --- /dev/null +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/identity_contract_nonce/v1/mod.rs @@ -0,0 +1,78 @@ +use crate::error::Error; +use dpp::block::block_info::BlockInfo; +use dpp::consensus::basic::document::NonceOutOfBoundsError; +use dpp::consensus::basic::BasicError; +use dpp::identity::identity_nonce::{ + validate_identity_nonce_update, validate_new_identity_nonce, MISSING_IDENTITY_REVISIONS_FILTER, +}; +use dpp::state_transition::data_contract_update_transition::accessors::DataContractUpdateTransitionAccessorsV0; +use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; +use dpp::state_transition::StateTransitionOwned; + +use dpp::validation::SimpleConsensusValidationResult; + +use crate::execution::types::execution_operation::ValidationOperation; +use crate::execution::types::state_transition_execution_context::{ + StateTransitionExecutionContext, StateTransitionExecutionContextMethodsV0, +}; +use crate::platform_types::platform::PlatformStateRef; +use dpp::version::PlatformVersion; +use drive::grovedb::TransactionArg; + +pub(in crate::execution::validation::state_transition::state_transitions) trait DataContractUpdateStateTransitionIdentityContractNonceV1 +{ + fn validate_identity_contract_nonce_v1( + &self, + platform: &PlatformStateRef, + block_info: &BlockInfo, + tx: TransactionArg, + execution_context: &mut StateTransitionExecutionContext, + platform_version: &PlatformVersion, + ) -> Result; +} + +impl DataContractUpdateStateTransitionIdentityContractNonceV1 for DataContractUpdateTransition { + /// Generation 1 (protocol version 15): generation 0, reading the owner and the contract + /// id through the transition's accessors rather than from the contract it embeds, so a + /// delta, which embeds none and names both itself, is checked as an update that embeds + /// its contract is. For that update the accessors read the embedded contract, so it is + /// checked exactly as generation 0 checks it. + fn validate_identity_contract_nonce_v1( + &self, + platform: &PlatformStateRef, + block_info: &BlockInfo, + tx: TransactionArg, + execution_context: &mut StateTransitionExecutionContext, + platform_version: &PlatformVersion, + ) -> Result { + let revision_nonce = self.identity_contract_nonce(); + + if revision_nonce & MISSING_IDENTITY_REVISIONS_FILTER > 0 { + return Ok(SimpleConsensusValidationResult::new_with_error( + BasicError::NonceOutOfBoundsError(NonceOutOfBoundsError::new(revision_nonce)) + .into(), + )); + } + + let identity_id = self.owner_id(); + let contract_id = self.data_contract_id(); + let (existing_nonce, fee) = platform.drive.fetch_identity_contract_nonce_with_fees( + identity_id.to_buffer(), + contract_id.to_buffer(), + block_info, + true, + tx, + platform_version, + )?; + + execution_context.add_operation(ValidationOperation::PrecalculatedOperation(fee)); + + let result = if let Some(existing_nonce) = existing_nonce { + validate_identity_nonce_update(existing_nonce, revision_nonce, identity_id) + } else { + validate_new_identity_nonce(revision_nonce, identity_id) + }; + + Ok(result) + } +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/mod.rs index 3decb2300e6..fef5ac7315a 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/mod.rs @@ -1,6 +1,7 @@ mod basic_structure; #[cfg(test)] mod contract_structure_error_tests; +mod delta; mod identity_contract_nonce; mod state; mod transform_into_action; @@ -8,8 +9,11 @@ mod transform_into_action; use basic_structure::v0::DataContractUpdateStateTransitionBasicStructureValidationV0; use basic_structure::v1::DataContractUpdateStateTransitionBasicStructureValidationV1; use basic_structure::v2::DataContractUpdateStateTransitionBasicStructureValidationV2; +use basic_structure::v3::DataContractUpdateStateTransitionBasicStructureValidationV3; use dpp::address_funds::PlatformAddress; use dpp::block::block_info::BlockInfo; +use dpp::consensus::basic::UnsupportedVersionError; +use dpp::consensus::ConsensusError; use dpp::dashcore::Network; use dpp::fee::Credits; use dpp::prelude::AddressNonce; @@ -36,25 +40,55 @@ use crate::platform_types::platform::PlatformRef; use crate::platform_types::platform_state::PlatformStateV0Methods; use crate::rpc::core::CoreRPCLike; +/// The refusal of a delta contract update that reaches a generation which validates the +/// contract an update embeds. +/// +/// A delta (version 1 of the transition) embeds no contract. It is not active before protocol +/// version 15, where decoding refuses it, and from 15 the tables select generations that admit +/// it. So these generations never see one; were one to get there, the dispatchers refuse it +/// before the generation runs, as an unsupported version: a consensus error, so that it can +/// never stop block execution, and the shipped generations stay as they were. +pub(in crate::execution::validation::state_transition::state_transitions::data_contract_update) fn unsupported_delta_error( + transition: &DataContractUpdateTransition, + platform_version: &PlatformVersion, +) -> ConsensusError { + let bounds = &platform_version + .dpp + .state_transition_serialization_versions + .contract_update_state_transition; + UnsupportedVersionError::new( + transition.feature_version(), + bounds.min_version, + bounds.max_version, + ) + .into() +} + impl StateTransitionBasicStructureValidationV0 for DataContractUpdateTransition { fn validate_basic_structure( &self, network_type: Network, platform_version: &PlatformVersion, ) -> Result { - match platform_version + let version = platform_version .drive_abci .validation_and_processing .state_transitions .contract_update_state_transition - .basic_structure - { + .basic_structure; + if matches!(self, DataContractUpdateTransition::V1(_)) && matches!(version, Some(0..=2)) { + return Ok(SimpleConsensusValidationResult::new_with_error( + unsupported_delta_error(self, platform_version), + )); + } + match version { Some(0) => self.validate_basic_structure_v0(network_type, platform_version), Some(1) => self.validate_basic_structure_v1(network_type, platform_version), Some(2) => self.validate_basic_structure_v2(network_type, platform_version), + Some(3) => self.validate_basic_structure_v3(network_type, platform_version), Some(version) => Err(Error::Execution(ExecutionError::UnknownVersionMismatch { method: "data contract update transition: validate_basic_structure".to_string(), - known_versions: vec![0, 1, 2], + known_versions: vec![0, 1, 2, 3], received: version, })), None => Err(Error::Execution(ExecutionError::VersionNotActive { @@ -75,17 +109,22 @@ impl StateTransitionActionTransformer for DataContractUpdateTransition { >, validation_mode: ValidationMode, execution_context: &mut StateTransitionExecutionContext, - _tx: TransactionArg, + tx: TransactionArg, ) -> Result, Error> { let platform_version = platform.state.current_platform_version()?; - match platform_version + let version = platform_version .drive_abci .validation_and_processing .state_transitions .contract_update_state_transition - .transform_into_action - { + .transform_into_action; + if matches!(self, DataContractUpdateTransition::V1(_)) && version == 0 { + return Ok(ConsensusValidationResult::new_with_error( + unsupported_delta_error(self, platform_version), + )); + } + match version { 0 => self.transform_into_action_v0( block_info, validation_mode, @@ -93,9 +132,11 @@ impl StateTransitionActionTransformer for DataContractUpdateTransition { platform_version, ), 1 => self.transform_into_action_v1( + platform, block_info, validation_mode, execution_context, + tx, platform_version, ), version => Err(Error::Execution(ExecutionError::UnknownVersionMismatch { @@ -262,6 +303,8 @@ mod tests { } } + mod delta; + mod validate_state { use super::*; use serde_json::json; diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/mod.rs index 9a79cc76590..0b770b6d5eb 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/mod.rs @@ -3,6 +3,8 @@ use crate::error::Error; use crate::execution::types::state_transition_execution_context::StateTransitionExecutionContext; use crate::execution::validation::state_transition::data_contract_update::state::v0::DataContractUpdateStateTransitionStateValidationV0; use crate::execution::validation::state_transition::data_contract_update::state::v1::DataContractUpdateStateTransitionStateValidationV1; +use crate::execution::validation::state_transition::data_contract_update::state::v2::DataContractUpdateStateTransitionStateValidationV2; +use crate::execution::validation::state_transition::data_contract_update::unsupported_delta_error; use crate::execution::validation::state_transition::processor::state::StateTransitionStateValidation; use crate::execution::validation::state_transition::ValidationMode; use crate::platform_types::platform::PlatformRef; @@ -16,6 +18,7 @@ use drive::state_transition_action::StateTransitionAction; pub(crate) mod v0; pub(crate) mod v1; +pub(crate) mod v2; impl StateTransitionStateValidation for DataContractUpdateTransition { fn validate_state( @@ -28,14 +31,22 @@ impl StateTransitionStateValidation for DataContractUpdateTransition { tx: TransactionArg, ) -> Result, Error> { let platform_version = platform.state.current_platform_version()?; - - match platform_version + let version = platform_version .drive_abci .validation_and_processing .state_transitions .contract_update_state_transition - .state - { + .state; + // Generations 0 and 1 validate the contract an update embeds. A delta, which embeds + // none, is not active at the protocol versions that select them and is refused at + // decode there; one that got here anyway is refused as an unsupported version, a + // consensus error, before either runs + if matches!(self, DataContractUpdateTransition::V1(_)) && version < 2 { + return Ok(ConsensusValidationResult::new_with_error( + unsupported_delta_error(self, platform_version), + )); + } + match version { 0 => { if action.is_some() { return Err(Error::Execution(ExecutionError::CorruptedCodeExecution("data contract update is calling validate state, and the action is already known. It should not be known at this point"))); @@ -62,9 +73,22 @@ impl StateTransitionStateValidation for DataContractUpdateTransition { platform_version, ) } + 2 => { + if action.is_some() { + return Err(Error::Execution(ExecutionError::CorruptedCodeExecution("data contract update is calling validate state, and the action is already known. It should not be known at this point"))); + } + self.validate_state_v2( + platform, + block_info, + validation_mode, + execution_context, + tx, + platform_version, + ) + } version => Err(Error::Execution(ExecutionError::UnknownVersionMismatch { method: "data contract update transition: validate_state".to_string(), - known_versions: vec![0, 1], + known_versions: vec![0, 1, 2], received: version, })), } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/v0/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/v0/mod.rs index f8428244d9f..5074f7a63a6 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/v0/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/v0/mod.rs @@ -78,6 +78,14 @@ impl DataContractUpdateStateTransitionStateValidationV0 for DataContractUpdateTr tx: TransactionArg, platform_version: &PlatformVersion, ) -> Result, Error> { + // Edited in place: the accessor returns no contract for a delta contract update, which + // the dispatcher refuses before this generation, so an update that embeds its contract + // is judged as it was + let Some(data_contract) = self.data_contract() else { + return Err(Error::Execution(ExecutionError::CorruptedCodeExecution( + "a delta contract update reached a generation that validates updates embedding their contract", + ))); + }; let mut action = self.transform_into_action_v0( block_info, validation_mode, @@ -196,7 +204,7 @@ impl DataContractUpdateStateTransitionStateValidationV0 for DataContractUpdateTr let mut validated_identities = BTreeSet::new(); - for (position, group) in self.data_contract().groups() { + for (position, group) in data_contract.groups() { for member_identity_id in group.members().keys() { if !validated_identities.contains(member_identity_id) { let identity_exists = validate_non_masternode_identity_exists( @@ -217,7 +225,7 @@ impl DataContractUpdateStateTransitionStateValidationV0 for DataContractUpdateTr bump_action, vec![StateError::IdentityMemberOfGroupNotFoundError( IdentityMemberOfGroupNotFoundError::new( - self.data_contract().id(), + data_contract.id(), *position, *member_identity_id, ), @@ -503,10 +511,18 @@ impl DataContractUpdateStateTransitionStateValidationV0 for DataContractUpdateTr execution_context: &mut StateTransitionExecutionContext, platform_version: &PlatformVersion, ) -> Result, Error> { + // Edited in place: the accessor returns no contract for a delta contract update, which + // the dispatcher refuses before this generation, so an update that embeds its contract + // is transformed as it was + let Some(data_contract) = self.data_contract() else { + return Err(Error::Execution(ExecutionError::CorruptedCodeExecution( + "a delta contract update reached a generation that transforms updates embedding their contract", + ))); + }; let mut validation_operations = vec![]; let result = validate_document_schemas_depth_for_check_tx( - self.data_contract(), + data_contract, validation_mode, platform_version, ) diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/v2/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/v2/mod.rs new file mode 100644 index 00000000000..ee65ac75172 --- /dev/null +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/state/v2/mod.rs @@ -0,0 +1,92 @@ +use dpp::block::block_info::BlockInfo; +use dpp::prelude::ConsensusValidationResult; +use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; +use dpp::version::PlatformVersion; +use drive::grovedb::TransactionArg; +use drive::state_transition_action::StateTransitionAction; + +use crate::error::Error; +use crate::execution::types::state_transition_execution_context::StateTransitionExecutionContext; +use crate::execution::validation::state_transition::state_transitions::data_contract_update::delta::{ + as_delta_result, merge_delta_onto_stored_contract, MergedDelta, +}; +use crate::execution::validation::state_transition::state_transitions::data_contract_update::state::v1::DataContractUpdateStateTransitionStateValidationV1; +use crate::execution::validation::state_transition::ValidationMode; +use crate::platform_types::platform::PlatformRef; +use crate::rpc::core::CoreRPCLike; + +pub(in crate::execution::validation::state_transition::state_transitions::data_contract_update) trait DataContractUpdateStateTransitionStateValidationV2 +{ + fn validate_state_v2( + &self, + platform: &PlatformRef, + block_info: &BlockInfo, + validation_mode: ValidationMode, + execution_context: &mut StateTransitionExecutionContext, + tx: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result, Error>; +} + +impl DataContractUpdateStateTransitionStateValidationV2 for DataContractUpdateTransition { + /// Generation 2 (protocol version 15): generation 1 for an update that embeds its + /// contract, and a delta, which carries only what it changes, is validated. + /// + /// A delta is merged onto the stored contract, and the update embedding the merged + /// contract is validated by generation 1 in the delta's place: the update rules against + /// the stored contract, the size caps, the identities new groups and tokens name, token + /// costs, references and moderators. Nothing of that is restated for a delta, so the two + /// forms cannot drift apart. A delta that does not merge, or whose merged contract breaks + /// a structure rule, is refused with a nonce bump before generation 1 runs. + /// + /// The stored contract is read twice, to merge the delta and by generation 1, and both + /// reads are billed. The action stores the merged contract and pays the registration cost + /// of what the delta registers. + fn validate_state_v2( + &self, + platform: &PlatformRef, + block_info: &BlockInfo, + validation_mode: ValidationMode, + execution_context: &mut StateTransitionExecutionContext, + tx: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result, Error> { + let DataContractUpdateTransition::V1(delta) = self else { + return self.validate_state_v1( + platform, + block_info, + validation_mode, + execution_context, + tx, + platform_version, + ); + }; + + match merge_delta_onto_stored_contract( + self, + delta, + platform, + block_info, + validation_mode, + execution_context, + tx, + platform_version, + )? { + MergedDelta::Refused(result) => Ok(result), + MergedDelta::Merged { + full_contract_update, + registration_cost, + } => Ok(as_delta_result( + full_contract_update.validate_state_v1( + platform, + block_info, + validation_mode, + execution_context, + tx, + platform_version, + )?, + registration_cost, + )), + } + } +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/tests/delta.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/tests/delta.rs new file mode 100644 index 00000000000..ba2b7239f86 --- /dev/null +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/tests/delta.rs @@ -0,0 +1,1081 @@ +//! Delta contract updates (version 1 of the update transition, from protocol version 15): +//! block execution, state validation, check_tx's transformation, the size a contract can grow +//! to, and execution proofs. + +use super::*; +use crate::execution::check_tx::CheckTxLevel; +use crate::execution::types::state_transition_execution_context::StateTransitionExecutionContext; +use crate::execution::validation::state_transition::processor::basic_structure::StateTransitionBasicStructureValidationV0; +use crate::execution::validation::state_transition::processor::identity_nonces::StateTransitionIdentityNonceValidationV0; +use crate::execution::validation::state_transition::processor::state::StateTransitionStateValidation; +use crate::execution::validation::state_transition::transformer::StateTransitionActionTransformer; +use crate::execution::validation::state_transition::ValidationMode; +use crate::platform_types::platform::PlatformStateRef; +use dpp::consensus::basic::data_contract::DataContractUpdateEntryKind; +use dpp::consensus::basic::UnsupportedVersionError; +use dpp::consensus::signature::SignatureError; +use dpp::dashcore::Network; +use dpp::data_contract::accessors::v1::DataContractV1Setters; +use dpp::data_contract::associated_token::token_configuration::v0::TokenConfigurationV0; +use dpp::data_contract::associated_token::token_configuration::TokenConfiguration; +use dpp::data_contract::config::v0::{DataContractConfigSettersV0, DataContractConfigV0}; +use dpp::data_contract::schema::DataContractSchemaMethodsV0; +use dpp::identity::identity_nonce::IDENTITY_NONCE_VALUE_FILTER; +use dpp::platform_value::{platform_value, Value}; +use dpp::prelude::ConsensusValidationResult; +use dpp::serialization::PlatformSerializableWithPlatformVersion; +use dpp::state_transition::data_contract_update_transition::accessors::DataContractUpdateTransitionAccessorsV0; +use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; +use dpp::state_transition::proof_result::StateTransitionProofResult; +use dpp::state_transition::{StateTransition, StateTransitionOwned}; +use drive::drive::Drive; +use drive::error::proof::ProofError; +use drive::error::Error as DriveError; +use drive::state_transition_action::system::bump_identity_data_contract_nonce_action::BumpIdentityDataContractNonceActionAccessorsV0; +use drive::state_transition_action::StateTransitionAction; +use platform_version::DefaultForPlatformVersion; +use std::sync::Arc; + +/// A platform at the latest protocol version, with genesis state: a contract's keywords are +/// indexed through the keyword search contract, which only genesis state holds. +fn platform() -> TempPlatform { + TestPlatformBuilder::new() + .build_with_mock_rpc() + .set_genesis_state() +} + +fn new_document_schema() -> Value { + platform_value!({ + "type": "object", + "properties": { + "name": { + "type": "string", + "position": 0 + } + }, + "additionalProperties": false + }) +} + +/// A document type whose schema takes about `properties` times 300 bytes. +fn wide_document_schema(properties: u32) -> Value { + let text = |text: &str| Value::Text(text.to_string()); + let properties = (0..properties) + .map(|position| { + ( + Value::Text(format!("property{position:03}")), + Value::Map(vec![ + (text("type"), text("string")), + (text("maxLength"), Value::U32(63)), + (text("position"), Value::U32(position)), + (text("description"), Value::Text("d".repeat(256))), + ]), + ) + }) + .collect(); + Value::Map(vec![ + (text("type"), text("object")), + (text("properties"), Value::Map(properties)), + (text("additionalProperties"), Value::Bool(false)), + ]) +} + +fn fixture_contract() -> DataContract { + get_data_contract_fixture(None, 0, PlatformVersion::latest().protocol_version) + .data_contract_owned() +} + +/// `contract` at its next version, with a new document type, two keywords and a description. +fn extended(contract: &DataContract) -> DataContract { + let mut updated = contract.clone(); + updated.increment_version(); + updated + .set_document_schema( + "newType", + new_document_schema(), + true, + &mut vec![], + PlatformVersion::latest(), + ) + .expect("expected to add a document type"); + updated.set_keywords(vec!["alpha".to_string(), "beta".to_string()]); + updated.set_description(Some("a described contract".to_string())); + updated +} + +/// The unsigned delta that turns `old_contract` into `new_contract`, under nonce 1. +fn delta(old_contract: &DataContract, new_contract: &DataContract) -> DataContractUpdateTransition { + let transition = DataContractUpdateTransition::from_contract_update( + old_contract, + new_contract, + 1, + PlatformVersion::latest(), + ) + .expect("expected the update to be expressible as a delta"); + assert_matches!(transition, DataContractUpdateTransition::V1(_)); + transition +} + +fn delta_fields(transition: &DataContractUpdateTransition) -> DataContractUpdateTransitionV1 { + let DataContractUpdateTransition::V1(delta) = transition else { + panic!("expected a delta contract update"); + }; + delta.clone() +} + +fn platform_ref<'a>( + platform: &'a TempPlatform, + state: &'a crate::platform_types::platform_state::PlatformState, +) -> PlatformRef<'a, MockCoreRPCLike> { + PlatformRef { + drive: &platform.drive, + state, + config: &platform.config, + core_rpc: &platform.core_rpc, + } +} + +/// State validation as a block runs it. +fn validate( + platform: &TempPlatform, + transition: &DataContractUpdateTransition, +) -> ConsensusValidationResult { + let state = platform.state.load(); + let mut execution_context = StateTransitionExecutionContext::default_for_platform_version( + state + .current_platform_version() + .expect("expected a platform version"), + ) + .expect("expected an execution context"); + transition + .validate_state( + None, + &platform_ref(platform, &state), + ValidationMode::Validator, + &BlockInfo::default(), + &mut execution_context, + None, + ) + .expect("expected state validation to run") +} + +/// The transformation into an action as check_tx runs it. +fn transform_in_check_tx( + platform: &TempPlatform, + transition: &DataContractUpdateTransition, +) -> ConsensusValidationResult { + let state = platform.state.load(); + let mut execution_context = StateTransitionExecutionContext::default_for_platform_version( + state + .current_platform_version() + .expect("expected a platform version"), + ) + .expect("expected an execution context"); + transition + .transform_into_action( + &platform_ref(platform, &state), + &BlockInfo::default(), + &None, + ValidationMode::CheckTx, + &mut execution_context, + None, + ) + .expect("expected the transformation to run") +} + +fn assert_bumps_nonce( + result: &ConsensusValidationResult, + identity_id: Identifier, + contract_id: Identifier, +) { + assert_matches!( + &result.data, + Some(StateTransitionAction::BumpIdentityDataContractNonceAction(action)) + if action.identity_id() == identity_id + && action.data_contract_id() == contract_id + && action.identity_contract_nonce() == 1 + ); +} + +fn stored_contract( + platform: &TempPlatform, + contract_id: Identifier, +) -> DataContract { + platform + .drive + .get_contract_with_fetch_info( + contract_id.to_buffer(), + false, + None, + PlatformVersion::latest(), + ) + .expect("expected to read the contract") + .expect("expected the contract to be stored") + .contract + .clone() +} + +/// The size of `contract` in the format state transitions carry, which the protocol caps. +fn serialized_size(contract: &DataContract) -> usize { + contract + .serialize_to_bytes_with_platform_version(PlatformVersion::latest()) + .expect("expected to serialize the contract") + .len() +} + +/// An identity, its signer, and a contract it owns, stored. +struct OwnedContract { + platform: TempPlatform, + identity: Identity, + signer: SimpleSigner, + key: IdentityPublicKey, + contract: DataContract, +} + +impl OwnedContract { + fn stored(contract: DataContract) -> Self { + let mut platform = platform(); + let (identity, signer, key) = setup_identity(&mut platform, 958, dash_to_credits!(50.0)); + let mut contract = contract; + contract.set_owner_id(identity.id()); + apply_contract(&platform, &contract, BlockInfo::default()); + Self { + platform, + identity, + signer, + key, + contract, + } + } + + /// The signed update that turns the stored contract into `new_contract`, in the form + /// the latest protocol version builds by default, the delta. + async fn signed_update( + &self, + old_contract: &DataContract, + new_contract: &DataContract, + nonce: u64, + ) -> StateTransition { + let transition = DataContractUpdateTransition::new_from_contract_update( + old_contract, + new_contract, + &self.identity.clone().into_partial_identity_info(), + self.key.id(), + nonce, + 0, + &self.signer, + PlatformVersion::latest(), + None, + ) + .await + .expect("expected a contract update transition"); + assert_matches!( + transition, + StateTransition::DataContractUpdate(DataContractUpdateTransition::V1(_)) + ); + transition + } + + /// Executes `transition` in a block of its own and commits it. + fn execute(&self, transition: &StateTransition) -> StateTransitionExecutionResult { + self.execute_in(transition, &BlockInfo::default()) + } + + fn execute_in( + &self, + transition: &StateTransition, + block_info: &BlockInfo, + ) -> StateTransitionExecutionResult { + let platform_version = PlatformVersion::latest(); + let platform_state = self.platform.state.load(); + let bytes = transition + .serialize_to_bytes() + .expect("expected to serialize the transition"); + let transaction = self.platform.drive.grove.start_transaction(); + let processing_result = self + .platform + .platform + .process_raw_state_transitions( + &[bytes], + &platform_state, + block_info, + &transaction, + platform_version, + false, + None, + ) + .expect("expected to process the state transition"); + self.platform + .drive + .grove + .commit_transaction(transaction) + .unwrap() + .expect("expected to commit the block"); + let mut execution_results = processing_result.into_execution_results(); + assert_eq!(execution_results.len(), 1, "{execution_results:?}"); + execution_results.remove(0) + } + + fn nonce(&self) -> Option { + self.platform + .drive + .fetch_identity_contract_nonce( + self.identity.id().to_buffer(), + self.contract.id().to_buffer(), + true, + None, + PlatformVersion::latest(), + ) + .expect("expected to read the identity contract nonce") + .map(|nonce| nonce & IDENTITY_NONCE_VALUE_FILTER) + } +} + +mod block_execution { + use super::*; + + #[tokio::test] + async fn should_execute_a_delta_and_store_the_merged_contract() { + let owned = OwnedContract::stored(fixture_contract()); + let updated = extended(&owned.contract); + let transition = owned.signed_update(&owned.contract, &updated, 1).await; + + assert_matches!( + owned.execute(&transition), + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + + let stored = stored_contract(&owned.platform, owned.contract.id()); + assert_eq!(stored.version(), owned.contract.version() + 1); + assert_eq!(stored.owner_id(), owned.identity.id()); + assert_eq!( + stored.document_types().len(), + owned.contract.document_types().len() + 1 + ); + assert!(stored.has_document_type_for_name("newType")); + assert_eq!(stored.keywords(), updated.keywords()); + assert_eq!(stored.description(), updated.description()); + assert_eq!(stored.created_at(), owned.contract.created_at()); + assert_eq!(owned.nonce(), Some(1)); + } + + /// An update that embeds its contract cannot grow a contract past what one state + /// transition carries. A delta can, a transition at a time, up to the size a contract may + /// take, where it is refused with a consensus error: Drive refuses to store a larger + /// contract, which would stop block execution. + #[tokio::test] + async fn should_grow_a_contract_past_one_transition_and_refuse_it_over_the_size_cap() { + let platform_version = PlatformVersion::latest(); + let max_state_transition_size = + platform_version.system_limits.max_state_transition_size as usize; + let max_serialized_size = platform_version.dpp.contract_versions.max_serialized_size; + let owned = OwnedContract::stored(fixture_contract()); + assert!(serialized_size(&owned.contract) < max_state_transition_size); + + let mut current = owned.contract.clone(); + let mut grown_past_one_transition = false; + let mut refused = None; + for step in 1..=12_u64 { + let mut next = current.clone(); + next.increment_version(); + next.set_document_schema( + &format!("wide{step}"), + wide_document_schema(28), + true, + &mut vec![], + platform_version, + ) + .expect("expected to add a document type"); + let transition = owned.signed_update(¤t, &next, step).await; + assert!( + transition + .serialize_to_bytes() + .expect("expected to serialize the delta") + .len() + < max_state_transition_size + ); + + match owned.execute(&transition) { + StateTransitionExecutionResult::SuccessfulExecution { .. } => { + assert_eq!( + stored_contract(&owned.platform, owned.contract.id()).version(), + next.version() + ); + current = next; + grown_past_one_transition |= + serialized_size(¤t) > max_state_transition_size; + } + result => { + refused = Some((result, next, step)); + break; + } + } + } + + assert!( + grown_past_one_transition, + "expected deltas to grow the contract past what one state transition carries" + ); + let (result, too_large, step) = + refused.expect("expected a delta to be refused at the size cap"); + assert!(serialized_size(¤t) <= max_serialized_size as usize); + assert!(serialized_size(&too_large) > max_serialized_size as usize); + assert_matches!( + result, + StateTransitionExecutionResult::PaidConsensusError { + error: ConsensusError::BasicError(BasicError::DataContractMaxSizeExceededError( + ref error + )), + .. + } if error.max_serialized_size() == max_serialized_size + && error.serialized_size() > u64::from(max_serialized_size) + ); + // The refusal is paid for with the nonce, and the contract stays as it was + assert_eq!(owned.nonce(), Some(step)); + assert_eq!( + stored_contract(&owned.platform, owned.contract.id()).version(), + current.version() + ); + } +} + +mod state_validation { + use super::*; + + #[test] + fn should_merge_a_delta_and_pay_the_registration_cost_of_what_it_registers() { + let platform_version = PlatformVersion::latest(); + let platform = platform(); + let contract = fixture_contract(); + apply_contract(&platform, &contract, BlockInfo::default()); + let updated = extended(&contract); + let transition = delta(&contract, &updated); + + let result = validate(&platform, &transition); + + assert!(result.is_valid(), "unexpected errors: {:?}", result.errors); + let StateTransitionAction::DataContractUpdateAction(action) = + result.into_data().expect("expected an action") + else { + panic!("expected a data contract update action"); + }; + let merged = action.data_contract_ref(); + assert_eq!(merged.id(), contract.id()); + assert_eq!(merged.owner_id(), contract.owner_id()); + assert_eq!(merged.version(), contract.version() + 1); + assert!(merged.has_document_type_for_name("newType")); + assert_eq!( + merged.document_types().len(), + contract.document_types().len() + 1 + ); + assert_eq!(merged.keywords(), updated.keywords()); + assert_eq!(merged.description(), updated.description()); + assert_eq!(merged.created_at(), contract.created_at()); + assert_eq!(action.identity_contract_nonce(), 1); + + let fees = &platform_version.fee_version.data_contract_registration; + let registration_cost = action + .registration_cost(platform_version) + .expect("expected a registration cost"); + assert_eq!( + registration_cost, + fees.document_type_registration_fee + 2 * fees.search_keyword_fee + ); + assert!( + registration_cost + < merged + .registration_cost(platform_version) + .expect("expected a registration cost") + ); + } + + #[test] + fn should_refuse_a_delta_of_a_contract_that_does_not_exist_as_a_paid_nonce_bump() { + let platform = platform(); + let contract = fixture_contract(); + let transition = delta(&contract, &extended(&contract)); + + let result = validate(&platform, &transition); + + assert_matches!( + result.errors.as_slice(), + [ConsensusError::BasicError(BasicError::DataContractNotPresentError(error))] + if error.data_contract_id() == contract.id() + ); + assert_bumps_nonce(&result, contract.owner_id(), contract.id()); + } + + #[test] + fn should_refuse_a_delta_of_an_identity_that_does_not_own_the_contract() { + let platform = platform(); + let contract = fixture_contract(); + apply_contract(&platform, &contract, BlockInfo::default()); + let mut fields = delta_fields(&delta(&contract, &extended(&contract))); + let intruder = Identifier::random(); + fields.owner_id = intruder; + + let result = validate(&platform, &fields.into()); + + assert_matches!( + result.errors.as_slice(), + [ConsensusError::StateError(StateError::DataContractUpdatePermissionError(error))] + if *error.data_contract_id() == contract.id() && *error.identity_id() == intruder + ); + // The intruder's nonce is bumped, never the owner's + assert_bumps_nonce(&result, intruder, contract.id()); + } + + #[test] + fn should_refuse_a_delta_that_does_not_fit_the_stored_contract() { + let platform = platform(); + let contract = fixture_contract(); + apply_contract(&platform, &contract, BlockInfo::default()); + let mut updated = contract.clone(); + updated.increment_version(); + let fields = delta_fields(&delta(&contract, &updated)); + + let mut adds_a_type_the_contract_has = fields.clone(); + adds_a_type_the_contract_has + .new_document_schemas + .insert("niceDocument".to_string(), new_document_schema()); + let result = validate(&platform, &adds_a_type_the_contract_has.into()); + assert_matches!( + result.errors.as_slice(), + [ConsensusError::StateError(StateError::DataContractUpdateEntryAlreadyExistsError(error))] + if error.entry_kind() == DataContractUpdateEntryKind::DocumentType + && error.name() == "niceDocument" + ); + assert_bumps_nonce(&result, contract.owner_id(), contract.id()); + + let mut replaces_a_type_the_contract_lacks = fields; + replaces_a_type_the_contract_lacks + .updated_document_schemas + .insert("missingType".to_string(), new_document_schema()); + let result = validate(&platform, &replaces_a_type_the_contract_lacks.into()); + assert_matches!( + result.errors.as_slice(), + [ConsensusError::StateError(StateError::DataContractUpdateEntryNotFoundError(error))] + if error.entry_kind() == DataContractUpdateEntryKind::DocumentType + && error.name() == "missingType" + ); + assert_bumps_nonce(&result, contract.owner_id(), contract.id()); + } + + /// The merged contract is validated as the contract of an update that embeds it: by the + /// update rules against the stored contract. + #[test] + fn should_hold_a_delta_to_the_update_rules_of_an_update_that_embeds_its_contract() { + let platform = platform(); + let contract = fixture_contract(); + apply_contract(&platform, &contract, BlockInfo::default()); + let mut updated = contract.clone(); + updated.set_version(contract.version() + 2); + + let result = validate(&platform, &delta(&contract, &updated)); + + assert_matches!( + result.errors.as_slice(), + [ConsensusError::BasicError(BasicError::InvalidDataContractVersionError(error))] + if error.expected_version() == contract.version() + 1 + && error.version() == contract.version() + 2 + ); + assert_bumps_nonce(&result, contract.owner_id(), contract.id()); + } + + /// The merged contract is held to the structure rules too, which basic structure checks + /// on an update that embeds its contract and cannot check on a delta: here, that token + /// positions are contiguous. + #[test] + fn should_hold_the_merged_contract_to_the_structure_rules() { + let platform = platform(); + let contract = fixture_contract(); + apply_contract(&platform, &contract, BlockInfo::default()); + let mut updated = contract.clone(); + updated.increment_version(); + let mut fields = delta_fields(&delta(&contract, &updated)); + fields.new_tokens.insert( + 5, + TokenConfiguration::V0(TokenConfigurationV0::default_most_restrictive()), + ); + + let result = validate(&platform, &fields.into()); + + assert_matches!( + result.errors.as_slice(), + [ConsensusError::BasicError( + BasicError::NonContiguousContractTokenPositionsError(_) + )] + ); + assert_bumps_nonce(&result, contract.owner_id(), contract.id()); + } + + /// A delta without a config keeps the stored one, and the merged contract is refused for + /// it as an update that embeds a contract with that config is. + #[test] + fn should_refuse_a_delta_that_keeps_a_config_no_longer_admitted() { + let platform = platform(); + let mut contract = fixture_contract(); + contract.set_config(DataContractConfig::V0(DataContractConfigV0::default())); + apply_contract(&platform, &contract, BlockInfo::default()); + let transition = delta(&contract, &extended(&contract)); + assert!(delta_fields(&transition).config.is_none()); + + let result = validate(&platform, &transition); + + assert_matches!( + result.errors.as_slice(), + [ConsensusError::StateError(StateError::DataContractConfigUpdateError(error))] + if error.additional_message().contains("minimum version") + ); + assert_bumps_nonce(&result, contract.owner_id(), contract.id()); + } +} + +mod basic_structure { + use super::*; + + fn validate_basic_structure( + transition: &DataContractUpdateTransition, + ) -> dpp::validation::SimpleConsensusValidationResult { + transition + .validate_basic_structure(Network::Testnet, PlatformVersion::latest()) + .expect("expected basic structure validation to run") + } + + #[test] + fn should_admit_a_delta_whose_sections_do_not_overlap() { + let contract = fixture_contract(); + let result = validate_basic_structure(&delta(&contract, &extended(&contract))); + assert!(result.is_valid(), "unexpected errors: {:?}", result.errors); + } + + #[test] + fn should_refuse_a_delta_naming_an_entry_in_two_sections_that_cannot_both_apply() { + let contract = fixture_contract(); + let fields = delta_fields(&delta(&contract, &extended(&contract))); + + let mut document_type = fields.clone(); + document_type + .updated_document_schemas + .insert("newType".to_string(), new_document_schema()); + let mut definition = fields.clone(); + definition + .new_schema_defs + .insert("label".to_string(), platform_value!({"type": "string"})); + definition + .updated_schema_defs + .insert("label".to_string(), platform_value!({"type": "string"})); + let mut keyword = fields; + keyword.remove_keywords.push("alpha".to_string()); + + for (fields, kind, name) in [ + ( + document_type, + DataContractUpdateEntryKind::DocumentType, + "newType", + ), + (definition, DataContractUpdateEntryKind::SchemaDef, "label"), + (keyword, DataContractUpdateEntryKind::Keyword, "alpha"), + ] { + let result = validate_basic_structure(&fields.into()); + assert_matches!( + result.errors.as_slice(), + [ConsensusError::BasicError( + BasicError::DataContractUpdateOverlappingEntriesError(error) + )] if error.entry_kind() == kind && error.name() == name + ); + } + } +} + +mod check_tx { + use super::*; + + #[test] + fn should_merge_a_delta_onto_the_stored_contract() { + let platform_version = PlatformVersion::latest(); + let platform = platform(); + let contract = fixture_contract(); + apply_contract(&platform, &contract, BlockInfo::default()); + let transition = delta(&contract, &extended(&contract)); + + let result = transform_in_check_tx(&platform, &transition); + + assert!(result.is_valid(), "unexpected errors: {:?}", result.errors); + let Some(StateTransitionAction::DataContractUpdateAction(action)) = result.data else { + panic!("expected a data contract update action"); + }; + assert!(action + .data_contract_ref() + .has_document_type_for_name("newType")); + assert_eq!( + action + .registration_cost(platform_version) + .expect("expected a registration cost"), + delta_fields(&transition) + .registration_cost(platform_version) + .expect("expected a registration cost") + ); + } + + /// A delta reads state in check_tx. One naming a contract that is not there is refused + /// with a consensus error, never an execution error. + #[test] + fn should_refuse_a_delta_of_a_contract_that_does_not_exist() { + let platform = platform(); + let contract = fixture_contract(); + let transition = delta(&contract, &extended(&contract)); + + let result = transform_in_check_tx(&platform, &transition); + + assert_matches!( + result.errors.as_slice(), + [ConsensusError::BasicError( + BasicError::DataContractNotPresentError(_) + )] + ); + assert_bumps_nonce(&result, contract.owner_id(), contract.id()); + } + + /// check_tx validates a transition's basic structure before it looks for the identity + /// that signed it, so that validation runs for anyone, on whatever a transition can + /// carry. A delta from an identity that does not exist, naming thousands of keywords to + /// add and as many to remove, is refused for its signer: comparing the two lists costs + /// what their lengths add up to, not their product. + #[test] + fn should_refuse_a_delta_with_long_keyword_lists_from_an_unknown_identity_for_its_signer() { + let platform_version = PlatformVersion::latest(); + let platform = platform(); + let contract = fixture_contract(); + let mut next_version = contract.clone(); + next_version.increment_version(); + let mut fields = delta_fields(&delta(&contract, &next_version)); + fields.add_keywords = vec!["a".to_string(); 3_000]; + fields.remove_keywords = vec!["b".to_string(); 3_000]; + let transition: StateTransition = DataContractUpdateTransition::V1(fields).into(); + let bytes = transition + .serialize_to_bytes() + .expect("expected to serialize the transition"); + assert!( + bytes.len() <= platform_version.system_limits.max_state_transition_size as usize, + "the transition must be one a node decodes" + ); + + let state = platform.state.load(); + let result = platform + .check_tx( + &bytes, + CheckTxLevel::FirstTimeCheck, + &platform_ref(&platform, &state), + platform_version, + ) + .expect("expected check_tx to run"); + + assert_matches!( + result.errors.as_slice(), + [ConsensusError::SignatureError( + SignatureError::IdentityNotFoundError(_) + )] + ); + } +} + +/// A delta is not active before protocol version 15, where decoding refuses it. Were one to +/// reach a validator there anyway, every dispatcher refuses it with a consensus error before a +/// shipped generation runs, so it can never stop block execution. +mod before_protocol_version_15 { + use super::*; + + fn platform_at_14() -> TempPlatform { + TestPlatformBuilder::new() + .with_initial_protocol_version(14) + .build_with_mock_rpc() + .set_initial_state_structure() + } + + fn assert_unsupported(errors: &[ConsensusError]) { + assert_matches!( + errors, + [ConsensusError::BasicError(BasicError::UnsupportedVersionError(error))] + if *error == UnsupportedVersionError::new(1, 0, 0) + ); + } + + /// The prover and the verifier generations protocol version 14 selects prove and verify + /// updates that embed their contract. They refuse a delta, which embeds none. + #[test] + fn should_refuse_to_prove_or_verify_a_delta() { + let platform_version_14 = + PlatformVersion::get(14).expect("expected protocol version 14 to exist"); + let platform = platform_at_14(); + let contract = get_data_contract_fixture(None, 0, 14).data_contract_owned(); + platform + .drive + .apply_contract( + &contract, + BlockInfo::default(), + true, + None, + None, + platform_version_14, + ) + .expect("expected to store the contract"); + let transition: StateTransition = delta(&contract, &extended(&contract)).into(); + + let proof = platform + .drive + .prove_state_transition(&transition, None, platform_version_14) + .expect("expected the prover to run"); + assert_matches!(proof.errors.as_slice(), [ProofError::InvalidTransition(_)]); + + let known_contract = Arc::new(contract); + assert_matches!( + Drive::verify_state_transition_was_executed_with_proof( + &transition, + &BlockInfo::default(), + &[], + &|_| Ok(Some(known_contract.clone())), + platform_version_14, + ), + Err(DriveError::Proof(ProofError::InvalidTransition(_))) + ); + } + + #[test] + fn should_refuse_a_delta_in_every_validation_with_a_consensus_error() { + let platform_version_14 = + PlatformVersion::get(14).expect("expected protocol version 14 to exist"); + let platform = platform_at_14(); + let contract = get_data_contract_fixture(None, 0, 14).data_contract_owned(); + platform + .drive + .apply_contract( + &contract, + BlockInfo::default(), + true, + None, + None, + platform_version_14, + ) + .expect("expected to store the contract"); + let transition = delta(&contract, &extended(&contract)); + let state = platform.state.load(); + + let basic_structure = transition + .validate_basic_structure(Network::Testnet, platform_version_14) + .expect("expected a consensus error, not an execution error"); + assert_unsupported(&basic_structure.errors); + + let mut execution_context = + StateTransitionExecutionContext::default_for_platform_version(platform_version_14) + .expect("expected an execution context"); + let nonce = transition + .validate_identity_nonces( + &PlatformStateRef { + drive: &platform.drive, + state: &state, + config: &platform.config, + }, + &BlockInfo::default(), + None, + &mut execution_context, + platform_version_14, + ) + .expect("expected a consensus error, not an execution error"); + assert_unsupported(&nonce.errors); + + let state_result = validate(&platform, &transition); + assert_unsupported(&state_result.errors); + assert!(state_result.data.is_none()); + + let transformed = transform_in_check_tx(&platform, &transition); + assert_unsupported(&transformed.errors); + assert!(transformed.data.is_none()); + } + + /// An update that embeds its contract is validated at protocol version 14 as it was. + #[test] + fn should_validate_an_update_that_embeds_its_contract_as_before() { + let platform_version_14 = + PlatformVersion::get(14).expect("expected protocol version 14 to exist"); + let platform = platform_at_14(); + let contract = get_data_contract_fixture(None, 0, 14).data_contract_owned(); + platform + .drive + .apply_contract( + &contract, + BlockInfo::default(), + true, + None, + None, + platform_version_14, + ) + .expect("expected to store the contract"); + let mut updated = contract.clone(); + updated.increment_version(); + let transition = DataContractUpdateTransition::from_contract_update( + &contract, + &updated, + 1, + platform_version_14, + ) + .expect("expected an update transition"); + assert_matches!(transition, DataContractUpdateTransition::V0(_)); + assert!(transition.data_contract().is_some()); + + let result = validate(&platform, &transition); + + assert!(result.is_valid(), "unexpected errors: {:?}", result.errors); + assert_matches!( + result.data, + Some(StateTransitionAction::DataContractUpdateAction(_)) + ); + } +} + +mod execution_proofs { + use super::*; + + /// Stores `contract`, executes the delta that extends it, and returns the contract as it + /// was before the update, as the update asks for it, the executed transition and the proof + /// of its execution. + async fn executed_delta( + contract: DataContract, + ) -> (DataContract, DataContract, StateTransition, Vec) { + let owned = OwnedContract::stored(contract); + let updated = extended(&owned.contract); + let transition = owned.signed_update(&owned.contract, &updated, 1).await; + // In a later block than the one that stored the contract: a contract that keeps + // history holds one revision per block time + assert_matches!( + owned.execute_in(&transition, &BlockInfo::default_with_time(1_000)), + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + let proof = owned + .platform + .drive + .prove_state_transition(&transition, None, PlatformVersion::latest()) + .expect("expected to prove the state transition"); + assert!(proof.is_valid(), "unexpected errors: {:?}", proof.errors); + ( + owned.contract.clone(), + updated, + transition, + proof.data.expect("expected proof data"), + ) + } + + fn verify( + transition: &StateTransition, + proof: &[u8], + known_contract: Option, + ) -> Result { + let known_contract = known_contract.map(Arc::new); + Drive::verify_state_transition_was_executed_with_proof( + transition, + &BlockInfo::default(), + proof, + &|_| Ok(known_contract.clone()), + PlatformVersion::latest(), + ) + .map(|(_root_hash, outcome)| outcome.into_result()) + } + + fn delta_of(transition: &StateTransition) -> DataContractUpdateTransitionV1 { + let StateTransition::DataContractUpdate(update) = transition else { + panic!("expected a contract update"); + }; + delta_fields(update) + } + + #[tokio::test] + async fn should_verify_the_whole_contract_a_delta_produces() { + let (original, updated, transition, proof) = executed_delta(fixture_contract()).await; + + let result = verify(&transition, &proof, Some(original)) + .expect("expected the proof of the delta's execution to verify"); + + let StateTransitionProofResult::VerifiedDataContract(contract) = result else { + panic!("expected a verified data contract"); + }; + assert_eq!(contract.version(), updated.version()); + assert_eq!(contract.keywords(), updated.keywords()); + assert_eq!(contract.description(), updated.description()); + assert!(contract.has_document_type_for_name("newType")); + } + + /// A delta embeds no contract, so whether its contract keeps history, which decides where + /// the contract is proved, is read from the stored contract. + #[tokio::test] + async fn should_prove_and_verify_a_delta_of_a_contract_that_keeps_history() { + let mut contract = fixture_contract(); + contract.config_mut().set_keeps_history(true); + let (original, updated, transition, proof) = executed_delta(contract).await; + + let result = verify(&transition, &proof, Some(original)) + .expect("expected the proof of the delta's execution to verify"); + + assert_matches!( + result, + StateTransitionProofResult::VerifiedDataContract(contract) + if contract.version() == updated.version() + ); + } + + #[tokio::test] + async fn should_need_the_contract_the_delta_was_built_on() { + let (_original, updated, transition, proof) = executed_delta(fixture_contract()).await; + + // unknown to the verifier's contract lookup + assert_matches!( + verify(&transition, &proof, None), + Err(DriveError::Proof(ProofError::MissingContextRequirement(_))) + ); + // known as it is after the update, which is not the contract the delta merges onto + assert_matches!( + verify(&transition, &proof, Some(updated)), + Err(DriveError::Proof(ProofError::MissingContextRequirement(_))) + ); + } + + /// The whole proved contract must be the one the delta merges into: a delta that names + /// less than the proved state holds did not produce that state. + #[tokio::test] + async fn should_refuse_a_proved_contract_the_delta_does_not_produce() { + let (original, _updated, transition, proof) = executed_delta(fixture_contract()).await; + let mut other = delta_of(&transition); + other.add_keywords.clear(); + + assert_matches!( + verify(&other.into(), &proof, Some(original)), + Err(DriveError::Proof(ProofError::IncorrectProof(_))) + ); + } + + #[tokio::test] + async fn should_refuse_a_delta_a_node_would_refuse() { + let (original, _updated, transition, proof) = executed_delta(fixture_contract()).await; + + // an entry in two sections that cannot both apply + let mut overlapping = delta_of(&transition); + overlapping + .updated_document_schemas + .insert("newType".to_string(), new_document_schema()); + assert_matches!( + verify(&overlapping.into(), &proof, Some(original.clone())), + Err(DriveError::Proof(ProofError::InvalidTransition(message))) + if message.contains("two conflicting sections") + ); + + // an entry to replace that the contract does not have + let mut misfit = delta_of(&transition); + misfit + .updated_document_schemas + .insert("missingType".to_string(), new_document_schema()); + assert_matches!( + verify(&misfit.into(), &proof, Some(original)), + Err(DriveError::Proof(ProofError::InvalidTransition(message))) + if message.contains("missingType") + ); + } +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/transform_into_action/v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/transform_into_action/v1/mod.rs index 99447398028..33c23f27950 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/transform_into_action/v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/data_contract_update/transform_into_action/v1/mod.rs @@ -11,12 +11,28 @@ use crate::error::Error; use crate::execution::types::state_transition_execution_context::{ StateTransitionExecutionContext, StateTransitionExecutionContextMethodsV0, }; +use crate::execution::validation::state_transition::state_transitions::data_contract_update::delta::{ + as_delta_result, merge_delta_onto_stored_contract, MergedDelta, +}; use crate::execution::validation::state_transition::state_transitions::data_contract_update::state::v0::DataContractUpdateStateTransitionStateValidationV0; use crate::execution::validation::state_transition::ValidationMode; +use crate::platform_types::platform::PlatformRef; +use crate::rpc::core::CoreRPCLike; +use drive::grovedb::TransactionArg; pub(in crate::execution::validation::state_transition::state_transitions::data_contract_update) trait DataContractUpdateStateTransitionTransformIntoActionV1 { - fn transform_into_action_v1( + fn transform_into_action_v1( + &self, + platform: &PlatformRef, + block_info: &BlockInfo, + validation_mode: ValidationMode, + execution_context: &mut StateTransitionExecutionContext, + tx: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result, Error>; + + fn transform_full_contract_update_into_action_v1( &self, block_info: &BlockInfo, validation_mode: ValidationMode, @@ -26,15 +42,68 @@ pub(in crate::execution::validation::state_transition::state_transitions::data_c } impl DataContractUpdateStateTransitionTransformIntoActionV1 for DataContractUpdateTransition { - /// v0, then, in check_tx and recheck, the compiled size cap. + /// [`Self::transform_full_contract_update_into_action_v1`] for an update that embeds its + /// contract. A delta, which carries only what it changes, is merged onto the stored + /// contract first, and the update embedding the merged contract is transformed in its + /// place; the action pays the registration cost of what the delta registers. + /// + /// Unlike an update that embeds its contract, a delta reads state here, in check_tx too: + /// one whose contract is not in state, because it does not exist or is created earlier in + /// the same block, is refused, and so is one that does not merge or whose merged contract + /// breaks a structure rule. A block refuses the same in state validation. + fn transform_into_action_v1( + &self, + platform: &PlatformRef, + block_info: &BlockInfo, + validation_mode: ValidationMode, + execution_context: &mut StateTransitionExecutionContext, + tx: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result, Error> { + let DataContractUpdateTransition::V1(delta) = self else { + return self.transform_full_contract_update_into_action_v1( + block_info, + validation_mode, + execution_context, + platform_version, + ); + }; + + match merge_delta_onto_stored_contract( + self, + delta, + platform, + block_info, + validation_mode, + execution_context, + tx, + platform_version, + )? { + MergedDelta::Refused(result) => Ok(result), + MergedDelta::Merged { + full_contract_update, + registration_cost, + } => Ok(as_delta_result( + full_contract_update.transform_full_contract_update_into_action_v1( + block_info, + validation_mode, + execution_context, + platform_version, + )?, + registration_cost, + )), + } + } + + /// v0, then, in check_tx and recheck, the size caps. /// - /// A block holds an update to the cap in state validation, which check_tx and recheck do not + /// A block holds an update to the caps in state validation, which check_tx and recheck do not /// run, once the stored contract's creation fields, which the transition does not carry, are /// restored, and with the time fields of the block that includes it. check_tx sees neither: /// the contract may be created earlier in the same block, and the block is not yet known. So /// it measures the updated contract with all six time fields at their widest encodings, /// which no block can exceed, and charges that compile. - fn transform_into_action_v1( + fn transform_full_contract_update_into_action_v1( &self, block_info: &BlockInfo, validation_mode: ValidationMode, @@ -130,7 +199,7 @@ mod tests { StateTransitionExecutionContext::default_for_platform_version(platform_version) .expect("failed to create execution context"); transition - .transform_into_action_v1( + .transform_full_contract_update_into_action_v1( &BlockInfo::default(), validation_mode, &mut execution_context, diff --git a/packages/rs-drive/src/prove/prove_state_transition/mod.rs b/packages/rs-drive/src/prove/prove_state_transition/mod.rs index 18274c076b7..5ccbdcb8115 100644 --- a/packages/rs-drive/src/prove/prove_state_transition/mod.rs +++ b/packages/rs-drive/src/prove/prove_state_transition/mod.rs @@ -1,5 +1,6 @@ mod v0; mod v1; +mod v2; use crate::drive::Drive; use crate::error::drive::DriveError; @@ -36,9 +37,10 @@ impl Drive { match platform_version.drive.methods.prove.prove_state_transition { 0 => self.prove_state_transition_v0(state_transition, transaction, platform_version), 1 => self.prove_state_transition_v1(state_transition, transaction, platform_version), + 2 => self.prove_state_transition_v2(state_transition, transaction, platform_version), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "prove_state_transition".to_string(), - known_versions: vec![0, 1], + known_versions: vec![0, 1, 2], received: version, })), } diff --git a/packages/rs-drive/src/prove/prove_state_transition/v0/mod.rs b/packages/rs-drive/src/prove/prove_state_transition/v0/mod.rs index 6dcc86658d6..92beb07497c 100644 --- a/packages/rs-drive/src/prove/prove_state_transition/v0/mod.rs +++ b/packages/rs-drive/src/prove/prove_state_transition/v0/mod.rs @@ -78,18 +78,27 @@ impl Drive { transaction: TransactionArg, platform_version: &PlatformVersion, ) -> Result>, Error> { - self.prove_state_transition_internal(state_transition, transaction, false, platform_version) + self.prove_state_transition_internal( + state_transition, + transaction, + false, + None, + platform_version, + ) } /// The proof of a state transition's execution, shared by every version of /// `prove_state_transition`. With `carries_owner_balance` (from version 1) the /// proof of an owned, fee-paying transition also carries the owner's credit - /// balance. + /// balance. `delta_contract_keeps_history` (from version 2) says whether the + /// contract a delta contract update names keeps history, which the transition, + /// embedding no contract, cannot say. pub(in crate::prove::prove_state_transition) fn prove_state_transition_internal( &self, state_transition: &StateTransition, transaction: TransactionArg, carries_owner_balance: bool, + delta_contract_keeps_history: Option, platform_version: &PlatformVersion, ) -> Result>, Error> { let path_query = match state_transition { @@ -101,7 +110,23 @@ impl Drive { } } StateTransition::DataContractUpdate(st) => { - if st.data_contract().config().keeps_history() { + // Edited in place: an update that embeds its contract, the only form active + // through protocol version 14, is proved as it was. A delta, which embeds + // none, is proved from what version 2 read of the stored contract and refused + // by versions 0 and 1, which read nothing + let keeps_history = match (st.data_contract(), delta_contract_keeps_history) { + (Some(data_contract), _) => data_contract.config().keeps_history(), + (None, Some(keeps_history)) => keeps_history, + (None, None) => { + return Ok(ProofCreationResult::new_with_error( + ProofError::InvalidTransition( + "a delta data contract update is proved from prove_state_transition 2" + .to_string(), + ), + )); + } + }; + if keeps_history { contract_ids_to_historical_path_query(&st.modified_data_ids()) } else { contract_ids_to_non_historical_path_query(&st.modified_data_ids()) diff --git a/packages/rs-drive/src/prove/prove_state_transition/v1/mod.rs b/packages/rs-drive/src/prove/prove_state_transition/v1/mod.rs index e9932b7b9af..c958b2e1354 100644 --- a/packages/rs-drive/src/prove/prove_state_transition/v1/mod.rs +++ b/packages/rs-drive/src/prove/prove_state_transition/v1/mod.rs @@ -17,6 +17,12 @@ impl Drive { transaction: TransactionArg, platform_version: &PlatformVersion, ) -> Result>, Error> { - self.prove_state_transition_internal(state_transition, transaction, true, platform_version) + self.prove_state_transition_internal( + state_transition, + transaction, + true, + None, + platform_version, + ) } } diff --git a/packages/rs-drive/src/prove/prove_state_transition/v2/mod.rs b/packages/rs-drive/src/prove/prove_state_transition/v2/mod.rs new file mode 100644 index 00000000000..2dcdac69839 --- /dev/null +++ b/packages/rs-drive/src/prove/prove_state_transition/v2/mod.rs @@ -0,0 +1,55 @@ +use crate::drive::Drive; +use crate::error::proof::ProofError; +use crate::error::Error; +use crate::prove::prove_state_transition::ProofCreationResult; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::config::v0::DataContractConfigGettersV0; +use dpp::state_transition::data_contract_update_transition::accessors::DataContractUpdateTransitionAccessorsV0; +use dpp::state_transition::StateTransition; +use dpp::version::PlatformVersion; +use grovedb::TransactionArg; + +impl Drive { + /// Version 2: version 1, and a delta contract update (version 1 of the update + /// transition, from protocol version 15) is proved too. Its proof is the one of an + /// update that embeds its contract, the contract and its owner's credit balance; as a + /// delta embeds no contract, whether the contract keeps history, which selects where + /// the contract is proved, is read from the stored contract. Every other transition + /// proves as in version 1, in the same layout. + pub(super) fn prove_state_transition_v2( + &self, + state_transition: &StateTransition, + transaction: TransactionArg, + platform_version: &PlatformVersion, + ) -> Result>, Error> { + let delta_contract_keeps_history = match state_transition { + StateTransition::DataContractUpdate(update) if update.data_contract().is_none() => { + let contract_id = update.data_contract_id(); + let Some(contract_fetch_info) = self.get_contract_with_fetch_info( + contract_id.to_buffer(), + false, + transaction, + platform_version, + )? + else { + return Ok(ProofCreationResult::new_with_error( + ProofError::UnknownContract(format!( + "unknown contract with id {} in the proof of a delta contract update", + contract_id + )), + )); + }; + Some(contract_fetch_info.contract.config().keeps_history()) + } + _ => None, + }; + + self.prove_state_transition_internal( + state_transition, + transaction, + true, + delta_contract_keeps_history, + platform_version, + ) + } +} diff --git a/packages/rs-drive/src/state_transition_action/contract/data_contract_update/mod.rs b/packages/rs-drive/src/state_transition_action/contract/data_contract_update/mod.rs index 17db5ed7650..edbd2f8908e 100644 --- a/packages/rs-drive/src/state_transition_action/contract/data_contract_update/mod.rs +++ b/packages/rs-drive/src/state_transition_action/contract/data_contract_update/mod.rs @@ -2,17 +2,25 @@ pub mod transformer; /// v0 pub mod v0; +/// v1 +pub mod v1; use crate::state_transition_action::contract::data_contract_update::v0::DataContractUpdateTransitionActionV0; +use crate::state_transition_action::contract::data_contract_update::v1::DataContractUpdateTransitionActionV1; use derive_more::From; use dpp::data_contract::DataContract; +use dpp::fee::Credits; use dpp::prelude::{IdentityNonce, UserFeeIncrease}; +use dpp::version::PlatformVersion; +use dpp::ProtocolError; /// data contract update transition action #[derive(Debug, Clone, From)] pub enum DataContractUpdateTransitionAction { /// v0 V0(DataContractUpdateTransitionActionV0), + /// v1: the action of a delta update, which carries the delta's registration cost + V1(DataContractUpdateTransitionActionV1), } impl DataContractUpdateTransitionAction { @@ -20,12 +28,14 @@ impl DataContractUpdateTransitionAction { pub fn data_contract(self) -> DataContract { match self { DataContractUpdateTransitionAction::V0(transition) => transition.data_contract, + DataContractUpdateTransitionAction::V1(transition) => transition.data_contract, } } /// data contract ref pub fn data_contract_ref(&self) -> &DataContract { match self { DataContractUpdateTransitionAction::V0(transition) => &transition.data_contract, + DataContractUpdateTransitionAction::V1(transition) => &transition.data_contract, } } @@ -33,6 +43,7 @@ impl DataContractUpdateTransitionAction { pub fn data_contract_mut(&mut self) -> &mut DataContract { match self { DataContractUpdateTransitionAction::V0(transition) => &mut transition.data_contract, + DataContractUpdateTransitionAction::V1(transition) => &mut transition.data_contract, } } @@ -42,6 +53,9 @@ impl DataContractUpdateTransitionAction { DataContractUpdateTransitionAction::V0(transition) => { transition.identity_contract_nonce } + DataContractUpdateTransitionAction::V1(transition) => { + transition.identity_contract_nonce + } } } @@ -49,6 +63,35 @@ impl DataContractUpdateTransitionAction { pub fn user_fee_increase(&self) -> UserFeeIncrease { match self { DataContractUpdateTransitionAction::V0(transition) => transition.user_fee_increase, + DataContractUpdateTransitionAction::V1(transition) => transition.user_fee_increase, + } + } + + /// The action of a delta update, from the action of the update carrying the whole + /// contract that the delta was merged into, which is `self`, and the registration cost + /// of what the delta registers. + pub fn into_delta_action(self, registration_cost: Credits) -> Self { + DataContractUpdateTransitionActionV1 { + identity_contract_nonce: self.identity_contract_nonce(), + user_fee_increase: self.user_fee_increase(), + data_contract: self.data_contract(), + registration_cost, + } + .into() + } + + /// The registration cost this update pays on top of its storage and processing fees: + /// the whole contract's for an update that carries the whole contract, and that of + /// what it registers alone for a delta. + pub fn registration_cost( + &self, + platform_version: &PlatformVersion, + ) -> Result { + match self { + DataContractUpdateTransitionAction::V0(transition) => { + transition.data_contract.registration_cost(platform_version) + } + DataContractUpdateTransitionAction::V1(transition) => Ok(transition.registration_cost), } } } @@ -167,6 +210,40 @@ mod tests { ); } + #[test] + fn should_pay_the_registration_cost_of_what_a_delta_registers() { + let platform_version = PlatformVersion::latest(); + let action = make_action(); + let whole_contract_cost = action + .data_contract_ref() + .registration_cost(platform_version) + .expect("expected a registration cost"); + assert_eq!( + action + .registration_cost(platform_version) + .expect("expected a registration cost"), + whole_contract_cost + ); + + let contract_id = action.data_contract_ref().id(); + let delta_action = action.into_delta_action(7); + + assert!(matches!( + delta_action, + DataContractUpdateTransitionAction::V1(_) + )); + assert_eq!(delta_action.identity_contract_nonce(), 99); + assert_eq!(delta_action.user_fee_increase(), 3); + assert_eq!(delta_action.data_contract_ref().id(), contract_id); + assert_ne!(whole_contract_cost, 7); + assert_eq!( + delta_action + .registration_cost(platform_version) + .expect("expected a registration cost"), + 7 + ); + } + #[test] fn test_debug() { let action = make_action(); diff --git a/packages/rs-drive/src/state_transition_action/contract/data_contract_update/transformer.rs b/packages/rs-drive/src/state_transition_action/contract/data_contract_update/transformer.rs index adf23f48b50..9085383935a 100644 --- a/packages/rs-drive/src/state_transition_action/contract/data_contract_update/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/contract/data_contract_update/transformer.rs @@ -1,15 +1,43 @@ use crate::state_transition_action::contract::data_contract_update::v0::DataContractUpdateTransitionActionV0; use crate::state_transition_action::contract::data_contract_update::DataContractUpdateTransitionAction; use dpp::block::block_info::BlockInfo; +use dpp::consensus::basic::UnsupportedVersionError; use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; use dpp::validation::operations::ProtocolValidationOperation; use dpp::ProtocolError; use platform_version::version::PlatformVersion; +/// The refusal of a delta update that reaches a transformer of updates carrying the whole +/// contract. A delta becomes an action only once it is merged onto the stored contract, which +/// its validation does from protocol version 15 +/// ([`DataContractUpdateTransitionAction::into_delta_action`]), so one that gets here was not +/// merged. It is refused as an unsupported version, a consensus error, rather than with an +/// error that would stop block execution. +fn delta_not_merged( + transition: &DataContractUpdateTransition, + platform_version: &PlatformVersion, +) -> ProtocolError { + let bounds = &platform_version + .dpp + .state_transition_serialization_versions + .contract_update_state_transition; + ProtocolError::ConsensusError(Box::new( + UnsupportedVersionError::new( + transition.feature_version(), + bounds.min_version, + bounds.max_version, + ) + .into(), + )) +} + impl DataContractUpdateTransitionAction { /// tries to transform the DataContractUpdateTransition into a DataContractUpdateTransitionAction /// if validation is true the data contract transformation verifies that the data contract is valid /// if validation is false, the data contract base structure is created regardless of if it is valid + /// + /// A delta update, which embeds no contract, is refused with a consensus error: see + /// [`Self::into_delta_action`]. pub fn try_from_transition( value: DataContractUpdateTransition, block_info: &BlockInfo, @@ -28,12 +56,16 @@ impl DataContractUpdateTransitionAction { )? .into()) } + DataContractUpdateTransition::V1(_) => Err(delta_not_merged(&value, platform_version)), } } /// tries to transform the borrowed DataContractUpdateTransition into a DataContractUpdateTransitionAction /// if validation is true the data contract transformation verifies that the data contract is valid /// if validation is false, the data contract base structure is created regardless of if it is valid + /// + /// A delta update, which embeds no contract, is refused with a consensus error: see + /// [`Self::into_delta_action`]. pub fn try_from_borrowed_transition( value: &DataContractUpdateTransition, block_info: &BlockInfo, @@ -52,6 +84,59 @@ impl DataContractUpdateTransitionAction { )? .into(), ), + DataContractUpdateTransition::V1(_) => Err(delta_not_merged(value, platform_version)), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use assert_matches::assert_matches; + use dpp::consensus::basic::BasicError; + use dpp::consensus::ConsensusError; + use dpp::data_contract::accessors::v0::DataContractV0Setters; + use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; + use dpp::tests::fixtures::get_data_contract_fixture; + + /// A delta is merged onto the stored contract before it becomes an action. One that reaches + /// a transformer of updates carrying the whole contract is refused with a consensus error, + /// never an error that would stop block execution. + #[test] + fn should_refuse_a_delta_that_was_not_merged_with_a_consensus_error() { + let platform_version = PlatformVersion::latest(); + let old_contract = get_data_contract_fixture(None, 0, platform_version.protocol_version) + .data_contract_owned(); + let mut new_contract = old_contract.clone(); + new_contract.increment_version(); + let delta: DataContractUpdateTransition = + DataContractUpdateTransitionV1::from_contract_update(&old_contract, &new_contract, 1) + .expect("expected a delta") + .into(); + + for result in [ + DataContractUpdateTransitionAction::try_from_borrowed_transition( + &delta, + &BlockInfo::default(), + true, + &mut vec![], + platform_version, + ), + DataContractUpdateTransitionAction::try_from_transition( + delta.clone(), + &BlockInfo::default(), + true, + &mut vec![], + platform_version, + ), + ] { + assert_matches!( + result, + Err(ProtocolError::ConsensusError(error)) if matches!( + *error, + ConsensusError::BasicError(BasicError::UnsupportedVersionError(_)) + ) + ); } } } diff --git a/packages/rs-drive/src/state_transition_action/contract/data_contract_update/v1/mod.rs b/packages/rs-drive/src/state_transition_action/contract/data_contract_update/v1/mod.rs new file mode 100644 index 00000000000..8df1f59a47c --- /dev/null +++ b/packages/rs-drive/src/state_transition_action/contract/data_contract_update/v1/mod.rs @@ -0,0 +1,23 @@ +use dpp::data_contract::DataContract; +use dpp::fee::Credits; +use dpp::prelude::{IdentityNonce, UserFeeIncrease}; + +/// The action of a delta data contract update (version 1 of the transition, from protocol +/// version 15). +/// +/// The delta was merged onto the stored contract, so `data_contract` is the whole contract to +/// store, as in the action of an update that carries it. What differs is the fee: an update +/// that carries the whole contract pays the registration cost of the whole contract again, +/// while a delta registers only what it adds, so its action carries that cost, which only the +/// transition knows. +#[derive(Debug, Clone)] +pub struct DataContractUpdateTransitionActionV1 { + /// The updated contract, as it will be stored. + pub data_contract: DataContract, + /// The identity contract nonce of the transition. + pub identity_contract_nonce: IdentityNonce, + /// The user fee increase of the transition. + pub user_fee_increase: UserFeeIncrease, + /// The registration cost of what the delta registers. + pub registration_cost: Credits, +} diff --git a/packages/rs-drive/src/state_transition_action/system/bump_identity_data_contract_nonce_action/transformer.rs b/packages/rs-drive/src/state_transition_action/system/bump_identity_data_contract_nonce_action/transformer.rs index 469498ba70a..e70b89022b1 100644 --- a/packages/rs-drive/src/state_transition_action/system/bump_identity_data_contract_nonce_action/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/system/bump_identity_data_contract_nonce_action/transformer.rs @@ -215,6 +215,9 @@ impl BumpIdentityDataContractNonceAction { DataContractUpdateTransition::V0(v0) => { BumpIdentityDataContractNonceActionV0::from_data_contract_update(v0).into() } + DataContractUpdateTransition::V1(v1) => { + BumpIdentityDataContractNonceActionV0::from_data_contract_update_v1(v1).into() + } } } @@ -226,6 +229,10 @@ impl BumpIdentityDataContractNonceAction { DataContractUpdateTransition::V0(v0) => { BumpIdentityDataContractNonceActionV0::from_borrowed_data_contract_update(v0).into() } + DataContractUpdateTransition::V1(v1) => { + BumpIdentityDataContractNonceActionV0::from_borrowed_data_contract_update_v1(v1) + .into() + } } } @@ -237,6 +244,10 @@ impl BumpIdentityDataContractNonceAction { DataContractUpdateTransitionAction::V0(v0) => { BumpIdentityDataContractNonceActionV0::from_data_contract_update_action(v0).into() } + DataContractUpdateTransitionAction::V1(v1) => { + BumpIdentityDataContractNonceActionV0::from_data_contract_update_action_v1(v1) + .into() + } } } @@ -266,6 +277,12 @@ impl BumpIdentityDataContractNonceAction { value: &DataContractUpdateTransitionAction, ) -> Self { match value { + DataContractUpdateTransitionAction::V1(v1) => { + BumpIdentityDataContractNonceActionV0::from_borrowed_data_contract_update_action_v1( + v1, + ) + .into() + } DataContractUpdateTransitionAction::V0(v0) => { BumpIdentityDataContractNonceActionV0::from_borrowed_data_contract_update_action(v0) .into() diff --git a/packages/rs-drive/src/state_transition_action/system/bump_identity_data_contract_nonce_action/v0/transformer.rs b/packages/rs-drive/src/state_transition_action/system/bump_identity_data_contract_nonce_action/v0/transformer.rs index edc62789a80..29373ac8e64 100644 --- a/packages/rs-drive/src/state_transition_action/system/bump_identity_data_contract_nonce_action/v0/transformer.rs +++ b/packages/rs-drive/src/state_transition_action/system/bump_identity_data_contract_nonce_action/v0/transformer.rs @@ -4,11 +4,14 @@ use dpp::prelude::UserFeeIncrease; use dpp::state_transition::batch_transition::document_base_transition::DocumentBaseTransition; use dpp::state_transition::contract_fee_claim_transition::v0::ContractFeeClaimTransitionV0; use dpp::state_transition::contract_user_moderation_transition::v0::ContractUserModerationTransitionV0; -use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransitionV0; +use dpp::state_transition::data_contract_update_transition::{ + DataContractUpdateTransitionV0, DataContractUpdateTransitionV1, +}; use dpp::state_transition::batch_transition::document_base_transition::v0::v0_methods::DocumentBaseTransitionV0Methods; use dpp::state_transition::batch_transition::token_base_transition::TokenBaseTransition; use dpp::state_transition::batch_transition::token_base_transition::v0::v0_methods::TokenBaseTransitionV0Methods; use crate::state_transition_action::contract::data_contract_update::v0::DataContractUpdateTransitionActionV0; +use crate::state_transition_action::contract::data_contract_update::v1::DataContractUpdateTransitionActionV1; use crate::state_transition_action::batch::batched_transition::document_transition::document_base_transition_action::{DocumentBaseTransitionAction, DocumentBaseTransitionActionAccessorsV0}; use crate::state_transition_action::batch::batched_transition::token_transition::token_base_transition_action::{TokenBaseTransitionAction, TokenBaseTransitionActionAccessorsV0}; use crate::state_transition_action::system::bump_identity_data_contract_nonce_action::BumpIdentityDataContractNonceActionV0; @@ -158,6 +161,22 @@ impl BumpIdentityDataContractNonceActionV0 { } } + /// from a delta data contract update, which names its contract and its owner itself + pub fn from_data_contract_update_v1(value: DataContractUpdateTransitionV1) -> Self { + Self::from_borrowed_data_contract_update_v1(&value) + } + + /// from a borrowed delta data contract update, which names its contract and its owner + /// itself + pub fn from_borrowed_data_contract_update_v1(value: &DataContractUpdateTransitionV1) -> Self { + BumpIdentityDataContractNonceActionV0 { + identity_id: value.owner_id, + data_contract_id: value.data_contract_id, + identity_contract_nonce: value.identity_contract_nonce, + user_fee_increase: value.user_fee_increase, + } + } + /// from borrowed contract user moderation transition pub fn from_borrowed_contract_user_moderation( value: &ContractUserModerationTransitionV0, @@ -210,6 +229,25 @@ impl BumpIdentityDataContractNonceActionV0 { } } + /// from the action of a delta data contract update + pub fn from_data_contract_update_action_v1( + value: DataContractUpdateTransitionActionV1, + ) -> Self { + Self::from_borrowed_data_contract_update_action_v1(&value) + } + + /// from the borrowed action of a delta data contract update + pub fn from_borrowed_data_contract_update_action_v1( + value: &DataContractUpdateTransitionActionV1, + ) -> Self { + BumpIdentityDataContractNonceActionV0 { + identity_id: value.data_contract.owner_id(), + data_contract_id: value.data_contract.id(), + identity_contract_nonce: value.identity_contract_nonce, + user_fee_increase: value.user_fee_increase, + } + } + /// from borrowed data contract update action pub fn from_borrowed_data_contract_update_action( value: &DataContractUpdateTransitionActionV0, diff --git a/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/mod.rs b/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/mod.rs index c0101d72c3a..002923493d2 100644 --- a/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/mod.rs +++ b/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/mod.rs @@ -11,6 +11,7 @@ use dpp::state_transition::StateTransition; use dpp::version::PlatformVersion; mod v0; +mod v2; impl Drive { /// Verifies a state transition against a provided proof, returning the @@ -118,8 +119,8 @@ impl Drive { // producer's `prove_state_transition` generation, so either one verifies a // proof from any producer whose prover generation this build knows; an // unknown prover generation is refused. Protocol versions 1 to 13 select - // verifier and prover generation 0, and protocol versions from 14 select 1 - // for both, so a proof checked at the version that made it runs the same body + // verifier and prover generation 0, and protocol version 14 selects 1 for + // both, so a proof checked at the version that made it runs the same body // with the layout that version's verifier generation named. 0 | 1 => Drive::verify_state_transition_was_executed_with_proof_v0( state_transition, @@ -129,17 +130,29 @@ impl Drive { Self::proof_carries_owner_balance(query_platform_version)?, platform_version, ), + // Generation 2, from protocol version 15, also verifies a delta contract + // update, against the contract the delta was built on. Every other transition + // runs the same body. + 2 => Drive::verify_state_transition_was_executed_with_proof_v2( + state_transition, + block_info, + proof, + known_contracts_provider_fn, + Self::proof_carries_owner_balance(query_platform_version)?, + platform_version, + ), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "verify_state_transition_was_executed_with_proof".to_string(), - known_versions: vec![0, 1], + known_versions: vec![0, 1, 2], received: version, })), } } /// Whether a producer at `query_platform_version` proves an owned, fee-paying - /// transition together with its owner's credit balance: generation 1 of - /// `prove_state_transition` does, generation 0 does not. + /// transition together with its owner's credit balance: generations 1 and 2 of + /// `prove_state_transition` do, generation 0 does not. Generation 2 proves in the + /// layout of generation 1. fn proof_carries_owner_balance( query_platform_version: &PlatformVersion, ) -> Result { @@ -150,10 +163,10 @@ impl Drive { .prove_state_transition { 0 => Ok(false), - 1 => Ok(true), + 1 | 2 => Ok(true), version => Err(Error::Drive(DriveError::UnknownVersionMismatch { method: "prove_state_transition".to_string(), - known_versions: vec![0, 1], + known_versions: vec![0, 1, 2], received: version, })), } diff --git a/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/v0/mod.rs b/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/v0/mod.rs index 779af2b8713..d4543439e66 100644 --- a/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/v0/mod.rs +++ b/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/v0/mod.rs @@ -89,7 +89,8 @@ use crate::query::{ContractLookupFn, SingleDocumentDriveQuery, SingleDocumentDri impl Drive { /// The verification of generations 0 and 1 of - /// `verify_state_transition_was_executed_with_proof`. With + /// `verify_state_transition_was_executed_with_proof`, which generation 2 runs too once + /// it has merged a delta contract update. With /// `carries_owner_balance` (a producer at `prove_state_transition` generation /// 1) the proof of an owned, fee-paying transition also carries the owner's /// credit balance: a document batch's proof is verified strictly as one merged @@ -135,27 +136,32 @@ impl Drive { Ok((root_hash, VerifiedDataContract(contract))) } StateTransition::DataContractUpdate(data_contract_update) => { + // Edited in place: an update that embeds its contract, the only form active + // through protocol version 14, is verified as it was. A delta embeds none: + // generation 2 merges it onto the contract it was built on and hands this + // body the update embedding the result + let Some(data_contract) = data_contract_update.data_contract() else { + return Err(Error::Proof(ProofError::InvalidTransition( + "a delta data contract update is verified from verify_state_transition_was_executed_with_proof 2" + .to_string(), + ))); + }; // we expect to get a contract that matches the state transition - let keeps_history = data_contract_update - .data_contract() - .config() - .keeps_history(); + let keeps_history = data_contract.config().keeps_history(); let (root_hash, contract) = Drive::verify_contract( proof, Some(keeps_history), carries_owner_balance, true, - data_contract_update.data_contract().id().into_buffer(), + data_contract.id().into_buffer(), platform_version, )?; - let contract = contract.ok_or(Error::Proof(ProofError::IncorrectProof(format!("proof did not contain contract with id {} expected to exist because of state transition (update", data_contract_update.data_contract().id()))))?; + let contract = contract.ok_or(Error::Proof(ProofError::IncorrectProof(format!("proof did not contain contract with id {} expected to exist because of state transition (update", data_contract.id()))))?; let contract_for_serialization: DataContractInSerializationFormat = contract .clone() .try_into_platform_versioned(platform_version)?; - if let Some(mismatch) = - contract_for_serialization.first_mismatch(data_contract_update.data_contract()) - { - return Err(Error::Proof(ProofError::IncorrectProof(format!("proof of state transition execution did not contain exact expected contract after update with id {}: {}", data_contract_update.data_contract().id(), mismatch)))); + if let Some(mismatch) = contract_for_serialization.first_mismatch(data_contract) { + return Err(Error::Proof(ProofError::IncorrectProof(format!("proof of state transition execution did not contain exact expected contract after update with id {}: {}", data_contract.id(), mismatch)))); } Ok((root_hash, VerifiedDataContract(contract))) } diff --git a/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/v2/mod.rs b/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/v2/mod.rs new file mode 100644 index 00000000000..23d67257e04 --- /dev/null +++ b/packages/rs-drive/src/verify/state_transition/verify_state_transition_was_executed_with_proof/v2/mod.rs @@ -0,0 +1,101 @@ +use crate::drive::Drive; +use crate::error::proof::ProofError; +use crate::error::Error; +use crate::query::ContractLookupFn; +use crate::verify::RootHash; +use dpp::block::block_info::BlockInfo; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; +use dpp::state_transition::proof_result::StateTransitionProofOutcome; +use dpp::state_transition::StateTransition; +use dpp::version::PlatformVersion; + +impl Drive { + /// Generation 2 of `verify_state_transition_was_executed_with_proof`: generations 0 and + /// 1, and the execution proof of a delta contract update (version 1 of the update + /// transition, from protocol version 15) is verified too. + /// + /// The proof of a contract update holds the contract as it is after the update, which + /// an update that embeds its contract is compared with. A delta embeds only what it + /// changes, so the contract it asks for exists only once it is merged onto the contract + /// it was built on. The verifier takes that contract from `known_contracts_provider_fn`, + /// as document verification takes a document's contract, merges the delta onto it with + /// the merge block execution runs ([`DataContract::apply_update`]), and verifies the + /// update embedding the result exactly as generations 0 and 1 verify one: the whole + /// proved contract must be the merged one, with the guarantee and the owner balance of + /// any contract update. + /// + /// - A lookup that does not know the contract, or knows it at another version than the + /// one before the delta's, is [`ProofError::MissingContextRequirement`]: the caller + /// must provide the contract the delta was built on. + /// - A delta that names an entry in two sections that cannot both apply, which a node + /// refuses, or that does not merge onto that contract, is + /// [`ProofError::InvalidTransition`]. + /// - A proved contract that is not the merged one is [`ProofError::IncorrectProof`], as + /// for an update that embeds its contract. + /// + /// [`DataContract::apply_update`]: dpp::data_contract::DataContract::apply_update + pub(super) fn verify_state_transition_was_executed_with_proof_v2( + state_transition: &StateTransition, + block_info: &BlockInfo, + proof: &[u8], + known_contracts_provider_fn: &ContractLookupFn, + carries_owner_balance: bool, + platform_version: &PlatformVersion, + ) -> Result<(RootHash, StateTransitionProofOutcome), Error> { + let StateTransition::DataContractUpdate(DataContractUpdateTransition::V1(delta)) = + state_transition + else { + return Drive::verify_state_transition_was_executed_with_proof_v0( + state_transition, + block_info, + proof, + known_contracts_provider_fn, + carries_owner_balance, + platform_version, + ); + }; + + if let Some(overlap) = delta.overlapping_entry() { + return Err(Error::Proof(ProofError::InvalidTransition( + overlap.to_string(), + ))); + } + + let contract_id = delta.data_contract_id; + let known_contract = known_contracts_provider_fn(&contract_id)?.ok_or_else(|| { + Error::Proof(ProofError::MissingContextRequirement(format!( + "the contract {} as it was before the update is needed to verify the proof of a delta contract update", + contract_id + ))) + })?; + if known_contract.version().checked_add(1) != Some(delta.version) { + return Err(Error::Proof(ProofError::MissingContextRequirement(format!( + "the contract {} is known at version {}, and the delta contract update that produces version {} is verified against the version before it", + contract_id, + known_contract.version(), + delta.version + )))); + } + + let merged = delta.to_full_contract_update(&known_contract, platform_version)?; + if let Some(error) = merged.errors.first() { + return Err(Error::Proof(ProofError::InvalidTransition(format!( + "the delta contract update does not apply to contract {} at version {}: {}", + contract_id, + known_contract.version(), + error + )))); + } + let full_contract_update: StateTransition = merged.into_data()?.into(); + + Drive::verify_state_transition_was_executed_with_proof_v0( + &full_contract_update, + block_info, + proof, + known_contracts_provider_fn, + carries_owner_balance, + platform_version, + ) + } +} diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/mod.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/mod.rs index 2b67fe1762a..c448e57c9ca 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/mod.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/mod.rs @@ -47,6 +47,9 @@ pub struct DataContractMethodVersions { pub validate_moderation_config: FeatureVersion, pub equal_ignoring_time_fields: FeatureVersion, pub registration_cost: FeatureVersion, + /// Merges a delta-based (V1) update transition onto the stored contract. + /// `None` before protocol version 15, where no delta transition is admitted. + pub apply_update: OptionalFeatureVersion, } #[derive(Clone, Debug, Default)] diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v1.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v1.rs index 2e37ed6d894..8295768046c 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v1.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v1.rs @@ -29,6 +29,7 @@ pub const CONTRACT_VERSIONS_V1: DPPContractVersions = DPPContractVersions { validate_moderation_config: 0, equal_ignoring_time_fields: 0, registration_cost: 0, + apply_update: None, }, document_type_versions: DocumentTypeVersions { index_versions: DocumentTypeIndexVersions { diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v2.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v2.rs index 4f91a868ec8..fd957025083 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v2.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v2.rs @@ -29,6 +29,7 @@ pub const CONTRACT_VERSIONS_V2: DPPContractVersions = DPPContractVersions { validate_moderation_config: 0, equal_ignoring_time_fields: 0, registration_cost: 1, //changed to version 1 + apply_update: None, }, document_type_versions: DocumentTypeVersions { index_versions: DocumentTypeIndexVersions { diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v3.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v3.rs index e6e257b610e..dcef5ff604d 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v3.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v3.rs @@ -31,6 +31,7 @@ pub const CONTRACT_VERSIONS_V3: DPPContractVersions = DPPContractVersions { validate_moderation_config: 0, equal_ignoring_time_fields: 0, registration_cost: 1, + apply_update: None, }, document_type_versions: DocumentTypeVersions { index_versions: DocumentTypeIndexVersions { diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v4.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v4.rs index 3f5e73a2bc6..a3bd23000c0 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v4.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v4.rs @@ -31,6 +31,7 @@ pub const CONTRACT_VERSIONS_V4: DPPContractVersions = DPPContractVersions { validate_moderation_config: 0, equal_ignoring_time_fields: 0, registration_cost: 1, + apply_update: None, }, document_type_versions: DocumentTypeVersions { index_versions: DocumentTypeIndexVersions { diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v5.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v5.rs index f40afeeddbf..5419d4d0cb1 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v5.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v5.rs @@ -33,6 +33,7 @@ pub const CONTRACT_VERSIONS_V5: DPPContractVersions = DPPContractVersions { validate_moderation_config: 0, equal_ignoring_time_fields: 0, registration_cost: 1, + apply_update: None, }, document_type_versions: DocumentTypeVersions { index_versions: DocumentTypeIndexVersions { diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v6.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v6.rs index c21b0bf83db..83279b33298 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v6.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v6.rs @@ -67,6 +67,7 @@ pub const CONTRACT_VERSIONS_V6: DPPContractVersions = DPPContractVersions { validate_moderation_config: 0, equal_ignoring_time_fields: 0, registration_cost: 2, // changed: charges the once-per-identity token distribution surcharge + apply_update: None, }, document_type_versions: DocumentTypeVersions { index_versions: DocumentTypeIndexVersions { diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs index af4d9953712..e2e4c145a94 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs @@ -26,6 +26,9 @@ use crate::version::dpp_versions::dpp_contract_versions::{ /// - `contract_storage_serialization_version`, 2 rather than 1: Drive stores a contract in /// format version 2, its document types compiled, while state transitions and clients keep /// format version 1. +/// - `apply_update`, `Some(0)` rather than `None`: merges what a delta contract update carries +/// onto the stored contract, the one definition of the merge, which block execution and the +/// verification of a delta's execution proof both run. /// /// v6 remains unchanged for `PROTOCOL_VERSION_14`, whose parse refuses a byte array key and /// whose schemas and documents the `jsonschema` crate checks. @@ -35,6 +38,8 @@ pub const CONTRACT_VERSIONS_V7: DPPContractVersions = DPPContractVersions { // `jsonschema` crate, reaching the same verdicts but for one rule of its own: in a // `uniqueItems` list, `0.0` and `-0.0` are one value however long the list validate_document: 2, + // changed: merges a delta contract update onto the stored contract (v15 note 33) + apply_update: Some(0), ..CONTRACT_VERSIONS_V6.methods }, document_type_versions: DocumentTypeVersions { diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_state_transition_serialization_versions/mod.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_state_transition_serialization_versions/mod.rs index 93461710789..6ceb419d81a 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_state_transition_serialization_versions/mod.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_state_transition_serialization_versions/mod.rs @@ -3,6 +3,7 @@ use versioned_feature_core::FeatureVersionBounds; pub mod v1; pub mod v2; pub mod v3; +pub mod v4; #[derive(Clone, Debug, Default)] pub struct DPPStateTransitionSerializationVersions { diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_state_transition_serialization_versions/v4.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_state_transition_serialization_versions/v4.rs new file mode 100644 index 00000000000..698a468cf91 --- /dev/null +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_state_transition_serialization_versions/v4.rs @@ -0,0 +1,17 @@ +//! V4 (PV15): identical to V3 except that the contract update transition admits version 1, the +//! delta form (`DataContractUpdateTransitionV1`), which carries only what an update changes, +//! and builds it by default. Version 0, which carries the whole contract, stays admitted. + +use crate::version::dpp_versions::dpp_state_transition_serialization_versions::v3::STATE_TRANSITION_SERIALIZATION_VERSIONS_V3; +use crate::version::dpp_versions::dpp_state_transition_serialization_versions::DPPStateTransitionSerializationVersions; +use versioned_feature_core::FeatureVersionBounds; + +pub const STATE_TRANSITION_SERIALIZATION_VERSIONS_V4: DPPStateTransitionSerializationVersions = + DPPStateTransitionSerializationVersions { + contract_update_state_transition: FeatureVersionBounds { + min_version: 0, + max_version: 1, // changed: version 1 carries only what the update changes + default_current_version: 1, // changed: an update built from the stored contract is a delta + }, + ..STATE_TRANSITION_SERIALIZATION_VERSIONS_V3 + }; diff --git a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_validation_versions/v11.rs b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_validation_versions/v11.rs index 152b44a6ea1..6caf43723ea 100644 --- a/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_validation_versions/v11.rs +++ b/packages/rs-platform-version/src/version/drive_abci_versions/drive_abci_validation_versions/v11.rs @@ -34,10 +34,22 @@ use super::{ /// - the masternode vote `transform_into_action`, 1 rather than 0: a vote on a yes/no poll looks up /// the masternode's previous answer on that poll. /// - the contract update `transform_into_action` 1: v0, then in check_tx and recheck, which run no -/// state validation, the updated contract is held to the compiled size cap with its time fields -/// at their widest, a bound on what a block measures once it restores the stored contract's -/// creation fields. It reads no state, so it covers an update to a contract created earlier in -/// the same block too. Mempool admission only: a block runs v0's state validation. +/// state validation, the updated contract is held to the size caps with its time fields at +/// their widest, a bound on what a block measures once it restores the stored contract's +/// creation fields. For an update that carries the whole contract it reads no state, so it +/// covers an update to a contract created earlier in the same block too. Mempool admission +/// only: a block runs state validation. +/// - the contract update `basic_structure` 3, `nonce` 1 and `state` 2, with +/// `transform_into_action` 1, admit version 1 of the transition, the delta form, which +/// carries only what an update changes (protocol v15 note 33). An update that carries the +/// whole contract runs the generations protocol version 14 selects (`basic_structure` 2, +/// `nonce` 0, `state` 1) unchanged. For a delta, `basic_structure` 3 refuses, without a fee, +/// one that names an entry in two sections that cannot both apply; `nonce` 1 reads the owner +/// and the contract the delta names; and `state` 2 and `transform_into_action` 1 read the +/// stored contract, merge the delta onto it and validate the update carrying the whole +/// contract that results, with `basic_structure` 2 and `state` 1 (or the mempool checks of +/// `transform_into_action` 1), so a delta is held to every rule of such an update. Its +/// action carries the registration cost of what the delta registers alone. /// - document create `structure_validation` 2: v1, then a create of the decision proposals /// contract's `proposal` (protocol version 15) must state exactly the decision proposal fund /// under the proposal's name, its rule must make a yes/no poll within the system limits, and @@ -97,7 +109,10 @@ pub const DRIVE_ABCI_VALIDATION_VERSIONS_V11: DriveAbciValidationVersions = .contract_user_moderation_state_transition }, contract_update_state_transition: DriveAbciStateTransitionValidationVersion { - transform_into_action: 1, // check_tx holds the update to the compiled size cap + basic_structure: Some(3), // a delta names no entry in two sections that cannot both apply + nonce: Some(1), // reads the owner and the contract a delta names + state: 2, // a delta is merged onto the stored contract and validated as the update carrying the whole contract + transform_into_action: 1, // check_tx holds the update to the size caps, and merges a delta ..DRIVE_ABCI_VALIDATION_VERSIONS_V10 .state_transitions .contract_update_state_transition diff --git a/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/v4.rs b/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/v4.rs index 65e5395e661..42948584a86 100644 --- a/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/v4.rs +++ b/packages/rs-platform-version/src/version/drive_versions/drive_verify_method_versions/v4.rs @@ -1,7 +1,8 @@ use crate::version::drive_versions::drive_verify_method_versions::v3::DRIVE_VERIFY_METHOD_VERSIONS_V3; use crate::version::drive_versions::drive_verify_method_versions::{ DriveVerifyDocumentMethodVersions, DriveVerifyMethodVersions, - DriveVerifySingleDocumentMethodVersions, DriveVerifyVoteMethodVersions, + DriveVerifySingleDocumentMethodVersions, DriveVerifyStateTransitionMethodVersions, + DriveVerifyVoteMethodVersions, }; /// Version 4 of the Drive verify method versions, introduced in protocol version 15 with the @@ -11,7 +12,10 @@ use crate::version::drive_versions::drive_verify_method_versions::{ /// `document.verify_private_document_entries`, with private document types. /// `single_document.verify_proof_keep_serialized` is 1: a document that may be contested is /// verified, and so is a document outside a contest at a block time in a type that keeps -/// history, where generation 0 refused every such query. Everything else matches +/// history, where generation 0 refused every such query. +/// `state_transition.verify_state_transition_was_executed_with_proof` is 2: the execution proof +/// of a delta contract update is verified against the contract the delta was built on. Every +/// other transition is verified as generation 1 verifies it. Everything else matches /// `DRIVE_VERIFY_METHOD_VERSIONS_V3`. pub const DRIVE_VERIFY_METHOD_VERSIONS_V4: DriveVerifyMethodVersions = DriveVerifyMethodVersions { voting: DriveVerifyVoteMethodVersions { @@ -24,6 +28,9 @@ pub const DRIVE_VERIFY_METHOD_VERSIONS_V4: DriveVerifyMethodVersions = DriveVeri verify_private_document_entries: Some(0), // changed: a proved page of a private type's store ..DRIVE_VERIFY_METHOD_VERSIONS_V3.document }, + state_transition: DriveVerifyStateTransitionMethodVersions { + verify_state_transition_was_executed_with_proof: 2, // changed: verifies a delta contract update against the contract it was built on + }, single_document: DriveVerifySingleDocumentMethodVersions { verify_proof_keep_serialized: 1, // changed: verifies a document that may be contested, and one outside a contest at a block time ..DRIVE_VERIFY_METHOD_VERSIONS_V3.single_document diff --git a/packages/rs-platform-version/src/version/drive_versions/v10.rs b/packages/rs-platform-version/src/version/drive_versions/v10.rs index 3bb45dbc713..6bd7f5c3207 100644 --- a/packages/rs-platform-version/src/version/drive_versions/v10.rs +++ b/packages/rs-platform-version/src/version/drive_versions/v10.rs @@ -17,8 +17,8 @@ use crate::version::drive_versions::v9::DRIVE_VERSION_V9; use crate::version::drive_versions::{ DriveBatchOperationsMethodVersion, DriveFeesMethodVersions, DriveInitializationMethodVersions, DriveMethodVersions, DrivePlatformSystemMethodVersions, - DrivePrefundedSpecializedMethodVersions, DriveSystemEstimationCostsMethodVersions, - DriveVersion, + DrivePrefundedSpecializedMethodVersions, DriveProveMethodVersions, + DriveSystemEstimationCostsMethodVersions, DriveVersion, }; use grovedb_version::version::v5::GROVE_V5; @@ -115,6 +115,13 @@ use grovedb_version::version::v5::GROVE_V5; /// `verify_proof_keep_serialized` 1 verifies its proof outside a contest. A document with /// history that may be contested is refused at a block time. /// +/// * **Delta contract updates** (protocol v15 note 33): `prove.prove_state_transition` is 2, +/// which proves a delta contract update, a transition that embeds no contract, by reading +/// from the stored contract whether the contract keeps history, and every other transition +/// as generation 1 does, in the same layout. `DRIVE_VERIFY_METHOD_VERSIONS_V4` sets +/// `state_transition.verify_state_transition_was_executed_with_proof` to 2, which verifies +/// that proof against the contract the delta was built on. +/// /// Everything else matches `DRIVE_VERSION_V9`. pub const DRIVE_VERSION_V10: DriveVersion = DriveVersion { methods: DriveMethodVersions { @@ -150,8 +157,12 @@ pub const DRIVE_VERSION_V10: DriveVersion = DriveVersion { estimated_cost_for_prefunded_specialized_balance_update: 2, // changed in v10: keeps a deeper prefunded balances layer description ..DRIVE_VERSION_V9.methods.prefunded_specialized_balances }, + prove: DriveProveMethodVersions { + prove_state_transition: 2, // changed in v10: a delta contract update is proved from the stored contract (note 33) + ..DRIVE_VERSION_V9.methods.prove + }, vote: DRIVE_VOTE_METHOD_VERSIONS_V4, // changed in v10: the yes/no poll kind - verify: DRIVE_VERIFY_METHOD_VERSIONS_V4, // changed in v10: the yes/no and private document entries proof verifiers; a document that may be contested is verified + verify: DRIVE_VERIFY_METHOD_VERSIONS_V4, // changed in v10: the yes/no and private document entries proof verifiers; a document that may be contested is verified; a delta contract update's execution proof is verified state_transitions: DRIVE_STATE_TRANSITION_METHOD_VERSIONS_V5, // changed in v10: a consume deletes what its lookup read platform_system: DrivePlatformSystemMethodVersions { estimation_costs: DriveSystemEstimationCostsMethodVersions { diff --git a/packages/rs-platform-version/src/version/feature_initial_protocol_versions.rs b/packages/rs-platform-version/src/version/feature_initial_protocol_versions.rs index fd91614fd9a..3c1404c099b 100644 --- a/packages/rs-platform-version/src/version/feature_initial_protocol_versions.rs +++ b/packages/rs-platform-version/src/version/feature_initial_protocol_versions.rs @@ -50,3 +50,7 @@ pub const DECISION_PROPOSALS_CONTRACT_INITIAL_PROTOCOL_VERSION: ProtocolVersion /// store paying from the credit shielded pool, is not active before it, as software that /// predates it cannot decode one. pub const PRIVATE_DOCUMENT_CREATE_FROM_SHIELDED_POOL_INITIAL_PROTOCOL_VERSION: ProtocolVersion = 15; +/// Version 1 of the data contract update transition, the delta form, which carries only what an +/// update changes instead of the whole contract, activates with protocol version 15. Below it a +/// delta is refused without a fee, as software that predates it cannot decode one. +pub const DATA_CONTRACT_UPDATE_V1_INITIAL_PROTOCOL_VERSION: ProtocolVersion = 15; diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index e488f588aa3..0049ace981d 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -8,7 +8,7 @@ use crate::version::dpp_versions::dpp_identity_versions::v1::IDENTITY_VERSIONS_V use crate::version::dpp_versions::dpp_method_versions::v3::DPP_METHOD_VERSIONS_V3; use crate::version::dpp_versions::dpp_state_transition_conversion_versions::v2::STATE_TRANSITION_CONVERSION_VERSIONS_V2; use crate::version::dpp_versions::dpp_state_transition_method_versions::v2::STATE_TRANSITION_METHOD_VERSIONS_V2; -use crate::version::dpp_versions::dpp_state_transition_serialization_versions::v3::STATE_TRANSITION_SERIALIZATION_VERSIONS_V3; +use crate::version::dpp_versions::dpp_state_transition_serialization_versions::v4::STATE_TRANSITION_SERIALIZATION_VERSIONS_V4; use crate::version::dpp_versions::dpp_state_transition_versions::v5::STATE_TRANSITION_VERSIONS_V5; use crate::version::dpp_versions::dpp_token_versions::v3::TOKEN_VERSIONS_V3; use crate::version::dpp_versions::dpp_validation_versions::v5::DPP_VALIDATION_VERSIONS_V5; @@ -658,13 +658,51 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// not Platform's, fails that block. Protocol v14 and earlier keep /// `update_masternode_list` 0 or 1, `update_operator_identity` 0 and /// `add_new_keys_to_masternode_identity` 0. +/// +/// 33. **Delta contract updates**: version 1 of the data contract update transition +/// (`DataContractUpdateTransitionV1`, `STATE_TRANSITION_SERIALIZATION_VERSIONS_V4`, where +/// it is also the version built by default) carries only what an update changes: new and +/// replaced document schemas and shared definitions, new groups and tokens, added and +/// removed keywords, and optionally a description or a config. Version 0, which carries +/// the whole contract, stays admitted. A delta is not active before this version +/// (`DATA_CONTRACT_UPDATE_V1_INITIAL_PROTOCOL_VERSION`), where it is refused at decode +/// without a fee, as software that predates it cannot decode one. A node reads the stored +/// contract, merges the delta onto it (`apply_update` 0, `None` before +/// `CONTRACT_VERSIONS_V7`) and validates the update carrying the whole contract that +/// results, with the generations such an update runs, so a delta is held to every rule of +/// one: contract update `state` 2 in a block and `transform_into_action` 1 in check_tx +/// (`DRIVE_ABCI_VALIDATION_VERSIONS_V11`). A delta naming a contract that does not exist, +/// an owner that does not own it, an entry to replace or remove that the contract does not +/// have (`DataContractUpdateEntryNotFoundError`, 40011) or an entry to add that it has +/// (`DataContractUpdateEntryAlreadyExistsError`, 40010) is refused in a block as a paid +/// nonce bump; one naming an entry in two sections that cannot both apply +/// (`DataContractUpdateOverlappingEntriesError`, 10283) is refused without a fee by +/// `basic_structure` 3. Each of these three errors carries at most 256 bytes of the +/// entry's name, as a delta can name an entry longer than a consensus error can be +/// (`MAX_DATA_CONTRACT_UPDATE_ENTRY_NAME_BYTES`). A delta pays the registration cost of what it registers alone (its +/// new and replaced document types, new tokens and added keywords), where an update +/// carrying the whole contract pays the whole contract's again; it pays the processing of +/// validating the whole merged contract as that update does. As a state transition is +/// capped at `max_state_transition_size`, well below the `max_serialized_size` a contract +/// may take, an update carrying the whole contract cannot grow a contract past the +/// transition cap; a delta grows one a transition at a time. A contract that would take +/// more than `max_serialized_size` in the format transitions carry is refused with a +/// consensus error (`DataContractMaxSizeExceededError`, 10284), by a contract create or +/// update or a token configuration update, next to the compiled size cap of note 8, as +/// Drive refuses to store one. `prove_state_transition` 2 (`DRIVE_VERSION_V10`) proves a +/// delta's execution by reading from the stored contract whether it keeps history, in the +/// layout of generation 1, and `verify_state_transition_was_executed_with_proof` 2 +/// (`DRIVE_VERIFY_METHOD_VERSIONS_V4`) verifies it against the contract the delta was +/// built on, which the verifier's contract lookup provides: it merges the delta onto that +/// contract with the same `apply_update` and requires the proved contract to be the +/// result. 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, stateless_delete_of_non_tree_for_costs 1 and for_total_system_credits_update 1 describe their layers as they are (note 14); create_initial_state_structure 5 adds the token marketplace escrow trees; calculate_total_tokens_balance 2 counts escrowed tokens; the escrow primitives; the identity balance, token balance, prefunded specialized balance and contract fee pot estimations (for_balances 1, for_token_balances 1, estimated_cost_for_prefunded_specialized_balance_update 2, add_estimation_costs_for_contract_fee_pot_update 1) keep a deeper layer description (note 17); 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 stops a single document lookup at a block time above the pointer to the latest version, and verify_proof_keep_serialized 1 verifies it (note 31); add_new_keys_to_masternode_identity 1 adds a masternode key whose hash the identity already holds a reference for (note 32) + 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, stateless_delete_of_non_tree_for_costs 1 and for_total_system_credits_update 1 describe their layers as they are (note 14); create_initial_state_structure 5 adds the token marketplace escrow trees; calculate_total_tokens_balance 2 counts escrowed tokens; the escrow primitives; the identity balance, token balance, prefunded specialized balance and contract fee pot estimations (for_balances 1, for_token_balances 1, estimated_cost_for_prefunded_specialized_balance_update 2, add_estimation_costs_for_contract_fee_pot_update 1) keep a deeper layer description (note 17); 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 stops a single document lookup at a block time above the pointer to the latest version, and verify_proof_keep_serialized 1 verifies it (note 31); add_new_keys_to_masternode_identity 1 adds a masternode key whose hash the identity already holds a reference for (note 32); prove_state_transition 2 proves a delta contract update from the stored contract, and verify methods v4: verify_state_transition_was_executed_with_proof 2 verifies it against the contract the delta was built on (note 33) drive_abci: DriveAbciVersion { structs: DRIVE_ABCI_STRUCTURE_VERSIONS_V2, methods: DRIVE_ABCI_METHOD_VERSIONS_V11, // changed: 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); 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) - 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 refuse a replace or a delete of a token market order (note 17) and 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) + 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 refuse a replace or a delete of a token market order (note 17) and 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); contract update basic_structure 3, nonce 1, state 2 and transform_into_action 1 admit a delta, merge it onto the stored contract and validate the update carrying the whole contract that results (note 33) withdrawal_constants: DRIVE_ABCI_WITHDRAWAL_CONSTANTS_V3, query: DRIVE_ABCI_QUERY_VERSIONS_V2, checkpoints: DRIVE_ABCI_CHECKPOINT_PARAMETERS_V1, @@ -672,11 +710,11 @@ pub const PLATFORM_V15: PlatformVersion = PlatformVersion { dpp: DPPVersion { costs: DPP_COSTS_VERSIONS_V1, validation: DPP_VALIDATION_VERSIONS_V5, - state_transition_serialization_versions: STATE_TRANSITION_SERIALIZATION_VERSIONS_V3, + state_transition_serialization_versions: STATE_TRANSITION_SERIALIZATION_VERSIONS_V4, // changed: contract update version 1, the delta form, is admitted and built by default (note 33) state_transition_conversion_versions: STATE_TRANSITION_CONVERSION_VERSIONS_V2, state_transition_method_versions: STATE_TRANSITION_METHOD_VERSIONS_V2, state_transitions: STATE_TRANSITION_VERSIONS_V5, // changed: validate_asset_lock_transaction_structure 1 drops the input cap and validate_instant_asset_lock_proof_structure 1 applies it to instant proofs only, so a chain proof redeems a lock of more than 100 inputs (note 30) - contract_versions: CONTRACT_VERSIONS_V7, // changed: parse_property_constraints 1 lets countOf and sumOf match byte array keys (note 4); validate_document 2 checks documents natively (note 6); check_document_type_schema 1 checks schemas natively at registration (note 7); contract_storage_serialization_version 2 stores contracts compiled (note 8); parse_private_document 0 parses private document types (note 13); apply_generated_from 1 admits sys.tokens.decimals (note 15) + contract_versions: CONTRACT_VERSIONS_V7, // changed: parse_property_constraints 1 lets countOf and sumOf match byte array keys (note 4); validate_document 2 checks documents natively (note 6); check_document_type_schema 1 checks schemas natively at registration (note 7); contract_storage_serialization_version 2 stores contracts compiled (note 8); parse_private_document 0 parses private document types (note 13); apply_generated_from 1 admits sys.tokens.decimals (note 15); apply_update 0 merges a delta contract update onto the stored contract (note 33) document_versions: DOCUMENT_VERSIONS_V4, identity_versions: IDENTITY_VERSIONS_V1, voting_versions: VOTING_VERSION_V3, // changed: the yes/no poll's stored info, id, parameter rules and decision rules are active (note 10), and the decision proposal's poll (note 12) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs index b40b4d2e1f6..6f94bc535b5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs @@ -28,6 +28,7 @@ use super::signing_key::AvailableSigningKey; use async_trait::async_trait; +use std::sync::Arc; use dpp::address_funds::AddressWitness; use dpp::data_contract::accessors::v0::DataContractV0Getters; @@ -35,18 +36,17 @@ use dpp::data_contract::serialized_version::DataContractInSerializationFormat; use dpp::data_contract::INITIAL_DATA_CONTRACT_VERSION; use dpp::identity::signer::Signer; use dpp::identity::{IdentityPublicKey, KeyType, PartialIdentity, Purpose, SecurityLevel}; -use dpp::platform_value::BinaryData; +use dpp::platform_value::{BinaryData, Value}; use dpp::prelude::{DataContract, Identifier}; -use dpp::state_transition::data_contract_update_transition::methods::DataContractUpdateTransitionMethodsV0; use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; -use dpp::version::TryFromPlatformVersioned; +use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; use dpp::ProtocolError; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_contract::{ ensure_private_document_entries_fit, PutContract, }; -use dash_sdk::platform::transition::waitable::Waitable; +use dash_sdk::platform::transition::waitable::wait_for_data_contract_update; use dash_sdk::platform::Fetch; use crate::error::{preserve_signer_key_unavailable_or, PlatformWalletError}; @@ -317,14 +317,15 @@ impl IdentityWallet { /// Mirrors `create_data_contract_with_signer` but targets an /// already-registered contract. Unlike create, the caller-supplied /// JSON sections are *merged onto the fetched on-chain contract* - /// rather than used to build the payload from scratch. A - /// `DataContractUpdateTransition` broadcasts a complete contract - /// definition (not a diff), so anything the caller omits would - /// otherwise be reset to serde defaults — wiping live keywords / - /// description / config and, worse, dropping document-type / token / - /// group entries (which DPP rejects as illegal removals). Seeding - /// from `existing` keeps every untouched section intact. The - /// function: + /// rather than used to build the payload from scratch: anything the + /// caller omits would otherwise be reset to serde defaults, wiping + /// live keywords / description / config and, worse, dropping + /// document-type / token / group entries (which DPP rejects as + /// illegal removals). Seeding from `existing` keeps every untouched + /// section intact. The transition itself is built from the pair + /// (`existing`, merged contract), so on protocol versions that + /// default to delta-based updates only the changed sections go on + /// the wire. The function: /// 1. Looks up `owner_identity_id` in the in-memory wallet /// manager and picks the CRITICAL + AUTHENTICATION + ECDSA /// key (same triple a contract-create signature requires). @@ -349,8 +350,9 @@ impl IdentityWallet { /// `DataContractInSerializationFormat` enum entry point and /// validated through `try_from_platform_versioned`. /// 4. Fetches + bumps the identity-contract nonce, builds a - /// `DataContractUpdateTransition`, signs it via the external - /// signer, broadcasts, and waits for the confirmed contract. + /// `DataContractUpdateTransition` from the (existing, updated) + /// pair, signs it via the external signer, broadcasts, and waits + /// for the confirmed contract. /// /// # JSON shapes /// @@ -449,64 +451,21 @@ impl IdentityWallet { ) })?; - // 3. Build the updated serialization-format payload by merging - // the caller's sections onto the fetched contract. `existing` - // is already a valid V1 on-chain contract, so serializing it - // to the canonical `DataContractInSerializationFormat` JSON - // gives us a base that carries every live field (config keeps - // its on-chain version, document/token/group sets are - // complete). We then overlay only what the caller supplied. + // 3. Build the contract the update asks for: the fetched one + // with the caller's sections merged in. let platform_version = self.sdk.version(); - let base_format = DataContractInSerializationFormat::try_from_platform_versioned( + let updated_contract = assemble_updated_contract( &existing, - platform_version, - ) - .map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to convert existing contract to serialization format: {e}" - )) - })?; - let base_value = serde_json::to_value(&base_format).map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to serialize existing contract format: {e}" - )) - })?; - - let merged_value = merge_contract_update_payload( - base_value, new_version, - parse_required_json("documents_schema_json", documents_schema_json)?, - parse_optional_json("tokens_schema_json", tokens_schema_json)?, - parse_optional_json("groups_schema_json", groups_schema_json)?, - parse_optional_json("keywords_json", keywords_json)?, - description.filter(|s| !s.is_empty()), - parse_optional_json("config_json", config_json)?, + documents_schema_json, + tokens_schema_json, + groups_schema_json, + keywords_json, + description, + config_json, + platform_version, )?; - // Round-trip through a string instead of `from_value` — see - // `create_data_contract_with_signer` for why the tagged-enum - // dispatch needs `to_string` + `from_str`. - let serialized = serde_json::to_string_pretty(&merged_value).map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to serialize updated contract format: {e}" - )) - })?; - let format: DataContractInSerializationFormat = - serde_json::from_str(&serialized).map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to assemble updated contract format: {e}\n\nAssembled JSON:\n{serialized}" - )) - })?; - - let mut errors = vec![]; - let updated_contract = - DataContract::try_from_platform_versioned(format, true, &mut errors, platform_version) - .map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to build updated contract: {e}\n\nAssembled JSON:\n{serialized}" - )) - })?; - // A private document type the update adds, or whose properties it changes, takes entries // that must hold its largest payload, as `PutContract` checks on create; `existing` is the // contract as Platform holds it, so an unchanged type is not checked again. @@ -537,8 +496,9 @@ impl IdentityWallet { not_found_public_keys: Default::default(), }; - let transition = DataContractUpdateTransition::new_from_data_contract( - updated_contract, + let transition = DataContractUpdateTransition::new_from_contract_update( + &existing, + &updated_contract, &partial_identity, key_id, new_identity_contract_nonce, @@ -559,14 +519,160 @@ impl IdentityWallet { .await .map_err(PlatformWalletError::Sdk)?; - let confirmed = DataContract::wait_for_response(&self.sdk, transition, None) - .await - .map_err(PlatformWalletError::Sdk)?; + // The proof of a delta-based update is verified by merging the + // delta onto the contract it was built on. That contract goes + // with this wait rather than through the SDK's shared context + // provider, which keeps only the latest version of a contract: + // once the update is committed, a concurrent operation can + // register the updated contract there before this proof is + // verified, and the update would be reported as failed. + let confirmed = + wait_for_data_contract_update(&self.sdk, &transition, &Arc::new(existing), None) + .await + .map_err(PlatformWalletError::Sdk)?; + + // Later operations on this contract verify against the + // confirmed one. + self.register_contract_for_proof_verification(&confirmed); Ok(confirmed) } } +/// The contract an update asks for: `existing` at `new_version`, with the +/// caller's sections merged in. +/// +/// `existing` is already a valid V1 on-chain contract, so serializing it +/// to the canonical `DataContractInSerializationFormat` JSON gives a base +/// that carries every live field (config keeps its on-chain version, +/// document/token/group sets are complete). Only what the caller supplied +/// is overlaid ([`merge_contract_update_payload`]), and the document +/// schemas and schema definitions the update leaves as they are come out +/// exactly as Platform holds them ([`keep_unchanged_schemas_as_stored`]). +#[allow(clippy::too_many_arguments)] +fn assemble_updated_contract( + existing: &DataContract, + new_version: u32, + documents_schema_json: &str, + tokens_schema_json: Option<&str>, + groups_schema_json: Option<&str>, + keywords_json: Option<&str>, + description: Option<&str>, + config_json: Option<&str>, + platform_version: &PlatformVersion, +) -> Result { + let base_format = + DataContractInSerializationFormat::try_from_platform_versioned(existing, platform_version) + .map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to convert existing contract to serialization format: {e}" + )) + })?; + let base_value = serde_json::to_value(&base_format).map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to serialize existing contract format: {e}" + )) + })?; + + let merged_value = merge_contract_update_payload( + base_value, + new_version, + parse_required_json("documents_schema_json", documents_schema_json)?, + parse_optional_json("tokens_schema_json", tokens_schema_json)?, + parse_optional_json("groups_schema_json", groups_schema_json)?, + parse_optional_json("keywords_json", keywords_json)?, + description.filter(|s| !s.is_empty()), + parse_optional_json("config_json", config_json)?, + )?; + + // Round-trip through a string instead of `from_value` — see + // `create_data_contract_with_signer` for why the tagged-enum + // dispatch needs `to_string` + `from_str`. + let serialized = serde_json::to_string_pretty(&merged_value).map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to serialize updated contract format: {e}" + )) + })?; + let mut format: DataContractInSerializationFormat = + serde_json::from_str(&serialized).map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to assemble updated contract format: {e}\n\nAssembled JSON:\n{serialized}" + )) + })?; + keep_unchanged_schemas_as_stored(&mut format, &base_format)?; + + let mut errors = vec![]; + DataContract::try_from_platform_versioned(format, true, &mut errors, platform_version).map_err( + |e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to build updated contract: {e}\n\nAssembled JSON:\n{serialized}" + )) + }, + ) +} + +/// Puts back, exactly as Platform holds them, the document schemas and +/// schema definitions that `updated` leaves as they are in `existing`. +/// +/// `updated` was read from JSON, and JSON does not keep how a schema's +/// values are typed: a `maxLength` Platform holds as a 32-bit integer reads +/// back as a 64-bit one. A delta carries every schema that is not exactly +/// the stored one, so a schema that only went through JSON would be sent +/// again as replaced and its registration paid for again, and a contract +/// grown past what one transition holds could not be updated at all. A +/// schema is one the update leaves as it is when it reads as the same JSON +/// as the stored one, whether the caller left it out or sent it again. +fn keep_unchanged_schemas_as_stored( + updated: &mut DataContractInSerializationFormat, + existing: &DataContractInSerializationFormat, +) -> Result<(), PlatformWalletError> { + let not_changeable = || { + PlatformWalletError::InvalidIdentityData( + "The updated contract is not in a format whose schemas can be set".to_string(), + ) + }; + + let schemas = updated + .document_schemas_mut() + .map_err(|_| not_changeable())?; + for (name, schema) in schemas.iter_mut() { + if let Some(stored) = existing.document_schemas().get(name) { + if reads_as_the_same_json(schema, stored)? { + *schema = stored.clone(); + } + } + } + + let definitions = match updated { + DataContractInSerializationFormat::V0(v0) => &mut v0.schema_defs, + DataContractInSerializationFormat::V1(v1) => &mut v1.schema_defs, + DataContractInSerializationFormat::V2(_) => return Err(not_changeable()), + }; + if let (Some(definitions), Some(stored_definitions)) = (definitions, existing.schema_defs()) { + for (name, definition) in definitions.iter_mut() { + if let Some(stored) = stored_definitions.get(name) { + if reads_as_the_same_json(definition, stored)? { + *definition = stored.clone(); + } + } + } + } + Ok(()) +} + +/// Whether two schema values are the same once written as JSON, the form +/// the caller's sections arrive in. +fn reads_as_the_same_json(a: &Value, b: &Value) -> Result { + let json = |value: &Value| { + serde_json::to_value(value).map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to write a schema as JSON: {e}" + )) + }) + }; + Ok(json(a)? == json(b)?) +} + /// Parse a required JSON `&str`. `field_name` only feeds the error /// message — it has no semantic effect. fn parse_required_json( @@ -763,7 +869,11 @@ fn build_config_object( #[cfg(test)] mod tests { use super::*; - use dpp::version::PlatformVersion; + use dpp::data_contract::schema::DataContractSchemaMethodsV0; + use dpp::data_contract::update_values::DescriptionUpdate; + use dpp::platform_value::platform_value; + use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransitionV1; + use dpp::tests::fixtures::get_data_contract_fixture; use serde_json::json; /// A minimal serialized-V1-contract base value, shaped like the @@ -1045,4 +1155,148 @@ mod tests { "assembled config must validate at the latest version: {contract:?} (errors: {errors:?})" ); } + + /// A contract as Platform can hold one and JSON cannot say: its schemas hold + /// integers 32 bits wide, in two document types and in a schema definition. + fn contract_with_narrow_integers() -> DataContract { + let platform_version = PlatformVersion::latest(); + let fixture = get_data_contract_fixture(None, 0, platform_version.protocol_version) + .data_contract_owned(); + let mut format = DataContractInSerializationFormat::try_from_platform_versioned( + &fixture, + platform_version, + ) + .expect("expected the fixture in serialization format"); + let DataContractInSerializationFormat::V1(v1) = &mut format else { + panic!("expected format version 1"); + }; + v1.schema_defs.get_or_insert_with(Default::default).insert( + "shortName".to_string(), + platform_value!({"type": "string", "maxLength": 20u32}), + ); + let contract = + DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) + .expect("expected a valid contract"); + + assert!( + holds_a_32_bit_integer(contract.document_schemas()["indexedDocument"]), + "the fixture's maxLength values are 32 bits wide" + ); + contract + } + + fn holds_a_32_bit_integer(value: &Value) -> bool { + match value { + Value::U32(_) => true, + Value::Map(entries) => entries + .iter() + .any(|(_, value)| holds_a_32_bit_integer(value)), + Value::Array(items) => items.iter().any(holds_a_32_bit_integer), + _ => false, + } + } + + fn delta_between( + existing: &DataContract, + updated: &DataContract, + ) -> DataContractUpdateTransitionV1 { + match DataContractUpdateTransition::from_contract_update( + existing, + updated, + 1, + PlatformVersion::latest(), + ) + .expect("expected a contract update") + { + DataContractUpdateTransition::V1(delta) => delta, + other => panic!("expected a delta, got {other:?}"), + } + } + + /// The whole contract goes through JSON on its way to the updated one, and JSON + /// reads a 32-bit integer back as a 64-bit one. An update that changes no schema + /// must still send none: a schema sent again is registered and paid for again. + #[test] + fn should_send_no_schema_in_the_delta_of_an_update_that_changes_none() { + let platform_version = PlatformVersion::latest(); + let existing = contract_with_narrow_integers(); + + let updated = assemble_updated_contract( + &existing, + existing.version() + 1, + "{}", + None, + None, + None, + Some("a new description"), + None, + platform_version, + ) + .expect("expected the updated contract"); + + let delta = delta_between(&existing, &updated); + assert!( + delta.updated_document_schemas.is_empty(), + "sent again: {:?}", + delta.updated_document_schemas.keys() + ); + assert!(delta.new_document_schemas.is_empty()); + assert!( + delta.updated_schema_defs.is_empty(), + "sent again: {:?}", + delta.updated_schema_defs.keys() + ); + assert!(delta.new_schema_defs.is_empty()); + assert_eq!( + delta.description, + DescriptionUpdate::Set("a new description".to_string()) + ); + assert_eq!( + delta + .registration_cost(platform_version) + .expect("expected a registration cost"), + 0 + ); + // The schemas asked for are the stored ones exactly, 32-bit integers included + assert_eq!(updated.document_schemas(), existing.document_schemas()); + assert_eq!(updated.schema_defs(), existing.schema_defs()); + } + + /// A schema the caller sends as it is stored is left out like one it does not + /// send, and a schema it changes is still sent. + #[test] + fn should_send_only_the_schema_the_caller_changes() { + let platform_version = PlatformVersion::latest(); + let existing = contract_with_narrow_integers(); + let as_stored = serde_json::to_value(existing.document_schemas()["indexedDocument"]) + .expect("expected the stored schema as JSON"); + let mut changed = serde_json::to_value(existing.document_schemas()["noTimeDocument"]) + .expect("expected the stored schema as JSON"); + changed["properties"]["nickname"] = + json!({"type": "string", "maxLength": 20, "position": 1}); + let documents = + json!({"indexedDocument": as_stored, "noTimeDocument": changed}).to_string(); + + let updated = assemble_updated_contract( + &existing, + existing.version() + 1, + &documents, + None, + None, + None, + None, + None, + platform_version, + ) + .expect("expected the updated contract"); + + let delta = delta_between(&existing, &updated); + assert_eq!( + delta.updated_document_schemas.keys().collect::>(), + ["noTimeDocument"] + ); + assert!(delta.new_document_schemas.is_empty()); + assert!(delta.updated_schema_defs.is_empty()); + assert!(delta.new_schema_defs.is_empty()); + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/state_transition_summary.rs b/packages/rs-platform-wallet/src/wallet/identity/network/state_transition_summary.rs index be0e36d27c8..c9e2d3d5d20 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/state_transition_summary.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/state_transition_summary.rs @@ -46,7 +46,9 @@ use dpp::state_transition::batch_transition::token_transfer_transition::v0::v0_m use dpp::state_transition::batch_transition::token_unfreeze_transition::v0::v0_methods::TokenUnfreezeTransitionV0Methods; use dpp::state_transition::batch_transition::BatchTransition; use dpp::state_transition::data_contract_create_transition::accessors::DataContractCreateTransitionAccessorsV0; -use dpp::state_transition::data_contract_update_transition::accessors::DataContractUpdateTransitionAccessorsV0; +use dpp::state_transition::data_contract_update_transition::{ + DataContractUpdateTransition, DataContractUpdateTransitionV1, +}; use dpp::state_transition::identity_credit_transfer_transition::accessors::IdentityCreditTransferTransitionAccessorsV0; use dpp::state_transition::identity_update_transition::accessors::IdentityUpdateTransitionAccessorsV0; use dpp::state_transition::public_key_in_creation::accessors::IdentityPublicKeyInCreationV0Getters; @@ -136,7 +138,8 @@ pub enum StateTransitionSummaryKind { pub struct DataContractSummary { pub contract_id: Identifier, pub owner_id: Identifier, - /// Document type names, in the contract's order. + /// Document type names, in the contract's order. For a delta contract update, which + /// carries only what it changes, the types it adds, then those it replaces. pub document_type_names: Vec, /// The whole transition: the contract (schemas, tokens and their /// distribution rules, groups, keywords), and for a create the contract @@ -307,10 +310,15 @@ fn summarize( )?) } StateTransition::DataContractUpdate(update) => { - StateTransitionSummaryKind::DataContractUpdate(summarize_contract( - update.data_contract(), - budget.render(update)?, - )?) + let details = budget.render(update)?; + StateTransitionSummaryKind::DataContractUpdate(match update { + DataContractUpdateTransition::V0(update) => { + summarize_contract(&update.data_contract, details)? + } + DataContractUpdateTransition::V1(delta) => { + summarize_contract_delta(delta, details)? + } + }) } other => StateTransitionSummaryKind::Other { details: budget.render(other)?, @@ -466,6 +474,29 @@ fn summarize_contract( }) } +/// A delta contract update carries only what it changes, so the names are those of the +/// document types it adds, then of those it replaces; `details` shows the rest of the delta. +fn summarize_contract_delta( + delta: &DataContractUpdateTransitionV1, + details: String, +) -> Result { + let document_type_names: Vec = delta + .new_document_schemas + .keys() + .chain(delta.updated_document_schemas.keys()) + .cloned() + .collect(); + for name in &document_type_names { + check_document_type_name(name)?; + } + Ok(DataContractSummary { + contract_id: delta.data_contract_id, + owner_id: delta.owner_id, + document_type_names, + details, + }) +} + fn summarize_batch( batch: &BatchTransition, budget: &mut DetailsBudget, diff --git a/packages/rs-sdk/src/platform/transition.rs b/packages/rs-sdk/src/platform/transition.rs index 62ece2c4ac8..2c2e745fd81 100644 --- a/packages/rs-sdk/src/platform/transition.rs +++ b/packages/rs-sdk/src/platform/transition.rs @@ -50,5 +50,6 @@ pub mod update_price_of_document; pub(crate) mod validation; pub mod vote; pub mod waitable; +mod with_contract; pub mod withdraw_from_identity; pub use txid::TxId; diff --git a/packages/rs-sdk/src/platform/transition/broadcast.rs b/packages/rs-sdk/src/platform/transition/broadcast.rs index 8cb64874b68..b6b16c9d6bd 100644 --- a/packages/rs-sdk/src/platform/transition/broadcast.rs +++ b/packages/rs-sdk/src/platform/transition/broadcast.rs @@ -1,5 +1,6 @@ use super::broadcast_request::{checked_broadcast_request, BroadcastRequestForStateTransition}; use super::put_settings::PutSettings; +use super::with_contract::WithContract; use crate::error::StateTransitionBroadcastError; use crate::platform::ProtocolRequirement; use crate::sync::retry; @@ -10,7 +11,8 @@ use dapi_grpc::platform::v0::{ wait_for_state_transition_result_response, BroadcastStateTransitionRequest, ResponseMetadata, WaitForStateTransitionResultResponse, }; -use dash_context_provider::ContextProviderError; +use dash_context_provider::{ContextProvider, ContextProviderError}; +use dpp::prelude::DataContract; use dpp::state_transition::batch_transition::accessors::DocumentsBatchTransitionAccessorsV0; use dpp::state_transition::batch_transition::batched_transition::document_transition::DocumentTransition; use dpp::state_transition::batch_transition::batched_transition::document_transition::DocumentTransitionV0Methods; @@ -33,6 +35,7 @@ use rs_dapi_client::{ use std::future::Future; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; +use std::sync::Arc; use tracing::{debug, trace, warn}; const DPNS_REGISTRATION_BROADCAST_RETRIES: usize = 2; @@ -484,141 +487,160 @@ impl WaitForOutcome for StateTransition { sdk: &Sdk, settings: Option, ) -> Result<(StateTransitionProofOutcome, ResponseMetadata), Error> { - trace!( - transaction_id = %self - .transaction_id() - .map(hex::encode) - .unwrap_or("UNKNOWN".to_string()), - "wait: start" - ); + wait_for_outcome_knowing_contract(self, sdk, settings, None).await + } +} - let retry_settings = match settings { - Some(s) => sdk.dapi_client_settings.override_by(s.request_settings), - None => sdk.dapi_client_settings, - }; +/// [`WaitForOutcome::wait_for_outcome_with_metadata`], with the proof verified knowing +/// `known_contract` when one is given: the verification's context is the SDK's context +/// provider, except that the data contract known under `known_contract`'s id is +/// `known_contract` itself ([`WithContract`]). +pub(super) async fn wait_for_outcome_knowing_contract( + state_transition: &StateTransition, + sdk: &Sdk, + settings: Option, + known_contract: Option<&Arc>, +) -> Result<(StateTransitionProofOutcome, ResponseMetadata), Error> { + trace!( + transaction_id = %state_transition + .transaction_id() + .map(hex::encode) + .unwrap_or("UNKNOWN".to_string()), + "wait: start" + ); + + let retry_settings = match settings { + Some(s) => sdk.dapi_client_settings.override_by(s.request_settings), + None => sdk.dapi_client_settings, + }; - // prepare a factory that will generate closure which executes actual code - let factory = |request_settings: RequestSettings| async move { - trace!("wait: creating request"); - let request = self - .wait_for_state_transition_result_request() - .map_err(|e| ExecutionError { - possibly_accepted: false, - inner: e, - address: None, - retries: 0, - })?; + // prepare a factory that will generate closure which executes actual code + let factory = |request_settings: RequestSettings| async move { + trace!("wait: creating request"); + let request = state_transition + .wait_for_state_transition_result_request() + .map_err(|e| ExecutionError { + possibly_accepted: false, + inner: e, + address: None, + retries: 0, + })?; - trace!("wait: executing request"); - let response = request.execute(sdk, request_settings).await.inner_into()?; - trace!("wait: received response"); + trace!("wait: executing request"); + let response = request.execute(sdk, request_settings).await.inner_into()?; + trace!("wait: received response"); - let grpc_response: &WaitForStateTransitionResultResponse = &response.inner; + let grpc_response: &WaitForStateTransitionResultResponse = &response.inner; - // We use match here to have a compilation error if a new version of the response is introduced - let state_transition_broadcast_error = match &grpc_response.version { - Some(wait_for_state_transition_result_response::Version::V0(result)) => { - match &result.result { - Some(wait_for_state_transition_result_response_v0::Result::Error(e)) => { - Some(e) - } - _ => None, - } + // We use match here to have a compilation error if a new version of the response is introduced + let state_transition_broadcast_error = match &grpc_response.version { + Some(wait_for_state_transition_result_response::Version::V0(result)) => { + match &result.result { + Some(wait_for_state_transition_result_response_v0::Result::Error(e)) => Some(e), + _ => None, } - None => None, - }; - - if let Some(e) = state_transition_broadcast_error { - warn!(error=?e, "wait: state transition broadcast error detected"); - let state_transition_broadcast_error: StateTransitionBroadcastError = - StateTransitionBroadcastError::try_from(e.clone()) - .wrap_to_execution_result(&response)? - .inner; - - return Err(Error::from(state_transition_broadcast_error)) - .wrap_to_execution_result(&response); } + None => None, + }; - let context_provider = sdk.context_provider().ok_or(ExecutionError { - possibly_accepted: false, - inner: Error::from(ContextProviderError::Config( - "Context provider not initialized".to_string(), - )), - address: Some(response.address.clone()), - retries: response.retries, - })?; + if let Some(e) = state_transition_broadcast_error { + warn!(error=?e, "wait: state transition broadcast error detected"); + let state_transition_broadcast_error: StateTransitionBroadcastError = + StateTransitionBroadcastError::try_from(e.clone()) + .wrap_to_execution_result(&response)? + .inner; - // Verify through the `FromProof` impl: it runs the GroveDB structural check AND - // `verify_tenderdash_proof` (the quorum BLS signature gate) that authenticates - // `metadata`. The request must be reconstructed to feed that verifier. A quorum - // key the provider has not cached is fetched and this same response verified - // again, so a transition that executed is not reported as failed. - let request: BroadcastStateTransitionRequest = self - .broadcast_request_for_state_transition() - .wrap_to_execution_result(&response)? - .inner; - - trace!("wait: verifying proof and quorum signature"); - let (maybe_outcome, metadata, _proof) = sdk - .verify_fetching_quorum_key::( - request, - grpc_response.clone(), - &context_provider, - "wait_for_state_transition_result", - ) - .await - .wrap_to_execution_result(&response)? - .inner; - - // The current `FromProof` impl always yields `Some`; this guards only a future - // impl change, so it stays a typed error rather than an unwrap. - let outcome: StateTransitionProofOutcome = maybe_outcome - .ok_or_else(|| { - Error::InvalidProvedResponse( - "state transition result missing from verified proof".to_string(), - ) - }) - .wrap_to_execution_result(&response)? - .inner; - - trace!("wait: proof verification successful"); - trace!( - result_variant = %outcome.result().to_string(), - execution_proved = outcome.is_execution_proved(), - "wait: result variant" - ); + return Err(Error::from(state_transition_broadcast_error)) + .wrap_to_execution_result(&response); + } - Ok::<_, Error>((outcome, metadata)).wrap_to_execution_result(&response) + let sdk_provider = sdk.context_provider().ok_or(ExecutionError { + possibly_accepted: false, + inner: Error::from(ContextProviderError::Config( + "Context provider not initialized".to_string(), + )), + address: Some(response.address.clone()), + retries: response.retries, + })?; + let with_known_contract; + let context_provider: &dyn ContextProvider = match known_contract { + Some(contract) => { + with_known_contract = WithContract::new(&sdk_provider, contract); + &with_known_contract + } + None => &sdk_provider, }; - let future = retry(sdk.address_list(), retry_settings, factory); - // run the future with or without timeout, depending on the settings - let wait_timeout = settings.and_then(|s| s.wait_timeout); + // Verify through the `FromProof` impl: it runs the GroveDB structural check AND + // `verify_tenderdash_proof` (the quorum BLS signature gate) that authenticates + // `metadata`. The request must be reconstructed to feed that verifier. A quorum + // key the provider has not cached is fetched and this same response verified + // again, so a transition that executed is not reported as failed. + let request: BroadcastStateTransitionRequest = state_transition + .broadcast_request_for_state_transition() + .wrap_to_execution_result(&response)? + .inner; + + trace!("wait: verifying proof and quorum signature"); + let (maybe_outcome, metadata, _proof) = sdk + .verify_fetching_quorum_key::( + request, + grpc_response.clone(), + context_provider, + "wait_for_state_transition_result", + ) + .await + .wrap_to_execution_result(&response)? + .inner; + + // The current `FromProof` impl always yields `Some`; this guards only a future + // impl change, so it stays a typed error rather than an unwrap. + let outcome: StateTransitionProofOutcome = maybe_outcome + .ok_or_else(|| { + Error::InvalidProvedResponse( + "state transition result missing from verified proof".to_string(), + ) + }) + .wrap_to_execution_result(&response)? + .inner; - trace!(timeout = ?wait_timeout, "wait: starting retry mechanism"); + trace!("wait: proof verification successful"); + trace!( + result_variant = %outcome.result().to_string(), + execution_proved = outcome.is_execution_proved(), + "wait: result variant" + ); - match wait_timeout { - Some(timeout) => { - trace!(?timeout, "wait: waiting with timeout"); - tokio::time::timeout(timeout, future) - .await - .map_err(|e| { - warn!(?timeout, "wait: timeout reached"); - Error::TimeoutReached( - timeout, - format!("Timeout waiting for result of {} (tx id: {}) affecting object {}: {:?}", - self.name(), - self.transaction_id().map(hex::encode).unwrap_or("UNKNOWN".to_string()), - self.unique_identifiers().join(","), - e), - ) - })? - .into_inner() - } - None => { - trace!("wait: waiting without timeout"); - future.await.into_inner() - } + Ok::<_, Error>((outcome, metadata)).wrap_to_execution_result(&response) + }; + + let future = retry(sdk.address_list(), retry_settings, factory); + // run the future with or without timeout, depending on the settings + let wait_timeout = settings.and_then(|s| s.wait_timeout); + + trace!(timeout = ?wait_timeout, "wait: starting retry mechanism"); + + match wait_timeout { + Some(timeout) => { + trace!(?timeout, "wait: waiting with timeout"); + tokio::time::timeout(timeout, future) + .await + .map_err(|e| { + warn!(?timeout, "wait: timeout reached"); + Error::TimeoutReached( + timeout, + format!("Timeout waiting for result of {} (tx id: {}) affecting object {}: {:?}", + state_transition.name(), + state_transition.transaction_id().map(hex::encode).unwrap_or("UNKNOWN".to_string()), + state_transition.unique_identifiers().join(","), + e), + ) + })? + .into_inner() + } + None => { + trace!("wait: waiting without timeout"); + future.await.into_inner() } } } diff --git a/packages/rs-sdk/src/platform/transition/outcome/inputs.rs b/packages/rs-sdk/src/platform/transition/outcome/inputs.rs index 37796339535..ac871af0a61 100644 --- a/packages/rs-sdk/src/platform/transition/outcome/inputs.rs +++ b/packages/rs-sdk/src/platform/transition/outcome/inputs.rs @@ -173,8 +173,8 @@ impl TransitionInputs { // Identity-contract nonces. StateTransition::DataContractUpdate(st) => { TransitionInputs::Nonces(vec![NonceInput::IdentityContract { - identity_id: st.data_contract().owner_id(), - contract_id: st.data_contract().id(), + identity_id: st.owner_id(), + contract_id: st.data_contract_id(), nonce: st.identity_contract_nonce(), }]) } diff --git a/packages/rs-sdk/src/platform/transition/waitable.rs b/packages/rs-sdk/src/platform/transition/waitable.rs index e00be951043..889e0a1d32b 100644 --- a/packages/rs-sdk/src/platform/transition/waitable.rs +++ b/packages/rs-sdk/src/platform/transition/waitable.rs @@ -1,7 +1,9 @@ use std::collections::BTreeMap; +use std::sync::Arc; use super::broadcast::{ - convert_proof_result, require_execution_proved, BroadcastStateTransition, WaitForOutcome, + convert_proof_result, require_execution_proved, wait_for_outcome_knowing_contract, + BroadcastStateTransition, WaitForOutcome, }; use super::put_settings::PutSettings; use crate::platform::Fetch; @@ -51,6 +53,41 @@ impl Waitable for DataContract { } } +/// Waits for the result of a data contract update and verifies its proof against +/// `pre_update_contract`, the contract as it was when the update was built. +/// +/// A delta contract update (version 1 of the update transition, from protocol version 15) +/// carries only what it changes, so its proof is verified by merging the delta onto the +/// contract it was built on and requiring the proved contract to be the result. +/// [`Waitable::wait_for_response`] takes that contract from the SDK's context provider, +/// which keeps the latest version of each contract it is given: once the update is +/// committed, any other operation may give the provider the updated contract before this +/// proof is verified, and the provider does not take an older version back. The verifier +/// then has no contract to merge the delta onto, and an update that executed and was paid +/// for is reported as failed. +/// +/// Here the contract is part of the call. It is known for this verification only, whatever +/// the provider holds, and the provider is not written. An update that embeds its contract +/// (version 0) is verified as [`Waitable::wait_for_response`] verifies it. +/// +/// As for any contract update, the proof authenticates the contract as it is after the +/// update: a snapshot at the proof's block. +pub async fn wait_for_data_contract_update( + sdk: &Sdk, + state_transition: &StateTransition, + pre_update_contract: &Arc, + settings: Option, +) -> Result { + let (outcome, _metadata) = wait_for_outcome_knowing_contract( + state_transition, + sdk, + settings, + Some(pre_update_contract), + ) + .await?; + convert_proof_result(outcome.into_result()) +} + #[async_trait::async_trait] impl Waitable for Document { async fn wait_for_response( diff --git a/packages/rs-sdk/src/platform/transition/with_contract.rs b/packages/rs-sdk/src/platform/transition/with_contract.rs new file mode 100644 index 00000000000..6f7d2bb8148 --- /dev/null +++ b/packages/rs-sdk/src/platform/transition/with_contract.rs @@ -0,0 +1,94 @@ +//! A context provider that knows one data contract itself. + +use dash_context_provider::{ContextProvider, ContextProviderError, QuorumKeyFuture}; +use dpp::dashcore::Network; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::TokenConfiguration; +use dpp::prelude::{CoreBlockHeight, DataContract, Identifier}; +use dpp::version::PlatformVersion; +use std::sync::Arc; + +/// `provider`, except that the data contract known under `contract`'s id is `contract`. +/// +/// A context provider keeps the latest version of each contract it is given, and any +/// operation may give it a newer one. A proof that is verified against one given version of +/// a contract, as the proof of a delta contract update is against the contract the delta +/// was built on, is verified in this context instead: the contract is the one the operation +/// started with, whatever the provider holds by the time the proof arrives. The provider is +/// not written, so other operations keep seeing its latest version. +pub(crate) struct WithContract<'a> { + provider: &'a dyn ContextProvider, + contract: &'a Arc, +} + +impl<'a> WithContract<'a> { + pub(crate) fn new(provider: &'a dyn ContextProvider, contract: &'a Arc) -> Self { + Self { provider, contract } + } +} + +impl ContextProvider for WithContract<'_> { + fn get_data_contract( + &self, + id: &Identifier, + platform_version: &PlatformVersion, + ) -> Result>, ContextProviderError> { + if *id == self.contract.id() { + return Ok(Some(Arc::clone(self.contract))); + } + self.provider.get_data_contract(id, platform_version) + } + + fn register_data_contract(&self, contract: Arc) { + self.provider.register_data_contract(contract) + } + + fn get_token_configuration( + &self, + token_id: &Identifier, + ) -> Result, ContextProviderError> { + self.provider.get_token_configuration(token_id) + } + + fn get_quorum_public_key( + &self, + quorum_type: u32, + quorum_hash: [u8; 32], + core_chain_locked_height: u32, + ) -> Result<[u8; 48], ContextProviderError> { + self.provider + .get_quorum_public_key(quorum_type, quorum_hash, core_chain_locked_height) + } + + fn fetch_quorum_public_key( + &self, + quorum_type: u32, + quorum_hash: [u8; 32], + core_chain_locked_height: u32, + ) -> Option { + self.provider + .fetch_quorum_public_key(quorum_type, quorum_hash, core_chain_locked_height) + } + + fn get_platform_activation_height(&self) -> Result { + self.provider.get_platform_activation_height() + } + + fn network(&self) -> Option { + self.provider.network() + } + + fn requires_proofs(&self) -> bool { + self.provider.requires_proofs() + } + + fn core_height_verified( + &self, + quorum_type: u32, + quorum_hash: [u8; 32], + core_chain_locked_height: u32, + ) { + self.provider + .core_height_verified(quorum_type, quorum_hash, core_chain_locked_height) + } +} diff --git a/packages/rs-sdk/src/sdk.rs b/packages/rs-sdk/src/sdk.rs index 95281eacaa3..f0b094158c2 100644 --- a/packages/rs-sdk/src/sdk.rs +++ b/packages/rs-sdk/src/sdk.rs @@ -53,6 +53,8 @@ use zeroize::Zeroizing; #[cfg(all(test, feature = "mocks"))] mod block_query_tests; #[cfg(all(test, feature = "mocks"))] +mod contract_update_wait_tests; +#[cfg(all(test, feature = "mocks"))] mod document_query_shape_tests; #[cfg(all(test, feature = "mocks"))] mod identity_discovery_tests; diff --git a/packages/rs-sdk/src/sdk/contract_update_wait_tests.rs b/packages/rs-sdk/src/sdk/contract_update_wait_tests.rs new file mode 100644 index 00000000000..50ac6f5aaa4 --- /dev/null +++ b/packages/rs-sdk/src/sdk/contract_update_wait_tests.rs @@ -0,0 +1,195 @@ +//! The wait for a delta contract update verifies its proof against the contract the delta +//! was built on, whatever the SDK's context provider holds by the time the proof arrives. + +use super::{SdkBuilder, SdkInstance}; +use crate::platform::transition::broadcast_request::BroadcastRequestForStateTransition; +use crate::platform::transition::put_settings::PutSettings; +use crate::platform::transition::waitable::{wait_for_data_contract_update, Waitable}; +use crate::platform::ContextProvider; +use crate::{Error, Sdk}; +use dapi_grpc::platform::v0::wait_for_state_transition_result_response::{ + wait_for_state_transition_result_response_v0::Result as WaitResult, Version as WaitVersion, + WaitForStateTransitionResultResponseV0, +}; +use dapi_grpc::platform::v0::{Proof, ResponseMetadata, WaitForStateTransitionResultResponse}; +use dpp::dashcore::Network; +use dpp::data_contract::accessors::v0::{DataContractV0Getters, DataContractV0Setters}; +use dpp::data_contract::accessors::v1::DataContractV1Setters; +use dpp::prelude::DataContract; +use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; +use dpp::state_transition::StateTransition; +use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; +use dpp::version::PlatformVersion; +use rs_dapi_client::{ExecutionResponse, RequestSettings}; +use rs_sdk_trusted_context_provider::TrustedHttpContextProvider; +use std::num::NonZeroUsize; +use std::path::PathBuf; +use std::sync::Arc; + +/// A contract, the contract a delta turns it into, and the delta. +fn delta_update() -> (Arc, Arc, StateTransition) { + let platform_version = PlatformVersion::latest(); + let original = load_system_data_contract(SystemDataContract::Dashpay, platform_version) + .expect("expected the DashPay contract"); + let mut updated = original.clone(); + updated.set_version(original.version() + 1); + updated.set_description(Some("payments between contacts".to_string())); + + let delta = DataContractUpdateTransition::from_contract_update( + &original, + &updated, + 1, + platform_version, + ) + .expect("expected a contract update"); + assert!( + matches!(delta, DataContractUpdateTransition::V1(_)), + "the latest protocol version builds a delta" + ); + (Arc::new(original), Arc::new(updated), delta.into()) +} + +/// A context provider that keeps the latest version of a contract it is given, as the one a +/// wallet shares between its operations does. +fn shared_provider() -> Arc { + Arc::new( + TrustedHttpContextProvider::new_with_url( + Network::Regtest, + "http://127.0.0.1:1".to_string(), + NonZeroUsize::new(10).expect("non-zero cache size"), + ) + .expect("expected a trusted provider") + .with_refetch_if_not_found(false), + ) +} + +/// An SDK verifying with `provider`, whose node answers the wait for `transition` with a +/// well-formed proof of something else: verification gets as far as reading that proof only +/// when the verifier has the contract the delta is merged onto. +async fn sdk_answering_the_wait( + transition: &StateTransition, + provider: Arc, +) -> Sdk { + let platform_version = PlatformVersion::latest(); + let recorded_proof = std::fs::read_to_string( + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../rs-drive-proof-verifier/tests/vectors/identity-balance/proof.hex"), + ) + .expect("expected the recorded proof"); + let response = WaitForStateTransitionResultResponse { + version: Some(WaitVersion::V0(WaitForStateTransitionResultResponseV0 { + result: Some(WaitResult::Proof(Proof { + grovedb_proof: hex::decode(recorded_proof.trim()) + .expect("expected the recorded proof to be hex"), + quorum_hash: vec![0; 32], + signature: vec![0; 96], + round: 0, + block_id_hash: vec![0; 32], + quorum_type: 106, + })), + metadata: Some(ResponseMetadata { + height: 10, + core_chain_locked_height: 1, + epoch: 0, + time_ms: 1_000, + protocol_version: platform_version.protocol_version, + chain_id: "test".to_string(), + }), + })), + }; + + let sdk = SdkBuilder::new_mock() + .with_network(Network::Regtest) + .with_version(platform_version) + .build() + .expect("expected a mock SDK"); + let SdkInstance::Mock { dapi, .. } = &sdk.inner else { + unreachable!("the SDK was built as a mock") + }; + dapi.lock() + .await + .expect( + &transition + .wait_for_state_transition_result_request() + .expect("expected a wait request"), + &Ok(ExecutionResponse { + inner: response, + address: "http://127.0.0.1:9000" + .parse() + .expect("expected an address"), + retries: 0, + }), + ) + .expect("expected the mock node to take the response"); + sdk.set_context_provider(provider) + .expect("expected the SDK to take the provider"); + sdk +} + +fn no_retries() -> Option { + Some(PutSettings { + request_settings: RequestSettings { + retries: Some(0), + ..Default::default() + }, + ..Default::default() + }) +} + +/// Whether verification stopped for want of the contract the delta is merged onto. +fn lacks_the_contract_the_delta_was_built_on(error: &Error) -> bool { + error + .to_string() + .contains("is verified against the version before it") +} + +/// The order of events this guards against: the wallet builds a delta on version N and +/// broadcasts it; the update is committed; another operation of the wallet fetches the +/// contract, now at version N + 1, and gives it to the shared provider; the proof of the +/// update arrives and is verified. +#[tokio::test] +async fn should_verify_a_delta_against_the_contract_it_was_built_on_after_the_provider_moved_on() { + let (original, updated, transition) = delta_update(); + let provider = shared_provider(); + // What the wallet did before it broadcast, when the provider was the only way to tell + // the verifier the contract + provider.register_data_contract(Arc::clone(&original)); + let sdk = sdk_answering_the_wait(&transition, Arc::clone(&provider)).await; + + // Between the broadcast and the proof, another operation promotes the provider + provider.register_data_contract(Arc::clone(&updated)); + // and the provider does not take the older contract back + provider.register_data_contract(Arc::clone(&original)); + let held = provider + .get_data_contract(&original.id(), PlatformVersion::latest()) + .expect("expected the provider to answer") + .expect("expected the provider to know the contract"); + assert_eq!(held.version(), updated.version()); + + // A wait that asks the provider has nothing to merge the delta onto + let error = DataContract::wait_for_response(&sdk, transition.clone(), no_retries()) + .await + .expect_err("the test's proof is not one of the update"); + assert!( + lacks_the_contract_the_delta_was_built_on(&error), + "got {error}" + ); + + // A wait that is given the contract merges the delta and goes on to read the proof, + // which here proves something else + let error = wait_for_data_contract_update(&sdk, &transition, &original, no_retries()) + .await + .expect_err("the test's proof is not one of the update"); + assert!( + !lacks_the_contract_the_delta_was_built_on(&error), + "got {error}" + ); + assert!(matches!(error, Error::Proof(_)), "got {error:?}"); + + // The wait left the provider as other operations need it + let held = provider + .get_data_contract(&original.id(), PlatformVersion::latest()) + .expect("expected the provider to answer") + .expect("expected the provider to know the contract"); + assert_eq!(held.version(), updated.version()); +} diff --git a/packages/wasm-dpp/src/data_contract/state_transition/data_contract_update_transition/mod.rs b/packages/wasm-dpp/src/data_contract/state_transition/data_contract_update_transition/mod.rs index d26e3ac3901..1c6eaeceed0 100644 --- a/packages/wasm-dpp/src/data_contract/state_transition/data_contract_update_transition/mod.rs +++ b/packages/wasm-dpp/src/data_contract/state_transition/data_contract_update_transition/mod.rs @@ -92,8 +92,14 @@ impl DataContractUpdateTransitionWasm { PlatformVersion::latest() }; + let data_contract = self.0.data_contract().ok_or_else(|| { + JsValue::from_str( + "a delta-based data contract update transition carries no full contract", + ) + })?; + DataContractWasm::try_from_serialization_format_with_platform_version( - self.0.data_contract().clone(), + data_contract.clone(), false, platform_version, ) @@ -111,6 +117,12 @@ impl DataContractUpdateTransitionWasm { self.0.owner_id().into() } + /// The contract the update targets: embedded in a V0 transition, named by a V1 delta. + #[wasm_bindgen(js_name=getDataContractId)] + pub fn get_data_contract_id(&self) -> IdentifierWrapper { + self.0.data_contract_id().into() + } + #[wasm_bindgen(js_name=getIdentityContractNonce)] pub fn get_identity_contract_nonce(&self) -> u64 { self.0.identity_contract_nonce() diff --git a/packages/wasm-dpp/src/errors/consensus/consensus_error.rs b/packages/wasm-dpp/src/errors/consensus/consensus_error.rs index ac96756afa9..d7046046540 100644 --- a/packages/wasm-dpp/src/errors/consensus/consensus_error.rs +++ b/packages/wasm-dpp/src/errors/consensus/consensus_error.rs @@ -73,6 +73,9 @@ use dpp::consensus::basic::identity::{DataContractBoundsNotPresentError, Disabli use dpp::consensus::basic::overflow_error::OverflowError; use dpp::consensus::basic::token::{ChoosingTokenMintRecipientNotAllowedError, ContractHasNoTokensError, DestinationIdentityForTokenMintingNotSetError, InvalidActionIdError, InvalidTokenAmountError, InvalidTokenConfigUpdateNoChangeError, InvalidTokenIdError, InvalidTokenNoteTooBigError, InvalidTokenPositionError, MissingDefaultLocalizationError, TokenNoteOnlyAllowedWhenProposerError, TokenPricingScheduleEmptyError, TokenTransferToOurselfError, InvalidTokenDistributionTimeIntervalNotMinuteAlignedError, InvalidTokenDistributionTimeIntervalTooShortError, InvalidTokenDistributionBlockIntervalTooShortError, InvalidTokenDistributionEpochIntervalTooShortError, InvalidTokenOncePerIdentityDistributionAmountError}; use dpp::consensus::state::data_contract::data_contract_not_found_error::DataContractNotFoundError; +use dpp::consensus::state::data_contract::data_contract_update_entry_already_exists_error::DataContractUpdateEntryAlreadyExistsError; +use dpp::consensus::state::data_contract::data_contract_update_entry_not_found_error::DataContractUpdateEntryNotFoundError; +use dpp::consensus::basic::data_contract::{DataContractMaxSizeExceededError, DataContractUpdateOverlappingEntriesError}; use dpp::consensus::state::data_contract::data_contract_update_action_not_allowed_error::DataContractUpdateActionNotAllowedError; use dpp::consensus::state::data_contract::document_type_update_error::DocumentTypeUpdateError; use dpp::consensus::state::document::document_contest_currently_locked_error::DocumentContestCurrentlyLockedError; @@ -835,6 +838,12 @@ pub fn from_state_error(state_error: &StateError) -> JsValue { StateError::PrivateDocumentEntrySizeMismatchError(e) => { generic_consensus_error!(PrivateDocumentEntrySizeMismatchError, e).into() } + StateError::DataContractUpdateEntryAlreadyExistsError(e) => { + generic_consensus_error!(DataContractUpdateEntryAlreadyExistsError, e).into() + } + StateError::DataContractUpdateEntryNotFoundError(e) => { + generic_consensus_error!(DataContractUpdateEntryNotFoundError, e).into() + } } } @@ -1472,6 +1481,12 @@ fn from_basic_error(basic_error: &BasicError) -> JsValue { BasicError::DuplicatePrivateDocumentEntryError(e) => { generic_consensus_error!(DuplicatePrivateDocumentEntryError, e).into() } + BasicError::DataContractUpdateOverlappingEntriesError(e) => { + generic_consensus_error!(DataContractUpdateOverlappingEntriesError, e).into() + } + BasicError::DataContractMaxSizeExceededError(e) => { + generic_consensus_error!(DataContractMaxSizeExceededError, e).into() + } } } diff --git a/packages/wasm-dpp2/src/data_contract/transitions/update.rs b/packages/wasm-dpp2/src/data_contract/transitions/update.rs index 740746e38b2..063b3c879f1 100644 --- a/packages/wasm-dpp2/src/data_contract/transitions/update.rs +++ b/packages/wasm-dpp2/src/data_contract/transitions/update.rs @@ -1,5 +1,6 @@ use crate::data_contract::DataContractWasm; use crate::error::{WasmDppError, WasmDppResult}; +use crate::identifier::IdentifierWasm; use crate::impl_wasm_conversions_inner; use crate::impl_wasm_type_info; use crate::state_transitions::StateTransitionWasm; @@ -10,6 +11,7 @@ use dpp::platform_value::string_encoding::{decode, encode}; use dpp::prelude::{DataContract, IdentityNonce}; use dpp::serialization::{PlatformDeserializableUntrusted, PlatformSerializable}; use dpp::state_transition::StateTransition; +use dpp::state_transition::StateTransitionOwned; use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; use dpp::state_transition::data_contract_update_transition::accessors::DataContractUpdateTransitionAccessorsV0; use dpp::validation::operations::ProtocolValidationOperation; @@ -19,26 +21,103 @@ use wasm_bindgen::prelude::wasm_bindgen; #[wasm_bindgen(typescript_custom_section)] const TS_TYPES: &str = r#" /** - * DataContractUpdateTransition serialized as a plain object. + * What a delta-based (V1) DataContractUpdateTransition does to the description. + */ +export type DataContractDescriptionUpdate = "keep" | "clear" | { set: string }; + +/** + * A full-contract (V0) DataContractUpdateTransition serialized as a plain object. */ -export interface DataContractUpdateTransitionObject { +export interface DataContractUpdateTransitionV0Object { + $formatVersion: "0"; dataContract: DataContractObject; - identityNonce: bigint; + "$identity-contract-nonce": bigint; userFeeIncrease: number; signaturePublicKeyId: number; signature?: Uint8Array; } /** - * DataContractUpdateTransition serialized as JSON. + * A delta-based (V1) DataContractUpdateTransition serialized as a plain object. + * It carries only what changed, keyed by the contract, its owner and the + * version the update produces. + * + * Every value is in its serialized form: the identifiers are bytes, and a group + * or a token configuration is a plain record, not a class instance. The + * transition's `dataContractId` and `ownerId` getters return `Identifier`s. + */ +export interface DataContractUpdateTransitionV1Object { + $formatVersion: "1"; + "$identity-contract-nonce": bigint; + dataContractId: Uint8Array; + ownerId: Uint8Array; + version: number; + config?: DataContractConfig; + updatedSchemaDefs?: Record; + newSchemaDefs?: Record; + updatedDocumentSchemas?: Record; + newDocumentSchemas?: Record; + newGroups?: Record; + newTokens?: Record; + addKeywords?: string[]; + removeKeywords?: string[]; + description?: DataContractDescriptionUpdate; + userFeeIncrease: number; + signaturePublicKeyId: number; + signature?: Uint8Array; +} + +/** + * DataContractUpdateTransition serialized as a plain object. + */ +export type DataContractUpdateTransitionObject = + | DataContractUpdateTransitionV0Object + | DataContractUpdateTransitionV1Object; + +/** + * A full-contract (V0) DataContractUpdateTransition serialized as JSON. */ -export interface DataContractUpdateTransitionJSON { +export interface DataContractUpdateTransitionV0JSON { + $formatVersion: "0"; dataContract: DataContractJSON; - identityNonce: string; + "$identity-contract-nonce": number | string; userFeeIncrease: number; signaturePublicKeyId: number; signature?: string; } + +/** + * A delta-based (V1) DataContractUpdateTransition serialized as JSON + * (with string identifiers). + */ +export interface DataContractUpdateTransitionV1JSON { + $formatVersion: "1"; + "$identity-contract-nonce": number | string; + dataContractId: string; + ownerId: string; + version: number; + /** `null` when the delta keeps the stored config. */ + config?: DataContractConfig | null; + updatedSchemaDefs?: Record; + newSchemaDefs?: Record; + updatedDocumentSchemas?: Record; + newDocumentSchemas?: Record; + newGroups?: Record; + newTokens?: Record; + addKeywords?: string[]; + removeKeywords?: string[]; + description?: DataContractDescriptionUpdate; + userFeeIncrease: number; + signaturePublicKeyId: number; + signature?: string; +} + +/** + * DataContractUpdateTransition serialized as JSON. + */ +export type DataContractUpdateTransitionJSON = + | DataContractUpdateTransitionV0JSON + | DataContractUpdateTransitionV1JSON; "#; #[wasm_bindgen] @@ -146,7 +225,8 @@ impl DataContractUpdateTransitionWasm { &platform_version.into(), )?; - self.0.set_data_contract(data_contract_serialization_format); + self.0 + .set_data_contract(data_contract_serialization_format)?; Ok(()) } @@ -156,6 +236,17 @@ impl DataContractUpdateTransitionWasm { self.0.identity_contract_nonce() } + /// The contract the update targets: embedded in a V0 transition, named by a V1 delta. + #[wasm_bindgen(getter = "dataContractId")] + pub fn data_contract_id(&self) -> IdentifierWasm { + self.0.data_contract_id().into() + } + + #[wasm_bindgen(getter = "ownerId")] + pub fn owner_id(&self) -> IdentifierWasm { + self.0.owner_id().into() + } + #[wasm_bindgen(js_name = "getDataContract")] pub fn get_data_contract( &self, @@ -164,7 +255,11 @@ impl DataContractUpdateTransitionWasm { ) -> WasmDppResult { let platform_version = PlatformVersionWasm::try_from(platform_version)?; - let data_contract_serialization_format = self.0.data_contract(); + let data_contract_serialization_format = self.0.data_contract().ok_or_else(|| { + WasmDppError::invalid_argument( + "a delta-based data contract update transition carries no full contract", + ) + })?; let mut validation_operations: Vec = Vec::new(); diff --git a/packages/wasm-dpp2/src/state_transitions/base/state_transition.rs b/packages/wasm-dpp2/src/state_transitions/base/state_transition.rs index 836e4044bca..3c28d98ddde 100644 --- a/packages/wasm-dpp2/src/state_transitions/base/state_transition.rs +++ b/packages/wasm-dpp2/src/state_transitions/base/state_transition.rs @@ -562,27 +562,37 @@ impl StateTransitionWasm { self.0 = DataContractCreate(contract_create); } - DataContractUpdate(mut contract_update) => { - let new_contract = match contract_update.data_contract().clone() { - DataContractInSerializationFormat::V0(mut v0) => { - v0.owner_id = owner_id; - - DataContractInSerializationFormat::V0(v0) + DataContractUpdate(contract_update) => { + let contract_update = match contract_update { + DataContractUpdateTransition::V0(mut v0) => { + v0.data_contract = match v0.data_contract { + DataContractInSerializationFormat::V0(mut format) => { + format.owner_id = owner_id; + + DataContractInSerializationFormat::V0(format) + } + DataContractInSerializationFormat::V1(mut format) => { + format.owner_id = owner_id; + + DataContractInSerializationFormat::V1(format) + } + DataContractInSerializationFormat::V2(mut format) => { + format.base.owner_id = owner_id; + + DataContractInSerializationFormat::V2(format) + } + }; + + DataContractUpdateTransition::V0(v0) } - DataContractInSerializationFormat::V1(mut v1) => { + // A delta embeds no contract and names its owner itself + DataContractUpdateTransition::V1(mut v1) => { v1.owner_id = owner_id; - DataContractInSerializationFormat::V1(v1) - } - DataContractInSerializationFormat::V2(mut v2) => { - v2.base.owner_id = owner_id; - - DataContractInSerializationFormat::V2(v2) + DataContractUpdateTransition::V1(v1) } }; - contract_update.set_data_contract(new_contract); - self.0 = DataContractUpdate(contract_update); } Batch(mut batch) => { @@ -709,6 +719,11 @@ impl StateTransitionWasm { DataContractUpdateTransition::V0(v0).into() } + DataContractUpdateTransition::V1(mut v1) => { + v1.identity_contract_nonce = nonce; + + DataContractUpdateTransition::V1(v1).into() + } }, Batch(mut batch) => { batch.set_identity_contract_nonce(nonce); diff --git a/packages/wasm-dpp2/tests/unit/DataContractUpdateStateTransition.spec.ts b/packages/wasm-dpp2/tests/unit/DataContractUpdateStateTransition.spec.ts index 0d7f2f8c7f9..0a67728c25d 100644 --- a/packages/wasm-dpp2/tests/unit/DataContractUpdateStateTransition.spec.ts +++ b/packages/wasm-dpp2/tests/unit/DataContractUpdateStateTransition.spec.ts @@ -225,4 +225,66 @@ describe('DataContractUpdateTransition', () => { expect(restoredContract.ownerId.toBase58()).to.equal(value.ownerId); }); }); + + describe('delta (version 1)', () => { + // A delta names its contract and owner and carries only what it changes + const deltaJSON = () => ({ + $formatVersion: '1', + '$identity-contract-nonce': 8, + dataContractId: value.id, + ownerId: value.ownerId, + version: 2, + newGroups: { + 0: { + $formatVersion: '0', + members: { [value.ownerId]: 1, [value.id]: 1 }, + requiredPower: 2, + }, + }, + addKeywords: ['wallet'], + description: { set: 'a described contract' }, + userFeeIncrease: 0, + signaturePublicKeyId: 0, + signature: '', + }); + + it('should read a delta from JSON through the getters', () => { + const transition = wasm.DataContractUpdateTransition.fromJSON(deltaJSON()); + + expect(transition.featureVersion).to.equal(1); + expect(transition.identityContractNonce).to.deep.equal(BigInt(8)); + expect(transition.dataContractId.toBase58()).to.equal(value.id); + expect(transition.ownerId.toBase58()).to.equal(value.ownerId); + expect(() => transition.getDataContract()).to.throw(); + }); + + it('should write a delta as JSON with text identifiers and a numeric nonce', () => { + const json = wasm.DataContractUpdateTransition.fromJSON(deltaJSON()).toJSON(); + + expect(json.$formatVersion).to.equal('1'); + expect(json['$identity-contract-nonce']).to.equal(8); + expect(json.dataContractId).to.equal(value.id); + expect(json.ownerId).to.equal(value.ownerId); + expect(json.version).to.equal(2); + // A delta that keeps the stored config writes a null + expect(json.config).to.equal(null); + expect(json.newGroups['0'].requiredPower).to.equal(2); + expect(json.addKeywords).to.deep.equal(['wallet']); + expect(json.description).to.deep.equal({ set: 'a described contract' }); + }); + + it('should write a delta as an object with byte identifiers and plain groups', () => { + const obj = wasm.DataContractUpdateTransition.fromJSON(deltaJSON()).toObject(); + + expect(obj.$formatVersion).to.equal('1'); + expect(obj['$identity-contract-nonce']).to.deep.equal(BigInt(8)); + expect(obj.dataContractId).to.be.instanceOf(Uint8Array); + expect(obj.ownerId).to.be.instanceOf(Uint8Array); + expect(obj.version).to.equal(2); + expect(obj.newGroups['0']).to.not.be.instanceOf(wasm.Group); + expect(obj.newGroups['0'].requiredPower).to.equal(2); + expect(obj.newGroups['0'].members[value.ownerId]).to.equal(1); + expect(obj.addKeywords).to.deep.equal(['wallet']); + }); + }); });