From 88124fd42a77fd5ce32900e1700297311edae7f6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:52:26 +0000 Subject: [PATCH 1/4] refactor(dpp): own the contract-bounds verdict for a document create ContractBounds::check_document_consumption yields what each type a create may consume (`consume`) needs once the bounds cover the create itself; ContractBounds::check_document_create combines it with the create's own type into one verdict a client can ask before it builds and signs. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG --- .../contract_bounds/mod.rs | 171 ++++++++++++++++++ 1 file changed, 171 insertions(+) diff --git a/packages/rs-dpp/src/identity/identity_public_key/contract_bounds/mod.rs b/packages/rs-dpp/src/identity/identity_public_key/contract_bounds/mod.rs index a640db0121b..cc7fcd9c156 100644 --- a/packages/rs-dpp/src/identity/identity_public_key/contract_bounds/mod.rs +++ b/packages/rs-dpp/src/identity/identity_public_key/contract_bounds/mod.rs @@ -1,6 +1,10 @@ #[cfg(feature = "state-transitions")] use crate::contract_group::ContractGroupMember; #[cfg(feature = "state-transitions")] +use crate::data_contract::document_type::accessors::DocumentTypeV0Getters; +#[cfg(feature = "state-transitions")] +use crate::data_contract::document_type::DocumentTypeRef; +#[cfg(feature = "state-transitions")] use crate::data_contract::TokenContractPosition; use crate::identifier::Identifier; use crate::identity::identity_public_key::contract_bounds::ContractBounds::{ @@ -251,6 +255,66 @@ impl ContractBounds { }, } } + + /// What authorizing a create of `document_type` with a key carrying these bounds needs, as + /// consensus checks it: the create's own type ([`Self::check_scope`]), then every type the + /// create may consume ([`Self::check_document_consumption`]). The first check that is not + /// `Allowed`, or `Allowed`. A client asks this before it builds and signs a create; a + /// contract group bound answers with the create's own membership, which only state can + /// confirm, and the consumed types need theirs too. + #[cfg(feature = "state-transitions")] + pub fn check_document_create( + &self, + document_type: DocumentTypeRef<'_>, + ) -> BatchedTransitionBoundsCheck { + let contract_id = document_type.data_contract_id(); + let own = self.check_scope( + contract_id, + ContractBoundsScope::DocumentType(document_type.name()), + ); + if own != BatchedTransitionBoundsCheck::Allowed { + return own; + } + self.check_document_consumption(contract_id, document_type) + .find(|check| *check != BatchedTransitionBoundsCheck::Allowed) + .unwrap_or(BatchedTransitionBoundsCheck::Allowed) + } + + /// What authorizing the documents a create of `document_type` of `contract_id` may consume + /// (`consume`) needs, once these bounds cover the create itself: one check per type in + /// [`DocumentTypeRef::consumable_document_type_names`] order. A create deletes the documents + /// it consumes with the key that signs it, so the key must be allowed to act on their types + /// as well. They are types of the create's own contract, so the contract is already + /// decided: a whole-contract bound allows them, a document-type bound allows its own type + /// only, and a contract group bound needs the contract's membership for the type. + #[cfg(feature = "state-transitions")] + pub fn check_document_consumption<'a>( + &'a self, + contract_id: Identifier, + document_type: DocumentTypeRef<'a>, + ) -> impl Iterator + 'a { + use BatchedTransitionBoundsCheck::{Allowed, Denied, RequiresContractGroupMembership}; + document_type + .consumable_document_type_names() + .into_iter() + .map(move |consumed| match self { + SingleContract { .. } => Allowed, + SingleContractDocumentType { + document_type_name, .. + } => { + if document_type_name == consumed { + Allowed + } else { + Denied + } + } + ContractGroup { id } => RequiresContractGroupMembership { + contract_group_id: *id, + contract_id, + member: ContractGroupMember::DocumentType(consumed.to_string()), + }, + }) + } } #[cfg(test)] @@ -699,3 +763,110 @@ mod batched_transition_tests { } } } + +#[cfg(all(test, feature = "state-transitions", feature = "dpns-contract"))] +mod document_create_tests { + use super::{BatchedTransitionBoundsCheck, ContractBounds}; + use crate::contract_group::ContractGroupMember; + use crate::data_contract::accessors::v0::DataContractV0Getters; + use crate::data_contract::DataContract; + use crate::identifier::Identifier; + use crate::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use crate::version::PlatformVersion; + use BatchedTransitionBoundsCheck::{Allowed, Denied, RequiresContractGroupMembership}; + + /// DPNS, whose `domain` create consumes a `preorder` and whose `preorder` consumes nothing. + fn dpns() -> DataContract { + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) + .expect("expected the bundled DPNS contract") + } + + fn document_type_bound(id: Identifier, name: &str) -> ContractBounds { + ContractBounds::SingleContractDocumentType { + id, + document_type_name: name.to_string(), + } + } + + #[test] + fn should_check_each_consumed_type_once_the_create_is_covered() { + let dpns = dpns(); + let domain = dpns.document_type_for_name("domain").expect("domain"); + let group_id = Identifier::from([7; 32]); + for (bounds, expected) in [ + (ContractBounds::SingleContract { id: dpns.id() }, Allowed), + (document_type_bound(dpns.id(), "preorder"), Allowed), + (document_type_bound(dpns.id(), "domain"), Denied), + ( + ContractBounds::ContractGroup { id: group_id }, + RequiresContractGroupMembership { + contract_group_id: group_id, + contract_id: dpns.id(), + member: ContractGroupMember::DocumentType("preorder".to_string()), + }, + ), + ] { + assert_eq!( + bounds + .check_document_consumption(dpns.id(), domain) + .collect::>(), + vec![expected], + "{bounds:?}" + ); + } + let preorder = dpns.document_type_for_name("preorder").expect("preorder"); + assert_eq!( + document_type_bound(dpns.id(), "domain") + .check_document_consumption(dpns.id(), preorder) + .count(), + 0, + "a type that consumes nothing needs no more than its own check" + ); + } + + #[test] + fn should_require_a_create_key_to_cover_its_type_and_every_type_it_consumes() { + let dpns = dpns(); + let domain = dpns.document_type_for_name("domain").expect("domain"); + let preorder = dpns.document_type_for_name("preorder").expect("preorder"); + let group_id = Identifier::from([7; 32]); + for (bounds, document_type, expected) in [ + ( + ContractBounds::SingleContract { id: dpns.id() }, + domain, + Allowed, + ), + ( + ContractBounds::SingleContract { + id: Identifier::from([1; 32]), + }, + domain, + Denied, + ), + // The create's own type is covered, the preorder it consumes is not + (document_type_bound(dpns.id(), "domain"), domain, Denied), + // The consumed type alone does not cover the create + (document_type_bound(dpns.id(), "preorder"), domain, Denied), + ( + document_type_bound(dpns.id(), "preorder"), + preorder, + Allowed, + ), + ( + ContractBounds::ContractGroup { id: group_id }, + domain, + RequiresContractGroupMembership { + contract_group_id: group_id, + contract_id: dpns.id(), + member: ContractGroupMember::DocumentType("domain".to_string()), + }, + ), + ] { + assert_eq!( + bounds.check_document_create(document_type), + expected, + "{bounds:?}" + ); + } + } +} From e24b14173559df4d04a4b1d161d4fc48d0f8c792 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:52:26 +0000 Subject: [PATCH 2/4] refactor(drive-abci): ask dpp which consumed types a bound key covers Batch advanced_structure v1 (PV14, and PV15 through v2) answers the consumed-type check of a contract-bound key through ContractBounds::check_document_consumption instead of its inline match. Edited in place: output-identical, pinned by an oracle test against the rule as shipped in v5.0.1 and by the bound-key consume reveal run at protocol version 14 and the latest, refused and accepted. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG --- .../batch/advanced_structure/v1/mod.rs | 287 +++++++++++++++--- .../tests/document/commit_reveal_lookup.rs | 118 +++++-- 2 files changed, 338 insertions(+), 67 deletions(-) diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v1/mod.rs index f9ec37005a7..0843a57e8bb 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v1/mod.rs @@ -24,7 +24,9 @@ use dpp::validation::ConsensusValidationResult; use dpp::version::PlatformVersion; -use drive::state_transition_action::batch::BatchTransitionAction; +use drive::state_transition_action::batch::{BatchTransitionAction, ResolvedContractGroupMemberships}; +use dpp::data_contract::document_type::DocumentTypeRef; +use dpp::platform_value::Identifier; use crate::execution::validation::state_transition::state_transitions::batch::action_validation::document::document_replace_transition_action::DocumentReplaceTransitionActionValidation; use crate::execution::validation::state_transition::state_transitions::batch::action_validation::document::document_delete_transition_action::DocumentDeleteTransitionActionValidation; use crate::execution::validation::state_transition::state_transitions::batch::action_validation::document::document_index_only_delete_transition_action::DocumentIndexOnlyDeleteTransitionActionValidation; @@ -219,41 +221,17 @@ impl DocumentsBatchStateTransitionStructureValidationV1 for BatchTransition { let document_type = contract .document_type_for_name(create.base().document_type_name()) .map_err(ProtocolError::from)?; - for consumed_type in document_type.consumable_document_type_names() { - let allowed = match bounds { - // The create itself is inside the contract - ContractBounds::SingleContract { .. } => true, - ContractBounds::SingleContractDocumentType { - document_type_name, - .. - } => document_type_name == consumed_type, - ContractBounds::ContractGroup { id } => { - let resolved = action - .contract_group_memberships(&contract.id()) - .ok_or(Error::Execution( - ExecutionError::CorruptedCodeExecution( - "the create's own bounds check resolved its contract's group memberships", - ), - ))?; - [ - ContractGroupMember::Contract, - ContractGroupMember::DocumentType( - consumed_type.to_string(), - ), - ] - .into_iter() - .any(|member| { - resolved.memberships.contains(&ContractGroupMembership { - contract_group_id: *id, - member, - }) - }) - } - }; - if !allowed { - out_of_bounds = true; - break 'creates; - } + // Shipped v1 (PV14; PV15 via v2) edited in place, output-identical: + // see `consumption_in_bounds_matches_the_rule_it_replaced`. + let allowed = create_consumption_in_bounds( + bounds, + contract.id(), + document_type, + action.contract_group_memberships(&contract.id()), + )?; + if !allowed { + out_of_bounds = true; + break 'creates; } } } @@ -500,3 +478,240 @@ impl DocumentsBatchStateTransitionStructureValidationV1 for BatchTransition { Ok(ConsensusValidationResult::new()) } } + +/// Whether `bounds`, already found to cover a create of `document_type` of `contract_id`, also +/// cover every type the create may consume ([`ContractBounds::check_document_consumption`]). A +/// contract group bound is answered from `memberships`, those the transformer resolved for the +/// create's contract; the batch billed that read where the create's own check used it. +fn create_consumption_in_bounds( + bounds: &ContractBounds, + contract_id: Identifier, + document_type: DocumentTypeRef<'_>, + memberships: Option<&ResolvedContractGroupMemberships>, +) -> Result { + for check in bounds.check_document_consumption(contract_id, document_type) { + let allowed = match check { + BatchedTransitionBoundsCheck::Allowed => true, + BatchedTransitionBoundsCheck::Denied => false, + BatchedTransitionBoundsCheck::RequiresContractGroupMembership { + contract_group_id, + member, + .. + } => { + let resolved = + memberships.ok_or(Error::Execution(ExecutionError::CorruptedCodeExecution( + "the create's own bounds check resolved its contract's group memberships", + )))?; + [ContractGroupMember::Contract, member] + .into_iter() + .any(|member| { + resolved.memberships.contains(&ContractGroupMembership { + contract_group_id, + member, + }) + }) + } + }; + if !allowed { + return Ok(false); + } + } + Ok(true) +} + +#[cfg(test)] +mod tests { + use super::create_consumption_in_bounds; + use crate::error::execution::ExecutionError; + use crate::error::Error; + use dpp::contract_group::{ContractGroupMember, ContractGroupMembership}; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::data_contract::conversion::json::DataContractJsonConversionMethodsV0; + use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; + use dpp::data_contract::document_type::DocumentTypeRef; + use dpp::data_contract::DataContract; + use dpp::identity::contract_bounds::ContractBounds; + use dpp::platform_value::Identifier; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::tests::json_document::json_document_to_json_value; + use dpp::version::PlatformVersion; + use drive::drive::contract_groups::types::ContractGroupMembershipsForContract; + use drive::state_transition_action::batch::ResolvedContractGroupMemberships; + use std::collections::BTreeSet; + + /// The consumed-type check of `validate_advanced_structure_from_state_v1` as it shipped in + /// PV14 (v5.0.1), copied verbatim but for the memberships, which it read from the action + /// for the create's contract. + fn shipped_rule( + bounds: &ContractBounds, + document_type: DocumentTypeRef<'_>, + memberships: Option<&ResolvedContractGroupMemberships>, + ) -> Result { + for consumed_type in document_type.consumable_document_type_names() { + let allowed = match bounds { + // The create itself is inside the contract + ContractBounds::SingleContract { .. } => true, + ContractBounds::SingleContractDocumentType { + document_type_name, .. + } => document_type_name == consumed_type, + ContractBounds::ContractGroup { id } => { + let resolved = memberships.ok_or(Error::Execution( + ExecutionError::CorruptedCodeExecution( + "the create's own bounds check resolved its contract's group memberships", + ), + ))?; + [ + ContractGroupMember::Contract, + ContractGroupMember::DocumentType(consumed_type.to_string()), + ] + .into_iter() + .any(|member| { + resolved.memberships.contains(&ContractGroupMembership { + contract_group_id: *id, + member, + }) + }) + } + }; + if !allowed { + return Ok(false); + } + } + Ok(true) + } + + /// Contracts whose document types consume others: DPNS (`domain` consumes `preorder`) and + /// the commit-reveal reference-validation fixture, parsed at `platform_version`. + fn consuming_contracts(platform_version: &PlatformVersion) -> Vec { + let fixture = json_document_to_json_value( + "tests/supporting_files/contract/reference-validation/reference-validation-contract-commit-reveal.json", + ) + .expect("expected the commit-reveal contract json"); + vec![ + load_system_data_contract(SystemDataContract::DPNS, platform_version) + .expect("expected the DPNS contract"), + DataContract::from_json(fixture, true, platform_version) + .expect("expected to parse the commit-reveal contract"), + ] + } + + fn resolved( + memberships: ContractGroupMembershipsForContract, + ) -> ResolvedContractGroupMemberships { + ResolvedContractGroupMemberships { + memberships, + fee: Default::default(), + } + } + + /// The memberships a group-bound create may find resolved for its contract: none resolved + /// at all, none held, the whole contract, or one document type or token, in the key's + /// group or another. + fn membership_cases( + type_names: &[String], + group: Identifier, + other_group: Identifier, + ) -> Vec> { + let mut cases = vec![ + None, + Some(resolved(Default::default())), + Some(resolved(ContractGroupMembershipsForContract { + contract: BTreeSet::from([group]), + ..Default::default() + })), + Some(resolved(ContractGroupMembershipsForContract { + contract: BTreeSet::from([other_group]), + ..Default::default() + })), + Some(resolved(ContractGroupMembershipsForContract { + tokens: [(0, BTreeSet::from([group]))].into(), + ..Default::default() + })), + ]; + for name in type_names { + for held_by in [group, other_group] { + cases.push(Some(resolved(ContractGroupMembershipsForContract { + document_types: [(name.clone(), BTreeSet::from([held_by]))].into(), + ..Default::default() + }))); + } + } + // Every type in the key's group at once + cases.push(Some(resolved(ContractGroupMembershipsForContract { + document_types: type_names + .iter() + .map(|name| (name.clone(), BTreeSet::from([group]))) + .collect(), + ..Default::default() + }))); + cases + } + + /// `create_consumption_in_bounds`, which asks dpp, answers exactly as the rule shipped in + /// v1 at PV14 did, on every bound kind, consuming type and membership state, error included. + #[test] + fn consumption_in_bounds_matches_the_rule_it_replaced() { + let group = Identifier::from([7; 32]); + let other_group = Identifier::from([8; 32]); + let foreign_contract = Identifier::from([9; 32]); + let mut consuming_types = 0; + for platform_version in [ + PlatformVersion::get(14).expect("expected protocol version 14"), + PlatformVersion::latest(), + ] { + for contract in consuming_contracts(platform_version) { + let type_names: Vec = contract.document_types().keys().cloned().collect(); + let mut bounds_cases = vec![ + ContractBounds::SingleContract { id: contract.id() }, + ContractBounds::SingleContract { + id: foreign_contract, + }, + ContractBounds::SingleContractDocumentType { + id: contract.id(), + document_type_name: "absent".to_string(), + }, + ContractBounds::ContractGroup { id: group }, + ]; + for name in &type_names { + for id in [contract.id(), foreign_contract] { + bounds_cases.push(ContractBounds::SingleContractDocumentType { + id, + document_type_name: name.clone(), + }); + } + } + let memberships = membership_cases(&type_names, group, other_group); + for name in &type_names { + let document_type = contract + .document_type_for_name(name) + .expect("expected the document type"); + if !document_type.consumable_document_type_names().is_empty() { + consuming_types += 1; + } + for bounds in &bounds_cases { + for resolved in &memberships { + let expected = shipped_rule(bounds, document_type, resolved.as_ref()); + let actual = create_consumption_in_bounds( + bounds, + contract.id(), + document_type, + resolved.as_ref(), + ); + assert_eq!( + format!("{actual:?}"), + format!("{expected:?}"), + "{} {name} {bounds:?} {resolved:?} at protocol version {}", + contract.id(), + platform_version.protocol_version + ); + } + } + } + } + } + assert!( + consuming_types >= 4, + "expected the grid to cover consuming types at both protocol versions, saw {consuming_types}" + ); + } +} diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/commit_reveal_lookup.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/commit_reveal_lookup.rs index 45a83377963..e0bd75f0e1a 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/commit_reveal_lookup.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/tests/document/commit_reveal_lookup.rs @@ -106,6 +106,8 @@ mod commit_reveal_lookup_tests { struct CommitRevealFixture { platform: TempPlatform, + /// The protocol version the chain runs and every transition is processed at. + platform_version: &'static PlatformVersion, contract: DataContract, rng: StdRng, alice: Writer, @@ -120,9 +122,16 @@ mod commit_reveal_lookup_tests { /// The fixture with `change` applied to the contract's JSON before it is parsed. fn new_with(change: impl FnOnce(&mut serde_json::Value)) -> Self { - let platform_version = PlatformVersion::latest(); + Self::new_at(PlatformVersion::latest(), change) + } + + /// [`Self::new_with`] on a chain running `platform_version`. + fn new_at( + platform_version: &'static PlatformVersion, + change: impl FnOnce(&mut serde_json::Value), + ) -> Self { let mut platform = TestPlatformBuilder::new() - .with_latest_protocol_version() + .with_initial_protocol_version(platform_version.protocol_version) .build_with_mock_rpc() .set_genesis_state(); @@ -161,6 +170,7 @@ mod commit_reveal_lookup_tests { Self { platform, + platform_version, contract, rng: StdRng::seed_from_u64(9061), alice, @@ -191,7 +201,7 @@ mod commit_reveal_lookup_tests { transition: &StateTransition, height: u64, ) -> StateTransitionExecutionResult { - let platform_version = PlatformVersion::latest(); + let platform_version = self.platform_version; let platform_state = self.platform.state.load(); let serialized = transition .serialize_to_bytes() @@ -263,7 +273,7 @@ mod commit_reveal_lookup_tests { absent: &[&str], token_payment_info: Option, ) -> (Document, StateTransition) { - let platform_version = PlatformVersion::latest(); + let platform_version = self.platform_version; let owner_id = self.id(who); let document_type = contract .document_type_for_name(type_name) @@ -321,7 +331,7 @@ mod commit_reveal_lookup_tests { transition: &StateTransition, level: CheckTxLevel, ) -> (Vec, Option) { - let platform_version = PlatformVersion::latest(); + let platform_version = self.platform_version; let state = self.platform.state.load(); let platform_ref = PlatformRef { drive: &self.platform.drive, @@ -342,7 +352,7 @@ mod commit_reveal_lookup_tests { /// Sets `who`'s balance to `credits`. fn set_balance(&self, who: Who, credits: Credits) { - let platform_version = PlatformVersion::latest(); + let platform_version = self.platform_version; let id = self.id(who).to_buffer(); let balance = self .platform @@ -418,7 +428,7 @@ mod commit_reveal_lookup_tests { change: impl FnOnce(&mut Document), height: u64, ) -> StateTransitionExecutionResult { - let platform_version = PlatformVersion::latest(); + let platform_version = self.platform_version; let mut replacement = document.clone(); replacement .increment_revision() @@ -456,7 +466,7 @@ mod commit_reveal_lookup_tests { document: &Document, height: u64, ) -> StateTransitionExecutionResult { - let platform_version = PlatformVersion::latest(); + let platform_version = self.platform_version; let contract = self.contract.clone(); let document_type = contract .document_type_for_name(type_name) @@ -487,7 +497,7 @@ mod commit_reveal_lookup_tests { /// Whether the `type_name` document with `id` is in state. fn document_exists(&self, type_name: &str, id: Identifier) -> bool { - let platform_version = PlatformVersion::latest(); + let platform_version = self.platform_version; let mut execution_context = StateTransitionExecutionContext::default_for_platform_version(platform_version) .expect("expected an execution context"); @@ -1279,13 +1289,15 @@ mod commit_reveal_lookup_tests { assert!(fixture.document_exists("ticket", second.id())); } - /// A key bound to the `domain` type signs a domain that reveals and - /// consumes a `preorder`: the consume deletes a document of a type outside - /// the key's bounds, so the batch is refused and the commitment stays. - #[tokio::test] - async fn should_refuse_a_reveal_consuming_outside_the_signing_keys_bounds() { - let mut fixture = CommitRevealFixture::new(); - let platform_version = PlatformVersion::latest(); + /// Mallory commits with an unbound key, then reveals and consumes the + /// commitment with a key carrying `bounds` of the fixture contract, on a + /// chain running `platform_version`. The reveal's result, and whether the + /// commitment is still stored after it. + async fn reveal_with_bound_key( + platform_version: &'static PlatformVersion, + bounds: impl FnOnce(Identifier) -> ContractBounds, + ) -> (StateTransitionExecutionResult, bool) { + let mut fixture = CommitRevealFixture::new_at(platform_version, |_| {}); let (mut identity, mut signer, unbound_key) = setup_identity_without_adding_it(4713, dash_to_credits!(0.5)); let (mut bound_key, private_key) = @@ -1298,10 +1310,7 @@ mod commit_reveal_lookup_tests { let IdentityPublicKey::V0(ref mut key) = bound_key else { panic!("expected a version 0 key") }; - key.contract_bounds = Some(ContractBounds::SingleContractDocumentType { - id: fixture.contract.id(), - document_type_name: "domain".into(), - }); + key.contract_bounds = Some(bounds(fixture.contract.id())); signer.add_identity_public_key(bound_key.clone(), private_key); identity.add_public_key(bound_key.clone()); fixture @@ -1336,17 +1345,64 @@ mod commit_reveal_lookup_tests { REVEAL_HEIGHT, ) .await; - assert_matches!( - result, - PaidConsensusError { - error: ConsensusError::SignatureError( - SignatureError::ContractBoundedKeyOutOfBoundsError(e) - ), - .. - } if *e.public_key_id() == 2, - "expected 20014 for the bound key" - ); - assert!(fixture.preorder_exists(preorder.id())); + (result, fixture.preorder_exists(preorder.id())) + } + + /// The protocol versions the consume bounds check runs at: the last + /// shipped one (14, `advanced_structure` v1) and the latest. + fn bounds_check_versions() -> [&'static PlatformVersion; 2] { + [ + PlatformVersion::get(14).expect("expected protocol version 14"), + PlatformVersion::latest(), + ] + } + + /// A key bound to the `domain` type signs a domain that reveals and + /// consumes a `preorder`: the consume deletes a document of a type outside + /// the key's bounds, so the batch is refused and the commitment stays. The + /// same at protocol version 14 as at the latest. + #[tokio::test] + async fn should_refuse_a_reveal_consuming_outside_the_signing_keys_bounds() { + for platform_version in bounds_check_versions() { + let (result, preorder_kept) = reveal_with_bound_key(platform_version, |id| { + ContractBounds::SingleContractDocumentType { + id, + document_type_name: "domain".into(), + } + }) + .await; + assert_matches!( + result, + PaidConsensusError { + error: ConsensusError::SignatureError( + SignatureError::ContractBoundedKeyOutOfBoundsError(e) + ), + .. + } if *e.public_key_id() == 2, + "expected 20014 for the bound key at protocol version {}", + platform_version.protocol_version + ); + assert!(preorder_kept); + } + } + + /// A key bound to the whole contract covers the `preorder` the reveal + /// consumes: the reveal is accepted and the commitment is gone, at + /// protocol version 14 as at the latest. + #[tokio::test] + async fn should_accept_a_reveal_consuming_inside_the_signing_keys_bounds() { + for platform_version in bounds_check_versions() { + let (result, preorder_kept) = + reveal_with_bound_key(platform_version, |id| ContractBounds::SingleContract { id }) + .await; + assert_matches!( + result, + StateTransitionExecutionResult::SuccessfulExecution { .. }, + "expected the reveal to be accepted at protocol version {}", + platform_version.protocol_version + ); + assert!(!preorder_kept); + } } /// The fixture with a `voucher`, a deletable document keyed by a unique `serial`, and a From affa464ac4b548652dd6df5845bd18b6ec41bffe Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:52:26 +0000 Subject: [PATCH 3/4] refactor(platform-wallet): take a create key's bounds verdict from dpp SigningScope::DocumentCreate asks ContractBounds::check_document_create instead of copying Drive's consumed-type rule. Same answers, a group-bound key included, which a new test pins. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG --- .../wallet/identity/network/key_selection.rs | 93 ++++++++++++------- 1 file changed, 60 insertions(+), 33 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/key_selection.rs b/packages/rs-platform-wallet/src/wallet/identity/network/key_selection.rs index a4effaa601a..aa89e5c52d6 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/key_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/key_selection.rs @@ -8,14 +8,13 @@ use dpp::consensus::signature::{ PublicKeyExpiredError, PublicKeyIsDisabledError, SignatureError, }; use dpp::consensus::ConsensusError; -use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dpp::data_contract::document_type::DocumentTypeRef; use dpp::data_contract::TokenContractPosition; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::identity_public_key::accessors::v1::IdentityPublicKeyGettersV1; use dpp::identity::identity_public_key::contract_bounds::{ - BatchedTransitionBoundsCheck, ContractBoundsScope, + BatchedTransitionBoundsCheck, ContractBounds, ContractBoundsScope, }; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; @@ -84,6 +83,12 @@ impl SigningScope<'_> { return BatchedTransitionBoundsCheck::Allowed } SigningScope::NonBatch => return BatchedTransitionBoundsCheck::Denied, + SigningScope::DocumentCreate { document_type } => { + return authentication_bounds(key) + .map_or(BatchedTransitionBoundsCheck::Allowed, |bounds| { + bounds.check_document_create(document_type) + }) + } SigningScope::DocumentType { contract_id, document_type_name, @@ -91,46 +96,24 @@ impl SigningScope<'_> { contract_id, ContractBoundsScope::DocumentType(document_type_name), ), - SigningScope::DocumentCreate { ref document_type } => ( - document_type.data_contract_id(), - ContractBoundsScope::DocumentType(document_type.name()), - ), SigningScope::Contract { contract_id } => (contract_id, ContractBoundsScope::Contract), SigningScope::Token { contract_id, position, } => (contract_id, ContractBoundsScope::Token(position)), }; - let Some(bounds) = key - .contract_bounds() - .filter(|_| key.purpose() == Purpose::AUTHENTICATION) - else { - return BatchedTransitionBoundsCheck::Allowed; - }; - let check = bounds.check_scope(contract_id, bounds_scope); - let SigningScope::DocumentCreate { ref document_type } = *self else { - return check; - }; - if check != BatchedTransitionBoundsCheck::Allowed { - return check; - } - // Drive's batch structure validation: a create deletes the documents it consumes with - // the key that signs it, so the bounds must allow each consumed type too. - let covers_consumed = document_type - .consumable_document_type_names() - .into_iter() - .all(|consumed| { - bounds.check_scope(contract_id, ContractBoundsScope::DocumentType(consumed)) - == BatchedTransitionBoundsCheck::Allowed - }); - if covers_consumed { - BatchedTransitionBoundsCheck::Allowed - } else { - BatchedTransitionBoundsCheck::Denied - } + authentication_bounds(key).map_or(BatchedTransitionBoundsCheck::Allowed, |bounds| { + bounds.check_scope(contract_id, bounds_scope) + }) } } +/// The contract bounds that limit what `key` signs: bounds limit only AUTHENTICATION keys. +fn authentication_bounds(key: &IdentityPublicKey) -> Option<&ContractBounds> { + key.contract_bounds() + .filter(|_| key.purpose() == Purpose::AUTHENTICATION) +} + /// The key of `identity` that should sign in `scope`: one of `purpose`, at one of /// `security_levels`, of one of `key_types`, that Platform would accept now AND that `signer` /// reports it can sign with. @@ -1201,4 +1184,48 @@ pub(super) mod tests { "the key bound to the created type only is skipped" ); } + + /// A create signed by a key bound to a contract group needs the group membership of the + /// created type, which only Platform can confirm: the explicit check lets it through and + /// automatic selection skips it, as before the verdict moved to dpp. + #[test] + fn should_leave_a_group_bound_create_key_to_platform() { + use dpp::contract_group::ContractGroupMember; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::PlatformVersion; + + let dpns = load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) + .expect("bundled DPNS contract"); + let scope = SigningScope::DocumentCreate { + document_type: dpns.document_type_for_name("domain").expect("domain"), + }; + let group_id = Identifier::from([7; 32]); + let group_bound = bound_key( + 1, + SecurityLevel::HIGH, + Some(ContractBounds::ContractGroup { id: group_id }), + ); + + assert_eq!( + scope.bounds_check(&group_bound), + BatchedTransitionBoundsCheck::RequiresContractGroupMembership { + contract_group_id: group_id, + contract_id: dpns.id(), + member: ContractGroupMember::DocumentType("domain".to_string()), + } + ); + check(&group_bound, scope).expect("only Platform can read the group's memberships"); + let identity = identity(vec![group_bound]); + let picked = usable_signing_key( + &identity, + &KeyFilter(|_| true), + Purpose::AUTHENTICATION, + &LEVELS, + &TYPES, + scope, + ) + .unwrap(); + assert!(picked.is_none(), "selection skips a group-bound key"); + } } From f45ab97d33c2583f3367932604de98135a2da4bd Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Fri, 30 Oct 2026 10:31:26 +0000 Subject: [PATCH 4/4] refactor(dpp): derive the contract id in check_document_consumption The contract_id parameter only ever repeated the document type's own id: every contract path that builds or re-ids a document type passes the contract's id. Read it from the document type, as check_document_create does. Drive's create_consumption_in_bounds drops the parameter too; it ignored that field of the group check. The function still does not compare the bounds' contract id, since a comparison would change the output of shipped generation v1 on foreign-contract bounds. Its doc comment now says so and points other callers to check_document_create. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG --- .../identity_public_key/contract_bounds/mod.rs | 16 ++++++++++------ .../batch/advanced_structure/v1/mod.rs | 14 +++++--------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/packages/rs-dpp/src/identity/identity_public_key/contract_bounds/mod.rs b/packages/rs-dpp/src/identity/identity_public_key/contract_bounds/mod.rs index cc7fcd9c156..c0b0bbc2b86 100644 --- a/packages/rs-dpp/src/identity/identity_public_key/contract_bounds/mod.rs +++ b/packages/rs-dpp/src/identity/identity_public_key/contract_bounds/mod.rs @@ -275,25 +275,29 @@ impl ContractBounds { if own != BatchedTransitionBoundsCheck::Allowed { return own; } - self.check_document_consumption(contract_id, document_type) + self.check_document_consumption(document_type) .find(|check| *check != BatchedTransitionBoundsCheck::Allowed) .unwrap_or(BatchedTransitionBoundsCheck::Allowed) } - /// What authorizing the documents a create of `document_type` of `contract_id` may consume - /// (`consume`) needs, once these bounds cover the create itself: one check per type in + /// What authorizing the documents a create of `document_type` may consume (`consume`) needs, + /// once these bounds cover the create itself: one check per type in /// [`DocumentTypeRef::consumable_document_type_names`] order. A create deletes the documents /// it consumes with the key that signs it, so the key must be allowed to act on their types /// as well. They are types of the create's own contract, so the contract is already /// decided: a whole-contract bound allows them, a document-type bound allows its own type /// only, and a contract group bound needs the contract's membership for the type. + /// + /// This does not compare the bounds' contract id with the document type's, so its answer + /// holds only once the bounds cover the create: on bounds of another contract it can still + /// say `Allowed`. Any other caller asks [`Self::check_document_create`], the full question. #[cfg(feature = "state-transitions")] pub fn check_document_consumption<'a>( &'a self, - contract_id: Identifier, document_type: DocumentTypeRef<'a>, ) -> impl Iterator + 'a { use BatchedTransitionBoundsCheck::{Allowed, Denied, RequiresContractGroupMembership}; + let contract_id = document_type.data_contract_id(); document_type .consumable_document_type_names() .into_iter() @@ -808,7 +812,7 @@ mod document_create_tests { ] { assert_eq!( bounds - .check_document_consumption(dpns.id(), domain) + .check_document_consumption(domain) .collect::>(), vec![expected], "{bounds:?}" @@ -817,7 +821,7 @@ mod document_create_tests { let preorder = dpns.document_type_for_name("preorder").expect("preorder"); assert_eq!( document_type_bound(dpns.id(), "domain") - .check_document_consumption(dpns.id(), preorder) + .check_document_consumption(preorder) .count(), 0, "a type that consumes nothing needs no more than its own check" diff --git a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v1/mod.rs b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v1/mod.rs index 0843a57e8bb..6ce8444e887 100644 --- a/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v1/mod.rs +++ b/packages/rs-drive-abci/src/execution/validation/state_transition/state_transitions/batch/advanced_structure/v1/mod.rs @@ -26,7 +26,6 @@ use dpp::version::PlatformVersion; use drive::state_transition_action::batch::{BatchTransitionAction, ResolvedContractGroupMemberships}; use dpp::data_contract::document_type::DocumentTypeRef; -use dpp::platform_value::Identifier; use crate::execution::validation::state_transition::state_transitions::batch::action_validation::document::document_replace_transition_action::DocumentReplaceTransitionActionValidation; use crate::execution::validation::state_transition::state_transitions::batch::action_validation::document::document_delete_transition_action::DocumentDeleteTransitionActionValidation; use crate::execution::validation::state_transition::state_transitions::batch::action_validation::document::document_index_only_delete_transition_action::DocumentIndexOnlyDeleteTransitionActionValidation; @@ -225,7 +224,6 @@ impl DocumentsBatchStateTransitionStructureValidationV1 for BatchTransition { // see `consumption_in_bounds_matches_the_rule_it_replaced`. let allowed = create_consumption_in_bounds( bounds, - contract.id(), document_type, action.contract_group_memberships(&contract.id()), )?; @@ -479,17 +477,16 @@ impl DocumentsBatchStateTransitionStructureValidationV1 for BatchTransition { } } -/// Whether `bounds`, already found to cover a create of `document_type` of `contract_id`, also -/// cover every type the create may consume ([`ContractBounds::check_document_consumption`]). A -/// contract group bound is answered from `memberships`, those the transformer resolved for the -/// create's contract; the batch billed that read where the create's own check used it. +/// Whether `bounds`, already found to cover a create of `document_type`, also cover every type +/// the create may consume ([`ContractBounds::check_document_consumption`]). A contract group +/// bound is answered from `memberships`, those the transformer resolved for the create's +/// contract; the batch billed that read where the create's own check used it. fn create_consumption_in_bounds( bounds: &ContractBounds, - contract_id: Identifier, document_type: DocumentTypeRef<'_>, memberships: Option<&ResolvedContractGroupMemberships>, ) -> Result { - for check in bounds.check_document_consumption(contract_id, document_type) { + for check in bounds.check_document_consumption(document_type) { let allowed = match check { BatchedTransitionBoundsCheck::Allowed => true, BatchedTransitionBoundsCheck::Denied => false, @@ -693,7 +690,6 @@ mod tests { let expected = shipped_rule(bounds, document_type, resolved.as_ref()); let actual = create_consumption_in_bounds( bounds, - contract.id(), document_type, resolved.as_ref(), );