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/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] + ); + } +} diff --git a/packages/rs-dpp/src/state_transition/mod.rs b/packages/rs-dpp/src/state_transition/mod.rs index e961ba3cfec..89d76478ac2 100644 --- a/packages/rs-dpp/src/state_transition/mod.rs +++ b/packages/rs-dpp/src/state_transition/mod.rs @@ -2027,15 +2027,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 }) { @@ -2046,6 +2046,7 @@ impl StateTransition { ))) } } + _ if identity_public_key.can_sign_non_batch() => Ok(()), _ => Err(ProtocolError::ConsensusError(Box::new( ContractBoundedKeyNonBatchError::new(identity_public_key.id()).into(), ))), @@ -3161,6 +3162,55 @@ mod tests { )) } + #[cfg(feature = "state-transition-signing")] + #[test] + 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; + + 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(); + let expected = purpose != Purpose::AUTHENTICATION || contract_bounds.is_none(); + assert_eq!( + key.can_sign_non_batch(), + 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:?}"), + } + } + } + } + #[cfg(all(feature = "state-transition-signing", feature = "bls-signatures"))] #[test] fn should_enforce_contract_bounds_before_private_key_signing() { 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() } } diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index d14d197ddb2..e3a13d0e237 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -987,6 +987,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 @@ -1381,6 +1389,33 @@ 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], + key_types: vec![dpp::identity::KeyType::ECDSA_SECP256K1], + 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", + "ECDSA_SECP256K1", + "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 85b86828e64..79d157d576f 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -7,6 +7,7 @@ use dpp::consensus::state::identity::invalid_identity_revision_error::InvalidIde use dpp::consensus::ConsensusError; use dpp::fee::Credits; use dpp::identifier::Identifier; +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; @@ -103,6 +104,23 @@ pub enum PlatformWalletError { #[error("Invalid identity data: {0}")] InvalidIdentityData(String), + /// 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 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, + }, + /// 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/lib.rs b/packages/rs-platform-wallet/src/lib.rs index 11170cad5f3..40b33328427 100644 --- a/packages/rs-platform-wallet/src/lib.rs +++ b/packages/rs-platform-wallet/src/lib.rs @@ -74,9 +74,10 @@ pub use masternode::{ }; pub use wallet::core_address_key::CoreAddressPrivateKey; pub use wallet::identity::network::{ - derive_identity_auth_keypair, AutoAcceptProofSource, ContactCryptoProvider, ContactInfoOpened, - ContactInfoPublishOutcome, ContactInfoSealed, PreparedDashPayPayment, SeedBindingVerification, - IDENTITY_GAP_LIMIT, MASTER_KEY_INDEX, + check_signing_key, derive_identity_auth_keypair, usable_signing_key, AutoAcceptProofSource, + ContactCryptoProvider, ContactInfoOpened, ContactInfoPublishOutcome, ContactInfoSealed, + PreparedDashPayPayment, 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/contact_requests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contact_requests.rs index 4d9e3e2eafb..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 @@ -1,6 +1,9 @@ //! DashPay contact request lifecycle: send, sync, accept, reject. -use super::signing_key::AvailableSigningKey; +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; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; @@ -615,26 +618,25 @@ 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, - )? - .cloned() - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "Sender identity has no HIGH or CRITICAL authentication key \ - (required for document state transitions)" - .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 identity_public_key = contact_request_signing_key( + &sender_identity, + signer, + prepared.contact_request_document_type(), + )? + .cloned() + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *sender_identity_id, + purpose: Purpose::AUTHENTICATION, + 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(), + })?; // 6. Client-side ECDH via the signer: the shared secret is derived in // the signer (scalar at `sender_enc_path`) against the recipient's @@ -671,6 +673,7 @@ impl DashPayView<'_, B> { let result = self .sdk_writer .send_contact_request(SendContactRequestParams { + prepared, sender_identity: sender_identity.clone(), recipient_identity, sender_key_index, @@ -1230,6 +1233,26 @@ fn select_recipient_key_index(recipient_identity: &Identity) -> Result( + identity: &'a Identity, + signer: &impl Signer, + contact_request: DocumentTypeRef<'_>, +) -> Result, dash_sdk::Error> { + document_signing_key( + identity, + signer, + contact_request.security_level_requirement(), + SigningScope::DocumentCreate { + document_type: contact_request, + }, + ) +} + /// Select our OWN ECDH root key: the first **enabled** `ECDSA_SECP256K1` /// ENCRYPTION key on the identity (`BTreeMap` order → lowest key id). /// @@ -6597,3 +6620,54 @@ 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::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; + + #[test] + fn should_sign_a_contact_request_with_a_key_bound_to_contact_requests_or_unbound() { + let dashpay = 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 contract = load_system_data_contract( + SystemDataContract::Dashpay, + 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), contact_request) + .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/contract.rs b/packages/rs-platform-wallet/src/wallet/identity/network/contract.rs index ffa31f95316..edc2d99da07 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,10 @@ //! the rs-sdk-ffi path — classic stack-guard fingerprint, not //! memory unsafety. -use super::signing_key::AvailableSigningKey; +use super::key_selection::WALLET_SIGNING_KEY_TYPES; +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; @@ -34,7 +37,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, Purpose}; use dpp::platform_value::BinaryData; use dpp::prelude::{DataContract, Identifier}; use dpp::state_transition::data_contract_update_transition::methods::DataContractUpdateTransitionMethodsV0; @@ -95,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 @@ -162,24 +165,13 @@ 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, - )? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "No CRITICAL authentication key found on owner identity \ - (required to sign a contract-create state transition)" - .to_string(), - ) + 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_CREATE_SIGNING_LEVELS.to_vec(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: "a contract-create state transition".to_string(), })? .clone() }; @@ -322,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, @@ -387,24 +379,13 @@ 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, - )? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "No CRITICAL authentication key found on owner identity \ - (required to sign a contract-update state transition)" - .to_string(), - ) + 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_UPDATE_SIGNING_LEVELS.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 0ddd1586b80..6ea7e81148c 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,10 @@ //! 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, PLATFORM_SIGNING_KEY_TYPES, + WALLET_SIGNING_KEY_TYPES, +}; use std::collections::BTreeMap; use std::sync::Arc; @@ -43,9 +46,8 @@ 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::{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; @@ -101,37 +103,42 @@ 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 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, + requirement: SecurityLevel, + scope: SigningScope<'_>, +) -> Result, dash_sdk::Error> { + usable_signing_key( + identity, + signer, + Purpose::AUTHENTICATION, + &SecurityLevel::accepted_for_requirement(requirement), + &WALLET_SIGNING_KEY_TYPES, + 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, except that any key +/// type Platform verifies is accepted. +pub(super) 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), + &PLATFORM_SIGNING_KEY_TYPES, + scope, + ) } impl IdentityWallet { @@ -166,10 +173,10 @@ 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 - /// `security_level_requirement()` (see - /// [`allowed_signing_security_levels`]). Returns a clear error + /// 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 /// key. /// 4. Broadcasts via @@ -275,7 +282,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 +295,22 @@ 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::DocumentCreate { + document_type: document_type.as_ref(), + }, + )? + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *owner_identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement(required_level), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: format!("a {document_type_name} document transition"), + })? + .clone() }; // 4. Broadcast via `PutDocument` on the platform-wallet 8 MB @@ -429,9 +435,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, + /// 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 /// by consensus with "requires AUTHENTICATION"). @@ -439,8 +446,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 +479,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) } @@ -506,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 @@ -548,10 +570,6 @@ impl IdentityWallet { )) })?; - let signing_key = self - .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) - .await?; - let builder = DocumentReplaceTransitionBuilder::new( data_contract, document_type_name.to_string(), @@ -598,7 +616,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 +692,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 +703,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 @@ -722,6 +752,43 @@ 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?; + + 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?; @@ -731,10 +798,6 @@ impl IdentityWallet { )) })?; - let signing_key = self - .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) - .await?; - let builder = DocumentTransferTransitionBuilder::new( data_contract, document_type_name.to_string(), @@ -743,7 +806,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 / @@ -785,6 +848,43 @@ 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?; + + 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?; @@ -794,10 +894,6 @@ impl IdentityWallet { )) })?; - let signing_key = self - .resolve_authentication_signing_key(owner_identity_id, signing_key_id, signer) - .await?; - let builder = DocumentSetPriceTransitionBuilder::new( data_contract, document_type_name.to_string(), @@ -806,7 +902,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 @@ -851,6 +947,46 @@ impl IdentityWallet { .fetch_contract_arc_for_document_op(contract_id, document_type_name) .await?; + let signing_key = self + .resolve_authentication_signing_key( + purchaser_identity_id, + signing_key_id, + &data_contract, + document_type_name, + signer, + ) + .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?; @@ -860,10 +996,6 @@ impl IdentityWallet { )) })?; - let signing_key = self - .resolve_authentication_signing_key(purchaser_identity_id, signing_key_id, signer) - .await?; - let builder = DocumentPurchaseTransitionBuilder::new( data_contract, document_type_name.to_string(), @@ -873,7 +1005,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 @@ -932,8 +1064,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() { @@ -941,7 +1184,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 +1235,186 @@ 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, IdentityPublicKeySettersV0, + }; + use dpp::identity::identity_public_key::contract_bounds::ContractBounds; + use dpp::identity::KeyType; + + 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()) + } + + #[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, + 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" + ); + 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 3dfb096b407..6d709496f61 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/dpns.rs @@ -1,23 +1,17 @@ //! DPNS name registration, resolution, search, and contest queries. -use super::signing_key::AvailableSigningKey; +use super::document::{check_document_signing_key, document_signing_key}; +use super::key_selection::{SigningScope, WALLET_SIGNING_KEY_TYPES}; 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::KeyType; -use dpp::identity::Purpose; -use dpp::identity::SecurityLevel; +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}; @@ -25,49 +19,46 @@ 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); - -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") - } +/// The key that signs both DPNS registration documents, `preorder` then `domain`: an +/// 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(dpns_contract_id), + ) } -#[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 - } +/// 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, + requirement: SecurityLevel, + dpns_contract_id: Identifier, +) -> Result<(), dash_sdk::Error> { + check_document_signing_key( + key, + signer, + requirement, + dpns_registration_scope(dpns_contract_id), + ) +} - fn can_sign_with(&self, key: &K) -> bool { - self.0.can_sign_with(key) +/// Registration writes `preorder` and then `domain`, so its key must cover the whole contract. +fn dpns_registration_scope(dpns_contract_id: Identifier) -> SigningScope<'static> { + SigningScope::Contract { + contract_id: dpns_contract_id, } } @@ -133,7 +124,10 @@ 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, 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 @@ -148,18 +142,26 @@ impl IdentityWallet { contest_fund: Option, signer: S, ) -> Result { - use dash_sdk::platform::dpns_usernames::RegisterDpnsNameInput; - - 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 registration = self + .sdk + .prepare_dpns_name_registration(name, identity.id()) + .await?; + check_dpns_registration_signing_key( + &identity_public_key, + &signer, + registration.signing_security_level_requirement(), + registration.dpns_contract_id(), + )?; + 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) } @@ -198,85 +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. - self.dpns_contract().await?; - - 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); - // 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, - )? - .ok_or_else(|| { - PlatformWalletError::InvalidIdentityData( - "No HIGH or CRITICAL authentication key found on identity \ - (required for document state transitions)" - .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; @@ -548,3 +526,210 @@ impl IdentityWallet { }) } } + +#[cfg(test)] +mod signing_key_tests { + 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() { + let dpns = 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), + SecurityLevel::HIGH, + dpns, + ) + .unwrap(); + assert_eq!( + chosen.map(|key| key.id()), + Some(2), + "a key bound to `domain` cannot sign the `preorder` document" + ); + } + + /// 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_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, + Some(ContractBounds::SingleContractDocumentType { + id: SystemDataContract::DPNS.id(), + document_type_name: "domain".to_string(), + }), + ); + // `KeyFilter` panics if anything is signed + 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!( + signature_refusal_of(&error), + Some(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!( + signature_refusal_of(&error), + Some(SignatureError::InvalidSignaturePublicKeySecurityLevelError( + _ + )) + ), + "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:?}" + ); + } + + #[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), + ) + .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 a448db29490..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 @@ -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; @@ -34,9 +33,8 @@ 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, KeyType, Purpose}; +use dpp::identity::{IdentityPublicKey, Purpose, SecurityLevel}; use dpp::platform_value::btreemap_extensions::BTreeValueMapHelper; use dpp::platform_value::Value; use dpp::prelude::{DataContract, Identifier}; @@ -55,7 +53,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, WALLET_SIGNING_KEY_TYPES}; use super::*; /// DPNS document type carrying registered names. @@ -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); @@ -947,17 +960,19 @@ 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 - /// layer's hardcoded "key id 1". + /// 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". 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| { @@ -966,7 +981,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 +993,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 \ - {required_level} found on identity {identity_id} \ - (required to sign a DPNS domain state transition)" - )) - }) + document_signing_key( + &identity, + signer, + required_level, + SigningScope::DocumentType { + contract_id: contract.id(), + document_type_name: DPNS_DOCUMENT_TYPE, + }, + )? + .cloned() + .ok_or_else(|| PlatformWalletError::NoUsableSigningKey { + identity_id: *identity_id, + purpose: Purpose::AUTHENTICATION, + security_levels: SecurityLevel::accepted_for_requirement(required_level), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: format!("a DPNS {DPNS_DOCUMENT_TYPE} document transition"), + }) } // ----------------------------------------------------------------- @@ -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), } @@ -2281,6 +2304,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 a1cde7283a6..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 @@ -1,83 +1,375 @@ -//! 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, + InvalidIdentityPublicKeyTypeError, InvalidSignaturePublicKeyPurposeError, + PublicKeyExpiredError, PublicKeyIsDisabledError, SignatureError, +}; +use dpp::consensus::ConsensusError; +use dpp::data_contract::document_type::accessors::DocumentTypeV0Getters; +use dpp::data_contract::document_type::DocumentTypeRef; +use dpp::data_contract::TokenContractPosition; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeyGettersV0; use dpp::identity::identity_public_key::accessors::v1::IdentityPublicKeyGettersV1; -use dpp::identity::identity_public_key::contract_bounds::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::ProtocolError; -use super::signing_key::first_available; -use crate::util::now_ms; +use super::signing_key::{first_available, require_available}; +use std::cmp::Reverse; +use std::time::{SystemTime, UNIX_EPOCH}; -/// 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. +/// 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. +/// 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`]. 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. +/// +/// `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)] +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 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, + }, + /// 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<'_> { + /// 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 ([`IdentityPublicKey::can_sign_non_batch`]). + pub fn bounds_check(&self, key: &IdentityPublicKey) -> BatchedTransitionBoundsCheck { + 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, + } => ( + contract_id, + ContractBoundsScope::DocumentType(document_type_name), + ), + SigningScope::DocumentCreate { ref document_type } => ( + document_type.data_contract_id(), + ContractBoundsScope::DocumentType(document_type.name()), + ), + SigningScope::Contract { contract_id } => (contract_id, ContractBoundsScope::Contract), + SigningScope::Token { + contract_id, + position, + } => (contract_id, ContractBoundsScope::Token(position)), + }; + let Some(bounds) = key + .contract_bounds() + .filter(|_| key.purpose() == Purpose::AUTHENTICATION) + else { + return BatchedTransitionBoundsCheck::Allowed; + }; + let check = bounds.check_scope(contract_id, bounds_scope); + let SigningScope::DocumentCreate { ref document_type } = *self else { + return check; + }; + if check != BatchedTransitionBoundsCheck::Allowed { + return check; + } + // Drive's batch structure validation: a create deletes the documents it consumes with + // the key that signs it, so the bounds must allow each consumed type too. + let covers_consumed = document_type + .consumable_document_type_names() + .into_iter() + .all(|consumed| { + bounds.check_scope(contract_id, ContractBoundsScope::DocumentType(consumed)) + == BatchedTransitionBoundsCheck::Allowed + }); + if covers_consumed { + BatchedTransitionBoundsCheck::Allowed + } else { + BatchedTransitionBoundsCheck::Denied + } + } +} + +/// 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 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. /// /// `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> { + 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 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) + && !expired_or_unknown(key, now) + && scope.bounds_check(key) == BatchedTransitionBoundsCheck::Allowed }; - let keys = identity.public_keys(); - let unlimited = keys - .values() - .filter(|key| qualifies(key) && !key.has_limits()); - let limited = keys + let mut candidates: Vec<&IdentityPublicKey> = identity + .public_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 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(), + ) + }); + first_available(candidates.into_iter(), 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 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 (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 +/// Unix epoch, since its expiry cannot be checked. +pub fn check_signing_key( + key: &IdentityPublicKey, + signer: &impl Signer, + purposes: &[Purpose], + 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> { + // 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( + InvalidSignaturePublicKeyPurposeError::new(key.purpose(), purposes.to_vec()), + ), + )); + } + if !security_levels.contains(&key.security_level()) { + return Err(signature_refusal( + SignatureError::InvalidSignaturePublicKeySecurityLevelError( + InvalidSignaturePublicKeySecurityLevelError::new( + key.security_level(), + security_levels.to_vec(), + ), + ), + )); + } + if key.is_disabled() { + return Err(signature_refusal(SignatureError::PublicKeyIsDisabledError( + PublicKeyIsDisabledError::new(key.id()), + ))); + } + 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()), + ), + )); + } + } + 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(|_| ()) +} + +/// 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() +} + +/// 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, 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)] -mod tests { +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; use dpp::identity::v0::IdentityV0; use dpp::identity::KeyID; @@ -88,11 +380,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, @@ -109,7 +401,7 @@ mod tests { }) } - fn identity(keys: Vec) -> Identity { + pub(crate) fn identity(keys: Vec) -> Identity { IdentityV0 { id: Identifier::from([1; 32]), public_keys: keys @@ -135,7 +427,14 @@ 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() { @@ -163,10 +462,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 +616,589 @@ 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_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_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![ + 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![ + 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, + } + } + + /// 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 { + 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 { + 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_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()) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::InvalidSignaturePublicKeySecurityLevelError( + _ + )) + )); + let mut eddsa = key(1, SecurityLevel::HIGH); + eddsa.set_key_type(KeyType::EDDSA_25519_HASH160); + assert!(matches!( + check(&eddsa, 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()) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::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}"); + } + + #[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 + )); + } + + #[test] + fn should_deny_a_non_batch_signature_exactly_when_dpp_says_the_key_cannot_sign_one() { + // 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, + 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:?}" + ); + } + } + } + + #[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:?}" + ); + } + + #[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 + ); + } + + #[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::EDDSA_25519_HASH160); + let refusal = check(&both_wrong, document_scope()); + assert!( + matches!( + refusal.as_ref().err().and_then(signature_refusal_of), + Some(SignatureError::InvalidIdentityPublicKeyTypeError(_)) + ), + "{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(_) + )); + } + + #[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" + ); + } } 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 e8af7ec0136..c515333e9a4 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/mod.rs @@ -50,7 +50,14 @@ 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, + WALLET_SIGNING_KEY_TYPES, +}; mod withdrawal; pub(crate) use withdrawal::{select_owner_withdrawal_key, select_transfer_withdrawal_key}; @@ -79,6 +86,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/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-platform-wallet/src/wallet/identity/network/signing_key.rs b/packages/rs-platform-wallet/src/wallet/identity/network/signing_key.rs index 4853014ffcf..29aa6e7bef1 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,13 @@ //! Signer-aware identity key selection shared by wallet operations. +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::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::identity::{Identity, IdentityPublicKey, Purpose, SecurityLevel}; use dpp::ProtocolError; /// Preserve the signer's unavailable-key discriminator through SDK and FFI errors. @@ -44,60 +47,92 @@ 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>; +/// 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: 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, + security_levels, + &WALLET_SIGNING_KEY_TYPES, + SigningScope::NonBatch, + ) } -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 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> { + usable_signing_key( + identity, + signer, + Purpose::AUTHENTICATION, + &MASTER_SIGNING_LEVELS, + &WALLET_SIGNING_KEY_TYPES, + SigningScope::NonBatch, + ) } -/// Respect explicit keys; automatic withdrawals exhaust TRANSFER before OWNER. -pub(super) fn credit_signing_key<'a>( +/// 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. 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>, 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); + check_signing_key( + key, + signer, + &purposes, + &CREDIT_SIGNING_LEVELS, + &PLATFORM_SIGNING_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)) - { - match identity.available_signing_key( + for purpose in purposes { + match usable_signing_key( + identity, signer, purpose, - &SecurityLevel::full_range(), - &KeyType::all_key_types(), - true, + &CREDIT_SIGNING_LEVELS, + &PLATFORM_SIGNING_KEY_TYPES, + SigningScope::NonBatch, ) { Ok(Some(key)) => return Ok(key), Ok(None) => {} @@ -116,14 +151,20 @@ pub(super) fn credit_signing_key<'a>( #[cfg(test)] pub(super) mod tests { + 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; + use dpp::identity::KeyType; 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); @@ -221,15 +262,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)); @@ -248,8 +289,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!( @@ -267,7 +314,110 @@ pub(super) mod tests { } #[test] - fn should_exhaust_transfer_keys_including_disabled_before_owner_fallback() { + 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.as_ref().err().and_then(signature_refusal_of), + Some(SignatureError::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( + 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_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( Purpose::TRANSFER, SecurityLevel::CRITICAL, @@ -285,10 +435,107 @@ 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_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), + &CONTRACT_UPDATE_SIGNING_LEVELS, + ) + .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_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( + 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] @@ -334,6 +581,74 @@ 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); + 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) + .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) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::PublicKeyIsDisabledError(_)) + ), + "Platform refuses a disabled signing key" + ); + 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_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!( + matches!( + explicit(5, false) + .as_ref() + .err() + .and_then(signature_refusal_of), + Some(SignatureError::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); + } + #[tokio::test] async fn should_surface_unavailable_signer_from_credit_operations() { let wallet = wallet_with_signing_keys().await; @@ -364,6 +679,55 @@ 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_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:?}" + ); + } + /// Records every changeset, so a test can read what reached the store. #[derive(Default)] pub(crate) struct CapturingStore( @@ -415,10 +779,12 @@ pub(super) mod tests { } } - pub(crate) async fn wallet_with_signing_keys() -> std::sync::Arc { + pub(crate) async fn wallet_with_signing_keys() -> Arc { + use crate::wallet::persister::NoPlatformPersistence; + wallet_with_signing_keys_on( dash_sdk::SdkBuilder::new_mock().build().unwrap(), - std::sync::Arc::new(crate::wallet::persister::NoPlatformPersistence), + Arc::new(NoPlatformPersistence), ) .await } @@ -427,15 +793,50 @@ pub(super) mod tests { /// that sets mock expectations first or reads what was persisted. pub(crate) async fn wallet_with_signing_keys_on

