From 68523e5037117585ad85747f1b79234ebfd3998d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:53:32 +0000 Subject: [PATCH 01/53] fix(platform-wallet): never sign credit or identity-update transitions with a disabled key `credit_signing_key` and the identity-update MASTER picker accepted disabled keys. Platform refuses a disabled signing key unconditionally (dpp's `verify_public_key_is_enabled` before signing, Drive's identity-signed validation after), so an identity whose lowest-id TRANSFER or MASTER key was disabled could never transfer, withdraw or update while an enabled replacement sat right next to it. Both now skip disabled keys; the MASTER picker moves into `signing_key.rs` as `master_signing_key` so it is testable. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- .../wallet/identity/network/signing_key.rs | 59 +++++++++++++++++-- .../src/wallet/identity/network/update.rs | 14 +---- 2 files changed, 55 insertions(+), 18 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 5e09f7af239..87cfd2ea7a1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -77,7 +77,21 @@ impl AvailableSigningKey for Identity { } } -/// Respect explicit keys; automatic withdrawals exhaust TRANSFER before OWNER. +/// The MASTER key that authorizes an identity update. Platform refuses a disabled signing key. +pub(super) fn master_signing_key<'a>( + identity: &'a Identity, + signer: &impl Signer, +) -> Result, dash_sdk::Error> { + identity.available_signing_key( + signer, + Purpose::AUTHENTICATION, + &[SecurityLevel::MASTER], + &[KeyType::ECDSA_SECP256K1], + false, + ) +} + +/// Respect explicit keys; automatic withdrawals exhaust enabled TRANSFER keys before OWNER. pub(super) fn credit_signing_key<'a>( identity: &'a Identity, explicit: Option<&'a IdentityPublicKey>, @@ -97,7 +111,7 @@ pub(super) fn credit_signing_key<'a>( purpose, &SecurityLevel::full_range(), &KeyType::all_key_types(), - true, + false, ) { Ok(Some(key)) => return Ok(key), Ok(None) => {} @@ -267,7 +281,7 @@ pub(super) mod tests { } #[test] - fn should_exhaust_transfer_keys_including_disabled_before_owner_fallback() { + fn should_skip_disabled_transfer_keys_before_owner_fallback() { let mut identity = identity( Purpose::TRANSFER, SecurityLevel::CRITICAL, @@ -285,10 +299,43 @@ pub(super) mod tests { let select = |ids: &[u32], allow_owner| { credit_signing_key(&identity, None, &available(ids), allow_owner).map(|k| k.id()) }; - assert_eq!(select(&[0, 1], true).unwrap(), 1); - assert_eq!(select(&[0, 2], true).unwrap(), 2); + assert_eq!( + select(&[0, 1, 2], true).unwrap(), + 2, + "Platform refuses a disabled signing key, so key 1 is never chosen" + ); + assert_eq!( + select(&[0, 1], true).unwrap(), + 0, + "only the disabled TRANSFER key is available, so OWNER signs" + ); assert_eq!(select(&[0], true).unwrap(), 0); - assert_unavailable(select(&[0], false).unwrap_err()); + assert_unavailable(select(&[1], false).unwrap_err()); + } + + #[test] + fn should_skip_a_disabled_master_key() { + let mut identity = identity( + Purpose::AUTHENTICATION, + SecurityLevel::MASTER, + KeyType::ECDSA_SECP256K1, + ); + identity + .public_keys_mut() + .get_mut(&1) + .unwrap() + .set_disabled_at(1); + let select = |identity: &Identity, ids: &[u32]| { + master_signing_key(identity, &available(ids)).map(|key| key.map(|key| key.id())) + }; + assert_eq!(select(&identity, &[1, 2]).unwrap(), Some(2)); + assert_unavailable(select(&identity, &[1]).unwrap_err()); + identity.public_keys_mut().retain(|id, _| *id == 1); + assert_eq!( + select(&identity, &[1]).unwrap(), + None, + "a disabled key is not eligible at all" + ); } #[test] diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs index 9806b257692..bc3da705911 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs @@ -8,9 +8,6 @@ use dpp::identity::accessors::IdentitySettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::Identity; use dpp::identity::IdentityPublicKey; -use dpp::identity::KeyType; -use dpp::identity::Purpose; -use dpp::identity::SecurityLevel; use dpp::platform_value::BinaryData; use dpp::prelude::Identifier; use dpp::ProtocolError; @@ -21,7 +18,7 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use crate::error::PlatformWalletError; -use super::signing_key::AvailableSigningKey; +use super::signing_key::master_signing_key; use super::*; // Borrowed-signer adapter — see `dpns.rs` for the same pattern. @@ -136,14 +133,7 @@ impl IdentityWallet { // Pick the MASTER signing key — DPP requires identity update // transitions to be authorized by MASTER specifically. - let master_key_id = identity - .available_signing_key( - signer, - Purpose::AUTHENTICATION, - &[SecurityLevel::MASTER], - &[KeyType::ECDSA_SECP256K1], - true, - )? + let master_key_id = master_signing_key(&identity, signer)? .map(|key| key.id()) .ok_or_else(|| { PlatformWalletError::InvalidIdentityData( From 0569898abd291d90aaf9a92edc9256f4792ec16d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:56:59 +0000 Subject: [PATCH 02/53] feat(dpp): add SecurityLevel::accepted_for_requirement A client choosing a signing key before it builds a batch needs the levels consensus accepts for a document type's requirement, but that rule only existed inside `combined_security_level_requirement`, which needs a built batch. `accepted_for_requirement` states it once for callers that have no transition yet; tests pin it to what consensus returns for document and token batches. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- .../identity_public_key/security_level.rs | 87 +++++++++++++++++++ 1 file changed, 87 insertions(+) diff --git a/packages/rs-dpp/src/identity/identity_public_key/security_level.rs b/packages/rs-dpp/src/identity/identity_public_key/security_level.rs index eacf4c4f2e8..8d757a2df62 100644 --- a/packages/rs-dpp/src/identity/identity_public_key/security_level.rs +++ b/packages/rs-dpp/src/identity/identity_public_key/security_level.rs @@ -105,6 +105,20 @@ impl SecurityLevel { pub fn stronger_or_equal_security_than(self: SecurityLevel, rhs: SecurityLevel) -> bool { (self as u8) <= (rhs as u8) } + + /// The levels a signing key may carry to meet `requirement`, strongest first: every level at + /// least as strong as `requirement`, except MASTER, which only a MASTER requirement admits. + /// This is the rule consensus applies to a batch (`combined_security_level_requirement`), + /// usable before a transition is built. + pub fn accepted_for_requirement(requirement: SecurityLevel) -> Vec { + if requirement == Self::MASTER { + return vec![Self::MASTER]; + } + [Self::CRITICAL, Self::HIGH, Self::MEDIUM] + .into_iter() + .filter(|level| level.stronger_or_equal_security_than(requirement)) + .collect() + } } impl std::fmt::Display for SecurityLevel { @@ -274,3 +288,76 @@ mod tests { } } } + +#[cfg(all(test, feature = "state-transitions"))] +mod accepted_for_requirement_tests { + use super::SecurityLevel; + use crate::state_transition::batch_transition::batched_transition::document_delete_transition::DocumentDeleteTransitionV0; + use crate::state_transition::batch_transition::batched_transition::{ + BatchedTransition, DocumentTransition, TokenTransition, + }; + use crate::state_transition::batch_transition::methods::v0::DocumentsBatchTransitionMethodsV0; + use crate::state_transition::batch_transition::{BatchTransition, BatchTransitionV1}; + use crate::ProtocolError; + use platform_value::Identifier; + + type RequirementFn = fn(Identifier, String) -> Result; + + fn batch(member: BatchedTransition) -> BatchTransition { + BatchTransitionV1 { + transitions: vec![member], + ..Default::default() + } + .into() + } + + #[test] + fn should_accept_what_consensus_accepts_for_a_document_batch() { + for requirement in SecurityLevel::full_range() { + let document = batch(BatchedTransition::Document(DocumentTransition::Delete( + DocumentDeleteTransitionV0::default().into(), + ))); + let consensus = document + .combined_security_level_requirement(Some(|_: Identifier, _: String| { + Ok(requirement) + })) + .unwrap(); + assert_eq!( + SecurityLevel::accepted_for_requirement(requirement), + consensus, + "{requirement:?}" + ); + } + } + + #[test] + fn should_accept_what_consensus_accepts_for_a_token_batch() { + let token = batch(BatchedTransition::Token(TokenTransition::Burn( + Default::default(), + ))); + assert_eq!( + SecurityLevel::accepted_for_requirement(SecurityLevel::CRITICAL), + token + .combined_security_level_requirement(None::) + .unwrap() + ); + } + + #[test] + fn should_list_stronger_levels_and_admit_master_only_for_master() { + use SecurityLevel::{CRITICAL, HIGH, MASTER, MEDIUM}; + assert_eq!(SecurityLevel::accepted_for_requirement(MASTER), [MASTER]); + assert_eq!( + SecurityLevel::accepted_for_requirement(CRITICAL), + [CRITICAL] + ); + assert_eq!( + SecurityLevel::accepted_for_requirement(HIGH), + [CRITICAL, HIGH] + ); + assert_eq!( + SecurityLevel::accepted_for_requirement(MEDIUM), + [CRITICAL, HIGH, MEDIUM] + ); + } +} From 956631a9ecd8b83d37260e3023d9a182430e55c5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:56:59 +0000 Subject: [PATCH 03/53] feat(dpp): check contract bounds and the non-batch rule before a transition is built `ContractBounds::check_scope` answers what `check_batched_transition` answers, for a `ContractBoundsScope` (whole contract, document type, or token) instead of a built batch member, and `check_batched_transition` now delegates to it (the existing per-transition tests pin the unchanged verdicts). `IdentityPublicKey::can_sign_non_batch` states the rule that a contract-bound AUTHENTICATION key signs only batches; a test pins it to the pre-sign check. Clients can now choose a key that Platform will accept without building the transition first. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- .../contract_bounds/mod.rs | 155 ++++++++++++++---- .../src/identity/identity_public_key/mod.rs | 7 + packages/rs-dpp/src/state_transition/mod.rs | 39 +++++ 3 files changed, 173 insertions(+), 28 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 80af5f6ccb5..a640db0121b 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,5 +1,7 @@ #[cfg(feature = "state-transitions")] use crate::contract_group::ContractGroupMember; +#[cfg(feature = "state-transitions")] +use crate::data_contract::TokenContractPosition; use crate::identifier::Identifier; use crate::identity::identity_public_key::contract_bounds::ContractBounds::{ ContractGroup, SingleContract, SingleContractDocumentType, @@ -82,6 +84,19 @@ pub enum BatchedTransitionBoundsCheck { }, } +/// The part of one contract a transition acts on, known before the transition is built. +#[cfg(feature = "state-transitions")] +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ContractBoundsScope<'a> { + /// The whole contract: every document type and every token, as in a flow that writes more + /// than one document type. + Contract, + /// One document type of the contract. + DocumentType(&'a str), + /// One token of the contract, by its position in the contract. + Token(TokenContractPosition), +} + impl ContractBounds { /// Creates a new contract bounds for the key pub fn new_from_type( @@ -184,43 +199,56 @@ impl ContractBounds { pub fn check_batched_transition( &self, transition: BatchedTransitionRef<'_>, + ) -> BatchedTransitionBoundsCheck { + match transition { + BatchedTransitionRef::Document(document) => self.check_scope( + document.data_contract_id(), + ContractBoundsScope::DocumentType(document.document_type_name()), + ), + BatchedTransitionRef::Token(token) => self.check_scope( + token.data_contract_id(), + ContractBoundsScope::Token(token.base().token_contract_position()), + ), + } + } + + /// What authorizing an action on `scope` of `contract_id` with a key carrying these bounds + /// needs: [`Self::check_batched_transition`] for a transition not built yet, so a client + /// can choose a key before it builds and signs. + #[cfg(feature = "state-transitions")] + pub fn check_scope( + &self, + contract_id: Identifier, + scope: ContractBoundsScope<'_>, ) -> BatchedTransitionBoundsCheck { use BatchedTransitionBoundsCheck::{Allowed, Denied, RequiresContractGroupMembership}; let allowed_if = |inside: bool| if inside { Allowed } else { Denied }; - match (self, transition) { - (SingleContract { id }, BatchedTransitionRef::Document(document)) => { - allowed_if(document.data_contract_id() == *id) - } - (SingleContract { id }, BatchedTransitionRef::Token(token)) => { - allowed_if(token.data_contract_id() == *id) - } + match (self, scope) { + (SingleContract { id }, _) => allowed_if(contract_id == *id), ( SingleContractDocumentType { id, document_type_name, }, - BatchedTransitionRef::Document(document), + ContractBoundsScope::DocumentType(scope_document_type_name), ) => allowed_if( - document.data_contract_id() == *id - && document.document_type_name() == document_type_name.as_str(), + contract_id == *id && scope_document_type_name == document_type_name.as_str(), ), - (SingleContractDocumentType { .. }, BatchedTransitionRef::Token(_)) => Denied, - (ContractGroup { id }, BatchedTransitionRef::Document(document)) => { - RequiresContractGroupMembership { - contract_group_id: *id, - contract_id: document.data_contract_id(), - member: ContractGroupMember::DocumentType( - document.document_type_name().to_string(), - ), - } - } - (ContractGroup { id }, BatchedTransitionRef::Token(token)) => { - RequiresContractGroupMembership { - contract_group_id: *id, - contract_id: token.data_contract_id(), - member: ContractGroupMember::Token(token.base().token_contract_position()), - } - } + ( + SingleContractDocumentType { .. }, + ContractBoundsScope::Contract | ContractBoundsScope::Token(_), + ) => Denied, + (ContractGroup { id }, scope) => RequiresContractGroupMembership { + contract_group_id: *id, + contract_id, + member: match scope { + ContractBoundsScope::Contract => ContractGroupMember::Contract, + ContractBoundsScope::DocumentType(document_type_name) => { + ContractGroupMember::DocumentType(document_type_name.to_string()) + } + ContractBoundsScope::Token(position) => ContractGroupMember::Token(position), + }, + }, } } } @@ -455,7 +483,7 @@ mod tests { #[cfg(all(test, feature = "state-transitions"))] mod batched_transition_tests { - use super::{BatchedTransitionBoundsCheck, ContractBounds}; + use super::{BatchedTransitionBoundsCheck, ContractBounds, ContractBoundsScope}; use crate::contract_group::ContractGroupMember; use crate::identifier::Identifier; use crate::state_transition::batch_transition::batched_transition::{ @@ -570,6 +598,77 @@ mod batched_transition_tests { } } + #[test] + fn should_check_a_document_type_scope_against_the_bound_contract_and_type() { + let contract = Identifier::from([0; 32]); + let check = |bounds: ContractBounds| { + bounds.check_scope(contract, ContractBoundsScope::DocumentType("profile")) + }; + for (bounds, expected) in [ + ( + ContractBounds::SingleContract { id: contract }, + BatchedTransitionBoundsCheck::Allowed, + ), + ( + ContractBounds::SingleContractDocumentType { + id: contract, + document_type_name: "profile".to_string(), + }, + BatchedTransitionBoundsCheck::Allowed, + ), + ( + ContractBounds::SingleContractDocumentType { + id: contract, + document_type_name: "contactInfo".to_string(), + }, + BatchedTransitionBoundsCheck::Denied, + ), + ( + ContractBounds::SingleContractDocumentType { + id: Identifier::from([1; 32]), + document_type_name: "profile".to_string(), + }, + BatchedTransitionBoundsCheck::Denied, + ), + ] { + assert_eq!(check(bounds.clone()), expected, "{bounds:?}"); + } + } + + #[test] + fn should_cover_the_whole_contract_only_with_a_whole_contract_bound() { + let contract = Identifier::from([0; 32]); + let check = + |bounds: ContractBounds| bounds.check_scope(contract, ContractBoundsScope::Contract); + assert_eq!( + check(ContractBounds::SingleContract { id: contract }), + BatchedTransitionBoundsCheck::Allowed + ); + assert_eq!( + check(ContractBounds::SingleContract { + id: Identifier::from([1; 32]) + }), + BatchedTransitionBoundsCheck::Denied + ); + assert_eq!( + check(ContractBounds::SingleContractDocumentType { + id: contract, + document_type_name: String::new(), + }), + BatchedTransitionBoundsCheck::Denied, + "a document-type bound never covers the rest of the contract" + ); + let group_id = Identifier::from([7; 32]); + assert_eq!( + check(ContractBounds::ContractGroup { id: group_id }), + BatchedTransitionBoundsCheck::RequiresContractGroupMembership { + contract_group_id: group_id, + contract_id: contract, + member: ContractGroupMember::Contract, + } + ); + } + #[test] fn should_defer_contract_group_bounds_to_state_with_the_member_to_look_up() { let group_id = Identifier::from([7; 32]); diff --git a/packages/rs-dpp/src/identity/identity_public_key/mod.rs b/packages/rs-dpp/src/identity/identity_public_key/mod.rs index 81cdf230868..1afc9f51469 100644 --- a/packages/rs-dpp/src/identity/identity_public_key/mod.rs +++ b/packages/rs-dpp/src/identity/identity_public_key/mod.rs @@ -168,6 +168,13 @@ impl IdentityPublicKey { self.security_level() == SecurityLevel::MASTER } + /// Whether the key may sign a transition that is not a batch. A contract-bound + /// AUTHENTICATION key signs only batches inside its bounds; consensus refuses it anywhere + /// else. + pub fn can_sign_non_batch(&self) -> bool { + self.purpose() != Purpose::AUTHENTICATION || self.contract_bounds().is_none() + } + /// Generates an identity public key with the maximum possible size based on the platform version. /// /// This method constructs a key of the largest possible size for the given platform version. diff --git a/packages/rs-dpp/src/state_transition/mod.rs b/packages/rs-dpp/src/state_transition/mod.rs index c33411e89c9..557efe69572 100644 --- a/packages/rs-dpp/src/state_transition/mod.rs +++ b/packages/rs-dpp/src/state_transition/mod.rs @@ -3010,6 +3010,45 @@ mod tests { )) } + #[cfg(feature = "state-transition-signing")] + #[test] + fn should_agree_with_the_pre_sign_rule_on_keys_that_may_sign_a_non_batch_transition() { + use crate::identity::contract_bounds::ContractBounds; + use crate::identity::identity_public_key::v0::IdentityPublicKeyV0; + use strum::IntoEnumIterator; + + let every_bounds = [ + None, + Some(ContractBounds::SingleContract { + id: Identifier::from([2; 32]), + }), + Some(ContractBounds::SingleContractDocumentType { + id: Identifier::from([2; 32]), + document_type_name: "preorder".to_string(), + }), + Some(ContractBounds::ContractGroup { + id: Identifier::from([3; 32]), + }), + ]; + let transfer = sample_transfer_st(); + for purpose in Purpose::iter() { + for contract_bounds in &every_bounds { + let key: IdentityPublicKey = IdentityPublicKeyV0 { + id: 7, + purpose, + contract_bounds: contract_bounds.clone(), + ..Default::default() + } + .into(); + assert_eq!( + key.can_sign_non_batch(), + transfer.verify_identity_key_bounds(&key).is_ok(), + "{purpose:?} {contract_bounds:?}" + ); + } + } + } + #[cfg(all(feature = "state-transition-signing", feature = "bls-signatures"))] #[test] fn should_enforce_contract_bounds_before_private_key_signing() { From 7066da04410dbb1cd53a24ba0914e121e78ab71e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 15:58:59 +0000 Subject: [PATCH 04/53] feat(platform-wallet): expose protocol-14-aware signing-key selection Clients that choose a key before they hand it to a wallet operation (Dash Evo Tool) kept private copies of the wallet's key policy because the selector was crate-private and covered only AUTHENTICATION keys for one document type. `usable_signing_key` generalizes it over purpose and a `SigningScope` (non-batch, document type, whole contract), using dpp's `check_scope` and non-batch rule for contract bounds, and keeps the split between "no eligible key" (`Ok(None)`) and "eligible key the signer cannot use" (`Err`). `check_signing_key` validates a key the caller chose with the same rules and answers with the typed error Platform returns for each refusal. `usable_authentication_key` becomes a thin wrapper over it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- packages/rs-platform-wallet/src/lib.rs | 6 +- .../src/wallet/identity/mod.rs | 4 +- .../wallet/identity/network/key_selection.rs | 418 ++++++++++++++++-- .../src/wallet/identity/network/mod.rs | 1 + 4 files changed, 387 insertions(+), 42 deletions(-) diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index 55a9695f34c..cb8ebabb1f8 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -74,9 +74,9 @@ pub use masternode::{ }; pub use wallet::core_address_key::CoreAddressPrivateKey; pub use wallet::identity::network::{ - derive_identity_auth_keypair, AutoAcceptProofSource, ContactCryptoProvider, ContactInfoOpened, - ContactInfoPublishOutcome, ContactInfoSealed, SeedBindingVerification, IDENTITY_GAP_LIMIT, - MASTER_KEY_INDEX, + check_signing_key, derive_identity_auth_keypair, usable_signing_key, AutoAcceptProofSource, + ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, ContactInfoSealed, + SeedBindingVerification, SigningScope, IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX, }; pub use wallet::identity::{ calculate_account_reference, derive_auto_accept_private_key, derive_contact_payment_address, diff --git a/packages/rs-platform-wallet/src/wallet/identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/mod.rs index 01079577e1b..56d405312ca 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/mod.rs @@ -29,7 +29,9 @@ pub use crypto::{ derive_contact_payment_addresses, derive_contact_xpub, pubkey_binds_expected_key_data, unmask_account_reference, ContactXpubData, DEFAULT_CONTACT_GAP_LIMIT, }; -pub use network::{DashPayView, IdentityWallet}; +pub use network::{ + check_signing_key, usable_signing_key, DashPayView, IdentityWallet, SigningScope, +}; pub use state::{ BlockTime, DashPayState, IdentityLocation, IdentityManager, ManagedIdentity, RegistrationIndex, }; 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 a1cde7283a6..1652c84a12a 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 @@ -1,46 +1,99 @@ -//! Choosing an authentication key to sign a document with, now that a key may carry limits -//! or contract bounds. +//! Choosing the identity key that signs a state transition, now that a key may carry limits +//! or contract bounds (protocol version 14). +use dpp::consensus::signature::InvalidSignaturePublicKeySecurityLevelError; +use dpp::consensus::signature::{ + ContractBoundedKeyNonBatchError, ContractBoundedKeyOutOfBoundsError, PublicKeyExpiredError, + PublicKeyIsDisabledError, SignatureError, +}; +use dpp::consensus::ConsensusError; 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::ContractBounds; +use dpp::identity::identity_public_key::contract_bounds::{ + BatchedTransitionBoundsCheck, ContractBoundsScope, +}; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; use dpp::prelude::Identifier; +use dpp::state_transition::errors::{ + InvalidIdentityPublicKeyTypeError, WrongPublicKeyPurposeError, +}; +use dpp::ProtocolError; -use super::signing_key::first_available; +use super::signing_key::{first_available, require_available}; use crate::util::now_ms; -/// The first AUTHENTICATION key of `identity` at one of `security_levels`, of one of -/// `key_types`, that can sign a `document_type_name` document of `contract_id` now -/// AND that `signer` reports it can sign with. +/// What a signature authorizes, as far as a key's contract bounds go. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SigningScope<'a> { + /// A transition that is not a batch: identity update, credit transfer or withdrawal, + /// contract create or update. A contract-bound AUTHENTICATION key cannot sign it. + NonBatch, + /// A batch of `document_type_name` documents of `contract_id`. + DocumentType { + contract_id: Identifier, + document_type_name: &'a str, + }, + /// A batch acting on all of `contract_id`: a token operation, or a flow that writes more + /// than one of its document types. + Contract { contract_id: Identifier }, +} + +impl SigningScope<'_> { + /// What `key`'s contract bounds say about signing in this scope. Bounds limit only + /// AUTHENTICATION keys, as in consensus. + fn bounds_check(&self, key: &IdentityPublicKey) -> BatchedTransitionBoundsCheck { + let bounds = match key.contract_bounds() { + Some(bounds) if key.purpose() == Purpose::AUTHENTICATION => bounds, + _ => return BatchedTransitionBoundsCheck::Allowed, + }; + match *self { + SigningScope::NonBatch => BatchedTransitionBoundsCheck::Denied, + SigningScope::DocumentType { + contract_id, + document_type_name, + } => bounds.check_scope( + contract_id, + ContractBoundsScope::DocumentType(document_type_name), + ), + SigningScope::Contract { contract_id } => { + bounds.check_scope(contract_id, ContractBoundsScope::Contract) + } + } + } +} + +/// 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. /// -/// A key bound to another contract, or to another document type of this contract, cannot -/// authorize the write and is skipped. A key without limits is preferred: a key with a budget -/// or an expiry is an application key, taken only when no unlimited key qualifies. A disabled -/// key is skipped, and so is a key whose expiry has passed the wall clock (the block time -/// trails it by seconds at most). What is left of a budget is not known offline; a spent key -/// is refused by Platform. +/// A key whose contract bounds do not cover `scope` is skipped, and so is a key bound to a +/// contract group: membership is state the wallet does not hold. A key without limits is +/// preferred over any key with limits, whatever their security levels: a key with a budget or +/// an expiry is an application key, taken only when no unlimited key qualifies. Within each +/// group keys go in key-id order. A disabled key is skipped, and so is a key whose expiry has +/// passed the wall clock (the block time trails it by seconds at most). What is left of a +/// budget is not known offline; a spent key is refused by Platform. /// /// `Ok(None)` means no key is eligible at all; `Err` means at least one eligible key exists /// but the signer cannot reach any of them. -pub(crate) fn usable_authentication_key<'a>( +pub fn usable_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, - contract_id: Identifier, - document_type_name: &str, + purpose: Purpose, security_levels: &[SecurityLevel], key_types: &[KeyType], + scope: SigningScope<'_>, ) -> Result, dash_sdk::Error> { let now = now_ms(); let qualifies = |key: &IdentityPublicKey| { - key.purpose() == Purpose::AUTHENTICATION + key.purpose() == purpose && security_levels.contains(&key.security_level()) && key_types.contains(&key.key_type()) - && bounds_cover(key.contract_bounds(), contract_id, document_type_name) && !key.is_disabled() && !key.is_expired_at(now) + && scope.bounds_check(key) == BatchedTransitionBoundsCheck::Allowed }; let keys = identity.public_keys(); let unlimited = keys @@ -52,25 +105,104 @@ pub(crate) fn usable_authentication_key<'a>( first_available(unlimited.chain(limited), signer) } -/// Whether a key carrying `bounds` may sign a `document_type_name` document of `contract_id`. +/// Check a key the caller chose to sign in `scope` against the rules [`usable_signing_key`] +/// applies, so an explicit choice is refused before anything is built or signed. /// -/// A contract group bound is answered by group membership, state the wallet does not hold, -/// so a group-bound key is never chosen here: the DashPay writes this picker serves are -/// signed with an unbound key or one bound to DashPay itself. -fn bounds_cover( - bounds: Option<&ContractBounds>, +/// Each refusal is the typed error Platform itself returns for it: a wrong purpose, a security +/// level outside `security_levels`, a key type outside `key_types`, a disabled key, an expired +/// key, or contract bounds that do not cover `scope`. A key bound to a contract group is +/// accepted: only Platform can read the group's memberships. A key `signer` cannot sign with +/// is refused with the signer-unavailable error. +pub fn check_signing_key( + key: &IdentityPublicKey, + signer: &impl Signer, + purpose: Purpose, + security_levels: &[SecurityLevel], + key_types: &[KeyType], + scope: SigningScope<'_>, +) -> Result<(), dash_sdk::Error> { + if key.purpose() != purpose { + return Err( + ProtocolError::WrongPublicKeyPurposeError(WrongPublicKeyPurposeError::new( + key.purpose(), + vec![purpose], + )) + .into(), + ); + } + if !security_levels.contains(&key.security_level()) { + return Err(ProtocolError::InvalidSignaturePublicKeySecurityLevelError( + InvalidSignaturePublicKeySecurityLevelError::new( + key.security_level(), + security_levels.to_vec(), + ), + ) + .into()); + } + if !key_types.contains(&key.key_type()) { + return Err(ProtocolError::InvalidIdentityPublicKeyTypeError( + InvalidIdentityPublicKeyTypeError::new(key.key_type()), + ) + .into()); + } + if key.is_disabled() { + return Err( + ProtocolError::PublicKeyIsDisabledError(PublicKeyIsDisabledError::new(key.id())).into(), + ); + } + let now = now_ms(); + if let Some(expires_at) = key.expires_at().filter(|_| key.is_expired_at(now)) { + return Err(signature_refusal(SignatureError::PublicKeyExpiredError( + PublicKeyExpiredError::new(key.id(), expires_at, now), + ))); + } + match scope.bounds_check(key) { + BatchedTransitionBoundsCheck::Allowed + | BatchedTransitionBoundsCheck::RequiresContractGroupMembership { .. } => {} + BatchedTransitionBoundsCheck::Denied if scope == SigningScope::NonBatch => { + return Err(signature_refusal( + SignatureError::ContractBoundedKeyNonBatchError( + ContractBoundedKeyNonBatchError::new(key.id()), + ), + )); + } + BatchedTransitionBoundsCheck::Denied => { + return Err(signature_refusal( + SignatureError::ContractBoundedKeyOutOfBoundsError( + ContractBoundedKeyOutOfBoundsError::new(key.id()), + ), + )); + } + } + require_available(key, signer).map(|_| ()) +} + +fn signature_refusal(error: SignatureError) -> dash_sdk::Error { + ProtocolError::ConsensusError(Box::new(ConsensusError::SignatureError(error))).into() +} + +/// The first AUTHENTICATION key of `identity` at one of `security_levels`, of one of +/// `key_types`, that can sign a `document_type_name` document of `contract_id` now AND that +/// `signer` can sign with: [`usable_signing_key`] for one document type. +pub(crate) fn usable_authentication_key<'a>( + identity: &'a Identity, + signer: &impl Signer, contract_id: Identifier, document_type_name: &str, -) -> bool { - match bounds { - None => true, - Some(ContractBounds::SingleContract { id }) => *id == contract_id, - Some(ContractBounds::SingleContractDocumentType { - id, - document_type_name: bound_document_type_name, - }) => *id == contract_id && bound_document_type_name == document_type_name, - Some(ContractBounds::ContractGroup { .. }) => false, - } + security_levels: &[SecurityLevel], + key_types: &[KeyType], +) -> Result, dash_sdk::Error> { + usable_signing_key( + identity, + signer, + Purpose::AUTHENTICATION, + security_levels, + key_types, + SigningScope::DocumentType { + contract_id, + document_type_name, + }, + ) } #[cfg(test)] @@ -78,6 +210,8 @@ mod tests { use super::super::signing_key::tests::{available, KeyFilter}; use super::*; use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; use dpp::identity::v0::IdentityV0; use dpp::identity::KeyID; @@ -163,10 +297,7 @@ mod tests { #[test] fn answers_none_when_every_candidate_is_disabled_or_expired() { let mut disabled = key(1, SecurityLevel::HIGH); - { - use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; - disabled.set_disabled_at(5); - } + disabled.set_disabled_at(5); let identity = identity(vec![ key(0, SecurityLevel::MASTER), disabled, @@ -320,4 +451,215 @@ mod tests { "unavailable but ineligible keys must not turn `None` into a signer error" ); } + + fn transfer_key(id: KeyID, contract_bounds: Option) -> IdentityPublicKey { + let mut key = bound_key(id, SecurityLevel::CRITICAL, contract_bounds); + key.set_purpose(Purpose::TRANSFER); + key + } + + fn pick_in(identity: &Identity, purpose: Purpose, scope: SigningScope<'_>) -> Option { + usable_signing_key( + identity, + &KeyFilter(|_| true), + purpose, + &SecurityLevel::full_range(), + &TYPES, + scope, + ) + .unwrap() + .map(|key| key.id()) + } + + fn whole_contract() -> SigningScope<'static> { + SigningScope::Contract { + contract_id: Identifier::from(CONTRACT), + } + } + + #[test] + fn should_rank_every_unlimited_key_before_any_limited_one_across_levels() { + let identity = identity(vec![ + key(1, SecurityLevel::CRITICAL), + key(2, SecurityLevel::HIGH).with_limits(Some(1_000), None), + ]); + assert_eq!( + pick(&identity).map(|key| key.id()), + Some(1), + "a budgeted HIGH key is not spent while an unlimited CRITICAL key qualifies" + ); + } + + #[test] + fn should_refuse_a_contract_bound_authentication_key_for_a_non_batch_transition() { + let identity = identity(vec![ + bound_key( + 1, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContract { + id: Identifier::from(CONTRACT), + }), + ), + key(2, SecurityLevel::CRITICAL), + ]); + assert_eq!( + pick_in(&identity, Purpose::AUTHENTICATION, SigningScope::NonBatch), + Some(2) + ); + } + + #[test] + fn should_not_apply_contract_bounds_to_keys_of_other_purposes() { + let bounds = Some(ContractBounds::SingleContract { + id: Identifier::from(OTHER_CONTRACT), + }); + let identity = identity(vec![transfer_key(1, bounds)]); + assert_eq!( + pick_in(&identity, Purpose::TRANSFER, SigningScope::NonBatch), + Some(1) + ); + assert_eq!( + pick_in(&identity, Purpose::TRANSFER, whole_contract()), + Some(1) + ); + } + + #[test] + fn should_cover_a_whole_contract_only_with_unbound_or_whole_contract_keys() { + let identity = identity(vec![ + bound_key( + 1, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContractDocumentType { + id: Identifier::from(CONTRACT), + document_type_name: DOCUMENT_TYPE.to_string(), + }), + ), + bound_key( + 2, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContract { + id: Identifier::from(CONTRACT), + }), + ), + ]); + assert_eq!( + pick_in(&identity, Purpose::AUTHENTICATION, whole_contract()), + Some(2), + "a document-type bound key cannot act on the rest of the contract" + ); + } + + fn check(key: &IdentityPublicKey, scope: SigningScope<'_>) -> Result<(), dash_sdk::Error> { + check_signing_key( + key, + &KeyFilter(|_| true), + Purpose::AUTHENTICATION, + &LEVELS, + &TYPES, + scope, + ) + } + + fn document_scope() -> SigningScope<'static> { + SigningScope::DocumentType { + contract_id: Identifier::from(CONTRACT), + document_type_name: DOCUMENT_TYPE, + } + } + + fn signature_error(result: Result<(), dash_sdk::Error>) -> SignatureError { + match result { + Err(dash_sdk::Error::Protocol(ProtocolError::ConsensusError(error))) => match *error { + ConsensusError::SignatureError(error) => error, + other => panic!("not a signature error: {other:?}"), + }, + other => panic!("not a consensus error: {other:?}"), + } + } + + #[test] + fn should_accept_an_explicit_key_that_qualifies() { + let far_future = now_ms() + 1_000_000; + let limited = key(1, SecurityLevel::HIGH).with_limits(Some(1), Some(far_future)); + check(&limited, document_scope()).expect("a limited key that has not expired"); + let group_bound = bound_key( + 2, + SecurityLevel::HIGH, + Some(ContractBounds::ContractGroup { + id: Identifier::from(OTHER_CONTRACT), + }), + ); + check(&group_bound, document_scope()) + .expect("group membership is left to Platform for an explicit choice"); + } + + #[test] + fn should_refuse_an_explicit_key_with_the_error_platform_returns() { + let mut wrong_purpose = key(1, SecurityLevel::HIGH); + wrong_purpose.set_purpose(Purpose::TRANSFER); + assert!(matches!( + check(&wrong_purpose, document_scope()), + Err(dash_sdk::Error::Protocol( + ProtocolError::WrongPublicKeyPurposeError(_) + )) + )); + assert!(matches!( + check(&key(1, SecurityLevel::MASTER), document_scope()), + Err(dash_sdk::Error::Protocol( + ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) + )) + )); + let mut hash160 = key(1, SecurityLevel::HIGH); + hash160.set_key_type(KeyType::ECDSA_HASH160); + assert!(matches!( + check(&hash160, document_scope()), + Err(dash_sdk::Error::Protocol( + ProtocolError::InvalidIdentityPublicKeyTypeError(_) + )) + )); + let mut disabled = key(1, SecurityLevel::HIGH); + disabled.set_disabled_at(5); + assert!(matches!( + check(&disabled, document_scope()), + Err(dash_sdk::Error::Protocol( + ProtocolError::PublicKeyIsDisabledError(_) + )) + )); + let expired = key(1, SecurityLevel::HIGH).with_limits(None, Some(1)); + assert!(matches!( + signature_error(check(&expired, document_scope())), + SignatureError::PublicKeyExpiredError(error) if error.expires_at() == 1 + )); + assert!(matches!( + signature_error(check(&bound_elsewhere(1), document_scope())), + SignatureError::ContractBoundedKeyOutOfBoundsError(_) + )); + let bound_here = bound_key( + 1, + SecurityLevel::HIGH, + Some(ContractBounds::SingleContract { + id: Identifier::from(CONTRACT), + }), + ); + assert!(matches!( + signature_error(check(&bound_here, SigningScope::NonBatch)), + SignatureError::ContractBoundedKeyNonBatchError(_) + )); + } + + #[test] + fn should_refuse_an_explicit_key_the_signer_cannot_use() { + let err = check_signing_key( + &key(1, SecurityLevel::HIGH), + &available(&[]), + Purpose::AUTHENTICATION, + &LEVELS, + &TYPES, + document_scope(), + ) + .unwrap_err() + .to_string(); + assert!(err.contains(SIGNER_KEY_UNAVAILABLE_PREFIX), "{err}"); + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index 8e121a95005..4d0bc358377 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -51,6 +51,7 @@ mod transfer; mod transfer_to_addresses; mod update; pub(crate) use key_selection::usable_authentication_key; +pub use key_selection::{check_signing_key, usable_signing_key, SigningScope}; mod withdrawal; pub(crate) use withdrawal::{select_owner_withdrawal_key, select_transfer_withdrawal_key}; From ed4fb7d016dc41e94b0c88b382faccc9c8b8d4c4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:08:31 +0000 Subject: [PATCH 05/53] fix(platform-wallet): choose protocol-14-aware keys for DPNS, contact-request and document writes DPNS registration and marketplace writes, contact-request send and generic document create picked the first key at an accepted level, ignoring contract bounds, expiry and limits: an identity holding a key bound to another contract or document type (or a spent application key) got that key and a refused transition. They now go through `usable_signing_key` via a shared `document_signing_key` (levels from `SecurityLevel::accepted_for_requirement`, which replaces the wallet's own copy of that rule). DPNS registration asks for a key covering the whole DPNS contract, since it writes `preorder` then `domain`. The explicit-key document flows (replace, delete, transfer, set price, purchase) now check the chosen key with `check_signing_key` against the document type's requirement and bounds, so a key Platform would refuse is refused before anything is built, with Platform's own typed error. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- .../identity/network/contact_requests.rs | 72 ++++- .../src/wallet/identity/network/document.rs | 298 ++++++++++++------ .../src/wallet/identity/network/dpns.rs | 76 +++-- .../identity/network/dpns_marketplace.rs | 41 +-- .../wallet/identity/network/key_selection.rs | 8 +- 5 files changed, 338 insertions(+), 157 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index aaff5afd70d..93f79ec0bbd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -1,6 +1,5 @@ //! DashPay contact request lifecycle: send, sync, accept, reject. -use super::signing_key::AvailableSigningKey; use dpp::document::DocumentV0Getters; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -613,17 +612,7 @@ impl DashPayView<'_, B> { }; // 5. Build the signing key reference for document signing. - let identity_public_key = sender_identity - // Contact-request send writes a document state transition, - // which DPP requires to be signed by a HIGH-or-stricter - // authentication key. MASTER is rejected on document writes. - .available_signing_key( - signer, - Purpose::AUTHENTICATION, - &[SecurityLevel::HIGH, SecurityLevel::CRITICAL], - &[KeyType::ECDSA_SECP256K1], - false, - )? + let identity_public_key = contact_request_signing_key(&sender_identity, signer)? .cloned() .ok_or_else(|| { PlatformWalletError::InvalidIdentityData( @@ -1178,6 +1167,25 @@ fn select_recipient_key_index(recipient_identity: &Identity) -> Result( + identity: &'a Identity, + signer: &impl Signer, +) -> Result, dash_sdk::Error> { + super::document::document_signing_key( + identity, + signer, + SecurityLevel::HIGH, + super::key_selection::SigningScope::DocumentType { + contract_id: dpp::data_contracts::SystemDataContract::Dashpay.id(), + document_type_name: "contactRequest", + }, + ) +} + /// Select our OWN ECDH root key: the first **enabled** `ECDSA_SECP256K1` /// ENCRYPTION key on the identity (`BTreeMap` order → lowest key id). /// @@ -5916,3 +5924,43 @@ mod pending_enqueue_tests { assert_eq!(backend.writes.load(Ordering::SeqCst), 1); } } + +#[cfg(test)] +mod contact_request_key_tests { + use super::super::key_selection::tests::{bound_key, identity, key}; + use super::super::signing_key::tests::KeyFilter; + use super::*; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + + #[test] + fn should_sign_a_contact_request_with_a_key_bound_to_contact_requests_or_unbound() { + let dashpay = dpp::data_contracts::SystemDataContract::Dashpay.id(); + let bound_to = |id, document_type_name: &str| { + bound_key( + id, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContractDocumentType { + id: dashpay, + document_type_name: document_type_name.to_string(), + }), + ) + }; + let pick = |identity: &Identity| { + contact_request_signing_key(identity, &KeyFilter(|_| true)) + .unwrap() + .map(|key| key.id()) + }; + assert_eq!( + pick(&identity(vec![ + bound_to(1, "contactInfo"), + key(2, SecurityLevel::HIGH) + ])), + Some(2), + "a key bound to contactInfo cannot sign a contact request" + ); + assert_eq!( + pick(&identity(vec![bound_to(1, "contactRequest")])), + Some(1) + ); + } +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index 0ddd1586b80..576a585ef97 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -27,7 +27,7 @@ //! post-broadcast GroveDB proof-verification recursion. The owner's //! balance the proof carries (from protocol version 14) is kept. -use super::signing_key::{require_available, AvailableSigningKey}; +use super::key_selection::{check_signing_key, usable_signing_key, SigningScope}; use std::collections::BTreeMap; use std::sync::Arc; @@ -45,7 +45,7 @@ use dpp::fee::Credits; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; -use dpp::identity::{IdentityPublicKey, KeyType, Purpose, SecurityLevel}; +use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; use dpp::platform_value::{BinaryData, Value}; use dpp::prelude::{DataContract, Identifier}; use dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions; @@ -101,37 +101,40 @@ where } } -/// Build the set of `SecurityLevel`s an AUTHENTICATION key may carry to -/// satisfy a document state-transition whose document type requires -/// `requirement`. -/// -/// This reproduces the consensus rule the network enforces in -/// `BatchTransition::combined_security_level_requirement` -/// (`rs-dpp/.../batch_transition/methods/v0/mod.rs`): the signing key's -/// security level must be **stronger-or-equal** to the document type's -/// requirement, expressed as the inclusive range `CRITICAL..=requirement` -/// over the `MASTER(0) < CRITICAL(1) < HIGH(2) < MEDIUM(3)` ordering — -/// with `MASTER` handled as its own degenerate `[MASTER]` set. MASTER is -/// otherwise excluded: it is reserved for identity-self-modification and -/// the document-batch purpose requirement (`vec![AUTHENTICATION]`) never -/// admits it for an ordinary document create. -/// -/// Picking the key against this exact set (rather than a hardcoded -/// CRITICAL, which the contract-create path uses) is what makes the -/// flow correct for *any* document type — e.g. DPNS `preorder` requires -/// `HIGH`, so both `CRITICAL` and `HIGH` keys qualify, but `MEDIUM` does -/// not. -pub(super) fn allowed_signing_security_levels(requirement: SecurityLevel) -> Vec { - if requirement == SecurityLevel::MASTER { - return vec![SecurityLevel::MASTER]; - } - // `CRITICAL as u8 == 1`; iterate down to (and including) the - // requirement. `SecurityLevel::try_from` only fails for values - // outside 0..=3, and every value in this range is valid by - // construction. - (SecurityLevel::CRITICAL as u8..=requirement as u8) - .filter_map(|level| SecurityLevel::try_from(level).ok()) - .collect() +/// The key that signs a document batch in `scope` whose document type requires +/// `requirement`: an AUTHENTICATION, ECDSA_SECP256K1 key at a level consensus accepts. +pub(super) fn document_signing_key<'a>( + identity: &'a Identity, + signer: &impl Signer, + requirement: SecurityLevel, + scope: SigningScope<'_>, +) -> Result, dash_sdk::Error> { + usable_signing_key( + identity, + signer, + Purpose::AUTHENTICATION, + &SecurityLevel::accepted_for_requirement(requirement), + &[KeyType::ECDSA_SECP256K1], + scope, + ) +} + +/// Check a key the caller chose to sign a document batch in `scope` whose document type +/// requires `requirement`, by the rules [`document_signing_key`] applies. +fn check_document_signing_key( + key: &IdentityPublicKey, + signer: &impl Signer, + requirement: SecurityLevel, + scope: SigningScope<'_>, +) -> Result<(), dash_sdk::Error> { + check_signing_key( + key, + signer, + Purpose::AUTHENTICATION, + &SecurityLevel::accepted_for_requirement(requirement), + &[KeyType::ECDSA_SECP256K1], + scope, + ) } impl IdentityWallet { @@ -168,8 +171,8 @@ impl IdentityWallet { /// 3. Selects the signing `IdentityPublicKey` from the in-memory /// wallet manager: an AUTHENTICATION-purpose, ECDSA_SECP256K1 /// key whose security level satisfies the document type's - /// `security_level_requirement()` (see - /// [`allowed_signing_security_levels`]). Returns a clear error + /// `security_level_requirement()` and whose bounds cover the + /// document type (see [`document_signing_key`]). Returns a clear error /// if the owner identity isn't loaded or carries no qualifying /// key. /// 4. Broadcasts via @@ -275,7 +278,6 @@ impl IdentityWallet { // the document type's requirement (NOT a fixed CRITICAL like // the contract-create path). let required_level = document_type.security_level_requirement(); - let allowed_levels = allowed_signing_security_levels(required_level); let signing_key = { let wm = self.wallet_manager.read().await; let info = wm.get_wallet_info(&self.wallet_id).ok_or_else(|| { @@ -289,22 +291,23 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*owner_identity_id))?; drop(wm); - identity - .available_signing_key( - signer, - Purpose::AUTHENTICATION, - &allowed_levels, - &[KeyType::ECDSA_SECP256K1], - false, - )? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "No ECDSA authentication key at a security level satisfying \ - {required_level} found on owner identity {owner_identity_id} \ - (required to sign a {document_type_name} document state transition)" - )) - })? - .clone() + document_signing_key( + &identity, + signer, + required_level, + SigningScope::DocumentType { + contract_id: *contract_id, + document_type_name, + }, + )? + .ok_or_else(|| { + PlatformWalletError::InvalidIdentityData(format!( + "No usable ECDSA authentication key at a security level satisfying \ + {required_level} found on owner identity {owner_identity_id} \ + (required to sign a {document_type_name} document state transition)" + )) + })? + .clone() }; // 4. Broadcast via `PutDocument` on the platform-wallet 8 MB @@ -429,9 +432,10 @@ impl IdentityWallet { /// AUTHENTICATION key by security level), the mutate flows take an /// explicit `signing_key_id` chosen by the caller's key picker, so /// the user keeps control of which key signs. We still enforce the - /// document state-transition signing rule here: the key must exist, - /// be AUTHENTICATION-purpose, and be ECDSA_SECP256K1 — the same - /// purpose `create` uses (see + /// document state-transition signing rules here: the key must exist + /// and pass [`check_document_signing_key`] — AUTHENTICATION-purpose, + /// ECDSA_SECP256K1, at an accepted level, enabled, unexpired and inside + /// its contract bounds — the same rules `create` uses (see /// `project_document_signing_key_purpose_bug`: signing with a /// non-AUTHENTICATION key, e.g. a TRANSFER/CRITICAL key, is rejected /// by consensus with "requires AUTHENTICATION"). @@ -439,8 +443,19 @@ impl IdentityWallet { &self, owner_identity_id: &Identifier, signing_key_id: u32, + data_contract: &DataContract, + document_type_name: &str, signer: &impl Signer, ) -> Result { + let requirement = data_contract + .document_type_for_name(document_type_name) + .map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Document type {document_type_name:?} not found on contract {}: {e}", + data_contract.id() + )) + })? + .security_level_requirement(); let wm = self.wallet_manager.read().await; let info = wm.get_wallet_info(&self.wallet_id).ok_or_else(|| { PlatformWalletError::WalletNotFound( @@ -461,21 +476,15 @@ impl IdentityWallet { )) })? .clone(); - if key.purpose() != Purpose::AUTHENTICATION { - return Err(PlatformWalletError::InvalidIdentityData(format!( - "Signing key {signing_key_id} on identity {owner_identity_id} has purpose {:?}, \ - but a document state transition must be signed with an AUTHENTICATION key", - key.purpose() - ))); - } - if key.key_type() != KeyType::ECDSA_SECP256K1 { - return Err(PlatformWalletError::InvalidIdentityData(format!( - "Signing key {signing_key_id} on identity {owner_identity_id} has key type {:?}, \ - but a document state transition must be signed with an ECDSA_SECP256K1 key", - key.key_type() - ))); - } - require_available(&key, signer)?; + check_document_signing_key( + &key, + signer, + requirement, + SigningScope::DocumentType { + contract_id: data_contract.id(), + document_type_name, + }, + )?; Ok(key) } @@ -549,7 +558,13 @@ impl IdentityWallet { })?; let signing_key = self - .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) + .resolve_authentication_signing_key( + owner_identity_id, + signing_key_id, + &data_contract, + document_type_name, + signer, + ) .await?; let builder = DocumentReplaceTransitionBuilder::new( @@ -598,7 +613,13 @@ impl IdentityWallet { .await?; let signing_key = self - .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) + .resolve_authentication_signing_key( + owner_identity_id, + signing_key_id, + &data_contract, + document_type_name, + signer, + ) .await?; // Delete is keyed by (document_id, owner_id); no current-document @@ -668,7 +689,7 @@ impl IdentityWallet { let (values, created_at) = values_from_json(properties_json)?; let builder = DocumentDeleteTransitionBuilder::from_values( - data_contract, + Arc::clone(&data_contract), document_type_name.to_string(), *document_id, *owner_identity_id, @@ -679,7 +700,13 @@ impl IdentityWallet { .map_err(delete_preparation_error)?; let signing_key = self - .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) + .resolve_authentication_signing_key( + owner_identity_id, + signing_key_id, + &data_contract, + document_type_name, + signer, + ) .await?; let DocumentDeleteResult::Deleted(deleted_id) = self @@ -732,7 +759,13 @@ impl IdentityWallet { })?; let signing_key = self - .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) + .resolve_authentication_signing_key( + owner_identity_id, + signing_key_id, + &data_contract, + document_type_name, + signer, + ) .await?; let builder = DocumentTransferTransitionBuilder::new( @@ -795,7 +828,13 @@ impl IdentityWallet { })?; let signing_key = self - .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) + .resolve_authentication_signing_key( + owner_identity_id, + signing_key_id, + &data_contract, + document_type_name, + signer, + ) .await?; let builder = DocumentSetPriceTransitionBuilder::new( @@ -861,7 +900,13 @@ impl IdentityWallet { })?; let signing_key = self - .resolve_authentication_signing_key(purchaser_identity_id, signing_key_id, signer) + .resolve_authentication_signing_key( + purchaser_identity_id, + signing_key_id, + &data_contract, + document_type_name, + signer, + ) .await?; let builder = DocumentPurchaseTransitionBuilder::new( @@ -941,7 +986,13 @@ mod tests { let signer = lock_checking_signer(wallet.identity()); let error = wallet .identity() - .resolve_authentication_signing_key(&Identifier::default(), 1, &signer) + .resolve_authentication_signing_key( + &Identifier::default(), + 1, + &super::super::dashpay_contract().unwrap(), + "contactRequest", + &signer, + ) .await .unwrap_err(); assert!( @@ -986,39 +1037,82 @@ mod tests { ); } + use super::super::key_selection::tests::{bound_key, identity, key}; + use super::super::signing_key::tests::KeyFilter; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + + const CONTRACT: [u8; 32] = [0xDA; 32]; + + fn scope() -> SigningScope<'static> { + SigningScope::DocumentType { + contract_id: Identifier::from(CONTRACT), + document_type_name: "note", + } + } + + fn pick(identity: &Identity, requirement: SecurityLevel) -> Option { + document_signing_key(identity, &KeyFilter(|_| true), requirement, scope()) + .unwrap() + .map(|key| key.id()) + } + + fn bound_elsewhere(id: u32, level: SecurityLevel) -> IdentityPublicKey { + bound_key( + id, + level, + Some(ContractBounds::SingleContract { + id: Identifier::from([0x0E; 32]), + }), + ) + } + #[test] - fn allowed_levels_high_requirement_admits_critical_and_high_only() { - // DPNS `preorder` requires HIGH: CRITICAL + HIGH qualify, - // MEDIUM does not, MASTER is excluded. - let levels = allowed_signing_security_levels(SecurityLevel::HIGH); - assert_eq!(levels, vec![SecurityLevel::CRITICAL, SecurityLevel::HIGH]); + fn should_choose_a_document_key_whose_bounds_cover_the_document_type() { + let identity = identity(vec![ + bound_elsewhere(1, SecurityLevel::CRITICAL), + key(2, SecurityLevel::HIGH), + ]); + assert_eq!(pick(&identity, SecurityLevel::HIGH), Some(2)); } #[test] - fn allowed_levels_medium_requirement_admits_critical_high_medium() { - let levels = allowed_signing_security_levels(SecurityLevel::MEDIUM); - assert_eq!( - levels, - vec![ - SecurityLevel::CRITICAL, - SecurityLevel::HIGH, - SecurityLevel::MEDIUM - ] - ); + fn should_choose_an_unlimited_document_key_before_a_limited_one() { + let identity = identity(vec![ + key(1, SecurityLevel::CRITICAL).with_limits(Some(1_000), None), + key(2, SecurityLevel::HIGH), + ]); + assert_eq!(pick(&identity, SecurityLevel::HIGH), Some(2)); } #[test] - fn allowed_levels_critical_requirement_admits_only_critical() { - let levels = allowed_signing_security_levels(SecurityLevel::CRITICAL); - assert_eq!(levels, vec![SecurityLevel::CRITICAL]); + fn should_choose_only_levels_the_document_type_accepts() { + let identity = identity(vec![ + key(0, SecurityLevel::MASTER), + key(1, SecurityLevel::MEDIUM), + key(2, SecurityLevel::HIGH), + ]); + assert_eq!(pick(&identity, SecurityLevel::HIGH), Some(2)); + assert_eq!(pick(&identity, SecurityLevel::CRITICAL), None); + assert_eq!(pick(&identity, SecurityLevel::MEDIUM), Some(1)); } #[test] - fn allowed_levels_master_requirement_is_master_only() { - // Degenerate case mirrored from the consensus rule: a MASTER - // requirement collapses to the single `[MASTER]` set rather - // than the CRITICAL..=MASTER range (which would be empty). - let levels = allowed_signing_security_levels(SecurityLevel::MASTER); - assert_eq!(levels, vec![SecurityLevel::MASTER]); + fn should_refuse_an_explicit_document_key_platform_would_refuse() { + let check = |key: &IdentityPublicKey| { + check_document_signing_key(key, &KeyFilter(|_| true), SecurityLevel::HIGH, scope()) + }; + check(&key(1, SecurityLevel::HIGH)).expect("a HIGH key meets a HIGH requirement"); + assert!( + check(&key(1, SecurityLevel::MEDIUM)).is_err(), + "MEDIUM is below the requirement" + ); + assert!( + check(&bound_elsewhere(1, SecurityLevel::HIGH)).is_err(), + "the key is bound to another contract" + ); + assert!( + check(&key(1, SecurityLevel::HIGH).with_limits(None, Some(1))).is_err(), + "the key has expired" + ); } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index 3dfb096b407..529dea169fd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -1,13 +1,12 @@ //! DPNS name registration, resolution, search, and contest queries. -use super::signing_key::AvailableSigningKey; +use super::document::document_signing_key; +use super::key_selection::SigningScope; use dpp::fee::Credits; use dpp::identity::Identity; use dpp::identity::IdentityPublicKey; -use dpp::identity::KeyType; -use dpp::identity::Purpose; use dpp::identity::SecurityLevel; use dpp::prelude::Identifier; @@ -42,6 +41,23 @@ use super::*; /// without forcing a clone or `Arc` round-trip per call. struct SignerRef<'a, S: ?Sized>(&'a S); +/// The key that signs both DPNS registration documents, `preorder` then `domain`: a HIGH or +/// CRITICAL AUTHENTICATION ECDSA key whose bounds cover the whole DPNS contract. MASTER is +/// reserved for identity operations and refused on document writes. +fn dpns_registration_signing_key<'a>( + identity: &'a Identity, + signer: &impl Signer, +) -> Result, dash_sdk::Error> { + document_signing_key( + identity, + signer, + SecurityLevel::HIGH, + SigningScope::Contract { + contract_id: dpp::data_contracts::SystemDataContract::DPNS.id(), + }, + ) +} + impl<'a, S: ?Sized> std::fmt::Debug for SignerRef<'a, S> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("SignerRef") @@ -223,24 +239,10 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; drop(wm); - // DPNS name registration writes a document state transition, - // which DPP requires to be signed by a HIGH-or-stricter - // authentication key. MASTER is intentionally excluded — - // it's reserved for identity-self-modification operations - // (identity update, key rotation, withdrawal) and is - // rejected by the protocol on document-side state - // transitions. - let key = identity - .available_signing_key( - signer, - Purpose::AUTHENTICATION, - &[SecurityLevel::HIGH, SecurityLevel::CRITICAL], - &[KeyType::ECDSA_SECP256K1], - false, - )? + let key = dpns_registration_signing_key(&identity, signer)? .ok_or_else(|| { PlatformWalletError::InvalidIdentityData( - "No HIGH or CRITICAL authentication key found on identity \ + "No usable HIGH or CRITICAL authentication key found on identity \ (required for document state transitions)" .to_string(), ) @@ -548,3 +550,39 @@ impl IdentityWallet { }) } } + +#[cfg(test)] +mod signing_key_tests { + use super::super::key_selection::tests::{bound_key, identity, key}; + use super::super::signing_key::tests::KeyFilter; + use super::*; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + + #[test] + fn should_register_with_a_key_that_covers_both_dpns_document_types() { + let dpns = dpp::data_contracts::SystemDataContract::DPNS.id(); + let identity = identity(vec![ + key(0, SecurityLevel::MASTER), + bound_key( + 1, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContractDocumentType { + id: dpns, + document_type_name: "domain".to_string(), + }), + ), + bound_key( + 2, + SecurityLevel::HIGH, + Some(ContractBounds::SingleContract { id: dpns }), + ), + ]); + let chosen = dpns_registration_signing_key(&identity, &KeyFilter(|_| true)).unwrap(); + assert_eq!( + chosen.map(|key| key.id()), + Some(2), + "a key bound to `domain` cannot sign the `preorder` document" + ); + } +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index a448db29490..2a9c7451baf 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -26,7 +26,6 @@ //! purchase/transfer; a name inside an active contested-name vote is not //! in the documents tree at all. -use super::signing_key::AvailableSigningKey; use std::collections::{BTreeMap, BTreeSet, VecDeque}; use std::sync::Arc; @@ -36,7 +35,7 @@ use dpp::fee::Credits; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; -use dpp::identity::{IdentityPublicKey, KeyType, Purpose}; +use dpp::identity::IdentityPublicKey; use dpp::platform_value::btreemap_extensions::BTreeValueMapHelper; use dpp::platform_value::Value; use dpp::prelude::{DataContract, Identifier}; @@ -55,7 +54,8 @@ use crate::changeset::{ use crate::error::PlatformWalletError; use crate::wallet::identity::types::key_storage::DpnsNameInfo; -use super::document::allowed_signing_security_levels; +use super::document::document_signing_key; +use super::key_selection::SigningScope; use super::*; /// DPNS document type carrying registered names. @@ -949,8 +949,8 @@ impl IdentityWallet { /// Auto-select the signing key for a DPNS `domain` state transition /// on `identity_id`: the identity's first AUTHENTICATION-purpose /// ECDSA_SECP256K1 key whose security level satisfies the document - /// type's requirement (the same consensus rule - /// [`allowed_signing_security_levels`] encodes). Replaces the app + /// type's requirement and whose bounds cover `domain` (see + /// [`document_signing_key`]). Replaces the app /// layer's hardcoded "key id 1". async fn select_dpns_signing_key( &self, @@ -966,7 +966,6 @@ impl IdentityWallet { )) })? .security_level_requirement(); - let allowed_levels = allowed_signing_security_levels(required_level); let wm = self.wallet_manager.read().await; let info = wm.get_wallet_info(&self.wallet_id).ok_or_else(|| { PlatformWalletError::WalletNotFound( @@ -979,22 +978,23 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; drop(wm); - identity - .available_signing_key( - signer, - Purpose::AUTHENTICATION, - &allowed_levels, - &[KeyType::ECDSA_SECP256K1], - false, - )? - .cloned() - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "No ECDSA authentication key at a security level satisfying \ + document_signing_key( + &identity, + signer, + required_level, + SigningScope::DocumentType { + contract_id: contract.id(), + document_type_name: DPNS_DOCUMENT_TYPE, + }, + )? + .cloned() + .ok_or_else(|| { + PlatformWalletError::InvalidIdentityData(format!( + "No usable ECDSA authentication key at a security level satisfying \ {required_level} found on identity {identity_id} \ (required to sign a DPNS domain state transition)" - )) - }) + )) + }) } // ----------------------------------------------------------------- @@ -2281,6 +2281,7 @@ mod tests { use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; use dpp::identity::accessors::IdentitySettersV0; use dpp::identity::SecurityLevel; + use dpp::identity::{KeyType, Purpose}; fn name_state_entry( document_id: Identifier, 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 1652c84a12a..1b31738ae8b 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 @@ -206,7 +206,7 @@ pub(crate) fn usable_authentication_key<'a>( } #[cfg(test)] -mod tests { +pub(super) mod tests { use super::super::signing_key::tests::{available, KeyFilter}; use super::*; use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; @@ -222,11 +222,11 @@ mod tests { const OTHER_CONTRACT: [u8; 32] = [0x0E; 32]; const DOCUMENT_TYPE: &str = "profile"; - fn key(id: KeyID, security_level: SecurityLevel) -> IdentityPublicKey { + pub(crate) fn key(id: KeyID, security_level: SecurityLevel) -> IdentityPublicKey { bound_key(id, security_level, None) } - fn bound_key( + pub(crate) fn bound_key( id: KeyID, security_level: SecurityLevel, contract_bounds: Option, @@ -243,7 +243,7 @@ mod tests { }) } - fn identity(keys: Vec) -> Identity { + pub(crate) fn identity(keys: Vec) -> Identity { IdentityV0 { id: Identifier::from([1; 32]), public_keys: keys From 7998aff4b40eb26d8f07e7f56fcae0378215649f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:08:31 +0000 Subject: [PATCH 06/53] fix(platform-wallet): choose protocol-14-aware keys for token, contract, identity-update and credit transitions Token operations, contract create/update, identity update and credit transfer/withdrawal now pick their key with `usable_signing_key`: tokens ask for a key covering the token's whole contract (a document-type bound key cannot sign them), the non-batch transitions skip contract-bound AUTHENTICATION keys that Platform refuses outside a batch, and unlimited keys are taken before budgeted ones. The signer-aware `AvailableSigningKey` trait has no callers left and is removed; its tests now exercise `usable_signing_key`. Contract create keeps its CRITICAL-only level set. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- .../src/wallet/identity/network/contract.rs | 34 +----- .../wallet/identity/network/signing_key.rs | 111 ++++++++++-------- .../wallet/identity/network/tokens/burn.rs | 4 +- .../wallet/identity/network/tokens/claim.rs | 4 +- .../network/tokens/destroy_frozen_funds.rs | 4 +- .../wallet/identity/network/tokens/freeze.rs | 4 +- .../wallet/identity/network/tokens/helpers.rs | 67 +++++++++-- .../wallet/identity/network/tokens/mint.rs | 4 +- .../wallet/identity/network/tokens/pause.rs | 4 +- .../identity/network/tokens/purchase.rs | 4 +- .../wallet/identity/network/tokens/resume.rs | 4 +- .../identity/network/tokens/set_price.rs | 4 +- .../identity/network/tokens/transfer.rs | 2 +- .../identity/network/tokens/unfreeze.rs | 4 +- .../identity/network/tokens/update_config.rs | 4 +- 15 files changed, 159 insertions(+), 99 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs index ffa31f95316..45b86d6a81b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs @@ -26,7 +26,7 @@ //! the rs-sdk-ffi path — classic stack-guard fingerprint, not //! memory unsafety. -use super::signing_key::AvailableSigningKey; +use super::signing_key::contract_signing_key; use async_trait::async_trait; use dpp::address_funds::AddressWitness; @@ -34,7 +34,7 @@ use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::serialized_version::DataContractInSerializationFormat; use dpp::data_contract::INITIAL_DATA_CONTRACT_VERSION; use dpp::identity::signer::Signer; -use dpp::identity::{IdentityPublicKey, KeyType, PartialIdentity, Purpose, SecurityLevel}; +use dpp::identity::{IdentityPublicKey, PartialIdentity}; use dpp::platform_value::BinaryData; use dpp::prelude::{DataContract, Identifier}; use dpp::state_transition::data_contract_update_transition::methods::DataContractUpdateTransitionMethodsV0; @@ -162,21 +162,10 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*owner_identity_id))?; drop(wm); - // Contract create requires CRITICAL + AUTHENTICATION + - // ECDSA_SECP256K1 specifically — DPP rejects HIGH / - // MEDIUM / non-ECDSA keys on this state-transition - // shape. - identity - .available_signing_key( - signer, - Purpose::AUTHENTICATION, - &[SecurityLevel::CRITICAL], - &[KeyType::ECDSA_SECP256K1], - false, - )? + contract_signing_key(&identity, signer)? .ok_or_else(|| { PlatformWalletError::InvalidIdentityData( - "No CRITICAL authentication key found on owner identity \ + "No usable CRITICAL authentication key found on owner identity \ (required to sign a contract-create state transition)" .to_string(), ) @@ -387,21 +376,10 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*owner_identity_id))?; drop(wm); - // Contract update requires the same CRITICAL + - // AUTHENTICATION + ECDSA_SECP256K1 key as create — DPP - // rejects HIGH / MEDIUM / non-ECDSA keys on this - // state-transition shape. - identity - .available_signing_key( - signer, - Purpose::AUTHENTICATION, - &[SecurityLevel::CRITICAL], - &[KeyType::ECDSA_SECP256K1], - false, - )? + contract_signing_key(&identity, signer)? .ok_or_else(|| { PlatformWalletError::InvalidIdentityData( - "No CRITICAL authentication key found on owner identity \ + "No usable CRITICAL authentication key found on owner identity \ (required to sign a contract-update state transition)" .to_string(), ) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 87cfd2ea7a1..23cb03b0301 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -1,7 +1,7 @@ //! Signer-aware identity key selection shared by wallet operations. +use super::key_selection::{usable_signing_key, SigningScope}; use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; -use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; @@ -44,37 +44,20 @@ pub(super) fn first_available<'a>( unavailable.map_or(Ok(None), |key| Err(signing_key_unavailable(key))) } -/// Signer-aware `get_first_public_key_matching`: key-ID order, same eligibility policy. -/// Call on an identity snapshot, outside wallet manager guards. -/// `Ok(None)` means no eligible key; `Err` means eligible keys are unavailable. -pub(super) trait AvailableSigningKey { - fn available_signing_key( - &self, - signer: &impl Signer, - purpose: Purpose, - security_levels: &[SecurityLevel], - key_types: &[KeyType], - allow_disabled: bool, - ) -> Result, dash_sdk::Error>; -} - -impl AvailableSigningKey for Identity { - fn available_signing_key( - &self, - signer: &impl Signer, - purpose: Purpose, - security_levels: &[SecurityLevel], - key_types: &[KeyType], - allow_disabled: bool, - ) -> Result, dash_sdk::Error> { - let eligible = self.public_keys().values().filter(|key| { - key.purpose() == purpose - && security_levels.contains(&key.security_level()) - && key_types.contains(&key.key_type()) - && (allow_disabled || !key.is_disabled()) - }); - first_available(eligible, signer) - } +/// The key that signs a contract create or update: a CRITICAL AUTHENTICATION ECDSA key. +/// These are not batches, so a contract-bound key cannot sign them. +pub(super) fn contract_signing_key<'a>( + identity: &'a Identity, + signer: &impl Signer, +) -> Result, dash_sdk::Error> { + usable_signing_key( + identity, + signer, + Purpose::AUTHENTICATION, + &[SecurityLevel::CRITICAL], + &[KeyType::ECDSA_SECP256K1], + SigningScope::NonBatch, + ) } /// The MASTER key that authorizes an identity update. Platform refuses a disabled signing key. @@ -82,12 +65,13 @@ pub(super) fn master_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, ) -> Result, dash_sdk::Error> { - identity.available_signing_key( + usable_signing_key( + identity, signer, Purpose::AUTHENTICATION, &[SecurityLevel::MASTER], &[KeyType::ECDSA_SECP256K1], - false, + SigningScope::NonBatch, ) } @@ -106,12 +90,13 @@ pub(super) fn credit_signing_key<'a>( .into_iter() .chain(allow_owner.then_some(Purpose::OWNER)) { - match identity.available_signing_key( + match usable_signing_key( + identity, signer, purpose, &SecurityLevel::full_range(), &KeyType::all_key_types(), - false, + SigningScope::NonBatch, ) { Ok(Some(key)) => return Ok(key), Ok(None) => {} @@ -133,6 +118,7 @@ pub(super) mod tests { use super::*; use async_trait::async_trait; use dpp::address_funds::AddressWitness; + use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; use dpp::platform_value::BinaryData; @@ -235,15 +221,15 @@ pub(super) mod tests { ineligible.set_purpose(Purpose::ENCRYPTION); identity.add_public_key(ineligible); let select = |identity: &Identity, ids: &[u32]| { - identity - .available_signing_key( - &available(ids), - Purpose::AUTHENTICATION, - &[SecurityLevel::HIGH], - &[KeyType::ECDSA_HASH160], - false, - ) - .map(|key| key.map(|key| key.id())) + usable_signing_key( + identity, + &available(ids), + Purpose::AUTHENTICATION, + &[SecurityLevel::HIGH], + &[KeyType::ECDSA_HASH160], + SigningScope::NonBatch, + ) + .map(|key| key.map(|key| key.id())) }; assert_eq!(select(&identity, &[2, 3]).unwrap(), Some(2)); assert_eq!(select(&identity, &[1, 2]).unwrap(), Some(1)); @@ -262,8 +248,14 @@ pub(super) mod tests { key.set_disabled_at(1); let select = |purpose, level, key_type| { let signer = available(&[1, 2]); - let key = - identity.available_signing_key(&signer, purpose, &[level], &[key_type], false); + let key = usable_signing_key( + &identity, + &signer, + purpose, + &[level], + &[key_type], + SigningScope::NonBatch, + ); key.unwrap().map(|k| k.id()) }; assert_eq!( @@ -313,6 +305,31 @@ pub(super) mod tests { assert_unavailable(select(&[1], false).unwrap_err()); } + #[test] + fn should_sign_a_contract_transition_only_with_a_key_free_of_contract_bounds() { + use super::super::key_selection::tests::{bound_key, identity as identity_of, key}; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + + let identity = identity_of(vec![ + bound_key( + 1, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContract { + id: Identifier::from([0x0C; 32]), + }), + ), + key(2, SecurityLevel::CRITICAL).with_limits(Some(1_000), None), + key(3, SecurityLevel::CRITICAL), + ]); + let chosen = contract_signing_key(&identity, &KeyFilter(|_| true)).unwrap(); + assert_eq!( + chosen.map(|key| key.id()), + Some(3), + "Platform refuses a contract-bound key outside a batch, and an unlimited key is \ + taken before a budgeted one" + ); + } + #[test] fn should_skip_a_disabled_master_key() { let mut identity = identity( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs index f8640ad1631..307930fcaae 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs @@ -63,7 +63,9 @@ impl IdentityWallet { signer: &S, ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_burn_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs index ee1edcff33d..04c4f475da5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs @@ -60,7 +60,9 @@ impl IdentityWallet { signer: &S, ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_claim_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs index 57e6b2b28f5..ef5fd151bf4 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs @@ -73,7 +73,9 @@ impl IdentityWallet { PlatformWalletError, > { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_destroy_frozen_funds_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs index 64a76f47370..d003319cbef 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs @@ -66,7 +66,9 @@ impl IdentityWallet { signer: &S, ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_freeze_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 300a32c62d3..87f2bb8aa3e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -12,18 +12,37 @@ //! all rejected by Drive. See //! `state_transitions/document/batch_transition/methods/v0/mod.rs:133-138`. -use super::super::signing_key::AvailableSigningKey; +use super::super::key_selection::{usable_signing_key, SigningScope}; use std::sync::Arc; use dpp::data_contract::DataContract; use dpp::identity::signer::Signer; -use dpp::identity::{IdentityPublicKey, KeyType, Purpose, SecurityLevel}; +use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; use dpp::prelude::Identifier; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; +/// The key that signs a token operation of `token_contract_id`: a CRITICAL AUTHENTICATION +/// ECDSA key whose bounds cover the whole contract, since token operations are contract-wide. +fn token_signing_key<'a>( + identity: &'a Identity, + token_contract_id: Identifier, + signer: &impl Signer, +) -> Result, dash_sdk::Error> { + usable_signing_key( + identity, + signer, + Purpose::AUTHENTICATION, + &[SecurityLevel::CRITICAL], + &[KeyType::ECDSA_SECP256K1], + SigningScope::Contract { + contract_id: token_contract_id, + }, + ) +} + impl IdentityWallet { /// Resolve the AUTHENTICATION signing key for token state /// transitions — used by the `_with_external_signer` variants @@ -31,13 +50,15 @@ impl IdentityWallet { /// which on-chain key id to sign with. /// /// Key selection is a fixed canonical policy: - /// `Purpose::AUTHENTICATION` × `SecurityLevel::CRITICAL` × `ECDSA_SECP256K1`. + /// `Purpose::AUTHENTICATION` × `SecurityLevel::CRITICAL` × `ECDSA_SECP256K1`, + /// bounds covering `token_contract_id` (see `token_signing_key`). /// Callers that pass a `signing_key_id` over FFI are advisory — /// this Rust path is authoritative and Drive validates the chosen /// key matches what the state transition needs. pub(super) async fn token_resolve_signing_key( &self, identity_id: &Identifier, + token_contract_id: Identifier, signer: &impl Signer, ) -> Result { let wm = self.wallet_manager.read().await; @@ -52,14 +73,7 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; drop(wm); - let signing_key = identity - .available_signing_key( - signer, - Purpose::AUTHENTICATION, - &[SecurityLevel::CRITICAL], - &[KeyType::ECDSA_SECP256K1], - false, - )? + let signing_key = token_signing_key(&identity, token_contract_id, signer)? .ok_or_else(|| { PlatformWalletError::InvalidIdentityData(format!( "No AUTHENTICATION ECDSA_SECP256K1 key at CRITICAL security level on identity {} — \ @@ -119,9 +133,38 @@ mod signing_tests { let signer = lock_checking_signer(wallet.identity()); let error = wallet .identity() - .token_resolve_signing_key(&Identifier::default(), &signer) + .token_resolve_signing_key(&Identifier::default(), Identifier::default(), &signer) .await .unwrap_err(); assert!(error.to_string().contains("available to signer"), "{error}"); } + + #[test] + fn should_sign_a_token_operation_with_a_key_that_covers_the_whole_contract() { + use crate::wallet::identity::network::key_selection::tests::{bound_key, identity, key}; + use crate::wallet::identity::network::signing_key::tests::KeyFilter; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + + let token_contract = Identifier::from([0x70; 32]); + let identity = identity(vec![ + bound_key( + 1, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContractDocumentType { + id: token_contract, + document_type_name: "note".to_string(), + }), + ), + key(2, SecurityLevel::CRITICAL).with_limits(Some(1_000), None), + key(3, SecurityLevel::CRITICAL), + ]); + let chosen = token_signing_key(&identity, token_contract, &KeyFilter(|_| true)).unwrap(); + assert_eq!( + chosen.map(|key| key.id()), + Some(3), + "a document-type bound key cannot sign a token operation, and an unlimited key \ + is taken before a budgeted one" + ); + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs index 483f613503a..4d5b7882b3b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs @@ -118,7 +118,9 @@ impl IdentityWallet { signer: &S, ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_mint_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs index 488d381db95..168aa426188 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs @@ -66,7 +66,9 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_pause_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs index a97e4858574..1ed519dc08d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs @@ -65,7 +65,9 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_purchase_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs index a55734a1a17..d766f5d8e60 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs @@ -65,7 +65,9 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_resume_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs index a23cdd874d0..fef8b33abb5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs @@ -83,7 +83,9 @@ impl IdentityWallet { use dpp::tokens::token_pricing_schedule::TokenPricingSchedule; let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; let pricing_schedule = if price_per_token == 0 { None diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs index baa692ed13b..ce3bb7dc276 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs @@ -69,7 +69,7 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&from_identity_id, signer) + .token_resolve_signing_key(&from_identity_id, token_contract_id, signer) .await?; self.token_transfer_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs index fb749d4809f..a8f1efce6d8 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs @@ -68,7 +68,9 @@ impl IdentityWallet { signer: &S, ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_unfreeze_with_signer( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs index 047b853cb2c..9194111377d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs @@ -72,7 +72,9 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; - let signing_key = self.token_resolve_signing_key(&identity_id, signer).await?; + let signing_key = self + .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .await?; self.token_update_config_with_signer( data_contract, From 68d0ed0af3ab9375e99a79e1d6e943c5ba1ca0cd Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:08:31 +0000 Subject: [PATCH 07/53] feat(platform-wallet): make select_own_encryption_key public Clients that build DashPay auto-accept proofs or contact requests need the same ECDH root key the wallet uses (the first enabled ECDSA_SECP256K1 ENCRYPTION key); exposing the selector lets them call it instead of keeping a copy that drifts. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- packages/rs-platform-wallet/src/lib.rs | 6 +++--- packages/rs-platform-wallet/src/wallet/identity/mod.rs | 3 ++- .../src/wallet/identity/network/contact_requests.rs | 2 +- .../rs-platform-wallet/src/wallet/identity/network/mod.rs | 1 + 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index cb8ebabb1f8..b33c35714e2 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -74,9 +74,9 @@ pub use masternode::{ }; pub use wallet::core_address_key::CoreAddressPrivateKey; pub use wallet::identity::network::{ - check_signing_key, derive_identity_auth_keypair, usable_signing_key, AutoAcceptProofSource, - ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, ContactInfoSealed, - SeedBindingVerification, SigningScope, IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX, + check_signing_key, derive_identity_auth_keypair, select_own_encryption_key, usable_signing_key, + AutoAcceptProofSource, ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, + ContactInfoSealed, SeedBindingVerification, SigningScope, IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX, }; pub use wallet::identity::{ calculate_account_reference, derive_auto_accept_private_key, derive_contact_payment_address, diff --git a/packages/rs-platform-wallet/src/wallet/identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/mod.rs index 56d405312ca..3d07c10b210 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/mod.rs @@ -30,7 +30,8 @@ pub use crypto::{ unmask_account_reference, ContactXpubData, DEFAULT_CONTACT_GAP_LIMIT, }; pub use network::{ - check_signing_key, usable_signing_key, DashPayView, IdentityWallet, SigningScope, + check_signing_key, select_own_encryption_key, usable_signing_key, DashPayView, IdentityWallet, + SigningScope, }; pub use state::{ BlockTime, DashPayState, IdentityLocation, IdentityManager, ManagedIdentity, RegistrationIndex, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index 93f79ec0bbd..f9093937d26 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -1196,7 +1196,7 @@ fn contact_request_signing_key<'a>( /// after a disable-and-replace key rotation, selecting the disabled /// lowest-id key would hard-fail pre-send validation on every new outgoing /// request even though an enabled replacement exists. -pub(crate) fn select_own_encryption_key( +pub fn select_own_encryption_key( identity: &Identity, ) -> Result<&IdentityPublicKey, PlatformWalletError> { identity diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index 4d0bc358377..a693bd54624 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -85,6 +85,7 @@ pub use seed_binding::SeedBindingVerification; mod tokens; pub use contact_info::ContactInfoPublishOutcome; +pub use contact_requests::select_own_encryption_key; /// Seed-backed [`ContactCryptoProvider`] for tests. Lives behind the private /// `contact_requests` module, so sibling modules reach it directly and the /// manager's tests reach it through here. From 4e57a6714d154e73bf4a84e11dd9055ef53ca466 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:11:00 +0000 Subject: [PATCH 08/53] feat(platform-wallet): expose SigningScope::bounds_check A key chooser that warns per key (outside its contract bounds, or bound to a contract group only Platform can answer for) needs the three-way bounds verdict the selector uses, not just the chosen key. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- .../wallet/identity/network/key_selection.rs | 46 +++++++++++++++++-- 1 file changed, 43 insertions(+), 3 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 1b31738ae8b..22f798cb10f 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 @@ -41,9 +41,11 @@ pub enum SigningScope<'a> { } impl SigningScope<'_> { - /// What `key`'s contract bounds say about signing in this scope. Bounds limit only - /// AUTHENTICATION keys, as in consensus. - fn bounds_check(&self, key: &IdentityPublicKey) -> BatchedTransitionBoundsCheck { + /// What `key`'s contract bounds say about signing in this scope: `Allowed`, `Denied`, or + /// `RequiresContractGroupMembership` for a group-bound key, which only Platform can answer. + /// Bounds limit only AUTHENTICATION keys, as in consensus, and a contract-bound + /// AUTHENTICATION key is `Denied` outside a batch. + pub fn bounds_check(&self, key: &IdentityPublicKey) -> BatchedTransitionBoundsCheck { let bounds = match key.contract_bounds() { Some(bounds) if key.purpose() == Purpose::AUTHENTICATION => bounds, _ => return BatchedTransitionBoundsCheck::Allowed, @@ -662,4 +664,42 @@ pub(super) mod tests { .to_string(); assert!(err.contains(SIGNER_KEY_UNAVAILABLE_PREFIX), "{err}"); } + + #[test] + fn should_report_the_bounds_verdict_for_each_scope() { + use BatchedTransitionBoundsCheck::{Allowed, Denied, RequiresContractGroupMembership}; + let contract = Identifier::from(CONTRACT); + let group_id = Identifier::from(OTHER_CONTRACT); + let group_bound = bound_key( + 1, + SecurityLevel::HIGH, + Some(ContractBounds::ContractGroup { id: group_id }), + ); + let bound_here = bound_key( + 2, + SecurityLevel::HIGH, + Some(ContractBounds::SingleContract { id: contract }), + ); + assert_eq!( + document_scope().bounds_check(&key(1, SecurityLevel::HIGH)), + Allowed + ); + assert_eq!(document_scope().bounds_check(&bound_here), Allowed); + assert_eq!(document_scope().bounds_check(&bound_elsewhere(3)), Denied); + assert_eq!(SigningScope::NonBatch.bounds_check(&bound_here), Denied); + assert_eq!( + SigningScope::NonBatch + .bounds_check(&transfer_key(4, bound_here.contract_bounds().cloned())), + Allowed, + "bounds limit only AUTHENTICATION keys" + ); + assert!(matches!( + document_scope().bounds_check(&group_bound), + RequiresContractGroupMembership { contract_group_id, .. } if contract_group_id == group_id + )); + assert!(matches!( + whole_contract().bounds_check(&group_bound), + RequiresContractGroupMembership { contract_id, .. } if contract_id == contract + )); + } } From eaecaa563b14004ba6ea4a91039f492d5bf4bc13 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Mon, 26 Oct 2026 16:15:46 +0000 Subject: [PATCH 09/53] style(platform-wallet): import key-selection helpers at the top Follow the coding conventions for the new DPNS and contact-request key pickers (no inline module paths at call sites) and move a getter import that only the document tests use into their module. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_012ujJpB9DBhvtbjhYB3aG9Q --- .../src/wallet/identity/network/contact_requests.rs | 11 +++++++---- .../src/wallet/identity/network/document.rs | 2 +- .../src/wallet/identity/network/dpns.rs | 5 +++-- 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index f9093937d26..b785072f3aa 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -1,5 +1,8 @@ //! DashPay contact request lifecycle: send, sync, accept, reject. +use super::document::document_signing_key; +use super::key_selection::SigningScope; +use dpp::data_contracts::SystemDataContract; use dpp::document::DocumentV0Getters; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -1175,12 +1178,12 @@ fn contact_request_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, ) -> Result, dash_sdk::Error> { - super::document::document_signing_key( + document_signing_key( identity, signer, SecurityLevel::HIGH, - super::key_selection::SigningScope::DocumentType { - contract_id: dpp::data_contracts::SystemDataContract::Dashpay.id(), + SigningScope::DocumentType { + contract_id: SystemDataContract::Dashpay.id(), document_type_name: "contactRequest", }, ) @@ -5934,7 +5937,7 @@ mod contact_request_key_tests { #[test] fn should_sign_a_contact_request_with_a_key_bound_to_contact_requests_or_unbound() { - let dashpay = dpp::data_contracts::SystemDataContract::Dashpay.id(); + let dashpay = SystemDataContract::Dashpay.id(); let bound_to = |id, document_type_name: &str| { bound_key( id, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index 576a585ef97..e7335f3436d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -43,7 +43,6 @@ use dpp::document::Document; use dpp::document::DocumentV0Setters; use dpp::fee::Credits; use dpp::identity::accessors::IdentityGettersV0; -use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; use dpp::platform_value::{BinaryData, Value}; @@ -1039,6 +1038,7 @@ mod tests { use super::super::key_selection::tests::{bound_key, identity, key}; use super::super::signing_key::tests::KeyFilter; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; const CONTRACT: [u8; 32] = [0xDA; 32]; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index 529dea169fd..25aa7f22332 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -2,6 +2,7 @@ use super::document::document_signing_key; use super::key_selection::SigningScope; +use dpp::data_contracts::SystemDataContract; use dpp::fee::Credits; @@ -53,7 +54,7 @@ fn dpns_registration_signing_key<'a>( signer, SecurityLevel::HIGH, SigningScope::Contract { - contract_id: dpp::data_contracts::SystemDataContract::DPNS.id(), + contract_id: SystemDataContract::DPNS.id(), }, ) } @@ -561,7 +562,7 @@ mod signing_key_tests { #[test] fn should_register_with_a_key_that_covers_both_dpns_document_types() { - let dpns = dpp::data_contracts::SystemDataContract::DPNS.id(); + let dpns = SystemDataContract::DPNS.id(); let identity = identity(vec![ key(0, SecurityLevel::MASTER), bound_key( From 949f6f93737a51574ed9025def584d939f3ba452 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:04:17 +0000 Subject: [PATCH 10/53] Revert "feat(platform-wallet): make select_own_encryption_key public" This reverts commit 68d0ed0af3ab9375e99a79e1d6e943c5ba1ca0cd. --- packages/rs-platform-wallet/src/lib.rs | 6 +++--- packages/rs-platform-wallet/src/wallet/identity/mod.rs | 3 +-- .../src/wallet/identity/network/contact_requests.rs | 2 +- .../rs-platform-wallet/src/wallet/identity/network/mod.rs | 1 - 4 files changed, 5 insertions(+), 7 deletions(-) diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index b33c35714e2..cb8ebabb1f8 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -74,9 +74,9 @@ pub use masternode::{ }; pub use wallet::core_address_key::CoreAddressPrivateKey; pub use wallet::identity::network::{ - check_signing_key, derive_identity_auth_keypair, select_own_encryption_key, usable_signing_key, - AutoAcceptProofSource, ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, - ContactInfoSealed, SeedBindingVerification, SigningScope, IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX, + check_signing_key, derive_identity_auth_keypair, usable_signing_key, AutoAcceptProofSource, + ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, ContactInfoSealed, + SeedBindingVerification, SigningScope, IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX, }; pub use wallet::identity::{ calculate_account_reference, derive_auto_accept_private_key, derive_contact_payment_address, diff --git a/packages/rs-platform-wallet/src/wallet/identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/mod.rs index 3d07c10b210..56d405312ca 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/mod.rs @@ -30,8 +30,7 @@ pub use crypto::{ unmask_account_reference, ContactXpubData, DEFAULT_CONTACT_GAP_LIMIT, }; pub use network::{ - check_signing_key, select_own_encryption_key, usable_signing_key, DashPayView, IdentityWallet, - SigningScope, + check_signing_key, usable_signing_key, DashPayView, IdentityWallet, SigningScope, }; pub use state::{ BlockTime, DashPayState, IdentityLocation, IdentityManager, ManagedIdentity, RegistrationIndex, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index e3319d1c6ce..ae31cf52396 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -1251,7 +1251,7 @@ fn contact_request_signing_key<'a>( /// after a disable-and-replace key rotation, selecting the disabled /// lowest-id key would hard-fail pre-send validation on every new outgoing /// request even though an enabled replacement exists. -pub fn select_own_encryption_key( +pub(crate) fn select_own_encryption_key( identity: &Identity, ) -> Result<&IdentityPublicKey, PlatformWalletError> { identity diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index a693bd54624..4d0bc358377 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -85,7 +85,6 @@ pub use seed_binding::SeedBindingVerification; mod tokens; pub use contact_info::ContactInfoPublishOutcome; -pub use contact_requests::select_own_encryption_key; /// Seed-backed [`ContactCryptoProvider`] for tests. Lives behind the private /// `contact_requests` module, so sibling modules reach it directly and the /// manager's tests reach it through here. From d32f7327eec0afe840c7ac96b1a876e3c7fb8b9a Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:04:39 +0000 Subject: [PATCH 11/53] refactor(platform-wallet): export key-selection helpers from the crate root only check_signing_key, usable_signing_key and SigningScope were re-exported twice: from the crate root and again from wallet::identity. One public path is enough; the crate root keeps them. Co-Authored-By: Claude Opus 5.5 --- packages/rs-platform-wallet/src/wallet/identity/mod.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/mod.rs index 56d405312ca..01079577e1b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/mod.rs @@ -29,9 +29,7 @@ pub use crypto::{ derive_contact_payment_addresses, derive_contact_xpub, pubkey_binds_expected_key_data, unmask_account_reference, ContactXpubData, DEFAULT_CONTACT_GAP_LIMIT, }; -pub use network::{ - check_signing_key, usable_signing_key, DashPayView, IdentityWallet, SigningScope, -}; +pub use network::{DashPayView, IdentityWallet}; pub use state::{ BlockTime, DashPayState, IdentityLocation, IdentityManager, ManagedIdentity, RegistrationIndex, }; From c0eccaf1b270c76ebf67b2cc0c66147b73795be8 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:08:11 +0000 Subject: [PATCH 12/53] refactor(platform-wallet): take the non-batch bounds rule from dpp SigningScope::bounds_check restated dpp's rule that a contract-bound AUTHENTICATION key cannot sign a non-batch transition, leaving IdentityPublicKey::can_sign_non_batch without a non-test caller. The NonBatch arm now asks can_sign_non_batch, and a test pins the verdict to it for every purpose and bounds kind. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/key_selection.rs | 62 ++++++++++++++++--- 1 file changed, 52 insertions(+), 10 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 22f798cb10f..793e9417d5d 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 @@ -44,24 +44,27 @@ impl SigningScope<'_> { /// What `key`'s contract bounds say about signing in this scope: `Allowed`, `Denied`, or /// `RequiresContractGroupMembership` for a group-bound key, which only Platform can answer. /// Bounds limit only AUTHENTICATION keys, as in consensus, and a contract-bound - /// AUTHENTICATION key is `Denied` outside a batch. + /// AUTHENTICATION key is `Denied` outside a batch ([`IdentityPublicKey::can_sign_non_batch`]). pub fn bounds_check(&self, key: &IdentityPublicKey) -> BatchedTransitionBoundsCheck { - let bounds = match key.contract_bounds() { - Some(bounds) if key.purpose() == Purpose::AUTHENTICATION => bounds, - _ => return BatchedTransitionBoundsCheck::Allowed, - }; - match *self { - SigningScope::NonBatch => BatchedTransitionBoundsCheck::Denied, + let (contract_id, bounds_scope) = match *self { + SigningScope::NonBatch if key.can_sign_non_batch() => { + return BatchedTransitionBoundsCheck::Allowed + } + SigningScope::NonBatch => return BatchedTransitionBoundsCheck::Denied, SigningScope::DocumentType { contract_id, document_type_name, - } => bounds.check_scope( + } => ( contract_id, ContractBoundsScope::DocumentType(document_type_name), ), - SigningScope::Contract { contract_id } => { - bounds.check_scope(contract_id, ContractBoundsScope::Contract) + SigningScope::Contract { contract_id } => (contract_id, ContractBoundsScope::Contract), + }; + match key.contract_bounds() { + Some(bounds) if key.purpose() == Purpose::AUTHENTICATION => { + bounds.check_scope(contract_id, bounds_scope) } + _ => BatchedTransitionBoundsCheck::Allowed, } } } @@ -702,4 +705,43 @@ pub(super) mod tests { RequiresContractGroupMembership { contract_id, .. } if contract_id == contract )); } + + #[test] + fn should_deny_a_non_batch_signature_exactly_when_dpp_says_the_key_cannot_sign_one() { + let purposes = [ + Purpose::AUTHENTICATION, + Purpose::ENCRYPTION, + Purpose::DECRYPTION, + Purpose::TRANSFER, + Purpose::SYSTEM, + Purpose::VOTING, + Purpose::OWNER, + ]; + let contract_id = Identifier::from(CONTRACT); + let bounds = [ + None, + Some(ContractBounds::SingleContract { id: contract_id }), + Some(ContractBounds::SingleContractDocumentType { + id: contract_id, + document_type_name: DOCUMENT_TYPE.to_string(), + }), + Some(ContractBounds::ContractGroup { id: contract_id }), + ]; + for purpose in purposes { + for contract_bounds in &bounds { + let mut key = bound_key(1, SecurityLevel::HIGH, contract_bounds.clone()); + key.set_purpose(purpose); + let expected = if key.can_sign_non_batch() { + BatchedTransitionBoundsCheck::Allowed + } else { + BatchedTransitionBoundsCheck::Denied + }; + assert_eq!( + SigningScope::NonBatch.bounds_check(&key), + expected, + "{purpose:?} {contract_bounds:?}" + ); + } + } + } } From 1f17f83d9963316f6f4fcf4c5e66388cd91a1e28 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:18:59 +0000 Subject: [PATCH 13/53] feat(platform-wallet): report a missing signing key as NoUsableSigningKey The operations that pick their own signing key turned the selector's "no eligible key" answer into InvalidIdentityData(String), so a caller could only tell it apart by its text. They now return PlatformWalletError::NoUsableSigningKey with the identity, purpose, accepted security levels and the transition it was to sign: contract create/update, identity update, token operations, document create, DPNS registration and marketplace, and contact-request send. The FFI keeps it on the code InvalidIdentityData had (ErrorUnknown), so the Swift and Kotlin result enums are unchanged; the message carries the context. Co-Authored-By: Claude Opus 5.5 --- packages/rs-platform-wallet-ffi/src/error.rs | 33 +++++++ packages/rs-platform-wallet/src/error.rs | 16 +++ .../identity/network/contact_requests.rs | 18 ++-- .../src/wallet/identity/network/contract.rs | 26 +++-- .../src/wallet/identity/network/document.rs | 11 +-- .../src/wallet/identity/network/dpns.rs | 20 ++-- .../identity/network/dpns_marketplace.rs | 13 ++- .../wallet/identity/network/signing_key.rs | 99 +++++++++++++++++-- .../wallet/identity/network/tokens/helpers.rs | 40 ++++++-- .../src/wallet/identity/network/update.rs | 13 +-- 10 files changed, 222 insertions(+), 67 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 0bc67f532c9..0c84cba6627 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -971,6 +971,14 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::InputMidBroadcast { .. } => { PlatformWalletFFIResultCode::ErrorUnknown } + // No key of the identity can sign the transition. Typed on the Rust + // side, but kept on the code it had as `InvalidIdentityData`, which + // fell to the catch-all: a dedicated code must be mirrored into the + // Swift and Kotlin result enums, a separate coordinated change. The + // message names the identity, purpose, levels and transition. + PlatformWalletError::NoUsableSigningKey { .. } => { + PlatformWalletFFIResultCode::ErrorUnknown + } // A definitively-failed address-nonce race (reaches the blanket impl // via identity `top_up_from_addresses` → `?`/`.into()`). Exposing // provided/expected nonce as structured out-fields is INTENTIONALLY @@ -1365,6 +1373,31 @@ mod tests { use key_wallet::account::StandardAccountType; use key_wallet::wallet::managed_wallet_info::transaction_building::AccountTypePreference; + #[test] + fn should_keep_no_usable_signing_key_on_its_former_code_with_the_context_in_the_message() { + let identity_id = Identifier::from([7; 32]); + let mut result = PlatformWalletFFIResult::from(PlatformWalletError::NoUsableSigningKey { + identity_id, + purpose: dpp::identity::Purpose::AUTHENTICATION, + security_levels: vec![dpp::identity::SecurityLevel::CRITICAL], + transition: "an identity update".to_string(), + }); + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorUnknown); + let message = unsafe { std::ffi::CStr::from_ptr(result.message) } + .to_string_lossy() + .into_owned(); + unsafe { platform_wallet_ffi_result_free(&mut result) }; + let identity = format!("{identity_id}"); + for part in [ + identity.as_str(), + "AUTHENTICATION", + "CRITICAL", + "an identity update", + ] { + assert!(message.contains(part), "{message}"); + } + } + #[test] fn ok_has_null_message() { let r = PlatformWalletFFIResult::ok(); diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index 5696d681d2b..ec28b6cbf63 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -6,6 +6,7 @@ use dpp::consensus::state::address_funds::AddressInvalidNonceError; use dpp::consensus::ConsensusError; use dpp::fee::Credits; use dpp::identifier::Identifier; +use dpp::identity::{Purpose, SecurityLevel}; use dpp::prelude::{AddressNonce, CoreBlockHeight}; use key_wallet::account::StandardAccountType; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -85,6 +86,21 @@ pub enum PlatformWalletError { #[error("Invalid identity data: {0}")] InvalidIdentityData(String), + /// No key of the identity can sign `transition`: none has `purpose` and one of + /// `security_levels` while also being enabled, unexpired and inside its contract bounds. + /// It stays so until an identity update adds such a key. A key that qualifies but that the + /// signer cannot use is the signer-unavailable error instead. + #[error( + "identity {identity_id} has no usable {purpose} key at security level \ + {security_levels:?} to sign {transition}" + )] + NoUsableSigningKey { + identity_id: Identifier, + purpose: Purpose, + security_levels: Vec, + transition: String, + }, + /// A DashPay invitation link's voucher key is for the other network (a /// testnet link opened in a mainnet wallet, or the reverse). Definitive: /// the claim refuses the link before any network work. diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index ae31cf52396..510f5a4d974 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -620,12 +620,13 @@ impl DashPayView<'_, B> { // 5. Build the signing key reference for document signing. let identity_public_key = contact_request_signing_key(&sender_identity, signer)? .cloned() - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "Sender identity has no HIGH or CRITICAL authentication key \ - (required for document state transitions)" - .to_string(), - ) + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *sender_identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement( + CONTACT_REQUEST_REQUIREMENT, + ), + transition: "a contactRequest document transition".to_string(), })?; // 6. Client-side ECDH via the signer: the shared secret is derived in @@ -1222,6 +1223,9 @@ fn select_recipient_key_index(recipient_identity: &Identity) -> Result( document_signing_key( identity, signer, - SecurityLevel::HIGH, + CONTACT_REQUEST_REQUIREMENT, SigningScope::DocumentType { contract_id: SystemDataContract::Dashpay.id(), document_type_name: "contactRequest", diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs index 45b86d6a81b..db4a0ba6731 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs @@ -26,7 +26,7 @@ //! the rs-sdk-ffi path — classic stack-guard fingerprint, not //! memory unsafety. -use super::signing_key::contract_signing_key; +use super::signing_key::{contract_signing_key, CONTRACT_SIGNING_LEVELS}; use async_trait::async_trait; use dpp::address_funds::AddressWitness; @@ -34,7 +34,7 @@ use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::serialized_version::DataContractInSerializationFormat; use dpp::data_contract::INITIAL_DATA_CONTRACT_VERSION; use dpp::identity::signer::Signer; -use dpp::identity::{IdentityPublicKey, PartialIdentity}; +use dpp::identity::{IdentityPublicKey, PartialIdentity, Purpose}; use dpp::platform_value::BinaryData; use dpp::prelude::{DataContract, Identifier}; use dpp::state_transition::data_contract_update_transition::methods::DataContractUpdateTransitionMethodsV0; @@ -163,12 +163,11 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*owner_identity_id))?; drop(wm); contract_signing_key(&identity, signer)? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "No usable CRITICAL authentication key found on owner identity \ - (required to sign a contract-create state transition)" - .to_string(), - ) + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *owner_identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: CONTRACT_SIGNING_LEVELS.to_vec(), + transition: "a contract-create state transition".to_string(), })? .clone() }; @@ -377,12 +376,11 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*owner_identity_id))?; drop(wm); contract_signing_key(&identity, signer)? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "No usable CRITICAL authentication key found on owner identity \ - (required to sign a contract-update state transition)" - .to_string(), - ) + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *owner_identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: CONTRACT_SIGNING_LEVELS.to_vec(), + transition: "a contract-update state transition".to_string(), })? .clone() }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index e7335f3436d..f73ca9ae06f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -299,12 +299,11 @@ impl IdentityWallet { document_type_name, }, )? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "No usable ECDSA authentication key at a security level satisfying \ - {required_level} found on owner identity {owner_identity_id} \ - (required to sign a {document_type_name} document state transition)" - )) + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *owner_identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement(required_level), + transition: format!("a {document_type_name} document transition"), })? .clone() }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index 25aa7f22332..6eaf76c7814 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -8,7 +8,7 @@ use dpp::fee::Credits; use dpp::identity::Identity; use dpp::identity::IdentityPublicKey; -use dpp::identity::SecurityLevel; +use dpp::identity::{Purpose, SecurityLevel}; use dpp::prelude::Identifier; use dpp::identity::signer::Signer; @@ -42,6 +42,9 @@ use super::*; /// without forcing a clone or `Arc` round-trip per call. struct SignerRef<'a, S: ?Sized>(&'a S); +/// The security level both DPNS registration documents require. +const DPNS_REGISTRATION_REQUIREMENT: SecurityLevel = SecurityLevel::HIGH; + /// The key that signs both DPNS registration documents, `preorder` then `domain`: a HIGH or /// CRITICAL AUTHENTICATION ECDSA key whose bounds cover the whole DPNS contract. MASTER is /// reserved for identity operations and refused on document writes. @@ -52,7 +55,7 @@ fn dpns_registration_signing_key<'a>( document_signing_key( identity, signer, - SecurityLevel::HIGH, + DPNS_REGISTRATION_REQUIREMENT, SigningScope::Contract { contract_id: SystemDataContract::DPNS.id(), }, @@ -241,12 +244,13 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; drop(wm); let key = dpns_registration_signing_key(&identity, signer)? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "No usable HIGH or CRITICAL authentication key found on identity \ - (required for document state transitions)" - .to_string(), - ) + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement( + DPNS_REGISTRATION_REQUIREMENT, + ), + transition: "a DPNS name registration".to_string(), })? .clone(); (identity, key) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index 2a9c7451baf..2d761f1e1a6 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -35,7 +35,7 @@ use dpp::fee::Credits; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; -use dpp::identity::IdentityPublicKey; +use dpp::identity::{IdentityPublicKey, Purpose, SecurityLevel}; use dpp::platform_value::btreemap_extensions::BTreeValueMapHelper; use dpp::platform_value::Value; use dpp::prelude::{DataContract, Identifier}; @@ -988,12 +988,11 @@ impl IdentityWallet { }, )? .cloned() - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "No usable ECDSA authentication key at a security level satisfying \ - {required_level} found on identity {identity_id} \ - (required to sign a DPNS domain state transition)" - )) + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement(required_level), + transition: format!("a DPNS {DPNS_DOCUMENT_TYPE} document transition"), }) } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 23cb03b0301..9db645f77b9 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -44,6 +44,12 @@ pub(super) fn first_available<'a>( unavailable.map_or(Ok(None), |key| Err(signing_key_unavailable(key))) } +/// The security levels [`contract_signing_key`] accepts. +pub(super) const CONTRACT_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; + +/// The security levels [`master_signing_key`] accepts. +pub(super) const MASTER_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::MASTER]; + /// The key that signs a contract create or update: a CRITICAL AUTHENTICATION ECDSA key. /// These are not batches, so a contract-bound key cannot sign them. pub(super) fn contract_signing_key<'a>( @@ -54,7 +60,7 @@ pub(super) fn contract_signing_key<'a>( identity, signer, Purpose::AUTHENTICATION, - &[SecurityLevel::CRITICAL], + &CONTRACT_SIGNING_LEVELS, &[KeyType::ECDSA_SECP256K1], SigningScope::NonBatch, ) @@ -69,7 +75,7 @@ pub(super) fn master_signing_key<'a>( identity, signer, Purpose::AUTHENTICATION, - &[SecurityLevel::MASTER], + &MASTER_SIGNING_LEVELS, &[KeyType::ECDSA_SECP256K1], SigningScope::NonBatch, ) @@ -116,6 +122,7 @@ pub(super) fn credit_signing_key<'a>( #[cfg(test)] pub(super) mod tests { use super::*; + use crate::{PlatformWallet, PlatformWalletError}; use async_trait::async_trait; use dpp::address_funds::AddressWitness; use dpp::identity::accessors::IdentityGettersV0; @@ -124,6 +131,7 @@ pub(super) mod tests { use dpp::platform_value::BinaryData; use dpp::prelude::Identifier; use dpp::version::PlatformVersion; + use std::sync::Arc; /// Test signer that can sign with the keys `F` accepts; selection must never sign. pub(crate) struct KeyFilter bool>(pub F); @@ -428,12 +436,21 @@ pub(super) mod tests { } } - pub(crate) async fn wallet_with_signing_keys() -> std::sync::Arc { + pub(crate) async fn wallet_with_signing_keys() -> Arc { + wallet_with_identity(identity( + Purpose::AUTHENTICATION, + SecurityLevel::CRITICAL, + KeyType::ECDSA_SECP256K1, + )) + .await + } + + /// A mock-SDK wallet that owns `identity`. + pub(crate) async fn wallet_with_identity(identity: Identity) -> Arc { use crate::events::{EventHandler, PlatformEventHandler}; use crate::wallet::persister::NoPlatformPersistence; use crate::PlatformWalletManager; use key_wallet::wallet::initialization::WalletAccountCreationOptions; - use std::sync::Arc; struct Events; impl EventHandler for Events {} @@ -457,11 +474,7 @@ pub(super) mod tests { .unwrap() .identity_manager .add_identity( - identity( - Purpose::AUTHENTICATION, - SecurityLevel::CRITICAL, - KeyType::ECDSA_SECP256K1, - ), + identity, 0, wallet.wallet_id(), &wallet.identity().persister, @@ -470,6 +483,74 @@ pub(super) mod tests { wallet } + /// A wallet identity holding only HIGH AUTHENTICATION keys: none can sign a contract + /// create or an identity update. + async fn wallet_without_critical_or_master_keys() -> (Arc, Identifier) { + let identity = identity( + Purpose::AUTHENTICATION, + SecurityLevel::HIGH, + KeyType::ECDSA_SECP256K1, + ); + let identity_id = identity.id(); + (wallet_with_identity(identity).await, identity_id) + } + + pub(crate) fn assert_no_usable_key( + error: PlatformWalletError, + identity: Identifier, + level: SecurityLevel, + ) { + assert!( + matches!( + &error, + PlatformWalletError::NoUsableSigningKey { + identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels, + .. + } if *identity_id == identity && security_levels == &[level] + ), + "{error:?}" + ); + } + + #[tokio::test] + async fn should_report_no_usable_contract_key_as_a_typed_error() { + let (wallet, identity_id) = wallet_without_critical_or_master_keys().await; + let error = wallet + .identity() + .create_data_contract_with_signer( + &identity_id, + "{}", + None, + None, + None, + None, + None, + &KeyFilter(|_| true), + ) + .await + .unwrap_err(); + assert_no_usable_key(error, identity_id, SecurityLevel::CRITICAL); + } + + #[tokio::test] + async fn should_report_no_usable_master_key_as_a_typed_error() { + let (wallet, identity_id) = wallet_without_critical_or_master_keys().await; + let error = wallet + .identity() + .update_identity_with_external_signer( + &identity_id, + vec![], + vec![], + &KeyFilter(|_| true), + None, + ) + .await + .unwrap_err(); + assert_no_usable_key(error, identity_id, SecurityLevel::MASTER); + } + #[tokio::test] async fn should_release_profile_wallet_lock_before_signer_callback() { let wallet = wallet_with_signing_keys().await; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 87f2bb8aa3e..bafbb6c01d9 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -24,6 +24,10 @@ use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; +/// The security levels [`token_signing_key`] accepts: consensus takes only CRITICAL for a +/// batch with a token transition. +const TOKEN_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; + /// The key that signs a token operation of `token_contract_id`: a CRITICAL AUTHENTICATION /// ECDSA key whose bounds cover the whole contract, since token operations are contract-wide. fn token_signing_key<'a>( @@ -35,7 +39,7 @@ fn token_signing_key<'a>( identity, signer, Purpose::AUTHENTICATION, - &[SecurityLevel::CRITICAL], + &TOKEN_SIGNING_LEVELS, &[KeyType::ECDSA_SECP256K1], SigningScope::Contract { contract_id: token_contract_id, @@ -74,13 +78,11 @@ impl IdentityWallet { drop(wm); let signing_key = token_signing_key(&identity, token_contract_id, signer)? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "No AUTHENTICATION ECDSA_SECP256K1 key at CRITICAL security level on identity {} — \ - identities registered before this fix may need an IdentityUpdate to add a CRITICAL key, \ - or re-registration", - identity_id - )) + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: TOKEN_SIGNING_LEVELS.to_vec(), + transition: format!("a token transition of contract {token_contract_id}"), })? .clone(); @@ -124,8 +126,27 @@ impl IdentityWallet { mod signing_tests { use super::*; use crate::wallet::identity::network::signing_key::tests::{ - lock_checking_signer, wallet_with_signing_keys, + assert_no_usable_key, identity as identity_with_keys, lock_checking_signer, + wallet_with_identity, wallet_with_signing_keys, KeyFilter, }; + use dpp::identity::accessors::IdentityGettersV0; + + #[tokio::test] + async fn should_report_no_usable_token_key_as_a_typed_error() { + let identity = identity_with_keys( + Purpose::AUTHENTICATION, + SecurityLevel::HIGH, + KeyType::ECDSA_SECP256K1, + ); + let identity_id = identity.id(); + let wallet = wallet_with_identity(identity).await; + let error = wallet + .identity() + .token_resolve_signing_key(&identity_id, Identifier::default(), &KeyFilter(|_| true)) + .await + .unwrap_err(); + assert_no_usable_key(error, identity_id, SecurityLevel::CRITICAL); + } #[tokio::test] async fn should_check_token_key_availability_outside_wallet_lock() { @@ -142,7 +163,6 @@ mod signing_tests { #[test] fn should_sign_a_token_operation_with_a_key_that_covers_the_whole_contract() { use crate::wallet::identity::network::key_selection::tests::{bound_key, identity, key}; - use crate::wallet::identity::network::signing_key::tests::KeyFilter; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs index bc3da705911..d328ca9bdc1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs @@ -7,7 +7,7 @@ use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::accessors::IdentitySettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::Identity; -use dpp::identity::IdentityPublicKey; +use dpp::identity::{IdentityPublicKey, Purpose}; use dpp::platform_value::BinaryData; use dpp::prelude::Identifier; use dpp::ProtocolError; @@ -18,7 +18,7 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use crate::error::PlatformWalletError; -use super::signing_key::master_signing_key; +use super::signing_key::{master_signing_key, MASTER_SIGNING_LEVELS}; use super::*; // Borrowed-signer adapter — see `dpns.rs` for the same pattern. @@ -135,10 +135,11 @@ impl IdentityWallet { // transitions to be authorized by MASTER specifically. let master_key_id = master_signing_key(&identity, signer)? .map(|key| key.id()) - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "No signable master key found on identity".to_string(), - ) + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: MASTER_SIGNING_LEVELS.to_vec(), + transition: "an identity update".to_string(), })?; let identity_nonce = self From 3e476c7db20e6d848009b6dff589f7c4031c9fb7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:21:21 +0000 Subject: [PATCH 14/53] fix(platform-wallet): check an explicit DPNS registration key before registering register_name_with_signer passed the caller's key straight to the SDK, so a key Platform refuses (MASTER, disabled, expired, or bound to only one DPNS document type) was only rejected after network round-trips. It now runs check_signing_key with the automatic path's rules (a HIGH or CRITICAL ECDSA AUTHENTICATION key covering the whole DPNS contract) and returns Platform's typed refusal before any request. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/document.rs | 2 +- .../src/wallet/identity/network/dpns.rs | 83 +++++++++++++++++-- 2 files changed, 79 insertions(+), 6 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index f73ca9ae06f..936d1c2d45f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -120,7 +120,7 @@ pub(super) fn document_signing_key<'a>( /// Check a key the caller chose to sign a document batch in `scope` whose document type /// requires `requirement`, by the rules [`document_signing_key`] applies. -fn check_document_signing_key( +pub(super) fn check_document_signing_key( key: &IdentityPublicKey, signer: &impl Signer, requirement: SecurityLevel, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index 6eaf76c7814..5e41c896366 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -1,6 +1,6 @@ //! DPNS name registration, resolution, search, and contest queries. -use super::document::document_signing_key; +use super::document::{check_document_signing_key, document_signing_key}; use super::key_selection::SigningScope; use dpp::data_contracts::SystemDataContract; @@ -56,12 +56,31 @@ fn dpns_registration_signing_key<'a>( identity, signer, DPNS_REGISTRATION_REQUIREMENT, - SigningScope::Contract { - contract_id: SystemDataContract::DPNS.id(), - }, + dpns_registration_scope(), ) } +/// Check a key the caller chose to register a DPNS name by the rules +/// [`dpns_registration_signing_key`] applies. +fn check_dpns_registration_signing_key( + key: &IdentityPublicKey, + signer: &impl Signer, +) -> Result<(), dash_sdk::Error> { + check_document_signing_key( + key, + signer, + DPNS_REGISTRATION_REQUIREMENT, + dpns_registration_scope(), + ) +} + +/// Registration writes `preorder` and then `domain`, so its key must cover the whole contract. +fn dpns_registration_scope() -> SigningScope<'static> { + SigningScope::Contract { + contract_id: SystemDataContract::DPNS.id(), + } +} + impl<'a, S: ?Sized> std::fmt::Debug for SignerRef<'a, S> { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str("SignerRef") @@ -153,7 +172,9 @@ impl IdentityWallet { /// [`register_name_with_external_signer`](Self::register_name_with_external_signer), /// this method does **not** look up the identity in the internal /// `IdentityManager`. The caller supplies the `Identity`, the - /// signing key, and a `Signer` directly. + /// signing key, and a `Signer` directly. The key is checked by the rules the + /// wallet's own choice follows before anything reaches the network; a key Platform + /// would refuse returns its typed refusal. /// /// `contest_fund` is the most the registration pays into the contest a contested name /// joins (the fund to join doubles once a contest holds 250 contenders and again for every @@ -170,6 +191,7 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::dpns_usernames::RegisterDpnsNameInput; + check_dpns_registration_signing_key(&identity_public_key, &signer)?; let input = RegisterDpnsNameInput { label: name.to_string(), identity, @@ -590,4 +612,55 @@ mod signing_key_tests { "a key bound to `domain` cannot sign the `preorder` document" ); } + + #[tokio::test] + async fn should_refuse_an_explicit_registration_key_before_any_network_call() { + use super::super::signing_key::tests::wallet_with_signing_keys; + use dpp::consensus::signature::SignatureError; + use dpp::consensus::ConsensusError; + + let wallet = wallet_with_signing_keys().await; + let bound_to_domain = bound_key( + 1, + SecurityLevel::HIGH, + Some(ContractBounds::SingleContractDocumentType { + id: SystemDataContract::DPNS.id(), + document_type_name: "domain".to_string(), + }), + ); + let identity = identity(vec![key(0, SecurityLevel::MASTER), bound_to_domain.clone()]); + let register = |key: IdentityPublicKey| { + wallet.identity().register_name_with_signer( + identity.clone(), + "alice", + key, + None, + KeyFilter(|_| true), + ) + }; + let error = register(bound_to_domain).await.unwrap_err(); + assert!( + matches!( + &error, + dash_sdk::Error::Protocol(ProtocolError::ConsensusError(consensus)) + if matches!( + consensus.as_ref(), + ConsensusError::SignatureError( + SignatureError::ContractBoundedKeyOutOfBoundsError(_) + ) + ) + ), + "a key bound to `domain` cannot sign the `preorder` document: {error:?}" + ); + let error = register(key(0, SecurityLevel::MASTER)).await.unwrap_err(); + assert!( + matches!( + error, + dash_sdk::Error::Protocol( + ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) + ) + ), + "MASTER is refused on document writes: {error:?}" + ); + } } From 68c996a5bf4ccf15378ee556ecb3dfe449398727 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:24:44 +0000 Subject: [PATCH 15/53] fix(platform-wallet): check explicit credit and token signing keys up front credit_signing_key only checked that the signer held an explicit key, and the token *_with_signer variants passed theirs on unchecked, so a disabled, expired, wrong-purpose or out-of-bounds key was signed and then refused by Platform. An explicit credit key must now be TRANSFER (or OWNER for a withdrawal) and pass check_signing_key for a non-batch transition. Every token *_with_signer variant checks its key with the automatic token path's rules: a CRITICAL ECDSA AUTHENTICATION key whose bounds cover the token's whole contract. Each refusal is Platform's typed error, returned before any request. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/signing_key.rs | 78 ++++++++++++-- .../wallet/identity/network/tokens/burn.rs | 2 + .../wallet/identity/network/tokens/claim.rs | 2 + .../network/tokens/destroy_frozen_funds.rs | 2 + .../wallet/identity/network/tokens/freeze.rs | 2 + .../wallet/identity/network/tokens/helpers.rs | 100 +++++++++++++++++- .../wallet/identity/network/tokens/mint.rs | 2 + .../wallet/identity/network/tokens/pause.rs | 2 + .../identity/network/tokens/purchase.rs | 2 + .../wallet/identity/network/tokens/resume.rs | 2 + .../identity/network/tokens/set_price.rs | 2 + .../identity/network/tokens/transfer.rs | 2 + .../identity/network/tokens/unfreeze.rs | 2 + .../identity/network/tokens/update_config.rs | 2 + 14 files changed, 193 insertions(+), 9 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 9db645f77b9..9fc969f9706 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -1,10 +1,11 @@ //! Signer-aware identity key selection shared by wallet operations. -use super::key_selection::{usable_signing_key, SigningScope}; +use super::key_selection::{check_signing_key, usable_signing_key, SigningScope}; use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; +use dpp::state_transition::errors::WrongPublicKeyPurposeError; use dpp::ProtocolError; /// Preserve the signer's unavailable-key discriminator through SDK and FFI errors. @@ -81,21 +82,38 @@ pub(super) fn master_signing_key<'a>( ) } -/// Respect explicit keys; automatic withdrawals exhaust enabled TRANSFER keys before OWNER. +/// The key that signs a credit transfer, or a withdrawal when `allow_owner`. An explicit key +/// is never substituted; it is checked by the rules automatic selection applies, and refused +/// with Platform's typed error. Automatic withdrawals exhaust TRANSFER keys before OWNER. pub(super) fn credit_signing_key<'a>( identity: &'a Identity, explicit: Option<&'a IdentityPublicKey>, signer: &impl Signer, allow_owner: bool, ) -> Result<&'a IdentityPublicKey, dash_sdk::Error> { + let purposes: Vec = [Purpose::TRANSFER] + .into_iter() + .chain(allow_owner.then_some(Purpose::OWNER)) + .collect(); if let Some(key) = explicit { - return require_available(key, signer); + if !purposes.contains(&key.purpose()) { + return Err(ProtocolError::WrongPublicKeyPurposeError( + WrongPublicKeyPurposeError::new(key.purpose(), purposes), + ) + .into()); + } + check_signing_key( + key, + signer, + key.purpose(), + &SecurityLevel::full_range(), + &KeyType::all_key_types(), + SigningScope::NonBatch, + )?; + return Ok(key); } let mut unavailable = None; - for purpose in [Purpose::TRANSFER] - .into_iter() - .chain(allow_owner.then_some(Purpose::OWNER)) - { + for purpose in purposes { match usable_signing_key( identity, signer, @@ -406,6 +424,52 @@ pub(super) mod tests { ); } + #[test] + fn should_refuse_an_explicit_credit_key_platform_would_refuse() { + let mut identity = identity( + Purpose::TRANSFER, + SecurityLevel::CRITICAL, + KeyType::ECDSA_HASH160, + ); + let mut owner = identity.public_keys().get(&2).unwrap().clone(); + owner.set_id(3); + owner.set_purpose(Purpose::OWNER); + identity.add_public_key(owner); + identity + .public_keys_mut() + .get_mut(&1) + .unwrap() + .set_disabled_at(1); + let explicit = |id: u32, allow_owner| { + credit_signing_key( + &identity, + identity.public_keys().get(&id), + &available(&[1, 2, 3]), + allow_owner, + ) + .map(|key| key.id()) + }; + assert!( + matches!( + explicit(1, true), + Err(dash_sdk::Error::Protocol( + ProtocolError::PublicKeyIsDisabledError(_) + )) + ), + "Platform refuses a disabled signing key" + ); + assert!( + matches!( + explicit(3, false), + Err(dash_sdk::Error::Protocol(ProtocolError::WrongPublicKeyPurposeError(ref error))) + if error.allowed_key_purposes() == &vec![Purpose::TRANSFER] + ), + "a credit transfer takes only a TRANSFER key" + ); + assert_eq!(explicit(3, true).unwrap(), 3, "a withdrawal may take OWNER"); + assert_eq!(explicit(2, false).unwrap(), 2); + } + #[tokio::test] async fn should_surface_unavailable_signer_from_credit_operations() { let wallet = wallet_with_signing_keys().await; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs index 307930fcaae..0b90a91ce3d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs @@ -9,6 +9,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -30,6 +31,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::burn::TokenBurnTransitionBuilder; let mut builder = diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs index 04c4f475da5..3cab3fa7c9e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs @@ -8,6 +8,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -28,6 +29,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::claim::TokenClaimTransitionBuilder; let mut builder = TokenClaimTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs index ef5fd151bf4..350ae023798 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs @@ -10,6 +10,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -32,6 +33,7 @@ impl IdentityWallet { >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::destroy::TokenDestroyFrozenFundsTransitionBuilder; let mut builder = TokenDestroyFrozenFundsTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs index d003319cbef..3fde116e1ca 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs @@ -8,6 +8,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -29,6 +30,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::freeze::TokenFreezeTransitionBuilder; let mut builder = TokenFreezeTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index bafbb6c01d9..14386bbc688 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -12,9 +12,10 @@ //! all rejected by Drive. See //! `state_transitions/document/batch_transition/methods/v0/mod.rs:133-138`. -use super::super::key_selection::{usable_signing_key, SigningScope}; +use super::super::key_selection::{check_signing_key, usable_signing_key, SigningScope}; use std::sync::Arc; +use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::DataContract; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; @@ -28,6 +29,9 @@ use crate::wallet::identity::network::IdentityWallet; /// batch with a token transition. const TOKEN_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; +/// The key types [`token_signing_key`] accepts. +const TOKEN_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; + /// The key that signs a token operation of `token_contract_id`: a CRITICAL AUTHENTICATION /// ECDSA key whose bounds cover the whole contract, since token operations are contract-wide. fn token_signing_key<'a>( @@ -40,13 +44,32 @@ fn token_signing_key<'a>( signer, Purpose::AUTHENTICATION, &TOKEN_SIGNING_LEVELS, - &[KeyType::ECDSA_SECP256K1], + &TOKEN_SIGNING_KEY_TYPES, SigningScope::Contract { contract_id: token_contract_id, }, ) } +/// Check a key the caller chose to sign a token operation of `data_contract` by the rules +/// [`token_signing_key`] applies, so a key Platform would refuse fails before any request. +pub(super) fn check_token_signing_key( + key: &IdentityPublicKey, + signer: &impl Signer, + data_contract: &DataContract, +) -> Result<(), dash_sdk::Error> { + check_signing_key( + key, + signer, + Purpose::AUTHENTICATION, + &TOKEN_SIGNING_LEVELS, + &TOKEN_SIGNING_KEY_TYPES, + SigningScope::Contract { + contract_id: data_contract.id(), + }, + ) +} + impl IdentityWallet { /// Resolve the AUTHENTICATION signing key for token state /// transitions — used by the `_with_external_signer` variants @@ -131,6 +154,79 @@ mod signing_tests { }; use dpp::identity::accessors::IdentityGettersV0; + #[tokio::test] + async fn should_refuse_an_explicit_token_key_before_any_network_call() { + use crate::wallet::identity::network::key_selection::tests::{bound_key, key}; + use dpp::consensus::signature::SignatureError; + use dpp::consensus::ConsensusError; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::data_contracts::SystemDataContract; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + use dpp::system_data_contracts::load_system_data_contract; + use dpp::version::PlatformVersion; + use dpp::ProtocolError; + + let wallet = wallet_with_signing_keys().await; + let contract = Arc::new( + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) + .expect("bundled DPNS contract"), + ); + let burn = |signing_key: IdentityPublicKey| { + let wallet = &wallet; + let contract = Arc::clone(&contract); + async move { + wallet + .identity() + .token_burn_with_signer( + contract, + 0, + Identifier::from([1; 32]), + 1, + &signing_key, + &KeyFilter(|_| true), + None, + None, + None, + ) + .await + .err() + .expect("the key must be refused") + } + }; + let error = burn(key(1, SecurityLevel::HIGH)).await; + assert!( + matches!( + error, + dash_sdk::Error::Protocol( + ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) + ) + ), + "a token transition takes only a CRITICAL key: {error:?}" + ); + let bound_to_one_document_type = bound_key( + 1, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContractDocumentType { + id: contract.id(), + document_type_name: "domain".to_string(), + }), + ); + let error = burn(bound_to_one_document_type).await; + assert!( + matches!( + &error, + dash_sdk::Error::Protocol(ProtocolError::ConsensusError(consensus)) + if matches!( + consensus.as_ref(), + ConsensusError::SignatureError( + SignatureError::ContractBoundedKeyOutOfBoundsError(_) + ) + ) + ), + "a token transition needs bounds covering the whole contract: {error:?}" + ); + } + #[tokio::test] async fn should_report_no_usable_token_key_as_a_typed_error() { let identity = identity_with_keys( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs index 4d5b7882b3b..efa540c5fd3 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs @@ -17,6 +17,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -39,6 +40,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::mint::TokenMintTransitionBuilder; // Contracts with `minting_allow_choosing_destination = false` diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs index 168aa426188..7ef56aae857 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs @@ -9,6 +9,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -30,6 +31,7 @@ impl IdentityWallet { >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; let mut builder = TokenEmergencyActionTransitionBuilder::pause( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs index 1ed519dc08d..1f534df1187 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs @@ -15,6 +15,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -36,6 +37,7 @@ impl IdentityWallet { >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::purchase::TokenDirectPurchaseTransitionBuilder; let mut builder = TokenDirectPurchaseTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs index d766f5d8e60..b102f92a1e9 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs @@ -8,6 +8,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -29,6 +30,7 @@ impl IdentityWallet { >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; let mut builder = TokenEmergencyActionTransitionBuilder::resume( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs index fef8b33abb5..c84ed1afce9 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs @@ -15,6 +15,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -37,6 +38,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::set_price::TokenChangeDirectPurchasePriceTransitionBuilder; let mut builder = TokenChangeDirectPurchasePriceTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs index ce3bb7dc276..2a04028557c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs @@ -9,6 +9,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -32,6 +33,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::transfer::TokenTransferTransitionBuilder; let mut builder = TokenTransferTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs index a8f1efce6d8..485fe238168 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs @@ -8,6 +8,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -29,6 +30,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::unfreeze::TokenUnfreezeTransitionBuilder; let mut builder = TokenUnfreezeTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs index 9194111377d..7270a6e4205 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs @@ -10,6 +10,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -31,6 +32,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + check_token_signing_key(signing_key, signer, &data_contract)?; use dash_sdk::platform::tokens::builders::config_update::TokenConfigUpdateTransitionBuilder; let mut builder = TokenConfigUpdateTransitionBuilder::new( From 9122d9c750c4e2f0b57a55961ee6f4f42ac88ab7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 12:38:44 +0000 Subject: [PATCH 16/53] refactor(platform-wallet): let check_signing_key take every accepted purpose Some transitions accept more than one key purpose (a withdrawal takes TRANSFER or OWNER), so credit_signing_key checked the purpose itself and then called check_signing_key with the key's own purpose, a check that could not fail. check_signing_key now takes the accepted purposes and refuses any other with WrongPublicKeyPurposeError naming all of them, so the rule lives in one place. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/document.rs | 2 +- .../wallet/identity/network/key_selection.rs | 14 ++++++------- .../wallet/identity/network/signing_key.rs | 21 ++++++++++++------- .../wallet/identity/network/tokens/helpers.rs | 2 +- 4 files changed, 22 insertions(+), 17 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index 936d1c2d45f..28b2a255699 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -129,7 +129,7 @@ pub(super) fn check_document_signing_key( check_signing_key( key, signer, - Purpose::AUTHENTICATION, + &[Purpose::AUTHENTICATION], &SecurityLevel::accepted_for_requirement(requirement), &[KeyType::ECDSA_SECP256K1], scope, 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 793e9417d5d..76c772a4a2b 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 @@ -113,24 +113,24 @@ pub fn usable_signing_key<'a>( /// Check a key the caller chose to sign in `scope` against the rules [`usable_signing_key`] /// applies, so an explicit choice is refused before anything is built or signed. /// -/// Each refusal is the typed error Platform itself returns for it: a wrong purpose, a security -/// level outside `security_levels`, a key type outside `key_types`, a disabled key, an expired +/// Each refusal is the typed error Platform itself returns for it: a purpose outside +/// `purposes`, a security level outside `security_levels`, a key type outside `key_types`, a disabled key, an expired /// key, or contract bounds that do not cover `scope`. A key bound to a contract group is /// accepted: only Platform can read the group's memberships. A key `signer` cannot sign with /// is refused with the signer-unavailable error. pub fn check_signing_key( key: &IdentityPublicKey, signer: &impl Signer, - purpose: Purpose, + purposes: &[Purpose], security_levels: &[SecurityLevel], key_types: &[KeyType], scope: SigningScope<'_>, ) -> Result<(), dash_sdk::Error> { - if key.purpose() != purpose { + if !purposes.contains(&key.purpose()) { return Err( ProtocolError::WrongPublicKeyPurposeError(WrongPublicKeyPurposeError::new( key.purpose(), - vec![purpose], + purposes.to_vec(), )) .into(), ); @@ -559,7 +559,7 @@ pub(super) mod tests { check_signing_key( key, &KeyFilter(|_| true), - Purpose::AUTHENTICATION, + &[Purpose::AUTHENTICATION], &LEVELS, &TYPES, scope, @@ -658,7 +658,7 @@ pub(super) mod tests { let err = check_signing_key( &key(1, SecurityLevel::HIGH), &available(&[]), - Purpose::AUTHENTICATION, + &[Purpose::AUTHENTICATION], &LEVELS, &TYPES, document_scope(), diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 9fc969f9706..356f8e56e40 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -5,7 +5,6 @@ use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; -use dpp::state_transition::errors::WrongPublicKeyPurposeError; use dpp::ProtocolError; /// Preserve the signer's unavailable-key discriminator through SDK and FFI errors. @@ -96,16 +95,10 @@ pub(super) fn credit_signing_key<'a>( .chain(allow_owner.then_some(Purpose::OWNER)) .collect(); if let Some(key) = explicit { - if !purposes.contains(&key.purpose()) { - return Err(ProtocolError::WrongPublicKeyPurposeError( - WrongPublicKeyPurposeError::new(key.purpose(), purposes), - ) - .into()); - } check_signing_key( key, signer, - key.purpose(), + &purposes, &SecurityLevel::full_range(), &KeyType::all_key_types(), SigningScope::NonBatch, @@ -434,7 +427,11 @@ pub(super) mod tests { let mut owner = identity.public_keys().get(&2).unwrap().clone(); owner.set_id(3); owner.set_purpose(Purpose::OWNER); + let mut authentication = owner.clone(); identity.add_public_key(owner); + authentication.set_id(4); + authentication.set_purpose(Purpose::AUTHENTICATION); + identity.add_public_key(authentication); identity .public_keys_mut() .get_mut(&1) @@ -466,6 +463,14 @@ pub(super) mod tests { ), "a credit transfer takes only a TRANSFER key" ); + assert!( + matches!( + explicit(4, true), + Err(dash_sdk::Error::Protocol(ProtocolError::WrongPublicKeyPurposeError(ref error))) + if error.allowed_key_purposes() == &vec![Purpose::TRANSFER, Purpose::OWNER] + ), + "a withdrawal names both purposes it takes" + ); assert_eq!(explicit(3, true).unwrap(), 3, "a withdrawal may take OWNER"); assert_eq!(explicit(2, false).unwrap(), 2); } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 14386bbc688..8f921444956 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -61,7 +61,7 @@ pub(super) fn check_token_signing_key( check_signing_key( key, signer, - Purpose::AUTHENTICATION, + &[Purpose::AUTHENTICATION], &TOKEN_SIGNING_LEVELS, &TOKEN_SIGNING_KEY_TYPES, SigningScope::Contract { From e8c391c1424d18bfbbb304bd4de75dbb7f464e0d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:06:06 +0000 Subject: [PATCH 17/53] fix(platform-wallet): accept a TRANSFER key for an explicit token transfer or claim Consensus lets a CRITICAL TRANSFER key sign a batch holding exactly one token transfer or token claim (BatchTransitionV1::purpose_requirement), but check_token_signing_key accepted only AUTHENTICATION keys, so token_transfer_with_signer and token_claim_with_signer refused a key Platform would take. Those two now accept AUTHENTICATION or TRANSFER; every other token operation keeps AUTHENTICATION only. Automatic selection is unchanged. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/tokens/burn.rs | 4 +- .../wallet/identity/network/tokens/claim.rs | 9 +- .../network/tokens/destroy_frozen_funds.rs | 4 +- .../wallet/identity/network/tokens/freeze.rs | 4 +- .../wallet/identity/network/tokens/helpers.rs | 150 ++++++++++++++++-- .../wallet/identity/network/tokens/mint.rs | 4 +- .../wallet/identity/network/tokens/pause.rs | 4 +- .../identity/network/tokens/purchase.rs | 4 +- .../wallet/identity/network/tokens/resume.rs | 4 +- .../identity/network/tokens/set_price.rs | 4 +- .../identity/network/tokens/transfer.rs | 9 +- .../identity/network/tokens/unfreeze.rs | 4 +- .../identity/network/tokens/update_config.rs | 4 +- 13 files changed, 167 insertions(+), 41 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs index 0b90a91ce3d..99f1523d005 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs @@ -9,7 +9,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -31,7 +31,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::burn::TokenBurnTransitionBuilder; let mut builder = diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs index 3cab3fa7c9e..0a2b67c9486 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs @@ -8,7 +8,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, LONE_TOKEN_TRANSFER_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -29,7 +29,12 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + )?; use dash_sdk::platform::tokens::builders::claim::TokenClaimTransitionBuilder; let mut builder = TokenClaimTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs index 350ae023798..6e6270e8672 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs @@ -10,7 +10,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -33,7 +33,7 @@ impl IdentityWallet { >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::destroy::TokenDestroyFrozenFundsTransitionBuilder; let mut builder = TokenDestroyFrozenFundsTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs index 3fde116e1ca..c323ff95d6e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs @@ -8,7 +8,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -30,7 +30,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::freeze::TokenFreezeTransitionBuilder; let mut builder = TokenFreezeTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 8f921444956..3d4f879c118 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -51,17 +51,27 @@ fn token_signing_key<'a>( ) } -/// Check a key the caller chose to sign a token operation of `data_contract` by the rules -/// [`token_signing_key`] applies, so a key Platform would refuse fails before any request. +/// The purposes a key may have to sign a token operation. +pub(super) const TOKEN_SIGNING_PURPOSES: [Purpose; 1] = [Purpose::AUTHENTICATION]; + +/// The purposes a key may have to sign a batch of exactly one token transfer or token claim: +/// consensus also takes a TRANSFER key there (`BatchTransitionV1::purpose_requirement`). +pub(super) const LONE_TOKEN_TRANSFER_SIGNING_PURPOSES: [Purpose; 2] = + [Purpose::AUTHENTICATION, Purpose::TRANSFER]; + +/// Check a key the caller chose to sign a token operation of `data_contract`, with one of +/// `purposes`, by the rules [`token_signing_key`] applies, so a key Platform would refuse fails +/// before any request. Contract bounds limit only an AUTHENTICATION key. pub(super) fn check_token_signing_key( key: &IdentityPublicKey, signer: &impl Signer, data_contract: &DataContract, + purposes: &[Purpose], ) -> Result<(), dash_sdk::Error> { check_signing_key( key, signer, - &[Purpose::AUTHENTICATION], + purposes, &TOKEN_SIGNING_LEVELS, &TOKEN_SIGNING_KEY_TYPES, SigningScope::Contract { @@ -148,29 +158,135 @@ impl IdentityWallet { #[cfg(test)] mod signing_tests { use super::*; + use crate::wallet::identity::network::key_selection::tests::{bound_key, key}; use crate::wallet::identity::network::signing_key::tests::{ assert_no_usable_key, identity as identity_with_keys, lock_checking_signer, wallet_with_identity, wallet_with_signing_keys, KeyFilter, }; + use dpp::consensus::signature::SignatureError; + use dpp::consensus::ConsensusError; + use dpp::data_contract::associated_token::token_distribution_key::TokenDistributionType; + use dpp::data_contracts::SystemDataContract; use dpp::identity::accessors::IdentityGettersV0; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + use dpp::system_data_contracts::load_system_data_contract; + use dpp::version::PlatformVersion; + use dpp::ProtocolError; - #[tokio::test] - async fn should_refuse_an_explicit_token_key_before_any_network_call() { - use crate::wallet::identity::network::key_selection::tests::{bound_key, key}; - use dpp::consensus::signature::SignatureError; - use dpp::consensus::ConsensusError; - use dpp::data_contract::accessors::v0::DataContractV0Getters; - use dpp::data_contracts::SystemDataContract; - use dpp::identity::identity_public_key::contract_bounds::ContractBounds; - use dpp::system_data_contracts::load_system_data_contract; - use dpp::version::PlatformVersion; - use dpp::ProtocolError; - - let wallet = wallet_with_signing_keys().await; - let contract = Arc::new( + /// A contract to point token operations at; the key check runs before its tokens matter. + fn some_contract() -> Arc { + Arc::new( load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) .expect("bundled DPNS contract"), + ) + } + + fn transfer_key(security_level: SecurityLevel) -> IdentityPublicKey { + let mut key = key(1, security_level); + key.set_purpose(Purpose::TRANSFER); + key + } + + #[tokio::test] + async fn should_accept_an_explicit_transfer_key_for_a_lone_token_transfer_or_claim() { + let wallet = wallet_with_signing_keys().await; + let identity = wallet.identity(); + let signer = KeyFilter(|_| true); + let owner = Identifier::from([1; 32]); + let critical = transfer_key(SecurityLevel::CRITICAL); + let transfer = identity + .token_transfer_with_signer( + some_contract(), + 0, + owner, + Identifier::from([2; 32]), + 1, + &critical, + &signer, + None, + None, + ) + .await + .err() + .expect("the mock SDK has no answers"); + assert!( + matches!(transfer, dash_sdk::Error::DapiClientError(_)), + "a CRITICAL TRANSFER key may sign a token transfer, so the request goes out: \ + {transfer:?}" ); + let claim = identity + .token_claim_with_signer( + some_contract(), + 0, + owner, + TokenDistributionType::Perpetual, + &critical, + &signer, + None, + None, + ) + .await + .err() + .expect("the mock SDK has no answers"); + assert!( + matches!(claim, dash_sdk::Error::DapiClientError(_)), + "a CRITICAL TRANSFER key may sign a token claim, so the request goes out: {claim:?}" + ); + let high = transfer_key(SecurityLevel::HIGH); + let transfer = identity + .token_transfer_with_signer( + some_contract(), + 0, + owner, + Identifier::from([2; 32]), + 1, + &high, + &signer, + None, + None, + ) + .await + .err() + .expect("the key must be refused"); + assert!( + matches!( + transfer, + dash_sdk::Error::Protocol( + ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) + ) + ), + "a TRANSFER key signs a batch only at CRITICAL: {transfer:?}" + ); + let burn = identity + .token_burn_with_signer( + some_contract(), + 0, + owner, + 1, + &critical, + &signer, + None, + None, + None, + ) + .await + .err() + .expect("the key must be refused"); + assert!( + matches!( + burn, + dash_sdk::Error::Protocol(ProtocolError::WrongPublicKeyPurposeError(ref error)) + if error.allowed_key_purposes() == &vec![Purpose::AUTHENTICATION] + ), + "only a lone transfer or claim takes a TRANSFER key: {burn:?}" + ); + } + + #[tokio::test] + async fn should_refuse_an_explicit_token_key_before_any_network_call() { + let wallet = wallet_with_signing_keys().await; + let contract = some_contract(); let burn = |signing_key: IdentityPublicKey| { let wallet = &wallet; let contract = Arc::clone(&contract); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs index efa540c5fd3..3940cc8017a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs @@ -17,7 +17,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -40,7 +40,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::mint::TokenMintTransitionBuilder; // Contracts with `minting_allow_choosing_destination = false` diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs index 7ef56aae857..031b2f3fd97 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs @@ -9,7 +9,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -31,7 +31,7 @@ impl IdentityWallet { >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; let mut builder = TokenEmergencyActionTransitionBuilder::pause( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs index 1f534df1187..b345a84da5b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs @@ -15,7 +15,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -37,7 +37,7 @@ impl IdentityWallet { >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::purchase::TokenDirectPurchaseTransitionBuilder; let mut builder = TokenDirectPurchaseTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs index b102f92a1e9..b932d94c215 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs @@ -8,7 +8,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -30,7 +30,7 @@ impl IdentityWallet { >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; let mut builder = TokenEmergencyActionTransitionBuilder::resume( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs index c84ed1afce9..91d2ea5749f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs @@ -15,7 +15,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -38,7 +38,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::set_price::TokenChangeDirectPurchasePriceTransitionBuilder; let mut builder = TokenChangeDirectPurchasePriceTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs index 2a04028557c..7fe41c06f21 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs @@ -9,7 +9,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, LONE_TOKEN_TRANSFER_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -33,7 +33,12 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + )?; use dash_sdk::platform::tokens::builders::transfer::TokenTransferTransitionBuilder; let mut builder = TokenTransferTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs index 485fe238168..2aac9b42398 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs @@ -8,7 +8,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -30,7 +30,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::unfreeze::TokenUnfreezeTransitionBuilder; let mut builder = TokenUnfreezeTransitionBuilder::new( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs index 7270a6e4205..89eaa499655 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs @@ -10,7 +10,7 @@ use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; -use super::helpers::check_token_signing_key; +use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -32,7 +32,7 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract)?; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::config_update::TokenConfigUpdateTransitionBuilder; let mut builder = TokenConfigUpdateTransitionBuilder::new( From f5d1518a17df515b1bbf85919cd9db62eafc39f5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:19:20 +0000 Subject: [PATCH 18/53] fix(platform-wallet): accept every key type Platform verifies for an explicit key The explicit-key checks for document operations, DPNS registration and token operations allowed only ECDSA_SECP256K1, although Drive verifies identity signatures by ECDSA_SECP256K1, BLS12_381 and ECDSA_HASH160, so a usable HASH160 or BLS key was refused up front. The explicit credit check went the other way and let through key types Drive refuses. All explicit-key checks now use PLATFORM_SIGNING_KEY_TYPES, Drive's set. Automatic selection keeps the narrower types it picks from. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/document.rs | 24 +++++++++-- .../src/wallet/identity/network/dpns.rs | 9 +++++ .../wallet/identity/network/key_selection.rs | 9 +++++ .../wallet/identity/network/signing_key.rs | 20 +++++++++- .../wallet/identity/network/tokens/helpers.rs | 40 ++++++++++++++++--- 5 files changed, 91 insertions(+), 11 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index 28b2a255699..04342983c48 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -27,7 +27,9 @@ //! post-broadcast GroveDB proof-verification recursion. The owner's //! balance the proof carries (from protocol version 14) is kept. -use super::key_selection::{check_signing_key, usable_signing_key, SigningScope}; +use super::key_selection::{ + check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, +}; use std::collections::BTreeMap; use std::sync::Arc; @@ -119,7 +121,8 @@ pub(super) fn document_signing_key<'a>( } /// Check a key the caller chose to sign a document batch in `scope` whose document type -/// requires `requirement`, by the rules [`document_signing_key`] applies. +/// requires `requirement`, by the rules [`document_signing_key`] applies, except that any key +/// type Platform verifies is accepted. pub(super) fn check_document_signing_key( key: &IdentityPublicKey, signer: &impl Signer, @@ -131,7 +134,7 @@ pub(super) fn check_document_signing_key( signer, &[Purpose::AUTHENTICATION], &SecurityLevel::accepted_for_requirement(requirement), - &[KeyType::ECDSA_SECP256K1], + &PLATFORM_SIGNING_KEY_TYPES, scope, ) } @@ -1037,7 +1040,9 @@ mod tests { use super::super::key_selection::tests::{bound_key, identity, key}; use super::super::signing_key::tests::KeyFilter; - use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dpp::identity::identity_public_key::accessors::v0::{ + IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0, + }; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; const CONTRACT: [u8; 32] = [0xDA; 32]; @@ -1113,5 +1118,16 @@ mod tests { check(&key(1, SecurityLevel::HIGH).with_limits(None, Some(1))).is_err(), "the key has expired" ); + for key_type in [KeyType::ECDSA_HASH160, KeyType::BLS12_381] { + let mut explicit = key(1, SecurityLevel::HIGH); + explicit.set_key_type(key_type); + check(&explicit).expect("Platform verifies a signature by this key type"); + } + let mut eddsa = key(1, SecurityLevel::HIGH); + eddsa.set_key_type(KeyType::EDDSA_25519_HASH160); + assert!( + check(&eddsa).is_err(), + "Platform cannot verify an identity signature by this key type" + ); } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index 5e41c896366..ebc941e45b2 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -618,6 +618,8 @@ mod signing_key_tests { use super::super::signing_key::tests::wallet_with_signing_keys; use dpp::consensus::signature::SignatureError; use dpp::consensus::ConsensusError; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dpp::identity::KeyType; let wallet = wallet_with_signing_keys().await; let bound_to_domain = bound_key( @@ -662,5 +664,12 @@ mod signing_key_tests { ), "MASTER is refused on document writes: {error:?}" ); + let mut hash160 = key(2, SecurityLevel::HIGH); + hash160.set_key_type(KeyType::ECDSA_HASH160); + let error = register(hash160).await.unwrap_err(); + assert!( + matches!(error, dash_sdk::Error::DapiClientError(_)), + "Platform verifies an ECDSA_HASH160 signature, so the request goes out: {error:?}" + ); } } 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 76c772a4a2b..e0b0ffa742a 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 @@ -24,6 +24,15 @@ use dpp::ProtocolError; use super::signing_key::{first_available, require_available}; use crate::util::now_ms; +/// The key types Platform verifies an identity signature by (Drive's +/// `validate_state_transition_identity_signed`). A key the caller chose is checked against +/// these, not against the narrower set the wallet picks its own keys from. +pub(crate) const PLATFORM_SIGNING_KEY_TYPES: [KeyType; 3] = [ + KeyType::ECDSA_SECP256K1, + KeyType::BLS12_381, + KeyType::ECDSA_HASH160, +]; + /// What a signature authorizes, as far as a key's contract bounds go. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SigningScope<'a> { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 356f8e56e40..51ddfda2e95 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -1,6 +1,8 @@ //! Signer-aware identity key selection shared by wallet operations. -use super::key_selection::{check_signing_key, usable_signing_key, SigningScope}; +use super::key_selection::{ + check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, +}; use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; @@ -100,7 +102,7 @@ pub(super) fn credit_signing_key<'a>( signer, &purposes, &SecurityLevel::full_range(), - &KeyType::all_key_types(), + &PLATFORM_SIGNING_KEY_TYPES, SigningScope::NonBatch, )?; return Ok(key); @@ -429,9 +431,14 @@ pub(super) mod tests { owner.set_purpose(Purpose::OWNER); let mut authentication = owner.clone(); identity.add_public_key(owner); + let mut script_hash = authentication.clone(); authentication.set_id(4); authentication.set_purpose(Purpose::AUTHENTICATION); identity.add_public_key(authentication); + script_hash.set_id(5); + script_hash.set_purpose(Purpose::TRANSFER); + script_hash.set_key_type(KeyType::BIP13_SCRIPT_HASH); + identity.add_public_key(script_hash); identity .public_keys_mut() .get_mut(&1) @@ -471,6 +478,15 @@ pub(super) mod tests { ), "a withdrawal names both purposes it takes" ); + assert!( + matches!( + explicit(5, false), + Err(dash_sdk::Error::Protocol( + ProtocolError::InvalidIdentityPublicKeyTypeError(_) + )) + ), + "Platform cannot verify an identity signature by a script hash" + ); assert_eq!(explicit(3, true).unwrap(), 3, "a withdrawal may take OWNER"); assert_eq!(explicit(2, false).unwrap(), 2); } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 3d4f879c118..a4fb264a4be 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -12,7 +12,9 @@ //! all rejected by Drive. See //! `state_transitions/document/batch_transition/methods/v0/mod.rs:133-138`. -use super::super::key_selection::{check_signing_key, usable_signing_key, SigningScope}; +use super::super::key_selection::{ + check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, +}; use std::sync::Arc; use dpp::data_contract::accessors::v0::DataContractV0Getters; @@ -29,7 +31,7 @@ use crate::wallet::identity::network::IdentityWallet; /// batch with a token transition. const TOKEN_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; -/// The key types [`token_signing_key`] accepts. +/// The key types [`token_signing_key`] picks from. const TOKEN_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; /// The key that signs a token operation of `token_contract_id`: a CRITICAL AUTHENTICATION @@ -60,8 +62,9 @@ pub(super) const LONE_TOKEN_TRANSFER_SIGNING_PURPOSES: [Purpose; 2] = [Purpose::AUTHENTICATION, Purpose::TRANSFER]; /// Check a key the caller chose to sign a token operation of `data_contract`, with one of -/// `purposes`, by the rules [`token_signing_key`] applies, so a key Platform would refuse fails -/// before any request. Contract bounds limit only an AUTHENTICATION key. +/// `purposes`, by the rules [`token_signing_key`] applies except that any key type Platform +/// verifies is accepted, so a key Platform would refuse fails before any request. Contract +/// bounds limit only an AUTHENTICATION key. pub(super) fn check_token_signing_key( key: &IdentityPublicKey, signer: &impl Signer, @@ -73,7 +76,7 @@ pub(super) fn check_token_signing_key( signer, purposes, &TOKEN_SIGNING_LEVELS, - &TOKEN_SIGNING_KEY_TYPES, + &PLATFORM_SIGNING_KEY_TYPES, SigningScope::Contract { contract_id: data_contract.id(), }, @@ -283,6 +286,33 @@ mod signing_tests { ); } + #[tokio::test] + async fn should_accept_an_explicit_token_key_of_any_type_platform_verifies() { + let wallet = wallet_with_signing_keys().await; + let mut hash160 = key(1, SecurityLevel::CRITICAL); + hash160.set_key_type(KeyType::ECDSA_HASH160); + let burn = wallet + .identity() + .token_burn_with_signer( + some_contract(), + 0, + Identifier::from([1; 32]), + 1, + &hash160, + &KeyFilter(|_| true), + None, + None, + None, + ) + .await + .err() + .expect("the mock SDK has no answers"); + assert!( + matches!(burn, dash_sdk::Error::DapiClientError(_)), + "Platform verifies an ECDSA_HASH160 signature, so the request goes out: {burn:?}" + ); + } + #[tokio::test] async fn should_refuse_an_explicit_token_key_before_any_network_call() { let wallet = wallet_with_signing_keys().await; From cd04dc61b0bb0a4f7e3c12bec7fa6f597495f80d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:46:48 +0000 Subject: [PATCH 19/53] feat(platform-wallet): name the accepted key types in NoUsableSigningKey The error listed the purpose and security levels a key needed but not its type, so an identity holding only an ECDSA_HASH160 key at the right level got a message that read as if any such key would do. The variant gains key_types, set from the same constants the selectors pick from, and the message names them. Co-Authored-By: Claude Opus 5.5 --- packages/rs-platform-wallet-ffi/src/error.rs | 2 ++ packages/rs-platform-wallet/src/error.rs | 12 +++++++----- .../src/wallet/identity/network/contact_requests.rs | 3 ++- .../src/wallet/identity/network/contract.rs | 6 +++++- .../src/wallet/identity/network/document.rs | 6 +++++- .../src/wallet/identity/network/dpns.rs | 5 ++++- .../src/wallet/identity/network/dpns_marketplace.rs | 3 ++- .../src/wallet/identity/network/signing_key.rs | 12 +++++++++--- .../src/wallet/identity/network/tokens/helpers.rs | 1 + .../src/wallet/identity/network/update.rs | 3 ++- 10 files changed, 39 insertions(+), 14 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 0c84cba6627..62c5900122c 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -1380,6 +1380,7 @@ mod tests { identity_id, purpose: dpp::identity::Purpose::AUTHENTICATION, security_levels: vec![dpp::identity::SecurityLevel::CRITICAL], + key_types: vec![dpp::identity::KeyType::ECDSA_SECP256K1], transition: "an identity update".to_string(), }); assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorUnknown); @@ -1392,6 +1393,7 @@ mod tests { identity.as_str(), "AUTHENTICATION", "CRITICAL", + "ECDSA_SECP256K1", "an identity update", ] { assert!(message.contains(part), "{message}"); diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index ec28b6cbf63..7ba176e540e 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -6,7 +6,7 @@ use dpp::consensus::state::address_funds::AddressInvalidNonceError; use dpp::consensus::ConsensusError; use dpp::fee::Credits; use dpp::identifier::Identifier; -use dpp::identity::{Purpose, SecurityLevel}; +use dpp::identity::{KeyType, Purpose, SecurityLevel}; use dpp::prelude::{AddressNonce, CoreBlockHeight}; use key_wallet::account::StandardAccountType; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -86,18 +86,20 @@ pub enum PlatformWalletError { #[error("Invalid identity data: {0}")] InvalidIdentityData(String), - /// No key of the identity can sign `transition`: none has `purpose` and one of - /// `security_levels` while also being enabled, unexpired and inside its contract bounds. + /// No key of the identity can sign `transition`: none has `purpose`, one of + /// `security_levels` and one of `key_types` while also being enabled, unexpired and inside + /// its contract bounds. /// It stays so until an identity update adds such a key. A key that qualifies but that the /// signer cannot use is the signer-unavailable error instead. #[error( - "identity {identity_id} has no usable {purpose} key at security level \ - {security_levels:?} to sign {transition}" + "identity {identity_id} has no usable {purpose} key of type {key_types:?} at security \ + level {security_levels:?} to sign {transition}" )] NoUsableSigningKey { identity_id: Identifier, purpose: Purpose, security_levels: Vec, + key_types: Vec, transition: String, }, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index 510f5a4d974..4b8bebf274c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -1,6 +1,6 @@ //! DashPay contact request lifecycle: send, sync, accept, reject. -use super::document::document_signing_key; +use super::document::{document_signing_key, DOCUMENT_SIGNING_KEY_TYPES}; use super::key_selection::SigningScope; use dpp::data_contracts::SystemDataContract; use dpp::document::DocumentV0Getters; @@ -626,6 +626,7 @@ impl DashPayView<'_, B> { security_levels: SecurityLevel::accepted_for_requirement( CONTACT_REQUEST_REQUIREMENT, ), + key_types: DOCUMENT_SIGNING_KEY_TYPES.to_vec(), transition: "a contactRequest document transition".to_string(), })?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs index db4a0ba6731..853cc3b83f3 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs @@ -26,7 +26,9 @@ //! the rs-sdk-ffi path — classic stack-guard fingerprint, not //! memory unsafety. -use super::signing_key::{contract_signing_key, CONTRACT_SIGNING_LEVELS}; +use super::signing_key::{ + contract_signing_key, CONTRACT_SIGNING_LEVELS, IDENTITY_SIGNING_KEY_TYPES, +}; use async_trait::async_trait; use dpp::address_funds::AddressWitness; @@ -167,6 +169,7 @@ impl IdentityWallet { identity_id: *owner_identity_id, purpose: Purpose::AUTHENTICATION, security_levels: CONTRACT_SIGNING_LEVELS.to_vec(), + key_types: IDENTITY_SIGNING_KEY_TYPES.to_vec(), transition: "a contract-create state transition".to_string(), })? .clone() @@ -380,6 +383,7 @@ impl IdentityWallet { identity_id: *owner_identity_id, purpose: Purpose::AUTHENTICATION, security_levels: CONTRACT_SIGNING_LEVELS.to_vec(), + key_types: IDENTITY_SIGNING_KEY_TYPES.to_vec(), transition: "a contract-update state transition".to_string(), })? .clone() diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index 04342983c48..af2089da112 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -102,6 +102,9 @@ where } } +/// The key types [`document_signing_key`] picks from. +pub(super) const DOCUMENT_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; + /// The key that signs a document batch in `scope` whose document type requires /// `requirement`: an AUTHENTICATION, ECDSA_SECP256K1 key at a level consensus accepts. pub(super) fn document_signing_key<'a>( @@ -115,7 +118,7 @@ pub(super) fn document_signing_key<'a>( signer, Purpose::AUTHENTICATION, &SecurityLevel::accepted_for_requirement(requirement), - &[KeyType::ECDSA_SECP256K1], + &DOCUMENT_SIGNING_KEY_TYPES, scope, ) } @@ -306,6 +309,7 @@ impl IdentityWallet { identity_id: *owner_identity_id, purpose: Purpose::AUTHENTICATION, security_levels: SecurityLevel::accepted_for_requirement(required_level), + key_types: DOCUMENT_SIGNING_KEY_TYPES.to_vec(), transition: format!("a {document_type_name} document transition"), })? .clone() diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index ebc941e45b2..44bd5dab4de 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -1,6 +1,8 @@ //! DPNS name registration, resolution, search, and contest queries. -use super::document::{check_document_signing_key, document_signing_key}; +use super::document::{ + check_document_signing_key, document_signing_key, DOCUMENT_SIGNING_KEY_TYPES, +}; use super::key_selection::SigningScope; use dpp::data_contracts::SystemDataContract; @@ -272,6 +274,7 @@ impl IdentityWallet { security_levels: SecurityLevel::accepted_for_requirement( DPNS_REGISTRATION_REQUIREMENT, ), + key_types: DOCUMENT_SIGNING_KEY_TYPES.to_vec(), transition: "a DPNS name registration".to_string(), })? .clone(); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index 2d761f1e1a6..566eaa44aeb 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -54,7 +54,7 @@ use crate::changeset::{ use crate::error::PlatformWalletError; use crate::wallet::identity::types::key_storage::DpnsNameInfo; -use super::document::document_signing_key; +use super::document::{document_signing_key, DOCUMENT_SIGNING_KEY_TYPES}; use super::key_selection::SigningScope; use super::*; @@ -992,6 +992,7 @@ impl IdentityWallet { identity_id: *identity_id, purpose: Purpose::AUTHENTICATION, security_levels: SecurityLevel::accepted_for_requirement(required_level), + key_types: DOCUMENT_SIGNING_KEY_TYPES.to_vec(), transition: format!("a DPNS {DPNS_DOCUMENT_TYPE} document transition"), }) } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 51ddfda2e95..a1551dad93e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -52,6 +52,9 @@ pub(super) const CONTRACT_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::C /// The security levels [`master_signing_key`] accepts. pub(super) const MASTER_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::MASTER]; +/// The key types [`contract_signing_key`] and [`master_signing_key`] pick from. +pub(super) const IDENTITY_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; + /// The key that signs a contract create or update: a CRITICAL AUTHENTICATION ECDSA key. /// These are not batches, so a contract-bound key cannot sign them. pub(super) fn contract_signing_key<'a>( @@ -63,7 +66,7 @@ pub(super) fn contract_signing_key<'a>( signer, Purpose::AUTHENTICATION, &CONTRACT_SIGNING_LEVELS, - &[KeyType::ECDSA_SECP256K1], + &IDENTITY_SIGNING_KEY_TYPES, SigningScope::NonBatch, ) } @@ -78,7 +81,7 @@ pub(super) fn master_signing_key<'a>( signer, Purpose::AUTHENTICATION, &MASTER_SIGNING_LEVELS, - &[KeyType::ECDSA_SECP256K1], + &IDENTITY_SIGNING_KEY_TYPES, SigningScope::NonBatch, ) } @@ -592,8 +595,11 @@ pub(super) mod tests { identity_id, purpose: Purpose::AUTHENTICATION, security_levels, + key_types, .. - } if *identity_id == identity && security_levels == &[level] + } if *identity_id == identity + && security_levels == &[level] + && key_types == &[KeyType::ECDSA_SECP256K1] ), "{error:?}" ); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index a4fb264a4be..7d49beba75f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -118,6 +118,7 @@ impl IdentityWallet { identity_id: *identity_id, purpose: Purpose::AUTHENTICATION, security_levels: TOKEN_SIGNING_LEVELS.to_vec(), + key_types: TOKEN_SIGNING_KEY_TYPES.to_vec(), transition: format!("a token transition of contract {token_contract_id}"), })? .clone(); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs index d328ca9bdc1..6e31ab473b1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs @@ -18,7 +18,7 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use crate::error::PlatformWalletError; -use super::signing_key::{master_signing_key, MASTER_SIGNING_LEVELS}; +use super::signing_key::{master_signing_key, IDENTITY_SIGNING_KEY_TYPES, MASTER_SIGNING_LEVELS}; use super::*; // Borrowed-signer adapter — see `dpns.rs` for the same pattern. @@ -139,6 +139,7 @@ impl IdentityWallet { identity_id: *identity_id, purpose: Purpose::AUTHENTICATION, security_levels: MASTER_SIGNING_LEVELS.to_vec(), + key_types: IDENTITY_SIGNING_KEY_TYPES.to_vec(), transition: "an identity update".to_string(), })?; From dacc85dc8a25ae90399e48d52cb290372335cf58 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 13:47:50 +0000 Subject: [PATCH 20/53] style(platform-wallet): tidy the key-check call sites and their tests Token *_with_signer bodies keep their local use lines first, then check the key. The non-batch agreement test walks every purpose dpp decodes instead of a hand-written list, so a new purpose cannot be missed. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/key_selection.rs | 16 ++++++---------- .../src/wallet/identity/network/tokens/burn.rs | 3 ++- .../src/wallet/identity/network/tokens/claim.rs | 3 ++- .../network/tokens/destroy_frozen_funds.rs | 3 ++- .../src/wallet/identity/network/tokens/freeze.rs | 3 ++- .../src/wallet/identity/network/tokens/mint.rs | 3 ++- .../src/wallet/identity/network/tokens/pause.rs | 3 ++- .../wallet/identity/network/tokens/purchase.rs | 3 ++- .../src/wallet/identity/network/tokens/resume.rs | 3 ++- .../wallet/identity/network/tokens/set_price.rs | 3 ++- .../wallet/identity/network/tokens/transfer.rs | 3 ++- .../wallet/identity/network/tokens/unfreeze.rs | 3 ++- .../identity/network/tokens/update_config.rs | 3 ++- 13 files changed, 30 insertions(+), 22 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 e0b0ffa742a..ff10baf5d16 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 @@ -717,15 +717,11 @@ pub(super) mod tests { #[test] fn should_deny_a_non_batch_signature_exactly_when_dpp_says_the_key_cannot_sign_one() { - let purposes = [ - Purpose::AUTHENTICATION, - Purpose::ENCRYPTION, - Purpose::DECRYPTION, - Purpose::TRANSFER, - Purpose::SYSTEM, - Purpose::VOTING, - Purpose::OWNER, - ]; + // Every purpose dpp decodes, so a purpose added later is covered too. + let purposes: Vec = (0..=u8::MAX) + .filter_map(|byte| Purpose::try_from(byte).ok()) + .collect(); + assert!(purposes.len() >= 7, "{purposes:?}"); let contract_id = Identifier::from(CONTRACT); let bounds = [ None, @@ -736,7 +732,7 @@ pub(super) mod tests { }), Some(ContractBounds::ContractGroup { id: contract_id }), ]; - for purpose in purposes { + for &purpose in &purposes { for contract_bounds in &bounds { let mut key = bound_key(1, SecurityLevel::HIGH, contract_bounds.clone()); key.set_purpose(purpose); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs index 99f1523d005..64a222af1c9 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs @@ -31,9 +31,10 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::burn::TokenBurnTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenBurnTransitionBuilder::new(data_contract, token_position, identity_id, amount); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs index 0a2b67c9486..1e98d345c1a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs @@ -29,13 +29,14 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + use dash_sdk::platform::tokens::builders::claim::TokenClaimTransitionBuilder; + check_token_signing_key( signing_key, signer, &data_contract, &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, )?; - use dash_sdk::platform::tokens::builders::claim::TokenClaimTransitionBuilder; let mut builder = TokenClaimTransitionBuilder::new( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs index 6e6270e8672..bbd548e8cef 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs @@ -33,9 +33,10 @@ impl IdentityWallet { >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::destroy::TokenDestroyFrozenFundsTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenDestroyFrozenFundsTransitionBuilder::new( data_contract, token_position, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs index c323ff95d6e..c7756fd4196 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs @@ -30,9 +30,10 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::freeze::TokenFreezeTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenFreezeTransitionBuilder::new( data_contract, token_position, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs index 3940cc8017a..2443d759e5c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs @@ -40,9 +40,10 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::mint::TokenMintTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + // Contracts with `minting_allow_choosing_destination = false` // reject any mint where `issued_to_identity_id.is_some()` at // execution time (rs-drive's TokenMintTransitionTransformer diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs index 031b2f3fd97..e639e58943a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs @@ -31,9 +31,10 @@ impl IdentityWallet { >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenEmergencyActionTransitionBuilder::pause( data_contract, token_position, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs index b345a84da5b..c9245f4b39a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs @@ -37,9 +37,10 @@ impl IdentityWallet { >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::purchase::TokenDirectPurchaseTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenDirectPurchaseTransitionBuilder::new( data_contract, token_position, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs index b932d94c215..498504d47b3 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs @@ -30,9 +30,10 @@ impl IdentityWallet { >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenEmergencyActionTransitionBuilder::resume( data_contract, token_position, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs index 91d2ea5749f..89191465f1c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs @@ -38,9 +38,10 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::set_price::TokenChangeDirectPurchasePriceTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenChangeDirectPurchasePriceTransitionBuilder::new( data_contract, token_position, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs index 7fe41c06f21..8620f0a56df 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs @@ -33,13 +33,14 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { + use dash_sdk::platform::tokens::builders::transfer::TokenTransferTransitionBuilder; + check_token_signing_key( signing_key, signer, &data_contract, &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, )?; - use dash_sdk::platform::tokens::builders::transfer::TokenTransferTransitionBuilder; let mut builder = TokenTransferTransitionBuilder::new( data_contract, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs index 2aac9b42398..42524737223 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs @@ -30,9 +30,10 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::unfreeze::TokenUnfreezeTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenUnfreezeTransitionBuilder::new( data_contract, token_position, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs index 89eaa499655..bb800883644 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs @@ -32,9 +32,10 @@ impl IdentityWallet { dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions, >, ) -> Result { - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; use dash_sdk::platform::tokens::builders::config_update::TokenConfigUpdateTransitionBuilder; + check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + let mut builder = TokenConfigUpdateTransitionBuilder::new( data_contract, token_position, From f34643fe0571bf4f42fb50593ff2eee28cc8d8e6 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:11:23 +0000 Subject: [PATCH 21/53] style(platform-wallet): one constant for the key types the wallet picks from Document, token, contract and identity-update selectors each declared their own [ECDSA_SECP256K1] constant. They share WALLET_SIGNING_KEY_TYPES, next to PLATFORM_SIGNING_KEY_TYPES, and a doc paragraph is rewrapped to the line limit. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/contact_requests.rs | 6 +++--- .../src/wallet/identity/network/contract.rs | 9 ++++----- .../src/wallet/identity/network/document.rs | 11 +++++------ .../src/wallet/identity/network/dpns.rs | 8 +++----- .../src/wallet/identity/network/dpns_marketplace.rs | 6 +++--- .../src/wallet/identity/network/key_selection.rs | 12 ++++++++---- .../src/wallet/identity/network/signing_key.rs | 8 +++----- .../src/wallet/identity/network/tokens/helpers.rs | 11 +++++------ .../src/wallet/identity/network/update.rs | 5 +++-- 9 files changed, 37 insertions(+), 39 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index 4b8bebf274c..b0834b56d57 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -1,7 +1,7 @@ //! DashPay contact request lifecycle: send, sync, accept, reject. -use super::document::{document_signing_key, DOCUMENT_SIGNING_KEY_TYPES}; -use super::key_selection::SigningScope; +use super::document::document_signing_key; +use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; use dpp::data_contracts::SystemDataContract; use dpp::document::DocumentV0Getters; use dpp::identity::accessors::IdentityGettersV0; @@ -626,7 +626,7 @@ impl DashPayView<'_, B> { security_levels: SecurityLevel::accepted_for_requirement( CONTACT_REQUEST_REQUIREMENT, ), - key_types: DOCUMENT_SIGNING_KEY_TYPES.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "a contactRequest document transition".to_string(), })?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs index 853cc3b83f3..bea686e517e 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs @@ -26,9 +26,8 @@ //! the rs-sdk-ffi path — classic stack-guard fingerprint, not //! memory unsafety. -use super::signing_key::{ - contract_signing_key, CONTRACT_SIGNING_LEVELS, IDENTITY_SIGNING_KEY_TYPES, -}; +use super::key_selection::WALLET_SIGNING_KEY_TYPES; +use super::signing_key::{contract_signing_key, CONTRACT_SIGNING_LEVELS}; use async_trait::async_trait; use dpp::address_funds::AddressWitness; @@ -169,7 +168,7 @@ impl IdentityWallet { identity_id: *owner_identity_id, purpose: Purpose::AUTHENTICATION, security_levels: CONTRACT_SIGNING_LEVELS.to_vec(), - key_types: IDENTITY_SIGNING_KEY_TYPES.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "a contract-create state transition".to_string(), })? .clone() @@ -383,7 +382,7 @@ impl IdentityWallet { identity_id: *owner_identity_id, purpose: Purpose::AUTHENTICATION, security_levels: CONTRACT_SIGNING_LEVELS.to_vec(), - key_types: IDENTITY_SIGNING_KEY_TYPES.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "a contract-update state transition".to_string(), })? .clone() diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index af2089da112..633ac0e0118 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -29,6 +29,7 @@ use super::key_selection::{ check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, + WALLET_SIGNING_KEY_TYPES, }; use std::collections::BTreeMap; use std::sync::Arc; @@ -46,7 +47,7 @@ use dpp::document::DocumentV0Setters; use dpp::fee::Credits; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; -use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; +use dpp::identity::{Identity, IdentityPublicKey, Purpose, SecurityLevel}; use dpp::platform_value::{BinaryData, Value}; use dpp::prelude::{DataContract, Identifier}; use dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions; @@ -102,9 +103,6 @@ where } } -/// The key types [`document_signing_key`] picks from. -pub(super) const DOCUMENT_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; - /// The key that signs a document batch in `scope` whose document type requires /// `requirement`: an AUTHENTICATION, ECDSA_SECP256K1 key at a level consensus accepts. pub(super) fn document_signing_key<'a>( @@ -118,7 +116,7 @@ pub(super) fn document_signing_key<'a>( signer, Purpose::AUTHENTICATION, &SecurityLevel::accepted_for_requirement(requirement), - &DOCUMENT_SIGNING_KEY_TYPES, + &WALLET_SIGNING_KEY_TYPES, scope, ) } @@ -309,7 +307,7 @@ impl IdentityWallet { identity_id: *owner_identity_id, purpose: Purpose::AUTHENTICATION, security_levels: SecurityLevel::accepted_for_requirement(required_level), - key_types: DOCUMENT_SIGNING_KEY_TYPES.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: format!("a {document_type_name} document transition"), })? .clone() @@ -1048,6 +1046,7 @@ mod tests { IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0, }; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + use dpp::identity::KeyType; const CONTRACT: [u8; 32] = [0xDA; 32]; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index 44bd5dab4de..fbfd157e76c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -1,9 +1,7 @@ //! DPNS name registration, resolution, search, and contest queries. -use super::document::{ - check_document_signing_key, document_signing_key, DOCUMENT_SIGNING_KEY_TYPES, -}; -use super::key_selection::SigningScope; +use super::document::{check_document_signing_key, document_signing_key}; +use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; use dpp::data_contracts::SystemDataContract; use dpp::fee::Credits; @@ -274,7 +272,7 @@ impl IdentityWallet { security_levels: SecurityLevel::accepted_for_requirement( DPNS_REGISTRATION_REQUIREMENT, ), - key_types: DOCUMENT_SIGNING_KEY_TYPES.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "a DPNS name registration".to_string(), })? .clone(); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index 566eaa44aeb..2e9d500949c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -54,8 +54,8 @@ use crate::changeset::{ use crate::error::PlatformWalletError; use crate::wallet::identity::types::key_storage::DpnsNameInfo; -use super::document::{document_signing_key, DOCUMENT_SIGNING_KEY_TYPES}; -use super::key_selection::SigningScope; +use super::document::document_signing_key; +use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; use super::*; /// DPNS document type carrying registered names. @@ -992,7 +992,7 @@ impl IdentityWallet { identity_id: *identity_id, purpose: Purpose::AUTHENTICATION, security_levels: SecurityLevel::accepted_for_requirement(required_level), - key_types: DOCUMENT_SIGNING_KEY_TYPES.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: format!("a DPNS {DPNS_DOCUMENT_TYPE} document transition"), }) } 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 ff10baf5d16..6013815d05f 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 @@ -33,6 +33,10 @@ pub(crate) const PLATFORM_SIGNING_KEY_TYPES: [KeyType; 3] = [ KeyType::ECDSA_HASH160, ]; +/// The key types the wallet picks its own signing keys from. A key the caller chose is checked +/// against [`PLATFORM_SIGNING_KEY_TYPES`] instead. +pub(crate) const WALLET_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; + /// What a signature authorizes, as far as a key's contract bounds go. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum SigningScope<'a> { @@ -123,10 +127,10 @@ pub fn usable_signing_key<'a>( /// applies, so an explicit choice is refused before anything is built or signed. /// /// Each refusal is the typed error Platform itself returns for it: a purpose outside -/// `purposes`, a security level outside `security_levels`, a key type outside `key_types`, a disabled key, an expired -/// key, or contract bounds that do not cover `scope`. A key bound to a contract group is -/// accepted: only Platform can read the group's memberships. A key `signer` cannot sign with -/// is refused with the signer-unavailable error. +/// `purposes`, a security level outside `security_levels`, a key type outside `key_types`, a +/// disabled key, an expired key, or contract bounds that do not cover `scope`. A key bound to +/// a contract group is accepted: only Platform can read the group's memberships. A key +/// `signer` cannot sign with is refused with the signer-unavailable error. pub fn check_signing_key( key: &IdentityPublicKey, signer: &impl Signer, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index a1551dad93e..54cfe5e49dc 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -2,6 +2,7 @@ use super::key_selection::{ check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, + WALLET_SIGNING_KEY_TYPES, }; use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -52,9 +53,6 @@ pub(super) const CONTRACT_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::C /// The security levels [`master_signing_key`] accepts. pub(super) const MASTER_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::MASTER]; -/// The key types [`contract_signing_key`] and [`master_signing_key`] pick from. -pub(super) const IDENTITY_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; - /// The key that signs a contract create or update: a CRITICAL AUTHENTICATION ECDSA key. /// These are not batches, so a contract-bound key cannot sign them. pub(super) fn contract_signing_key<'a>( @@ -66,7 +64,7 @@ pub(super) fn contract_signing_key<'a>( signer, Purpose::AUTHENTICATION, &CONTRACT_SIGNING_LEVELS, - &IDENTITY_SIGNING_KEY_TYPES, + &WALLET_SIGNING_KEY_TYPES, SigningScope::NonBatch, ) } @@ -81,7 +79,7 @@ pub(super) fn master_signing_key<'a>( signer, Purpose::AUTHENTICATION, &MASTER_SIGNING_LEVELS, - &IDENTITY_SIGNING_KEY_TYPES, + &WALLET_SIGNING_KEY_TYPES, SigningScope::NonBatch, ) } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 7d49beba75f..80785a5ce49 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -14,13 +14,14 @@ use super::super::key_selection::{ check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, + WALLET_SIGNING_KEY_TYPES, }; use std::sync::Arc; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::DataContract; use dpp::identity::signer::Signer; -use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; +use dpp::identity::{Identity, IdentityPublicKey, Purpose, SecurityLevel}; use dpp::prelude::Identifier; use crate::broadcaster::TransactionBroadcaster; @@ -31,9 +32,6 @@ use crate::wallet::identity::network::IdentityWallet; /// batch with a token transition. const TOKEN_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; -/// The key types [`token_signing_key`] picks from. -const TOKEN_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; - /// The key that signs a token operation of `token_contract_id`: a CRITICAL AUTHENTICATION /// ECDSA key whose bounds cover the whole contract, since token operations are contract-wide. fn token_signing_key<'a>( @@ -46,7 +44,7 @@ fn token_signing_key<'a>( signer, Purpose::AUTHENTICATION, &TOKEN_SIGNING_LEVELS, - &TOKEN_SIGNING_KEY_TYPES, + &WALLET_SIGNING_KEY_TYPES, SigningScope::Contract { contract_id: token_contract_id, }, @@ -118,7 +116,7 @@ impl IdentityWallet { identity_id: *identity_id, purpose: Purpose::AUTHENTICATION, security_levels: TOKEN_SIGNING_LEVELS.to_vec(), - key_types: TOKEN_SIGNING_KEY_TYPES.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: format!("a token transition of contract {token_contract_id}"), })? .clone(); @@ -174,6 +172,7 @@ mod signing_tests { use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + use dpp::identity::KeyType; use dpp::system_data_contracts::load_system_data_contract; use dpp::version::PlatformVersion; use dpp::ProtocolError; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs index 6e31ab473b1..ae9f8fa459a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs @@ -18,7 +18,8 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use crate::error::PlatformWalletError; -use super::signing_key::{master_signing_key, IDENTITY_SIGNING_KEY_TYPES, MASTER_SIGNING_LEVELS}; +use super::key_selection::WALLET_SIGNING_KEY_TYPES; +use super::signing_key::{master_signing_key, MASTER_SIGNING_LEVELS}; use super::*; // Borrowed-signer adapter — see `dpns.rs` for the same pattern. @@ -139,7 +140,7 @@ impl IdentityWallet { identity_id: *identity_id, purpose: Purpose::AUTHENTICATION, security_levels: MASTER_SIGNING_LEVELS.to_vec(), - key_types: IDENTITY_SIGNING_KEY_TYPES.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "an identity update".to_string(), })?; From d78d7be44792f8a32cdc3af8e87e7801fbae3645 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:31:35 +0000 Subject: [PATCH 22/53] fix(platform-wallet): treat a key expiry as unknown when the clock cannot be read util::now_ms reads 0 when the system clock is before the Unix epoch, so every expiry looked in the future and an expired key could be chosen or pass an explicit check. Key selection reads the clock itself: without a valid clock a key carrying an expiry is not eligible, and check_signing_key refuses it with dash_sdk::Error::Config. Keys without an expiry are unaffected. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/key_selection.rs | 136 ++++++++++++++++-- 1 file changed, 126 insertions(+), 10 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 6013815d05f..36de4ac4cfb 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 @@ -22,7 +22,7 @@ use dpp::state_transition::errors::{ use dpp::ProtocolError; use super::signing_key::{first_available, require_available}; -use crate::util::now_ms; +use std::time::{SystemTime, UNIX_EPOCH}; /// The key types Platform verifies an identity signature by (Drive's /// `validate_state_transition_identity_signed`). A key the caller chose is checked against @@ -91,7 +91,8 @@ impl SigningScope<'_> { /// preferred over any key with limits, whatever their security levels: a key with a budget or /// an expiry is an application key, taken only when no unlimited key qualifies. Within each /// group keys go in key-id order. A disabled key is skipped, and so is a key whose expiry has -/// passed the wall clock (the block time trails it by seconds at most). What is left of a +/// passed the wall clock (the block time trails it by seconds at most), or any key with an +/// expiry when the system clock reads before the Unix epoch. What is left of a /// budget is not known offline; a spent key is refused by Platform. /// /// `Ok(None)` means no key is eligible at all; `Err` means at least one eligible key exists @@ -104,13 +105,34 @@ pub fn usable_signing_key<'a>( key_types: &[KeyType], scope: SigningScope<'_>, ) -> Result, dash_sdk::Error> { - let now = now_ms(); + usable_signing_key_at( + identity, + signer, + purpose, + security_levels, + key_types, + scope, + wall_clock_ms(), + ) +} + +/// [`usable_signing_key`] at wall-clock time `now`, in milliseconds since the Unix epoch; +/// `None` when the clock cannot be read. +fn usable_signing_key_at<'a>( + identity: &'a Identity, + signer: &impl Signer, + purpose: Purpose, + security_levels: &[SecurityLevel], + key_types: &[KeyType], + scope: SigningScope<'_>, + now: Option, +) -> Result, dash_sdk::Error> { let qualifies = |key: &IdentityPublicKey| { key.purpose() == purpose && security_levels.contains(&key.security_level()) && key_types.contains(&key.key_type()) && !key.is_disabled() - && !key.is_expired_at(now) + && !expired_or_unknown(key, now) && scope.bounds_check(key) == BatchedTransitionBoundsCheck::Allowed }; let keys = identity.public_keys(); @@ -130,7 +152,9 @@ pub fn usable_signing_key<'a>( /// `purposes`, a security level outside `security_levels`, a key type outside `key_types`, a /// disabled key, an expired key, or contract bounds that do not cover `scope`. A key bound to /// a contract group is accepted: only Platform can read the group's memberships. A key -/// `signer` cannot sign with is refused with the signer-unavailable error. +/// `signer` cannot sign with is refused with the signer-unavailable error. A key with an +/// expiry is refused with [`dash_sdk::Error::Config`] when the system clock reads before the +/// Unix epoch, since its expiry cannot be checked. pub fn check_signing_key( key: &IdentityPublicKey, signer: &impl Signer, @@ -138,6 +162,28 @@ pub fn check_signing_key( security_levels: &[SecurityLevel], key_types: &[KeyType], scope: SigningScope<'_>, +) -> Result<(), dash_sdk::Error> { + check_signing_key_at( + key, + signer, + purposes, + security_levels, + key_types, + scope, + wall_clock_ms(), + ) +} + +/// [`check_signing_key`] at wall-clock time `now`, in milliseconds since the Unix epoch; +/// `None` when the clock cannot be read. +fn check_signing_key_at( + key: &IdentityPublicKey, + signer: &impl Signer, + purposes: &[Purpose], + security_levels: &[SecurityLevel], + key_types: &[KeyType], + scope: SigningScope<'_>, + now: Option, ) -> Result<(), dash_sdk::Error> { if !purposes.contains(&key.purpose()) { return Err( @@ -168,11 +214,19 @@ pub fn check_signing_key( ProtocolError::PublicKeyIsDisabledError(PublicKeyIsDisabledError::new(key.id())).into(), ); } - let now = now_ms(); - if let Some(expires_at) = key.expires_at().filter(|_| key.is_expired_at(now)) { - return Err(signature_refusal(SignatureError::PublicKeyExpiredError( - PublicKeyExpiredError::new(key.id(), expires_at, now), - ))); + if let Some(expires_at) = key.expires_at() { + let Some(now) = now else { + return Err(dash_sdk::Error::Config(format!( + "the system clock reads before the Unix epoch, so whether key {} has expired \ + cannot be told", + key.id() + ))); + }; + if key.is_expired_at(now) { + return Err(signature_refusal(SignatureError::PublicKeyExpiredError( + PublicKeyExpiredError::new(key.id(), expires_at, now), + ))); + } } match scope.bounds_check(key) { BatchedTransitionBoundsCheck::Allowed @@ -195,6 +249,24 @@ pub fn check_signing_key( require_available(key, signer).map(|_| ()) } +/// Whether `key` cannot be shown unexpired at `now`: its expiry has passed, or it has one and +/// the clock could not be read. A key without an expiry never expires. +fn expired_or_unknown(key: &IdentityPublicKey, now: Option) -> bool { + match (key.expires_at(), now) { + (None, _) => false, + (Some(_), None) => true, + (Some(_), Some(now)) => key.is_expired_at(now), + } +} + +/// Milliseconds since the Unix epoch, or `None` when the system clock reads before it. +fn wall_clock_ms() -> Option { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .ok() + .map(|elapsed| elapsed.as_millis() as u64) +} + fn signature_refusal(error: SignatureError) -> dash_sdk::Error { ProtocolError::ConsensusError(Box::new(ConsensusError::SignatureError(error))).into() } @@ -228,6 +300,7 @@ pub(super) mod tests { use super::super::signing_key::tests::{available, KeyFilter}; use super::*; use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; + use crate::util::now_ms; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; @@ -753,4 +826,47 @@ pub(super) mod tests { } } } + + #[test] + fn should_not_trust_an_expiry_without_a_valid_clock() { + let far_future = now_ms() + 1_000_000; + let expiring = key(1, SecurityLevel::HIGH).with_limits(None, Some(far_future)); + let pick_without_clock = |identity: &Identity| { + usable_signing_key_at( + identity, + &KeyFilter(|_| true), + Purpose::AUTHENTICATION, + &LEVELS, + &TYPES, + document_scope(), + None, + ) + .unwrap() + .map(|key| key.id()) + }; + assert_eq!( + pick_without_clock(&identity(vec![expiring.clone()])), + None, + "without a clock an expiry cannot be told from a passed one" + ); + let budget_only = key(2, SecurityLevel::HIGH).with_limits(Some(1_000), None); + assert_eq!( + pick_without_clock(&identity(vec![expiring.clone(), budget_only])), + Some(2), + "a key without an expiry does not need the clock" + ); + let refusal = check_signing_key_at( + &expiring, + &KeyFilter(|_| true), + &[Purpose::AUTHENTICATION], + &LEVELS, + &TYPES, + document_scope(), + None, + ); + assert!( + matches!(refusal, Err(dash_sdk::Error::Config(_))), + "an explicit key with an expiry is refused without a clock: {refusal:?}" + ); + } } From dd905ac3049cfe8a618d370bba1a92ef366e56d9 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:31:35 +0000 Subject: [PATCH 23/53] fix(platform-wallet): check token keys against the token, not the whole contract Consensus checks a token transition's key bounds with ContractBoundsScope::Token(position), but the wallet used the whole-contract scope, so a key bound to a contract group was reported as needing a whole-contract membership instead of the token's. SigningScope gains Token { contract_id, position }, mapped to the same scope, and automatic and explicit token key checks use it. Whole-contract flows such as DPNS registration keep SigningScope::Contract. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/key_selection.rs | 64 ++++++++++++++++++- .../wallet/identity/network/tokens/burn.rs | 10 ++- .../wallet/identity/network/tokens/claim.rs | 3 +- .../network/tokens/destroy_frozen_funds.rs | 10 ++- .../wallet/identity/network/tokens/freeze.rs | 10 ++- .../wallet/identity/network/tokens/helpers.rs | 26 +++++--- .../wallet/identity/network/tokens/mint.rs | 10 ++- .../wallet/identity/network/tokens/pause.rs | 10 ++- .../identity/network/tokens/purchase.rs | 10 ++- .../wallet/identity/network/tokens/resume.rs | 10 ++- .../identity/network/tokens/set_price.rs | 10 ++- .../identity/network/tokens/transfer.rs | 3 +- .../identity/network/tokens/unfreeze.rs | 10 ++- .../identity/network/tokens/update_config.rs | 10 ++- 14 files changed, 162 insertions(+), 34 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 36de4ac4cfb..e16a6e1f98f 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 @@ -7,6 +7,7 @@ use dpp::consensus::signature::{ PublicKeyIsDisabledError, SignatureError, }; use dpp::consensus::ConsensusError; +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; @@ -48,9 +49,14 @@ pub enum SigningScope<'a> { contract_id: Identifier, document_type_name: &'a str, }, - /// A batch acting on all of `contract_id`: a token operation, or a flow that writes more - /// than one of its document types. + /// A batch acting on all of `contract_id`: a flow that writes more than one of its + /// document types. Contract { contract_id: Identifier }, + /// A batch acting on the token at `position` of `contract_id`. + Token { + contract_id: Identifier, + position: TokenContractPosition, + }, } impl SigningScope<'_> { @@ -72,6 +78,10 @@ impl SigningScope<'_> { ContractBoundsScope::DocumentType(document_type_name), ), SigningScope::Contract { contract_id } => (contract_id, ContractBoundsScope::Contract), + SigningScope::Token { + contract_id, + position, + } => (contract_id, ContractBoundsScope::Token(position)), }; match key.contract_bounds() { Some(bounds) if key.purpose() == Purpose::AUTHENTICATION => { @@ -869,4 +879,54 @@ pub(super) mod tests { "an explicit key with an expiry is refused without a clock: {refusal:?}" ); } + + #[test] + fn should_report_a_token_scope_as_the_token_consensus_checks() { + use dpp::contract_group::ContractGroupMember; + let contract_id = Identifier::from(CONTRACT); + let token = SigningScope::Token { + contract_id, + position: 3, + }; + let group_bound = bound_key( + 1, + SecurityLevel::CRITICAL, + Some(ContractBounds::ContractGroup { + id: Identifier::from(OTHER_CONTRACT), + }), + ); + assert!( + matches!( + token.bounds_check(&group_bound), + BatchedTransitionBoundsCheck::RequiresContractGroupMembership { + contract_id: member_contract, + member: ContractGroupMember::Token(3), + .. + } if member_contract == contract_id + ), + "{:?}", + token.bounds_check(&group_bound) + ); + let bound_here = bound_key( + 2, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContract { id: contract_id }), + ); + assert_eq!( + token.bounds_check(&bound_here), + BatchedTransitionBoundsCheck::Allowed + ); + let bound_to_a_document_type = bound_key( + 3, + SecurityLevel::CRITICAL, + Some(ContractBounds::SingleContractDocumentType { + id: contract_id, + document_type_name: DOCUMENT_TYPE.to_string(), + }), + ); + assert_eq!( + token.bounds_check(&bound_to_a_document_type), + BatchedTransitionBoundsCheck::Denied + ); + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs index 64a222af1c9..4f64f98a63f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs @@ -33,7 +33,13 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::burn::TokenBurnTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenBurnTransitionBuilder::new(data_contract, token_position, identity_id, amount); @@ -67,7 +73,7 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_burn_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs index 1e98d345c1a..3792441fded 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs @@ -35,6 +35,7 @@ impl IdentityWallet { signing_key, signer, &data_contract, + token_position, &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, )?; @@ -69,7 +70,7 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_claim_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs index bbd548e8cef..af1214f3741 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs @@ -35,7 +35,13 @@ impl IdentityWallet { { use dash_sdk::platform::tokens::builders::destroy::TokenDestroyFrozenFundsTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenDestroyFrozenFundsTransitionBuilder::new( data_contract, @@ -77,7 +83,7 @@ impl IdentityWallet { > { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_destroy_frozen_funds_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs index c7756fd4196..8e8821cacf3 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs @@ -32,7 +32,13 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::freeze::TokenFreezeTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenFreezeTransitionBuilder::new( data_contract, @@ -70,7 +76,7 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_freeze_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 80785a5ce49..14e72908470 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -19,7 +19,7 @@ use super::super::key_selection::{ use std::sync::Arc; use dpp::data_contract::accessors::v0::DataContractV0Getters; -use dpp::data_contract::DataContract; +use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, Purpose, SecurityLevel}; use dpp::prelude::Identifier; @@ -32,11 +32,12 @@ use crate::wallet::identity::network::IdentityWallet; /// batch with a token transition. const TOKEN_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; -/// The key that signs a token operation of `token_contract_id`: a CRITICAL AUTHENTICATION -/// ECDSA key whose bounds cover the whole contract, since token operations are contract-wide. +/// The key that signs an operation on the token at `position` of `token_contract_id`: a +/// CRITICAL AUTHENTICATION ECDSA key whose bounds cover that token. fn token_signing_key<'a>( identity: &'a Identity, token_contract_id: Identifier, + position: TokenContractPosition, signer: &impl Signer, ) -> Result, dash_sdk::Error> { usable_signing_key( @@ -45,8 +46,9 @@ fn token_signing_key<'a>( Purpose::AUTHENTICATION, &TOKEN_SIGNING_LEVELS, &WALLET_SIGNING_KEY_TYPES, - SigningScope::Contract { + SigningScope::Token { contract_id: token_contract_id, + position, }, ) } @@ -59,7 +61,8 @@ pub(super) const TOKEN_SIGNING_PURPOSES: [Purpose; 1] = [Purpose::AUTHENTICATION pub(super) const LONE_TOKEN_TRANSFER_SIGNING_PURPOSES: [Purpose; 2] = [Purpose::AUTHENTICATION, Purpose::TRANSFER]; -/// Check a key the caller chose to sign a token operation of `data_contract`, with one of +/// Check a key the caller chose to sign an operation on the token at `position` of +/// `data_contract`, with one of /// `purposes`, by the rules [`token_signing_key`] applies except that any key type Platform /// verifies is accepted, so a key Platform would refuse fails before any request. Contract /// bounds limit only an AUTHENTICATION key. @@ -67,6 +70,7 @@ pub(super) fn check_token_signing_key( key: &IdentityPublicKey, signer: &impl Signer, data_contract: &DataContract, + position: TokenContractPosition, purposes: &[Purpose], ) -> Result<(), dash_sdk::Error> { check_signing_key( @@ -75,8 +79,9 @@ pub(super) fn check_token_signing_key( purposes, &TOKEN_SIGNING_LEVELS, &PLATFORM_SIGNING_KEY_TYPES, - SigningScope::Contract { + SigningScope::Token { contract_id: data_contract.id(), + position, }, ) } @@ -97,6 +102,7 @@ impl IdentityWallet { &self, identity_id: &Identifier, token_contract_id: Identifier, + token_position: TokenContractPosition, signer: &impl Signer, ) -> Result { let wm = self.wallet_manager.read().await; @@ -111,7 +117,7 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; drop(wm); - let signing_key = token_signing_key(&identity, token_contract_id, signer)? + let signing_key = token_signing_key(&identity, token_contract_id, token_position, signer)? .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { identity_id: *identity_id, purpose: Purpose::AUTHENTICATION, @@ -384,7 +390,7 @@ mod signing_tests { let wallet = wallet_with_identity(identity).await; let error = wallet .identity() - .token_resolve_signing_key(&identity_id, Identifier::default(), &KeyFilter(|_| true)) + .token_resolve_signing_key(&identity_id, Identifier::default(), 0, &KeyFilter(|_| true)) .await .unwrap_err(); assert_no_usable_key(error, identity_id, SecurityLevel::CRITICAL); @@ -396,7 +402,7 @@ mod signing_tests { let signer = lock_checking_signer(wallet.identity()); let error = wallet .identity() - .token_resolve_signing_key(&Identifier::default(), Identifier::default(), &signer) + .token_resolve_signing_key(&Identifier::default(), Identifier::default(), 0, &signer) .await .unwrap_err(); assert!(error.to_string().contains("available to signer"), "{error}"); @@ -421,7 +427,7 @@ mod signing_tests { key(2, SecurityLevel::CRITICAL).with_limits(Some(1_000), None), key(3, SecurityLevel::CRITICAL), ]); - let chosen = token_signing_key(&identity, token_contract, &KeyFilter(|_| true)).unwrap(); + let chosen = token_signing_key(&identity, token_contract, 0, &KeyFilter(|_| true)).unwrap(); assert_eq!( chosen.map(|key| key.id()), Some(3), diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs index 2443d759e5c..8130c7790a0 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs @@ -42,7 +42,13 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::mint::TokenMintTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; // Contracts with `minting_allow_choosing_destination = false` // reject any mint where `issued_to_identity_id.is_some()` at @@ -122,7 +128,7 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_mint_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs index e639e58943a..a73c2be28f7 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs @@ -33,7 +33,13 @@ impl IdentityWallet { { use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenEmergencyActionTransitionBuilder::pause( data_contract, @@ -70,7 +76,7 @@ impl IdentityWallet { { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_pause_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs index c9245f4b39a..02936e9657b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs @@ -39,7 +39,13 @@ impl IdentityWallet { { use dash_sdk::platform::tokens::builders::purchase::TokenDirectPurchaseTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenDirectPurchaseTransitionBuilder::new( data_contract, @@ -69,7 +75,7 @@ impl IdentityWallet { { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_purchase_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs index 498504d47b3..b8ae3d56342 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs @@ -32,7 +32,13 @@ impl IdentityWallet { { use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenEmergencyActionTransitionBuilder::resume( data_contract, @@ -69,7 +75,7 @@ impl IdentityWallet { { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_resume_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs index 89191465f1c..56fcf074b7a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs @@ -40,7 +40,13 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::set_price::TokenChangeDirectPurchasePriceTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenChangeDirectPurchasePriceTransitionBuilder::new( data_contract, @@ -87,7 +93,7 @@ impl IdentityWallet { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; let pricing_schedule = if price_per_token == 0 { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs index 8620f0a56df..19de10f558a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs @@ -39,6 +39,7 @@ impl IdentityWallet { signing_key, signer, &data_contract, + token_position, &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, )?; @@ -77,7 +78,7 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&from_identity_id, token_contract_id, signer) + .token_resolve_signing_key(&from_identity_id, token_contract_id, token_position, signer) .await?; self.token_transfer_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs index 42524737223..f1a9f383e53 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs @@ -32,7 +32,13 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::unfreeze::TokenUnfreezeTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenUnfreezeTransitionBuilder::new( data_contract, @@ -72,7 +78,7 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_unfreeze_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs index bb800883644..aabdd4839eb 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs @@ -34,7 +34,13 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::config_update::TokenConfigUpdateTransitionBuilder; - check_token_signing_key(signing_key, signer, &data_contract, &TOKEN_SIGNING_PURPOSES)?; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + &TOKEN_SIGNING_PURPOSES, + )?; let mut builder = TokenConfigUpdateTransitionBuilder::new( data_contract, @@ -76,7 +82,7 @@ impl IdentityWallet { { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, signer) + .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) .await?; self.token_update_config_with_signer( From a41a26b80abbce600e6b75cc25ce03f1b9846e62 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:31:35 +0000 Subject: [PATCH 24/53] fix(platform-wallet): derive the DPNS registration key level from the contract DPNS registration required a HIGH key from a hard-coded constant. It now takes the strongest signature requirement of the DPNS contract's preorder and domain document types, since one key signs both: the automatic path reads the contract it already fetches, and register_name_with_signer loads the bundled contract for the SDK's protocol version, so neither makes an extra request. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/dpns.rs | 105 ++++++++++++++---- 1 file changed, 81 insertions(+), 24 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index fbfd157e76c..de17fe55dfe 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -2,7 +2,11 @@ use super::document::{check_document_signing_key, document_signing_key}; use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dpp::data_contract::DataContract; use dpp::data_contracts::SystemDataContract; +use dpp::system_data_contracts::load_system_data_contract; use dpp::fee::Credits; @@ -42,22 +46,36 @@ use super::*; /// without forcing a clone or `Arc` round-trip per call. struct SignerRef<'a, S: ?Sized>(&'a S); -/// The security level both DPNS registration documents require. -const DPNS_REGISTRATION_REQUIREMENT: SecurityLevel = SecurityLevel::HIGH; +/// The document types a DPNS registration writes, in order, all signed by one key. +const DPNS_REGISTRATION_DOCUMENT_TYPES: [&str; 2] = ["preorder", "domain"]; + +/// The security level the key signing a registration must meet: the strongest that `dpns`'s +/// `preorder` and `domain` document types require. +fn dpns_registration_requirement(dpns: &DataContract) -> Result { + DPNS_REGISTRATION_DOCUMENT_TYPES.into_iter().try_fold( + SecurityLevel::MEDIUM, + |strongest, document_type_name| { + let required = dpns + .document_type_for_name(document_type_name)? + .security_level_requirement(); + Ok(if required.stronger_security_than(strongest) { + required + } else { + strongest + }) + }, + ) +} -/// The key that signs both DPNS registration documents, `preorder` then `domain`: a HIGH or -/// CRITICAL AUTHENTICATION ECDSA key whose bounds cover the whole DPNS contract. MASTER is -/// reserved for identity operations and refused on document writes. +/// The key that signs both DPNS registration documents, `preorder` then `domain`: an +/// AUTHENTICATION ECDSA key meeting `requirement` whose bounds cover the whole DPNS contract. +/// MASTER is reserved for identity operations and refused on document writes. fn dpns_registration_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, + requirement: SecurityLevel, ) -> Result, dash_sdk::Error> { - document_signing_key( - identity, - signer, - DPNS_REGISTRATION_REQUIREMENT, - dpns_registration_scope(), - ) + document_signing_key(identity, signer, requirement, dpns_registration_scope()) } /// Check a key the caller chose to register a DPNS name by the rules @@ -65,13 +83,9 @@ fn dpns_registration_signing_key<'a>( fn check_dpns_registration_signing_key( key: &IdentityPublicKey, signer: &impl Signer, + requirement: SecurityLevel, ) -> Result<(), dash_sdk::Error> { - check_document_signing_key( - key, - signer, - DPNS_REGISTRATION_REQUIREMENT, - dpns_registration_scope(), - ) + check_document_signing_key(key, signer, requirement, dpns_registration_scope()) } /// Registration writes `preorder` and then `domain`, so its key must cover the whole contract. @@ -191,7 +205,12 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::dpns_usernames::RegisterDpnsNameInput; - check_dpns_registration_signing_key(&identity_public_key, &signer)?; + let dpns = load_system_data_contract(SystemDataContract::DPNS, self.sdk.version())?; + check_dpns_registration_signing_key( + &identity_public_key, + &signer, + dpns_registration_requirement(&dpns)?, + )?; let input = RegisterDpnsNameInput { label: name.to_string(), identity, @@ -250,7 +269,8 @@ impl IdentityWallet { // consumer) would otherwise fail proof verification with // "unknown contract ... in document verification" even though // the registration landed on-chain. - self.dpns_contract().await?; + let dpns = self.dpns_contract().await?; + let requirement = dpns_registration_requirement(&dpns).map_err(dash_sdk::Error::from)?; let (identity, auth_key) = { let wm = self.wallet_manager.read().await; @@ -265,13 +285,11 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; drop(wm); - let key = dpns_registration_signing_key(&identity, signer)? + let key = dpns_registration_signing_key(&identity, signer, requirement)? .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { identity_id: *identity_id, purpose: Purpose::AUTHENTICATION, - security_levels: SecurityLevel::accepted_for_requirement( - DPNS_REGISTRATION_REQUIREMENT, - ), + security_levels: SecurityLevel::accepted_for_requirement(requirement), key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "a DPNS name registration".to_string(), })? @@ -606,7 +624,9 @@ mod signing_key_tests { Some(ContractBounds::SingleContract { id: dpns }), ), ]); - let chosen = dpns_registration_signing_key(&identity, &KeyFilter(|_| true)).unwrap(); + let chosen = + dpns_registration_signing_key(&identity, &KeyFilter(|_| true), SecurityLevel::HIGH) + .unwrap(); assert_eq!( chosen.map(|key| key.id()), Some(2), @@ -673,4 +693,41 @@ mod signing_key_tests { "Platform verifies an ECDSA_HASH160 signature, so the request goes out: {error:?}" ); } + + #[test] + fn should_require_the_strongest_level_of_both_registration_documents() { + use dpp::data_contract::serialized_version::DataContractInSerializationFormat; + use dpp::platform_value::Value; + use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; + + let platform_version = PlatformVersion::latest(); + let dpns = load_system_data_contract(SystemDataContract::DPNS, platform_version) + .expect("bundled DPNS contract"); + assert_eq!( + dpns_registration_requirement(&dpns).unwrap(), + SecurityLevel::HIGH + ); + let mut format = + DataContractInSerializationFormat::try_from_platform_versioned(dpns, platform_version) + .expect("serialization format") + .into_schema_form(); + format + .document_schemas_mut() + .expect("schema form") + .get_mut("domain") + .expect("domain schema") + .set_value( + "signatureSecurityLevelRequirement", + Value::U8(SecurityLevel::CRITICAL as u8), + ) + .expect("schema is a map"); + let stricter_domain = + DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) + .expect("a valid contract"); + assert_eq!( + dpns_registration_requirement(&stricter_domain).unwrap(), + SecurityLevel::CRITICAL, + "one key signs both documents, so it must meet the stricter one" + ); + } } From eb09e53153d7abf493e5c48068e001ab1e9e38fc Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:31:35 +0000 Subject: [PATCH 25/53] fix(platform-wallet): sign a withdrawal to a chosen address only with TRANSFER Platform refuses an OWNER key for a withdrawal that names its own output address (WithdrawalOutputScriptNotAllowedWhenSigningWithOwnerKeyError); OWNER signs only a withdrawal to the identity's payout address. Both withdrawal paths allowed OWNER regardless, for explicit keys and as the automatic fallback. They now allow it only when no address is given. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/signing_key.rs | 60 ++++++++++++++++++- .../src/wallet/identity/network/withdrawal.rs | 13 +++- 2 files changed, 67 insertions(+), 6 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 54cfe5e49dc..8e152f87d53 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -84,9 +84,11 @@ pub(super) fn master_signing_key<'a>( ) } -/// The key that signs a credit transfer, or a withdrawal when `allow_owner`. An explicit key -/// is never substituted; it is checked by the rules automatic selection applies, and refused -/// with Platform's typed error. Automatic withdrawals exhaust TRANSFER keys before OWNER. +/// The key that signs a credit transfer or withdrawal: a TRANSFER key, or an OWNER key when +/// `allow_owner`, which only a withdrawal to the identity's payout address sets. An explicit +/// key is never substituted; it is checked by the rules automatic selection applies, and +/// refused with Platform's typed error. Automatic withdrawals exhaust TRANSFER keys before +/// OWNER. pub(super) fn credit_signing_key<'a>( identity: &'a Identity, explicit: Option<&'a IdentityPublicKey>, @@ -522,6 +524,58 @@ pub(super) mod tests { } } + #[tokio::test] + async fn should_not_sign_a_withdrawal_to_an_address_with_an_owner_key() { + use dashcore::{Address as DashAddress, Network}; + + let wallet = wallet_with_signing_keys().await; + let identity = identity( + Purpose::OWNER, + SecurityLevel::CRITICAL, + KeyType::ECDSA_HASH160, + ); + let to_address = Some(DashAddress::dummy(Network::Testnet, 1)); + let automatic = wallet + .identity() + .withdraw_credits_with_signer( + &identity, + to_address.clone(), + 1, + None, + available(&[1, 2]), + None, + ) + .await; + assert!( + matches!( + automatic, + Err(dash_sdk::Error::Protocol( + ProtocolError::DesiredKeyWithTypePurposeSecurityLevelMissing(_) + )) + ), + "only an OWNER key is held, and it cannot sign this withdrawal: {automatic:?}" + ); + let explicit = wallet + .identity() + .withdraw_credits_with_signer( + &identity, + to_address, + 1, + identity.public_keys().get(&1), + available(&[1, 2]), + None, + ) + .await; + assert!( + matches!( + explicit, + Err(dash_sdk::Error::Protocol(ProtocolError::WrongPublicKeyPurposeError(ref error))) + if error.allowed_key_purposes() == &vec![Purpose::TRANSFER] + ), + "Platform refuses an OWNER key for a withdrawal to a chosen address: {explicit:?}" + ); + } + pub(crate) async fn wallet_with_signing_keys() -> Arc { wallet_with_identity(identity( Purpose::AUTHENTICATION, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/withdrawal.rs b/packages/rs-platform-wallet/src/wallet/identity/network/withdrawal.rs index c9484d071d0..672787d50be 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/withdrawal.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/withdrawal.rs @@ -102,7 +102,8 @@ impl IdentityWallet { Some(to_address.clone()), amount, None, // core_fee_per_byte - Some(credit_signing_key(&identity, None, signer, true)?), + // Platform refuses an OWNER key for a withdrawal to a chosen address. + Some(credit_signing_key(&identity, None, signer, false)?), SignerRef(signer), settings, ) @@ -159,8 +160,14 @@ impl IdentityWallet { signer: S, settings: Option, ) -> Result { - let signing_key = - credit_signing_key(identity, signing_withdrawal_key_to_use, &signer, true)?; + // Platform takes an OWNER key only for a withdrawal to the identity's payout address + // (no `to_address`). + let signing_key = credit_signing_key( + identity, + signing_withdrawal_key_to_use, + &signer, + to_address.is_none(), + )?; identity .withdraw( &self.sdk, From b24cba2cbf46daad1735a7681c4f2c374638747e Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 14:59:29 +0000 Subject: [PATCH 26/53] fix(platform-wallet): pick an automatic credit key only of a type Drive verifies The automatic credit path filtered keys with KeyType::all_key_types(), so it could choose a BIP13_SCRIPT_HASH or EDDSA_25519_HASH160 TRANSFER or OWNER key that Drive cannot verify a signature by, while the explicit path already refused those. Both paths now use PLATFORM_SIGNING_KEY_TYPES, which keeps ECDSA_HASH160 transfer keys selectable. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/signing_key.rs | 35 +++++++++++++++++-- 1 file changed, 33 insertions(+), 2 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 8e152f87d53..9f84cc04c22 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -7,7 +7,7 @@ use super::key_selection::{ use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; -use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; +use dpp::identity::{Identity, IdentityPublicKey, Purpose, SecurityLevel}; use dpp::ProtocolError; /// Preserve the signer's unavailable-key discriminator through SDK and FFI errors. @@ -117,7 +117,7 @@ pub(super) fn credit_signing_key<'a>( signer, purpose, &SecurityLevel::full_range(), - &KeyType::all_key_types(), + &PLATFORM_SIGNING_KEY_TYPES, SigningScope::NonBatch, ) { Ok(Some(key)) => return Ok(key), @@ -144,6 +144,7 @@ pub(super) mod tests { use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::identity::KeyType; use dpp::platform_value::BinaryData; use dpp::prelude::Identifier; use dpp::version::PlatformVersion; @@ -296,6 +297,36 @@ pub(super) mod tests { } } + #[test] + fn should_pick_only_a_credit_key_of_a_type_platform_verifies() { + let mut identity = identity( + Purpose::TRANSFER, + SecurityLevel::CRITICAL, + KeyType::ECDSA_HASH160, + ); + for (id, key_type) in [ + (1, KeyType::BIP13_SCRIPT_HASH), + (2, KeyType::EDDSA_25519_HASH160), + ] { + identity + .public_keys_mut() + .get_mut(&id) + .unwrap() + .set_key_type(key_type); + } + let mut verifiable = identity.public_keys().get(&2).unwrap().clone(); + verifiable.set_id(3); + verifiable.set_key_type(KeyType::ECDSA_HASH160); + identity.add_public_key(verifiable); + assert_eq!( + credit_signing_key(&identity, None, &available(&[1, 2, 3]), false) + .unwrap() + .id(), + 3, + "Drive cannot verify a signature by keys 1 and 2" + ); + } + #[test] fn should_skip_disabled_transfer_keys_before_owner_fallback() { let mut identity = identity( From 96f27ac312b4094c80d4dd7c88b57e1f8d48f947 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:00:34 +0000 Subject: [PATCH 27/53] docs(platform-wallet): note the credit-key exception on the key-type constants Automatic credit transfer and withdrawal selection picks from PLATFORM_SIGNING_KEY_TYPES, not WALLET_SIGNING_KEY_TYPES; both doc comments now say so. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/key_selection.rs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 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 e16a6e1f98f..935fe3d3bcc 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 @@ -27,15 +27,18 @@ use std::time::{SystemTime, UNIX_EPOCH}; /// The key types Platform verifies an identity signature by (Drive's /// `validate_state_transition_identity_signed`). A key the caller chose is checked against -/// these, not against the narrower set the wallet picks its own keys from. +/// these, and so is the wallet's own choice of a credit transfer or withdrawal key, so an +/// `ECDSA_HASH160` TRANSFER key stays usable. Other automatic selection uses the narrower +/// [`WALLET_SIGNING_KEY_TYPES`]. pub(crate) const PLATFORM_SIGNING_KEY_TYPES: [KeyType; 3] = [ KeyType::ECDSA_SECP256K1, KeyType::BLS12_381, KeyType::ECDSA_HASH160, ]; -/// The key types the wallet picks its own signing keys from. A key the caller chose is checked -/// against [`PLATFORM_SIGNING_KEY_TYPES`] instead. +/// The key types the wallet picks its own signing keys from, except for a credit transfer or +/// withdrawal key, which may be any of [`PLATFORM_SIGNING_KEY_TYPES`]. A key the caller chose +/// is checked against [`PLATFORM_SIGNING_KEY_TYPES`] instead. pub(crate) const WALLET_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; /// What a signature authorizes, as far as a key's contract bounds go. From ab842efbede4e3c4ef90f7431a92c86ae5bbfb19 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:56:43 +0000 Subject: [PATCH 28/53] fix(platform-wallet): refuse a wrong-purpose key with Drive's consensus error check_signing_key reported a purpose mismatch as ProtocolError::WrongPublicKeyPurposeError (code 20005), while Drive's identity-signed validation returns the consensus SignatureError::InvalidSignaturePublicKeyPurposeError (20011). It now returns the consensus error, as the disabled, expired and bounds refusals already do, so a host sees the code Platform would send. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/key_selection.rs | 48 ++++++++++++------- .../wallet/identity/network/signing_key.rs | 28 ++++------- .../wallet/identity/network/tokens/helpers.rs | 13 +++-- 3 files changed, 46 insertions(+), 43 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 935fe3d3bcc..2466359a792 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 @@ -3,8 +3,9 @@ use dpp::consensus::signature::InvalidSignaturePublicKeySecurityLevelError; use dpp::consensus::signature::{ - ContractBoundedKeyNonBatchError, ContractBoundedKeyOutOfBoundsError, PublicKeyExpiredError, - PublicKeyIsDisabledError, SignatureError, + ContractBoundedKeyNonBatchError, ContractBoundedKeyOutOfBoundsError, + InvalidSignaturePublicKeyPurposeError, PublicKeyExpiredError, PublicKeyIsDisabledError, + SignatureError, }; use dpp::consensus::ConsensusError; use dpp::data_contract::TokenContractPosition; @@ -17,9 +18,7 @@ use dpp::identity::identity_public_key::contract_bounds::{ use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; use dpp::prelude::Identifier; -use dpp::state_transition::errors::{ - InvalidIdentityPublicKeyTypeError, WrongPublicKeyPurposeError, -}; +use dpp::state_transition::errors::InvalidIdentityPublicKeyTypeError; use dpp::ProtocolError; use super::signing_key::{first_available, require_available}; @@ -199,13 +198,11 @@ fn check_signing_key_at( now: Option, ) -> Result<(), dash_sdk::Error> { if !purposes.contains(&key.purpose()) { - return Err( - ProtocolError::WrongPublicKeyPurposeError(WrongPublicKeyPurposeError::new( - key.purpose(), - purposes.to_vec(), - )) - .into(), - ); + return Err(signature_refusal( + SignatureError::InvalidSignaturePublicKeyPurposeError( + InvalidSignaturePublicKeyPurposeError::new(key.purpose(), purposes.to_vec()), + ), + )); } if !security_levels.contains(&key.security_level()) { return Err(ProtocolError::InvalidSignaturePublicKeySecurityLevelError( @@ -672,6 +669,20 @@ pub(super) mod tests { } } + /// The purposes `error` names when it is Platform's purpose refusal. + pub(crate) fn refused_purposes(error: &dash_sdk::Error) -> Option> { + match error { + dash_sdk::Error::Protocol(ProtocolError::ConsensusError(error)) => match error.as_ref() + { + ConsensusError::SignatureError( + SignatureError::InvalidSignaturePublicKeyPurposeError(error), + ) => Some(error.allowed_key_purposes().clone()), + _ => None, + }, + _ => None, + } + } + fn signature_error(result: Result<(), dash_sdk::Error>) -> SignatureError { match result { Err(dash_sdk::Error::Protocol(ProtocolError::ConsensusError(error))) => match *error { @@ -702,12 +713,13 @@ pub(super) mod tests { fn should_refuse_an_explicit_key_with_the_error_platform_returns() { let mut wrong_purpose = key(1, SecurityLevel::HIGH); wrong_purpose.set_purpose(Purpose::TRANSFER); - assert!(matches!( - check(&wrong_purpose, document_scope()), - Err(dash_sdk::Error::Protocol( - ProtocolError::WrongPublicKeyPurposeError(_) - )) - )); + assert_eq!( + check(&wrong_purpose, document_scope()) + .as_ref() + .err() + .and_then(refused_purposes), + Some(vec![Purpose::AUTHENTICATION]) + ); assert!(matches!( check(&key(1, SecurityLevel::MASTER), document_scope()), Err(dash_sdk::Error::Protocol( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 9f84cc04c22..e34557c2085 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -137,6 +137,7 @@ pub(super) fn credit_signing_key<'a>( #[cfg(test)] pub(super) mod tests { + use super::super::key_selection::tests::refused_purposes; use super::*; use crate::{PlatformWallet, PlatformWalletError}; use async_trait::async_trait; @@ -496,20 +497,14 @@ pub(super) mod tests { ), "Platform refuses a disabled signing key" ); - assert!( - matches!( - explicit(3, false), - Err(dash_sdk::Error::Protocol(ProtocolError::WrongPublicKeyPurposeError(ref error))) - if error.allowed_key_purposes() == &vec![Purpose::TRANSFER] - ), + assert_eq!( + explicit(3, false).as_ref().err().and_then(refused_purposes), + Some(vec![Purpose::TRANSFER]), "a credit transfer takes only a TRANSFER key" ); - assert!( - matches!( - explicit(4, true), - Err(dash_sdk::Error::Protocol(ProtocolError::WrongPublicKeyPurposeError(ref error))) - if error.allowed_key_purposes() == &vec![Purpose::TRANSFER, Purpose::OWNER] - ), + assert_eq!( + explicit(4, true).as_ref().err().and_then(refused_purposes), + Some(vec![Purpose::TRANSFER, Purpose::OWNER]), "a withdrawal names both purposes it takes" ); assert!( @@ -597,12 +592,9 @@ pub(super) mod tests { None, ) .await; - assert!( - matches!( - explicit, - Err(dash_sdk::Error::Protocol(ProtocolError::WrongPublicKeyPurposeError(ref error))) - if error.allowed_key_purposes() == &vec![Purpose::TRANSFER] - ), + assert_eq!( + explicit.as_ref().err().and_then(refused_purposes), + Some(vec![Purpose::TRANSFER]), "Platform refuses an OWNER key for a withdrawal to a chosen address: {explicit:?}" ); } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 14e72908470..da5341dbc88 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -166,7 +166,9 @@ impl IdentityWallet { #[cfg(test)] mod signing_tests { use super::*; - use crate::wallet::identity::network::key_selection::tests::{bound_key, key}; + use crate::wallet::identity::network::key_selection::tests::{ + bound_key, key, refused_purposes, + }; use crate::wallet::identity::network::signing_key::tests::{ assert_no_usable_key, identity as identity_with_keys, lock_checking_signer, wallet_with_identity, wallet_with_signing_keys, KeyFilter, @@ -282,12 +284,9 @@ mod signing_tests { .await .err() .expect("the key must be refused"); - assert!( - matches!( - burn, - dash_sdk::Error::Protocol(ProtocolError::WrongPublicKeyPurposeError(ref error)) - if error.allowed_key_purposes() == &vec![Purpose::AUTHENTICATION] - ), + assert_eq!( + refused_purposes(&burn), + Some(vec![Purpose::AUTHENTICATION]), "only a lone transfer or claim takes a TRANSFER key: {burn:?}" ); } From 6ffd86a91107d72b61ec54b55bc93e2950c7f3e7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:56:43 +0000 Subject: [PATCH 29/53] fix(platform-wallet): sign credit transfers and withdrawals only with a CRITICAL key Credit transfer and both withdrawal generations accept only CRITICAL keys (identity_signed security_level_requirement), but credit_signing_key accepted any level, so an explicit HIGH TRANSFER or OWNER key passed the check and automatic selection could take a HIGH key before a CRITICAL one. Both paths now use one CRITICAL-only slice. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/signing_key.rs | 55 ++++++++++++++++--- 1 file changed, 48 insertions(+), 7 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index e34557c2085..d5820041e0d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -84,11 +84,14 @@ pub(super) fn master_signing_key<'a>( ) } -/// The key that signs a credit transfer or withdrawal: a TRANSFER key, or an OWNER key when -/// `allow_owner`, which only a withdrawal to the identity's payout address sets. An explicit -/// key is never substituted; it is checked by the rules automatic selection applies, and -/// refused with Platform's typed error. Automatic withdrawals exhaust TRANSFER keys before -/// OWNER. +/// The security levels a credit transfer or withdrawal accepts, whatever the key's purpose. +const CREDIT_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; + +/// The key that signs a credit transfer or withdrawal: a CRITICAL TRANSFER key, or a CRITICAL +/// OWNER key when `allow_owner`, which only a withdrawal to the identity's payout address sets. +/// An explicit key is never substituted; it is checked by the rules automatic selection +/// applies, and refused with Platform's typed error. Automatic withdrawals exhaust TRANSFER +/// keys before OWNER. pub(super) fn credit_signing_key<'a>( identity: &'a Identity, explicit: Option<&'a IdentityPublicKey>, @@ -104,7 +107,7 @@ pub(super) fn credit_signing_key<'a>( key, signer, &purposes, - &SecurityLevel::full_range(), + &CREDIT_SIGNING_LEVELS, &PLATFORM_SIGNING_KEY_TYPES, SigningScope::NonBatch, )?; @@ -116,7 +119,7 @@ pub(super) fn credit_signing_key<'a>( identity, signer, purpose, - &SecurityLevel::full_range(), + &CREDIT_SIGNING_LEVELS, &PLATFORM_SIGNING_KEY_TYPES, SigningScope::NonBatch, ) { @@ -298,6 +301,44 @@ pub(super) mod tests { } } + #[test] + fn should_sign_credit_operations_only_with_a_critical_key() { + let mut identity = identity( + Purpose::TRANSFER, + SecurityLevel::HIGH, + KeyType::ECDSA_HASH160, + ); + let mut critical = identity.public_keys().get(&2).unwrap().clone(); + critical.set_id(3); + critical.set_security_level(SecurityLevel::CRITICAL); + identity.add_public_key(critical); + let mut owner = identity.public_keys().get(&2).unwrap().clone(); + owner.set_id(4); + owner.set_purpose(Purpose::OWNER); + identity.add_public_key(owner); + let signer = available(&[1, 2, 3, 4]); + assert_eq!( + credit_signing_key(&identity, None, &signer, true) + .unwrap() + .id(), + 3, + "the HIGH TRANSFER keys 1 and 2 are skipped" + ); + for id in [1, 4] { + let refusal = + credit_signing_key(&identity, identity.public_keys().get(&id), &signer, true); + assert!( + matches!( + refusal, + Err(dash_sdk::Error::Protocol( + ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) + )) + ), + "credit transitions take only a CRITICAL key: {refusal:?}" + ); + } + } + #[test] fn should_pick_only_a_credit_key_of_a_type_platform_verifies() { let mut identity = identity( From dd67de2a301f631fc67d930b4d638edc00a411fb Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 15:56:43 +0000 Subject: [PATCH 30/53] fix(platform-wallet): derive the contact-request key level from the DashPay contract The contact-request selector required a HIGH key from a hard-coded constant. It now reads the contactRequest document type's signature requirement from the bundled DashPay contract for the SDK's protocol version, so no request is made for it. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/contact_requests.rs | 92 +++++++++++++++---- 1 file changed, 73 insertions(+), 19 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index b0834b56d57..0d182436b86 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -2,6 +2,9 @@ use super::document::document_signing_key; use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dpp::data_contract::DataContract; use dpp::data_contracts::SystemDataContract; use dpp::document::DocumentV0Getters; use dpp::identity::accessors::IdentityGettersV0; @@ -14,6 +17,8 @@ use dpp::identity::KeyType; use dpp::identity::SecurityLevel; use dpp::platform_value::Value; use dpp::prelude::Identifier; +use dpp::system_data_contracts::load_system_data_contract; +use dpp::ProtocolError; use super::contacts::{ExternalAccountRegistration, RegisterExternalError}; use super::sdk_writer::SendContactRequestParams; @@ -618,17 +623,21 @@ impl DashPayView<'_, B> { }; // 5. Build the signing key reference for document signing. - let identity_public_key = contact_request_signing_key(&sender_identity, signer)? - .cloned() - .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { - identity_id: *sender_identity_id, - purpose: Purpose::AUTHENTICATION, - security_levels: SecurityLevel::accepted_for_requirement( - CONTACT_REQUEST_REQUIREMENT, - ), - key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), - transition: "a contactRequest document transition".to_string(), - })?; + // The level comes from the bundled DashPay contract for the SDK's + // protocol version, so no request is made for it. + let dashpay = load_system_data_contract(SystemDataContract::Dashpay, self.sdk.version()) + .map_err(dash_sdk::Error::from)?; + let requirement = contact_request_requirement(&dashpay).map_err(dash_sdk::Error::from)?; + let identity_public_key = + contact_request_signing_key(&sender_identity, signer, requirement)? + .cloned() + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *sender_identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement(requirement), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: "a contactRequest document transition".to_string(), + })?; // 6. Client-side ECDH via the signer: the shared secret is derived in // the signer (scalar at `sender_enc_path`) against the recipient's @@ -1224,24 +1233,32 @@ fn select_recipient_key_index(recipient_identity: &Identity) -> Result Result { + Ok(dashpay + .document_type_for_name(CONTACT_REQUEST_DOCUMENT_TYPE)? + .security_level_requirement()) +} + +/// The key that signs an outgoing `contactRequest` document: an AUTHENTICATION ECDSA key +/// meeting `requirement` whose bounds cover `contactRequest`. MASTER is rejected on document /// writes. fn contact_request_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, + requirement: SecurityLevel, ) -> Result, dash_sdk::Error> { document_signing_key( identity, signer, - CONTACT_REQUEST_REQUIREMENT, + requirement, SigningScope::DocumentType { contract_id: SystemDataContract::Dashpay.id(), - document_type_name: "contactRequest", + document_type_name: CONTACT_REQUEST_DOCUMENT_TYPE, }, ) } @@ -6621,6 +6638,43 @@ mod contact_request_key_tests { use super::*; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + #[test] + fn should_require_the_level_the_contact_request_document_type_requires() { + use dpp::data_contract::serialized_version::DataContractInSerializationFormat; + use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; + + let platform_version = PlatformVersion::latest(); + let dashpay = load_system_data_contract(SystemDataContract::Dashpay, platform_version) + .expect("bundled DashPay contract"); + assert_eq!( + contact_request_requirement(&dashpay).unwrap(), + SecurityLevel::HIGH + ); + let mut format = DataContractInSerializationFormat::try_from_platform_versioned( + dashpay, + platform_version, + ) + .expect("serialization format") + .into_schema_form(); + format + .document_schemas_mut() + .expect("schema form") + .get_mut(CONTACT_REQUEST_DOCUMENT_TYPE) + .expect("contactRequest schema") + .set_value( + "signatureSecurityLevelRequirement", + Value::U8(SecurityLevel::CRITICAL as u8), + ) + .expect("schema is a map"); + let stricter = + DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) + .expect("a valid contract"); + assert_eq!( + contact_request_requirement(&stricter).unwrap(), + SecurityLevel::CRITICAL + ); + } + #[test] fn should_sign_a_contact_request_with_a_key_bound_to_contact_requests_or_unbound() { let dashpay = SystemDataContract::Dashpay.id(); @@ -6635,7 +6689,7 @@ mod contact_request_key_tests { ) }; let pick = |identity: &Identity| { - contact_request_signing_key(identity, &KeyFilter(|_| true)) + contact_request_signing_key(identity, &KeyFilter(|_| true), SecurityLevel::HIGH) .unwrap() .map(|key| key.id()) }; From 68769e079b40f973952e3ff25164223ad10143d0 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:12:00 +0000 Subject: [PATCH 31/53] fix(platform-wallet): refuse explicit keys with Drive's consensus errors, in its order check_signing_key returned ProtocolError variants for a wrong security level, a wrong key type and a disabled key, while Drive's identity-signed validation returns the consensus SignatureError ones, and it checked the purpose before the key type. All refusals now go through the consensus path, and the checks run in Drive's order: key type, purpose, security level, disabled; then expiry and contract bounds. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/dpns.rs | 9 +- .../wallet/identity/network/key_selection.rs | 85 ++++++++++++------- .../wallet/identity/network/signing_key.rs | 27 +++--- .../wallet/identity/network/tokens/helpers.rs | 18 ++-- 4 files changed, 82 insertions(+), 57 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index de17fe55dfe..cb82c8f967c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -636,6 +636,7 @@ mod signing_key_tests { #[tokio::test] async fn should_refuse_an_explicit_registration_key_before_any_network_call() { + use super::super::key_selection::tests::signature_refusal_of; use super::super::signing_key::tests::wallet_with_signing_keys; use dpp::consensus::signature::SignatureError; use dpp::consensus::ConsensusError; @@ -678,10 +679,10 @@ mod signing_key_tests { let error = register(key(0, SecurityLevel::MASTER)).await.unwrap_err(); assert!( matches!( - error, - dash_sdk::Error::Protocol( - ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) - ) + signature_refusal_of(&error), + Some(SignatureError::InvalidSignaturePublicKeySecurityLevelError( + _ + )) ), "MASTER is refused on document writes: {error:?}" ); 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 2466359a792..d8daa7c08aa 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 @@ -4,8 +4,8 @@ use dpp::consensus::signature::InvalidSignaturePublicKeySecurityLevelError; use dpp::consensus::signature::{ ContractBoundedKeyNonBatchError, ContractBoundedKeyOutOfBoundsError, - InvalidSignaturePublicKeyPurposeError, PublicKeyExpiredError, PublicKeyIsDisabledError, - SignatureError, + InvalidIdentityPublicKeyTypeError, InvalidSignaturePublicKeyPurposeError, + PublicKeyExpiredError, PublicKeyIsDisabledError, SignatureError, }; use dpp::consensus::ConsensusError; use dpp::data_contract::TokenContractPosition; @@ -18,7 +18,6 @@ use dpp::identity::identity_public_key::contract_bounds::{ use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, KeyType, Purpose, SecurityLevel}; use dpp::prelude::Identifier; -use dpp::state_transition::errors::InvalidIdentityPublicKeyTypeError; use dpp::ProtocolError; use super::signing_key::{first_available, require_available}; @@ -160,9 +159,10 @@ fn usable_signing_key_at<'a>( /// Check a key the caller chose to sign in `scope` against the rules [`usable_signing_key`] /// applies, so an explicit choice is refused before anything is built or signed. /// -/// Each refusal is the typed error Platform itself returns for it: a purpose outside -/// `purposes`, a security level outside `security_levels`, a key type outside `key_types`, a -/// disabled key, an expired key, or contract bounds that do not cover `scope`. A key bound to +/// Each refusal is the consensus signature error Platform itself returns for it, checked in +/// Drive's order: a key type outside `key_types`, a purpose outside `purposes`, a security +/// level outside `security_levels`, a disabled key; then an expired key, or contract bounds +/// that do not cover `scope`. A key bound to /// a contract group is accepted: only Platform can read the group's memberships. A key /// `signer` cannot sign with is refused with the signer-unavailable error. A key with an /// expiry is refused with [`dash_sdk::Error::Config`] when the system clock reads before the @@ -197,6 +197,15 @@ fn check_signing_key_at( scope: SigningScope<'_>, now: Option, ) -> Result<(), dash_sdk::Error> { + // Drive's identity-signed validation checks in this order: key type, purpose, security + // level, disabled. + if !key_types.contains(&key.key_type()) { + return Err(signature_refusal( + SignatureError::InvalidIdentityPublicKeyTypeError( + InvalidIdentityPublicKeyTypeError::new(key.key_type()), + ), + )); + } if !purposes.contains(&key.purpose()) { return Err(signature_refusal( SignatureError::InvalidSignaturePublicKeyPurposeError( @@ -205,24 +214,19 @@ fn check_signing_key_at( )); } if !security_levels.contains(&key.security_level()) { - return Err(ProtocolError::InvalidSignaturePublicKeySecurityLevelError( - InvalidSignaturePublicKeySecurityLevelError::new( - key.security_level(), - security_levels.to_vec(), + return Err(signature_refusal( + SignatureError::InvalidSignaturePublicKeySecurityLevelError( + InvalidSignaturePublicKeySecurityLevelError::new( + key.security_level(), + security_levels.to_vec(), + ), ), - ) - .into()); - } - if !key_types.contains(&key.key_type()) { - return Err(ProtocolError::InvalidIdentityPublicKeyTypeError( - InvalidIdentityPublicKeyTypeError::new(key.key_type()), - ) - .into()); + )); } if key.is_disabled() { - return Err( - ProtocolError::PublicKeyIsDisabledError(PublicKeyIsDisabledError::new(key.id())).into(), - ); + return Err(signature_refusal(SignatureError::PublicKeyIsDisabledError( + PublicKeyIsDisabledError::new(key.id()), + ))); } if let Some(expires_at) = key.expires_at() { let Some(now) = now else { @@ -669,6 +673,18 @@ pub(super) mod tests { } } + /// The consensus signature error `error` carries, if it is one. + pub(crate) fn signature_refusal_of(error: &dash_sdk::Error) -> Option<&SignatureError> { + match error { + dash_sdk::Error::Protocol(ProtocolError::ConsensusError(error)) => match error.as_ref() + { + ConsensusError::SignatureError(error) => Some(error), + _ => None, + }, + _ => None, + } + } + /// The purposes `error` names when it is Platform's purpose refusal. pub(crate) fn refused_purposes(error: &dash_sdk::Error) -> Option> { match error { @@ -721,26 +737,31 @@ pub(super) mod tests { Some(vec![Purpose::AUTHENTICATION]) ); assert!(matches!( - check(&key(1, SecurityLevel::MASTER), document_scope()), - Err(dash_sdk::Error::Protocol( - ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) + check(&key(1, SecurityLevel::MASTER), document_scope()) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::InvalidSignaturePublicKeySecurityLevelError( + _ )) )); let mut hash160 = key(1, SecurityLevel::HIGH); hash160.set_key_type(KeyType::ECDSA_HASH160); assert!(matches!( - check(&hash160, document_scope()), - Err(dash_sdk::Error::Protocol( - ProtocolError::InvalidIdentityPublicKeyTypeError(_) - )) + check(&hash160, document_scope()) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::InvalidIdentityPublicKeyTypeError(_)) )); let mut disabled = key(1, SecurityLevel::HIGH); disabled.set_disabled_at(5); assert!(matches!( - check(&disabled, document_scope()), - Err(dash_sdk::Error::Protocol( - ProtocolError::PublicKeyIsDisabledError(_) - )) + check(&disabled, document_scope()) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::PublicKeyIsDisabledError(_)) )); let expired = key(1, SecurityLevel::HIGH).with_limits(None, Some(1)); assert!(matches!( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index d5820041e0d..6d7abd72acc 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -140,11 +140,12 @@ pub(super) fn credit_signing_key<'a>( #[cfg(test)] pub(super) mod tests { - use super::super::key_selection::tests::refused_purposes; + use super::super::key_selection::tests::{refused_purposes, signature_refusal_of}; use super::*; use crate::{PlatformWallet, PlatformWalletError}; use async_trait::async_trait; use dpp::address_funds::AddressWitness; + use dpp::consensus::signature::SignatureError; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; @@ -329,9 +330,9 @@ pub(super) mod tests { credit_signing_key(&identity, identity.public_keys().get(&id), &signer, true); assert!( matches!( - refusal, - Err(dash_sdk::Error::Protocol( - ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) + refusal.as_ref().err().and_then(signature_refusal_of), + Some(SignatureError::InvalidSignaturePublicKeySecurityLevelError( + _ )) ), "credit transitions take only a CRITICAL key: {refusal:?}" @@ -531,10 +532,11 @@ pub(super) mod tests { }; assert!( matches!( - explicit(1, true), - Err(dash_sdk::Error::Protocol( - ProtocolError::PublicKeyIsDisabledError(_) - )) + explicit(1, true) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::PublicKeyIsDisabledError(_)) ), "Platform refuses a disabled signing key" ); @@ -550,10 +552,11 @@ pub(super) mod tests { ); assert!( matches!( - explicit(5, false), - Err(dash_sdk::Error::Protocol( - ProtocolError::InvalidIdentityPublicKeyTypeError(_) - )) + explicit(5, false) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::InvalidIdentityPublicKeyTypeError(_)) ), "Platform cannot verify an identity signature by a script hash" ); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index da5341dbc88..44643c95726 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -167,7 +167,7 @@ impl IdentityWallet { mod signing_tests { use super::*; use crate::wallet::identity::network::key_selection::tests::{ - bound_key, key, refused_purposes, + bound_key, key, refused_purposes, signature_refusal_of, }; use crate::wallet::identity::network::signing_key::tests::{ assert_no_usable_key, identity as identity_with_keys, lock_checking_signer, @@ -262,10 +262,10 @@ mod signing_tests { .expect("the key must be refused"); assert!( matches!( - transfer, - dash_sdk::Error::Protocol( - ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) - ) + signature_refusal_of(&transfer), + Some(SignatureError::InvalidSignaturePublicKeySecurityLevelError( + _ + )) ), "a TRANSFER key signs a batch only at CRITICAL: {transfer:?}" ); @@ -347,10 +347,10 @@ mod signing_tests { let error = burn(key(1, SecurityLevel::HIGH)).await; assert!( matches!( - error, - dash_sdk::Error::Protocol( - ProtocolError::InvalidSignaturePublicKeySecurityLevelError(_) - ) + signature_refusal_of(&error), + Some(SignatureError::InvalidSignaturePublicKeySecurityLevelError( + _ + )) ), "a token transition takes only a CRITICAL key: {error:?}" ); From a2b3c083ce45d5cd67645b7f8dee0b3c9cc7f12f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 16:15:28 +0000 Subject: [PATCH 32/53] test(platform-wallet): pin the key-type-before-purpose check order A key with both a wrong type and a wrong purpose must be refused with the consensus InvalidIdentityPublicKeyTypeError, as Drive's identity-signed validation does. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/key_selection.rs | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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 d8daa7c08aa..b358222233c 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 @@ -965,4 +965,19 @@ pub(super) mod tests { BatchedTransitionBoundsCheck::Denied ); } + + #[test] + fn should_report_a_wrong_key_type_before_a_wrong_purpose_as_drive_does() { + let mut both_wrong = key(1, SecurityLevel::HIGH); + both_wrong.set_purpose(Purpose::TRANSFER); + both_wrong.set_key_type(KeyType::ECDSA_HASH160); + let refusal = check(&both_wrong, document_scope()); + assert!( + matches!( + refusal.as_ref().err().and_then(signature_refusal_of), + Some(SignatureError::InvalidIdentityPublicKeyTypeError(_)) + ), + "{refusal:?}" + ); + } } From af044e66f1a48c9df3c9b27380f6ee43c27e24d4 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:40:38 +0000 Subject: [PATCH 33/53] feat(platform-wallet): export the signing key-type sets with the key helpers A client calling check_signing_key or usable_signing_key had to restate which key types Drive verifies. PLATFORM_SIGNING_KEY_TYPES (for an explicit key) and WALLET_SIGNING_KEY_TYPES (to choose as the wallet does) are public and re-exported at the crate root, and their docs say which to pass. Co-Authored-By: Claude Opus 5.5 --- packages/rs-platform-wallet/src/lib.rs | 1 + .../wallet/identity/network/key_selection.rs | 18 ++++++++++-------- .../src/wallet/identity/network/mod.rs | 5 ++++- 3 files changed, 15 insertions(+), 9 deletions(-) diff --git a/packages/rs-platform-wallet/src/lib.rs b/packages/rs-platform-wallet/src/lib.rs index cb8ebabb1f8..2ce1f59a806 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -77,6 +77,7 @@ pub use wallet::identity::network::{ check_signing_key, derive_identity_auth_keypair, usable_signing_key, AutoAcceptProofSource, ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, ContactInfoSealed, SeedBindingVerification, SigningScope, IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX, + PLATFORM_SIGNING_KEY_TYPES, WALLET_SIGNING_KEY_TYPES, }; pub use wallet::identity::{ calculate_account_reference, derive_auto_accept_private_key, derive_contact_payment_address, 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 b358222233c..5cfa779e247 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 @@ -24,20 +24,22 @@ use super::signing_key::{first_available, require_available}; use std::time::{SystemTime, UNIX_EPOCH}; /// The key types Platform verifies an identity signature by (Drive's -/// `validate_state_transition_identity_signed`). A key the caller chose is checked against -/// these, and so is the wallet's own choice of a credit transfer or withdrawal key, so an -/// `ECDSA_HASH160` TRANSFER key stays usable. Other automatic selection uses the narrower -/// [`WALLET_SIGNING_KEY_TYPES`]. -pub(crate) const PLATFORM_SIGNING_KEY_TYPES: [KeyType; 3] = [ +/// `validate_state_transition_identity_signed`). Pass these as `key_types` to +/// [`check_signing_key`] for a key the caller chose, so it is refused exactly where Platform +/// refuses it. The wallet's own choice of a credit transfer or withdrawal key uses them too, +/// so an `ECDSA_HASH160` TRANSFER key stays usable. Other automatic selection uses the +/// narrower [`WALLET_SIGNING_KEY_TYPES`]. +pub const PLATFORM_SIGNING_KEY_TYPES: [KeyType; 3] = [ KeyType::ECDSA_SECP256K1, KeyType::BLS12_381, KeyType::ECDSA_HASH160, ]; /// The key types the wallet picks its own signing keys from, except for a credit transfer or -/// withdrawal key, which may be any of [`PLATFORM_SIGNING_KEY_TYPES`]. A key the caller chose -/// is checked against [`PLATFORM_SIGNING_KEY_TYPES`] instead. -pub(crate) const WALLET_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; +/// withdrawal key, which may be any of [`PLATFORM_SIGNING_KEY_TYPES`]. Pass these as +/// `key_types` to [`usable_signing_key`] to choose the key the wallet itself would; a key the +/// caller chose is checked against [`PLATFORM_SIGNING_KEY_TYPES`] instead. +pub const WALLET_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; /// What a signature authorizes, as far as a key's contract bounds go. #[derive(Debug, Clone, Copy, PartialEq, Eq)] diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index 4d0bc358377..c8ed7521f96 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -51,7 +51,10 @@ mod transfer; mod transfer_to_addresses; mod update; pub(crate) use key_selection::usable_authentication_key; -pub use key_selection::{check_signing_key, usable_signing_key, SigningScope}; +pub use key_selection::{ + check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, + WALLET_SIGNING_KEY_TYPES, +}; mod withdrawal; pub(crate) use withdrawal::{select_owner_withdrawal_key, select_transfer_withdrawal_key}; From 45567c9c99557f5f48c22be4033d7cc6b3c46025 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:52:05 +0000 Subject: [PATCH 34/53] fix(platform-wallet): check contract bounds before expiry, as Drive does Drive refuses an out-of-bounds or non-batch contract-bound key during validation (batch advanced structure, identity-signed v1), and an expired key only later, at fee validation. check_signing_key checked expiry first, so a key both expired and out of bounds got PublicKeyExpiredError where Platform reports the bounds error. The bounds check now runs before the expiry check. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/key_selection.rs | 54 +++++++++++++------ 1 file changed, 38 insertions(+), 16 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 5cfa779e247..250cf0fc109 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 @@ -163,8 +163,9 @@ fn usable_signing_key_at<'a>( /// /// Each refusal is the consensus signature error Platform itself returns for it, checked in /// Drive's order: a key type outside `key_types`, a purpose outside `purposes`, a security -/// level outside `security_levels`, a disabled key; then an expired key, or contract bounds -/// that do not cover `scope`. A key bound to +/// level outside `security_levels`, a disabled key (identity-signed validation); then contract +/// bounds that do not cover `scope` (structure validation); then an expired key (fee +/// validation). A key bound to /// a contract group is accepted: only Platform can read the group's memberships. A key /// `signer` cannot sign with is refused with the signer-unavailable error. A key with an /// expiry is refused with [`dash_sdk::Error::Config`] when the system clock reads before the @@ -230,20 +231,6 @@ fn check_signing_key_at( PublicKeyIsDisabledError::new(key.id()), ))); } - if let Some(expires_at) = key.expires_at() { - let Some(now) = now else { - return Err(dash_sdk::Error::Config(format!( - "the system clock reads before the Unix epoch, so whether key {} has expired \ - cannot be told", - key.id() - ))); - }; - if key.is_expired_at(now) { - return Err(signature_refusal(SignatureError::PublicKeyExpiredError( - PublicKeyExpiredError::new(key.id(), expires_at, now), - ))); - } - } match scope.bounds_check(key) { BatchedTransitionBoundsCheck::Allowed | BatchedTransitionBoundsCheck::RequiresContractGroupMembership { .. } => {} @@ -262,6 +249,20 @@ fn check_signing_key_at( )); } } + if let Some(expires_at) = key.expires_at() { + let Some(now) = now else { + return Err(dash_sdk::Error::Config(format!( + "the system clock reads before the Unix epoch, so whether key {} has expired \ + cannot be told", + key.id() + ))); + }; + if key.is_expired_at(now) { + return Err(signature_refusal(SignatureError::PublicKeyExpiredError( + PublicKeyExpiredError::new(key.id(), expires_at, now), + ))); + } + } require_available(key, signer).map(|_| ()) } @@ -982,4 +983,25 @@ pub(super) mod tests { "{refusal:?}" ); } + + #[test] + fn should_report_contract_bounds_before_expiry_as_drive_does() { + let expired_elsewhere = bound_elsewhere(1).with_limits(None, Some(1)); + assert!(matches!( + signature_error(check(&expired_elsewhere, document_scope())), + SignatureError::ContractBoundedKeyOutOfBoundsError(_) + )); + let expired_bound_here = bound_key( + 2, + SecurityLevel::HIGH, + Some(ContractBounds::SingleContract { + id: Identifier::from(CONTRACT), + }), + ) + .with_limits(None, Some(1)); + assert!(matches!( + signature_error(check(&expired_bound_here, SigningScope::NonBatch)), + SignatureError::ContractBoundedKeyNonBatchError(_) + )); + } } From 227ec7b69b0120ca3d78c35c6ba7ad4ad950078d Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:52:05 +0000 Subject: [PATCH 35/53] fix(platform-wallet): check an explicit document key before fetching the document Replace, transfer, set-price and purchase fetched the current document before checking the caller's key, so a key Platform would refuse still cost a document request, and a missing document hid the refusal. The key is now resolved and checked right after the contract fetch. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/document.rs | 187 ++++++++++++++---- .../wallet/identity/network/signing_key.rs | 10 +- 2 files changed, 158 insertions(+), 39 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index 633ac0e0118..aa8cbe55856 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -518,6 +518,16 @@ impl IdentityWallet { .fetch_contract_arc_for_document_op(contract_id, document_type_name) .await?; + let signing_key = self + .resolve_authentication_signing_key( + owner_identity_id, + signing_key_id, + &data_contract, + document_type_name, + signer, + ) + .await?; + // Owned `DocumentType` to sanitize the supplied properties // against the schema — same conversion the create path runs. let document_type = data_contract @@ -560,16 +570,6 @@ impl IdentityWallet { )) })?; - let signing_key = self - .resolve_authentication_signing_key( - owner_identity_id, - signing_key_id, - &data_contract, - document_type_name, - signer, - ) - .await?; - let builder = DocumentReplaceTransitionBuilder::new( data_contract, document_type_name.to_string(), @@ -752,15 +752,6 @@ impl IdentityWallet { .fetch_contract_arc_for_document_op(contract_id, document_type_name) .await?; - let mut document = self - .fetch_current_document(&data_contract, document_type_name, document_id) - .await?; - document.increment_revision().map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to increment document revision: {e}" - )) - })?; - let signing_key = self .resolve_authentication_signing_key( owner_identity_id, @@ -771,6 +762,15 @@ impl IdentityWallet { ) .await?; + let mut document = self + .fetch_current_document(&data_contract, document_type_name, document_id) + .await?; + document.increment_revision().map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to increment document revision: {e}" + )) + })?; + let builder = DocumentTransferTransitionBuilder::new( data_contract, document_type_name.to_string(), @@ -821,15 +821,6 @@ impl IdentityWallet { .fetch_contract_arc_for_document_op(contract_id, document_type_name) .await?; - let mut document = self - .fetch_current_document(&data_contract, document_type_name, document_id) - .await?; - document.increment_revision().map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to increment document revision: {e}" - )) - })?; - let signing_key = self .resolve_authentication_signing_key( owner_identity_id, @@ -840,6 +831,15 @@ impl IdentityWallet { ) .await?; + let mut document = self + .fetch_current_document(&data_contract, document_type_name, document_id) + .await?; + document.increment_revision().map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to increment document revision: {e}" + )) + })?; + let builder = DocumentSetPriceTransitionBuilder::new( data_contract, document_type_name.to_string(), @@ -893,15 +893,6 @@ impl IdentityWallet { .fetch_contract_arc_for_document_op(contract_id, document_type_name) .await?; - let mut document = self - .fetch_current_document(&data_contract, document_type_name, document_id) - .await?; - document.increment_revision().map_err(|e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to increment document revision: {e}" - )) - })?; - let signing_key = self .resolve_authentication_signing_key( purchaser_identity_id, @@ -912,6 +903,15 @@ impl IdentityWallet { ) .await?; + let mut document = self + .fetch_current_document(&data_contract, document_type_name, document_id) + .await?; + document.increment_revision().map_err(|e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to increment document revision: {e}" + )) + })?; + let builder = DocumentPurchaseTransitionBuilder::new( data_contract, document_type_name.to_string(), @@ -980,8 +980,119 @@ fn delete_preparation_error(error: dash_sdk::Error) -> PlatformWalletError { #[cfg(test)] mod tests { - use super::super::signing_key::tests::{lock_checking_signer, wallet_with_signing_keys}; + use super::super::key_selection::tests::signature_refusal_of; + use super::super::signing_key::tests::{ + identity as identity_with_keys, lock_checking_signer, wallet_with_identity_on, + wallet_with_signing_keys, + }; use super::*; + use dpp::consensus::signature::SignatureError; + use dpp::identity::accessors::IdentityGettersV0; + + /// A wallet whose SDK answers only the fetch of the DashPay contract, owning an identity + /// whose key 1 is disabled. + async fn wallet_answering_only_the_contract() -> (Arc, Identifier) { + let contract = super::super::dashpay_contract().unwrap(); + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().unwrap(); + sdk.mock() + .expect_fetch::(contract.id(), Some((*contract).clone())) + .await + .unwrap(); + let mut identity = identity_with_keys( + Purpose::AUTHENTICATION, + SecurityLevel::CRITICAL, + KeyType::ECDSA_SECP256K1, + ); + identity + .public_keys_mut() + .get_mut(&1) + .unwrap() + .set_disabled_at(1); + let owner = identity.id(); + (wallet_with_identity_on(sdk, identity).await, owner) + } + + fn assert_disabled_refusal(result: Result) { + assert!( + matches!( + &result, + Err(PlatformWalletError::Sdk(error)) + if matches!( + signature_refusal_of(error), + Some(SignatureError::PublicKeyIsDisabledError(_)) + ) + ), + "the key is refused before the document is fetched: {result:?}" + ); + } + + #[tokio::test] + async fn should_refuse_an_explicit_key_before_fetching_the_document() { + let contract_id = super::super::dashpay_contract().unwrap().id(); + let document_id = Identifier::from([9; 32]); + let signer = KeyFilter(|_| true); + + let (wallet, owner) = wallet_answering_only_the_contract().await; + assert_disabled_refusal( + wallet + .identity() + .replace_document_with_signer( + &owner, + &contract_id, + "profile", + &document_id, + "{}", + 1, + &signer, + ) + .await, + ); + let (wallet, owner) = wallet_answering_only_the_contract().await; + assert_disabled_refusal( + wallet + .identity() + .transfer_document_with_signer( + &owner, + &contract_id, + "profile", + &document_id, + &Identifier::from([3; 32]), + 1, + &signer, + ) + .await, + ); + let (wallet, owner) = wallet_answering_only_the_contract().await; + assert_disabled_refusal( + wallet + .identity() + .set_document_price_with_signer( + &owner, + &contract_id, + "profile", + &document_id, + 5, + 1, + &signer, + ) + .await, + ); + let (wallet, owner) = wallet_answering_only_the_contract().await; + assert_disabled_refusal( + wallet + .identity() + .purchase_document_with_signer( + &owner, + &contract_id, + "profile", + &document_id, + 5, + 1, + &signer, + ) + .await, + ); + } #[tokio::test] async fn should_reject_unavailable_explicit_document_key_outside_wallet_lock() { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 6d7abd72acc..7aac9a492e2 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -654,6 +654,14 @@ pub(super) mod tests { /// A mock-SDK wallet that owns `identity`. pub(crate) async fn wallet_with_identity(identity: Identity) -> Arc { + wallet_with_identity_on(dash_sdk::SdkBuilder::new_mock().build().unwrap(), identity).await + } + + /// A wallet on `sdk` that owns `identity`. + pub(crate) async fn wallet_with_identity_on( + sdk: dash_sdk::Sdk, + identity: Identity, + ) -> Arc { use crate::events::{EventHandler, PlatformEventHandler}; use crate::wallet::persister::NoPlatformPersistence; use crate::PlatformWalletManager; @@ -663,7 +671,7 @@ pub(super) mod tests { impl EventHandler for Events {} impl PlatformEventHandler for Events {} let manager = PlatformWalletManager::new( - Arc::new(dash_sdk::SdkBuilder::new_mock().build().unwrap()), + Arc::new(sdk), Arc::new(NoPlatformPersistence), Arc::new(Events), ); From 5a7f5188a1d9eb31d3fdadfd1f4bd8e35dcc48b7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 17:52:05 +0000 Subject: [PATCH 36/53] fix(platform-wallet): check a masternode withdrawal key like an identity withdrawal The masternode withdrawal picked its OWNER or TRANSFER key by purpose and key material only, so a disabled, expired or non-CRITICAL key, or an OWNER key for a withdrawal to a chosen address, was signed and refused by Platform. The chosen key now goes through credit_signing_key, the identity withdrawal's check. A masternode's CRITICAL ECDSA_HASH160 keys pass it. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/mod.rs | 4 + .../wallet/identity/network/signing_key.rs | 2 +- .../src/wallet/masternode_withdrawal.rs | 85 ++++++++++++++++++- 3 files changed, 89 insertions(+), 2 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs index c8ed7521f96..61fc866a4a0 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -50,6 +50,9 @@ mod top_up_from_addresses; mod transfer; mod transfer_to_addresses; mod update; +/// Reads a consensus signature refusal out of an SDK error, for tests outside this module. +#[cfg(test)] +pub(crate) use key_selection::tests::signature_refusal_of; pub(crate) use key_selection::usable_authentication_key; pub use key_selection::{ check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, @@ -81,6 +84,7 @@ pub(crate) mod sdk_writer; mod seed_binding; mod signing_key; pub use seed_binding::SeedBindingVerification; +pub(crate) use signing_key::credit_signing_key; // Token state-transition operations (same `IdentityWallet` impl blocks). // Bookkeeping (watch / sync / balance) lives on diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 7aac9a492e2..87f499945d1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -92,7 +92,7 @@ const CREDIT_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; /// An explicit key is never substituted; it is checked by the rules automatic selection /// applies, and refused with Platform's typed error. Automatic withdrawals exhaust TRANSFER /// keys before OWNER. -pub(super) fn credit_signing_key<'a>( +pub(crate) fn credit_signing_key<'a>( identity: &'a Identity, explicit: Option<&'a IdentityPublicKey>, signer: &impl Signer, diff --git a/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs b/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs index e90851b9fb5..f6c1c73f86a 100644 --- a/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs +++ b/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs @@ -60,7 +60,7 @@ use crate::broadcast_outcome::{broadcast_definitely_failed, carries_consensus_re use crate::error::{PlatformWalletError, SIGNER_KEY_UNAVAILABLE_PREFIX}; use crate::wallet::core::is_signable_funding_account; use crate::wallet::identity::network::{ - select_owner_withdrawal_key, select_transfer_withdrawal_key, + credit_signing_key, select_owner_withdrawal_key, select_transfer_withdrawal_key, }; use crate::wallet::platform_wallet::PlatformWallet; use crate::wallet::provider_key_at_index::ProviderKeyKind; @@ -450,6 +450,14 @@ pub(crate) async fn execute_masternode_withdrawal path, expected_key_hash160: expected_hash160, }; + // The checks an identity withdrawal runs on its key: a CRITICAL key, enabled and unexpired, + // of a type Platform verifies, and OWNER only for a withdrawal to the payout address. + credit_signing_key( + &identity, + Some(&identity_key), + &identity_signer, + destination.is_none(), + )?; let definitive = |e: dash_sdk::Error| { crate::error::preserve_signer_key_unavailable_or(e, |e| { @@ -880,4 +888,79 @@ mod tests { assert!(transfer.can_withdraw()); assert!(transfer.can_choose_destination()); } + + #[tokio::test] + async fn should_refuse_a_withdrawal_key_platform_would_refuse() { + use crate::wallet::identity::network::signature_refusal_of; + use dpp::consensus::signature::SignatureError; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dpp::identity::v0::IdentityV0; + + let pro_tx_hash = [0x5A; 32]; + let mut id_bytes = pro_tx_hash; + id_bytes.reverse(); + let identity_id = Identifier::from(id_bytes); + let withdraw = |key: IdentityPublicKey, destination: Option| async move { + let (signer, hash, _) = fixture(); + let identity: Identity = IdentityV0 { + id: identity_id, + public_keys: [(key.id(), key)].into_iter().collect(), + balance: 1_000_000, + revision: 0, + } + .into(); + let mut sdk = dash_sdk::SdkBuilder::new_mock().build().unwrap(); + sdk.mock() + .expect_fetch::(identity_id, Some(identity)) + .await + .unwrap(); + execute_masternode_withdrawal( + &sdk, + pro_tx_hash, + 1, + MasternodeWithdrawalKey::Owner, + hash, + DerivationPath::from_str("m/9'/1'/3'/2'/0").unwrap(), + destination, + &signer, + ) + .await + }; + let refusal = |result: &Result| match result { + Err(PlatformWalletError::Sdk(error)) => signature_refusal_of(error).cloned(), + _ => None, + }; + let (_, _, owner_key) = fixture(); + + let mut disabled = owner_key.clone(); + disabled.set_disabled_at(1); + let result = withdraw(disabled, None).await; + assert!( + matches!( + refusal(&result), + Some(SignatureError::PublicKeyIsDisabledError(_)) + ), + "{result:?}" + ); + + let result = withdraw( + owner_key.clone(), + Some(DashAddress::dummy(Network::Testnet, 1)), + ) + .await; + assert!( + matches!( + refusal(&result), + Some(SignatureError::InvalidSignaturePublicKeyPurposeError(_)) + ), + "an OWNER key cannot withdraw to a chosen address: {result:?}" + ); + + let result = withdraw(owner_key, None).await; + assert_eq!( + refusal(&result), + None, + "a CRITICAL ECDSA_HASH160 OWNER key passes and the withdrawal goes on: {result:?}" + ); + } } From 4ac66a4f8c197c478d1aaf9d9e22feb7357712b7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:05:01 +0000 Subject: [PATCH 37/53] fix(platform-wallet): require a create key to cover the types the create consumes Drive's batch structure validation requires the key signing a document create to be allowed on every type the create may consume (consumable_document_type_names), as well as on the created type. The wallet checked the created type only, so a key bound to DPNS domain alone was chosen for, or accepted on, a domain create that consumes a preorder, and Platform refused it. SigningScope gains DocumentCreate { document_type }, whose bounds check also covers the consumed types the way Drive does. Document create and contact-request send use it. SigningScope drops Eq, as DocumentTypeRef only implements PartialEq. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/contact_requests.rs | 33 ++++-- .../src/wallet/identity/network/document.rs | 5 +- .../wallet/identity/network/key_selection.rs | 101 ++++++++++++++++-- 3 files changed, 119 insertions(+), 20 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index 0d182436b86..41156da44ac 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -629,7 +629,7 @@ impl DashPayView<'_, B> { .map_err(dash_sdk::Error::from)?; let requirement = contact_request_requirement(&dashpay).map_err(dash_sdk::Error::from)?; let identity_public_key = - contact_request_signing_key(&sender_identity, signer, requirement)? + contact_request_signing_key(&sender_identity, signer, &dashpay, requirement)? .cloned() .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { identity_id: *sender_identity_id, @@ -1244,21 +1244,24 @@ fn contact_request_requirement(dashpay: &DataContract) -> Result( identity: &'a Identity, signer: &impl Signer, + dashpay: &DataContract, requirement: SecurityLevel, ) -> Result, dash_sdk::Error> { + let contact_request = dashpay + .document_type_for_name(CONTACT_REQUEST_DOCUMENT_TYPE) + .map_err(ProtocolError::from)?; document_signing_key( identity, signer, requirement, - SigningScope::DocumentType { - contract_id: SystemDataContract::Dashpay.id(), - document_type_name: CONTACT_REQUEST_DOCUMENT_TYPE, + SigningScope::DocumentCreate { + document_type: contact_request, }, ) } @@ -6688,10 +6691,20 @@ mod contact_request_key_tests { }), ) }; + let contract = load_system_data_contract( + SystemDataContract::Dashpay, + dpp::version::PlatformVersion::latest(), + ) + .expect("bundled DashPay contract"); let pick = |identity: &Identity| { - contact_request_signing_key(identity, &KeyFilter(|_| true), SecurityLevel::HIGH) - .unwrap() - .map(|key| key.id()) + contact_request_signing_key( + identity, + &KeyFilter(|_| true), + &contract, + SecurityLevel::HIGH, + ) + .unwrap() + .map(|key| key.id()) }; assert_eq!( pick(&identity(vec![ diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index aa8cbe55856..d20124befc0 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -298,9 +298,8 @@ impl IdentityWallet { &identity, signer, required_level, - SigningScope::DocumentType { - contract_id: *contract_id, - document_type_name, + SigningScope::DocumentCreate { + document_type: document_type.as_ref(), }, )? .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { 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 250cf0fc109..cc0cf6ca990 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,6 +8,8 @@ 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; @@ -42,12 +44,15 @@ pub const PLATFORM_SIGNING_KEY_TYPES: [KeyType; 3] = [ pub const WALLET_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; /// What a signature authorizes, as far as a key's contract bounds go. -#[derive(Debug, Clone, Copy, PartialEq, Eq)] +#[derive(Debug, Clone, Copy, PartialEq)] pub enum SigningScope<'a> { /// A transition that is not a batch: identity update, credit transfer or withdrawal, /// contract create or update. A contract-bound AUTHENTICATION key cannot sign it. NonBatch, - /// A batch of `document_type_name` documents of `contract_id`. + /// A batch creating a `document_type` document. The key's bounds must cover the type and + /// every type the create may consume, as Platform checks. + DocumentCreate { document_type: DocumentTypeRef<'a> }, + /// A batch acting on existing `document_type_name` documents of `contract_id`. DocumentType { contract_id: Identifier, document_type_name: &'a str, @@ -80,17 +85,42 @@ 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)), }; - match key.contract_bounds() { - Some(bounds) if key.purpose() == Purpose::AUTHENTICATION => { - bounds.check_scope(contract_id, bounds_scope) - } - _ => BatchedTransitionBoundsCheck::Allowed, + 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 } } } @@ -1004,4 +1034,61 @@ pub(super) mod tests { SignatureError::ContractBoundedKeyNonBatchError(_) )); } + + #[test] + fn should_require_a_create_key_to_cover_the_types_the_create_consumes() { + 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 domain = dpns.document_type_for_name("domain").expect("domain"); + assert!(domain.consumable_document_type_names().contains("preorder")); + let scope = SigningScope::DocumentCreate { + document_type: domain, + }; + let bound_to_domain = bound_key( + 1, + SecurityLevel::HIGH, + Some(ContractBounds::SingleContractDocumentType { + id: dpns.id(), + document_type_name: "domain".to_string(), + }), + ); + let bound_to_dpns = bound_key( + 2, + SecurityLevel::HIGH, + Some(ContractBounds::SingleContract { id: dpns.id() }), + ); + + assert_eq!( + scope.bounds_check(&bound_to_domain), + BatchedTransitionBoundsCheck::Denied + ); + assert!(matches!( + signature_error(check(&bound_to_domain, scope)), + SignatureError::ContractBoundedKeyOutOfBoundsError(_) + )); + assert_eq!( + scope.bounds_check(&bound_to_dpns), + BatchedTransitionBoundsCheck::Allowed + ); + check(&bound_to_dpns, scope).expect("a key bound to the whole contract signs the create"); + let picked = usable_signing_key( + &identity(vec![bound_to_domain, bound_to_dpns]), + &KeyFilter(|_| true), + Purpose::AUTHENTICATION, + &LEVELS, + &TYPES, + scope, + ) + .unwrap() + .map(|key| key.id()); + assert_eq!( + picked, + Some(2), + "the key bound to the created type only is skipped" + ); + } } From 59444a0ecef287c72fe4bc5c10da1b073523ad0c Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:15:15 +0000 Subject: [PATCH 38/53] refactor(dpp): ask can_sign_non_batch in the pre-sign bounds check verify_identity_key_bounds wrote the non-batch rule out a second time. It now asks IdentityPublicKey::can_sign_non_batch, which is the negation of the old condition (AUTHENTICATION and contract-bound), so every key gets the same answer. The batch arm is unchanged. This is a client-side pre-sign check; Drive's validation does not call it. Co-Authored-By: Claude Opus 5.5 --- packages/rs-dpp/src/state_transition/mod.rs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/packages/rs-dpp/src/state_transition/mod.rs b/packages/rs-dpp/src/state_transition/mod.rs index f1ab959dbc0..52684c4940b 100644 --- a/packages/rs-dpp/src/state_transition/mod.rs +++ b/packages/rs-dpp/src/state_transition/mod.rs @@ -1984,15 +1984,15 @@ impl StateTransition { &self, identity_public_key: &IdentityPublicKey, ) -> Result<(), ProtocolError> { - if identity_public_key.purpose() != Purpose::AUTHENTICATION { - return Ok(()); - } - let Some(bounds) = identity_public_key.contract_bounds() else { - return Ok(()); - }; match self { StateTransition::Batch(batch) => { use crate::state_transition::batch_transition::accessors::DocumentsBatchTransitionAccessorsV0; + if identity_public_key.purpose() != Purpose::AUTHENTICATION { + return Ok(()); + } + let Some(bounds) = identity_public_key.contract_bounds() else { + return Ok(()); + }; if batch.transitions_iter().all(|member| { bounds.check_batched_transition(member) != BatchedTransitionBoundsCheck::Denied }) { @@ -2003,6 +2003,7 @@ impl StateTransition { ))) } } + _ if identity_public_key.can_sign_non_batch() => Ok(()), _ => Err(ProtocolError::ConsensusError(Box::new( ContractBoundedKeyNonBatchError::new(identity_public_key.id()).into(), ))), From f681ab7d372477048230512f1cfe94d43179cf6f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Tue, 27 Oct 2026 18:27:31 +0000 Subject: [PATCH 39/53] test(platform-wallet,dpp): pin the expected outcomes instead of comparing implementations The masternode withdrawal test accepted any error that was not a signature refusal for the passing key, including signer-unavailable. It now requires the failure of the nonce fetch the mock does not answer, which only a key that passed the check reaches. The dpp non-batch test compared can_sign_non_batch with verify_identity_key_bounds, which now asks it, so it could not fail off a batch. It now states the expected outcome per purpose and bounds kind and checks both against it, including the ContractBoundedKeyNonBatchError. Co-Authored-By: Claude Opus 5.5 --- packages/rs-dpp/src/state_transition/mod.rs | 14 ++++++++++++-- .../src/wallet/masternode_withdrawal.rs | 12 +++++++++--- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/packages/rs-dpp/src/state_transition/mod.rs b/packages/rs-dpp/src/state_transition/mod.rs index 52684c4940b..7e408b40d96 100644 --- a/packages/rs-dpp/src/state_transition/mod.rs +++ b/packages/rs-dpp/src/state_transition/mod.rs @@ -3032,7 +3032,8 @@ mod tests { #[cfg(feature = "state-transition-signing")] #[test] - fn should_agree_with_the_pre_sign_rule_on_keys_that_may_sign_a_non_batch_transition() { + fn should_refuse_only_a_contract_bound_authentication_key_for_a_non_batch_transition() { + use crate::consensus::signature::ContractBoundedKeyNonBatchError; use crate::identity::contract_bounds::ContractBounds; use crate::identity::identity_public_key::v0::IdentityPublicKeyV0; use strum::IntoEnumIterator; @@ -3060,11 +3061,20 @@ mod tests { ..Default::default() } .into(); + let expected = purpose != Purpose::AUTHENTICATION || contract_bounds.is_none(); assert_eq!( key.can_sign_non_batch(), - transfer.verify_identity_key_bounds(&key).is_ok(), + expected, "{purpose:?} {contract_bounds:?}" ); + match transfer.verify_identity_key_bounds(&key) { + Ok(()) => assert!(expected, "{purpose:?} {contract_bounds:?}"), + Err(ProtocolError::ConsensusError(error)) => { + assert!(!expected, "{purpose:?} {contract_bounds:?}"); + assert_eq!(*error, ContractBoundedKeyNonBatchError::new(7).into()); + } + Err(other) => panic!("{purpose:?} {contract_bounds:?}: {other:?}"), + } } } } diff --git a/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs b/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs index f6c1c73f86a..3453e1e0afc 100644 --- a/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs +++ b/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs @@ -956,10 +956,16 @@ mod tests { "an OWNER key cannot withdraw to a chosen address: {result:?}" ); + // The mock answers only the identity fetch, so a key that passes the check fails at + // the next request, the nonce fetch. let result = withdraw(owner_key, None).await; - assert_eq!( - refusal(&result), - None, + assert!( + matches!( + &result, + Err(PlatformWalletError::InvalidIdentityData(message)) + if message.starts_with("masternode withdrawal failed") + && message.contains("GetIdentityNonce") + ), "a CRITICAL ECDSA_HASH160 OWNER key passes and the withdrawal goes on: {result:?}" ); } From 3cc2b139220c8b28f7507bd755f409d7d7bf8707 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:07:53 +0000 Subject: [PATCH 40/53] fix(platform-wallet,sdk): judge DPNS signing keys by the contract the transition is built against A DPNS registration checked or picked its signing key against one DPNS contract snapshot (the bundled contract at the SDK's possibly stale protocol version, or a separate fetch) while `Sdk::register_dpns_name` built the preorder and domain against another (refreshed version, proved fetch). After a protocol or system-contract upgrade the two could disagree: a key passing the local check that Platform refuses, or a valid key refused locally. rs-sdk splits the registration around one snapshot (additive API): - `Sdk::prepare_dpns_name_registration` fetches the current DPNS contract and builds both documents, returning a `DpnsNameRegistration` that states the signing-level requirement and contract id of that snapshot. - `Sdk::submit_dpns_name_registration` signs and submits exactly those documents. `register_dpns_name*` are now prepare + submit. platform-wallet's `register_name_with_signer` and `register_name_with_external_signer` check or select the key from the prepared registration and submit it; public signatures are unchanged and the redundant DPNS contract round-trip is gone. The DPNS marketplace (set price, delist, transfer, purchase) resolves the contract once and passes it through the state lookup, key selection and transition build. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/document.rs | 90 +++- .../src/wallet/identity/network/dpns.rs | 419 +++++++++--------- .../identity/network/dpns_marketplace.rs | 97 ++-- .../rs-sdk/src/platform/dpns_usernames/mod.rs | 209 ++++++++- 4 files changed, 546 insertions(+), 269 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index d20124befc0..93466702d66 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -761,6 +761,33 @@ impl IdentityWallet { ) .await?; + self.transfer_document_in_contract( + data_contract, + document_type_name, + document_id, + recipient_id, + &signing_key, + signer, + ) + .await + } + + /// Transfer like [`Self::transfer_document_with_signer`], on `data_contract` as the + /// caller resolved it, signing with `signing_key`, which the caller checked against that + /// same contract: the key and the transition it signs are judged by one contract + /// snapshot. + pub(super) async fn transfer_document_in_contract( + &self, + data_contract: Arc, + document_type_name: &str, + document_id: &Identifier, + recipient_id: &Identifier, + signing_key: &IdentityPublicKey, + signer: &S, + ) -> Result + where + S: Signer + Send + Sync, + { let mut document = self .fetch_current_document(&data_contract, document_type_name, document_id) .await?; @@ -778,7 +805,7 @@ impl IdentityWallet { ); let DocumentTransferResult::Document(confirmed) = self .sdk - .document_transfer(builder, &signing_key, &SignerRef(signer)) + .document_transfer(builder, signing_key, &SignerRef(signer)) .await .map_err(|e| { // Typed trade rejections (not-for-sale / price-changed / @@ -830,6 +857,33 @@ impl IdentityWallet { ) .await?; + self.set_document_price_in_contract( + data_contract, + document_type_name, + document_id, + price, + &signing_key, + signer, + ) + .await + } + + /// Set a price like [`Self::set_document_price_with_signer`], on `data_contract` as the + /// caller resolved it, signing with `signing_key`, which the caller checked against that + /// same contract: the key and the transition it signs are judged by one contract + /// snapshot. + pub(super) async fn set_document_price_in_contract( + &self, + data_contract: Arc, + document_type_name: &str, + document_id: &Identifier, + price: u64, + signing_key: &IdentityPublicKey, + signer: &S, + ) -> Result + where + S: Signer + Send + Sync, + { let mut document = self .fetch_current_document(&data_contract, document_type_name, document_id) .await?; @@ -847,7 +901,7 @@ impl IdentityWallet { ); let DocumentSetPriceResult::Document(confirmed) = self .sdk - .document_set_price(builder, &signing_key, &SignerRef(signer)) + .document_set_price(builder, signing_key, &SignerRef(signer)) .await .map_err(|e| { // Typed trade rejections and the structured key-unavailable @@ -902,6 +956,36 @@ impl IdentityWallet { ) .await?; + self.purchase_document_in_contract( + data_contract, + document_type_name, + document_id, + purchaser_identity_id, + price, + &signing_key, + signer, + ) + .await + } + + /// Purchase like [`Self::purchase_document_with_signer`], on `data_contract` as the + /// caller resolved it, signing with `signing_key`, which the caller checked against that + /// same contract: the key and the transition it signs are judged by one contract + /// snapshot. + #[allow(clippy::too_many_arguments)] + pub(super) async fn purchase_document_in_contract( + &self, + data_contract: Arc, + document_type_name: &str, + document_id: &Identifier, + purchaser_identity_id: &Identifier, + price: u64, + signing_key: &IdentityPublicKey, + signer: &S, + ) -> Result + where + S: Signer + Send + Sync, + { let mut document = self .fetch_current_document(&data_contract, document_type_name, document_id) .await?; @@ -920,7 +1004,7 @@ impl IdentityWallet { ); let DocumentPurchaseResult::Document(confirmed) = self .sdk - .document_purchase(builder, &signing_key, &SignerRef(signer)) + .document_purchase(builder, signing_key, &SignerRef(signer)) .await .map_err(|e| { // Typed trade rejections — crucially the price-changed race diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs index cb82c8f967c..6d709496f61 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -2,26 +2,16 @@ use super::document::{check_document_signing_key, document_signing_key}; use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; -use dpp::data_contract::accessors::v0::DataContractV0Getters; -use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; -use dpp::data_contract::DataContract; -use dpp::data_contracts::SystemDataContract; -use dpp::system_data_contracts::load_system_data_contract; use dpp::fee::Credits; +use dpp::identity::accessors::IdentityGettersV0; +use dpp::identity::signer::Signer; use dpp::identity::Identity; use dpp::identity::IdentityPublicKey; use dpp::identity::{Purpose, SecurityLevel}; use dpp::prelude::Identifier; -use dpp::identity::signer::Signer; -use dpp::ProtocolError; - -use async_trait::async_trait; -use dpp::address_funds::AddressWitness; -use dpp::platform_value::BinaryData; - use crate::error::PlatformWalletError; use crate::wallet::identity::types::key_storage::{DpnsFetch, DpnsNameInfo}; @@ -29,53 +19,24 @@ use super::{DPNS_USERNAMES_MAX_PAGES, DPNS_USERNAMES_PAGE_LIMIT}; use super::*; -// --------------------------------------------------------------------------- -// Signer reference adapter -// --------------------------------------------------------------------------- - -/// Thin wrapper that lets us pass a borrowed `&S` (where `S: Signer`) -/// into APIs whose generic bound requires an owned `S2: Signer`. -/// -/// `dpp::identity::signer::Signer` is not implemented for `&T`, so a -/// caller who only has `&KeychainSigner` can't directly satisfy -/// `RegisterDpnsNameInput>`. This wrapper -/// owns a `&'a S`, copies the trait's `Send + Sync + Debug` bounds, and -/// delegates each method back to the inner reference. Used internally -/// by [`IdentityWallet::register_name_with_external_signer`] so the -/// public FFI surface can pass the iOS `KeychainSigner` by reference -/// without forcing a clone or `Arc` round-trip per call. -struct SignerRef<'a, S: ?Sized>(&'a S); - -/// The document types a DPNS registration writes, in order, all signed by one key. -const DPNS_REGISTRATION_DOCUMENT_TYPES: [&str; 2] = ["preorder", "domain"]; - -/// The security level the key signing a registration must meet: the strongest that `dpns`'s -/// `preorder` and `domain` document types require. -fn dpns_registration_requirement(dpns: &DataContract) -> Result { - DPNS_REGISTRATION_DOCUMENT_TYPES.into_iter().try_fold( - SecurityLevel::MEDIUM, - |strongest, document_type_name| { - let required = dpns - .document_type_for_name(document_type_name)? - .security_level_requirement(); - Ok(if required.stronger_security_than(strongest) { - required - } else { - strongest - }) - }, - ) -} - /// The key that signs both DPNS registration documents, `preorder` then `domain`: an -/// AUTHENTICATION ECDSA key meeting `requirement` whose bounds cover the whole DPNS contract. -/// MASTER is reserved for identity operations and refused on document writes. +/// AUTHENTICATION ECDSA key meeting `requirement` whose bounds cover the whole DPNS contract +/// `dpns_contract_id`. MASTER is reserved for identity operations and refused on document +/// writes. Both come from the +/// [`DpnsNameRegistration`](dash_sdk::platform::dpns_usernames::DpnsNameRegistration) the key +/// will sign, so the key is judged by the contract the documents are built against. fn dpns_registration_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, requirement: SecurityLevel, + dpns_contract_id: Identifier, ) -> Result, dash_sdk::Error> { - document_signing_key(identity, signer, requirement, dpns_registration_scope()) + document_signing_key( + identity, + signer, + requirement, + dpns_registration_scope(dpns_contract_id), + ) } /// Check a key the caller chose to register a DPNS name by the rules @@ -84,43 +45,20 @@ fn check_dpns_registration_signing_key( key: &IdentityPublicKey, signer: &impl Signer, requirement: SecurityLevel, + dpns_contract_id: Identifier, ) -> Result<(), dash_sdk::Error> { - check_document_signing_key(key, signer, requirement, dpns_registration_scope()) + check_document_signing_key( + key, + signer, + requirement, + dpns_registration_scope(dpns_contract_id), + ) } /// Registration writes `preorder` and then `domain`, so its key must cover the whole contract. -fn dpns_registration_scope() -> SigningScope<'static> { +fn dpns_registration_scope(dpns_contract_id: Identifier) -> SigningScope<'static> { SigningScope::Contract { - contract_id: SystemDataContract::DPNS.id(), - } -} - -impl<'a, S: ?Sized> std::fmt::Debug for SignerRef<'a, S> { - fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { - f.write_str("SignerRef") - } -} - -#[async_trait] -impl<'a, K, S> Signer for SignerRef<'a, S> -where - K: Send + Sync, - S: Signer + ?Sized + Send + Sync, -{ - async fn sign(&self, key: &K, data: &[u8]) -> Result { - self.0.sign(key, data).await - } - - async fn sign_create_witness( - &self, - key: &K, - data: &[u8], - ) -> Result { - self.0.sign_create_witness(key, data).await - } - - fn can_sign_with(&self, key: &K) -> bool { - self.0.can_sign_with(key) + contract_id: dpns_contract_id, } } @@ -187,8 +125,9 @@ impl IdentityWallet { /// this method does **not** look up the identity in the internal /// `IdentityManager`. The caller supplies the `Identity`, the /// signing key, and a `Signer` directly. The key is checked by the rules the - /// wallet's own choice follows before anything reaches the network; a key Platform - /// would refuse returns its typed refusal. + /// wallet's own choice follows, against the DPNS contract the network stores now (the + /// one the registration's documents are built against), before anything is signed; a + /// key Platform would refuse returns its typed refusal. /// /// `contest_fund` is the most the registration pays into the contest a contested name /// joins (the fund to join doubles once a contest holds 250 contenders and again for every @@ -203,24 +142,26 @@ impl IdentityWallet { contest_fund: Option, signer: S, ) -> Result { - use dash_sdk::platform::dpns_usernames::RegisterDpnsNameInput; - - let dpns = load_system_data_contract(SystemDataContract::DPNS, self.sdk.version())?; + let registration = self + .sdk + .prepare_dpns_name_registration(name, identity.id()) + .await?; check_dpns_registration_signing_key( &identity_public_key, &signer, - dpns_registration_requirement(&dpns)?, + registration.signing_security_level_requirement(), + registration.dpns_contract_id(), )?; - let input = RegisterDpnsNameInput { - label: name.to_string(), - identity, - identity_public_key, - signer, - preorder_callback: None, - contest_fund, - }; - - let result = self.sdk.register_dpns_name(input).await?; + let (result, _owner_balance, _metadata) = self + .sdk + .submit_dpns_name_registration( + registration, + identity_public_key, + &signer, + None, + contest_fund, + ) + .await?; Ok(result.full_domain_name) } @@ -259,72 +200,61 @@ impl IdentityWallet { where S: Signer + Send + Sync, { - use dash_sdk::platform::dpns_usernames::RegisterDpnsNameInput; - - // Ensure the on-chain DPNS contract is fetched and registered - // with the SDK's context provider BEFORE broadcasting: the - // post-broadcast proof of the preorder/domain documents needs it, - // `Sdk::register_dpns_name` never registers it back, and a host - // that doesn't pre-seed known contracts (e.g. a headless - // consumer) would otherwise fail proof verification with - // "unknown contract ... in document verification" even though - // the registration landed on-chain. - let dpns = self.dpns_contract().await?; - let requirement = dpns_registration_requirement(&dpns).map_err(dash_sdk::Error::from)?; - - let (identity, auth_key) = { + // Map a registration failure, keeping a structured key-unavailable signer failure + // so the FFI boundary can still restore code 31; only genuine operation failures + // get stringified into `InvalidIdentityData`. + let registration_error = |e: dash_sdk::Error| { + crate::error::preserve_signer_key_unavailable_or(e, |e| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to register DPNS name '{}': {}", + name, e + )) + }) + }; + + let identity = { let wm = self.wallet_manager.read().await; let info = wm.get_wallet_info(&self.wallet_id).ok_or_else(|| { crate::error::PlatformWalletError::WalletNotFound( "Wallet info not found in wallet manager".to_string(), ) })?; - let manager = &info.identity_manager; - let identity = manager + info.identity_manager .identity(identity_id) .map(|m| m.identity.clone()) - .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; - drop(wm); - let key = dpns_registration_signing_key(&identity, signer, requirement)? - .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { - identity_id: *identity_id, - purpose: Purpose::AUTHENTICATION, - security_levels: SecurityLevel::accepted_for_requirement(requirement), - key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), - transition: "a DPNS name registration".to_string(), - })? - .clone(); - (identity, key) + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))? }; - let input = RegisterDpnsNameInput { - label: name.to_string(), - identity, - identity_public_key: auth_key, - // Wrap the borrowed signer in `SignerRef` so the - // `RegisterDpnsNameInput>` - // bound is satisfied without forcing the caller to hand - // over ownership / wrap in an Arc per call. - signer: SignerRef(signer), - preorder_callback: None, - contest_fund, - }; + // One DPNS contract snapshot, the one the network stores now, decides both the key + // and the documents it signs. Preparing also registers that contract with the SDK's + // context provider, which the post-broadcast proof of the documents needs on a host + // that doesn't pre-seed known contracts. + let registration = self + .sdk + .prepare_dpns_name_registration(name, *identity_id) + .await + .map_err(registration_error)?; + let requirement = registration.signing_security_level_requirement(); + let auth_key = dpns_registration_signing_key( + &identity, + signer, + requirement, + registration.dpns_contract_id(), + )? + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement(requirement), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: "a DPNS name registration".to_string(), + })? + .clone(); let (result, owner_balance, metadata) = self .sdk - .register_dpns_name_with_owner_balance_and_metadata(input) + .submit_dpns_name_registration(registration, auth_key, signer, None, contest_fund) .await - .map_err(|e| { - // Preserve a structured key-unavailable signer failure so the FFI - // boundary can still restore code 31; only genuine operation - // failures get stringified into `InvalidIdentityData`. - crate::error::preserve_signer_key_unavailable_or(e, |e| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to register DPNS name '{}': {}", - name, e - )) - }) - })?; + .map_err(registration_error)?; self.persist_proven_owner_balance(identity_id, owner_balance, metadata) .await; @@ -599,11 +529,21 @@ impl IdentityWallet { #[cfg(test)] mod signing_key_tests { - use super::super::key_selection::tests::{bound_key, identity, key}; - use super::super::signing_key::tests::KeyFilter; + use super::super::key_selection::tests::{bound_key, identity, key, signature_refusal_of}; + use super::super::signing_key::tests::{wallet_with_identity_on, KeyFilter}; use super::*; + use dpp::consensus::signature::SignatureError; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::data_contract::serialized_version::DataContractInSerializationFormat; + use dpp::data_contract::DataContract; + use dpp::data_contracts::SystemDataContract; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; + use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + use dpp::identity::KeyType; + use dpp::platform_value::Value; + use dpp::system_data_contracts::load_system_data_contract; + use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; #[test] fn should_register_with_a_key_that_covers_both_dpns_document_types() { @@ -624,9 +564,13 @@ mod signing_key_tests { Some(ContractBounds::SingleContract { id: dpns }), ), ]); - let chosen = - dpns_registration_signing_key(&identity, &KeyFilter(|_| true), SecurityLevel::HIGH) - .unwrap(); + let chosen = dpns_registration_signing_key( + &identity, + &KeyFilter(|_| true), + SecurityLevel::HIGH, + dpns, + ) + .unwrap(); assert_eq!( chosen.map(|key| key.id()), Some(2), @@ -634,16 +578,55 @@ mod signing_key_tests { ); } + /// A mock SDK on a network that stores `dpns` as its DPNS contract. + async fn sdk_storing_dpns(dpns: &DataContract) -> dash_sdk::Sdk { + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(dpns.id(), Some(dpns.clone())) + .await + .unwrap(); + sdk + } + + /// The DPNS contract the SDK bundles for the latest protocol version. + fn bundled_dpns() -> DataContract { + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) + .expect("bundled DPNS contract") + } + + /// The latest DPNS contract with its `domain` document type requiring a CRITICAL key, + /// where every bundled DPNS contract requires HIGH: what a network upgrade could store. + fn dpns_with_critical_domain() -> DataContract { + let platform_version = PlatformVersion::latest(); + let mut format = DataContractInSerializationFormat::try_from_platform_versioned( + bundled_dpns(), + platform_version, + ) + .expect("serialization format") + .into_schema_form(); + format + .document_schemas_mut() + .expect("schema form") + .get_mut("domain") + .expect("domain schema") + .set_value( + "signatureSecurityLevelRequirement", + Value::U8(SecurityLevel::CRITICAL as u8), + ) + .expect("schema is a map"); + DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) + .expect("a valid contract") + } + #[tokio::test] - async fn should_refuse_an_explicit_registration_key_before_any_network_call() { - use super::super::key_selection::tests::signature_refusal_of; - use super::super::signing_key::tests::wallet_with_signing_keys; - use dpp::consensus::signature::SignatureError; - use dpp::consensus::ConsensusError; - use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; - use dpp::identity::KeyType; - - let wallet = wallet_with_signing_keys().await; + async fn should_refuse_an_explicit_registration_key_before_signing() { + let identity = identity(vec![key(0, SecurityLevel::MASTER)]); + let wallet = + wallet_with_identity_on(sdk_storing_dpns(&bundled_dpns()).await, identity.clone()) + .await; let bound_to_domain = bound_key( 1, SecurityLevel::HIGH, @@ -652,7 +635,7 @@ mod signing_key_tests { document_type_name: "domain".to_string(), }), ); - let identity = identity(vec![key(0, SecurityLevel::MASTER), bound_to_domain.clone()]); + // `KeyFilter` panics if anything is signed let register = |key: IdentityPublicKey| { wallet.identity().register_name_with_signer( identity.clone(), @@ -665,14 +648,8 @@ mod signing_key_tests { let error = register(bound_to_domain).await.unwrap_err(); assert!( matches!( - &error, - dash_sdk::Error::Protocol(ProtocolError::ConsensusError(consensus)) - if matches!( - consensus.as_ref(), - ConsensusError::SignatureError( - SignatureError::ContractBoundedKeyOutOfBoundsError(_) - ) - ) + signature_refusal_of(&error), + Some(SignatureError::ContractBoundedKeyOutOfBoundsError(_)) ), "a key bound to `domain` cannot sign the `preorder` document: {error:?}" ); @@ -695,40 +672,64 @@ mod signing_key_tests { ); } - #[test] - fn should_require_the_strongest_level_of_both_registration_documents() { - use dpp::data_contract::serialized_version::DataContractInSerializationFormat; - use dpp::platform_value::Value; - use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; - - let platform_version = PlatformVersion::latest(); - let dpns = load_system_data_contract(SystemDataContract::DPNS, platform_version) - .expect("bundled DPNS contract"); - assert_eq!( - dpns_registration_requirement(&dpns).unwrap(), - SecurityLevel::HIGH - ); - let mut format = - DataContractInSerializationFormat::try_from_platform_versioned(dpns, platform_version) - .expect("serialization format") - .into_schema_form(); - format - .document_schemas_mut() - .expect("schema form") - .get_mut("domain") - .expect("domain schema") - .set_value( - "signatureSecurityLevelRequirement", - Value::U8(SecurityLevel::CRITICAL as u8), + #[tokio::test] + async fn should_check_the_registration_key_against_the_contract_the_registration_submits() { + // The SDK bundles a DPNS contract requiring HIGH; the network stores one whose + // `domain` requires CRITICAL, which the registration's documents are built against + let identity = identity(vec![key(0, SecurityLevel::MASTER)]); + let wallet = wallet_with_identity_on( + sdk_storing_dpns(&dpns_with_critical_domain()).await, + identity.clone(), + ) + .await; + let error = wallet + .identity() + .register_name_with_signer( + identity, + "alice", + key(1, SecurityLevel::HIGH), + None, + KeyFilter(|_| true), ) - .expect("schema is a map"); - let stricter_domain = - DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) - .expect("a valid contract"); - assert_eq!( - dpns_registration_requirement(&stricter_domain).unwrap(), - SecurityLevel::CRITICAL, - "one key signs both documents, so it must meet the stricter one" + .await + .unwrap_err(); + assert!( + matches!( + signature_refusal_of(&error), + Some(SignatureError::InvalidSignaturePublicKeySecurityLevelError( + _ + )) + ), + "a HIGH key cannot sign a `domain` the stored contract requires CRITICAL for: \ + {error:?}" + ); + } + + #[tokio::test] + async fn should_select_the_registration_key_by_the_contract_the_registration_submits() { + let wallet = wallet_with_identity_on( + sdk_storing_dpns(&dpns_with_critical_domain()).await, + identity(vec![ + key(0, SecurityLevel::MASTER), + key(1, SecurityLevel::HIGH), + ]), + ) + .await; + let identity_id = Identifier::from([1; 32]); + let error = wallet + .identity() + .register_name_with_external_signer(&identity_id, "alice", None, &KeyFilter(|_| true)) + .await + .unwrap_err(); + assert!( + matches!( + &error, + PlatformWalletError::NoUsableSigningKey { security_levels, .. } + if *security_levels + == SecurityLevel::accepted_for_requirement(SecurityLevel::CRITICAL) + ), + "only a CRITICAL key can sign a `domain` the stored contract requires CRITICAL \ + for: {error:?}" ); } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index 2e9d500949c..c14ca62b2e6 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -33,7 +33,6 @@ use dpp::document::property_names::PRICE; use dpp::document::{Document, DocumentV0Getters}; use dpp::fee::Credits; use dpp::identity::accessors::IdentityGettersV0; -use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; use dpp::identity::{IdentityPublicKey, Purpose, SecurityLevel}; use dpp::platform_value::btreemap_extensions::BTreeValueMapHelper; @@ -739,6 +738,16 @@ impl IdentityWallet { name: &str, ) -> Result, PlatformWalletError> { let contract = self.dpns_contract().await?; + self.dpns_name_state_in_contract(contract, name).await + } + + /// [`Self::dpns_name_state`] read through `contract`, the DPNS contract the caller + /// resolved for the whole operation. + async fn dpns_name_state_in_contract( + &self, + contract: Arc, + name: &str, + ) -> Result, PlatformWalletError> { let normalized = convert_to_homograph_safe_chars(dpns_label(name)); if normalized.is_empty() { return Err(PlatformWalletError::InvalidParameter( @@ -913,9 +922,13 @@ impl IdentityWallet { /// [`PlatformWalletError::DpnsNameNotFound`] otherwise. async fn fetch_dpns_domain_state_required( &self, + contract: &Arc, name: &str, ) -> Result { - if let Some(state) = self.dpns_name_state(name).await? { + if let Some(state) = self + .dpns_name_state_in_contract(Arc::clone(contract), name) + .await? + { return Ok(state); } let label = dpns_label(name); @@ -948,16 +961,18 @@ impl IdentityWallet { /// Auto-select the signing key for a DPNS `domain` state transition /// on `identity_id`: the identity's first AUTHENTICATION-purpose - /// ECDSA_SECP256K1 key whose security level satisfies the document - /// type's requirement and whose bounds cover `domain` (see - /// [`document_signing_key`]). Replaces the app - /// layer's hardcoded "key id 1". + /// ECDSA_SECP256K1 key whose security level satisfies what `contract`'s + /// `domain` type requires and whose bounds cover `domain` (see + /// [`document_signing_key`]). `contract` is the DPNS contract the + /// operation builds its transition against, so the key is judged by the + /// same snapshot it signs under. Replaces the app layer's hardcoded + /// "key id 1". async fn select_dpns_signing_key( &self, + contract: &DataContract, identity_id: &Identifier, signer: &impl Signer, ) -> Result { - let contract = self.dpns_contract().await?; let required_level = contract .document_type_for_name(DPNS_DOCUMENT_TYPE) .map_err(|e| { @@ -1147,7 +1162,10 @@ impl IdentityWallet { ))); } let _operation = self.dpns_operation_gate.lock().await; - let state = self.fetch_dpns_domain_state_required(name).await?; + let contract = self.dpns_contract().await?; + let state = self + .fetch_dpns_domain_state_required(&contract, name) + .await?; if state.owner_id != *owner_identity_id { return Err(PlatformWalletError::InvalidParameter(format!( "DPNS name {name:?} is owned by {}, not by {owner_identity_id}", @@ -1155,17 +1173,15 @@ impl IdentityWallet { ))); } let signing_key = self - .select_dpns_signing_key(owner_identity_id, signer) + .select_dpns_signing_key(&contract, owner_identity_id, signer) .await?; - let contract_id = dpns_contract_id(); let confirmed = self - .set_document_price_with_signer( - owner_identity_id, - &contract_id, + .set_document_price_in_contract( + contract, DPNS_DOCUMENT_TYPE, &state.document_id, price, - signing_key.id(), + &signing_key, signer, ) .await?; @@ -1196,7 +1212,10 @@ impl IdentityWallet { S: Signer + Send + Sync, { let _operation = self.dpns_operation_gate.lock().await; - let state = self.fetch_dpns_domain_state_required(name).await?; + let contract = self.dpns_contract().await?; + let state = self + .fetch_dpns_domain_state_required(&contract, name) + .await?; if state.owner_id != *owner_identity_id { return Err(PlatformWalletError::InvalidParameter(format!( "DPNS name {name:?} is owned by {}, not by {owner_identity_id}", @@ -1209,17 +1228,15 @@ impl IdentityWallet { }); } let signing_key = self - .select_dpns_signing_key(owner_identity_id, signer) + .select_dpns_signing_key(&contract, owner_identity_id, signer) .await?; - let contract_id = dpns_contract_id(); let confirmed = self - .transfer_document_with_signer( - owner_identity_id, - &contract_id, + .transfer_document_in_contract( + contract, DPNS_DOCUMENT_TYPE, &state.document_id, owner_identity_id, - signing_key.id(), + &signing_key, signer, ) .await?; @@ -1264,7 +1281,10 @@ impl IdentityWallet { .to_string(), )); } - let state = self.fetch_dpns_domain_state_required(name).await?; + let contract = self.dpns_contract().await?; + let state = self + .fetch_dpns_domain_state_required(&contract, name) + .await?; if state.owner_id != *owner_identity_id { return Err(PlatformWalletError::InvalidParameter(format!( "DPNS name {name:?} is owned by {}, not by {owner_identity_id}", @@ -1272,17 +1292,15 @@ impl IdentityWallet { ))); } let signing_key = self - .select_dpns_signing_key(owner_identity_id, signer) + .select_dpns_signing_key(&contract, owner_identity_id, signer) .await?; - let contract_id = dpns_contract_id(); let confirmed = self - .transfer_document_with_signer( - owner_identity_id, - &contract_id, + .transfer_document_in_contract( + contract, DPNS_DOCUMENT_TYPE, &state.document_id, recipient_id, - signing_key.id(), + &signing_key, signer, ) .await?; @@ -1358,7 +1376,10 @@ impl IdentityWallet { S: Signer + Send + Sync, { let _operation = self.dpns_operation_gate.lock().await; - let state = self.fetch_dpns_domain_state_required(name).await?; + let contract = self.dpns_contract().await?; + let state = self + .fetch_dpns_domain_state_required(&contract, name) + .await?; if state.owner_id == *purchaser_identity_id { return Err(PlatformWalletError::InvalidParameter(format!( "identity {purchaser_identity_id} already owns DPNS name {name:?}" @@ -1394,17 +1415,16 @@ impl IdentityWallet { }); } let signing_key = self - .select_dpns_signing_key(purchaser_identity_id, signer) + .select_dpns_signing_key(&contract, purchaser_identity_id, signer) .await?; - let contract_id = dpns_contract_id(); let confirmed = self - .purchase_document_with_signer( - purchaser_identity_id, - &contract_id, + .purchase_document_in_contract( + contract, DPNS_DOCUMENT_TYPE, &state.document_id, + purchaser_identity_id, expected_price, - signing_key.id(), + &signing_key, signer, ) .await?; @@ -1460,7 +1480,10 @@ impl IdentityWallet { ) -> Result, PlatformWalletError> { // Resolve the domain document id (live first, local rows for // departed names) and the registration timestamp when known. - let live = self.dpns_name_state(name).await?; + let contract = self.dpns_contract().await?; + let live = self + .dpns_name_state_in_contract(Arc::clone(&contract), name) + .await?; let (document_id, registered_at_ms) = match &live { Some(state) => (state.document_id, state.created_at_ms), None => { @@ -1476,7 +1499,7 @@ impl IdentityWallet { // Reuse the contested-aware classification for the // typed error. If the name appeared between the two // reads (registration race), just use it. - match self.fetch_dpns_domain_state_required(name).await { + match self.fetch_dpns_domain_state_required(&contract, name).await { Ok(state) => (state.document_id, state.created_at_ms), Err(e) => return Err(e), } diff --git a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs index d4677138e99..779dd73e37a 100644 --- a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs +++ b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs @@ -16,13 +16,13 @@ use crate::{Error, Sdk}; use dapi_grpc::platform::v0::ResponseMetadata; use dash_context_provider::ContextProvider; use dpp::data_contract::accessors::v0::DataContractV0Getters; -use dpp::data_contract::document_type::accessors::DocumentTypeV2Getters; +use dpp::data_contract::document_type::accessors::{DocumentTypeV0Getters, DocumentTypeV2Getters}; use dpp::data_contract::document_type::{DocumentType, DocumentTypeRef, LookupHashKey}; use dpp::document::{DocumentV0, DocumentV0Getters}; use dpp::fee::Credits; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; -use dpp::identity::{Identity, IdentityPublicKey}; +use dpp::identity::{Identity, IdentityPublicKey, SecurityLevel}; use dpp::platform_value::Value; use dpp::prelude::Identifier; use dpp::secp256k1::rand::rngs::StdRng; @@ -232,6 +232,7 @@ pub struct RegisterDpnsNameResult { } /// The documents a DPNS registration submits, built against one DPNS contract. +#[derive(Debug)] struct DpnsRegistrationDocuments { /// The DPNS contract the network stores now, which the documents were built against. dpns_contract: DataContract, @@ -240,6 +241,49 @@ struct DpnsRegistrationDocuments { domain_document_type: DocumentType, domain_document: Document, normalized_label: String, + /// The security level the key signing both documents must meet under `dpns_contract`. + signing_requirement: SecurityLevel, +} + +/// A DPNS name registration prepared by [`Sdk::prepare_dpns_name_registration`]: the preorder +/// and domain documents, built against the DPNS contract the network stores now, and what +/// that same contract requires of the key that signs them. A caller choosing or checking the +/// key reads its requirement here, then submits through +/// [`Sdk::submit_dpns_name_registration`], so the key is judged by the contract the +/// documents are built against and never by another snapshot of it. +#[derive(Debug)] +pub struct DpnsNameRegistration { + identity_id: Identifier, + documents: DpnsRegistrationDocuments, +} + +impl DpnsNameRegistration { + /// The security level the one key signing both registration documents must meet: the + /// strongest the `preorder` and `domain` document types require. + pub fn signing_security_level_requirement(&self) -> SecurityLevel { + self.documents.signing_requirement + } + + /// The id of the DPNS contract the registration writes to, which the signing key's + /// contract bounds must cover. + pub fn dpns_contract_id(&self) -> Identifier { + self.documents.dpns_contract.id() + } +} + +/// The security level the one key signing a registration's `preorder` and then its `domain` +/// must meet: the stronger of what the two document types require. +fn registration_signing_requirement( + preorder: DocumentTypeRef, + domain: DocumentTypeRef, +) -> SecurityLevel { + let preorder_requirement = preorder.security_level_requirement(); + let domain_requirement = domain.security_level_requirement(); + if domain_requirement.stronger_security_than(preorder_requirement) { + domain_requirement + } else { + preorder_requirement + } } /// How many DPNS contract responses a registration reads for one proved at the protocol @@ -448,6 +492,9 @@ impl Sdk { moderated_by: None, }); + let signing_requirement = + registration_signing_requirement(preorder_document_type, domain_document_type); + Ok(DpnsRegistrationDocuments { preorder_document_type: preorder_document_type.to_owned_document_type(), dpns_contract: dpns_contract.clone(), @@ -455,6 +502,7 @@ impl Sdk { domain_document_type: domain_document_type.to_owned_document_type(), domain_document, normalized_label, + signing_requirement, }) } @@ -500,17 +548,61 @@ impl Sdk { &self, input: RegisterDpnsNameInput, ) -> Result<(RegisterDpnsNameResult, Option, ResponseMetadata), Error> { - let identity_id = input.identity.id().to_owned(); - let DpnsRegistrationDocuments { - dpns_contract, - preorder_document_type, - preorder_document, - domain_document_type, - domain_document, - normalized_label, - } = self - .dpns_registration_documents(&input.label, identity_id) + let registration = self + .prepare_dpns_name_registration(&input.label, input.identity.id()) .await?; + self.submit_dpns_name_registration( + registration, + input.identity_public_key, + &input.signer, + input.preorder_callback, + input.contest_fund, + ) + .await + } + + /// Prepare the registration of `label` for `identity_id`: learn the network's protocol + /// version, fetch the DPNS contract the network stores now, and build the preorder and + /// domain documents against it. Nothing is signed or submitted. The returned + /// [`DpnsNameRegistration`] tells what that contract requires of the signing key; submit + /// it with [`Sdk::submit_dpns_name_registration`]. + pub async fn prepare_dpns_name_registration( + &self, + label: &str, + identity_id: Identifier, + ) -> Result { + let documents = self.dpns_registration_documents(label, identity_id).await?; + Ok(DpnsNameRegistration { + identity_id, + documents, + }) + } + + /// Submit a registration [`Sdk::prepare_dpns_name_registration`] prepared, signing both + /// documents with `identity_public_key` through `signer`, and return what + /// [`Sdk::register_dpns_name_with_owner_balance_and_metadata`] returns. `preorder_callback` + /// and `contest_fund` are those of [`RegisterDpnsNameInput`]. + pub async fn submit_dpns_name_registration>( + &self, + registration: DpnsNameRegistration, + identity_public_key: IdentityPublicKey, + signer: &S, + preorder_callback: Option, + contest_fund: Option, + ) -> Result<(RegisterDpnsNameResult, Option, ResponseMetadata), Error> { + let DpnsNameRegistration { + identity_id, + documents: + DpnsRegistrationDocuments { + dpns_contract, + preorder_document_type, + preorder_document, + domain_document_type, + domain_document, + normalized_label, + signing_requirement: _, + }, + } = registration; // From DPNS v3 an identity holds one pending preorder of a name: one an earlier // registration left behind, whose domain create failed, is revealed again rather @@ -534,8 +626,8 @@ impl Sdk { "preorder".to_string(), &expiring, ), - &input.identity_public_key, - &input.signer, + &identity_public_key, + signer, ) .await .inspect_err(|error| { @@ -549,9 +641,9 @@ impl Sdk { self, preorder_document_type, None, // entropy: generated together with the id once the nonce is known - input.identity_public_key.clone(), + identity_public_key.clone(), None, // token payment info - &input.signer, + signer, None, // settings ) .await @@ -563,13 +655,13 @@ impl Sdk { }; // Call the preorder callback if provided - if let Some(callback) = input.preorder_callback { + if let Some(callback) = preorder_callback { callback(&platform_preorder_document); } // Submit domain document after preorder debug!(%identity_id, stage = "domain", "DPNS registration: submitting document"); - let domain_settings = input.contest_fund.map(|contest_fund| PutSettings { + let domain_settings = contest_fund.map(|contest_fund| PutSettings { state_transition_creation_options: Some(StateTransitionCreationOptions { contest_fund: Some(contest_fund), ..Default::default() @@ -581,9 +673,9 @@ impl Sdk { self, domain_document_type, None, // entropy: generated together with the id once the nonce is known - input.identity_public_key, + identity_public_key, None, // token payment info - &input.signer, + signer, domain_settings, ) .await @@ -1089,6 +1181,83 @@ mod tests { assert!(declares_the_preorder_hash(&resolved)); } + /// The latest DPNS contract with its `domain` document type requiring a CRITICAL key, + /// where every shipped DPNS contract requires HIGH: what a network upgrade could store. + fn dpns_with_critical_domain() -> DataContract { + use dpp::data_contract::serialized_version::DataContractInSerializationFormat; + use dpp::identity::SecurityLevel; + use dpp::version::TryFromPlatformVersioned; + + let platform_version = PlatformVersion::latest(); + let dpns = load_system_data_contract(SystemDataContract::DPNS, platform_version) + .expect("the DPNS contract loads"); + let mut format = + DataContractInSerializationFormat::try_from_platform_versioned(dpns, platform_version) + .expect("the serialization format") + .into_schema_form(); + format + .document_schemas_mut() + .expect("the schema form") + .get_mut("domain") + .expect("the domain schema") + .set_value( + "signatureSecurityLevelRequirement", + Value::U8(SecurityLevel::CRITICAL as u8), + ) + .expect("the schema is a map"); + DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) + .expect("a valid contract") + } + + #[test] + fn should_require_the_strongest_level_of_both_registration_documents() { + use dpp::identity::SecurityLevel; + + let dpns = load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) + .expect("the DPNS contract loads"); + let level_of = |contract: &DataContract| { + registration_signing_requirement( + contract + .document_type_for_name("preorder") + .expect("preorder"), + contract.document_type_for_name("domain").expect("domain"), + ) + }; + assert_eq!(level_of(&dpns), SecurityLevel::HIGH); + assert_eq!( + level_of(&dpns_with_critical_domain()), + SecurityLevel::CRITICAL, + "one key signs both documents, so it must meet the stricter one" + ); + } + + #[tokio::test] + async fn should_prepare_the_signing_requirement_from_the_dpns_contract_the_network_stores() { + use dpp::identity::SecurityLevel; + + // The SDK bundles DPNS contracts requiring HIGH; the network stores one requiring + // CRITICAL for `domain` + let mut sdk = SdkBuilder::new_mock().build().expect("the mock SDK builds"); + expect_epoch_refresh(&mut sdk).await; + let stored = dpns_with_critical_domain(); + sdk.mock() + .expect_fetch(stored.id(), Some(stored.clone())) + .await + .expect("the DPNS fetch is expected"); + + let registration = sdk + .prepare_dpns_name_registration("Bob", Identifier::new([1u8; 32])) + .await + .expect("the registration is prepared"); + + assert_eq!( + registration.signing_security_level_requirement(), + SecurityLevel::CRITICAL, + "the key is checked against the contract the documents are built against" + ); + assert_eq!(registration.dpns_contract_id(), stored.id()); + } + /// A signer the tests never reach: each registration below stops before it signs. #[derive(Debug)] struct UnusedSigner; From ccb3d7a79cab0617d54e28b7eecb207b84420a98 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:15:16 +0000 Subject: [PATCH 41/53] fix(platform-wallet): sign with the weakest security level the requirement accepts Automatic signing-key selection walked qualifying keys in key-id order, so with the usual layout (1 CRITICAL, 2 HIGH) a HIGH write such as a DashPay contact request or a DPNS registration signed with the CRITICAL key. DIP-11 has clients gate stronger keys behind stronger authentication, so that meant a strong-auth prompt on routine writes or a CRITICAL key used as an everyday one. Within each limits group (unlimited keys, then limited ones) candidates now go weakest qualifying level first, then lowest key id; a stronger key signs only when the signer cannot reach a weaker one. Consensus accepts either key, so no on-chain behaviour changes. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/dpns_marketplace.rs | 8 +- .../wallet/identity/network/key_selection.rs | 83 ++++++++++++++++--- 2 files changed, 76 insertions(+), 15 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index c14ca62b2e6..7c30572e6f1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -960,10 +960,10 @@ impl IdentityWallet { // ----------------------------------------------------------------- /// Auto-select the signing key for a DPNS `domain` state transition - /// on `identity_id`: the identity's first AUTHENTICATION-purpose - /// ECDSA_SECP256K1 key whose security level satisfies what `contract`'s - /// `domain` type requires and whose bounds cover `domain` (see - /// [`document_signing_key`]). `contract` is the DPNS contract the + /// on `identity_id`: an AUTHENTICATION-purpose ECDSA_SECP256K1 key + /// whose security level satisfies what `contract`'s `domain` type + /// requires and whose bounds cover `domain`, the weakest such level + /// first (see [`document_signing_key`]). `contract` is the DPNS contract the /// operation builds its transition against, so the key is judged by the /// same snapshot it signs under. Replaces the app layer's hardcoded /// "key id 1". 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 cc0cf6ca990..b2db7c76e4c 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 @@ -23,6 +23,7 @@ use dpp::prelude::Identifier; use dpp::ProtocolError; use super::signing_key::{first_available, require_available}; +use std::cmp::Reverse; use std::time::{SystemTime, UNIX_EPOCH}; /// The key types Platform verifies an identity signature by (Drive's @@ -133,7 +134,10 @@ impl SigningScope<'_> { /// contract group: membership is state the wallet does not hold. A key without limits is /// preferred over any key with limits, whatever their security levels: a key with a budget or /// an expiry is an application key, taken only when no unlimited key qualifies. Within each -/// group keys go in key-id order. A disabled key is skipped, and so is a key whose expiry has +/// group the weakest qualifying security level goes first, then the lowest key id: DIP-11 has +/// clients ask for stronger authentication the stronger the key, so a HIGH write signs with a +/// HIGH key rather than a CRITICAL one, and a stronger key signs only when the signer cannot +/// reach a weaker one. A disabled key is skipped, and so is a key whose expiry has /// passed the wall clock (the block time trails it by seconds at most), or any key with an /// expiry when the system clock reads before the Unix epoch. What is left of a /// budget is not known offline; a spent key is refused by Platform. @@ -178,14 +182,21 @@ fn usable_signing_key_at<'a>( && !expired_or_unknown(key, now) && scope.bounds_check(key) == BatchedTransitionBoundsCheck::Allowed }; - let keys = identity.public_keys(); - let unlimited = keys + let mut candidates: Vec<&IdentityPublicKey> = identity + .public_keys() .values() - .filter(|key| qualifies(key) && !key.has_limits()); - let limited = keys - .values() - .filter(|key| qualifies(key) && key.has_limits()); - first_available(unlimited.chain(limited), signer) + .filter(|key| qualifies(key)) + .collect(); + // Unlimited keys first, then within each group the weakest level (the highest + // `SecurityLevel` discriminant: MASTER is 0, MEDIUM 3), then the lowest key id. + candidates.sort_by_key(|key| { + ( + key.has_limits(), + Reverse(key.security_level() as u8), + key.id(), + ) + }); + first_available(candidates.into_iter(), signer) } /// Check a key the caller chose to sign in `scope` against the rules [`usable_signing_key`] @@ -318,9 +329,10 @@ fn signature_refusal(error: SignatureError) -> dash_sdk::Error { ProtocolError::ConsensusError(Box::new(ConsensusError::SignatureError(error))).into() } -/// The first AUTHENTICATION key of `identity` at one of `security_levels`, of one of -/// `key_types`, that can sign a `document_type_name` document of `contract_id` now AND that -/// `signer` can sign with: [`usable_signing_key`] for one document type. +/// The AUTHENTICATION key of `identity` at one of `security_levels`, of one of `key_types`, +/// that can sign a `document_type_name` document of `contract_id` now AND that `signer` can +/// sign with, preferred in [`usable_signing_key`]'s order: [`usable_signing_key`] for one +/// document type. pub(crate) fn usable_authentication_key<'a>( identity: &'a Identity, signer: &impl Signer, @@ -615,6 +627,55 @@ pub(super) mod tests { } } + #[test] + fn should_sign_with_the_weakest_level_the_requirement_accepts() { + // DIP-11: a CRITICAL key asks for stronger authentication than a HIGH write needs + let identity = identity(vec![ + key(0, SecurityLevel::MASTER), + key(1, SecurityLevel::CRITICAL), + key(2, SecurityLevel::HIGH), + ]); + assert_eq!( + pick(&identity).map(|key| key.id()), + Some(2), + "a HIGH requirement signs with the HIGH key, not the lower-id CRITICAL one" + ); + } + + #[test] + fn should_take_the_lowest_key_id_among_keys_of_the_weakest_level() { + let identity = identity(vec![ + key(1, SecurityLevel::CRITICAL), + key(3, SecurityLevel::HIGH), + key(2, SecurityLevel::HIGH), + key(4, SecurityLevel::CRITICAL).with_limits(Some(1_000), None), + key(5, SecurityLevel::HIGH).with_limits(Some(1_000), None), + ]); + assert_eq!(pick(&identity).map(|key| key.id()), Some(2)); + } + + #[test] + fn should_order_limited_keys_weakest_level_first_too() { + let identity = identity(vec![ + key(1, SecurityLevel::CRITICAL).with_limits(Some(1_000), None), + key(2, SecurityLevel::HIGH).with_limits(Some(1_000), None), + ]); + assert_eq!(pick(&identity).map(|key| key.id()), Some(2)); + } + + #[test] + fn should_fall_back_to_a_stronger_key_the_signer_holds() { + let subject = identity(vec![ + key(1, SecurityLevel::CRITICAL), + key(2, SecurityLevel::HIGH), + ]); + assert_eq!( + pick_with_signer(&subject, &[1]).unwrap(), + Some(1), + "the signer cannot reach the HIGH key, so the CRITICAL one signs" + ); + } + #[test] fn should_rank_every_unlimited_key_before_any_limited_one_across_levels() { let identity = identity(vec![ From 1e4f3d205981d7d6811acaad257186f0a4a1b003 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:27:21 +0000 Subject: [PATCH 42/53] fix(platform-wallet): pick ECDSA_HASH160 signing keys, preferring DIP-11 key types Identities older Dash Evo Tool versions created hold ECDSA_HASH160 authentication keys by default. Platform verifies signatures by them on every identity-signed transition, but automatic selection only read ECDSA_SECP256K1 keys, so such identities could not register names, write documents, create contracts or use tokens without an explicit key. WALLET_SIGNING_KEY_TYPES now holds ECDSA_SECP256K1 and ECDSA_HASH160, and the profile and contactInfo writers read it instead of their own lists. Within each limits group, selection takes a DIP-11 key type before HASH160, then the weakest sufficient security level, then the lowest key id, so an identity holding both keeps signing with its raw public key. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/contact_info.rs | 4 +- .../src/wallet/identity/network/document.rs | 98 ++++++++++++++++++- .../identity/network/dpns_marketplace.rs | 8 +- .../wallet/identity/network/key_selection.rs | 79 ++++++++++++--- .../src/wallet/identity/network/profile.rs | 4 +- .../wallet/identity/network/signing_key.rs | 2 +- .../wallet/identity/network/tokens/helpers.rs | 4 +- 7 files changed, 169 insertions(+), 30 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_info.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_info.rs index 851b94291ef..4b64e8eda06 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_info.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_info.rs @@ -18,7 +18,7 @@ use dpp::document::{Document, DocumentV0}; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; -use dpp::identity::{IdentityPublicKey, KeyType, SecurityLevel}; +use dpp::identity::{IdentityPublicKey, SecurityLevel}; use dpp::platform_value::Value; use dpp::prelude::Identifier; @@ -603,7 +603,7 @@ impl DashPayView<'_, B> { dashpay_contract.id(), "contactInfo", &[SecurityLevel::HIGH, SecurityLevel::CRITICAL], - &[KeyType::ECDSA_SECP256K1], + &super::WALLET_SIGNING_KEY_TYPES, )? .cloned() .ok_or_else(|| { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs index 93466702d66..6ea7e81148c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/document.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/document.rs @@ -104,7 +104,8 @@ where } /// The key that signs a document batch in `scope` whose document type requires -/// `requirement`: an AUTHENTICATION, ECDSA_SECP256K1 key at a level consensus accepts. +/// `requirement`: an AUTHENTICATION key of one of [`WALLET_SIGNING_KEY_TYPES`] at a level +/// consensus accepts, in [`usable_signing_key`]'s order of preference. pub(super) fn document_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, @@ -172,8 +173,8 @@ impl IdentityWallet { /// `(contract, owner, type, entropy)` there — the placeholder /// id this build step assigns is overwritten. /// 3. Selects the signing `IdentityPublicKey` from the in-memory - /// wallet manager: an AUTHENTICATION-purpose, ECDSA_SECP256K1 - /// key whose security level satisfies the document type's + /// wallet manager: an AUTHENTICATION-purpose ECDSA key + /// (`ECDSA_SECP256K1` preferred, `ECDSA_HASH160` accepted) whose security level satisfies the document type's /// `security_level_requirement()` and whose bounds cover the /// document type (see [`document_signing_key`]). Returns a clear error /// if the owner identity isn't loaded or carries no qualifying @@ -436,7 +437,7 @@ impl IdentityWallet { /// the user keeps control of which key signs. We still enforce the /// document state-transition signing rules here: the key must exist /// and pass [`check_document_signing_key`] — AUTHENTICATION-purpose, - /// ECDSA_SECP256K1, at an accepted level, enabled, unexpired and inside + /// a key type Platform verifies, at an accepted level, enabled, unexpired and inside /// its contract bounds — the same rules `create` uses (see /// `project_document_signing_key_purpose_bug`: signing with a /// non-AUTHENTICATION key, e.g. a TRANSFER/CRITICAL key, is rejected @@ -1257,6 +1258,95 @@ mod tests { .map(|key| key.id()) } + #[tokio::test] + async fn should_sign_a_document_write_for_an_identity_holding_only_hash160_keys() { + use dpp::bls::native_bls::NativeBlsModule; + use dpp::data_contracts::SystemDataContract; + use dpp::document::DocumentV0; + use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::state_transition::batch_transition::methods::v0::DocumentsBatchTransitionMethodsV0; + use dpp::state_transition::batch_transition::BatchTransition; + use dpp::system_data_contracts::load_system_data_contract; + use dpp::util::hash::ripemd160_sha256; + use dpp::version::PlatformVersion; + use simple_signer::signer::SimpleSigner; + + // The default key layout of identities older Dash Evo Tool versions created: every + // key a HASH160 of its public key + let platform_version = PlatformVersion::latest(); + let mut signer = SimpleSigner::default(); + let keys: Vec = [ + (0, SecurityLevel::MASTER), + (1, SecurityLevel::CRITICAL), + (2, SecurityLevel::HIGH), + ] + .into_iter() + .map(|(id, security_level)| { + let private_key = [id as u8 + 1; 32]; + let secret = dpp::secp256k1::SecretKey::from_secret_bytes(private_key) + .expect("a valid secret key"); + let public_key = secret.public_key().serialize(); + let key = IdentityPublicKey::V0(IdentityPublicKeyV0 { + id, + purpose: Purpose::AUTHENTICATION, + security_level, + contract_bounds: None, + key_type: KeyType::ECDSA_HASH160, + read_only: false, + data: BinaryData::new(ripemd160_sha256(&public_key).to_vec()), + disabled_at: None, + }); + signer.add_identity_public_key(key.clone(), private_key); + key + }) + .collect(); + let identity = identity(keys); + + let dashpay = load_system_data_contract(SystemDataContract::Dashpay, platform_version) + .expect("the DashPay contract loads"); + let profile = dashpay + .document_type_for_name("profile") + .expect("the profile type"); + let key = document_signing_key( + &identity, + &signer, + profile.security_level_requirement(), + SigningScope::DocumentCreate { + document_type: profile, + }, + ) + .expect("the signer reaches the keys") + .expect("a HASH160 key signs a document write"); + assert_eq!(key.id(), 2, "the HIGH key, as the profile type requires"); + + let document = Document::V0(DocumentV0 { + id: Identifier::from([7; 32]), + owner_id: identity.id(), + properties: BTreeMap::from([( + "displayName".to_string(), + Value::Text("Alice".to_string()), + )]), + ..Default::default() + }); + let transition = BatchTransition::new_document_creation_transition_from_document( + document, + profile, + [9; 32], + key, + 1, + 0, + None, + &signer, + platform_version, + None, + ) + .await + .expect("the HASH160 key signs the batch"); + transition + .verify_identity_signed_signature(key, &NativeBlsModule, platform_version) + .expect("Platform verifies the signature by the HASH160 key"); + } + fn bound_elsewhere(id: u32, level: SecurityLevel) -> IdentityPublicKey { bound_key( id, diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs index 7c30572e6f1..24991575527 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns_marketplace.rs @@ -960,10 +960,10 @@ impl IdentityWallet { // ----------------------------------------------------------------- /// Auto-select the signing key for a DPNS `domain` state transition - /// on `identity_id`: an AUTHENTICATION-purpose ECDSA_SECP256K1 key - /// whose security level satisfies what `contract`'s `domain` type - /// requires and whose bounds cover `domain`, the weakest such level - /// first (see [`document_signing_key`]). `contract` is the DPNS contract the + /// on `identity_id`: an AUTHENTICATION-purpose ECDSA key whose + /// security level satisfies what `contract`'s `domain` type requires + /// and whose bounds cover `domain`, chosen in + /// [`document_signing_key`]'s order of preference. `contract` is the DPNS contract the /// operation builds its transition against, so the key is judged by the /// same snapshot it signs under. Replaces the app layer's hardcoded /// "key id 1". 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 b2db7c76e4c..a4effaa601a 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 @@ -29,9 +29,8 @@ use std::time::{SystemTime, UNIX_EPOCH}; /// The key types Platform verifies an identity signature by (Drive's /// `validate_state_transition_identity_signed`). Pass these as `key_types` to /// [`check_signing_key`] for a key the caller chose, so it is refused exactly where Platform -/// refuses it. The wallet's own choice of a credit transfer or withdrawal key uses them too, -/// so an `ECDSA_HASH160` TRANSFER key stays usable. Other automatic selection uses the -/// narrower [`WALLET_SIGNING_KEY_TYPES`]. +/// refuses it. The wallet's own choice of a credit transfer or withdrawal key uses them too. +/// Other automatic selection uses the narrower [`WALLET_SIGNING_KEY_TYPES`]. pub const PLATFORM_SIGNING_KEY_TYPES: [KeyType; 3] = [ KeyType::ECDSA_SECP256K1, KeyType::BLS12_381, @@ -42,7 +41,13 @@ pub const PLATFORM_SIGNING_KEY_TYPES: [KeyType; 3] = [ /// withdrawal key, which may be any of [`PLATFORM_SIGNING_KEY_TYPES`]. Pass these as /// `key_types` to [`usable_signing_key`] to choose the key the wallet itself would; a key the /// caller chose is checked against [`PLATFORM_SIGNING_KEY_TYPES`] instead. -pub const WALLET_SIGNING_KEY_TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; +/// +/// `ECDSA_HASH160` is here so identities whose keys hold only the hash of the public key, the +/// default layout older Dash Evo Tool versions created, keep signing wherever Platform +/// accepts the key; [`usable_signing_key`] still prefers an `ECDSA_SECP256K1` key, the type +/// DIP-11 defines. +pub const WALLET_SIGNING_KEY_TYPES: [KeyType; 2] = + [KeyType::ECDSA_SECP256K1, KeyType::ECDSA_HASH160]; /// What a signature authorizes, as far as a key's contract bounds go. #[derive(Debug, Clone, Copy, PartialEq)] @@ -134,10 +139,11 @@ impl SigningScope<'_> { /// contract group: membership is state the wallet does not hold. A key without limits is /// preferred over any key with limits, whatever their security levels: a key with a budget or /// an expiry is an application key, taken only when no unlimited key qualifies. Within each -/// group the weakest qualifying security level goes first, then the lowest key id: DIP-11 has -/// clients ask for stronger authentication the stronger the key, so a HIGH write signs with a -/// HIGH key rather than a CRITICAL one, and a stronger key signs only when the signer cannot -/// reach a weaker one. A disabled key is skipped, and so is a key whose expiry has +/// group a key of a type DIP-11 defines goes before an `ECDSA_HASH160` one, which holds only +/// the hash of its public key; then the weakest qualifying security level, then the lowest key +/// id: DIP-11 has clients ask for stronger authentication the stronger the key, so a HIGH +/// write signs with a HIGH key rather than a CRITICAL one, and a stronger key signs only when +/// the signer cannot reach a weaker one. A disabled key is skipped, and so is a key whose expiry has /// passed the wall clock (the block time trails it by seconds at most), or any key with an /// expiry when the system clock reads before the Unix epoch. What is left of a /// budget is not known offline; a spent key is refused by Platform. @@ -187,11 +193,13 @@ fn usable_signing_key_at<'a>( .values() .filter(|key| qualifies(key)) .collect(); - // Unlimited keys first, then within each group the weakest level (the highest - // `SecurityLevel` discriminant: MASTER is 0, MEDIUM 3), then the lowest key id. + // Unlimited keys first, then within each group a DIP-11 key type before HASH160, then the + // weakest level (the highest `SecurityLevel` discriminant: MASTER is 0, MEDIUM 3), then the + // lowest key id. candidates.sort_by_key(|key| { ( key.has_limits(), + key.key_type() == KeyType::ECDSA_HASH160, Reverse(key.security_level() as u8), key.id(), ) @@ -419,7 +427,14 @@ pub(super) mod tests { } const LEVELS: [SecurityLevel; 2] = [SecurityLevel::HIGH, SecurityLevel::CRITICAL]; - const TYPES: [KeyType; 1] = [KeyType::ECDSA_SECP256K1]; + /// The key types the wallet's own choice reads, as production passes them. + const TYPES: [KeyType; 2] = WALLET_SIGNING_KEY_TYPES; + + fn hash160(mut key: IdentityPublicKey) -> IdentityPublicKey { + key.set_key_type(KeyType::ECDSA_HASH160); + key.set_data(BinaryData::new(vec![key.id() as u8; 20])); + key + } #[test] fn prefers_a_key_without_limits_over_an_earlier_limited_one() { @@ -642,6 +657,40 @@ pub(super) mod tests { ); } + #[test] + fn should_prefer_a_raw_public_key_over_a_hash160_key_of_a_weaker_level() { + // DIP-11 keys hold the public key itself; older Dash Evo Tool identities hold HASH160 + let identity = identity(vec![ + key(1, SecurityLevel::CRITICAL), + hash160(key(2, SecurityLevel::HIGH)), + ]); + assert_eq!(pick(&identity).map(|key| key.id()), Some(1)); + } + + #[test] + fn should_sign_with_a_hash160_key_when_the_identity_holds_no_other() { + // The default key layout of identities older Dash Evo Tool versions created + let identity = identity(vec![ + hash160(key(0, SecurityLevel::MASTER)), + hash160(key(1, SecurityLevel::CRITICAL)), + hash160(key(2, SecurityLevel::HIGH)), + ]); + assert_eq!( + pick(&identity).map(|key| key.id()), + Some(2), + "the weakest level the requirement accepts, among HASH160 keys too" + ); + } + + #[test] + fn should_rank_an_unlimited_hash160_key_before_a_limited_raw_one() { + let identity = identity(vec![ + key(1, SecurityLevel::HIGH).with_limits(Some(1_000), None), + hash160(key(2, SecurityLevel::HIGH)), + ]); + assert_eq!(pick(&identity).map(|key| key.id()), Some(2)); + } + #[test] fn should_take_the_lowest_key_id_among_keys_of_the_weakest_level() { let identity = identity(vec![ @@ -839,10 +888,10 @@ pub(super) mod tests { _ )) )); - let mut hash160 = key(1, SecurityLevel::HIGH); - hash160.set_key_type(KeyType::ECDSA_HASH160); + let mut eddsa = key(1, SecurityLevel::HIGH); + eddsa.set_key_type(KeyType::EDDSA_25519_HASH160); assert!(matches!( - check(&hash160, document_scope()) + check(&eddsa, document_scope()) .as_ref() .err() .and_then(signature_refusal_of), @@ -1064,7 +1113,7 @@ pub(super) mod tests { fn should_report_a_wrong_key_type_before_a_wrong_purpose_as_drive_does() { let mut both_wrong = key(1, SecurityLevel::HIGH); both_wrong.set_purpose(Purpose::TRANSFER); - both_wrong.set_key_type(KeyType::ECDSA_HASH160); + both_wrong.set_key_type(KeyType::EDDSA_25519_HASH160); let refusal = check(&both_wrong, document_scope()); assert!( matches!( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 14e82b28e91..160f92df4fd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -9,7 +9,6 @@ use dpp::identity::accessors::IdentityGettersV0; #[cfg(test)] use dpp::identity::identity_public_key::Purpose; use dpp::identity::signer::Signer; -use dpp::identity::KeyType; use dpp::identity::SecurityLevel; use dpp::identity::{Identity, IdentityPublicKey}; use dpp::platform_value::Value; @@ -41,7 +40,7 @@ fn profile_signing_key<'a>( dashpay_contract_id, "profile", &[SecurityLevel::HIGH, SecurityLevel::CRITICAL], - &[KeyType::ECDSA_SECP256K1, KeyType::ECDSA_HASH160], + &super::WALLET_SIGNING_KEY_TYPES, ) } @@ -585,6 +584,7 @@ mod tests { use std::collections::BTreeMap; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::identity::KeyType; use dpp::version::PlatformVersion; fn profile_key(key_type: KeyType, security_level: SecurityLevel) -> IdentityPublicKeyV0 { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 87f499945d1..6e139de6bbd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -726,7 +726,7 @@ pub(super) mod tests { .. } if *identity_id == identity && security_levels == &[level] - && key_types == &[KeyType::ECDSA_SECP256K1] + && key_types == &WALLET_SIGNING_KEY_TYPES ), "{error:?}" ); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 44643c95726..9d485176aa1 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -1,7 +1,7 @@ //! Shared lookups for token state-transition methods on //! [`IdentityWallet`]. All token actions need to (a) fetch the data //! contract by id and (b) resolve the canonical AUTHENTICATION / -//! CRITICAL / ECDSA_SECP256K1 signing key on the actor identity, +//! CRITICAL / ECDSA signing key on the actor identity, //! so those steps live here rather than being copy-pasted across each //! action file. //! @@ -93,7 +93,7 @@ impl IdentityWallet { /// which on-chain key id to sign with. /// /// Key selection is a fixed canonical policy: - /// `Purpose::AUTHENTICATION` × `SecurityLevel::CRITICAL` × `ECDSA_SECP256K1`, + /// `Purpose::AUTHENTICATION` × `SecurityLevel::CRITICAL` × `WALLET_SIGNING_KEY_TYPES`, /// bounds covering `token_contract_id` (see `token_signing_key`). /// Callers that pass a `signing_key_id` over FFI are advisory — /// this Rust path is authoritative and Drive validates the chosen From e9580039434998a9be860d1e8bb4464952dde22f Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:31:54 +0000 Subject: [PATCH 43/53] fix(platform-wallet): sign a contract create with a HIGH key Consensus accepts a HIGH or CRITICAL key for a contract create and only a CRITICAL key for a contract update, but the wallet asked for CRITICAL on both. A create now selects from HIGH or stronger (HIGH preferred, by the weakest-sufficient-level rule); an update keeps CRITICAL. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/contract.rs | 22 ++--- .../wallet/identity/network/signing_key.rs | 90 +++++++++++++++++-- 2 files changed, 96 insertions(+), 16 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs index bea686e517e..edc2d99da07 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs @@ -27,7 +27,9 @@ //! memory unsafety. use super::key_selection::WALLET_SIGNING_KEY_TYPES; -use super::signing_key::{contract_signing_key, CONTRACT_SIGNING_LEVELS}; +use super::signing_key::{ + contract_signing_key, CONTRACT_CREATE_SIGNING_LEVELS, CONTRACT_UPDATE_SIGNING_LEVELS, +}; use async_trait::async_trait; use dpp::address_funds::AddressWitness; @@ -96,9 +98,9 @@ impl IdentityWallet { /// beyond `documents_schema_json` is optional and absent when /// `None`. The function: /// 1. Looks up `owner_identity_id` in the in-memory wallet - /// manager, picks a CRITICAL + AUTHENTICATION + ECDSA - /// key (DPP requires that exact triple for a contract- - /// create signature). + /// manager and picks an AUTHENTICATION ECDSA key at HIGH or + /// stronger short of MASTER, the levels DPP accepts for a + /// contract-create signature (HIGH preferred). /// 2. Generates the deterministic contract id from /// `(owner_id, identity_nonce)`. /// 3. Assembles a V1 serialization-format payload carrying @@ -163,11 +165,11 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*owner_identity_id))?; drop(wm); - contract_signing_key(&identity, signer)? + contract_signing_key(&identity, signer, &CONTRACT_CREATE_SIGNING_LEVELS)? .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { identity_id: *owner_identity_id, purpose: Purpose::AUTHENTICATION, - security_levels: CONTRACT_SIGNING_LEVELS.to_vec(), + security_levels: CONTRACT_CREATE_SIGNING_LEVELS.to_vec(), key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "a contract-create state transition".to_string(), })? @@ -312,8 +314,8 @@ impl IdentityWallet { /// from `existing` keeps every untouched section intact. The /// function: /// 1. Looks up `owner_identity_id` in the in-memory wallet - /// manager and picks the CRITICAL + AUTHENTICATION + ECDSA - /// key (same triple a contract-create signature requires). + /// manager and picks a CRITICAL AUTHENTICATION ECDSA key, the + /// only level DPP accepts for a contract-update signature. /// 2. Fetches the *current* contract from Platform and validates /// that it is actually owned by `owner_identity_id` — this /// runs *before* any nonce fetch/bump so a bad (owner, @@ -377,11 +379,11 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*owner_identity_id))?; drop(wm); - contract_signing_key(&identity, signer)? + contract_signing_key(&identity, signer, &CONTRACT_UPDATE_SIGNING_LEVELS)? .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { identity_id: *owner_identity_id, purpose: Purpose::AUTHENTICATION, - security_levels: CONTRACT_SIGNING_LEVELS.to_vec(), + security_levels: CONTRACT_UPDATE_SIGNING_LEVELS.to_vec(), key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "a contract-update state transition".to_string(), })? diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 6e139de6bbd..e22125b3ac8 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -47,23 +47,31 @@ pub(super) fn first_available<'a>( unavailable.map_or(Ok(None), |key| Err(signing_key_unavailable(key))) } -/// The security levels [`contract_signing_key`] accepts. -pub(super) const CONTRACT_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; +/// The security levels a contract create accepts: HIGH or stronger short of MASTER, as +/// consensus does (`DataContractCreateTransition::security_level_requirement`). +pub(super) const CONTRACT_CREATE_SIGNING_LEVELS: [SecurityLevel; 2] = + [SecurityLevel::CRITICAL, SecurityLevel::HIGH]; + +/// The security levels a contract update accepts: CRITICAL only, as consensus does +/// (`DataContractUpdateTransition::security_level_requirement`). +pub(super) const CONTRACT_UPDATE_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; /// The security levels [`master_signing_key`] accepts. pub(super) const MASTER_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::MASTER]; -/// The key that signs a contract create or update: a CRITICAL AUTHENTICATION ECDSA key. +/// The key that signs a contract create or update: an AUTHENTICATION ECDSA key at one of +/// `security_levels`, [`CONTRACT_CREATE_SIGNING_LEVELS`] or [`CONTRACT_UPDATE_SIGNING_LEVELS`]. /// These are not batches, so a contract-bound key cannot sign them. pub(super) fn contract_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, + security_levels: &[SecurityLevel], ) -> Result, dash_sdk::Error> { usable_signing_key( identity, signer, Purpose::AUTHENTICATION, - &CONTRACT_SIGNING_LEVELS, + security_levels, &WALLET_SIGNING_KEY_TYPES, SigningScope::NonBatch, ) @@ -419,7 +427,12 @@ pub(super) mod tests { key(2, SecurityLevel::CRITICAL).with_limits(Some(1_000), None), key(3, SecurityLevel::CRITICAL), ]); - let chosen = contract_signing_key(&identity, &KeyFilter(|_| true)).unwrap(); + let chosen = contract_signing_key( + &identity, + &KeyFilter(|_| true), + &CONTRACT_UPDATE_SIGNING_LEVELS, + ) + .unwrap(); assert_eq!( chosen.map(|key| key.id()), Some(3), @@ -428,6 +441,40 @@ pub(super) mod tests { ); } + #[test] + fn should_create_a_contract_with_the_high_key_and_update_it_only_with_a_critical_one() { + use super::super::key_selection::tests::{identity as identity_of, key}; + + let pick = |keys: Vec, levels: &[SecurityLevel]| { + contract_signing_key(&identity_of(keys), &KeyFilter(|_| true), levels) + .unwrap() + .map(|key| key.id()) + }; + let layout = || { + vec![ + key(0, SecurityLevel::MASTER), + key(1, SecurityLevel::CRITICAL), + key(2, SecurityLevel::HIGH), + ] + }; + assert_eq!( + pick(layout(), &CONTRACT_CREATE_SIGNING_LEVELS), + Some(2), + "consensus accepts a HIGH key for a contract create" + ); + assert_eq!(pick(layout(), &CONTRACT_UPDATE_SIGNING_LEVELS), Some(1)); + let without_critical = || vec![key(0, SecurityLevel::MASTER), key(2, SecurityLevel::HIGH)]; + assert_eq!( + pick(without_critical(), &CONTRACT_UPDATE_SIGNING_LEVELS), + None, + "a contract update requires a CRITICAL key" + ); + assert_eq!( + pick(without_critical(), &CONTRACT_CREATE_SIGNING_LEVELS), + Some(2) + ); + } + #[test] fn should_skip_a_disabled_master_key() { let mut identity = identity( @@ -737,8 +784,9 @@ pub(super) mod tests { let (wallet, identity_id) = wallet_without_critical_or_master_keys().await; let error = wallet .identity() - .create_data_contract_with_signer( + .update_data_contract_with_signer( &identity_id, + &Identifier::from([0x0C; 32]), "{}", None, None, @@ -750,6 +798,36 @@ pub(super) mod tests { .await .unwrap_err(); assert_no_usable_key(error, identity_id, SecurityLevel::CRITICAL); + + let identity = identity( + Purpose::AUTHENTICATION, + SecurityLevel::MEDIUM, + KeyType::ECDSA_SECP256K1, + ); + let identity_id = identity.id(); + let wallet = wallet_with_identity(identity).await; + let error = wallet + .identity() + .create_data_contract_with_signer( + &identity_id, + "{}", + None, + None, + None, + None, + None, + &KeyFilter(|_| true), + ) + .await + .unwrap_err(); + assert!( + matches!( + &error, + PlatformWalletError::NoUsableSigningKey { security_levels, .. } + if security_levels == &[SecurityLevel::CRITICAL, SecurityLevel::HIGH] + ), + "a contract create accepts HIGH or stronger: {error:?}" + ); } #[tokio::test] From 747d5cdcddca4b6a7a33c3aa56cd599bb1cdb749 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:53:31 +0000 Subject: [PATCH 44/53] fix(platform-wallet,sdk): judge contact-request signing keys by the contract the document is built against The wallet chose a contact request's signing key by the DashPay contract bundled for the SDK's protocol version, while `Sdk::send_contact_request` built and submitted the document against the contract it fetched itself (twice: once to build, once to submit). After a protocol or system-contract upgrade the two could disagree on the level the key must meet. rs-sdk (additive API): `Sdk::prepare_contact_request` fetches the DashPay contract once and returns a `PreparedContactRequest` stating the signing-level requirement and the `contactRequest` document type of that snapshot; `Sdk::submit_contact_request` builds and submits the document as exactly that type. `create_contact_request` and `send_contact_request` keep their signatures and use one snapshot each. platform-wallet selects the key from the prepared request and hands the same value to the SDK writer; public signatures are unchanged. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/contact_requests.rs | 112 +++------ .../src/wallet/identity/network/sdk_writer.rs | 17 +- .../src/platform/dashpay/contact_request.rs | 235 ++++++++++++++++-- packages/rs-sdk/src/platform/dashpay/mod.rs | 3 +- 4 files changed, 262 insertions(+), 105 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index 41156da44ac..5ef13cb1cc9 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -2,10 +2,7 @@ use super::document::document_signing_key; use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; -use dpp::data_contract::accessors::v0::DataContractV0Getters; -use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; -use dpp::data_contract::DataContract; -use dpp::data_contracts::SystemDataContract; +use dpp::data_contract::document_type::DocumentTypeRef; use dpp::document::DocumentV0Getters; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -17,8 +14,6 @@ use dpp::identity::KeyType; use dpp::identity::SecurityLevel; use dpp::platform_value::Value; use dpp::prelude::Identifier; -use dpp::system_data_contracts::load_system_data_contract; -use dpp::ProtocolError; use super::contacts::{ExternalAccountRegistration, RegisterExternalError}; use super::sdk_writer::SendContactRequestParams; @@ -622,22 +617,25 @@ impl DashPayView<'_, B> { ), }; - // 5. Build the signing key reference for document signing. - // The level comes from the bundled DashPay contract for the SDK's - // protocol version, so no request is made for it. - let dashpay = load_system_data_contract(SystemDataContract::Dashpay, self.sdk.version()) - .map_err(dash_sdk::Error::from)?; - let requirement = contact_request_requirement(&dashpay).map_err(dash_sdk::Error::from)?; - let identity_public_key = - contact_request_signing_key(&sender_identity, signer, &dashpay, requirement)? - .cloned() - .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { - identity_id: *sender_identity_id, - purpose: Purpose::AUTHENTICATION, - security_levels: SecurityLevel::accepted_for_requirement(requirement), - key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), - transition: "a contactRequest document transition".to_string(), - })?; + // 5. Choose the document signing key by the DashPay contract the + // SDK builds the request against: one snapshot decides both the + // key and the document it signs. + let prepared = self.sdk.prepare_contact_request().await?; + let requirement = prepared.signing_security_level_requirement(); + let identity_public_key = contact_request_signing_key( + &sender_identity, + signer, + prepared.contact_request_document_type(), + requirement, + )? + .cloned() + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *sender_identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement(requirement), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: "a contactRequest document transition".to_string(), + })?; // 6. Client-side ECDH via the signer: the shared secret is derived in // the signer (scalar at `sender_enc_path`) against the recipient's @@ -674,6 +672,7 @@ impl DashPayView<'_, B> { let result = self .sdk_writer .send_contact_request(SendContactRequestParams { + prepared, sender_identity: sender_identity.clone(), recipient_identity, sender_key_index, @@ -1233,29 +1232,17 @@ fn select_recipient_key_index(recipient_identity: &Identity) -> Result Result { - Ok(dashpay - .document_type_for_name(CONTACT_REQUEST_DOCUMENT_TYPE)? - .security_level_requirement()) -} - -/// The key that signs an outgoing `contactRequest` document of `dashpay`: an AUTHENTICATION -/// ECDSA key meeting `requirement` whose bounds cover creating a `contactRequest`. MASTER is -/// rejected on document writes. +/// The key that signs an outgoing document of the `contactRequest` type `contact_request`: an +/// AUTHENTICATION ECDSA key meeting `requirement` whose bounds cover creating a +/// `contactRequest`. MASTER is rejected on document writes. Both come from the +/// [`PreparedContactRequest`](dash_sdk::platform::dashpay::PreparedContactRequest) the key +/// will sign, so the key is judged by the contract the document is built against. fn contact_request_signing_key<'a>( identity: &'a Identity, signer: &impl Signer, - dashpay: &DataContract, + contact_request: DocumentTypeRef<'_>, requirement: SecurityLevel, ) -> Result, dash_sdk::Error> { - let contact_request = dashpay - .document_type_for_name(CONTACT_REQUEST_DOCUMENT_TYPE) - .map_err(ProtocolError::from)?; document_signing_key( identity, signer, @@ -6639,44 +6626,10 @@ mod contact_request_key_tests { use super::super::key_selection::tests::{bound_key, identity, key}; use super::super::signing_key::tests::KeyFilter; use super::*; + use dpp::data_contract::accessors::v0::DataContractV0Getters; + use dpp::data_contracts::SystemDataContract; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; - - #[test] - fn should_require_the_level_the_contact_request_document_type_requires() { - use dpp::data_contract::serialized_version::DataContractInSerializationFormat; - use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; - - let platform_version = PlatformVersion::latest(); - let dashpay = load_system_data_contract(SystemDataContract::Dashpay, platform_version) - .expect("bundled DashPay contract"); - assert_eq!( - contact_request_requirement(&dashpay).unwrap(), - SecurityLevel::HIGH - ); - let mut format = DataContractInSerializationFormat::try_from_platform_versioned( - dashpay, - platform_version, - ) - .expect("serialization format") - .into_schema_form(); - format - .document_schemas_mut() - .expect("schema form") - .get_mut(CONTACT_REQUEST_DOCUMENT_TYPE) - .expect("contactRequest schema") - .set_value( - "signatureSecurityLevelRequirement", - Value::U8(SecurityLevel::CRITICAL as u8), - ) - .expect("schema is a map"); - let stricter = - DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) - .expect("a valid contract"); - assert_eq!( - contact_request_requirement(&stricter).unwrap(), - SecurityLevel::CRITICAL - ); - } + use dpp::system_data_contracts::load_system_data_contract; #[test] fn should_sign_a_contact_request_with_a_key_bound_to_contact_requests_or_unbound() { @@ -6696,11 +6649,14 @@ mod contact_request_key_tests { dpp::version::PlatformVersion::latest(), ) .expect("bundled DashPay contract"); + let contact_request = contract + .document_type_for_name("contactRequest") + .expect("the contactRequest type"); let pick = |identity: &Identity| { contact_request_signing_key( identity, &KeyFilter(|_| true), - &contract, + contact_request, SecurityLevel::HIGH, ) .unwrap() diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs index 765074e7b7a..6457c9aed6a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/sdk_writer.rs @@ -27,8 +27,8 @@ use dpp::identity::{Identity, IdentityPublicKey}; use dash_sdk::dapi_grpc::platform::v0::ResponseMetadata; use dash_sdk::platform::dashpay::{ - ContactRequestInput, EcdhProvider, RecipientIdentity, SendContactRequestInput, - SendContactRequestResult, + ContactRequestInput, EcdhProvider, PreparedContactRequest, RecipientIdentity, + SendContactRequestInput, SendContactRequestResult, }; use crate::error::PlatformWalletError; @@ -91,6 +91,9 @@ where /// either the resident seed or the Keychain signer without the helper /// knowing which. pub(crate) struct SendContactRequestParams<'a> { + /// The DashPay contract snapshot `signing_public_key` was chosen by; + /// the document is built and submitted as its `contactRequest` type. + pub prepared: PreparedContactRequest, /// Sender (owner) identity — already loaded from local state. pub sender_identity: Identity, /// Recipient identity — already fetched from Platform. @@ -185,6 +188,7 @@ impl SdkWriter { params: SendContactRequestParams<'_>, ) -> Result { let SendContactRequestParams { + prepared, sender_identity, recipient_identity, sender_key_index, @@ -247,9 +251,12 @@ impl SdkWriter { let xpub_bytes_clone = xpub_bytes.clone(); self.sdk - .send_contact_request(send_input, ecdh_provider, |_account_ref: u32| async move { - Ok::, dash_sdk::Error>(xpub_bytes_clone) - }) + .submit_contact_request( + prepared, + send_input, + ecdh_provider, + |_account_ref: u32| async move { Ok::, dash_sdk::Error>(xpub_bytes_clone) }, + ) .await .map_err(PlatformWalletError::Sdk) } diff --git a/packages/rs-sdk/src/platform/dashpay/contact_request.rs b/packages/rs-sdk/src/platform/dashpay/contact_request.rs index 3f528a4bba6..63ef6731550 100644 --- a/packages/rs-sdk/src/platform/dashpay/contact_request.rs +++ b/packages/rs-sdk/src/platform/dashpay/contact_request.rs @@ -7,12 +7,14 @@ use crate::platform::Document; use crate::{Error, Sdk}; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dpp::data_contract::document_type::{DocumentType, DocumentTypeRef}; +use dpp::data_contract::DataContract; use dpp::document::DocumentV0; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::identity_public_key::Purpose; use dpp::identity::signer::Signer; -use dpp::identity::{Identity, IdentityPublicKey}; +use dpp::identity::{Identity, IdentityPublicKey, SecurityLevel}; use dpp::platform_value::{Bytes32, Value}; use dpp::prelude::Identifier; use dpp::secp256k1::rand::rngs::StdRng; @@ -22,6 +24,41 @@ use platform_encryption::{ derive_shared_key_ecdh, encrypt_account_label, encrypt_extended_public_key, COMPACT_XPUB_LEN, }; use std::collections::BTreeMap; +use std::sync::Arc; + +/// The DashPay document type a contact request writes. +const CONTACT_REQUEST_DOCUMENT_TYPE: &str = "contactRequest"; + +/// A contact request prepared by [`Sdk::prepare_contact_request`]: the DashPay contract the +/// request document is built against, and what that same contract requires of the key that +/// signs it. A caller choosing the key reads it here, then sends through +/// [`Sdk::submit_contact_request`], so the key is judged by the contract the document is +/// built against and never by another snapshot of it. +#[derive(Debug, Clone)] +pub struct PreparedContactRequest { + dashpay_contract: Arc, + contact_request_document_type: DocumentType, +} + +impl PreparedContactRequest { + /// The security level the key signing the `contactRequest` document must meet. + pub fn signing_security_level_requirement(&self) -> SecurityLevel { + self.contact_request_document_type + .as_ref() + .security_level_requirement() + } + + /// The `contactRequest` document type the request is built as, which the signing key's + /// contract bounds must cover. + pub fn contact_request_document_type(&self) -> DocumentTypeRef<'_> { + self.contact_request_document_type.as_ref() + } + + /// The id of the DashPay contract the request writes to. + pub fn dashpay_contract_id(&self) -> Identifier { + self.dashpay_contract.id() + } +} /// ECDH provider for contact request encryption /// @@ -258,6 +295,45 @@ impl Sdk { ecdh_provider: EcdhProvider, get_extended_public_key: H, ) -> Result + where + F: FnOnce(&IdentityPublicKey, u32) -> Fut, + Fut: std::future::Future>, + G: FnOnce(&PublicKey) -> Gut, + Gut: std::future::Future>, + H: FnOnce(u32) -> Hut, + Hut: std::future::Future, Error>>, + { + let prepared = self.prepare_contact_request().await?; + self.build_contact_request(&prepared, input, ecdh_provider, get_extended_public_key) + .await + } + + /// Prepare a contact request: fetch the DashPay contract (from the context provider when + /// it holds one) and resolve its `contactRequest` document type. Nothing is built, signed + /// or submitted. The returned [`PreparedContactRequest`] tells what that contract requires + /// of the signing key; send it with [`Sdk::submit_contact_request`]. + pub async fn prepare_contact_request(&self) -> Result { + let dashpay_contract = self.fetch_dashpay_contract().await?; + let contact_request_document_type = dashpay_contract + .document_type_cloned_for_name(CONTACT_REQUEST_DOCUMENT_TYPE) + .map_err(|_| { + Error::Generic("DashPay contactRequest document type not found".to_string()) + })?; + Ok(PreparedContactRequest { + dashpay_contract, + contact_request_document_type, + }) + } + + /// The contact request document [`Sdk::create_contact_request`] describes, built as + /// `prepared`'s `contactRequest` document type. + async fn build_contact_request( + &self, + prepared: &PreparedContactRequest, + input: ContactRequestInput, + ecdh_provider: EcdhProvider, + get_extended_public_key: H, + ) -> Result where F: FnOnce(&IdentityPublicKey, u32) -> Fut, Fut: std::future::Future>, @@ -399,15 +475,7 @@ impl Sdk { None }; - // Fetch DashPay contract - let dashpay_contract = self.fetch_dashpay_contract().await?; - - // Get contactRequest document type - let contact_request_document_type = dashpay_contract - .document_type_for_name("contactRequest") - .map_err(|_| { - Error::Generic("DashPay contactRequest document type not found".to_string()) - })?; + let contact_request_document_type = prepared.contact_request_document_type(); // Generate entropy for document ID let mut rng = StdRng::from_os_rng(); @@ -416,7 +484,7 @@ impl Sdk { // Generate document ID let sender_id = input.sender_identity.id().to_owned(); let document_id = Document::generate_document_id_v0( - &dashpay_contract.id(), + &prepared.dashpay_contract_id(), &sender_id, contact_request_document_type.name(), entropy.as_slice(), @@ -494,6 +562,29 @@ impl Sdk { ecdh_provider: EcdhProvider, get_extended_public_key: H, ) -> Result + where + F: FnOnce(&IdentityPublicKey, u32) -> Fut, + Fut: std::future::Future>, + G: FnOnce(&PublicKey) -> Gut, + Gut: std::future::Future>, + H: FnOnce(u32) -> Hut, + Hut: std::future::Future, Error>>, + { + let prepared = self.prepare_contact_request().await?; + self.submit_contact_request(prepared, input, ecdh_provider, get_extended_public_key) + .await + } + + /// Send a contact request like [`Sdk::send_contact_request`], building and submitting + /// the document as the `contactRequest` type of `prepared`, the snapshot the caller + /// chose `input`'s signing key by. + pub async fn submit_contact_request, F, Fut, G, Gut, H, Hut>( + &self, + prepared: PreparedContactRequest, + input: SendContactRequestInput, + ecdh_provider: EcdhProvider, + get_extended_public_key: H, + ) -> Result where F: FnOnce(&IdentityPublicKey, u32) -> Fut, Fut: std::future::Future>, @@ -508,21 +599,14 @@ impl Sdk { // Create the contact request document (handles ECDH encryption internally) let result = self - .create_contact_request( + .build_contact_request( + &prepared, input.contact_request, ecdh_provider, get_extended_public_key, ) .await?; - // Get the DashPay contract for the document type - let dashpay_contract = self.fetch_dashpay_contract().await?; - let contact_request_document_type = dashpay_contract - .document_type_for_name("contactRequest") - .map_err(|_| { - Error::Generic("DashPay contactRequest document type not found".to_string()) - })?; - // Reuse the entropy that derived result.id during creation. Platform // consensus recomputes the document id from this entropy and rejects the // create transition unless it matches result.id, so a freshly generated @@ -554,7 +638,7 @@ impl Sdk { let platform_document = document .put_to_platform_and_wait_for_response( self, - contact_request_document_type.to_owned_document_type(), + prepared.contact_request_document_type, Some(entropy.0), input.identity_public_key, None, // token payment info @@ -786,4 +870,113 @@ mod tests { "Both parties should derive the same shared secret" ); } + + /// The latest DashPay contract with its `contactRequest` type requiring a CRITICAL key, + /// where every shipped DashPay contract requires HIGH: what a network upgrade could store. + fn dashpay_with_critical_contact_requests() -> dpp::data_contract::DataContract { + use dpp::data_contract::serialized_version::DataContractInSerializationFormat; + use dpp::data_contract::DataContract; + use dpp::identity::SecurityLevel; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; + + let platform_version = PlatformVersion::latest(); + let dashpay = load_system_data_contract(SystemDataContract::Dashpay, platform_version) + .expect("the DashPay contract loads"); + let mut format = DataContractInSerializationFormat::try_from_platform_versioned( + dashpay, + platform_version, + ) + .expect("the serialization format") + .into_schema_form(); + format + .document_schemas_mut() + .expect("the schema form") + .get_mut("contactRequest") + .expect("the contactRequest schema") + .set_value( + "signatureSecurityLevelRequirement", + Value::U8(SecurityLevel::CRITICAL as u8), + ) + .expect("the schema is a map"); + DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) + .expect("a valid contract") + } + + /// A context provider that knows no contract, so every contract is fetched from Platform. + struct NoKnownContracts; + + impl dash_context_provider::ContextProvider for NoKnownContracts { + fn get_data_contract( + &self, + _id: &Identifier, + _platform_version: &dpp::version::PlatformVersion, + ) -> Result>, dash_context_provider::ContextProviderError> + { + Ok(None) + } + + fn get_token_configuration( + &self, + _token_id: &Identifier, + ) -> Result< + Option, + dash_context_provider::ContextProviderError, + > { + Ok(None) + } + + fn get_quorum_public_key( + &self, + _quorum_type: u32, + _quorum_hash: [u8; 32], + _core_chain_locked_height: u32, + ) -> Result<[u8; 48], dash_context_provider::ContextProviderError> { + Err(dash_context_provider::ContextProviderError::InvalidQuorum( + "no quorum in this test".to_string(), + )) + } + + fn get_platform_activation_height( + &self, + ) -> Result + { + Ok(1) + } + } + + #[tokio::test] + async fn should_prepare_the_signing_requirement_from_the_dashpay_contract_it_builds_against() { + use dpp::identity::SecurityLevel; + use dpp::version::PlatformVersion; + + let mut sdk = crate::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .with_context_provider(NoKnownContracts) + .build() + .expect("the mock SDK builds"); + let stored = dashpay_with_critical_contact_requests(); + sdk.mock() + .expect_fetch(stored.id(), Some(stored.clone())) + .await + .expect("the DashPay fetch is expected"); + + let prepared = sdk + .prepare_contact_request() + .await + .expect("the contact request is prepared"); + + assert_eq!( + prepared.signing_security_level_requirement(), + SecurityLevel::CRITICAL, + "the key is judged by the contract the document is built against" + ); + assert_eq!( + prepared + .contact_request_document_type() + .security_level_requirement(), + SecurityLevel::CRITICAL + ); + assert_eq!(prepared.dashpay_contract_id(), stored.id()); + } } diff --git a/packages/rs-sdk/src/platform/dashpay/mod.rs b/packages/rs-sdk/src/platform/dashpay/mod.rs index 3789065cd31..23538a1ce7b 100644 --- a/packages/rs-sdk/src/platform/dashpay/mod.rs +++ b/packages/rs-sdk/src/platform/dashpay/mod.rs @@ -12,7 +12,8 @@ mod profile; pub use contact_request::{ recipient_key_purpose_is_acceptable_on_receive, recipient_key_purpose_is_valid, sender_key_purpose_is_acceptable_on_receive, ContactRequestInput, ContactRequestResult, - EcdhProvider, RecipientIdentity, SendContactRequestInput, SendContactRequestResult, + EcdhProvider, PreparedContactRequest, RecipientIdentity, SendContactRequestInput, + SendContactRequestResult, }; pub use contact_request_queries::ContactRequestDocuments; pub use invitation::{ From d098bdb52b67aad2afd3b8d49eb22c72d18e29af Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 13:56:30 +0000 Subject: [PATCH 45/53] revert(platform-wallet): leave the profile and contactInfo key-type lists to #5546 Restore the key-type lists the profile and contactInfo writers pass to key selection as they were before 1e4f3d2059. Widening contactInfo to ECDSA_HASH160 is the subject of #5546; changing the same lines here only enlarges the conflict between the two. Pointing both writers at WALLET_SIGNING_KEY_TYPES is left until both PRs have merged. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/contact_info.rs | 4 ++-- .../rs-platform-wallet/src/wallet/identity/network/profile.rs | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_info.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_info.rs index 4b64e8eda06..851b94291ef 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_info.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_info.rs @@ -18,7 +18,7 @@ use dpp::document::{Document, DocumentV0}; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::signer::Signer; -use dpp::identity::{IdentityPublicKey, SecurityLevel}; +use dpp::identity::{IdentityPublicKey, KeyType, SecurityLevel}; use dpp::platform_value::Value; use dpp::prelude::Identifier; @@ -603,7 +603,7 @@ impl DashPayView<'_, B> { dashpay_contract.id(), "contactInfo", &[SecurityLevel::HIGH, SecurityLevel::CRITICAL], - &super::WALLET_SIGNING_KEY_TYPES, + &[KeyType::ECDSA_SECP256K1], )? .cloned() .ok_or_else(|| { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs index 160f92df4fd..14e82b28e91 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/profile.rs @@ -9,6 +9,7 @@ use dpp::identity::accessors::IdentityGettersV0; #[cfg(test)] use dpp::identity::identity_public_key::Purpose; use dpp::identity::signer::Signer; +use dpp::identity::KeyType; use dpp::identity::SecurityLevel; use dpp::identity::{Identity, IdentityPublicKey}; use dpp::platform_value::Value; @@ -40,7 +41,7 @@ fn profile_signing_key<'a>( dashpay_contract_id, "profile", &[SecurityLevel::HIGH, SecurityLevel::CRITICAL], - &super::WALLET_SIGNING_KEY_TYPES, + &[KeyType::ECDSA_SECP256K1, KeyType::ECDSA_HASH160], ) } @@ -584,7 +585,6 @@ mod tests { use std::collections::BTreeMap; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; - use dpp::identity::KeyType; use dpp::version::PlatformVersion; fn profile_key(key_type: KeyType, security_level: SecurityLevel) -> IdentityPublicKeyV0 { From 44f2e4008e297658791e18618ce3fb62c83517f7 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:04:18 +0000 Subject: [PATCH 46/53] test(platform-wallet): pin the DIP-11-first order of automatic credit-key selection Automatic TRANSFER/OWNER key selection follows `usable_signing_key`, so a DIP-11 key type (ECDSA_SECP256K1, BLS12_381) signs before an ECDSA_HASH160 key of the same purpose, then the lowest key id. Document it on `credit_signing_key` and pin it: CRITICAL TRANSFER keys {3 HASH160, 4 SECP} pick 4, and a HASH160-only identity still picks its HASH160 key. The masternode OWNER/TRANSFER selectors match a key by its hash and only pass it to `credit_signing_key` as an explicit key, so they are unaffected. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/signing_key.rs | 40 ++++++++++++++++++- 1 file changed, 39 insertions(+), 1 deletion(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index e22125b3ac8..6e431977e8a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs @@ -99,7 +99,10 @@ const CREDIT_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; /// OWNER key when `allow_owner`, which only a withdrawal to the identity's payout address sets. /// An explicit key is never substituted; it is checked by the rules automatic selection /// applies, and refused with Platform's typed error. Automatic withdrawals exhaust TRANSFER -/// keys before OWNER. +/// keys before OWNER. Among keys of one purpose the automatic choice follows +/// [`usable_signing_key`]: a key of a type DIP-11 defines (`ECDSA_SECP256K1`, `BLS12_381`) +/// before an `ECDSA_HASH160` one, then the lowest key id; an identity holding only HASH160 +/// keys still signs with one. pub(crate) fn credit_signing_key<'a>( identity: &'a Identity, explicit: Option<&'a IdentityPublicKey>, @@ -378,6 +381,41 @@ pub(super) mod tests { ); } + #[test] + fn should_prefer_a_dip11_transfer_key_over_a_hash160_one() { + let transfer_key = |id: u32, key_type: KeyType| -> IdentityPublicKey { + IdentityPublicKeyV0 { + id, + purpose: Purpose::TRANSFER, + security_level: SecurityLevel::CRITICAL, + key_type, + data: vec![id as u8; key_type.default_size()].into(), + ..Default::default() + } + .into() + }; + let mut regular = Identity::default_versioned(PlatformVersion::latest()).unwrap(); + regular.add_public_key(transfer_key(3, KeyType::ECDSA_HASH160)); + regular.add_public_key(transfer_key(4, KeyType::ECDSA_SECP256K1)); + assert_eq!( + credit_signing_key(®ular, None, &available(&[3, 4]), false) + .unwrap() + .id(), + 4, + "the raw public key DIP-11 defines signs before the lower-id HASH160 key" + ); + + let mut hash160_only = Identity::default_versioned(PlatformVersion::latest()).unwrap(); + hash160_only.add_public_key(transfer_key(3, KeyType::ECDSA_HASH160)); + assert_eq!( + credit_signing_key(&hash160_only, None, &available(&[3]), false) + .unwrap() + .id(), + 3, + "an identity holding only HASH160 keys still signs with one" + ); + } + #[test] fn should_skip_disabled_transfer_keys_before_owner_fallback() { let mut identity = identity( From 155f8f1667fb66a4bf213268a7d2e23cc1af2de5 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 14:14:39 +0000 Subject: [PATCH 47/53] fix(sdk): prepare contact requests against the DashPay contract the network stores `Sdk::prepare_contact_request` took the DashPay contract from the context provider when it held one, which can be the bundled contract at a stale protocol version: the wallet and the SDK agreed on the key, but Platform could still refuse it after an upgrade raised `contactRequest`'s level. It now refreshes the protocol version and takes the proved current contract the way DPNS registration does, and registers it with the context provider so the confirmation decodes under it. - The DPNS-only "proved at the parsed version" helper moves to `platform::system_data_contract` as `Sdk::fetch_current_system_data_contract`, shared by DPNS and DashPay. - `PreparedContactRequest` holds only the `contactRequest` document type; the contract id comes from it. - platform-wallet's `contact_request_signing_key` reads the level from the document type it is given instead of taking it separately. - The rs-sdk tests share one fixture that raises a document type's `signatureSecurityLevelRequirement`. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/contact_requests.rs | 23 ++-- packages/rs-sdk/src/platform.rs | 2 +- .../src/platform/dashpay/contact_request.rs | 130 ++++++++++-------- .../rs-sdk/src/platform/dpns_usernames/mod.rs | 103 ++++---------- .../src/platform/system_data_contract.rs | 95 +++++++++++++ 5 files changed, 204 insertions(+), 149 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index 5ef13cb1cc9..84b48d6a934 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs @@ -2,6 +2,7 @@ use super::document::document_signing_key; use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; +use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dpp::data_contract::document_type::DocumentTypeRef; use dpp::document::DocumentV0Getters; use dpp::identity::accessors::IdentityGettersV0; @@ -621,18 +622,18 @@ impl DashPayView<'_, B> { // SDK builds the request against: one snapshot decides both the // key and the document it signs. let prepared = self.sdk.prepare_contact_request().await?; - let requirement = prepared.signing_security_level_requirement(); let identity_public_key = contact_request_signing_key( &sender_identity, signer, prepared.contact_request_document_type(), - requirement, )? .cloned() .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { identity_id: *sender_identity_id, purpose: Purpose::AUTHENTICATION, - security_levels: SecurityLevel::accepted_for_requirement(requirement), + security_levels: SecurityLevel::accepted_for_requirement( + prepared.signing_security_level_requirement(), + ), key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), transition: "a contactRequest document transition".to_string(), })?; @@ -1233,7 +1234,7 @@ fn select_recipient_key_index(recipient_identity: &Identity) -> Result( identity: &'a Identity, signer: &impl Signer, contact_request: DocumentTypeRef<'_>, - requirement: SecurityLevel, ) -> Result, dash_sdk::Error> { document_signing_key( identity, signer, - requirement, + contact_request.security_level_requirement(), SigningScope::DocumentCreate { document_type: contact_request, }, @@ -6653,14 +6653,9 @@ mod contact_request_key_tests { .document_type_for_name("contactRequest") .expect("the contactRequest type"); let pick = |identity: &Identity| { - contact_request_signing_key( - identity, - &KeyFilter(|_| true), - contact_request, - SecurityLevel::HIGH, - ) - .unwrap() - .map(|key| key.id()) + contact_request_signing_key(identity, &KeyFilter(|_| true), contact_request) + .unwrap() + .map(|key| key.id()) }; assert_eq!( pick(&identity(vec![ diff --git a/packages/rs-sdk/src/platform.rs b/packages/rs-sdk/src/platform.rs index 3090558060a..cf00fc947b1 100644 --- a/packages/rs-sdk/src/platform.rs +++ b/packages/rs-sdk/src/platform.rs @@ -29,7 +29,7 @@ pub mod query; pub mod query_settings; #[cfg(feature = "shielded")] pub mod shielded; -mod system_data_contract; +pub(crate) mod system_data_contract; pub mod tokens; pub mod transition; pub mod trunk_branch_sync; diff --git a/packages/rs-sdk/src/platform/dashpay/contact_request.rs b/packages/rs-sdk/src/platform/dashpay/contact_request.rs index 63ef6731550..841ce33a088 100644 --- a/packages/rs-sdk/src/platform/dashpay/contact_request.rs +++ b/packages/rs-sdk/src/platform/dashpay/contact_request.rs @@ -5,10 +5,10 @@ use crate::platform::transition::put_document::PutDocument; use crate::platform::Document; use crate::{Error, Sdk}; +use dash_context_provider::ContextProvider; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dpp::data_contract::document_type::{DocumentType, DocumentTypeRef}; -use dpp::data_contract::DataContract; use dpp::document::DocumentV0; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -29,14 +29,13 @@ use std::sync::Arc; /// The DashPay document type a contact request writes. const CONTACT_REQUEST_DOCUMENT_TYPE: &str = "contactRequest"; -/// A contact request prepared by [`Sdk::prepare_contact_request`]: the DashPay contract the -/// request document is built against, and what that same contract requires of the key that -/// signs it. A caller choosing the key reads it here, then sends through -/// [`Sdk::submit_contact_request`], so the key is judged by the contract the document is -/// built against and never by another snapshot of it. +/// A contact request prepared by [`Sdk::prepare_contact_request`]: the `contactRequest` +/// document type of the DashPay contract the network stores now, which the request document is +/// built as and whose rules the key that signs it must meet. A caller choosing the key reads +/// them here, then sends through [`Sdk::submit_contact_request`], so the key is judged by the +/// contract the document is built against and never by another snapshot of it. #[derive(Debug, Clone)] pub struct PreparedContactRequest { - dashpay_contract: Arc, contact_request_document_type: DocumentType, } @@ -56,7 +55,9 @@ impl PreparedContactRequest { /// The id of the DashPay contract the request writes to. pub fn dashpay_contract_id(&self) -> Identifier { - self.dashpay_contract.id() + self.contact_request_document_type + .as_ref() + .data_contract_id() } } @@ -308,19 +309,29 @@ impl Sdk { .await } - /// Prepare a contact request: fetch the DashPay contract (from the context provider when - /// it holds one) and resolve its `contactRequest` document type. Nothing is built, signed - /// or submitted. The returned [`PreparedContactRequest`] tells what that contract requires - /// of the signing key; send it with [`Sdk::submit_contact_request`]. + /// Prepare a contact request: learn the network's protocol version, fetch the DashPay + /// contract the network stores now, proved at the version the SDK parsed it under + /// ([`Sdk::fetch_current_system_data_contract`]), and resolve its `contactRequest` document + /// type. A contract the context provider holds can be older than the network's, and the + /// level it requires of the signing key one Platform no longer accepts. Nothing is built, + /// signed or submitted. The returned [`PreparedContactRequest`] tells what that contract + /// requires of the signing key; send it with [`Sdk::submit_contact_request`]. pub async fn prepare_contact_request(&self) -> Result { - let dashpay_contract = self.fetch_dashpay_contract().await?; + let dashpay_contract = self + .fetch_current_system_data_contract(self.get_dashpay_contract_id()?, "DashPay") + .await?; let contact_request_document_type = dashpay_contract .document_type_cloned_for_name(CONTACT_REQUEST_DOCUMENT_TYPE) .map_err(|_| { Error::Generic("DashPay contactRequest document type not found".to_string()) })?; + // The confirmation of the document is a proof the SDK decodes under the DashPay + // contract its context provider resolves: give it the contract the document is built + // against, so it decodes under it + if let Some(provider) = self.context_provider() { + provider.register_data_contract(Arc::new(dashpay_contract)); + } Ok(PreparedContactRequest { - dashpay_contract, contact_request_document_type, }) } @@ -659,6 +670,7 @@ impl Sdk { #[cfg(test)] mod tests { use super::*; + use dpp::data_contract::DataContract; use dpp::secp256k1; use dpp::secp256k1::rand::{self, RngCore}; @@ -871,49 +883,34 @@ mod tests { ); } - /// The latest DashPay contract with its `contactRequest` type requiring a CRITICAL key, - /// where every shipped DashPay contract requires HIGH: what a network upgrade could store. - fn dashpay_with_critical_contact_requests() -> dpp::data_contract::DataContract { - use dpp::data_contract::serialized_version::DataContractInSerializationFormat; - use dpp::data_contract::DataContract; - use dpp::identity::SecurityLevel; - use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; - use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; - - let platform_version = PlatformVersion::latest(); - let dashpay = load_system_data_contract(SystemDataContract::Dashpay, platform_version) - .expect("the DashPay contract loads"); - let mut format = DataContractInSerializationFormat::try_from_platform_versioned( - dashpay, - platform_version, - ) - .expect("the serialization format") - .into_schema_form(); - format - .document_schemas_mut() - .expect("the schema form") - .get_mut("contactRequest") - .expect("the contactRequest schema") - .set_value( - "signatureSecurityLevelRequirement", - Value::U8(SecurityLevel::CRITICAL as u8), - ) - .expect("the schema is a map"); - DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) - .expect("a valid contract") + /// A context provider that holds the DashPay contract the SDK bundles for the latest + /// protocol version until a contract is registered with it, which then takes its place. + /// Its clones share what was registered. + #[derive(Clone, Default)] + struct BundledDashPayProvider { + registered: Arc>>>, } - /// A context provider that knows no contract, so every contract is fetched from Platform. - struct NoKnownContracts; - - impl dash_context_provider::ContextProvider for NoKnownContracts { + impl dash_context_provider::ContextProvider for BundledDashPayProvider { fn get_data_contract( &self, _id: &Identifier, _platform_version: &dpp::version::PlatformVersion, ) -> Result>, dash_context_provider::ContextProviderError> { - Ok(None) + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + + if let Some(contract) = self.registered.lock().expect("the lock").clone() { + return Ok(Some(contract)); + } + load_system_data_contract( + SystemDataContract::Dashpay, + dpp::version::PlatformVersion::latest(), + ) + .map(|contract| Some(Arc::new(contract))) + .map_err(|error| { + dash_context_provider::ContextProviderError::Generic(error.to_string()) + }) } fn get_token_configuration( @@ -943,19 +940,34 @@ mod tests { { Ok(1) } + + fn register_data_contract(&self, contract: Arc) { + *self.registered.lock().expect("the lock") = Some(contract); + } } #[tokio::test] - async fn should_prepare_the_signing_requirement_from_the_dashpay_contract_it_builds_against() { + async fn should_prepare_the_signing_requirement_from_the_dashpay_contract_the_network_stores() { + use crate::platform::system_data_contract::tests::with_document_security_level; + use dash_context_provider::ContextProvider; use dpp::identity::SecurityLevel; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; use dpp::version::PlatformVersion; + // The context provider holds the bundled DashPay contract, which requires HIGH; the + // network stores one whose `contactRequest` requires CRITICAL + let provider = BundledDashPayProvider::default(); let mut sdk = crate::SdkBuilder::new_mock() .with_version(PlatformVersion::latest()) - .with_context_provider(NoKnownContracts) + .with_context_provider(provider.clone()) .build() .expect("the mock SDK builds"); - let stored = dashpay_with_critical_contact_requests(); + let stored = with_document_security_level( + load_system_data_contract(SystemDataContract::Dashpay, PlatformVersion::latest()) + .expect("the DashPay contract loads"), + "contactRequest", + SecurityLevel::CRITICAL, + ); sdk.mock() .expect_fetch(stored.id(), Some(stored.clone())) .await @@ -969,14 +981,20 @@ mod tests { assert_eq!( prepared.signing_security_level_requirement(), SecurityLevel::CRITICAL, - "the key is judged by the contract the document is built against" + "the key is judged by the contract the network stores, not the provider's" ); + assert_eq!(prepared.dashpay_contract_id(), stored.id()); + // The document's confirmation decodes under the contract it was built against + let resolved = provider + .get_data_contract(&stored.id(), PlatformVersion::latest()) + .expect("the provider answers") + .expect("the provider holds DashPay"); assert_eq!( - prepared - .contact_request_document_type() + resolved + .document_type_for_name("contactRequest") + .expect("the contactRequest type") .security_level_requirement(), SecurityLevel::CRITICAL ); - assert_eq!(prepared.dashpay_contract_id(), stored.id()); } } diff --git a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs index 779dd73e37a..8414826769e 100644 --- a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs +++ b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs @@ -11,7 +11,7 @@ use crate::platform::documents::document_query::DocumentQuery; use crate::platform::documents::transitions::DocumentDeleteTransitionBuilder; use crate::platform::transition::put_document::PutDocument; use crate::platform::transition::put_settings::PutSettings; -use crate::platform::{DataContract, Document, Fetch, FetchMany}; +use crate::platform::{DataContract, Document, FetchMany}; use crate::{Error, Sdk}; use dapi_grpc::platform::v0::ResponseMetadata; use dash_context_provider::ContextProvider; @@ -30,7 +30,6 @@ use dpp::secp256k1::rand::{Rng, SeedableRng}; use dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions; use drive::query::{SelectProjection, WhereClause, WhereOperator}; use std::collections::BTreeMap; -use std::future::Future; use std::sync::Arc; use tracing::debug; use tracing::warn; @@ -286,45 +285,6 @@ fn registration_signing_requirement( } } -/// How many DPNS contract responses a registration reads for one proved at the protocol -/// version the SDK parsed it under. -const DPNS_CONTRACT_FETCH_ATTEMPTS: usize = 3; - -/// The DPNS contract of the first response proved at the protocol version the SDK parsed it -/// under, reading the SDK's version through `sdk_version` and each response through `fetch`, -/// at most [`DPNS_CONTRACT_FETCH_ATTEMPTS`] times. The SDK's version only rises, and SDK clones -/// share it, so a version unchanged across the fetch is the one the response was parsed under; -/// one that rose meanwhile (this response, or another request, taught the SDK a newer version) -/// leaves the response unused. A response proved at a newer version was parsed under an older -/// one, which can drop the declaration the preorder hash follows. One proved at an older -/// version comes from a node behind the network, which can still hold the contract an upgrade -/// replaced. Either would commit the preorder to a hash the domain cannot reveal. -async fn dpns_contract_proved_at_parsed_version( - sdk_version: V, - mut fetch: F, -) -> Result -where - V: Fn() -> u32, - F: FnMut() -> R, - R: Future, ResponseMetadata), Error>>, -{ - let mut last_mismatch = None; - for _ in 0..DPNS_CONTRACT_FETCH_ATTEMPTS { - let parsed_under = sdk_version(); - let (dpns_contract, metadata) = fetch().await?; - if metadata.protocol_version == parsed_under && sdk_version() == parsed_under { - return dpns_contract - .ok_or_else(|| Error::Generic("DPNS contract not found".to_string())); - } - last_mismatch = Some((metadata.protocol_version, parsed_under)); - } - let (proved_at, parsed_under) = last_mismatch.unwrap_or_default(); - Err(Error::Generic(format!( - "no DPNS contract response was proved at the protocol version the SDK parsed it under \ - (last proved at {proved_at}, parsed under {parsed_under})" - ))) -} - impl Sdk { /// Helper method to get the DPNS contract ID fn get_dpns_contract_id(&self) -> Result { @@ -360,17 +320,14 @@ impl Sdk { /// The preorder commits to the hash that contract declares, so neither a contract the /// context provider holds for the SDK's protocol version nor one cached before an upgrade /// changed it will do: either can be older than the network's, and its hash one the - /// domain cannot reveal. The SDK first learns the network's protocol version (a proven - /// refresh), then takes a response proved at the version it parsed it under - /// ([`dpns_contract_proved_at_parsed_version`]). + /// domain cannot reveal. A response parsed under another protocol version than the one it + /// was proved at can drop the declaration the preorder hash follows, and one from a node + /// behind the network can still hold the contract an upgrade replaced + /// ([`Sdk::fetch_current_system_data_contract`]). async fn fetch_current_dpns_contract(&self) -> Result { let dpns_contract_id = self.get_dpns_contract_id()?; - self.refresh_protocol_version().await?; - dpns_contract_proved_at_parsed_version( - || self.protocol_version_number(), - || DataContract::fetch_with_metadata(self, dpns_contract_id, None), - ) - .await + self.fetch_current_system_data_contract(dpns_contract_id, "DPNS") + .await } /// The documents a registration of `label` by `identity_id` submits, built against the @@ -887,6 +844,9 @@ fn identity_from_domain_records( #[cfg(test)] mod tests { use super::*; + use crate::platform::system_data_contract::{ + contract_proved_at_parsed_version, SYSTEM_CONTRACT_FETCH_ATTEMPTS, + }; use crate::query_types::Documents; use crate::sdk::test::expect_epoch_refresh; use crate::SdkBuilder; @@ -1184,29 +1144,12 @@ mod tests { /// The latest DPNS contract with its `domain` document type requiring a CRITICAL key, /// where every shipped DPNS contract requires HIGH: what a network upgrade could store. fn dpns_with_critical_domain() -> DataContract { - use dpp::data_contract::serialized_version::DataContractInSerializationFormat; - use dpp::identity::SecurityLevel; - use dpp::version::TryFromPlatformVersioned; - - let platform_version = PlatformVersion::latest(); - let dpns = load_system_data_contract(SystemDataContract::DPNS, platform_version) - .expect("the DPNS contract loads"); - let mut format = - DataContractInSerializationFormat::try_from_platform_versioned(dpns, platform_version) - .expect("the serialization format") - .into_schema_form(); - format - .document_schemas_mut() - .expect("the schema form") - .get_mut("domain") - .expect("the domain schema") - .set_value( - "signatureSecurityLevelRequirement", - Value::U8(SecurityLevel::CRITICAL as u8), - ) - .expect("the schema is a map"); - DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) - .expect("a valid contract") + crate::platform::system_data_contract::tests::with_document_security_level( + load_system_data_contract(SystemDataContract::DPNS, PlatformVersion::latest()) + .expect("the DPNS contract loads"), + "domain", + dpp::identity::SecurityLevel::CRITICAL, + ) } #[test] @@ -1650,7 +1593,8 @@ mod tests { // version, so the next one is parsed under it. let sdk_version = Cell::new(13); let fetches = Cell::new(0); - let dpns_contract = dpns_contract_proved_at_parsed_version( + let dpns_contract = contract_proved_at_parsed_version( + "DPNS", || sdk_version.get(), || { fetches.set(fetches.get() + 1); @@ -1679,7 +1623,8 @@ mod tests { (PlatformVersion::latest(), LATEST_VERSION), (PlatformVersion::get(13).expect("protocol version 13"), 13), ]); - let dpns_contract = dpns_contract_proved_at_parsed_version( + let dpns_contract = contract_proved_at_parsed_version( + "DPNS", || LATEST_VERSION, || { let (stored_at, proved) = responses @@ -1705,7 +1650,8 @@ mod tests { // SDK has learned since. let sdk_version = Cell::new(13); let fetches = Cell::new(0); - let dpns_contract = dpns_contract_proved_at_parsed_version( + let dpns_contract = contract_proved_at_parsed_version( + "DPNS", || sdk_version.get(), || { fetches.set(fetches.get() + 1); @@ -1732,7 +1678,8 @@ mod tests { #[tokio::test] async fn should_refuse_when_every_dpns_contract_response_is_behind_the_network() { let fetches = Cell::new(0); - let result = dpns_contract_proved_at_parsed_version( + let result = contract_proved_at_parsed_version( + "DPNS", || LATEST_VERSION, || { fetches.set(fetches.get() + 1); @@ -1744,7 +1691,7 @@ mod tests { .await; assert!(result.is_err()); - assert_eq!(fetches.get(), DPNS_CONTRACT_FETCH_ATTEMPTS); + assert_eq!(fetches.get(), SYSTEM_CONTRACT_FETCH_ATTEMPTS); } #[test] diff --git a/packages/rs-sdk/src/platform/system_data_contract.rs b/packages/rs-sdk/src/platform/system_data_contract.rs index 66953140548..dc29bdd7446 100644 --- a/packages/rs-sdk/src/platform/system_data_contract.rs +++ b/packages/rs-sdk/src/platform/system_data_contract.rs @@ -3,9 +3,50 @@ use crate::platform::{DataContract, Fetch, Identifier}; use crate::{Error, Sdk}; +use dapi_grpc::platform::v0::ResponseMetadata; use dash_context_provider::ContextProvider; +use std::future::Future; use std::sync::Arc; +/// How many responses [`Sdk::fetch_current_system_data_contract`] reads for one proved at the +/// protocol version the SDK parsed it under. +pub(crate) const SYSTEM_CONTRACT_FETCH_ATTEMPTS: usize = 3; + +/// The `name` contract of the first response proved at the protocol version the SDK parsed it +/// under, reading the SDK's version through `sdk_version` and each response through `fetch`, +/// at most [`SYSTEM_CONTRACT_FETCH_ATTEMPTS`] times. The SDK's version only rises, and SDK +/// clones share it, so a version unchanged across the fetch is the one the response was parsed +/// under; one that rose meanwhile (this response, or another request, taught the SDK a newer +/// version) leaves the response unused. A response proved at a newer version was parsed under +/// an older one, which can drop declarations the newer contract makes. One proved at an older +/// version comes from a node behind the network, which can still hold the contract an upgrade +/// replaced. +pub(crate) async fn contract_proved_at_parsed_version( + name: &str, + sdk_version: V, + mut fetch: F, +) -> Result +where + V: Fn() -> u32, + F: FnMut() -> R, + R: Future, ResponseMetadata), Error>>, +{ + let mut last_mismatch = None; + for _ in 0..SYSTEM_CONTRACT_FETCH_ATTEMPTS { + let parsed_under = sdk_version(); + let (contract, metadata) = fetch().await?; + if metadata.protocol_version == parsed_under && sdk_version() == parsed_under { + return contract.ok_or_else(|| Error::Generic(format!("{name} contract not found"))); + } + last_mismatch = Some((metadata.protocol_version, parsed_under)); + } + let (proved_at, parsed_under) = last_mismatch.unwrap_or_default(); + Err(Error::Generic(format!( + "no {name} contract response was proved at the protocol version the SDK parsed it \ + under (last proved at {proved_at}, parsed under {parsed_under})" + ))) +} + impl Sdk { /// The system data contract `contract_id`, from the context provider when it holds it at /// the SDK's protocol version, fetched and proved otherwise. `None` when the network has no @@ -21,4 +62,58 @@ impl Sdk { } Ok(DataContract::fetch(self, contract_id).await?.map(Arc::new)) } + + /// The system data contract `contract_id` (named `name` in errors) the network stores now, + /// fetched and proved, for a transition whose rules come from it. Neither a contract the + /// context provider holds for the SDK's protocol version nor one cached before an upgrade + /// will do: either can be older than the network's. The SDK first learns the network's + /// protocol version (a proven refresh), then takes a response proved at the version it + /// parsed it under ([`contract_proved_at_parsed_version`]). + pub(crate) async fn fetch_current_system_data_contract( + &self, + contract_id: Identifier, + name: &str, + ) -> Result { + self.refresh_protocol_version().await?; + contract_proved_at_parsed_version( + name, + || self.protocol_version_number(), + || DataContract::fetch_with_metadata(self, contract_id, None), + ) + .await + } +} + +#[cfg(test)] +pub(crate) mod tests { + use crate::platform::DataContract; + use dpp::data_contract::serialized_version::DataContractInSerializationFormat; + use dpp::identity::SecurityLevel; + use dpp::platform_value::Value; + use dpp::version::{PlatformVersion, TryFromPlatformVersioned}; + + /// `contract` with its `document_type_name` type requiring a `level` key to sign: a contract + /// an upgrade could store in place of the one the SDK bundles. + pub(crate) fn with_document_security_level( + contract: DataContract, + document_type_name: &str, + level: SecurityLevel, + ) -> DataContract { + let platform_version = PlatformVersion::latest(); + let mut format = DataContractInSerializationFormat::try_from_platform_versioned( + contract, + platform_version, + ) + .expect("the serialization format") + .into_schema_form(); + format + .document_schemas_mut() + .expect("the schema form") + .get_mut(document_type_name) + .expect("the document type's schema") + .set_value("signatureSecurityLevelRequirement", Value::U8(level as u8)) + .expect("the schema is a map"); + DataContract::try_from_platform_versioned(format, true, &mut vec![], platform_version) + .expect("a valid contract") + } } From 51f35ad4b81b30e79cf3b0d26727f923495732ab Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:39:16 +0000 Subject: [PATCH 48/53] fix(platform-wallet): let automatic selection sign a lone token transfer or claim with a TRANSFER key Consensus (BatchTransitionV1::purpose_requirement) accepts a CRITICAL TRANSFER key for a batch holding exactly one token transfer or claim, and the explicit-key checks already allowed it. Automatic selection still looked at AUTHENTICATION keys only, so an identity whose only CRITICAL key was a TRANSFER key got NoUsableSigningKey from token_transfer_with_external_signer and token_claim_with_external_signer. token_resolve_signing_key now takes the operation's allowed purposes and tries them in order: AUTHENTICATION first, so existing identities keep signing with the key they always used, then TRANSFER. Every other token operation still passes AUTHENTICATION only. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/tokens/burn.rs | 8 +- .../wallet/identity/network/tokens/claim.rs | 8 +- .../network/tokens/destroy_frozen_funds.rs | 8 +- .../wallet/identity/network/tokens/freeze.rs | 8 +- .../wallet/identity/network/tokens/helpers.rs | 249 +++++++++++++++--- .../wallet/identity/network/tokens/mint.rs | 8 +- .../wallet/identity/network/tokens/pause.rs | 8 +- .../identity/network/tokens/purchase.rs | 8 +- .../wallet/identity/network/tokens/resume.rs | 8 +- .../identity/network/tokens/set_price.rs | 8 +- .../identity/network/tokens/transfer.rs | 8 +- .../identity/network/tokens/unfreeze.rs | 8 +- .../identity/network/tokens/update_config.rs | 8 +- 13 files changed, 302 insertions(+), 43 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs index 4f64f98a63f..4cf29197e6f 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs @@ -73,7 +73,13 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_burn_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs index 3792441fded..5f434290058 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs @@ -70,7 +70,13 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + ) .await?; self.token_claim_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs index af1214f3741..5bd2bff7f9b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs @@ -83,7 +83,13 @@ impl IdentityWallet { > { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_destroy_frozen_funds_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs index 8e8821cacf3..13f4fc25f30 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs @@ -76,7 +76,13 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_freeze_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 9d485176aa1..0544c2a6310 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -1,9 +1,8 @@ //! Shared lookups for token state-transition methods on //! [`IdentityWallet`]. All token actions need to (a) fetch the data -//! contract by id and (b) resolve the canonical AUTHENTICATION / -//! CRITICAL / ECDSA signing key on the actor identity, -//! so those steps live here rather than being copy-pasted across each -//! action file. +//! contract by id and (b) resolve the CRITICAL signing key on the actor +//! identity, so those steps live here rather than being copy-pasted +//! across each action file. //! //! `CRITICAL` is non-negotiable: rs-dpp's //! `combined_security_level_requirement` collapses the allowed key @@ -33,24 +32,43 @@ use crate::wallet::identity::network::IdentityWallet; const TOKEN_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; /// The key that signs an operation on the token at `position` of `token_contract_id`: a -/// CRITICAL AUTHENTICATION ECDSA key whose bounds cover that token. +/// CRITICAL key of one of [`WALLET_SIGNING_KEY_TYPES`] with one of `purposes`, whose bounds +/// cover that token. `purposes` is [`TOKEN_SIGNING_PURPOSES`], or +/// [`LONE_TOKEN_TRANSFER_SIGNING_PURPOSES`] for a lone transfer or claim. Purposes are tried +/// in the order given, so an identity keeps signing with the AUTHENTICATION key it always has +/// and a TRANSFER key signs only when no AUTHENTICATION key qualifies or the signer reaches +/// none; within one purpose the order is [`usable_signing_key`]'s. +/// +/// `Ok(None)` means no key of any of `purposes` is eligible; `Err` means one is, but the +/// signer reaches none. fn token_signing_key<'a>( identity: &'a Identity, token_contract_id: Identifier, position: TokenContractPosition, signer: &impl Signer, + purposes: &[Purpose], ) -> Result, dash_sdk::Error> { - usable_signing_key( - identity, - signer, - Purpose::AUTHENTICATION, - &TOKEN_SIGNING_LEVELS, - &WALLET_SIGNING_KEY_TYPES, - SigningScope::Token { - contract_id: token_contract_id, - position, - }, - ) + let mut unavailable = None; + for &purpose in purposes { + match usable_signing_key( + identity, + signer, + purpose, + &TOKEN_SIGNING_LEVELS, + &WALLET_SIGNING_KEY_TYPES, + SigningScope::Token { + contract_id: token_contract_id, + position, + }, + ) { + Ok(Some(key)) => return Ok(Some(key)), + Ok(None) => {} + Err(error) => { + unavailable.get_or_insert(error); + } + } + } + unavailable.map_or(Ok(None), Err) } /// The purposes a key may have to sign a token operation. @@ -87,13 +105,13 @@ pub(super) fn check_token_signing_key( } impl IdentityWallet { - /// Resolve the AUTHENTICATION signing key for token state + /// Resolve the signing key for token state /// transitions — used by the `_with_external_signer` variants /// where the caller brings the `Signer` and we just need to pick /// which on-chain key id to sign with. /// /// Key selection is a fixed canonical policy: - /// `Purpose::AUTHENTICATION` × `SecurityLevel::CRITICAL` × `WALLET_SIGNING_KEY_TYPES`, + /// one of `purposes` × `SecurityLevel::CRITICAL` × `WALLET_SIGNING_KEY_TYPES`, /// bounds covering `token_contract_id` (see `token_signing_key`). /// Callers that pass a `signing_key_id` over FFI are advisory — /// this Rust path is authoritative and Drive validates the chosen @@ -104,6 +122,7 @@ impl IdentityWallet { token_contract_id: Identifier, token_position: TokenContractPosition, signer: &impl Signer, + purposes: &[Purpose], ) -> Result { let wm = self.wallet_manager.read().await; let info = wm @@ -117,15 +136,21 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; drop(wm); - let signing_key = token_signing_key(&identity, token_contract_id, token_position, signer)? - .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { - identity_id: *identity_id, - purpose: Purpose::AUTHENTICATION, - security_levels: TOKEN_SIGNING_LEVELS.to_vec(), - key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), - transition: format!("a token transition of contract {token_contract_id}"), - })? - .clone(); + let signing_key = token_signing_key( + &identity, + token_contract_id, + token_position, + signer, + purposes, + )? + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: TOKEN_SIGNING_LEVELS.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: format!("a token transition of contract {token_contract_id}"), + })? + .clone(); Ok(signing_key) } @@ -178,7 +203,9 @@ mod signing_tests { use dpp::data_contract::associated_token::token_distribution_key::TokenDistributionType; use dpp::data_contracts::SystemDataContract; use dpp::identity::accessors::IdentityGettersV0; - use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; + use dpp::identity::identity_public_key::accessors::v0::{ + IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0, + }; use dpp::identity::identity_public_key::contract_bounds::ContractBounds; use dpp::identity::KeyType; use dpp::system_data_contracts::load_system_data_contract; @@ -389,7 +416,13 @@ mod signing_tests { let wallet = wallet_with_identity(identity).await; let error = wallet .identity() - .token_resolve_signing_key(&identity_id, Identifier::default(), 0, &KeyFilter(|_| true)) + .token_resolve_signing_key( + &identity_id, + Identifier::default(), + 0, + &KeyFilter(|_| true), + &TOKEN_SIGNING_PURPOSES, + ) .await .unwrap_err(); assert_no_usable_key(error, identity_id, SecurityLevel::CRITICAL); @@ -401,7 +434,13 @@ mod signing_tests { let signer = lock_checking_signer(wallet.identity()); let error = wallet .identity() - .token_resolve_signing_key(&Identifier::default(), Identifier::default(), 0, &signer) + .token_resolve_signing_key( + &Identifier::default(), + Identifier::default(), + 0, + &signer, + &TOKEN_SIGNING_PURPOSES, + ) .await .unwrap_err(); assert!(error.to_string().contains("available to signer"), "{error}"); @@ -426,7 +465,14 @@ mod signing_tests { key(2, SecurityLevel::CRITICAL).with_limits(Some(1_000), None), key(3, SecurityLevel::CRITICAL), ]); - let chosen = token_signing_key(&identity, token_contract, 0, &KeyFilter(|_| true)).unwrap(); + let chosen = token_signing_key( + &identity, + token_contract, + 0, + &KeyFilter(|_| true), + &TOKEN_SIGNING_PURPOSES, + ) + .unwrap(); assert_eq!( chosen.map(|key| key.id()), Some(3), @@ -434,4 +480,145 @@ mod signing_tests { is taken before a budgeted one" ); } + #[tokio::test] + async fn should_sign_a_lone_token_transfer_or_claim_with_a_transfer_key_when_no_authentication_key_qualifies( + ) { + let identity = identity_with_keys( + Purpose::TRANSFER, + SecurityLevel::CRITICAL, + KeyType::ECDSA_SECP256K1, + ); + let identity_id = identity.id(); + let wallet = wallet_with_identity(identity).await; + let chosen = wallet + .identity() + .token_resolve_signing_key( + &identity_id, + Identifier::default(), + 0, + &KeyFilter(|_| true), + &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + ) + .await + .expect("consensus takes a CRITICAL TRANSFER key for a lone transfer or claim"); + assert_eq!(chosen.purpose(), Purpose::TRANSFER); + let error = wallet + .identity() + .token_resolve_signing_key( + &identity_id, + Identifier::default(), + 0, + &KeyFilter(|_| true), + &TOKEN_SIGNING_PURPOSES, + ) + .await + .unwrap_err(); + assert_no_usable_key(error, identity_id, SecurityLevel::CRITICAL); + } + + #[test] + fn should_prefer_an_authentication_key_over_a_transfer_key_for_a_lone_token_transfer() { + use crate::wallet::identity::network::key_selection::tests::identity; + + let identity = identity(vec![ + transfer_key(SecurityLevel::CRITICAL), + key(2, SecurityLevel::CRITICAL), + ]); + let pick = |signer: &KeyFilter bool>| { + token_signing_key( + &identity, + Identifier::default(), + 0, + signer, + &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + ) + .map(|key| key.map(|key| key.id())) + }; + assert_eq!( + pick(&KeyFilter(|_| true)).unwrap(), + Some(2), + "the AUTHENTICATION key an identity already signs token operations with goes first" + ); + assert_eq!( + pick(&KeyFilter(|key| key.purpose() == Purpose::TRANSFER)).unwrap(), + Some(1), + "a TRANSFER key signs when the signer cannot reach the AUTHENTICATION key" + ); + } + #[tokio::test] + async fn should_sign_external_signer_token_transfers_and_claims_with_a_lone_transfer_key() { + use crate::wallet::identity::network::signing_key::tests::wallet_with_identity_on; + + let contract = some_contract(); + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .unwrap(); + sdk.mock() + .expect_fetch(contract.id(), Some(contract.as_ref().clone())) + .await + .unwrap(); + let identity = identity_with_keys( + Purpose::TRANSFER, + SecurityLevel::CRITICAL, + KeyType::ECDSA_SECP256K1, + ); + let identity_id = identity.id(); + let wallet = wallet_with_identity_on(sdk, identity).await; + let signer = KeyFilter(|_| true); + let transfer = wallet + .identity() + .token_transfer_with_external_signer( + identity_id, + contract.id(), + 0, + Identifier::from([2; 32]), + 1, + None, + &signer, + ) + .await + .err() + .expect("the mock SDK has no answers"); + assert!( + matches!( + transfer, + PlatformWalletError::TokenOperationFailed { + source: dash_sdk::Error::DapiClientError(_), + .. + } + ), + "the CRITICAL TRANSFER key signs the transfer, so the request goes out: {transfer:?}" + ); + let claim = wallet + .identity() + .token_claim_with_external_signer( + identity_id, + contract.id(), + 0, + TokenDistributionType::Perpetual, + None, + &signer, + ) + .await + .err() + .expect("the mock SDK has no answers"); + assert!( + matches!( + claim, + PlatformWalletError::TokenOperationFailed { + source: dash_sdk::Error::DapiClientError(_), + .. + } + ), + "the CRITICAL TRANSFER key signs the claim, so the request goes out: {claim:?}" + ); + let burn = wallet + .identity() + .token_burn_with_external_signer(identity_id, contract.id(), 0, 1, None, None, &signer) + .await + .err() + .expect("a burn takes no TRANSFER key"); + assert_no_usable_key(burn, identity_id, SecurityLevel::CRITICAL); + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs index 8130c7790a0..5c7328a20f5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs @@ -128,7 +128,13 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_mint_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs index a73c2be28f7..a2e6b7b2999 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs @@ -76,7 +76,13 @@ impl IdentityWallet { { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_pause_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs index 02936e9657b..6655203a34b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs @@ -75,7 +75,13 @@ impl IdentityWallet { { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_purchase_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs index b8ae3d56342..b15d3c80857 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs @@ -75,7 +75,13 @@ impl IdentityWallet { { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_resume_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs index 56fcf074b7a..f28f306cedd 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs @@ -93,7 +93,13 @@ impl IdentityWallet { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; let pricing_schedule = if price_per_token == 0 { diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs index 19de10f558a..03886eab65b 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs @@ -78,7 +78,13 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&from_identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &from_identity_id, + token_contract_id, + token_position, + signer, + &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + ) .await?; self.token_transfer_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs index f1a9f383e53..4585f51610a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs @@ -78,7 +78,13 @@ impl IdentityWallet { ) -> Result { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_unfreeze_with_signer( diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs index aabdd4839eb..e712e23d978 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs @@ -82,7 +82,13 @@ impl IdentityWallet { { let data_contract = self.token_fetch_data_contract(token_contract_id).await?; let signing_key = self - .token_resolve_signing_key(&identity_id, token_contract_id, token_position, signer) + .token_resolve_signing_key( + &identity_id, + token_contract_id, + token_position, + signer, + &TOKEN_SIGNING_PURPOSES, + ) .await?; self.token_update_config_with_signer( From e18ff2f207786272aeea928df0436d8286f04b96 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:42:52 +0000 Subject: [PATCH 49/53] fix(sdk): keep the name and preorder salt out of a prepared DPNS registration's Debug output DpnsNameRegistration derived Debug through its documents, so formatting a prepared registration printed the domain document: the clear label and, before DPNS v3, the preorderSalt its preorder commits to. A log line carrying them before the preorder lands lets anyone race for the name. DpnsNameRegistration now implements Debug by hand and shows only the identity id, the DPNS contract id and the signing-key security level. The private DpnsRegistrationDocuments no longer derives Debug. Co-Authored-By: Claude Opus 5.5 --- .../rs-sdk/src/platform/dpns_usernames/mod.rs | 56 ++++++++++++++++++- 1 file changed, 54 insertions(+), 2 deletions(-) diff --git a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs index 8414826769e..9f9fbfc154e 100644 --- a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs +++ b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs @@ -30,6 +30,7 @@ use dpp::secp256k1::rand::{Rng, SeedableRng}; use dpp::state_transition::batch_transition::methods::StateTransitionCreationOptions; use drive::query::{SelectProjection, WhereClause, WhereOperator}; use std::collections::BTreeMap; +use std::fmt; use std::sync::Arc; use tracing::debug; use tracing::warn; @@ -231,7 +232,6 @@ pub struct RegisterDpnsNameResult { } /// The documents a DPNS registration submits, built against one DPNS contract. -#[derive(Debug)] struct DpnsRegistrationDocuments { /// The DPNS contract the network stores now, which the documents were built against. dpns_contract: DataContract, @@ -250,12 +250,27 @@ struct DpnsRegistrationDocuments { /// key reads its requirement here, then submits through /// [`Sdk::submit_dpns_name_registration`], so the key is judged by the contract the /// documents are built against and never by another snapshot of it. -#[derive(Debug)] pub struct DpnsNameRegistration { identity_id: Identifier, documents: DpnsRegistrationDocuments, } +/// Shows only who registers and what the signing key must meet. The documents stay out: the +/// domain holds the clear name and, before DPNS v3, the salt its preorder commits to, and a +/// log line revealing them before the preorder lands would let anyone race for the name. +impl fmt::Debug for DpnsNameRegistration { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("DpnsNameRegistration") + .field("identity_id", &self.identity_id) + .field("dpns_contract_id", &self.dpns_contract_id()) + .field( + "signing_security_level_requirement", + &self.signing_security_level_requirement(), + ) + .finish_non_exhaustive() + } +} + impl DpnsNameRegistration { /// The security level the one key signing both registration documents must meet: the /// strongest the `preorder` and `domain` document types require. @@ -1201,6 +1216,43 @@ mod tests { assert_eq!(registration.dpns_contract_id(), stored.id()); } + #[tokio::test] + async fn should_keep_the_name_and_preorder_salt_out_of_a_prepared_registrations_debug_output() { + let mut sdk = SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .expect("the mock SDK builds"); + let stored = dpns_v3(); + sdk.mock() + .expect_fetch(stored.id(), Some(stored.clone())) + .await + .expect("the DPNS fetch is expected"); + let identity_id = Identifier::new([1u8; 32]); + let mut registration = sdk + .prepare_dpns_name_registration("Bob", identity_id) + .await + .expect("the registration is prepared"); + // Before DPNS v3 the domain also carries the salt its preorder commits to + const SALT: [u8; 32] = [0xAB; 32]; + registration + .documents + .domain_document + .properties_mut() + .insert("preorderSalt".to_string(), Value::Bytes32(SALT)); + + let shown = format!("{registration:?}"); + + for secret in ["Bob", "b0b", "preorderSalt", "171, 171", "abab"] { + assert!( + !shown.contains(secret), + "a prepared registration must not show {secret:?} before its preorder lands: \ + {shown}" + ); + } + assert!(shown.contains(&format!("{identity_id:?}")), "{shown}"); + assert!(shown.contains("HIGH"), "{shown}"); + } + /// A signer the tests never reach: each registration below stops before it signs. #[derive(Debug)] struct UnusedSigner; From 3d44b9cab315949bc6f8f954583f71852d4bd820 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 15:53:49 +0000 Subject: [PATCH 50/53] fix(platform-wallet): fall back to a TRANSFER token key only when no AUTHENTICATION key qualifies Automatic lone-transfer/claim selection also took a TRANSFER key when the identity held a qualifying CRITICAL AUTHENTICATION key the signer could not reach, which turned the signer-unavailable error such an identity always got into a signature by another key. A purpose is now tried only when no key of the earlier ones qualifies, so identities with a qualifying AUTHENTICATION key keep their exact previous outcome and TRANSFER is a pure fallback. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/tokens/helpers.rs | 41 ++++++++++--------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 0544c2a6310..3563e8a23d4 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -34,13 +34,14 @@ const TOKEN_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; /// The key that signs an operation on the token at `position` of `token_contract_id`: a /// CRITICAL key of one of [`WALLET_SIGNING_KEY_TYPES`] with one of `purposes`, whose bounds /// cover that token. `purposes` is [`TOKEN_SIGNING_PURPOSES`], or -/// [`LONE_TOKEN_TRANSFER_SIGNING_PURPOSES`] for a lone transfer or claim. Purposes are tried -/// in the order given, so an identity keeps signing with the AUTHENTICATION key it always has -/// and a TRANSFER key signs only when no AUTHENTICATION key qualifies or the signer reaches -/// none; within one purpose the order is [`usable_signing_key`]'s. +/// [`LONE_TOKEN_TRANSFER_SIGNING_PURPOSES`] for a lone transfer or claim. A purpose is tried +/// only when no key of the ones before it qualifies, so an identity holding a qualifying +/// AUTHENTICATION key keeps the outcome it always had, the signer-unavailable error +/// included, and a TRANSFER key signs only for an identity without one. Within one purpose +/// the order is [`usable_signing_key`]'s. /// -/// `Ok(None)` means no key of any of `purposes` is eligible; `Err` means one is, but the -/// signer reaches none. +/// `Ok(None)` means no key of any of `purposes` is eligible; `Err` means the first purpose +/// with an eligible key has none the signer reaches. fn token_signing_key<'a>( identity: &'a Identity, token_contract_id: Identifier, @@ -48,9 +49,8 @@ fn token_signing_key<'a>( signer: &impl Signer, purposes: &[Purpose], ) -> Result, dash_sdk::Error> { - let mut unavailable = None; for &purpose in purposes { - match usable_signing_key( + let key = usable_signing_key( identity, signer, purpose, @@ -60,15 +60,12 @@ fn token_signing_key<'a>( contract_id: token_contract_id, position, }, - ) { - Ok(Some(key)) => return Ok(Some(key)), - Ok(None) => {} - Err(error) => { - unavailable.get_or_insert(error); - } + )?; + if key.is_some() { + return Ok(key); } } - unavailable.map_or(Ok(None), Err) + Ok(None) } /// The purposes a key may have to sign a token operation. @@ -191,6 +188,7 @@ impl IdentityWallet { #[cfg(test)] mod signing_tests { use super::*; + use crate::error::SIGNER_KEY_UNAVAILABLE_PREFIX; use crate::wallet::identity::network::key_selection::tests::{ bound_key, key, refused_purposes, signature_refusal_of, }; @@ -539,12 +537,17 @@ mod signing_tests { Some(2), "the AUTHENTICATION key an identity already signs token operations with goes first" ); - assert_eq!( - pick(&KeyFilter(|key| key.purpose() == Purpose::TRANSFER)).unwrap(), - Some(1), - "a TRANSFER key signs when the signer cannot reach the AUTHENTICATION key" + let unreachable = pick(&KeyFilter(|key| key.purpose() == Purpose::TRANSFER)) + .expect_err("a qualifying AUTHENTICATION key the signer cannot reach is reported"); + assert!( + matches!(&unreachable, dash_sdk::Error::Protocol(ProtocolError::Generic(message)) + if message.starts_with(SIGNER_KEY_UNAVAILABLE_PREFIX) + && message.contains("Signing key 2 ")), + "a TRANSFER key stands in only when no AUTHENTICATION key qualifies, so an \ + identity with one keeps the outcome it had: {unreachable:?}" ); } + #[tokio::test] async fn should_sign_external_signer_token_transfers_and_claims_with_a_lone_transfer_key() { use crate::wallet::identity::network::signing_key::tests::wallet_with_identity_on; From cafa0b6cbed41c4fdf60671c0fbc73070f447646 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:23:00 +0000 Subject: [PATCH 51/53] refactor(dpp): expose BatchTransitionV1::signing_key_purposes as the batch key-purpose rule A client choosing the key for a token transition has no built batch to ask purpose_requirement, so the wallet restated the rule by hand. The rule now lives in one pure function: the purposes a key may have to sign a version 1 batch, given the action of its only transition when that is a token transition. purpose_requirement delegates to it, so Drive and clients run the same code. In-place, output-identical refactor of the shipped BatchTransitionV1 (protocol versions 9 to 15): action_type() is Transfer exactly for TokenTransition::Transfer and Claim exactly for TokenTransition::Claim, the two transitions the previous as_transition_token_transfer / as_transition_token_claim checks matched; every other batch still gets AUTHENTICATION alone. Tests pin the outcome for every token action, a lone document, several transitions and an empty batch. Co-Authored-By: Claude Opus 5.5 --- .../document/batch_transition/tests.rs | 102 ++++++++++++++++++ .../batch_transition/v1/identity_signed.rs | 63 ++++++++--- 2 files changed, 153 insertions(+), 12 deletions(-) diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/tests.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/tests.rs index d55399d2319..5c1836edf81 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/tests.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/tests.rs @@ -783,6 +783,108 @@ mod batch_transition_tests { assert_eq!(purposes, vec![Purpose::AUTHENTICATION]); } + /// Every token action, alone in a batch: only a transfer or a claim may also be signed by a + /// TRANSFER key. Any other batch, `None`, takes AUTHENTICATION only. + #[test] + fn v1_signing_key_purposes_pin_every_lone_token_action_and_any_other_batch() { + use crate::identity::Purpose; + use TokenTransitionActionType::*; + + let authentication_or_transfer = [Purpose::AUTHENTICATION, Purpose::TRANSFER]; + let authentication = [Purpose::AUTHENTICATION]; + let expected: [(TokenTransitionActionType, &[Purpose]); 18] = [ + (Burn, &authentication), + (Mint, &authentication), + (Transfer, &authentication_or_transfer), + (Freeze, &authentication), + (Unfreeze, &authentication), + (DestroyFrozenFunds, &authentication), + (Claim, &authentication_or_transfer), + (EmergencyAction, &authentication), + (ConfigUpdate, &authentication), + (DirectPurchase, &authentication), + (SetPriceForDirectPurchase, &authentication), + (Shield, &authentication), + (MintToPool, &authentication), + (BurnFromPool, &authentication), + (ClaimToPool, &authentication), + (DirectPurchaseToPool, &authentication), + (Unshield, &authentication), + (ShieldedTransfer, &authentication), + ]; + for (action, purposes) in expected { + assert_eq!( + BatchTransitionV1::signing_key_purposes(Some(action)), + purposes, + "a batch holding only a {action} transition" + ); + } + assert_eq!( + BatchTransitionV1::signing_key_purposes(None), + authentication + ); + } + + /// `purpose_requirement` answers through `signing_key_purposes`, with the action of the + /// batch's only transition when that is a token transition: a lone burn and an empty batch + /// keep AUTHENTICATION only, as before the rule moved. + #[test] + fn v1_purpose_requirement_answers_through_signing_key_purposes() { + use crate::identity::Purpose; + use crate::state_transition::StateTransitionIdentitySigned; + + let cases = [ + ( + make_batch_v1(vec![BatchedTransition::Token( + make_token_transfer_transition(1), + )]), + Some(TokenTransitionActionType::Transfer), + ), + ( + make_batch_v1(vec![BatchedTransition::Token(make_token_claim_transition( + 1, + ))]), + Some(TokenTransitionActionType::Claim), + ), + ( + make_batch_v1(vec![BatchedTransition::Token(make_token_burn_transition( + 1, 100, + ))]), + Some(TokenTransitionActionType::Burn), + ), + ( + make_batch_v1(vec![BatchedTransition::Document(make_delete_transition(1))]), + None, + ), + ( + make_batch_v1(vec![ + BatchedTransition::Token(make_token_transfer_transition(1)), + BatchedTransition::Token(make_token_claim_transition(2)), + ]), + None, + ), + (make_batch_v1(vec![]), None), + ]; + for (batch, lone_token_action) in cases { + assert_eq!( + batch.purpose_requirement(), + BatchTransitionV1::signing_key_purposes(lone_token_action).to_vec(), + "{lone_token_action:?}" + ); + } + let lone_burn = make_batch_v1(vec![BatchedTransition::Token(make_token_burn_transition( + 1, 100, + ))]); + assert_eq!( + lone_burn.purpose_requirement(), + vec![Purpose::AUTHENTICATION] + ); + assert_eq!( + make_batch_v1(vec![]).purpose_requirement(), + vec![Purpose::AUTHENTICATION] + ); + } + #[tokio::test] async fn signing_single_token_transfer_accepts_critical_authentication_key() { let platform_version = PlatformVersion::latest(); diff --git a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/identity_signed.rs b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/identity_signed.rs index 32458067c0b..2baeb153ed8 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/identity_signed.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/document/batch_transition/v1/identity_signed.rs @@ -1,10 +1,50 @@ use crate::identity::SecurityLevel::{CRITICAL, HIGH, MEDIUM}; use crate::identity::{KeyID, Purpose, SecurityLevel}; use crate::state_transition::batch_transition::accessors::DocumentsBatchTransitionAccessorsV0; -use crate::state_transition::batch_transition::resolvers::v0::BatchTransitionResolversV0; +use crate::state_transition::batch_transition::batched_transition::token_transition_action_type::{ + TokenTransitionActionType, TokenTransitionActionTypeGetter, +}; +use crate::state_transition::batch_transition::batched_transition::BatchedTransitionRef; use crate::state_transition::batch_transition::BatchTransitionV1; use crate::state_transition::StateTransitionIdentitySigned; +impl BatchTransitionV1 { + /// The purposes a key may have to sign a version 1 batch. `lone_token_action` is the action + /// of the batch's only transition when that is a token transition, and `None` for any other + /// batch: several transitions, a document transition, or none. A TRANSFER key may sign a + /// lone token transfer or claim; every other batch takes AUTHENTICATION only. + /// + /// [`StateTransitionIdentitySigned::purpose_requirement`] answers through this, so a client + /// choosing a key before it builds the batch applies the rule consensus does. + pub fn signing_key_purposes( + lone_token_action: Option, + ) -> &'static [Purpose] { + use TokenTransitionActionType::*; + match lone_token_action { + Some(Transfer | Claim) => &[Purpose::AUTHENTICATION, Purpose::TRANSFER], + Some( + Burn + | Mint + | Freeze + | Unfreeze + | DestroyFrozenFunds + | EmergencyAction + | ConfigUpdate + | DirectPurchase + | SetPriceForDirectPurchase + | Shield + | MintToPool + | BurnFromPool + | ClaimToPool + | DirectPurchaseToPool + | Unshield + | ShieldedTransfer, + ) + | None => &[Purpose::AUTHENTICATION], + } + } +} + impl StateTransitionIdentitySigned for BatchTransitionV1 { fn signature_public_key_id(&self) -> KeyID { self.signature_public_key_id @@ -27,16 +67,15 @@ impl StateTransitionIdentitySigned for BatchTransitionV1 { } fn purpose_requirement(&self) -> Vec { - if self.transitions_len() == 1 { - if let Some(first) = self.first_transition() { - if first.as_transition_token_claim().is_some() - || first.as_transition_token_transfer().is_some() - { - return vec![Purpose::AUTHENTICATION, Purpose::TRANSFER]; - } - } - } - - vec![Purpose::AUTHENTICATION] + // Edited in place in a shipped generation (BatchTransitionV1, protocol versions 9 to + // 15) as an output-identical refactor: `action_type()` is `Transfer` exactly for + // `TokenTransition::Transfer` and `Claim` exactly for `TokenTransition::Claim`, the two + // transitions the previous `as_transition_token_transfer` / `as_transition_token_claim` + // checks matched, and every other batch still gets AUTHENTICATION alone. + let lone_token_action = match (self.transitions_len(), self.first_transition()) { + (1, Some(BatchedTransitionRef::Token(token))) => Some(token.action_type()), + _ => None, + }; + Self::signing_key_purposes(lone_token_action).to_vec() } } From 129e5fc95818653dd50fd963bf067c99de36bebe Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Wed, 28 Oct 2026 16:23:00 +0000 Subject: [PATCH 52/53] refactor(platform-wallet): ask dpp which purposes may sign each token operation Drop the hand-kept TOKEN_SIGNING_PURPOSES and LONE_TOKEN_TRANSFER_SIGNING_PURPOSES copies of consensus's batch purpose rule. check_token_signing_key and token_resolve_signing_key take the operation's TokenTransitionActionType and read the allowed purposes from BatchTransitionV1::signing_key_purposes, since every token operation the wallet sends is a batch holding that one transition. Selection behaviour is unchanged: AUTHENTICATION first, TRANSFER only for a lone transfer or claim of an identity with no qualifying AUTHENTICATION key. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/tokens/burn.rs | 7 +- .../wallet/identity/network/tokens/claim.rs | 7 +- .../network/tokens/destroy_frozen_funds.rs | 7 +- .../wallet/identity/network/tokens/freeze.rs | 7 +- .../wallet/identity/network/tokens/helpers.rs | 87 +++++++++---------- .../wallet/identity/network/tokens/mint.rs | 7 +- .../wallet/identity/network/tokens/pause.rs | 7 +- .../identity/network/tokens/purchase.rs | 7 +- .../wallet/identity/network/tokens/resume.rs | 7 +- .../identity/network/tokens/set_price.rs | 7 +- .../identity/network/tokens/transfer.rs | 7 +- .../identity/network/tokens/unfreeze.rs | 7 +- .../identity/network/tokens/update_config.rs | 7 +- 13 files changed, 89 insertions(+), 82 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs index 4cf29197e6f..2f709760777 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs @@ -8,8 +8,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -38,7 +39,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Burn, )?; let mut builder = @@ -78,7 +79,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Burn, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs index 5f434290058..901b4b78a86 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/claim.rs @@ -7,8 +7,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, LONE_TOKEN_TRANSFER_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -36,7 +37,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + TokenTransitionActionType::Claim, )?; let mut builder = TokenClaimTransitionBuilder::new( @@ -75,7 +76,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + TokenTransitionActionType::Claim, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs index 5bd2bff7f9b..fca98f930dc 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/destroy_frozen_funds.rs @@ -9,8 +9,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -40,7 +41,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::DestroyFrozenFunds, )?; let mut builder = TokenDestroyFrozenFundsTransitionBuilder::new( @@ -88,7 +89,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::DestroyFrozenFunds, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs index 13f4fc25f30..38e05a9f6c6 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/freeze.rs @@ -7,8 +7,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -37,7 +38,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Freeze, )?; let mut builder = TokenFreezeTransitionBuilder::new( @@ -81,7 +82,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Freeze, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs index 3563e8a23d4..f2a9771a2b8 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/helpers.rs @@ -22,6 +22,8 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityPublicKey, Purpose, SecurityLevel}; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; +use dpp::state_transition::batch_transition::BatchTransitionV1; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; @@ -31,25 +33,32 @@ use crate::wallet::identity::network::IdentityWallet; /// batch with a token transition. const TOKEN_SIGNING_LEVELS: [SecurityLevel; 1] = [SecurityLevel::CRITICAL]; -/// The key that signs an operation on the token at `position` of `token_contract_id`: a -/// CRITICAL key of one of [`WALLET_SIGNING_KEY_TYPES`] with one of `purposes`, whose bounds -/// cover that token. `purposes` is [`TOKEN_SIGNING_PURPOSES`], or -/// [`LONE_TOKEN_TRANSFER_SIGNING_PURPOSES`] for a lone transfer or claim. A purpose is tried -/// only when no key of the ones before it qualifies, so an identity holding a qualifying +/// The purposes a key may have to sign a token `action`, as consensus rules them +/// ([`BatchTransitionV1::signing_key_purposes`]): every token operation the wallet sends is a +/// batch holding that one transition, so a transfer or claim may also take a TRANSFER key. +/// AUTHENTICATION comes first. +fn token_signing_purposes(action: TokenTransitionActionType) -> &'static [Purpose] { + BatchTransitionV1::signing_key_purposes(Some(action)) +} + +/// The key that signs a token `action` on the token at `position` of `token_contract_id`: a +/// CRITICAL key of one of [`WALLET_SIGNING_KEY_TYPES`] with one of the purposes +/// [`token_signing_purposes`] allows, whose bounds cover that token. A purpose is tried only +/// when no key of the ones before it qualifies, so an identity holding a qualifying /// AUTHENTICATION key keeps the outcome it always had, the signer-unavailable error /// included, and a TRANSFER key signs only for an identity without one. Within one purpose /// the order is [`usable_signing_key`]'s. /// -/// `Ok(None)` means no key of any of `purposes` is eligible; `Err` means the first purpose +/// `Ok(None)` means no key of any allowed purpose is eligible; `Err` means the first purpose /// with an eligible key has none the signer reaches. fn token_signing_key<'a>( identity: &'a Identity, token_contract_id: Identifier, position: TokenContractPosition, signer: &impl Signer, - purposes: &[Purpose], + action: TokenTransitionActionType, ) -> Result, dash_sdk::Error> { - for &purpose in purposes { + for &purpose in token_signing_purposes(action) { let key = usable_signing_key( identity, signer, @@ -68,30 +77,21 @@ fn token_signing_key<'a>( Ok(None) } -/// The purposes a key may have to sign a token operation. -pub(super) const TOKEN_SIGNING_PURPOSES: [Purpose; 1] = [Purpose::AUTHENTICATION]; - -/// The purposes a key may have to sign a batch of exactly one token transfer or token claim: -/// consensus also takes a TRANSFER key there (`BatchTransitionV1::purpose_requirement`). -pub(super) const LONE_TOKEN_TRANSFER_SIGNING_PURPOSES: [Purpose; 2] = - [Purpose::AUTHENTICATION, Purpose::TRANSFER]; - -/// Check a key the caller chose to sign an operation on the token at `position` of -/// `data_contract`, with one of -/// `purposes`, by the rules [`token_signing_key`] applies except that any key type Platform -/// verifies is accepted, so a key Platform would refuse fails before any request. Contract -/// bounds limit only an AUTHENTICATION key. +/// Check a key the caller chose to sign a token `action` on the token at `position` of +/// `data_contract` by the rules [`token_signing_key`] applies, except that any key type +/// Platform verifies is accepted, so a key Platform would refuse fails before any request. +/// Contract bounds limit only an AUTHENTICATION key. pub(super) fn check_token_signing_key( key: &IdentityPublicKey, signer: &impl Signer, data_contract: &DataContract, position: TokenContractPosition, - purposes: &[Purpose], + action: TokenTransitionActionType, ) -> Result<(), dash_sdk::Error> { check_signing_key( key, signer, - purposes, + token_signing_purposes(action), &TOKEN_SIGNING_LEVELS, &PLATFORM_SIGNING_KEY_TYPES, SigningScope::Token { @@ -108,7 +108,7 @@ impl IdentityWallet { /// which on-chain key id to sign with. /// /// Key selection is a fixed canonical policy: - /// one of `purposes` × `SecurityLevel::CRITICAL` × `WALLET_SIGNING_KEY_TYPES`, + /// a purpose `action` allows × `SecurityLevel::CRITICAL` × `WALLET_SIGNING_KEY_TYPES`, /// bounds covering `token_contract_id` (see `token_signing_key`). /// Callers that pass a `signing_key_id` over FFI are advisory — /// this Rust path is authoritative and Drive validates the chosen @@ -119,7 +119,7 @@ impl IdentityWallet { token_contract_id: Identifier, token_position: TokenContractPosition, signer: &impl Signer, - purposes: &[Purpose], + action: TokenTransitionActionType, ) -> Result { let wm = self.wallet_manager.read().await; let info = wm @@ -133,21 +133,16 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; drop(wm); - let signing_key = token_signing_key( - &identity, - token_contract_id, - token_position, - signer, - purposes, - )? - .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { - identity_id: *identity_id, - purpose: Purpose::AUTHENTICATION, - security_levels: TOKEN_SIGNING_LEVELS.to_vec(), - key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), - transition: format!("a token transition of contract {token_contract_id}"), - })? - .clone(); + let signing_key = + token_signing_key(&identity, token_contract_id, token_position, signer, action)? + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: TOKEN_SIGNING_LEVELS.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: format!("a token transition of contract {token_contract_id}"), + })? + .clone(); Ok(signing_key) } @@ -419,7 +414,7 @@ mod signing_tests { Identifier::default(), 0, &KeyFilter(|_| true), - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Burn, ) .await .unwrap_err(); @@ -437,7 +432,7 @@ mod signing_tests { Identifier::default(), 0, &signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Burn, ) .await .unwrap_err(); @@ -468,7 +463,7 @@ mod signing_tests { token_contract, 0, &KeyFilter(|_| true), - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Burn, ) .unwrap(); assert_eq!( @@ -495,7 +490,7 @@ mod signing_tests { Identifier::default(), 0, &KeyFilter(|_| true), - &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + TokenTransitionActionType::Transfer, ) .await .expect("consensus takes a CRITICAL TRANSFER key for a lone transfer or claim"); @@ -507,7 +502,7 @@ mod signing_tests { Identifier::default(), 0, &KeyFilter(|_| true), - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Burn, ) .await .unwrap_err(); @@ -528,7 +523,7 @@ mod signing_tests { Identifier::default(), 0, signer, - &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + TokenTransitionActionType::Transfer, ) .map(|key| key.map(|key| key.id())) }; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs index 5c7328a20f5..d04225ed78a 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/mint.rs @@ -16,8 +16,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -47,7 +48,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Mint, )?; // Contracts with `minting_allow_choosing_destination = false` @@ -133,7 +134,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Mint, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs index a2e6b7b2999..25254a2c949 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/pause.rs @@ -8,8 +8,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -38,7 +39,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::EmergencyAction, )?; let mut builder = TokenEmergencyActionTransitionBuilder::pause( @@ -81,7 +82,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::EmergencyAction, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs index 6655203a34b..76d730b10ff 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/purchase.rs @@ -14,8 +14,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -44,7 +45,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::DirectPurchase, )?; let mut builder = TokenDirectPurchaseTransitionBuilder::new( @@ -80,7 +81,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::DirectPurchase, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs index b15d3c80857..6d28fe8a079 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/resume.rs @@ -7,8 +7,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -37,7 +38,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::EmergencyAction, )?; let mut builder = TokenEmergencyActionTransitionBuilder::resume( @@ -80,7 +81,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::EmergencyAction, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs index f28f306cedd..16b6a259db4 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/set_price.rs @@ -14,8 +14,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -45,7 +46,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::SetPriceForDirectPurchase, )?; let mut builder = TokenChangeDirectPurchasePriceTransitionBuilder::new( @@ -98,7 +99,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::SetPriceForDirectPurchase, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs index 03886eab65b..ea2224842f0 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/transfer.rs @@ -8,8 +8,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, LONE_TOKEN_TRANSFER_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -40,7 +41,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + TokenTransitionActionType::Transfer, )?; let mut builder = TokenTransferTransitionBuilder::new( @@ -83,7 +84,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &LONE_TOKEN_TRANSFER_SIGNING_PURPOSES, + TokenTransitionActionType::Transfer, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs index 4585f51610a..119f098494c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/unfreeze.rs @@ -7,8 +7,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -37,7 +38,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Unfreeze, )?; let mut builder = TokenUnfreezeTransitionBuilder::new( @@ -83,7 +84,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::Unfreeze, ) .await?; diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs index e712e23d978..81382fa77ab 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/update_config.rs @@ -9,8 +9,9 @@ use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; use dpp::identity::IdentityPublicKey; use dpp::prelude::Identifier; +use dpp::state_transition::batch_transition::batched_transition::token_transition_action_type::TokenTransitionActionType; -use super::helpers::{check_token_signing_key, TOKEN_SIGNING_PURPOSES}; +use super::helpers::check_token_signing_key; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -39,7 +40,7 @@ impl IdentityWallet { signer, &data_contract, token_position, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::ConfigUpdate, )?; let mut builder = TokenConfigUpdateTransitionBuilder::new( @@ -87,7 +88,7 @@ impl IdentityWallet { token_contract_id, token_position, signer, - &TOKEN_SIGNING_PURPOSES, + TokenTransitionActionType::ConfigUpdate, ) .await?; From 8e1173bb7f632689dd6f35ac257108eeae773749 Mon Sep 17 00:00:00 2001 From: Lukasz Klimek <842586+lklimek@users.noreply.github.com> Date: Thu, 29 Oct 2026 09:28:25 +0000 Subject: [PATCH 53/53] refactor(sdk): resolve the contact-request DashPay contract the established way Drop Sdk::fetch_current_system_data_contract, contract_proved_at_parsed_version and SYSTEM_CONTRACT_FETCH_ATTEMPTS. prepare_contact_request goes back to fetch_dashpay_contract (the context provider's contract at the SDK's protocol version, fetched and proved when it holds none), as before this branch. The key is still chosen from the same contactRequest type the document is built as. DPNS registration keeps the DPNS-local proved-at-parsed-version fetch that #5337 introduced, restored verbatim. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01WunYYjpfLux1ByK7fGF7SG --- packages/rs-sdk/src/platform.rs | 2 +- .../src/platform/dashpay/contact_request.rs | 135 ++++++++---------- .../rs-sdk/src/platform/dpns_usernames/mod.rs | 74 +++++++--- .../src/platform/system_data_contract.rs | 61 -------- 4 files changed, 119 insertions(+), 153 deletions(-) diff --git a/packages/rs-sdk/src/platform.rs b/packages/rs-sdk/src/platform.rs index cf00fc947b1..3090558060a 100644 --- a/packages/rs-sdk/src/platform.rs +++ b/packages/rs-sdk/src/platform.rs @@ -29,7 +29,7 @@ pub mod query; pub mod query_settings; #[cfg(feature = "shielded")] pub mod shielded; -pub(crate) mod system_data_contract; +mod system_data_contract; pub mod tokens; pub mod transition; pub mod trunk_branch_sync; diff --git a/packages/rs-sdk/src/platform/dashpay/contact_request.rs b/packages/rs-sdk/src/platform/dashpay/contact_request.rs index 841ce33a088..731fcf8a484 100644 --- a/packages/rs-sdk/src/platform/dashpay/contact_request.rs +++ b/packages/rs-sdk/src/platform/dashpay/contact_request.rs @@ -5,7 +5,6 @@ use crate::platform::transition::put_document::PutDocument; use crate::platform::Document; use crate::{Error, Sdk}; -use dash_context_provider::ContextProvider; use dpp::data_contract::accessors::v0::DataContractV0Getters; use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; use dpp::data_contract::document_type::{DocumentType, DocumentTypeRef}; @@ -24,16 +23,16 @@ use platform_encryption::{ derive_shared_key_ecdh, encrypt_account_label, encrypt_extended_public_key, COMPACT_XPUB_LEN, }; use std::collections::BTreeMap; -use std::sync::Arc; /// The DashPay document type a contact request writes. const CONTACT_REQUEST_DOCUMENT_TYPE: &str = "contactRequest"; /// A contact request prepared by [`Sdk::prepare_contact_request`]: the `contactRequest` -/// document type of the DashPay contract the network stores now, which the request document is -/// built as and whose rules the key that signs it must meet. A caller choosing the key reads -/// them here, then sends through [`Sdk::submit_contact_request`], so the key is judged by the -/// contract the document is built against and never by another snapshot of it. +/// document type of the DashPay contract the SDK resolves for its protocol version, which the +/// request document is built as and whose rules the key that signs it must meet. A caller +/// choosing the key reads them here, then sends through [`Sdk::submit_contact_request`], so the +/// key is judged by the contract the document is built against and never by another snapshot +/// of it. #[derive(Debug, Clone)] pub struct PreparedContactRequest { contact_request_document_type: DocumentType, @@ -309,28 +308,18 @@ impl Sdk { .await } - /// Prepare a contact request: learn the network's protocol version, fetch the DashPay - /// contract the network stores now, proved at the version the SDK parsed it under - /// ([`Sdk::fetch_current_system_data_contract`]), and resolve its `contactRequest` document - /// type. A contract the context provider holds can be older than the network's, and the - /// level it requires of the signing key one Platform no longer accepts. Nothing is built, - /// signed or submitted. The returned [`PreparedContactRequest`] tells what that contract - /// requires of the signing key; send it with [`Sdk::submit_contact_request`]. + /// Prepare a contact request: resolve the DashPay contract for the SDK's protocol version + /// (the context provider's, fetched and proved when it holds none) and its + /// `contactRequest` document type. Nothing is built, signed or submitted. The returned + /// [`PreparedContactRequest`] tells what that contract requires of the signing key; send + /// it with [`Sdk::submit_contact_request`]. pub async fn prepare_contact_request(&self) -> Result { - let dashpay_contract = self - .fetch_current_system_data_contract(self.get_dashpay_contract_id()?, "DashPay") - .await?; + let dashpay_contract = self.fetch_dashpay_contract().await?; let contact_request_document_type = dashpay_contract .document_type_cloned_for_name(CONTACT_REQUEST_DOCUMENT_TYPE) .map_err(|_| { Error::Generic("DashPay contactRequest document type not found".to_string()) })?; - // The confirmation of the document is a proof the SDK decodes under the DashPay - // contract its context provider resolves: give it the contract the document is built - // against, so it decodes under it - if let Some(provider) = self.context_provider() { - provider.register_data_contract(Arc::new(dashpay_contract)); - } Ok(PreparedContactRequest { contact_request_document_type, }) @@ -673,6 +662,7 @@ mod tests { use dpp::data_contract::DataContract; use dpp::secp256k1; use dpp::secp256k1::rand::{self, RngCore}; + use std::sync::Arc; #[test] fn test_ecdh_encryption_produces_correct_size() { @@ -883,34 +873,19 @@ mod tests { ); } - /// A context provider that holds the DashPay contract the SDK bundles for the latest - /// protocol version until a contract is registered with it, which then takes its place. - /// Its clones share what was registered. - #[derive(Clone, Default)] - struct BundledDashPayProvider { - registered: Arc>>>, + /// A context provider holding `contract`, if any, for every id and protocol version. + struct DashPayProvider { + contract: Option>, } - impl dash_context_provider::ContextProvider for BundledDashPayProvider { + impl dash_context_provider::ContextProvider for DashPayProvider { fn get_data_contract( &self, _id: &Identifier, _platform_version: &dpp::version::PlatformVersion, ) -> Result>, dash_context_provider::ContextProviderError> { - use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; - - if let Some(contract) = self.registered.lock().expect("the lock").clone() { - return Ok(Some(contract)); - } - load_system_data_contract( - SystemDataContract::Dashpay, - dpp::version::PlatformVersion::latest(), - ) - .map(|contract| Some(Arc::new(contract))) - .map_err(|error| { - dash_context_provider::ContextProviderError::Generic(error.to_string()) - }) + Ok(self.contract.clone()) } fn get_token_configuration( @@ -940,34 +915,63 @@ mod tests { { Ok(1) } - - fn register_data_contract(&self, contract: Arc) { - *self.registered.lock().expect("the lock") = Some(contract); - } } - #[tokio::test] - async fn should_prepare_the_signing_requirement_from_the_dashpay_contract_the_network_stores() { + /// The latest DashPay contract with its `contactRequest` type requiring a CRITICAL key, + /// where the bundled one requires HIGH. + fn dashpay_with_critical_contact_request() -> DataContract { use crate::platform::system_data_contract::tests::with_document_security_level; - use dash_context_provider::ContextProvider; use dpp::identity::SecurityLevel; use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; use dpp::version::PlatformVersion; - // The context provider holds the bundled DashPay contract, which requires HIGH; the - // network stores one whose `contactRequest` requires CRITICAL - let provider = BundledDashPayProvider::default(); - let mut sdk = crate::SdkBuilder::new_mock() - .with_version(PlatformVersion::latest()) - .with_context_provider(provider.clone()) - .build() - .expect("the mock SDK builds"); - let stored = with_document_security_level( + with_document_security_level( load_system_data_contract(SystemDataContract::Dashpay, PlatformVersion::latest()) .expect("the DashPay contract loads"), "contactRequest", SecurityLevel::CRITICAL, + ) + } + + #[tokio::test] + async fn should_prepare_the_signing_requirement_from_the_dashpay_contract_the_provider_holds() { + use dpp::identity::SecurityLevel; + use dpp::version::PlatformVersion; + + // No network expectation: a fetch would fail the test + let held = dashpay_with_critical_contact_request(); + let sdk = crate::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .with_context_provider(DashPayProvider { + contract: Some(Arc::new(held.clone())), + }) + .build() + .expect("the mock SDK builds"); + + let prepared = sdk + .prepare_contact_request() + .await + .expect("the contact request is prepared"); + + assert_eq!( + prepared.signing_security_level_requirement(), + SecurityLevel::CRITICAL, + "the key is judged by the contract the document is built against" ); + assert_eq!(prepared.dashpay_contract_id(), held.id()); + } + + #[tokio::test] + async fn should_prepare_the_signing_requirement_from_the_fetched_dashpay_contract() { + use dpp::identity::SecurityLevel; + use dpp::version::PlatformVersion; + + let mut sdk = crate::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .with_context_provider(DashPayProvider { contract: None }) + .build() + .expect("the mock SDK builds"); + let stored = dashpay_with_critical_contact_request(); sdk.mock() .expect_fetch(stored.id(), Some(stored.clone())) .await @@ -980,21 +984,8 @@ mod tests { assert_eq!( prepared.signing_security_level_requirement(), - SecurityLevel::CRITICAL, - "the key is judged by the contract the network stores, not the provider's" - ); - assert_eq!(prepared.dashpay_contract_id(), stored.id()); - // The document's confirmation decodes under the contract it was built against - let resolved = provider - .get_data_contract(&stored.id(), PlatformVersion::latest()) - .expect("the provider answers") - .expect("the provider holds DashPay"); - assert_eq!( - resolved - .document_type_for_name("contactRequest") - .expect("the contactRequest type") - .security_level_requirement(), SecurityLevel::CRITICAL ); + assert_eq!(prepared.dashpay_contract_id(), stored.id()); } } diff --git a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs index 9f9fbfc154e..df9a34154ca 100644 --- a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs +++ b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs @@ -11,7 +11,7 @@ use crate::platform::documents::document_query::DocumentQuery; use crate::platform::documents::transitions::DocumentDeleteTransitionBuilder; use crate::platform::transition::put_document::PutDocument; use crate::platform::transition::put_settings::PutSettings; -use crate::platform::{DataContract, Document, FetchMany}; +use crate::platform::{DataContract, Document, Fetch, FetchMany}; use crate::{Error, Sdk}; use dapi_grpc::platform::v0::ResponseMetadata; use dash_context_provider::ContextProvider; @@ -31,6 +31,7 @@ use dpp::state_transition::batch_transition::methods::StateTransitionCreationOpt use drive::query::{SelectProjection, WhereClause, WhereOperator}; use std::collections::BTreeMap; use std::fmt; +use std::future::Future; use std::sync::Arc; use tracing::debug; use tracing::warn; @@ -244,6 +245,45 @@ struct DpnsRegistrationDocuments { signing_requirement: SecurityLevel, } +/// How many DPNS contract responses a registration reads for one proved at the protocol +/// version the SDK parsed it under. +const DPNS_CONTRACT_FETCH_ATTEMPTS: usize = 3; + +/// The DPNS contract of the first response proved at the protocol version the SDK parsed it +/// under, reading the SDK's version through `sdk_version` and each response through `fetch`, +/// at most [`DPNS_CONTRACT_FETCH_ATTEMPTS`] times. The SDK's version only rises, and SDK clones +/// share it, so a version unchanged across the fetch is the one the response was parsed under; +/// one that rose meanwhile (this response, or another request, taught the SDK a newer version) +/// leaves the response unused. A response proved at a newer version was parsed under an older +/// one, which can drop the declaration the preorder hash follows. One proved at an older +/// version comes from a node behind the network, which can still hold the contract an upgrade +/// replaced. Either would commit the preorder to a hash the domain cannot reveal. +async fn dpns_contract_proved_at_parsed_version( + sdk_version: V, + mut fetch: F, +) -> Result +where + V: Fn() -> u32, + F: FnMut() -> R, + R: Future, ResponseMetadata), Error>>, +{ + let mut last_mismatch = None; + for _ in 0..DPNS_CONTRACT_FETCH_ATTEMPTS { + let parsed_under = sdk_version(); + let (dpns_contract, metadata) = fetch().await?; + if metadata.protocol_version == parsed_under && sdk_version() == parsed_under { + return dpns_contract + .ok_or_else(|| Error::Generic("DPNS contract not found".to_string())); + } + last_mismatch = Some((metadata.protocol_version, parsed_under)); + } + let (proved_at, parsed_under) = last_mismatch.unwrap_or_default(); + Err(Error::Generic(format!( + "no DPNS contract response was proved at the protocol version the SDK parsed it under \ + (last proved at {proved_at}, parsed under {parsed_under})" + ))) +} + /// A DPNS name registration prepared by [`Sdk::prepare_dpns_name_registration`]: the preorder /// and domain documents, built against the DPNS contract the network stores now, and what /// that same contract requires of the key that signs them. A caller choosing or checking the @@ -335,14 +375,17 @@ impl Sdk { /// The preorder commits to the hash that contract declares, so neither a contract the /// context provider holds for the SDK's protocol version nor one cached before an upgrade /// changed it will do: either can be older than the network's, and its hash one the - /// domain cannot reveal. A response parsed under another protocol version than the one it - /// was proved at can drop the declaration the preorder hash follows, and one from a node - /// behind the network can still hold the contract an upgrade replaced - /// ([`Sdk::fetch_current_system_data_contract`]). + /// domain cannot reveal. The SDK first learns the network's protocol version (a proven + /// refresh), then takes a response proved at the version it parsed it under + /// ([`dpns_contract_proved_at_parsed_version`]). async fn fetch_current_dpns_contract(&self) -> Result { let dpns_contract_id = self.get_dpns_contract_id()?; - self.fetch_current_system_data_contract(dpns_contract_id, "DPNS") - .await + self.refresh_protocol_version().await?; + dpns_contract_proved_at_parsed_version( + || self.protocol_version_number(), + || DataContract::fetch_with_metadata(self, dpns_contract_id, None), + ) + .await } /// The documents a registration of `label` by `identity_id` submits, built against the @@ -859,9 +902,6 @@ fn identity_from_domain_records( #[cfg(test)] mod tests { use super::*; - use crate::platform::system_data_contract::{ - contract_proved_at_parsed_version, SYSTEM_CONTRACT_FETCH_ATTEMPTS, - }; use crate::query_types::Documents; use crate::sdk::test::expect_epoch_refresh; use crate::SdkBuilder; @@ -1645,8 +1685,7 @@ mod tests { // version, so the next one is parsed under it. let sdk_version = Cell::new(13); let fetches = Cell::new(0); - let dpns_contract = contract_proved_at_parsed_version( - "DPNS", + let dpns_contract = dpns_contract_proved_at_parsed_version( || sdk_version.get(), || { fetches.set(fetches.get() + 1); @@ -1675,8 +1714,7 @@ mod tests { (PlatformVersion::latest(), LATEST_VERSION), (PlatformVersion::get(13).expect("protocol version 13"), 13), ]); - let dpns_contract = contract_proved_at_parsed_version( - "DPNS", + let dpns_contract = dpns_contract_proved_at_parsed_version( || LATEST_VERSION, || { let (stored_at, proved) = responses @@ -1702,8 +1740,7 @@ mod tests { // SDK has learned since. let sdk_version = Cell::new(13); let fetches = Cell::new(0); - let dpns_contract = contract_proved_at_parsed_version( - "DPNS", + let dpns_contract = dpns_contract_proved_at_parsed_version( || sdk_version.get(), || { fetches.set(fetches.get() + 1); @@ -1730,8 +1767,7 @@ mod tests { #[tokio::test] async fn should_refuse_when_every_dpns_contract_response_is_behind_the_network() { let fetches = Cell::new(0); - let result = contract_proved_at_parsed_version( - "DPNS", + let result = dpns_contract_proved_at_parsed_version( || LATEST_VERSION, || { fetches.set(fetches.get() + 1); @@ -1743,7 +1779,7 @@ mod tests { .await; assert!(result.is_err()); - assert_eq!(fetches.get(), SYSTEM_CONTRACT_FETCH_ATTEMPTS); + assert_eq!(fetches.get(), DPNS_CONTRACT_FETCH_ATTEMPTS); } #[test] diff --git a/packages/rs-sdk/src/platform/system_data_contract.rs b/packages/rs-sdk/src/platform/system_data_contract.rs index dc29bdd7446..208d9c38df1 100644 --- a/packages/rs-sdk/src/platform/system_data_contract.rs +++ b/packages/rs-sdk/src/platform/system_data_contract.rs @@ -3,50 +3,9 @@ use crate::platform::{DataContract, Fetch, Identifier}; use crate::{Error, Sdk}; -use dapi_grpc::platform::v0::ResponseMetadata; use dash_context_provider::ContextProvider; -use std::future::Future; use std::sync::Arc; -/// How many responses [`Sdk::fetch_current_system_data_contract`] reads for one proved at the -/// protocol version the SDK parsed it under. -pub(crate) const SYSTEM_CONTRACT_FETCH_ATTEMPTS: usize = 3; - -/// The `name` contract of the first response proved at the protocol version the SDK parsed it -/// under, reading the SDK's version through `sdk_version` and each response through `fetch`, -/// at most [`SYSTEM_CONTRACT_FETCH_ATTEMPTS`] times. The SDK's version only rises, and SDK -/// clones share it, so a version unchanged across the fetch is the one the response was parsed -/// under; one that rose meanwhile (this response, or another request, taught the SDK a newer -/// version) leaves the response unused. A response proved at a newer version was parsed under -/// an older one, which can drop declarations the newer contract makes. One proved at an older -/// version comes from a node behind the network, which can still hold the contract an upgrade -/// replaced. -pub(crate) async fn contract_proved_at_parsed_version( - name: &str, - sdk_version: V, - mut fetch: F, -) -> Result -where - V: Fn() -> u32, - F: FnMut() -> R, - R: Future, ResponseMetadata), Error>>, -{ - let mut last_mismatch = None; - for _ in 0..SYSTEM_CONTRACT_FETCH_ATTEMPTS { - let parsed_under = sdk_version(); - let (contract, metadata) = fetch().await?; - if metadata.protocol_version == parsed_under && sdk_version() == parsed_under { - return contract.ok_or_else(|| Error::Generic(format!("{name} contract not found"))); - } - last_mismatch = Some((metadata.protocol_version, parsed_under)); - } - let (proved_at, parsed_under) = last_mismatch.unwrap_or_default(); - Err(Error::Generic(format!( - "no {name} contract response was proved at the protocol version the SDK parsed it \ - under (last proved at {proved_at}, parsed under {parsed_under})" - ))) -} - impl Sdk { /// The system data contract `contract_id`, from the context provider when it holds it at /// the SDK's protocol version, fetched and proved otherwise. `None` when the network has no @@ -62,26 +21,6 @@ impl Sdk { } Ok(DataContract::fetch(self, contract_id).await?.map(Arc::new)) } - - /// The system data contract `contract_id` (named `name` in errors) the network stores now, - /// fetched and proved, for a transition whose rules come from it. Neither a contract the - /// context provider holds for the SDK's protocol version nor one cached before an upgrade - /// will do: either can be older than the network's. The SDK first learns the network's - /// protocol version (a proven refresh), then takes a response proved at the version it - /// parsed it under ([`contract_proved_at_parsed_version`]). - pub(crate) async fn fetch_current_system_data_contract( - &self, - contract_id: Identifier, - name: &str, - ) -> Result { - self.refresh_protocol_version().await?; - contract_proved_at_parsed_version( - name, - || self.protocol_version_number(), - || DataContract::fetch_with_metadata(self, contract_id, None), - ) - .await - } } #[cfg(test)]