From fd216b747580416aba28c8e18f76e5b19c05f188 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sun, 8 Nov 2026 00:37:10 +0700 Subject: [PATCH 1/4] feat(sdk): refuse a private document type too small for its payload Platform holds a private document type's entrySize only to 1 to 4096: it never reads an entry, so it registers a type whose entries cannot hold its own properties, and that size can never change. The SDK now refuses such a type before signing. dpp: - DocumentPropertyType::max_encoded_value_size, next to the encoder it follows: the most bytes a value's encoding takes, None when nothing bounds it (a string without maxLength or maxBytes, a byte array without maxItems, an untyped array). - largest_private_document_payload_size: a type's properties at their largest, with the presence byte of each optional one, as a document writes them after its system fields; refused with UnboundedPrivateDocumentProperty when a property has no bound. - minimum_private_document_entry_size: that plus the 299 bytes of the standard private document envelope (version 1), whose sizes are now named constants. - validate_private_document_entry_size: refuses a private type whose entrySize is below it (PrivateDocumentEntrySizeTooSmall). rs-sdk: ensure_private_document_entries_fit runs it on every type of a contract; PutContract calls it before fetching the nonce, and wasm-sdk's contract update calls it too. Tests check the largest payload against a document of a type holding every bounded property kind, serialized. Co-Authored-By: Claude Opus 5.5 --- book/src/contract-keywords.md | 2 +- .../src/data_contract/document_type/mod.rs | 7 +- .../document_type/private_document.rs | 342 +++++++++++++++++- .../document_type/property/mod.rs | 74 ++++ packages/rs-dpp/src/errors/protocol_error.rs | 23 ++ .../src/platform/transition/put_contract.rs | 82 +++++ .../src/state_transitions/contract.rs | 8 +- 7 files changed, 534 insertions(+), 4 deletions(-) diff --git a/book/src/contract-keywords.md b/book/src/contract-keywords.md index 0483204e46f..d25620aee1d 100644 --- a/book/src/contract-keywords.md +++ b/book/src/contract-keywords.md @@ -146,7 +146,7 @@ Every key a contract can write, grouped by where it goes. **Since** is the proto | `rangeCountable`, `rangeSummable`, `rangeAverageable` | boolean | Provable counts, sums or averages over ranges of document ids. | 12 | [Document type range keys](contract-keywords/aggregates.md#document-type-rangecountable-rangesummable-rangeaverageable) | | `indexOnly` | boolean | Documents are never stored whole: the index entries are the rows. | 14 | [indexOnly](contract-keywords/index-only.md#indexonly) · [internals](drive/index-only-document-types.md) | | `entryPayload` | array of 1 to 16 names | On an index-only type, properties carried in each entry's value instead of a key. | 14 | [entryPayload](contract-keywords/index-only.md#entrypayload) | -| `private` | object: `entrySize`, 1 to 4096 | A private type: its documents are encrypted entries of `entrySize` bytes, which the chain never reads. Its `properties` describe the plaintext. It declares only `type`, `properties`, `required`, `additionalProperties`, `minProperties`, `maxProperties`, `dependentRequired`, `$comment`, `description`, the two bounded key keys, and `documentsMutable`, `canBeDeleted` and `documentsKeepHistory` as `false`, each at most once; neither its properties nor `required` nor `dependentRequired` name a system field, no property at any depth declares `refersTo`, `distinctFrom`, `generatedFrom`, `encryptedFor` or `requiredSince`, and the contract's elected moderators may not moderate it. No reference, `countOf` or `sumOf` may name it, an update cannot change it, and a Batch refuses every document transition on it (`DocumentTypePrivateError`, 10425). Entries are appended only by `PrivateDocumentCreateFromShieldedPool` (type 29), from 1 to 16 distinct entries of exactly `entrySize` bytes, paid from the credit shielded pool. | 15 | | +| `private` | object: `entrySize`, 1 to 4096 | A private type: its documents are encrypted entries of `entrySize` bytes, which the chain never reads. Its `properties` describe the plaintext. It declares only `type`, `properties`, `required`, `additionalProperties`, `minProperties`, `maxProperties`, `dependentRequired`, `$comment`, `description`, the two bounded key keys, and `documentsMutable`, `canBeDeleted` and `documentsKeepHistory` as `false`, each at most once; neither its properties nor `required` nor `dependentRequired` name a system field, no property at any depth declares `refersTo`, `distinctFrom`, `generatedFrom`, `encryptedFor` or `requiredSince`, and the contract's elected moderators may not moderate it. No reference, `countOf` or `sumOf` may name it, an update cannot change it, and a Batch refuses every document transition on it (`DocumentTypePrivateError`, 10425). Entries are appended only by `PrivateDocumentCreateFromShieldedPool` (type 29), from 1 to 16 distinct entries of exactly `entrySize` bytes, paid from the credit shielded pool. The chain does not compare `entrySize` with the properties; the SDK refuses to register a private type whose `entrySize` is below its largest payload plus the private document envelope's 299 bytes, or whose properties are not all bounded (`minimum_private_document_entry_size` in dpp). | 15 | | ### Property diff --git a/packages/rs-dpp/src/data_contract/document_type/mod.rs b/packages/rs-dpp/src/data_contract/document_type/mod.rs index 2669afc319a..cf279a48e93 100644 --- a/packages/rs-dpp/src/data_contract/document_type/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/mod.rs @@ -14,8 +14,13 @@ pub mod property_constraints; pub use index_level::IndexLevel; pub use index_level::IndexLevelTypeInfo; pub use index_level::IndexType; -pub use private_document::PrivateDocumentConfig; pub(crate) use private_document::PRIVATE_DOCUMENT_TYPE_KEYWORDS; +pub use private_document::{ + largest_private_document_payload_size, minimum_private_document_entry_size, + validate_private_document_entry_size, PrivateDocumentConfig, + PRIVATE_DOCUMENT_ENVELOPE_V1_BODY_HEADER_BYTES, PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES, + PRIVATE_DOCUMENT_ENVELOPE_V1_WRAPPER_BYTES, +}; #[cfg(feature = "random-documents")] pub mod random_document; diff --git a/packages/rs-dpp/src/data_contract/document_type/private_document.rs b/packages/rs-dpp/src/data_contract/document_type/private_document.rs index 324adfe5d6d..b22f0fcb6de 100644 --- a/packages/rs-dpp/src/data_contract/document_type/private_document.rs +++ b/packages/rs-dpp/src/data_contract/document_type/private_document.rs @@ -8,7 +8,12 @@ //! The type's `properties` describe the plaintext, so that clients can decode it with types. //! The chain checks them at registration like any schema, and never against an entry. -use crate::data_contract::document_type::property_names; +use crate::data_contract::document_type::accessors::{ + DocumentTypeV0Getters, DocumentTypeV2Getters, +}; +use crate::data_contract::document_type::{property_names, DocumentTypeRef}; +use crate::ProtocolError; +use platform_version::version::PlatformVersion; use std::num::NonZeroU32; /// What a document type's `private` keyword declares (`{ "entrySize": n }`). Built only by the @@ -59,3 +64,338 @@ pub(crate) const PRIVATE_DOCUMENT_TYPE_KEYWORDS: [&str; 15] = [ property_names::REQUIRES_IDENTITY_ENCRYPTION_BOUNDED_KEY, property_names::REQUIRES_IDENTITY_DECRYPTION_BOUNDED_KEY, ]; + +/// The bytes the standard private document envelope (version 1) wraps the encrypted body in: the +/// commitment (32), the ephemeral public key (33), the body's AEAD tag (16) and the sender-recovery +/// ciphertext (81). +pub const PRIVATE_DOCUMENT_ENVELOPE_V1_WRAPPER_BYTES: u32 = 32 + 33 + 16 + 81; + +/// The bytes the standard private document envelope (version 1) puts in the body before the +/// payload: the envelope version (1), the authentication mode (1), the sender's identity id (32) +/// and key id (4), the authentication (65), the recipient's identity id (32) and the payload's +/// length (2). +pub const PRIVATE_DOCUMENT_ENVELOPE_V1_BODY_HEADER_BYTES: u32 = 1 + 1 + 32 + 4 + 65 + 32 + 2; + +/// Every byte of an entry the standard private document envelope (version 1) takes besides the +/// payload: 299. +pub const PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES: u32 = + PRIVATE_DOCUMENT_ENVELOPE_V1_WRAPPER_BYTES + PRIVATE_DOCUMENT_ENVELOPE_V1_BODY_HEADER_BYTES; + +/// The most bytes a payload of `document_type` takes: its properties in the document property +/// encoding, as a document writes them after its system fields, each one present at its largest +/// and one written with a presence byte (optional or transient) counting that byte. A private +/// type's entries carry their plaintext in this encoding. +/// +/// Refused with `UnboundedPrivateDocumentProperty` when a property sets no largest value, since +/// then no entry size holds every payload. +pub fn largest_private_document_payload_size( + document_type: DocumentTypeRef, + platform_version: &PlatformVersion, +) -> Result { + let mut size = 0u32; + for (property_name, property) in document_type.properties() { + // A private type refuses `requiredSince`, so a property is required at every contract + // version an entry is written under. + let presence_byte = !property.required || property.transient; + let Some(value_size) = property + .property_type + .max_encoded_value_size(property.required, platform_version)? + else { + return Err(ProtocolError::UnboundedPrivateDocumentProperty { + document_type_name: document_type.name().clone(), + property_name: property_name.clone(), + }); + }; + size = size + .saturating_add(value_size) + .saturating_add(u32::from(presence_byte)); + } + Ok(size) +} + +/// The smallest `entrySize` that holds every payload of `document_type` in the standard private +/// document envelope (version 1): its largest payload plus +/// [`PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES`]. +pub fn minimum_private_document_entry_size( + document_type: DocumentTypeRef, + platform_version: &PlatformVersion, +) -> Result { + Ok( + largest_private_document_payload_size(document_type, platform_version)? + .saturating_add(PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES), + ) +} + +/// Refuses a private document type whose `entrySize` cannot hold its largest payload in the +/// standard private document envelope (version 1), which clients check before registering one. +/// The chain does not: it never reads an entry, so it only holds `entrySize` to +/// `max_private_document_entry_size`, and such a type registers but takes no full payload. A type +/// that is not private passes. +pub fn validate_private_document_entry_size( + document_type: DocumentTypeRef, + platform_version: &PlatformVersion, +) -> Result<(), ProtocolError> { + let Some(private_document) = document_type.private_document() else { + return Ok(()); + }; + let minimum_entry_size = minimum_private_document_entry_size(document_type, platform_version)?; + if private_document.entry_size() < minimum_entry_size { + return Err(ProtocolError::PrivateDocumentEntrySizeTooSmall { + document_type_name: document_type.name().clone(), + entry_size: private_document.entry_size(), + minimum_entry_size, + }); + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::data_contract::accessors::v0::DataContractV0Getters; + use crate::data_contract::conversion::value::v0::DataContractValueConversionMethodsV0; + use crate::data_contract::document_type::DocumentPropertyType; + use crate::data_contract::DataContract; + use crate::document::serialization_traits::DocumentPlatformConversionMethodsV0; + use crate::document::DocumentV0; + use platform_value::string_encoding::Encoding; + use platform_value::{Identifier, Value}; + use serde_json::json; + use std::collections::BTreeMap; + + /// A contract holding the private `secret` type of `entry_size`-byte entries with + /// `properties`, of which `required` are required, and the public `note` type. + fn contract( + entry_size: u32, + properties: serde_json::Value, + required: serde_json::Value, + ) -> DataContract { + DataContract::from_value( + platform_value::to_value(json!({ + "$formatVersion": "1", + "id": Identifier::from([7; 32]).to_string(Encoding::Base58), + "ownerId": Identifier::from([8; 32]).to_string(Encoding::Base58), + "version": 1, + "documentSchemas": { + "secret": { + "type": "object", + "private": { "entrySize": entry_size }, + "documentsMutable": false, + "canBeDeleted": false, + "properties": properties, + "required": required, + "additionalProperties": false + }, + "note": { + "type": "object", + "properties": { + "text": { "type": "string", "maxLength": 63, "position": 0 } + }, + "additionalProperties": false + } + } + })) + .expect("the contract converts"), + true, + PlatformVersion::latest(), + ) + .expect("the contract registers") + } + + /// One property of every kind a largest size bounds, optional ones among them. + fn every_bounded_kind() -> serde_json::Value { + json!({ + "small": { "type": "integer", "minimum": 0, "maximum": 255, "position": 0 }, + "large": { "type": "integer", "position": 1 }, + "label": { "type": "string", "maxLength": 10, "position": 2 }, + "short": { "type": "string", "maxBytes": 20, "position": 3 }, + "both": { "type": "string", "maxLength": 4, "maxBytes": 10, "position": 4 }, + "key": { + "type": "array", "byteArray": true, "minItems": 33, "maxItems": 33, + "position": 5 + }, + "blob": { "type": "array", "byteArray": true, "maxItems": 300, "position": 6 }, + "flag": { "type": "boolean", "position": 7 }, + "who": { + "type": "array", "byteArray": true, "minItems": 32, "maxItems": 32, + "contentMediaType": "application/x.dash.dpp.identifier", "position": 8 + }, + "meta": { + "type": "object", + "properties": { + "a": { "type": "integer", "minimum": 0, "maximum": 65535, "position": 0 }, + "b": { "type": "string", "maxLength": 5, "position": 1 } + }, + "required": ["a"], + "additionalProperties": false, + "position": 9 + }, + "tags": { + "type": "array", "maxItems": 3, "items": { "type": "string", "maxLength": 8 }, + "position": 10 + } + }) + } + + /// Four bytes a character, the most UTF-8 takes. + fn wide(characters: usize) -> String { + "\u{1F600}".repeat(characters) + } + + /// Every property of [`every_bounded_kind`] at its largest value. + fn largest_values() -> BTreeMap { + BTreeMap::from([ + ("small".to_string(), Value::U64(255)), + ("large".to_string(), Value::I64(i64::MAX)), + ("label".to_string(), Value::Text(wide(10))), + ("short".to_string(), Value::Text("a".repeat(20))), + // Four characters, ten bytes: the byte bound is the lower one. + ("both".to_string(), Value::Text(format!("{}ab", wide(2)))), + ("key".to_string(), Value::Bytes(vec![1; 33])), + ("blob".to_string(), Value::Bytes(vec![2; 300])), + ("flag".to_string(), Value::Bool(true)), + ("who".to_string(), Value::Identifier([3; 32])), + ( + "meta".to_string(), + Value::Map(vec![ + (Value::Text("a".to_string()), Value::U64(65535)), + (Value::Text("b".to_string()), Value::Text(wide(5))), + ]), + ), + ( + "tags".to_string(), + Value::Array(vec![Value::Text(wide(8)); 3]), + ), + ]) + } + + /// The largest payload is what a document of the type holding every property at its largest + /// serializes to after its system fields: the format version (1), the contract version stamp + /// (1), `$id` (32), `$ownerId` (32) and the system field flags (2), 68 bytes for a private + /// type, which keeps no revision, times or creator. + #[test] + fn should_size_the_largest_payload_as_a_document_serializes_it() { + let platform_version = PlatformVersion::latest(); + let contract = contract(1000, every_bounded_kind(), json!(["small", "large", "key"])); + let secret = contract + .document_type_for_name("secret") + .expect("the secret type"); + + let largest = largest_private_document_payload_size(secret, platform_version) + .expect("every property is bounded"); + // 1 + 8 + (1 + 1 + 40) + (1 + 1 + 20) + (1 + 1 + 10) + 33 + (1 + 2 + 300) + (1 + 1) + // + (1 + 32) + (1 + 1 + 2 + 1 + 1 + 20) + (1 + 1 + 3 * (1 + 32)) + assert_eq!(largest, 583); + + let document = DocumentV0 { + id: Identifier::from([4; 32]), + owner_id: Identifier::from([5; 32]), + properties: largest_values(), + ..Default::default() + }; + let serialized = document + .serialize(secret, &contract, platform_version) + .expect("the document serializes"); + assert_eq!(&serialized[..2], &[3, 0]); + assert_eq!(&serialized[2..34], &[4; 32]); + assert_eq!(&serialized[34..66], &[5; 32]); + assert_eq!(&serialized[66..68], &[0, 0]); + assert_eq!(serialized.len() - 68, largest as usize); + } + + /// The smallest entry size is the largest payload and the envelope's 299 bytes; a type of that + /// size passes, one byte less is refused with both numbers, and a public type always passes. + #[test] + fn should_refuse_a_private_type_whose_entries_cannot_hold_its_largest_payload() { + let platform_version = PlatformVersion::latest(); + assert_eq!(PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES, 299); + let required = json!(["small", "large", "key"]); + let minimum = minimum_private_document_entry_size( + contract(1000, every_bounded_kind(), required.clone()) + .document_type_for_name("secret") + .expect("the secret type"), + platform_version, + ) + .expect("every property is bounded"); + assert_eq!(minimum, 583 + 299); + + let fitting = contract(minimum, every_bounded_kind(), required.clone()); + for name in ["secret", "note"] { + validate_private_document_entry_size( + fitting.document_type_for_name(name).expect("the type"), + platform_version, + ) + .unwrap_or_else(|error| panic!("{name} passes: {error}")); + } + + let short = contract(minimum - 1, every_bounded_kind(), required); + match validate_private_document_entry_size( + short.document_type_for_name("secret").expect("the type"), + platform_version, + ) { + Err(ProtocolError::PrivateDocumentEntrySizeTooSmall { + document_type_name, + entry_size, + minimum_entry_size, + }) => { + assert_eq!(document_type_name, "secret"); + assert_eq!(entry_size, minimum - 1); + assert_eq!(minimum_entry_size, minimum); + } + other => panic!("expected the entry size refusal, got {other:?}"), + } + } + + /// A string without `maxLength` or `maxBytes`, or a byte array without `maxItems`, sets no + /// largest payload, so no entry size holds every one. + #[test] + fn should_refuse_a_private_type_with_an_unbounded_property() { + for property in [ + json!({ "type": "string", "position": 1 }), + json!({ "type": "array", "byteArray": true, "position": 1 }), + ] { + let contract = contract( + 4096, + json!({ + "small": { "type": "integer", "minimum": 0, "maximum": 255, "position": 0 }, + "open": property + }), + json!(["small"]), + ); + match validate_private_document_entry_size( + contract.document_type_for_name("secret").expect("the type"), + PlatformVersion::latest(), + ) { + Err(ProtocolError::UnboundedPrivateDocumentProperty { + document_type_name, + property_name, + }) => { + assert_eq!(document_type_name, "secret"); + assert_eq!(property_name, "open"); + } + other => panic!("expected the unbounded refusal, got {other:?}"), + } + } + } + + /// A `Date` property carries a marker byte when it is optional; its largest size counts it, + /// as its encoding writes it. + #[test] + fn should_size_a_date_with_its_optional_marker() { + let platform_version = PlatformVersion::latest(); + for required in [true, false] { + assert_eq!( + DocumentPropertyType::Date + .max_encoded_value_size(required, platform_version) + .expect("sized"), + Some( + DocumentPropertyType::Date + .encode_value_ref_with_size(&Value::Float(1.5), required) + .expect("encodes") + .len() as u32 + ), + "required: {required}" + ); + } + } +} diff --git a/packages/rs-dpp/src/data_contract/document_type/property/mod.rs b/packages/rs-dpp/src/data_contract/document_type/property/mod.rs index e7b17533de8..c9e2567d2e7 100644 --- a/packages/rs-dpp/src/data_contract/document_type/property/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/property/mod.rs @@ -3050,6 +3050,80 @@ impl DocumentPropertyType { } } + /// The most bytes [`Self::encode_value_ref_with_size`] writes for a value of this type, `None` + /// when the type sets no largest value: a string with neither `maxLength` nor `maxBytes`, a byte + /// array without `maxItems`, or an untyped array. `required` is the flag the encoding is called + /// with (an optional `Date` carries a marker byte); the presence byte a document writes before + /// an optional property is not counted. + /// + /// Each arm is the largest output of the matching arm of the encoder, which this must follow + /// when that changes. + pub fn max_encoded_value_size( + &self, + required: bool, + platform_version: &PlatformVersion, + ) -> Result, ProtocolError> { + // A varint length, then that many bytes. + let length_prefixed = |bytes: u32| bytes.saturating_add(bytes.required_space() as u32); + Ok(match self { + DocumentPropertyType::String(sizes) => { + // A character takes at most 4 bytes in UTF-8. + let max_bytes = match (sizes.max_length, sizes.max_bytes) { + (max_length, Some(max_bytes)) => max_length + .map_or(u32::from(max_bytes), |length| { + (u32::from(length) * 4).min(u32::from(max_bytes)) + }), + (Some(max_length), None) => u32::from(max_length) * 4, + (None, None) => return Ok(None), + }; + Some(length_prefixed(max_bytes)) + } + DocumentPropertyType::Date => Some(if required { 8 } else { 9 }), + DocumentPropertyType::U128 | DocumentPropertyType::I128 => Some(16), + DocumentPropertyType::U64 | DocumentPropertyType::I64 | DocumentPropertyType::F64 => { + Some(8) + } + DocumentPropertyType::U32 + | DocumentPropertyType::I32 + | DocumentPropertyType::KeyIdWithReference(_) => Some(4), + DocumentPropertyType::U16 | DocumentPropertyType::I16 => Some(2), + DocumentPropertyType::U8 | DocumentPropertyType::I8 | DocumentPropertyType::Boolean => { + Some(1) + } + DocumentPropertyType::ByteArray(sizes) => match (sizes.min_size, sizes.max_size) { + (Some(min), Some(max)) if min == max => Some(u32::from(max)), + (_, Some(max)) => Some(length_prefixed(u32::from(max))), + (_, None) => None, + }, + DocumentPropertyType::Identifier | DocumentPropertyType::IdentifierWithReference(_) => { + Some(32) + } + DocumentPropertyType::Object(inner_fields) => { + let mut inner = 0u32; + for field in inner_fields.values() { + let Some(field_size) = field + .property_type + .max_encoded_value_size(field.required, platform_version)? + else { + return Ok(None); + }; + inner = inner + .saturating_add(field_size) + .saturating_add(u32::from(!field.required)); + } + Some(length_prefixed(inner)) + } + DocumentPropertyType::TypedArray(typed_array) => { + // It saturates at `u16::MAX`, which an unbounded element reports. + match typed_array.max_encoded_size(platform_version)? { + u16::MAX => None, + size => Some(u32::from(size)), + } + } + DocumentPropertyType::Array(_) | DocumentPropertyType::VariableTypeArray(_) => None, + }) + } + pub fn encode_value_ref_with_size( &self, value: &Value, diff --git a/packages/rs-dpp/src/errors/protocol_error.rs b/packages/rs-dpp/src/errors/protocol_error.rs index 1cc5106db22..4bf6d504d64 100644 --- a/packages/rs-dpp/src/errors/protocol_error.rs +++ b/packages/rs-dpp/src/errors/protocol_error.rs @@ -164,6 +164,29 @@ pub enum ProtocolError { #[error("Shielded transaction build error: {0}")] ShieldedBuildError(String), + /// A private document type's `entrySize` is smaller than its largest payload needs in the + /// standard private document envelope. The chain registers such a type, but clients refuse to. + #[error( + "private document type {document_type_name} takes entries of {entry_size} bytes, fewer than \ + the {minimum_entry_size} its largest payload needs in the private document envelope" + )] + PrivateDocumentEntrySizeTooSmall { + document_type_name: String, + entry_size: u32, + minimum_entry_size: u32, + }, + + /// A property of a private document type sets no largest value, so no entry size holds every + /// payload of the type. + #[error( + "property {property_name} of private document type {document_type_name} sets no largest \ + value, so no entry size holds every payload" + )] + UnboundedPrivateDocumentProperty { + document_type_name: String, + property_name: String, + }, + #[error("Not supported Error: {0}")] NotSupported(String), diff --git a/packages/rs-sdk/src/platform/transition/put_contract.rs b/packages/rs-sdk/src/platform/transition/put_contract.rs index 19e0ec51182..225df46c531 100644 --- a/packages/rs-sdk/src/platform/transition/put_contract.rs +++ b/packages/rs-sdk/src/platform/transition/put_contract.rs @@ -4,6 +4,7 @@ use crate::{Error, Sdk}; use crate::platform::transition::put_settings::PutSettings; use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::document_type::validate_private_document_entry_size; use dpp::data_contract::DataContract; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; @@ -11,11 +12,26 @@ use dpp::identity::{IdentityPublicKey, PartialIdentity}; use dpp::state_transition::data_contract_create_transition::methods::DataContractCreateTransitionMethodsV0; use dpp::state_transition::data_contract_create_transition::DataContractCreateTransition; use dpp::state_transition::StateTransition; +use dpp::version::PlatformVersion; use super::broadcast::BroadcastStateTransition; use super::validation::ensure_valid_state_transition_structure; use super::waitable::Waitable; +/// Refuses `data_contract` when one of its private document types takes entries too small for +/// its largest payload in the standard private document envelope, or has a property with no +/// largest value. Platform registers such a type, since it never reads an entry, but no full +/// entry fits it and its entry size can never change, so the SDK refuses it before signing. +pub fn ensure_private_document_entries_fit( + data_contract: &DataContract, + platform_version: &PlatformVersion, +) -> Result<(), Error> { + for document_type in data_contract.document_types().values() { + validate_private_document_entry_size(document_type.as_ref(), platform_version)?; + } + Ok(()) +} + #[async_trait::async_trait] /// A trait for putting a contract to platform pub trait PutContract>: Waitable { @@ -48,6 +64,8 @@ impl> PutContract for DataContract { signer: &S, settings: Option, ) -> Result { + ensure_private_document_entries_fit(self, sdk.version())?; + let new_identity_nonce = sdk .get_identity_nonce(self.owner_id(), true, settings) .await?; @@ -93,3 +111,67 @@ impl> PutContract for DataContract { Self::wait_for_response(sdk, state_transition, settings).await } } + +#[cfg(test)] +mod tests { + use super::*; + use dpp::data_contract::conversion::value::v0::DataContractValueConversionMethodsV0; + use dpp::platform_value::string_encoding::Encoding; + use dpp::platform_value::{platform_value, Identifier}; + use dpp::ProtocolError; + + /// A contract with the private type `request` of `entry_size`-byte entries, whose largest + /// payload is 8 + 69 = 77 bytes, so it needs 77 + 299 = 376. + fn contract(entry_size: u32) -> DataContract { + let id = Identifier::from([7; 32]).to_string(Encoding::Base58); + let owner_id = Identifier::from([8; 32]).to_string(Encoding::Base58); + DataContract::from_value( + platform_value!({ + "$formatVersion": "1", + "id": id, + "ownerId": owner_id, + "version": 1, + "documentSchemas": { + "request": { + "type": "object", + "private": { "entrySize": entry_size }, + "documentsMutable": false, + "canBeDeleted": false, + "properties": { + "reference": { "type": "integer", "position": 0 }, + "key": { + "type": "array", "byteArray": true, + "minItems": 69, "maxItems": 69, "position": 1 + } + }, + "required": ["reference", "key"], + "additionalProperties": false + } + } + }), + true, + PlatformVersion::latest(), + ) + .expect("the contract registers") + } + + #[test] + fn should_refuse_a_contract_whose_private_entries_cannot_hold_their_payload() { + let platform_version = PlatformVersion::latest(); + ensure_private_document_entries_fit(&contract(376), platform_version) + .expect("376 bytes hold the largest payload"); + match ensure_private_document_entries_fit(&contract(375), platform_version) { + Err(Error::Protocol(ProtocolError::PrivateDocumentEntrySizeTooSmall { + document_type_name, + entry_size, + minimum_entry_size, + })) => { + assert_eq!( + (document_type_name.as_str(), entry_size, minimum_entry_size), + ("request", 375, 376) + ); + } + other => panic!("expected the entry size refusal, got {other:?}"), + } + } +} diff --git a/packages/wasm-sdk/src/state_transitions/contract.rs b/packages/wasm-sdk/src/state_transitions/contract.rs index 8e66b8220e9..89329140206 100644 --- a/packages/wasm-sdk/src/state_transitions/contract.rs +++ b/packages/wasm-sdk/src/state_transitions/contract.rs @@ -23,7 +23,9 @@ use dash_sdk::dpp::state_transition::data_contract_update_transition::DataContra use dash_sdk::dpp::ProtocolError; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::contract_user_moderation::ModerateContractUser; -use dash_sdk::platform::transition::put_contract::PutContract; +use dash_sdk::platform::transition::put_contract::{ + ensure_private_document_entries_fit, PutContract, +}; use dash_sdk::platform::transition::put_settings::PutSettings; use std::collections::BTreeMap; use wasm_bindgen::prelude::*; @@ -223,6 +225,10 @@ impl WasmSdk { let contract_id: Identifier = updated_contract.id(); let owner_id: Identifier = updated_contract.owner_id(); + // A private document type the update adds takes entries that must hold its largest + // payload, as on create. + ensure_private_document_entries_fit(&updated_contract, self.inner_sdk().version())?; + // Get identity contract nonce let identity_contract_nonce = self .inner_sdk() From 63e31599bde16647143caace3c2231076f5e2f3f Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sun, 8 Nov 2026 01:21:30 +0700 Subject: [PATCH 2/4] fix(sdk): check only the private types a contract update adds or changes, and size typed arrays exactly - A contract update is checked against the contract as Platform holds it: a private type it already holds with the same properties is skipped, so an update is never refused for a type registered before it. rs-sdk's ensure_private_document_entries_fit takes the stored contract, and the new ensure_private_document_entries_fit_on_update fetches it, only when the update declares a private type; wasm-sdk's contractUpdate calls that. - A typed array is sized from its element's own largest size instead of TypedArrayProperty::max_encoded_size, which saturates at u16::MAX: a bounded array larger than that keeps its size and is refused as too small, not as unbounded, and one of maxItems 0 takes its 1 byte whatever its element type. - The size functions take no platform version: the encoding they follow takes none. Co-Authored-By: Claude Opus 5.5 --- .../document_type/private_document.rs | 82 ++++++++++---- .../document_type/property/mod.rs | 37 +++---- .../src/platform/transition/put_contract.rs | 100 +++++++++++++++--- .../src/state_transitions/contract.rs | 8 +- 4 files changed, 165 insertions(+), 62 deletions(-) diff --git a/packages/rs-dpp/src/data_contract/document_type/private_document.rs b/packages/rs-dpp/src/data_contract/document_type/private_document.rs index b22f0fcb6de..3342f427101 100644 --- a/packages/rs-dpp/src/data_contract/document_type/private_document.rs +++ b/packages/rs-dpp/src/data_contract/document_type/private_document.rs @@ -13,7 +13,6 @@ use crate::data_contract::document_type::accessors::{ }; use crate::data_contract::document_type::{property_names, DocumentTypeRef}; use crate::ProtocolError; -use platform_version::version::PlatformVersion; use std::num::NonZeroU32; /// What a document type's `private` keyword declares (`{ "entrySize": n }`). Built only by the @@ -90,7 +89,6 @@ pub const PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES: u32 = /// then no entry size holds every payload. pub fn largest_private_document_payload_size( document_type: DocumentTypeRef, - platform_version: &PlatformVersion, ) -> Result { let mut size = 0u32; for (property_name, property) in document_type.properties() { @@ -99,7 +97,7 @@ pub fn largest_private_document_payload_size( let presence_byte = !property.required || property.transient; let Some(value_size) = property .property_type - .max_encoded_value_size(property.required, platform_version)? + .max_encoded_value_size(property.required) else { return Err(ProtocolError::UnboundedPrivateDocumentProperty { document_type_name: document_type.name().clone(), @@ -118,12 +116,9 @@ pub fn largest_private_document_payload_size( /// [`PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES`]. pub fn minimum_private_document_entry_size( document_type: DocumentTypeRef, - platform_version: &PlatformVersion, ) -> Result { - Ok( - largest_private_document_payload_size(document_type, platform_version)? - .saturating_add(PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES), - ) + Ok(largest_private_document_payload_size(document_type)? + .saturating_add(PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES)) } /// Refuses a private document type whose `entrySize` cannot hold its largest payload in the @@ -133,12 +128,11 @@ pub fn minimum_private_document_entry_size( /// that is not private passes. pub fn validate_private_document_entry_size( document_type: DocumentTypeRef, - platform_version: &PlatformVersion, ) -> Result<(), ProtocolError> { let Some(private_document) = document_type.private_document() else { return Ok(()); }; - let minimum_entry_size = minimum_private_document_entry_size(document_type, platform_version)?; + let minimum_entry_size = minimum_private_document_entry_size(document_type)?; if private_document.entry_size() < minimum_entry_size { return Err(ProtocolError::PrivateDocumentEntrySizeTooSmall { document_type_name: document_type.name().clone(), @@ -160,6 +154,7 @@ mod tests { use crate::document::DocumentV0; use platform_value::string_encoding::Encoding; use platform_value::{Identifier, Value}; + use platform_version::version::PlatformVersion; use serde_json::json; use std::collections::BTreeMap; @@ -281,8 +276,8 @@ mod tests { .document_type_for_name("secret") .expect("the secret type"); - let largest = largest_private_document_payload_size(secret, platform_version) - .expect("every property is bounded"); + let largest = + largest_private_document_payload_size(secret).expect("every property is bounded"); // 1 + 8 + (1 + 1 + 40) + (1 + 1 + 20) + (1 + 1 + 10) + 33 + (1 + 2 + 300) + (1 + 1) // + (1 + 32) + (1 + 1 + 2 + 1 + 1 + 20) + (1 + 1 + 3 * (1 + 32)) assert_eq!(largest, 583); @@ -307,14 +302,12 @@ mod tests { /// size passes, one byte less is refused with both numbers, and a public type always passes. #[test] fn should_refuse_a_private_type_whose_entries_cannot_hold_its_largest_payload() { - let platform_version = PlatformVersion::latest(); assert_eq!(PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES, 299); let required = json!(["small", "large", "key"]); let minimum = minimum_private_document_entry_size( contract(1000, every_bounded_kind(), required.clone()) .document_type_for_name("secret") .expect("the secret type"), - platform_version, ) .expect("every property is bounded"); assert_eq!(minimum, 583 + 299); @@ -323,7 +316,6 @@ mod tests { for name in ["secret", "note"] { validate_private_document_entry_size( fitting.document_type_for_name(name).expect("the type"), - platform_version, ) .unwrap_or_else(|error| panic!("{name} passes: {error}")); } @@ -331,7 +323,6 @@ mod tests { let short = contract(minimum - 1, every_bounded_kind(), required); match validate_private_document_entry_size( short.document_type_for_name("secret").expect("the type"), - platform_version, ) { Err(ProtocolError::PrivateDocumentEntrySizeTooSmall { document_type_name, @@ -364,7 +355,6 @@ mod tests { ); match validate_private_document_entry_size( contract.document_type_for_name("secret").expect("the type"), - PlatformVersion::latest(), ) { Err(ProtocolError::UnboundedPrivateDocumentProperty { document_type_name, @@ -378,16 +368,66 @@ mod tests { } } + /// A typed array is its varint count and that many of its largest element, as its encoder + /// writes it: one of no element takes 1 byte whatever its element type, and one larger than + /// `u16::MAX` bytes keeps its exact size. + #[test] + fn should_size_a_typed_array_as_its_encoding_takes_it() { + use crate::data_contract::document_type::property::array::TypedArrayProperty; + use crate::data_contract::document_type::{ByteArrayPropertySizes, StringPropertySizes}; + + let typed_array = |item_type: DocumentPropertyType, max_items: u16| { + DocumentPropertyType::TypedArray(TypedArrayProperty { + item_type: Box::new(item_type), + item_constraints: Default::default(), + min_items: None, + max_items, + unique_items: false, + }) + }; + let unbounded_string = DocumentPropertyType::String(StringPropertySizes { + min_length: None, + max_length: None, + max_bytes: None, + }); + let hundred_bytes = DocumentPropertyType::ByteArray(ByteArrayPropertySizes { + min_size: Some(100), + max_size: Some(100), + }); + + for (array, value) in [ + ( + typed_array(unbounded_string.clone(), 0), + Value::Array(vec![]), + ), + ( + typed_array(hundred_bytes, 1000), + Value::Array(vec![Value::Bytes(vec![1; 100]); 1000]), + ), + ] { + assert_eq!( + array.max_encoded_value_size(true), + Some( + array + .encode_value_ref_with_size(&value, true) + .expect("encodes") + .len() as u32 + ) + ); + } + assert_eq!( + typed_array(unbounded_string, 1).max_encoded_value_size(true), + None + ); + } + /// A `Date` property carries a marker byte when it is optional; its largest size counts it, /// as its encoding writes it. #[test] fn should_size_a_date_with_its_optional_marker() { - let platform_version = PlatformVersion::latest(); for required in [true, false] { assert_eq!( - DocumentPropertyType::Date - .max_encoded_value_size(required, platform_version) - .expect("sized"), + DocumentPropertyType::Date.max_encoded_value_size(required), Some( DocumentPropertyType::Date .encode_value_ref_with_size(&Value::Float(1.5), required) diff --git a/packages/rs-dpp/src/data_contract/document_type/property/mod.rs b/packages/rs-dpp/src/data_contract/document_type/property/mod.rs index c9e2567d2e7..a1f37c863f9 100644 --- a/packages/rs-dpp/src/data_contract/document_type/property/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/property/mod.rs @@ -3052,20 +3052,17 @@ impl DocumentPropertyType { /// The most bytes [`Self::encode_value_ref_with_size`] writes for a value of this type, `None` /// when the type sets no largest value: a string with neither `maxLength` nor `maxBytes`, a byte - /// array without `maxItems`, or an untyped array. `required` is the flag the encoding is called + /// array without `maxItems`, an untyped array, or a typed array that may hold an element of + /// such a type. `required` is the flag the encoding is called /// with (an optional `Date` carries a marker byte); the presence byte a document writes before /// an optional property is not counted. /// /// Each arm is the largest output of the matching arm of the encoder, which this must follow /// when that changes. - pub fn max_encoded_value_size( - &self, - required: bool, - platform_version: &PlatformVersion, - ) -> Result, ProtocolError> { + pub fn max_encoded_value_size(&self, required: bool) -> Option { // A varint length, then that many bytes. let length_prefixed = |bytes: u32| bytes.saturating_add(bytes.required_space() as u32); - Ok(match self { + match self { DocumentPropertyType::String(sizes) => { // A character takes at most 4 bytes in UTF-8. let max_bytes = match (sizes.max_length, sizes.max_bytes) { @@ -3074,7 +3071,7 @@ impl DocumentPropertyType { (u32::from(length) * 4).min(u32::from(max_bytes)) }), (Some(max_length), None) => u32::from(max_length) * 4, - (None, None) => return Ok(None), + (None, None) => return None, }; Some(length_prefixed(max_bytes)) } @@ -3101,12 +3098,7 @@ impl DocumentPropertyType { DocumentPropertyType::Object(inner_fields) => { let mut inner = 0u32; for field in inner_fields.values() { - let Some(field_size) = field - .property_type - .max_encoded_value_size(field.required, platform_version)? - else { - return Ok(None); - }; + let field_size = field.property_type.max_encoded_value_size(field.required)?; inner = inner .saturating_add(field_size) .saturating_add(u32::from(!field.required)); @@ -3114,14 +3106,19 @@ impl DocumentPropertyType { Some(length_prefixed(inner)) } DocumentPropertyType::TypedArray(typed_array) => { - // It saturates at `u16::MAX`, which an unbounded element reports. - match typed_array.max_encoded_size(platform_version)? { - u16::MAX => None, - size => Some(u32::from(size)), - } + // A varint count, then each element encoded as a required property of its type. + // Counted here rather than by `max_encoded_size`, which saturates at `u16::MAX`. + let max_items = u32::from(typed_array.max_items); + let elements = if max_items == 0 { + 0 + } else { + let element = typed_array.item_type.max_encoded_value_size(true)?; + max_items.saturating_mul(element) + }; + Some(elements.saturating_add(max_items.required_space() as u32)) } DocumentPropertyType::Array(_) | DocumentPropertyType::VariableTypeArray(_) => None, - }) + } } pub fn encode_value_ref_with_size( diff --git a/packages/rs-sdk/src/platform/transition/put_contract.rs b/packages/rs-sdk/src/platform/transition/put_contract.rs index 225df46c531..f654469ee73 100644 --- a/packages/rs-sdk/src/platform/transition/put_contract.rs +++ b/packages/rs-sdk/src/platform/transition/put_contract.rs @@ -3,7 +3,9 @@ use std::collections::BTreeMap; use crate::{Error, Sdk}; use crate::platform::transition::put_settings::PutSettings; +use crate::platform::Fetch; use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters}; use dpp::data_contract::document_type::validate_private_document_entry_size; use dpp::data_contract::DataContract; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -12,7 +14,6 @@ use dpp::identity::{IdentityPublicKey, PartialIdentity}; use dpp::state_transition::data_contract_create_transition::methods::DataContractCreateTransitionMethodsV0; use dpp::state_transition::data_contract_create_transition::DataContractCreateTransition; use dpp::state_transition::StateTransition; -use dpp::version::PlatformVersion; use super::broadcast::BroadcastStateTransition; use super::validation::ensure_valid_state_transition_structure; @@ -22,16 +23,43 @@ use super::waitable::Waitable; /// its largest payload in the standard private document envelope, or has a property with no /// largest value. Platform registers such a type, since it never reads an entry, but no full /// entry fits it and its entry size can never change, so the SDK refuses it before signing. +/// +/// For an update, `stored_contract` is the contract as Platform holds it: a type it already +/// holds with the same properties is not checked, since the update does not change what its +/// entries carry, so an update is never refused for a type registered before it. pub fn ensure_private_document_entries_fit( data_contract: &DataContract, - platform_version: &PlatformVersion, + stored_contract: Option<&DataContract>, ) -> Result<(), Error> { - for document_type in data_contract.document_types().values() { - validate_private_document_entry_size(document_type.as_ref(), platform_version)?; + for (name, document_type) in data_contract.document_types() { + let unchanged = stored_contract + .and_then(|stored| stored.document_types().get(name)) + .is_some_and(|stored_type| stored_type.properties() == document_type.properties()); + if !unchanged { + validate_private_document_entry_size(document_type.as_ref())?; + } } Ok(()) } +/// [`ensure_private_document_entries_fit`] for an update of `data_contract`, against the contract +/// as Platform holds it. It fetches that only when `data_contract` declares a private document +/// type, the one case with anything to check. +pub async fn ensure_private_document_entries_fit_on_update( + sdk: &Sdk, + data_contract: &DataContract, +) -> Result<(), Error> { + let declares_private_types = data_contract + .document_types() + .values() + .any(|document_type| document_type.private_document().is_some()); + if !declares_private_types { + return Ok(()); + } + let stored_contract = DataContract::fetch(sdk, data_contract.id()).await?; + ensure_private_document_entries_fit(data_contract, stored_contract.as_ref()) +} + #[async_trait::async_trait] /// A trait for putting a contract to platform pub trait PutContract>: Waitable { @@ -64,7 +92,7 @@ impl> PutContract for DataContract { signer: &S, settings: Option, ) -> Result { - ensure_private_document_entries_fit(self, sdk.version())?; + ensure_private_document_entries_fit(self, None)?; let new_identity_nonce = sdk .get_identity_nonce(self.owner_id(), true, settings) @@ -118,13 +146,30 @@ mod tests { use dpp::data_contract::conversion::value::v0::DataContractValueConversionMethodsV0; use dpp::platform_value::string_encoding::Encoding; use dpp::platform_value::{platform_value, Identifier}; + use dpp::version::PlatformVersion; use dpp::ProtocolError; /// A contract with the private type `request` of `entry_size`-byte entries, whose largest - /// payload is 8 + 69 = 77 bytes, so it needs 77 + 299 = 376. - fn contract(entry_size: u32) -> DataContract { + /// payload is 8 + 69 = 77 bytes, so it needs 77 + 299 = 376; with `label`, an optional string + /// of at most 20 bytes, 22 more. + fn contract(entry_size: u32, label: bool) -> DataContract { let id = Identifier::from([7; 32]).to_string(Encoding::Base58); let owner_id = Identifier::from([8; 32]).to_string(Encoding::Base58); + let mut properties = platform_value!({ + "reference": { "type": "integer", "position": 0 }, + "key": { + "type": "array", "byteArray": true, + "minItems": 69, "maxItems": 69, "position": 1 + } + }); + if label { + properties + .set_value( + "label", + platform_value!({ "type": "string", "maxBytes": 20, "position": 2 }), + ) + .expect("a map"); + } DataContract::from_value( platform_value!({ "$formatVersion": "1", @@ -137,13 +182,7 @@ mod tests { "private": { "entrySize": entry_size }, "documentsMutable": false, "canBeDeleted": false, - "properties": { - "reference": { "type": "integer", "position": 0 }, - "key": { - "type": "array", "byteArray": true, - "minItems": 69, "maxItems": 69, "position": 1 - } - }, + "properties": properties, "required": ["reference", "key"], "additionalProperties": false } @@ -157,10 +196,9 @@ mod tests { #[test] fn should_refuse_a_contract_whose_private_entries_cannot_hold_their_payload() { - let platform_version = PlatformVersion::latest(); - ensure_private_document_entries_fit(&contract(376), platform_version) + ensure_private_document_entries_fit(&contract(376, false), None) .expect("376 bytes hold the largest payload"); - match ensure_private_document_entries_fit(&contract(375), platform_version) { + match ensure_private_document_entries_fit(&contract(375, false), None) { Err(Error::Protocol(ProtocolError::PrivateDocumentEntrySizeTooSmall { document_type_name, entry_size, @@ -174,4 +212,32 @@ mod tests { other => panic!("expected the entry size refusal, got {other:?}"), } } + + /// An update checks the private types it adds or whose properties it changes, and leaves a + /// type Platform already holds unchanged, even one too small, since the update does not + /// change what its entries carry. + #[test] + fn should_check_only_the_private_types_an_update_adds_or_changes() { + let stored = contract(375, false); + ensure_private_document_entries_fit(&contract(375, false), Some(&stored)) + .expect("an unchanged type is not checked"); + assert!(matches!( + ensure_private_document_entries_fit(&contract(375, true), Some(&stored),), + Err(Error::Protocol( + ProtocolError::PrivateDocumentEntrySizeTooSmall { + minimum_entry_size: 398, + .. + } + )) + )); + // A type the stored contract does not hold is new, and checked. + let mut without_the_type = contract(4096, false); + without_the_type.document_types_mut().clear(); + assert!(matches!( + ensure_private_document_entries_fit(&contract(375, false), Some(&without_the_type),), + Err(Error::Protocol( + ProtocolError::PrivateDocumentEntrySizeTooSmall { .. } + )) + )); + } } diff --git a/packages/wasm-sdk/src/state_transitions/contract.rs b/packages/wasm-sdk/src/state_transitions/contract.rs index 89329140206..0ff48503b91 100644 --- a/packages/wasm-sdk/src/state_transitions/contract.rs +++ b/packages/wasm-sdk/src/state_transitions/contract.rs @@ -24,7 +24,7 @@ use dash_sdk::dpp::ProtocolError; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::contract_user_moderation::ModerateContractUser; use dash_sdk::platform::transition::put_contract::{ - ensure_private_document_entries_fit, PutContract, + ensure_private_document_entries_fit_on_update, PutContract, }; use dash_sdk::platform::transition::put_settings::PutSettings; use std::collections::BTreeMap; @@ -225,9 +225,9 @@ impl WasmSdk { let contract_id: Identifier = updated_contract.id(); let owner_id: Identifier = updated_contract.owner_id(); - // A private document type the update adds takes entries that must hold its largest - // payload, as on create. - ensure_private_document_entries_fit(&updated_contract, self.inner_sdk().version())?; + // A private document type the update adds, or whose properties it changes, takes entries + // that must hold its largest payload, as on create. + ensure_private_document_entries_fit_on_update(self.inner_sdk(), &updated_contract).await?; // Get identity contract nonce let identity_contract_nonce = self From e3e77076cb1006975724358ffe50ba54fac8ce91 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sun, 8 Nov 2026 02:52:56 +0700 Subject: [PATCH 3/4] fix(sdk): check private entry sizes on native wallet contract updates too - platform-wallet's update_data_contract_with_signer runs ensure_private_document_entries_fit against the contract it already fetched, before fetching the nonce, so a native update adding an undersized private type is refused as a wasm-sdk update and a create are. - The largest payload is documented as an upper bound read from the property types alone: a schema's enum, or a maxProperties keeping optional properties apart, can only lower the real one and is not counted. The book says so too. - rs-sdk tests ensure_private_document_entries_fit_on_update with the mock SDK: an unchanged undersized type passes against the fetched contract, a changed one is refused, every type is checked when Platform holds no such contract, a failed fetch stops the update, and a contract with no private type fetches nothing. Co-Authored-By: Claude Opus 5.5 --- book/src/contract-keywords.md | 2 +- .../document_type/private_document.rs | 22 +++-- .../src/wallet/identity/network/contract.rs | 10 ++- .../src/platform/transition/put_contract.rs | 84 +++++++++++++++++++ 4 files changed, 109 insertions(+), 9 deletions(-) diff --git a/book/src/contract-keywords.md b/book/src/contract-keywords.md index d25620aee1d..1d70ac185fd 100644 --- a/book/src/contract-keywords.md +++ b/book/src/contract-keywords.md @@ -146,7 +146,7 @@ Every key a contract can write, grouped by where it goes. **Since** is the proto | `rangeCountable`, `rangeSummable`, `rangeAverageable` | boolean | Provable counts, sums or averages over ranges of document ids. | 12 | [Document type range keys](contract-keywords/aggregates.md#document-type-rangecountable-rangesummable-rangeaverageable) | | `indexOnly` | boolean | Documents are never stored whole: the index entries are the rows. | 14 | [indexOnly](contract-keywords/index-only.md#indexonly) · [internals](drive/index-only-document-types.md) | | `entryPayload` | array of 1 to 16 names | On an index-only type, properties carried in each entry's value instead of a key. | 14 | [entryPayload](contract-keywords/index-only.md#entrypayload) | -| `private` | object: `entrySize`, 1 to 4096 | A private type: its documents are encrypted entries of `entrySize` bytes, which the chain never reads. Its `properties` describe the plaintext. It declares only `type`, `properties`, `required`, `additionalProperties`, `minProperties`, `maxProperties`, `dependentRequired`, `$comment`, `description`, the two bounded key keys, and `documentsMutable`, `canBeDeleted` and `documentsKeepHistory` as `false`, each at most once; neither its properties nor `required` nor `dependentRequired` name a system field, no property at any depth declares `refersTo`, `distinctFrom`, `generatedFrom`, `encryptedFor` or `requiredSince`, and the contract's elected moderators may not moderate it. No reference, `countOf` or `sumOf` may name it, an update cannot change it, and a Batch refuses every document transition on it (`DocumentTypePrivateError`, 10425). Entries are appended only by `PrivateDocumentCreateFromShieldedPool` (type 29), from 1 to 16 distinct entries of exactly `entrySize` bytes, paid from the credit shielded pool. The chain does not compare `entrySize` with the properties; the SDK refuses to register a private type whose `entrySize` is below its largest payload plus the private document envelope's 299 bytes, or whose properties are not all bounded (`minimum_private_document_entry_size` in dpp). | 15 | | +| `private` | object: `entrySize`, 1 to 4096 | A private type: its documents are encrypted entries of `entrySize` bytes, which the chain never reads. Its `properties` describe the plaintext. It declares only `type`, `properties`, `required`, `additionalProperties`, `minProperties`, `maxProperties`, `dependentRequired`, `$comment`, `description`, the two bounded key keys, and `documentsMutable`, `canBeDeleted` and `documentsKeepHistory` as `false`, each at most once; neither its properties nor `required` nor `dependentRequired` name a system field, no property at any depth declares `refersTo`, `distinctFrom`, `generatedFrom`, `encryptedFor` or `requiredSince`, and the contract's elected moderators may not moderate it. No reference, `countOf` or `sumOf` may name it, an update cannot change it, and a Batch refuses every document transition on it (`DocumentTypePrivateError`, 10425). Entries are appended only by `PrivateDocumentCreateFromShieldedPool` (type 29), from 1 to 16 distinct entries of exactly `entrySize` bytes, paid from the credit shielded pool. The chain does not compare `entrySize` with the properties; the SDK refuses to register a private type whose `entrySize` is below its largest payload plus the private document envelope's 299 bytes, or whose properties are not all bounded (`minimum_private_document_entry_size` in dpp). The largest payload is read from the property types alone: an `enum` or a `maxProperties` that would make it smaller is not counted. | 15 | | ### Property diff --git a/packages/rs-dpp/src/data_contract/document_type/private_document.rs b/packages/rs-dpp/src/data_contract/document_type/private_document.rs index 3342f427101..76fc87dec72 100644 --- a/packages/rs-dpp/src/data_contract/document_type/private_document.rs +++ b/packages/rs-dpp/src/data_contract/document_type/private_document.rs @@ -80,10 +80,17 @@ pub const PRIVATE_DOCUMENT_ENVELOPE_V1_BODY_HEADER_BYTES: u32 = 1 + 1 + 32 + 4 + pub const PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES: u32 = PRIVATE_DOCUMENT_ENVELOPE_V1_WRAPPER_BYTES + PRIVATE_DOCUMENT_ENVELOPE_V1_BODY_HEADER_BYTES; -/// The most bytes a payload of `document_type` takes: its properties in the document property -/// encoding, as a document writes them after its system fields, each one present at its largest -/// and one written with a presence byte (optional or transient) counting that byte. A private -/// type's entries carry their plaintext in this encoding. +/// The most bytes a payload of `document_type` takes as its property types bound it: its +/// properties in the document property encoding, as a document writes them after its system +/// fields, each one present at its largest and one written with a presence byte (optional or +/// transient) counting that byte. A private type's entries carry their plaintext in this +/// encoding. +/// +/// It is an upper bound, read from the property types alone: a schema's `enum`, or a +/// `maxProperties` keeping some optional properties from appearing together, can only make the +/// real largest payload smaller, and is not counted. A type sized between the two is refused by +/// [`validate_private_document_entry_size`] although every payload its schema admits would fit; +/// size it to this bound, or bound the property types themselves. /// /// Refused with `UnboundedPrivateDocumentProperty` when a property sets no largest value, since /// then no entry size holds every payload. @@ -111,9 +118,10 @@ pub fn largest_private_document_payload_size( Ok(size) } -/// The smallest `entrySize` that holds every payload of `document_type` in the standard private -/// document envelope (version 1): its largest payload plus -/// [`PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES`]. +/// The smallest `entrySize` that holds every payload the property types of `document_type` +/// allow in the standard private document envelope (version 1): its largest payload plus +/// [`PRIVATE_DOCUMENT_ENVELOPE_V1_OVERHEAD_BYTES`]. As +/// [`largest_private_document_payload_size`] says, `enum` and `maxProperties` are not counted. pub fn minimum_private_document_entry_size( document_type: DocumentTypeRef, ) -> Result { 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 ffa31f95316..809927f9aca 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs @@ -43,7 +43,9 @@ use dpp::version::TryFromPlatformVersioned; use dpp::ProtocolError; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; -use dash_sdk::platform::transition::put_contract::PutContract; +use dash_sdk::platform::transition::put_contract::{ + ensure_private_document_entries_fit, PutContract, +}; use dash_sdk::platform::transition::waitable::Waitable; use dash_sdk::platform::Fetch; @@ -503,6 +505,12 @@ impl IdentityWallet { )) })?; + // 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. + ensure_private_document_entries_fit(&updated_contract, Some(&existing)) + .map_err(PlatformWalletError::Sdk)?; + // 4. Build + broadcast the update transition. There's no // `UpdateContract` SDK extension mirroring `PutContract`, // so assemble the `DataContractUpdateTransition` directly: diff --git a/packages/rs-sdk/src/platform/transition/put_contract.rs b/packages/rs-sdk/src/platform/transition/put_contract.rs index f654469ee73..1befb981eb9 100644 --- a/packages/rs-sdk/src/platform/transition/put_contract.rs +++ b/packages/rs-sdk/src/platform/transition/put_contract.rs @@ -240,4 +240,88 @@ mod tests { )) )); } + + /// A mock SDK at the latest protocol version, the first whose contracts declare private + /// types. + fn latest_mock_sdk() -> Sdk { + crate::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .expect("a mock SDK") + } + + /// A contract holding only the public type `note`. + fn public_contract() -> DataContract { + let id = Identifier::from([7; 32]).to_string(Encoding::Base58); + let owner_id = Identifier::from([8; 32]).to_string(Encoding::Base58); + DataContract::from_value( + platform_value!({ + "$formatVersion": "1", + "id": id, + "ownerId": owner_id, + "version": 1, + "documentSchemas": { + "note": { + "type": "object", + "properties": { + "text": { "type": "string", "maxLength": 63, "position": 0 } + }, + "additionalProperties": false + } + } + }), + true, + PlatformVersion::latest(), + ) + .expect("the contract registers") + } + + /// An update declaring a private type is checked against the contract Platform holds, + /// fetched: an unchanged undersized type passes, a changed one is refused, every type is new + /// when Platform holds no such contract, and a fetch that fails stops the update. An update + /// declaring no private type fetches nothing. + #[tokio::test] + async fn should_check_an_update_against_the_contract_platform_holds() { + let stored = contract(375, false); + let mut sdk = latest_mock_sdk(); + sdk.mock() + .expect_fetch(stored.id(), Some(stored.clone())) + .await + .expect("an expectation"); + ensure_private_document_entries_fit_on_update(&sdk, &contract(375, false)) + .await + .expect("an unchanged type is not checked"); + assert!(matches!( + ensure_private_document_entries_fit_on_update(&sdk, &contract(375, true)).await, + Err(Error::Protocol( + ProtocolError::PrivateDocumentEntrySizeTooSmall { + minimum_entry_size: 398, + .. + } + )) + )); + + let mut absent = latest_mock_sdk(); + absent + .mock() + .expect_fetch(stored.id(), None::) + .await + .expect("an expectation"); + assert!(matches!( + ensure_private_document_entries_fit_on_update(&absent, &contract(375, false)).await, + Err(Error::Protocol( + ProtocolError::PrivateDocumentEntrySizeTooSmall { .. } + )) + )); + + // No expectation: the mock fails the fetch, and the update stops there. + let failing = latest_mock_sdk(); + let error = ensure_private_document_entries_fit_on_update(&failing, &contract(376, false)) + .await + .expect_err("the fetch fails"); + assert!(!matches!(error, Error::Protocol(_)), "{error:?}"); + ensure_private_document_entries_fit_on_update(&failing, &public_contract()) + .await + .expect("a contract with no private type is not fetched"); + } } From d1308804f2167d226269c1b393a57224038ab171 Mon Sep 17 00:00:00 2001 From: Quantum Explorer Date: Sun, 8 Nov 2026 03:09:59 +0700 Subject: [PATCH 4/4] test(dpp): count a private type's integers at the width the contract stores them A test holds largest_private_document_payload_size to the contract's integer width: with a version 0 config, or sized integer types off as DashPay keeps them, a bounded integer counts 8 bytes, as format 0 writes every integer; with sized integers on, its own width. Co-Authored-By: Claude Opus 5.5 --- .../document_type/private_document.rs | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) diff --git a/packages/rs-dpp/src/data_contract/document_type/private_document.rs b/packages/rs-dpp/src/data_contract/document_type/private_document.rs index 76fc87dec72..4c7760730e2 100644 --- a/packages/rs-dpp/src/data_contract/document_type/private_document.rs +++ b/packages/rs-dpp/src/data_contract/document_type/private_document.rs @@ -429,6 +429,59 @@ mod tests { ); } + /// Integers take the width the contract's documents store them in: with sized integer + /// types off, as a version 0 config always has them and DashPay keeps them, a bounded + /// integer is an i64 of 8 bytes, as format 0 writes every integer. + #[test] + fn should_count_integers_at_the_width_the_contract_stores_them() { + for config in [ + json!({ "$formatVersion": "0" }), + json!({ "$formatVersion": "1", "sizedIntegerTypes": false }), + json!({ "$formatVersion": "1", "sizedIntegerTypes": true }), + ] { + let sized = config.get("sizedIntegerTypes") == Some(&json!(true)); + let contract = DataContract::from_value( + platform_value::to_value(json!({ + "$formatVersion": "1", + "id": Identifier::from([7; 32]).to_string(Encoding::Base58), + "ownerId": Identifier::from([8; 32]).to_string(Encoding::Base58), + "version": 1, + "config": config, + "documentSchemas": { + "secret": { + "type": "object", + "private": { "entrySize": 400 }, + "documentsMutable": false, + "canBeDeleted": false, + "properties": { + "small": { + "type": "integer", "minimum": 0, "maximum": 255, + "position": 0 + } + }, + "required": ["small"], + "additionalProperties": false + } + } + })) + .expect("the contract converts"), + true, + PlatformVersion::latest(), + ) + .expect("the contract registers"); + assert_eq!( + largest_private_document_payload_size( + contract + .document_type_for_name("secret") + .expect("the secret type") + ) + .expect("bounded"), + if sized { 1 } else { 8 }, + "{config}" + ); + } + } + /// A `Date` property carries a marker byte when it is optional; its largest size counts it, /// as its encoding writes it. #[test]