( sdk: dash_sdk::Sdk, - persistence: std::sync::Arc

, - ) -> std::sync::Arc + persistence: Arc

, + ) -> Arc + where + P: crate::changeset::PlatformWalletPersistence + 'static, + { + wallet_with_identity_in( + sdk, + persistence, + 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 { + 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::wallet::persister::NoPlatformPersistence; + + wallet_with_identity_in(sdk, Arc::new(NoPlatformPersistence), identity).await + } + + /// A wallet on `sdk` and `persistence` that owns `identity`. + async fn wallet_with_identity_in

( + sdk: dash_sdk::Sdk, + persistence: Arc

, + identity: Identity, + ) -> Arc where P: crate::changeset::PlatformWalletPersistence + 'static, { use crate::events::{EventHandler, PlatformEventHandler}; use crate::PlatformWalletManager; use key_wallet::wallet::initialization::WalletAccountCreationOptions; - use std::sync::Arc; struct Events; impl EventHandler for Events {} @@ -455,11 +856,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, @@ -468,6 +865,108 @@ 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, + key_types, + .. + } if *identity_id == identity + && security_levels == &[level] + && key_types == &WALLET_SIGNING_KEY_TYPES + ), + "{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() + .update_data_contract_with_signer( + &identity_id, + &Identifier::from([0x0C; 32]), + "{}", + None, + None, + None, + None, + None, + &KeyFilter(|_| true), + ) + .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] + 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/burn.rs b/packages/rs-platform-wallet/src/wallet/identity/network/tokens/burn.rs index f8640ad1631..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -32,6 +34,14 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::burn::TokenBurnTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::Burn, + )?; + let mut builder = TokenBurnTransitionBuilder::new(data_contract, token_position, identity_id, amount); @@ -63,7 +73,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::Burn, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -30,6 +32,14 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::claim::TokenClaimTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::Claim, + )?; + let mut builder = TokenClaimTransitionBuilder::new( data_contract, token_position, @@ -60,7 +70,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::Claim, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -34,6 +36,14 @@ impl IdentityWallet { { use dash_sdk::platform::tokens::builders::destroy::TokenDestroyFrozenFundsTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::DestroyFrozenFunds, + )?; + let mut builder = TokenDestroyFrozenFundsTransitionBuilder::new( data_contract, token_position, @@ -73,7 +83,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::DestroyFrozenFunds, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -31,6 +33,14 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::freeze::TokenFreezeTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::Freeze, + )?; + let mut builder = TokenFreezeTransitionBuilder::new( data_contract, token_position, @@ -66,7 +76,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::Freeze, + ) + .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..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 @@ -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_SECP256K1 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 @@ -12,33 +11,115 @@ //! 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::{ + check_signing_key, usable_signing_key, SigningScope, PLATFORM_SIGNING_KEY_TYPES, + WALLET_SIGNING_KEY_TYPES, +}; use std::sync::Arc; -use dpp::data_contract::DataContract; +use dpp::data_contract::accessors::v0::DataContractV0Getters; +use dpp::data_contract::{DataContract, TokenContractPosition}; use dpp::identity::signer::Signer; -use dpp::identity::{IdentityPublicKey, KeyType, Purpose, SecurityLevel}; +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; 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 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 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, + action: TokenTransitionActionType, +) -> Result, dash_sdk::Error> { + for &purpose in token_signing_purposes(action) { + let key = usable_signing_key( + identity, + signer, + purpose, + &TOKEN_SIGNING_LEVELS, + &WALLET_SIGNING_KEY_TYPES, + SigningScope::Token { + contract_id: token_contract_id, + position, + }, + )?; + if key.is_some() { + return Ok(key); + } + } + Ok(None) +} + +/// 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, + action: TokenTransitionActionType, +) -> Result<(), dash_sdk::Error> { + check_signing_key( + key, + signer, + token_signing_purposes(action), + &TOKEN_SIGNING_LEVELS, + &PLATFORM_SIGNING_KEY_TYPES, + SigningScope::Token { + contract_id: data_contract.id(), + position, + }, + ) +} + 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` × `ECDSA_SECP256K1`. + /// 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 /// key matches what the state transition needs. pub(super) async fn token_resolve_signing_key( &self, identity_id: &Identifier, + token_contract_id: Identifier, + token_position: TokenContractPosition, signer: &impl Signer, + action: TokenTransitionActionType, ) -> Result { let wm = self.wallet_manager.read().await; let info = wm @@ -52,23 +133,16 @@ 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, - )? - .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 - )) - })? - .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) } @@ -109,9 +183,243 @@ 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, + }; 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::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::{ + IdentityPublicKeyGettersV0, 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; + + /// 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!( + signature_refusal_of(&transfer), + Some(SignatureError::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_eq!( + refused_purposes(&burn), + Some(vec![Purpose::AUTHENTICATION]), + "only a lone transfer or claim takes a TRANSFER key: {burn:?}" + ); + } + + #[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; + let contract = some_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!( + signature_refusal_of(&error), + Some(SignatureError::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( + 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(), + 0, + &KeyFilter(|_| true), + TokenTransitionActionType::Burn, + ) + .await + .unwrap_err(); + assert_no_usable_key(error, identity_id, SecurityLevel::CRITICAL); + } #[tokio::test] async fn should_check_token_key_availability_outside_wallet_lock() { @@ -119,9 +427,196 @@ 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(), + 0, + &signer, + TokenTransitionActionType::Burn, + ) .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 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, + 0, + &KeyFilter(|_| true), + TokenTransitionActionType::Burn, + ) + .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" + ); + } + #[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), + TokenTransitionActionType::Transfer, + ) + .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), + TokenTransitionActionType::Burn, + ) + .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, + TokenTransitionActionType::Transfer, + ) + .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" + ); + 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; + + 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 483f613503a..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -41,6 +43,14 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::mint::TokenMintTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::Mint, + )?; + // Contracts with `minting_allow_choosing_destination = false` // reject any mint where `issued_to_identity_id.is_some()` at // execution time (rs-drive's TokenMintTransitionTransformer @@ -118,7 +128,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::Mint, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -32,6 +34,14 @@ impl IdentityWallet { { use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::EmergencyAction, + )?; + let mut builder = TokenEmergencyActionTransitionBuilder::pause( data_contract, token_position, @@ -66,7 +76,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::EmergencyAction, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -38,6 +40,14 @@ impl IdentityWallet { { use dash_sdk::platform::tokens::builders::purchase::TokenDirectPurchaseTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::DirectPurchase, + )?; + let mut builder = TokenDirectPurchaseTransitionBuilder::new( data_contract, token_position, @@ -65,7 +75,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::DirectPurchase, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -31,6 +33,14 @@ impl IdentityWallet { { use dash_sdk::platform::tokens::builders::emergency_action::TokenEmergencyActionTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::EmergencyAction, + )?; + let mut builder = TokenEmergencyActionTransitionBuilder::resume( data_contract, token_position, @@ -65,7 +75,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::EmergencyAction, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -39,6 +41,14 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::set_price::TokenChangeDirectPurchasePriceTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::SetPriceForDirectPurchase, + )?; + let mut builder = TokenChangeDirectPurchasePriceTransitionBuilder::new( data_contract, token_position, @@ -83,7 +93,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::SetPriceForDirectPurchase, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -34,6 +36,14 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::transfer::TokenTransferTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::Transfer, + )?; + let mut builder = TokenTransferTransitionBuilder::new( data_contract, token_position, @@ -69,7 +79,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, signer) + .token_resolve_signing_key( + &from_identity_id, + token_contract_id, + token_position, + signer, + TokenTransitionActionType::Transfer, + ) .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -31,6 +33,14 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::unfreeze::TokenUnfreezeTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::Unfreeze, + )?; + let mut builder = TokenUnfreezeTransitionBuilder::new( data_contract, token_position, @@ -68,7 +78,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::Unfreeze, + ) + .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..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,7 +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; use crate::broadcaster::TransactionBroadcaster; use crate::error::PlatformWalletError; use crate::wallet::identity::network::IdentityWallet; @@ -33,6 +35,14 @@ impl IdentityWallet { ) -> Result { use dash_sdk::platform::tokens::builders::config_update::TokenConfigUpdateTransitionBuilder; + check_token_signing_key( + signing_key, + signer, + &data_contract, + token_position, + TokenTransitionActionType::ConfigUpdate, + )?; + let mut builder = TokenConfigUpdateTransitionBuilder::new( data_contract, token_position, @@ -72,7 +82,15 @@ 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, + token_position, + signer, + TokenTransitionActionType::ConfigUpdate, + ) + .await?; self.token_update_config_with_signer( data_contract, 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 e8a3777fb63..73cb4af1747 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/update.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/update.rs @@ -9,10 +9,7 @@ use dpp::identity::identity_public_key::accessors::v0::{ IdentityPublicKeyGettersV0, IdentityPublicKeySettersV0, }; use dpp::identity::Identity; -use dpp::identity::IdentityPublicKey; -use dpp::identity::KeyType; -use dpp::identity::Purpose; -use dpp::identity::SecurityLevel; +use dpp::identity::{IdentityPublicKey, Purpose}; use dpp::platform_value::BinaryData; use dpp::prelude::Identifier; use dpp::ProtocolError; @@ -25,7 +22,8 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use crate::changeset::{KeyWithBreadcrumb, PersistenceError}; use crate::error::{as_identity_revision_invalid, PlatformWalletError}; -use super::signing_key::AvailableSigningKey; +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. @@ -146,19 +144,14 @@ 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( - "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(), + key_types: WALLET_SIGNING_KEY_TYPES.to_vec(), + transition: "an identity update".to_string(), })?; let identity_nonce = self @@ -518,6 +511,7 @@ mod update_identity_tests { use crate::PlatformWallet; use dpp::identity::identity_public_key::accessors::v0::IdentityPublicKeySettersV0; use dpp::identity::identity_public_key::v0::IdentityPublicKeyV0; + use dpp::identity::{KeyType, SecurityLevel}; use std::sync::atomic::Ordering; use std::sync::Arc; 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, diff --git a/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs b/packages/rs-platform-wallet/src/wallet/masternode_withdrawal.rs index e90851b9fb5..3453e1e0afc 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,85 @@ 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:?}" + ); + + // 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!( + 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:?}" + ); + } } diff --git a/packages/rs-sdk/src/platform/dashpay/contact_request.rs b/packages/rs-sdk/src/platform/dashpay/contact_request.rs index 3f528a4bba6..731fcf8a484 100644 --- a/packages/rs-sdk/src/platform/dashpay/contact_request.rs +++ b/packages/rs-sdk/src/platform/dashpay/contact_request.rs @@ -7,12 +7,13 @@ 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::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; @@ -23,6 +24,42 @@ use platform_encryption::{ }; use std::collections::BTreeMap; +/// 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 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, +} + +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.contact_request_document_type + .as_ref() + .data_contract_id() + } +} + /// ECDH provider for contact request encryption /// /// Supports two modes: @@ -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: 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_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 { + 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 @@ -575,8 +659,10 @@ impl Sdk { #[cfg(test)] mod tests { use super::*; + 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() { @@ -786,4 +872,120 @@ mod tests { "Both parties should derive the same shared secret" ); } + + /// A context provider holding `contract`, if any, for every id and protocol version. + struct DashPayProvider { + contract: Option>, + } + + impl dash_context_provider::ContextProvider for DashPayProvider { + fn get_data_contract( + &self, + _id: &Identifier, + _platform_version: &dpp::version::PlatformVersion, + ) -> Result>, dash_context_provider::ContextProviderError> + { + Ok(self.contract.clone()) + } + + 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) + } + } + + /// 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 dpp::identity::SecurityLevel; + use dpp::system_data_contracts::{load_system_data_contract, SystemDataContract}; + use dpp::version::PlatformVersion; + + 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 + .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 + ); + 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::{ diff --git a/packages/rs-sdk/src/platform/dpns_usernames/mod.rs b/packages/rs-sdk/src/platform/dpns_usernames/mod.rs index d4677138e99..df9a34154ca 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; @@ -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::future::Future; use std::sync::Arc; use tracing::debug; @@ -240,6 +241,8 @@ 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, } /// How many DPNS contract responses a registration reads for one proved at the protocol @@ -281,6 +284,62 @@ where ))) } +/// 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. +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. + 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 + } +} + impl Sdk { /// Helper method to get the DPNS contract ID fn get_dpns_contract_id(&self) -> Result { @@ -448,6 +507,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 +517,7 @@ impl Sdk { domain_document_type: domain_document_type.to_owned_document_type(), domain_document, normalized_label, + signing_requirement, }) } @@ -500,17 +563,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 +641,8 @@ impl Sdk { "preorder".to_string(), &expiring, ), - &input.identity_public_key, - &input.signer, + &identity_public_key, + signer, ) .await .inspect_err(|error| { @@ -549,9 +656,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 +670,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 +688,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 +1196,103 @@ 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 { + 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] + 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()); + } + + #[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; diff --git a/packages/rs-sdk/src/platform/system_data_contract.rs b/packages/rs-sdk/src/platform/system_data_contract.rs index 66953140548..208d9c38df1 100644 --- a/packages/rs-sdk/src/platform/system_data_contract.rs +++ b/packages/rs-sdk/src/platform/system_data_contract.rs @@ -22,3 +22,37 @@ impl Sdk { Ok(DataContract::fetch(self, contract_id).await?.map(Arc::new)) } } + +#[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") + } +}