diff --git a/book/src/contract-keywords.md b/book/src/contract-keywords.md index 0483204e46f..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. | 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/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..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 @@ -8,7 +8,11 @@ //! 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 std::num::NonZeroU32; /// What a document type's `private` keyword declares (`{ "entrySize": n }`). Built only by the @@ -59,3 +63,440 @@ 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 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. +pub fn largest_private_document_payload_size( + document_type: DocumentTypeRef, +) -> 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) + 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 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 { + 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 +/// 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, +) -> Result<(), ProtocolError> { + let Some(private_document) = document_type.private_document() else { + return Ok(()); + }; + 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(), + 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 platform_version::version::PlatformVersion; + 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).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() { + 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"), + ) + .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"), + ) + .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"), + ) { + 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"), + ) { + 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 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 + ); + } + + /// 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] + fn should_size_a_date_with_its_optional_marker() { + for required in [true, false] { + assert_eq!( + DocumentPropertyType::Date.max_encoded_value_size(required), + 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..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 @@ -3050,6 +3050,77 @@ 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`, 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) -> Option { + // A varint length, then that many bytes. + let length_prefixed = |bytes: u32| bytes.saturating_add(bytes.required_space() as u32); + 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 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 field_size = field.property_type.max_encoded_value_size(field.required)?; + inner = inner + .saturating_add(field_size) + .saturating_add(u32::from(!field.required)); + } + Some(length_prefixed(inner)) + } + DocumentPropertyType::TypedArray(typed_array) => { + // 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( &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-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 19e0ec51182..1befb981eb9 100644 --- a/packages/rs-sdk/src/platform/transition/put_contract.rs +++ b/packages/rs-sdk/src/platform/transition/put_contract.rs @@ -3,7 +3,10 @@ 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; use dpp::identity::signer::Signer; @@ -16,6 +19,47 @@ 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. +/// +/// 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, + stored_contract: Option<&DataContract>, +) -> Result<(), Error> { + 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 { @@ -48,6 +92,8 @@ impl> PutContract for DataContract { signer: &S, settings: Option, ) -> Result { + ensure_private_document_entries_fit(self, None)?; + let new_identity_nonce = sdk .get_identity_nonce(self.owner_id(), true, settings) .await?; @@ -93,3 +139,189 @@ 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::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; 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", + "id": id, + "ownerId": owner_id, + "version": 1, + "documentSchemas": { + "request": { + "type": "object", + "private": { "entrySize": entry_size }, + "documentsMutable": false, + "canBeDeleted": false, + "properties": properties, + "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() { + ensure_private_document_entries_fit(&contract(376, false), None) + .expect("376 bytes hold the largest payload"); + match ensure_private_document_entries_fit(&contract(375, false), None) { + 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:?}"), + } + } + + /// 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 { .. } + )) + )); + } + + /// 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"); + } +} diff --git a/packages/wasm-sdk/src/state_transitions/contract.rs b/packages/wasm-sdk/src/state_transitions/contract.rs index 8e66b8220e9..0ff48503b91 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_on_update, 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, 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 .inner_sdk()