From f9f9a82119d5419cfb80896b2e4cb29376c2d6fb Mon Sep 17 00:00:00 2001 From: QuantumExplorer Date: Mon, 16 Nov 2026 13:40:16 +0700 Subject: [PATCH 1/3] fix(dpp)!: refuse updating a contract whose stored schema repeats a key (PV15) From protocol version 15 registration already refuses a document type schema, or the contract's `$defs`, that names a key twice in any object. A contract stored earlier may still hold one. `DataContract::validate_update` generation 2, selected only by protocol version 15, runs generation 1 once no stored document type schema (with the stored `$defs` its parse reads) repeats a key, using the same walk as registration, and refuses the update with `DocumentTypeUpdateError` otherwise. Also adds regression tests for the registration refusal: a repeated key in either order at the root, in a nested object, in an array's `items`, in an index and in a definition, and contract create and update in a block. Co-Authored-By: Claude Opus 5.5 --- .../document_type/class_methods/mod.rs | 2 + .../class_methods/try_from_schema/mod.rs | 2 + .../try_from_schema/native_schema/mod.rs | 78 +++-- .../v3/repeated_doctype_key_tests.rs | 224 ++++++++++++ .../methods/validate_update/mod.rs | 4 +- .../methods/validate_update/v2/mod.rs | 321 ++++++++++++++++++ .../document/repeated_properties_update.rs | 160 ++++++++- .../dpp_versions/dpp_contract_versions/v7.rs | 5 + .../rs-platform-version/src/version/v15.rs | 5 +- 9 files changed, 756 insertions(+), 45 deletions(-) create mode 100644 packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/mod.rs index 1862f681cfb..f4d248c20e7 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/mod.rs @@ -13,6 +13,8 @@ mod should_use_creator_id; mod system_properties; mod try_from_schema; +#[cfg(feature = "validation")] +pub(in crate::data_contract) use try_from_schema::first_repeated_doctype_key; #[cfg(all(test, feature = "validation"))] pub(in crate::data_contract) use try_from_schema::DOCUMENT_SCHEMA_ROOT_KEYS; pub use try_from_schema::{ diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs index 63398697c57..d536da8e420 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs @@ -63,6 +63,8 @@ mod v2; mod v3; mod v4; +#[cfg(feature = "validation")] +pub(in crate::data_contract) use native_schema::first_repeated_doctype_key; #[cfg(all(test, feature = "validation"))] pub(in crate::data_contract) use native_schema::DOCUMENT_SCHEMA_ROOT_KEYS; pub(in crate::data_contract) use v3::{ diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/native_schema/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/native_schema/mod.rs index d5bf13b7815..8ca657690ab 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/native_schema/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/native_schema/mod.rs @@ -113,21 +113,54 @@ pub(super) fn refuse_a_repeated_doctype_key( name: &str, read: &mut u64, ) -> Result<(), ProtocolError> { - refuse_a_repeated_key_within(schema, name, &mut String::new(), read)?; + match first_repeated_doctype_key(schema, schema_defs, read) { + None => Ok(()), + Some((key, path)) => { + let place = if path.is_empty() { + "at its root".to_string() + } else { + format!("at `{path}`") + }; + Err(consensus_or_protocol_data_contract_error( + DataContractError::InvalidContractStructure(format!( + "document type \"{name}\" declares `{key}` more than once {place}: \ + the document type parser may read its first entry where the \ + schema checks read its last" + )), + )) + } + } +} + +/// The first key an object of the document `schema`, or of the contract's `schema_defs`, +/// names more than once, with the path of that object (empty at the schema's root, +/// `$defs....` in a definition), walking as [`refuse_a_repeated_doctype_key`] does and +/// counting in `read` each value it reads. `None` when no object repeats a key. +pub(in crate::data_contract) fn first_repeated_doctype_key( + schema: &Value, + schema_defs: Option<&BTreeMap>, + read: &mut u64, +) -> Option<(String, String)> { + if let Some(repeat) = first_repeated_key_within(schema, &mut String::new(), read) { + return Some(repeat); + } for (definition, value) in schema_defs.into_iter().flatten() { - refuse_a_repeated_key_within(value, name, &mut format!("$defs.{definition}"), read)?; + if let Some(repeat) = + first_repeated_key_within(value, &mut format!("$defs.{definition}"), read) + { + return Some(repeat); + } } - Ok(()) + None } -/// [`refuse_a_repeated_doctype_key`] over `value`, found at `path` within the schema (empty -/// at its root), and everything it holds. -fn refuse_a_repeated_key_within( +/// [`first_repeated_doctype_key`] over `value`, found at `path` within the schema (empty at +/// its root), and everything it holds. +fn first_repeated_key_within( value: &Value, - name: &str, path: &mut String, read: &mut u64, -) -> Result<(), ProtocolError> { +) -> Option<(String, String)> { *read = read.saturating_add(1); match value { Value::Map(map) => { @@ -140,39 +173,34 @@ fn refuse_a_repeated_key_within( continue; }; if !declared.insert(key) { - let place = if path.is_empty() { - "at its root".to_string() - } else { - format!("at `{path}`") - }; - return Err(consensus_or_protocol_data_contract_error( - DataContractError::InvalidContractStructure(format!( - "document type \"{name}\" declares `{key}` more than once {place}: \ - the document type parser may read its first entry where the \ - schema checks read its last" - )), - )); + return Some((key.to_string(), path.clone())); } let len = path.len(); if !path.is_empty() { path.push('.'); } path.push_str(key); - refuse_a_repeated_key_within(entry, name, path, read)?; + let repeat = first_repeated_key_within(entry, path, read); path.truncate(len); + if repeat.is_some() { + return repeat; + } } - Ok(()) + None } Value::Array(items) => { for (index, item) in items.iter().enumerate() { let len = path.len(); path.push_str(&format!("[{index}]")); - refuse_a_repeated_key_within(item, name, path, read)?; + let repeat = first_repeated_key_within(item, path, read); path.truncate(len); + if repeat.is_some() { + return repeat; + } } - Ok(()) + None } - _ => Ok(()), + _ => None, } } diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/repeated_doctype_key_tests.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/repeated_doctype_key_tests.rs index 0a68a4a189b..b9bea1659d7 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/repeated_doctype_key_tests.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/v3/repeated_doctype_key_tests.rs @@ -638,3 +638,227 @@ fn should_refuse_a_nested_repeat_beside_a_reference_only_the_expansion_resolves( "`properties.note`", ); } + +/// A map of `entries` in order, keeping every repeat. +fn map_of(entries: Vec<(&str, Value)>) -> Value { + Value::Map( + entries + .into_iter() + .map(|(key, value)| (text(key), value)) + .collect(), + ) +} + +/// Every key the parser reads, repeated in either order, at the root, in a nested object, in +/// an array's `items`, in an index and in a definition, is refused under full validation, +/// naming the object repeating it. +#[test] +fn should_refuse_a_repeated_key_in_every_object_a_schema_or_its_definitions_hold() { + let string_list = |items: Value| { + platform_value!({ + "list": map_of(vec![ + ("type", text("array")), + ("position", Value::U64(0)), + ("maxItems", Value::U64(4)), + ("items", items), + ]) + }) + }; + let note_object = |entries: Vec<(&str, Value)>| { + let mut note = vec![ + ("type", text("object")), + ("position", Value::U64(0)), + ( + "properties", + platform_value!({ "leaf": { "type": "string", "maxLength": 10, "position": 0 } }), + ), + ("additionalProperties", Value::Bool(false)), + ]; + note.extend(entries); + platform_value!({ "note": map_of(note) }) + }; + let index_on_a = |index: Value| { + schema_of(vec![ + ("properties", string_properties()), + ("indices", Value::Array(vec![index])), + ]) + }; + let cases: Vec<(&str, &str, &str, Value)> = vec![ + ( + "root properties, the second entry first", + "properties", + "its root", + schema_of(vec![ + ("properties", integer_properties()), + ("properties", string_properties()), + ]), + ), + ( + "root type", + "type", + "its root", + schema_of(vec![ + ("type", text("array")), + ("properties", string_properties()), + ]), + ), + ( + "root required", + "required", + "its root", + schema_of(vec![ + ("properties", string_properties()), + ("required", platform_value!(["a"])), + ("required", platform_value!([])), + ]), + ), + ( + "root indices", + "indices", + "its root", + schema_of(vec![ + ("properties", string_properties()), + ( + "indices", + platform_value!([{ "name": "byA", "properties": [{ "a": "asc" }], "unique": true }]), + ), + ("indices", platform_value!([])), + ]), + ), + ( + "root additionalProperties", + "additionalProperties", + "its root", + Value::Map(vec![ + (text("type"), text("object")), + (text("properties"), string_properties()), + (text("additionalProperties"), Value::Bool(true)), + (text("additionalProperties"), Value::Bool(false)), + ]), + ), + ( + "required of a nested object", + "required", + "`properties.note`", + schema_of(vec![( + "properties", + note_object(vec![ + ("required", platform_value!(["leaf"])), + ("required", platform_value!([])), + ]), + )]), + ), + ( + "type of a nested property", + "type", + "`properties.note.properties.leaf`", + schema_of(vec![( + "properties", + platform_value!({ + "note": { + "type": "object", + "position": 0, + "properties": { + "leaf": map_of(vec![ + ("type", text("integer")), + ("position", Value::U64(0)), + ("type", text("string")), + ("maxLength", Value::U64(10)), + ]) + }, + "additionalProperties": false + } + }), + )]), + ), + ( + "a key of an array's items", + "maxLength", + "`properties.list.items`", + schema_of(vec![( + "properties", + string_list(map_of(vec![ + ("type", text("string")), + ("maxLength", Value::U64(5)), + ("maxLength", Value::U64(50)), + ])), + )]), + ), + ( + "an array's items", + "items", + "`properties.list`", + schema_of(vec![( + "properties", + platform_value!({ + "list": map_of(vec![ + ("type", text("array")), + ("position", Value::U64(0)), + ("maxItems", Value::U64(4)), + ("items", platform_value!({ "type": "string", "maxLength": 5 })), + ("items", platform_value!({ "type": "integer" })), + ]) + }), + )]), + ), + ( + "a property of an index", + "a", + "`indices[0].properties[0]`", + index_on_a(platform_value!({ + "name": "byA", + "properties": [map_of(vec![("a", text("asc")), ("a", text("desc"))])] + })), + ), + ]; + for (case, key, place, schema) in cases { + let error = + parse(schema, true).expect_err(&format!("expected the repeat of {case} to be refused")); + assert_repeat_refused(error, key, place); + } + + let schema = schema_of(vec![( + "properties", + platform_value!({ "a": { "$ref": "#/$defs/address", "position": 0 } }), + )]); + let street = |max_length: u64| platform_value!({ "street": { "type": "string", "maxLength": max_length, "position": 0 } }); + let defs_cases: Vec<(&str, &str, &str, Value)> = vec![ + ( + "properties of a definition", + "properties", + "`$defs.address`", + map_of(vec![ + ("type", text("object")), + ("properties", street(10)), + ( + "properties", + platform_value!({ "street": { "type": "integer", "position": 0 } }), + ), + ("additionalProperties", Value::Bool(false)), + ]), + ), + ( + "a key of a definition's property", + "maxLength", + "`$defs.address.properties.street`", + platform_value!({ + "type": "object", + "properties": { + "street": map_of(vec![ + ("type", text("string")), + ("maxLength", Value::U64(10)), + ("position", Value::U64(0)), + ("maxLength", Value::U64(20)), + ]) + }, + "additionalProperties": false + }), + ), + ]; + for (case, key, place, definition) in defs_cases { + let defs = BTreeMap::from([("address".to_string(), definition)]); + let error = parse_on(schema.clone(), Some(&defs), true, PlatformVersion::latest()) + .expect_err(&format!("expected the repeat of {case} to be refused")); + assert_repeat_refused(error, key, place); + } +} diff --git a/packages/rs-dpp/src/data_contract/methods/validate_update/mod.rs b/packages/rs-dpp/src/data_contract/methods/validate_update/mod.rs index 5081e57bcd3..a110b20101f 100644 --- a/packages/rs-dpp/src/data_contract/methods/validate_update/mod.rs +++ b/packages/rs-dpp/src/data_contract/methods/validate_update/mod.rs @@ -5,6 +5,7 @@ use platform_version::version::PlatformVersion; mod common; mod v0; mod v1; +mod v2; use crate::validation::SimpleConsensusValidationResult; use crate::ProtocolError; pub use v0::*; @@ -24,9 +25,10 @@ impl DataContractUpdateValidationMethodsV0 for DataContract { { 0 => self.validate_update_v0(data_contract, block_info, platform_version), 1 => self.validate_update_v1(data_contract, block_info, platform_version), + 2 => self.validate_update_v2(data_contract, block_info, platform_version), version => Err(ProtocolError::UnknownVersionMismatch { method: "DataContract::validate_update".to_string(), - known_versions: vec![0, 1], + known_versions: vec![0, 1, 2], received: version, }), } diff --git a/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs b/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs new file mode 100644 index 00000000000..c4a888e3d1a --- /dev/null +++ b/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs @@ -0,0 +1,321 @@ +use crate::block::block_info::BlockInfo; +use crate::consensus::state::data_contract::document_type_update_error::DocumentTypeUpdateError; +use crate::data_contract::accessors::v0::DataContractV0Getters; +use crate::data_contract::document_type::accessors::DocumentTypeV0Getters; +use crate::data_contract::document_type::class_methods::first_repeated_doctype_key; +use crate::data_contract::schema::DataContractSchemaMethodsV0; +use crate::data_contract::DataContract; +use crate::validation::SimpleConsensusValidationResult; +use crate::ProtocolError; +use platform_version::version::PlatformVersion; + +impl DataContract { + /// Generation 2 (protocol version 15): generation 1, once no document type of the stored + /// contract names a key twice in an object of its schema, or of the contract's `$defs`. + /// + /// From protocol version 15 registration refuses such a schema (`check_document_type_schema` + /// 1), but a contract stored earlier may hold one. The checks of an update read the stored + /// schema as JSON, which keeps the last entry of a repeated key, where the document type + /// parser may have read the first, so they can not judge an update of it: an update of a + /// contract whose stored schema repeats a key is refused. The new schema can not repeat + /// the key either, so such a contract stays as it was stored. + /// + /// Delegating to generation 1 is safe because that generation is shipped and therefore + /// frozen. The checks are independent and short-circuiting, so running the extra one first + /// changes only which error is reported when an update violates several rules at once, + /// never whether it is rejected. + #[inline(always)] + pub(super) fn validate_update_v2( + &self, + new_data_contract: &DataContract, + block_info: &BlockInfo, + platform_version: &PlatformVersion, + ) -> Result { + let result = self.validate_update_stored_schemas_repeat_no_key(); + if !result.is_valid() { + return Ok(result); + } + + self.validate_update_v1(new_data_contract, block_info, platform_version) + } + + /// Refuses the update when an object of a stored document type's schema, or of the + /// stored `$defs` its parse reads, names a key more than once, as registration from + /// protocol version 15 refuses a schema that does + /// ([`first_repeated_doctype_key`], the same walk). The walk is linear in the size of the + /// stored contract, which the update already fetched and pays for. + fn validate_update_stored_schemas_repeat_no_key(&self) -> SimpleConsensusValidationResult { + let schema_defs = self.schema_defs(); + for (name, document_type) in self.document_types() { + let mut read = 0; + let Some((key, path)) = + first_repeated_doctype_key(document_type.schema(), schema_defs, &mut read) + else { + continue; + }; + let place = if path.is_empty() { + "at its root".to_string() + } else { + format!("at `{path}`") + }; + return SimpleConsensusValidationResult::new_with_error( + DocumentTypeUpdateError::new( + self.id(), + name, + format!( + "its stored schema declares `{key}` more than once {place}, and a \ + contract whose schema repeats a key can not be updated" + ), + ) + .into(), + ); + } + + SimpleConsensusValidationResult::new() + } +} + +#[cfg(test)] +mod tests { + use crate::block::block_info::BlockInfo; + use crate::consensus::state::state_error::StateError; + use crate::consensus::ConsensusError; + use crate::data_contract::accessors::v0::{DataContractV0Getters, DataContractV0Setters}; + use crate::data_contract::document_type::accessors::DocumentTypeV0Getters; + use crate::data_contract::document_type::DocumentPropertyType; + use crate::data_contract::methods::validate_update::DataContractUpdateValidationMethodsV0; + use crate::data_contract::schema::DataContractSchemaMethodsV0; + use crate::data_contract::DataContract; + use crate::prelude::IdentityNonce; + use crate::tests::fixtures::get_data_contract_fixture; + use assert_matches::assert_matches; + use platform_value::{platform_value, Value}; + use platform_version::version::PlatformVersion; + use std::collections::BTreeMap; + + const TYPE_NAME: &str = "t"; + + fn text(value: &str) -> Value { + Value::Text(value.to_string()) + } + + fn string_a() -> Value { + platform_value!({ "a": { "type": "string", "maxLength": 10, "position": 0 } }) + } + + fn integer_a() -> Value { + platform_value!({ "a": { "type": "integer", "minimum": 0, "maximum": 100, "position": 0 } }) + } + + /// A document type schema holding `properties` once for each of `properties`, in order. + fn schema(properties: Vec) -> Value { + let mut entries = vec![(text("type"), text("object"))]; + entries.extend( + properties + .into_iter() + .map(|properties| (text("properties"), properties)), + ); + entries.push((text("additionalProperties"), Value::Bool(false))); + Value::Map(entries) + } + + /// The fixture contract with the type `t` of `stored_schema` and the `$defs` + /// `stored_defs`, placed as a contract read back from state is parsed (without + /// validation), and its update to `new_schema` and `new_defs`, parsed under full + /// validation as a block parses the update's contract. + fn stored_and_updated( + stored_schema: Value, + stored_defs: Option>, + new_schema: Value, + new_defs: Option>, + platform_version: &PlatformVersion, + ) -> (DataContract, DataContract) { + let mut stored = get_data_contract_fixture( + None, + IdentityNonce::default(), + platform_version.protocol_version, + ) + .data_contract_owned(); + let with_fixture_defs = |contract: &DataContract, defs: Option>| { + defs.map(|defs| { + let mut all = contract.schema_defs().cloned().unwrap_or_default(); + all.extend(defs); + all + }) + }; + if let Some(defs) = with_fixture_defs(&stored, stored_defs) { + stored + .set_schema_defs(Some(defs), false, &mut Vec::new(), platform_version) + .expect("expected the stored $defs to be placed"); + } + stored + .set_document_schema( + TYPE_NAME, + stored_schema, + false, + &mut Vec::new(), + platform_version, + ) + .expect("expected the stored schema to load"); + + let mut updated = stored.clone(); + updated.set_version(stored.version() + 1); + if let Some(defs) = with_fixture_defs(&updated, new_defs) { + updated + .set_schema_defs(Some(defs), false, &mut Vec::new(), platform_version) + .expect("expected the new $defs to be placed"); + } + updated + .set_document_schema( + TYPE_NAME, + new_schema, + true, + &mut Vec::new(), + platform_version, + ) + .expect("expected the new schema to register"); + (stored, updated) + } + + fn parsed_type_of(contract: &DataContract, path: &str) -> DocumentPropertyType { + contract + .document_type_for_name(TYPE_NAME) + .expect("expected the type") + .flattened_properties() + .get(path) + .expect("expected the property") + .property_type + .clone() + } + + fn assert_update_refused(stored: &DataContract, updated: &DataContract, key: &str) { + let result = stored + .validate_update(updated, &BlockInfo::default(), PlatformVersion::latest()) + .expect("expected the update to be judged"); + assert_matches!( + result.errors.as_slice(), + [ConsensusError::StateError(StateError::DocumentTypeUpdateError(e))] + if e.additional_message().contains(&format!("declares `{key}` more than once")) + ); + } + + /// The stored type reads one entry of a repeated root `properties`, the update keeps the + /// other: whichever order, the update is refused, so the parsed type of `a` stays as it + /// was stored. + #[test] + fn should_refuse_an_update_of_a_stored_schema_repeating_root_properties() { + let platform_version = PlatformVersion::latest(); + for (stored_schema, new_properties) in [ + (schema(vec![string_a(), integer_a()]), integer_a()), + (schema(vec![integer_a(), string_a()]), string_a()), + ] { + let (stored, updated) = stored_and_updated( + stored_schema, + None, + schema(vec![new_properties]), + None, + platform_version, + ); + assert_ne!( + std::mem::discriminant(&parsed_type_of(&stored, "a")), + std::mem::discriminant(&parsed_type_of(&updated, "a")), + ); + assert_update_refused(&stored, &updated, "properties"); + } + } + + /// The same for a repeated `properties` of a nested object. + #[test] + fn should_refuse_an_update_of_a_stored_schema_repeating_nested_properties() { + let platform_version = PlatformVersion::latest(); + let note = |properties: Vec| { + let mut entries = vec![ + (text("type"), text("object")), + (text("position"), Value::U64(0)), + ]; + entries.extend( + properties + .into_iter() + .map(|properties| (text("properties"), properties)), + ); + entries.push((text("additionalProperties"), Value::Bool(false))); + schema(vec![platform_value!({ "note": Value::Map(entries) })]) + }; + let (stored, updated) = stored_and_updated( + note(vec![string_a(), integer_a()]), + None, + note(vec![integer_a()]), + None, + platform_version, + ); + assert_update_refused(&stored, &updated, "properties"); + } + + /// The same for a repeated key of the stored `$defs` a property of the type refers to. + #[test] + fn should_refuse_an_update_of_a_stored_definition_repeating_a_key() { + let platform_version = PlatformVersion::latest(); + let word = |properties: Vec| { + let mut entries = vec![(text("type"), text("object"))]; + entries.extend( + properties + .into_iter() + .map(|properties| (text("properties"), properties)), + ); + entries.push((text("additionalProperties"), Value::Bool(false))); + BTreeMap::from([("word".to_string(), Value::Map(entries))]) + }; + let referring = schema(vec![ + platform_value!({ "w": { "$ref": "#/$defs/word", "position": 0 } }), + ]); + let (stored, updated) = stored_and_updated( + referring.clone(), + Some(word(vec![string_a(), integer_a()])), + referring, + Some(word(vec![integer_a()])), + platform_version, + ); + assert_update_refused(&stored, &updated, "properties"); + } + + /// An update of a contract whose stored schema names each key once is judged as before. + #[test] + fn should_admit_an_update_of_a_stored_schema_naming_each_key_once() { + let platform_version = PlatformVersion::latest(); + let (stored, updated) = stored_and_updated( + schema(vec![string_a()]), + None, + schema(vec![string_a()]), + None, + platform_version, + ); + let result = stored + .validate_update(&updated, &BlockInfo::default(), platform_version) + .expect("expected the update to be judged"); + assert!(result.is_valid(), "{:?}", result.errors); + } + + /// Protocol version 14 selects generation 1, which this generation leaves as it was: the + /// update check of protocol version 14 judges any update as generation 1 does. + #[test] + fn should_judge_an_update_at_protocol_version_14_as_generation_1_does() { + let platform_version = PlatformVersion::get(14).expect("protocol version 14"); + for (stored_schema, new_schema) in [ + (schema(vec![string_a()]), schema(vec![string_a()])), + ( + schema(vec![string_a(), integer_a()]), + schema(vec![integer_a()]), + ), + ] { + let (stored, updated) = + stored_and_updated(stored_schema, None, new_schema, None, platform_version); + let dispatched = stored + .validate_update(&updated, &BlockInfo::default(), platform_version) + .expect("expected the update to be judged"); + let generation_1 = stored + .validate_update_v1(&updated, &BlockInfo::default(), platform_version) + .expect("expected the update to be judged"); + assert_eq!(dispatched.errors, generation_1.errors); + } + } +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/repeated_properties_update.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/repeated_properties_update.rs index 030e69fe034..99f1fcf3490 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/repeated_properties_update.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/repeated_properties_update.rs @@ -1,10 +1,13 @@ -//! A data contract update whose document type schema names `properties` twice, -//! run through block execution. From protocol version 15 registration refuses a -//! key a document type schema repeats, at its root or below it. +//! A data contract create or update whose document type schema names `properties` +//! twice, run through block execution. From protocol version 15 registration refuses +//! a key a document type schema repeats, at its root or below it, and an update of a +//! contract stored with such a schema is refused. use super::*; use dpp::consensus::basic::BasicError; +use dpp::consensus::state::state_error::StateError; use dpp::data_contract::accessors::v0::DataContractV0Setters; +use dpp::data_contract::document_type::DocumentPropertyType; use dpp::data_contract::errors::DataContractError; use dpp::data_contract::schema::DataContractSchemaMethodsV0; use dpp::document::{Document, DocumentV0}; @@ -12,6 +15,9 @@ use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV use dpp::identity::IdentityPublicKey; use dpp::platform_value::platform_value; use dpp::prelude::DataContract; +use dpp::state_transition::data_contract_create_transition::accessors::DataContractCreateTransitionAccessorsV0; +use dpp::state_transition::data_contract_create_transition::methods::DataContractCreateTransitionMethodsV0; +use dpp::state_transition::data_contract_create_transition::DataContractCreateTransition; use dpp::state_transition::data_contract_update_transition::methods::DataContractUpdateTransitionMethodsV0; use dpp::state_transition::data_contract_update_transition::DataContractUpdateTransition; use dpp::state_transition::StateTransition; @@ -62,6 +68,12 @@ struct Fixture { impl Fixture { fn new(version: &'static PlatformVersion) -> Self { + Self::storing(version, schema(vec![integer_properties()])) + } + + /// A platform storing the contract whose type `t` has `stored_schema`, placed + /// unvalidated, as a contract stored before the schema checks it misses. + fn storing(version: &'static PlatformVersion, stored_schema: Value) -> Self { let mut platform = TestPlatformBuilder::new() .with_initial_protocol_version(version.protocol_version) .build_with_mock_rpc() @@ -71,13 +83,7 @@ impl Fixture { get_data_contract_fixture(Some(identity.id()), 0, version.protocol_version) .data_contract_owned(); contract - .set_document_schema( - TYPE_NAME, - schema(vec![integer_properties()]), - true, - &mut Vec::new(), - version, - ) + .set_document_schema(TYPE_NAME, stored_schema, false, &mut Vec::new(), version) .expect("schema parses"); platform .drive @@ -145,18 +151,18 @@ impl Fixture { /// An update to version 2 naming `properties` twice: first with `a` a /// string, then as stored. async fn update_repeating_properties(&mut self) -> StateTransition { + self.update_to(schema(vec![string_properties(), integer_properties()])) + .await + } + + /// An update to version 2 giving the type `t` the schema `new_schema`. + async fn update_to(&mut self, new_schema: Value) -> StateTransition { let mut contract = self.contract.clone(); contract.set_version(2); // Placed unvalidated: the transition carries the schema as written, and // the platform validates it contract - .set_document_schema( - TYPE_NAME, - schema(vec![string_properties(), integer_properties()]), - false, - &mut Vec::new(), - self.version, - ) + .set_document_schema(TYPE_NAME, new_schema, false, &mut Vec::new(), self.version) .expect("schema placed"); let transition = DataContractUpdateTransition::new_from_data_contract( contract, @@ -174,6 +180,42 @@ impl Fixture { transition } + /// A create of a new contract whose type `t` has `new_schema`, placed + /// unvalidated, as the transition carries it. + async fn contract_creation(&self, new_schema: Value) -> StateTransition { + let identity_nonce = 1; + let mut contract = get_data_contract_fixture( + Some(self.identity.id()), + identity_nonce, + self.version.protocol_version, + ) + .data_contract_owned(); + contract + .set_document_schema(TYPE_NAME, new_schema, false, &mut Vec::new(), self.version) + .expect("schema placed"); + DataContractCreateTransition::new_from_data_contract( + contract, + identity_nonce, + &self.identity.clone().into_partial_identity_info(), + self.key.id(), + &self.signer, + self.version, + None, + ) + .await + .expect("create transition") + } + + /// The parsed type of `a` in the contract as Drive has it now. + fn stored_type_of_a(&self) -> DocumentPropertyType { + self.current_contract() + .document_type_for_name(TYPE_NAME) + .expect("the type exists") + .flattened_properties()["a"] + .property_type + .clone() + } + /// Executes `transition` as a validator executes a received block, and /// commits. fn process(&self, transition: &StateTransition) -> StateTransitionExecutionResult { @@ -267,3 +309,87 @@ async fn should_refuse_a_contract_update_repeating_properties() { "the stored documents read as they were written" ); } + +/// Whichever entry comes first, an update repeating `properties` is refused in the +/// block, paid, and the stored type of `a` stays as it was. +#[tokio::test] +async fn should_refuse_a_contract_update_repeating_properties_in_either_order() { + for properties in [ + vec![string_properties(), integer_properties()], + vec![integer_properties(), string_properties()], + ] { + let mut fixture = Fixture::new(PlatformVersion::latest()); + let before = fixture.stored_type_of_a(); + let update = fixture.update_to(schema(properties)).await; + assert_matches!( + fixture.process(&update), + StateTransitionExecutionResult::PaidConsensusError { + error: ConsensusError::BasicError(BasicError::ContractError( + DataContractError::InvalidContractStructure(ref message) + )), + .. + } if message.contains("declares `properties` more than once at its root") + ); + assert_eq!(fixture.current_contract().version(), 1); + assert_eq!(fixture.stored_type_of_a(), before); + } +} + +/// A contract create repeating `properties` is refused in the block, paid, and no +/// contract is stored. +#[tokio::test] +async fn should_refuse_a_contract_create_repeating_properties() { + let fixture = Fixture::new(PlatformVersion::latest()); + let create = fixture + .contract_creation(schema(vec![string_properties(), integer_properties()])) + .await; + let StateTransition::DataContractCreate(create_transition) = &create else { + panic!("expected a contract create"); + }; + let contract_id = create_transition.data_contract().id(); + assert_matches!( + fixture.process(&create), + StateTransitionExecutionResult::PaidConsensusError { + error: ConsensusError::BasicError(BasicError::ContractError( + DataContractError::InvalidContractStructure(ref message) + )), + .. + } if message.contains("declares `properties` more than once at its root") + ); + assert!(fixture + .platform + .drive + .get_contract_with_fetch_info(contract_id.to_buffer(), false, None, fixture.version) + .expect("contract fetch") + .is_none()); +} + +/// A contract stored with a schema naming `properties` twice can not be updated, in +/// particular not to the one entry the stored type did not read: the update is refused +/// in the block, paid, and the stored type of `a` stays as it was. +#[tokio::test] +async fn should_refuse_an_update_of_a_contract_stored_with_repeated_properties() { + for (stored, kept) in [ + ( + vec![string_properties(), integer_properties()], + integer_properties(), + ), + ( + vec![integer_properties(), string_properties()], + string_properties(), + ), + ] { + let mut fixture = Fixture::storing(PlatformVersion::latest(), schema(stored)); + let before = fixture.stored_type_of_a(); + let update = fixture.update_to(schema(vec![kept])).await; + assert_matches!( + fixture.process(&update), + StateTransitionExecutionResult::PaidConsensusError { + error: ConsensusError::StateError(StateError::DocumentTypeUpdateError(ref e)), + .. + } if e.additional_message().contains("declares `properties` more than once at its root") + ); + assert_eq!(fixture.current_contract().version(), 1); + assert_eq!(fixture.stored_type_of_a(), before); + } +} diff --git a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs index c58b4b21b62..ff4b4028f25 100644 --- a/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs +++ b/packages/rs-platform-version/src/version/dpp_versions/dpp_contract_versions/v7.rs @@ -18,6 +18,9 @@ use crate::version::dpp_versions::dpp_contract_versions::{ /// - `check_document_type_schema`, 1 rather than 0: a schema is checked at registration /// natively instead of against the document meta-schema through the `jsonschema` crate, and /// every new document type must have a validation schema; +/// - `validate_update`, 2 rather than 1: an update of a contract is refused when an object of +/// a stored document type's schema, or of the stored `$defs`, names a key twice, as +/// registration from this version refuses a schema that does; /// - `validate_max_depth`, 2 rather than 1: the depth and cycle check resolves `$ref` /// pointers by RFC 6901, as the native validator does; /// - `validation_schema`, `Some(0)` rather than `None`: builds that typed validation schema @@ -60,6 +63,8 @@ pub const CONTRACT_VERSIONS_V7: DPPContractVersions = DPPContractVersions { validate_schema_patterns: Some(0), // changed: the fee estimate bills an index without compiling its field matches registration_cost: 3, + // changed: an update of a contract whose stored schema repeats a key is refused + validate_update: 2, ..CONTRACT_VERSIONS_V6.methods }, document_type_versions: DocumentTypeVersions { diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index 4407188f234..54311ba42f8 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -179,8 +179,9 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// refuses a document type schema, or the contract's `$defs`, naming a key /// twice in any object it holds, at its root or below it, as sent, whose /// first entry the parser may read where every check reads the last -/// (`InvalidContractStructure`; a stored contract with one, which no JSON -/// could have written, must drop it to be updated), +/// (`InvalidContractStructure`), and refuses an update of a contract stored +/// with one, which no JSON could have written (`DocumentTypeUpdateError`, +/// `validate_update` 2 of `CONTRACT_VERSIONS_V7`), /// refuses a contested index whose contest its index values do not decide /// (`InvalidContractStructure`, note 19) or that is keyed by a property path or a /// system property (`InvalidContractStructure`, note 21), From 1758991781b5dccee39bfe6ceae359a5e86e8511 Mon Sep 17 00:00:00 2001 From: QuantumExplorer Date: Mon, 16 Nov 2026 18:46:26 +0700 Subject: [PATCH 2/3] fix(dpp): report a stored `$defs` repeating a key on the contract, read it once (PV15) Follow-up to the refusal of an update of a contract whose stored schema repeats a key (`validate_update` 2, protocol version 15 only): - the stored `$defs` are walked once, not once per document type, and a key they repeat is reported on the contract (`DataContractUpdateActionNotAllowedError`) instead of on whichever document type sorts first; a type's own schema is still reported on the type (`DocumentTypeUpdateError`); - the walk is split into `first_repeated_key_of_schema` and `first_repeated_key_of_definitions`, which share the wording of the place with registration's refusal; - generation 1's tests are pinned to protocol version 14; - the version gate is tested by behaviour on both sides of it; - a block test registers the contract under protocol version 14, runs the first block of the latest version and updates it; - the block test fixture registers its starting schema under full validation again; - the wasm `validateUpdate` doc names the rule. Co-Authored-By: Claude Fable 5.2 --- .../document_type/class_methods/mod.rs | 6 +- .../class_methods/try_from_schema/mod.rs | 6 +- .../try_from_schema/native_schema/mod.rs | 93 ++++++++------ .../methods/validate_update/v1/mod.rs | 10 +- .../methods/validate_update/v2/mod.rs | 118 ++++++++++++------ .../document/repeated_properties_update.rs | 108 +++++++++++++++- .../rs-platform-version/src/version/v15.rs | 1 + packages/wasm-dpp2/src/data_contract/model.rs | 5 +- 8 files changed, 263 insertions(+), 84 deletions(-) diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/mod.rs index f4d248c20e7..a8fcf96e11e 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/mod.rs @@ -13,10 +13,12 @@ mod should_use_creator_id; mod system_properties; mod try_from_schema; -#[cfg(feature = "validation")] -pub(in crate::data_contract) use try_from_schema::first_repeated_doctype_key; #[cfg(all(test, feature = "validation"))] pub(in crate::data_contract) use try_from_schema::DOCUMENT_SCHEMA_ROOT_KEYS; +#[cfg(feature = "validation")] +pub(in crate::data_contract) use try_from_schema::{ + first_repeated_key_of_definitions, first_repeated_key_of_schema, +}; pub use try_from_schema::{ referenced_peer_kind_error, referenced_peer_kind_mismatch, referenced_reads_error, where_condition_literal_error, diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs index d536da8e420..ed4f49bc5e4 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/mod.rs @@ -63,10 +63,12 @@ mod v2; mod v3; mod v4; -#[cfg(feature = "validation")] -pub(in crate::data_contract) use native_schema::first_repeated_doctype_key; #[cfg(all(test, feature = "validation"))] pub(in crate::data_contract) use native_schema::DOCUMENT_SCHEMA_ROOT_KEYS; +#[cfg(feature = "validation")] +pub(in crate::data_contract) use native_schema::{ + first_repeated_key_of_definitions, first_repeated_key_of_schema, +}; pub(in crate::data_contract) use v3::{ resolve_derived_index_properties, validate_preallocated_indexes_kept_on_removal, validate_summable_off_count_indexes_lossless, diff --git a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/native_schema/mod.rs b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/native_schema/mod.rs index 8ca657690ab..2919233e2c2 100644 --- a/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/native_schema/mod.rs +++ b/packages/rs-dpp/src/data_contract/document_type/class_methods/try_from_schema/native_schema/mod.rs @@ -113,54 +113,74 @@ pub(super) fn refuse_a_repeated_doctype_key( name: &str, read: &mut u64, ) -> Result<(), ProtocolError> { - match first_repeated_doctype_key(schema, schema_defs, read) { + let repeated = first_repeated_key_of_schema(schema, read) + .or_else(|| first_repeated_key_of_definitions(schema_defs, read)); + match repeated { None => Ok(()), - Some((key, path)) => { - let place = if path.is_empty() { - "at its root".to_string() - } else { - format!("at `{path}`") - }; - Err(consensus_or_protocol_data_contract_error( - DataContractError::InvalidContractStructure(format!( - "document type \"{name}\" declares `{key}` more than once {place}: \ - the document type parser may read its first entry where the \ - schema checks read its last" - )), - )) + Some(repeated) => Err(consensus_or_protocol_data_contract_error( + DataContractError::InvalidContractStructure(format!( + "document type \"{name}\" declares `{}` more than once {}: \ + the document type parser may read its first entry where the \ + schema checks read its last", + repeated.key(), + repeated.place() + )), + )), + } +} + +/// A key an object of a document schema, or of a contract's `$defs`, names more than once. +pub(in crate::data_contract) struct RepeatedKey { + key: String, + /// The path of the object naming it: empty at a document schema's root, + /// `$defs....` in a definition. + path: String, +} + +impl RepeatedKey { + /// The key named more than once. + pub(in crate::data_contract) fn key(&self) -> &str { + &self.key + } + + /// Where the object naming it is, as a refusal words it. + pub(in crate::data_contract) fn place(&self) -> String { + if self.path.is_empty() { + "at its root".to_string() + } else { + format!("at `{}`", self.path) } } } -/// The first key an object of the document `schema`, or of the contract's `schema_defs`, -/// names more than once, with the path of that object (empty at the schema's root, -/// `$defs....` in a definition), walking as [`refuse_a_repeated_doctype_key`] does and -/// counting in `read` each value it reads. `None` when no object repeats a key. -pub(in crate::data_contract) fn first_repeated_doctype_key( +/// The first key an object of the document `schema` names more than once, at its root or +/// anywhere below it, walking as [`refuse_a_repeated_doctype_key`] does and counting in +/// `read` each value it reads. `None` when no object repeats a key. +pub(in crate::data_contract) fn first_repeated_key_of_schema( schema: &Value, + read: &mut u64, +) -> Option { + first_repeated_key_within(schema, &mut String::new(), read) +} + +/// [`first_repeated_key_of_schema`] over each definition of a contract's `schema_defs`, in +/// the order of their names. +pub(in crate::data_contract) fn first_repeated_key_of_definitions( schema_defs: Option<&BTreeMap>, read: &mut u64, -) -> Option<(String, String)> { - if let Some(repeat) = first_repeated_key_within(schema, &mut String::new(), read) { - return Some(repeat); - } - for (definition, value) in schema_defs.into_iter().flatten() { - if let Some(repeat) = - first_repeated_key_within(value, &mut format!("$defs.{definition}"), read) - { - return Some(repeat); - } - } - None +) -> Option { + schema_defs.into_iter().flatten().find_map(|(name, value)| { + first_repeated_key_within(value, &mut format!("$defs.{name}"), read) + }) } -/// [`first_repeated_doctype_key`] over `value`, found at `path` within the schema (empty at -/// its root), and everything it holds. +/// The first repeated key of `value`, found at `path` within the schema (empty at its +/// root), and of everything it holds. fn first_repeated_key_within( value: &Value, path: &mut String, read: &mut u64, -) -> Option<(String, String)> { +) -> Option { *read = read.saturating_add(1); match value { Value::Map(map) => { @@ -173,7 +193,10 @@ fn first_repeated_key_within( continue; }; if !declared.insert(key) { - return Some((key.to_string(), path.clone())); + return Some(RepeatedKey { + key: key.to_string(), + path: path.clone(), + }); } let len = path.len(); if !path.is_empty() { diff --git a/packages/rs-dpp/src/data_contract/methods/validate_update/v1/mod.rs b/packages/rs-dpp/src/data_contract/methods/validate_update/v1/mod.rs index 3ba6b4423d6..8b019703175 100644 --- a/packages/rs-dpp/src/data_contract/methods/validate_update/v1/mod.rs +++ b/packages/rs-dpp/src/data_contract/methods/validate_update/v1/mod.rs @@ -145,7 +145,7 @@ mod tests { #[test] fn should_validate_required_since_on_document_types_added_by_the_update() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(14).expect("expected protocol version 14"); let old_data_contract = get_data_contract_fixture( None, @@ -262,7 +262,7 @@ mod tests { #[test] fn should_reject_a_token_added_by_the_update_whose_release_totals_over_the_limit() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(14).expect("expected protocol version 14"); let over_limit_releases: [&[TokenAmount]; 2] = [ &[i64::MAX as TokenAmount + 1], &[i64::MAX as TokenAmount, 1], @@ -290,7 +290,7 @@ mod tests { #[test] fn should_accept_a_token_added_by_the_update_whose_release_totals_the_limit() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(14).expect("expected protocol version 14"); let (old_data_contract, new_data_contract) = contract_and_its_update( BTreeMap::new(), @@ -311,7 +311,7 @@ mod tests { /// the ones it carries over. #[test] fn should_not_judge_the_release_totals_of_tokens_the_contract_already_had() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(14).expect("expected protocol version 14"); let legacy_token = token_releasing(&[i64::MAX as TokenAmount, 1]); let (old_data_contract, new_data_contract) = contract_and_its_update( @@ -350,7 +350,7 @@ mod tests { /// error. #[test] fn should_refuse_a_defs_change_under_a_keyword_without_a_shared_rule() { - let platform_version = PlatformVersion::latest(); + let platform_version = PlatformVersion::get(14).expect("expected protocol version 14"); let defs = |max_properties: u64| { platform_value!({ "lastName": { "type": "string" }, diff --git a/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs b/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs index c4a888e3d1a..93ac88f72d3 100644 --- a/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs +++ b/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs @@ -1,8 +1,11 @@ use crate::block::block_info::BlockInfo; +use crate::consensus::state::data_contract::data_contract_update_action_not_allowed_error::DataContractUpdateActionNotAllowedError; use crate::consensus::state::data_contract::document_type_update_error::DocumentTypeUpdateError; use crate::data_contract::accessors::v0::DataContractV0Getters; use crate::data_contract::document_type::accessors::DocumentTypeV0Getters; -use crate::data_contract::document_type::class_methods::first_repeated_doctype_key; +use crate::data_contract::document_type::class_methods::{ + first_repeated_key_of_definitions, first_repeated_key_of_schema, +}; use crate::data_contract::schema::DataContractSchemaMethodsV0; use crate::data_contract::DataContract; use crate::validation::SimpleConsensusValidationResult; @@ -40,31 +43,41 @@ impl DataContract { } /// Refuses the update when an object of a stored document type's schema, or of the - /// stored `$defs` its parse reads, names a key more than once, as registration from - /// protocol version 15 refuses a schema that does - /// ([`first_repeated_doctype_key`], the same walk). The walk is linear in the size of the - /// stored contract, which the update already fetched and pays for. + /// stored `$defs` a type's parse reads, names a key more than once, as registration from + /// protocol version 15 refuses a schema that does (the same walk). A type's schema is + /// reported on the type, `$defs` on the contract. + /// + /// The walk reads each stored schema and the stored `$defs` once, so it is linear in the + /// size of the stored contract, which the update already fetched and pays for: the count + /// of values read, which registration bills on a refusal, is not billed here. fn validate_update_stored_schemas_repeat_no_key(&self) -> SimpleConsensusValidationResult { - let schema_defs = self.schema_defs(); + let mut read = 0; for (name, document_type) in self.document_types() { - let mut read = 0; - let Some((key, path)) = - first_repeated_doctype_key(document_type.schema(), schema_defs, &mut read) - else { - continue; - }; - let place = if path.is_empty() { - "at its root".to_string() - } else { - format!("at `{path}`") - }; + if let Some(repeated) = first_repeated_key_of_schema(document_type.schema(), &mut read) + { + return SimpleConsensusValidationResult::new_with_error( + DocumentTypeUpdateError::new( + self.id(), + name, + format!( + "its stored schema declares `{}` more than once {}, and a \ + contract whose schema repeats a key can not be updated", + repeated.key(), + repeated.place() + ), + ) + .into(), + ); + } + } + if let Some(repeated) = first_repeated_key_of_definitions(self.schema_defs(), &mut read) { return SimpleConsensusValidationResult::new_with_error( - DocumentTypeUpdateError::new( + DataContractUpdateActionNotAllowedError::new( self.id(), - name, format!( - "its stored schema declares `{key}` more than once {place}, and a \ - contract whose schema repeats a key can not be updated" + "update a contract whose stored `$defs` declare `{}` more than once {}", + repeated.key(), + repeated.place() ), ) .into(), @@ -275,6 +288,38 @@ mod tests { Some(word(vec![integer_a()])), platform_version, ); + let result = stored + .validate_update(&updated, &BlockInfo::default(), platform_version) + .expect("expected the update to be judged"); + assert_matches!( + result.errors.as_slice(), + [ConsensusError::StateError(StateError::DataContractUpdateActionNotAllowedError(e))] + if e.action().contains("`$defs` declare `properties` more than once at `$defs.word`") + ); + } + + /// The stored `$defs` are read once, whatever the number of document types, and a + /// type's own schema is reported before them. + #[test] + fn should_report_a_stored_schema_repeating_a_key_before_the_stored_definitions() { + let platform_version = PlatformVersion::latest(); + let word = BTreeMap::from([( + "word".to_string(), + Value::Map(vec![ + (text("type"), text("string")), + (text("type"), text("string")), + ]), + )]); + let (stored, updated) = stored_and_updated( + schema(vec![string_a(), string_a()]), + Some(word), + schema(vec![string_a()]), + Some(BTreeMap::from([( + "word".to_string(), + platform_value!({ "type": "string" }), + )])), + platform_version, + ); assert_update_refused(&stored, &updated, "properties"); } @@ -295,27 +340,28 @@ mod tests { assert!(result.is_valid(), "{:?}", result.errors); } - /// Protocol version 14 selects generation 1, which this generation leaves as it was: the - /// update check of protocol version 14 judges any update as generation 1 does. + /// The rule starts with protocol version 15: before it, an update of a contract whose + /// stored schema names a key twice is judged by the rules of generation 1 alone. #[test] - fn should_judge_an_update_at_protocol_version_14_as_generation_1_does() { - let platform_version = PlatformVersion::get(14).expect("protocol version 14"); - for (stored_schema, new_schema) in [ - (schema(vec![string_a()]), schema(vec![string_a()])), + fn should_refuse_an_update_of_a_stored_schema_repeating_a_key_from_protocol_version_15() { + for (platform_version, refused) in [ ( - schema(vec![string_a(), integer_a()]), - schema(vec![integer_a()]), + PlatformVersion::get(14).expect("protocol version 14"), + false, ), + (PlatformVersion::latest(), true), ] { - let (stored, updated) = - stored_and_updated(stored_schema, None, new_schema, None, platform_version); - let dispatched = stored + let (stored, updated) = stored_and_updated( + schema(vec![string_a(), string_a()]), + None, + schema(vec![string_a()]), + None, + platform_version, + ); + let result = stored .validate_update(&updated, &BlockInfo::default(), platform_version) .expect("expected the update to be judged"); - let generation_1 = stored - .validate_update_v1(&updated, &BlockInfo::default(), platform_version) - .expect("expected the update to be judged"); - assert_eq!(dispatched.errors, generation_1.errors); + assert_eq!(!result.is_valid(), refused, "{:?}", result.errors); } } } diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/repeated_properties_update.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/repeated_properties_update.rs index 99f1fcf3490..e0559c3367b 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/repeated_properties_update.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/repeated_properties_update.rs @@ -4,6 +4,7 @@ //! contract stored with such a schema is refused. use super::*; +use crate::platform_types::platform_state::PlatformState; use dpp::consensus::basic::BasicError; use dpp::consensus::state::state_error::StateError; use dpp::data_contract::accessors::v0::DataContractV0Setters; @@ -23,6 +24,7 @@ use dpp::state_transition::data_contract_update_transition::DataContractUpdateTr use dpp::state_transition::StateTransition; use dpp::tests::fixtures::get_data_contract_fixture; use simple_signer::signer::SimpleSigner; +use std::sync::Arc; const TYPE_NAME: &str = "t"; @@ -67,23 +69,40 @@ struct Fixture { } impl Fixture { + /// A platform storing the contract whose type `t` names `properties` once, registered + /// under full validation. fn new(version: &'static PlatformVersion) -> Self { - Self::storing(version, schema(vec![integer_properties()])) + Self::with_stored(version, schema(vec![integer_properties()]), true) } /// A platform storing the contract whose type `t` has `stored_schema`, placed /// unvalidated, as a contract stored before the schema checks it misses. fn storing(version: &'static PlatformVersion, stored_schema: Value) -> Self { + Self::with_stored(version, stored_schema, false) + } + + fn with_stored( + version: &'static PlatformVersion, + stored_schema: Value, + full_validation: bool, + ) -> Self { let mut platform = TestPlatformBuilder::new() .with_initial_protocol_version(version.protocol_version) .build_with_mock_rpc() - .set_initial_state_structure(); + .with_no_core_masternodes() + .set_genesis_state(); let (identity, signer, key) = setup_identity(&mut platform, 977, dash_to_credits!(1.0)); let mut contract = get_data_contract_fixture(Some(identity.id()), 0, version.protocol_version) .data_contract_owned(); contract - .set_document_schema(TYPE_NAME, stored_schema, false, &mut Vec::new(), version) + .set_document_schema( + TYPE_NAME, + stored_schema, + full_validation, + &mut Vec::new(), + version, + ) .expect("schema parses"); platform .drive @@ -206,6 +225,55 @@ impl Fixture { .expect("create transition") } + /// Registers, through a contract create executed in a block, a new contract whose type + /// `t` has `new_schema`, and makes it the contract the fixture updates. + async fn register(&mut self, new_schema: Value) { + let create = self.contract_creation(new_schema).await; + let StateTransition::DataContractCreate(create_transition) = &create else { + panic!("expected a contract create"); + }; + let contract_id = create_transition.data_contract().id(); + assert_matches!( + self.process(&create), + StateTransitionExecutionResult::SuccessfulExecution { .. } + ); + // The create spent the nonce an update of the contract would open with + self.nonce += 1; + self.contract = self + .platform + .drive + .get_contract_with_fetch_info(contract_id.to_buffer(), false, None, self.version) + .expect("contract fetch") + .expect("contract exists") + .contract + .clone(); + } + + /// Runs the first block of the latest protocol version, and moves the chain to it. + fn upgrade_to_the_latest_protocol_version(&mut self) { + let latest = PlatformVersion::latest(); + let transaction = self.platform.drive.grove.start_transaction(); + let platform_state = self.platform.state.load(); + let mut block_platform_state = PlatformState::clone(&platform_state); + block_platform_state.set_current_protocol_version_in_consensus(latest.protocol_version); + self.platform + .perform_events_on_first_block_of_protocol_change( + &platform_state, + &mut block_platform_state, + &BlockInfo::default(), + &transaction, + self.version.protocol_version, + latest, + ) + .expect("expected the protocol change to run"); + self.platform + .drive + .commit_transaction(transaction, &latest.drive) + .expect("expected to commit the protocol change"); + self.platform.state.store(Arc::new(block_platform_state)); + self.version = latest; + } + /// The parsed type of `a` in the contract as Drive has it now. fn stored_type_of_a(&self) -> DocumentPropertyType { self.current_contract() @@ -393,3 +461,37 @@ async fn should_refuse_an_update_of_a_contract_stored_with_repeated_properties() assert_eq!(fixture.stored_type_of_a(), before); } } + +/// The same for a contract registered in a block before protocol version 15 and read +/// back after the upgrade: its update is refused in the block, paid, and the stored type +/// of `a` stays as it was. +#[tokio::test] +async fn should_refuse_an_update_of_a_contract_registered_with_repeated_properties_before_the_upgrade( +) { + for (registered, kept) in [ + ( + vec![string_properties(), integer_properties()], + integer_properties(), + ), + ( + vec![integer_properties(), string_properties()], + string_properties(), + ), + ] { + let mut fixture = Fixture::new(PlatformVersion::get(14).expect("protocol version 14")); + fixture.register(schema(registered)).await; + fixture.upgrade_to_the_latest_protocol_version(); + let before = fixture.stored_type_of_a(); + + let update = fixture.update_to(schema(vec![kept])).await; + assert_matches!( + fixture.process(&update), + StateTransitionExecutionResult::PaidConsensusError { + error: ConsensusError::StateError(StateError::DocumentTypeUpdateError(ref e)), + .. + } if e.additional_message().contains("declares `properties` more than once at its root") + ); + assert_eq!(fixture.current_contract().version(), 1); + assert_eq!(fixture.stored_type_of_a(), before); + } +} diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index 54311ba42f8..6490d41be0b 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -181,6 +181,7 @@ pub const PROTOCOL_VERSION_15: ProtocolVersion = 15; /// first entry the parser may read where every check reads the last /// (`InvalidContractStructure`), and refuses an update of a contract stored /// with one, which no JSON could have written (`DocumentTypeUpdateError`, +/// or `DataContractUpdateActionNotAllowedError` when its `$defs` hold it, /// `validate_update` 2 of `CONTRACT_VERSIONS_V7`), /// refuses a contested index whose contest its index values do not decide /// (`InvalidContractStructure`, note 19) or that is keyed by a property path or a diff --git a/packages/wasm-dpp2/src/data_contract/model.rs b/packages/wasm-dpp2/src/data_contract/model.rs index f1a60433b38..fa47b3d127c 100644 --- a/packages/wasm-dpp2/src/data_contract/model.rs +++ b/packages/wasm-dpp2/src/data_contract/model.rs @@ -1013,7 +1013,10 @@ impl DataContractWasm { /// the version must rise by exactly one, the config and every existing /// document type follow their update rules, `schemaDefs` stay compatible, /// groups and tokens are kept, and an added token's pre-programmed - /// distributions may not start before the block time. + /// distributions may not start before the block time. From protocol + /// version 15 an update of a contract whose own schema names a key twice + /// in one object is refused whatever the new contract holds; no contract + /// built from JSON has such a schema. /// /// Returns the consensus errors a refused update would carry, each with /// the `code` a rejected transition reaches JS with, or an empty array From 1da8a51e44ce2ce0a1782edcd6cb1afea51f149a Mon Sep 17 00:00:00 2001 From: QuantumExplorer Date: Tue, 17 Nov 2026 00:40:53 +0700 Subject: [PATCH 3/3] docs(dpp): name validate_update 2 in the protocol version 15 snapshot, scope the rule to updates that submit schemas The `contract_versions` comment of `PLATFORM_V15` listed every change of `CONTRACT_VERSIONS_V7` but `validate_update` 2. Generation 2's doc comment said a contract stored with a repeated schema key stays as it was stored: its schemas do, a token configuration update still changes its token configuration. Co-Authored-By: Claude Fable 5.2 --- .../src/data_contract/methods/validate_update/v2/mod.rs | 5 ++++- packages/rs-platform-version/src/version/v15.rs | 2 +- 2 files changed, 5 insertions(+), 2 deletions(-) diff --git a/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs b/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs index 93ac88f72d3..2fdb9261c8a 100644 --- a/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs +++ b/packages/rs-dpp/src/data_contract/methods/validate_update/v2/mod.rs @@ -21,7 +21,10 @@ impl DataContract { /// schema as JSON, which keeps the last entry of a repeated key, where the document type /// parser may have read the first, so they can not judge an update of it: an update of a /// contract whose stored schema repeats a key is refused. The new schema can not repeat - /// the key either, so such a contract stays as it was stored. + /// the key either, so the schemas of such a contract stay as they were stored. + /// + /// The rule is about an update that submits schemas. A token configuration update submits + /// none and stores the stored schemas and `$defs` as they are, so it does not come here. /// /// Delegating to generation 1 is safe because that generation is shipped and therefore /// frozen. The checks are independent and short-circuiting, so running the extra one first diff --git a/packages/rs-platform-version/src/version/v15.rs b/packages/rs-platform-version/src/version/v15.rs index 39945644c54..8ca0c99a1fe 100644 --- a/packages/rs-platform-version/src/version/v15.rs +++ b/packages/rs-platform-version/src/version/v15.rs @@ -954,7 +954,7 @@ pub const PLATFORM_V15: PlatformVersion = PlatformVersion { state_transition_conversion_versions: STATE_TRANSITION_CONVERSION_VERSIONS_V2, state_transition_method_versions: STATE_TRANSITION_METHOD_VERSIONS_V3, // changed: verify_hash_signature 1 refuses a high-S signature and an uncompressed-key header where the key is recovered (note 43) state_transitions: STATE_TRANSITION_VERSIONS_V5, // changed: validate_asset_lock_transaction_structure 1 drops the input cap and validate_instant_asset_lock_proof_structure 1 applies it to instant proofs only, so a chain proof redeems a lock of more than 100 inputs (note 30) - contract_versions: CONTRACT_VERSIONS_V7, // changed: parse_property_constraints 1 lets countOf and sumOf match byte array keys (note 4); validate_document 2 checks documents natively (note 6); check_document_type_schema 1 checks schemas natively at registration (note 7); contract_storage_serialization_version 2 stores contracts compiled (note 8); parse_private_document 0 parses private document types (note 13); apply_generated_from 1 admits sys.tokens.decimals (note 15); try_from_schema 4 parses lifecycle flags (note 41); validate_schema_patterns 0 bounds the patterns of a contract and registration_cost 3 estimates its fee without compiling one (note 42) + contract_versions: CONTRACT_VERSIONS_V7, // changed: parse_property_constraints 1 lets countOf and sumOf match byte array keys (note 4); validate_document 2 checks documents natively (note 6); check_document_type_schema 1 checks schemas natively at registration and validate_update 2 refuses an update of a contract stored with a schema naming a key twice (note 7); contract_storage_serialization_version 2 stores contracts compiled (note 8); parse_private_document 0 parses private document types (note 13); apply_generated_from 1 admits sys.tokens.decimals (note 15); try_from_schema 4 parses lifecycle flags (note 41); validate_schema_patterns 0 bounds the patterns of a contract and registration_cost 3 estimates its fee without compiling one (note 42) document_versions: DOCUMENT_VERSIONS_V4, identity_versions: IDENTITY_VERSIONS_V1, voting_versions: VOTING_VERSION_V3, // changed: the yes/no poll's stored info, id, parameter rules and decision rules are active (note 10), and the decision proposal's poll (note 12)