diff --git a/packages/rs-dapi/src/services/platform_service/shielded_proof_failure_budget.rs b/packages/rs-dapi/src/services/platform_service/shielded_proof_failure_budget.rs index 92c50e9eb2b..35928262747 100644 --- a/packages/rs-dapi/src/services/platform_service/shielded_proof_failure_budget.rs +++ b/packages/rs-dapi/src/services/platform_service/shielded_proof_failure_budget.rs @@ -20,6 +20,11 @@ use std::time::{Duration, Instant}; use dpp::serialization::PlatformDeserializableUntrusted; use dpp::state_transition::StateTransition; +use dpp::state_transition::batch_transition::accessors::DocumentsBatchTransitionAccessorsV0; +use dpp::state_transition::batch_transition::batched_transition::BatchedTransitionRef; +use dpp::state_transition::batch_transition::batched_transition::document_transition::DocumentTransitionV0Methods; +use dpp::state_transition::batch_transition::batched_transition::token_transition::TokenTransitionV0Methods; +use dpp::state_transition::batch_transition::document_base_transition::v1::v1_methods::DocumentBaseTransitionV1Methods; use dpp::state_transition::identity_create_from_shielded_pool_transition::IdentityCreateFromShieldedPoolTransition; use dpp::state_transition::identity_top_up_from_shielded_pool_transition::IdentityTopUpFromShieldedPoolTransition; use dpp::state_transition::private_document_create_from_shielded_pool_transition::PrivateDocumentCreateFromShieldedPoolTransition; @@ -28,7 +33,11 @@ use dpp::state_transition::shield_from_identity_transition::ShieldFromIdentityTr use dpp::state_transition::shield_transition::ShieldTransition; use dpp::state_transition::shielded_transfer_transition::ShieldedTransferTransition; use dpp::state_transition::shielded_withdrawal_transition::ShieldedWithdrawalTransition; +use dpp::state_transition::token_purchase_from_shielded_pool_transition::TokenPurchaseFromShieldedPoolTransition; +use dpp::state_transition::token_shielded_transfer_with_shielded_fee_transition::TokenShieldedTransferWithShieldedFeeTransition; +use dpp::state_transition::token_unshield_with_shielded_fee_transition::TokenUnshieldWithShieldedFeeTransition; use dpp::state_transition::unshield_transition::UnshieldTransition; +use dpp::tokens::token_payment_info::v1::v1_accessors::TokenPaymentInfoAccessorsV1; use dpp::version::PlatformVersion; use tonic::Request; @@ -111,7 +120,10 @@ fn last_forwarded_address(header: &str) -> Option { /// Orchard actions whose proof Drive verifies before admitting the transition, /// or 0 for bytes without any (including bytes that do not decode, which Drive -/// refuses before any proof work). +/// refuses before any proof work). The same count Drive's CheckTx proof +/// admission takes (`shielded_proof_action_count` in drive-abci). Every kind +/// and version is named, so a new one has to say whether it carries actions +/// before this compiles. pub(super) fn orchard_action_count(state_transition_bytes: &[u8]) -> usize { let Ok(state_transition) = StateTransition::deserialize_from_bytes_untrusted(state_transition_bytes) @@ -125,6 +137,9 @@ pub(super) fn orchard_action_count(state_transition_bytes: &[u8]) -> usize { StateTransition::ShieldFromAssetLock(ShieldFromAssetLockTransition::V0(v0)) => { v0.actions.len() } + StateTransition::ShieldFromAssetLock(ShieldFromAssetLockTransition::V1(v1)) => { + v1.actions.len() + } StateTransition::ShieldedWithdrawal(ShieldedWithdrawalTransition::V0(v0)) => { v0.actions.len() } @@ -140,7 +155,51 @@ pub(super) fn orchard_action_count(state_transition_bytes: &[u8]) -> usize { StateTransition::PrivateDocumentCreateFromShieldedPool( PrivateDocumentCreateFromShieldedPoolTransition::V0(v0), ) => v0.actions.len(), - _ => 0, + // A token pool transition carries two bundles, one against the token's + // pool and one paying the fee from the credit shielded pool; Drive + // verifies both. + StateTransition::TokenShieldedTransferWithShieldedFee( + TokenShieldedTransferWithShieldedFeeTransition::V0(v0), + ) => v0.token_actions.len() + v0.fee_actions.len(), + StateTransition::TokenUnshieldWithShieldedFee( + TokenUnshieldWithShieldedFeeTransition::V0(v0), + ) => v0.token_actions.len() + v0.fee_actions.len(), + StateTransition::TokenPurchaseFromShieldedPool( + TokenPurchaseFromShieldedPoolTransition::V0(v0), + ) => v0.token_actions.len() + v0.fee_actions.len(), + // A batch carries a bundle for each token transition against a token's + // shielded pool and each document whose token price is paid from one. + StateTransition::Batch(batch) => batch + .transitions_iter() + .map(|transition| match transition { + BatchedTransitionRef::Token(token_transition) => token_transition + .shielded_pool_actions() + .map_or(0, |actions| actions.len()), + BatchedTransitionRef::Document(document_transition) => document_transition + .base() + .token_payment_info_ref() + .as_ref() + .and_then(|info| info.shielded_payment()) + .map_or(0, |payment| payment.actions.len()), + }) + .sum(), + StateTransition::DataContractCreate(_) + | StateTransition::DataContractUpdate(_) + | StateTransition::IdentityCreate(_) + | StateTransition::IdentityTopUp(_) + | StateTransition::IdentityCreditWithdrawal(_) + | StateTransition::IdentityUpdate(_) + | StateTransition::IdentityCreditTransfer(_) + | StateTransition::MasternodeVote(_) + | StateTransition::IdentityCreditTransferToAddresses(_) + | StateTransition::IdentityCreateFromAddresses(_) + | StateTransition::IdentityTopUpFromAddresses(_) + | StateTransition::AddressFundsTransfer(_) + | StateTransition::AddressFundingFromAssetLock(_) + | StateTransition::AddressCreditWithdrawal(_) + | StateTransition::IdentityKeyLimitsUpdate(_) + | StateTransition::ContractUserModeration(_) + | StateTransition::ContractFeeClaim(_) => 0, } } @@ -329,11 +388,34 @@ mod tests { use dpp::consensus::codes::ErrorWithCode; use dpp::consensus::state::shielded::invalid_shielded_proof_error::InvalidShieldedProofError; use dpp::consensus::state::state_error::StateError; + use dpp::identity::state_transition::asset_lock_proof::AssetLockProof; + use dpp::identity::state_transition::asset_lock_proof::chain::ChainAssetLockProof; use dpp::platform_value::{BinaryData, Identifier}; use dpp::serialization::PlatformSerializable; use dpp::shielded::SerializedAction; + use dpp::state_transition::batch_transition::batched_transition::BatchedTransition; + use dpp::state_transition::batch_transition::batched_transition::document_transition::DocumentTransition; + use dpp::state_transition::batch_transition::batched_transition::token_transition::TokenTransition; + use dpp::state_transition::batch_transition::document_base_transition::DocumentBaseTransition; + use dpp::state_transition::batch_transition::document_base_transition::v1::DocumentBaseTransitionV1; + use dpp::state_transition::batch_transition::document_delete_transition::DocumentDeleteTransitionV0; + use dpp::state_transition::batch_transition::token_base_transition::TokenBaseTransition; + use dpp::state_transition::batch_transition::token_base_transition::v0::TokenBaseTransitionV0; + use dpp::state_transition::batch_transition::token_burn_transition::TokenBurnTransitionV0; + use dpp::state_transition::batch_transition::token_shielded_transfer_transition::TokenShieldedTransferTransitionV0; + use dpp::state_transition::batch_transition::{ + BatchTransition, BatchTransitionV1, DocumentDeleteTransition, TokenBurnTransition, + TokenShieldedTransferTransition, + }; use dpp::state_transition::private_document_create_from_shielded_pool_transition::v0::PrivateDocumentCreateFromShieldedPoolTransitionV0; + use dpp::state_transition::shield_from_asset_lock_transition::v1::ShieldFromAssetLockTransitionV1; use dpp::state_transition::shielded_transfer_transition::v0::ShieldedTransferTransitionV0; + use dpp::state_transition::token_purchase_from_shielded_pool_transition::v0::TokenPurchaseFromShieldedPoolTransitionV0; + use dpp::state_transition::token_shielded_transfer_with_shielded_fee_transition::v0::TokenShieldedTransferWithShieldedFeeTransitionV0; + use dpp::state_transition::token_unshield_with_shielded_fee_transition::v0::TokenUnshieldWithShieldedFeeTransitionV0; + use dpp::tokens::gas_fees_paid_by::GasFeesPaidBy; + use dpp::tokens::token_payment_info::TokenPaymentInfo; + use dpp::tokens::token_payment_info::v1::{TokenPaymentInfoV1, TokenShieldedPayment}; use std::net::Ipv6Addr; const SOURCE: SourceKey = SourceKey::V4(Ipv4Addr::new(203, 0, 113, 7)); @@ -633,4 +715,200 @@ mod tests { "a third failing create waits until one bundle has drained" ); } + + fn actions(count: usize) -> Vec { + vec![ + SerializedAction { + nullifier: [1; 32], + rk: [2; 32], + cmx: [3; 32], + encrypted_note: vec![4; 216], + cv_net: [5; 32], + spend_auth_sig: [6; 64], + }; + count + ] + } + + /// A token pool transition carrying a 3-action token bundle and a 2-action + /// fee bundle is charged 5 actions when its proof fails. That is more than + /// the 4-action allowance, so after one failure the source waits until all + /// 5 have drained. + fn assert_both_bundles_metered(transition: StateTransition) { + let actions = orchard_action_count(&transition.serialize_to_bytes().unwrap()); + assert_eq!(actions, 5, "the token bundle and the fee bundle both count"); + + let budget = budget(); + let now = Instant::now(); + broadcast(&budget, SOURCE, actions, true, now).expect("a clean source is admitted"); + assert_eq!( + broadcast(&budget, SOURCE, actions, true, now), + Err(ACTION_DRAIN_INTERVAL * 5), + "a second failing broadcast waits until the first has drained" + ); + } + + #[test] + fn should_meter_a_token_shielded_transfer_with_shielded_fee_and_refuse_a_failing_source() { + assert_both_bundles_metered(StateTransition::TokenShieldedTransferWithShieldedFee( + TokenShieldedTransferWithShieldedFeeTransition::V0( + TokenShieldedTransferWithShieldedFeeTransitionV0 { + data_contract_id: Identifier::from([9; 32]), + token_contract_position: 0, + token_id: Identifier::from([8; 32]), + token_actions: actions(3), + token_anchor: [7; 32], + token_proof: vec![0; 100], + token_binding_signature: [0; 64], + fee_actions: actions(2), + fee_anchor: [7; 32], + fee_proof: vec![0; 100], + fee_binding_signature: [0; 64], + credit_amount: 1, + }, + ), + )); + } + + #[test] + fn should_meter_a_token_unshield_with_shielded_fee_and_refuse_a_failing_source() { + assert_both_bundles_metered(StateTransition::TokenUnshieldWithShieldedFee( + TokenUnshieldWithShieldedFeeTransition::V0(TokenUnshieldWithShieldedFeeTransitionV0 { + data_contract_id: Identifier::from([9; 32]), + token_contract_position: 0, + token_id: Identifier::from([8; 32]), + recipient_id: Identifier::from([5; 32]), + amount: 1, + token_actions: actions(3), + token_anchor: [7; 32], + token_proof: vec![0; 100], + token_binding_signature: [0; 64], + fee_actions: actions(2), + fee_anchor: [7; 32], + fee_proof: vec![0; 100], + fee_binding_signature: [0; 64], + credit_amount: 1, + }), + )); + } + + #[test] + fn should_meter_a_token_purchase_from_shielded_pool_and_refuse_a_failing_source() { + assert_both_bundles_metered(StateTransition::TokenPurchaseFromShieldedPool( + TokenPurchaseFromShieldedPoolTransition::V0( + TokenPurchaseFromShieldedPoolTransitionV0 { + data_contract_id: Identifier::from([9; 32]), + token_contract_position: 0, + token_id: Identifier::from([8; 32]), + token_count: 1, + total_agreed_price: 1, + token_actions: actions(3), + token_anchor: [7; 32], + token_proof: vec![0; 100], + token_binding_signature: [0; 64], + fee_actions: actions(2), + fee_anchor: [7; 32], + fee_proof: vec![0; 100], + fee_binding_signature: [0; 64], + credit_amount: 1, + }, + ), + )); + } + + /// Version 1 is the only shield from an asset lock protocol version 14 + /// admits. + #[test] + fn should_count_the_actions_of_a_shield_from_asset_lock_v1() { + let shield = StateTransition::ShieldFromAssetLock(ShieldFromAssetLockTransition::V1( + ShieldFromAssetLockTransitionV1 { + asset_lock_proof: AssetLockProof::Chain(ChainAssetLockProof::new(1, [1; 36])), + actions: actions(2), + value_balance: 1, + anchor: [7; 32], + proof: vec![0; 100], + binding_signature: [0; 64], + surplus_output: None, + signature: BinaryData::new(vec![0; 65]), + }, + )); + assert_eq!( + orchard_action_count(&shield.serialize_to_bytes().unwrap()), + 2 + ); + } + + #[test] + fn should_count_the_pool_bundles_of_a_batch() { + let token_base = TokenBaseTransition::V0(TokenBaseTransitionV0 { + identity_contract_nonce: 1, + token_contract_position: 0, + data_contract_id: Identifier::from([9; 32]), + token_id: Identifier::from([8; 32]), + using_group_info: None, + }); + let burn = BatchedTransition::Token(TokenTransition::Burn(TokenBurnTransition::V0( + TokenBurnTransitionV0 { + base: token_base.clone(), + burn_amount: 1, + public_note: None, + }, + ))); + let shielded_transfer = BatchedTransition::Token(TokenTransition::ShieldedTransfer( + TokenShieldedTransferTransition::V0(TokenShieldedTransferTransitionV0 { + base: token_base, + actions: actions(2), + anchor: [7; 32], + proof: vec![0; 100], + binding_signature: [0; 64], + }), + )); + let paid_from_pool = BatchedTransition::Document(DocumentTransition::Delete( + DocumentDeleteTransition::V0(DocumentDeleteTransitionV0 { + base: DocumentBaseTransition::V1(DocumentBaseTransitionV1 { + id: Identifier::from([4; 32]), + identity_contract_nonce: 1, + document_type_name: "note".to_string(), + data_contract_id: Identifier::from([9; 32]), + token_payment_info: Some(TokenPaymentInfo::V1(TokenPaymentInfoV1 { + payment_token_contract_id: None, + token_contract_position: 0, + minimum_token_cost: None, + maximum_token_cost: Some(1), + gas_fees_paid_by: GasFeesPaidBy::DocumentOwner, + shielded_payment: Box::new(TokenShieldedPayment { + amount: 1, + actions: actions(3), + anchor: [7; 32], + proof: vec![0; 100], + binding_signature: [0; 64], + }), + })), + }), + }), + )); + let count = |transitions| { + let batch = StateTransition::Batch(BatchTransition::V1(BatchTransitionV1 { + owner_id: Identifier::from([3; 32]), + transitions, + user_fee_increase: 0, + signature_public_key_id: 0, + signature: BinaryData::default(), + })); + orchard_action_count(&batch.serialize_to_bytes().unwrap()) + }; + + assert_eq!( + count(vec![burn.clone()]), + 0, + "a plain token burn is not metered" + ); + assert_eq!(count(vec![shielded_transfer.clone()]), 2); + assert_eq!(count(vec![paid_from_pool.clone()]), 3); + assert_eq!( + count(vec![shielded_transfer, burn, paid_from_pool]), + 5, + "every pool bundle in the batch counts" + ); + } } diff --git a/packages/rs-drive-abci/src/query/system/total_credits_in_platform/v0/mod.rs b/packages/rs-drive-abci/src/query/system/total_credits_in_platform/v0/mod.rs index 680716b4bb4..af8942c8479 100644 --- a/packages/rs-drive-abci/src/query/system/total_credits_in_platform/v0/mod.rs +++ b/packages/rs-drive-abci/src/query/system/total_credits_in_platform/v0/mod.rs @@ -140,13 +140,23 @@ impl Platform { #[cfg(test)] mod tests { use super::*; - use crate::query::tests::setup_platform; + use crate::query::tests::{assert_drive_part_of_proof_verified, setup_platform}; use crate::test::helpers::fast_forward_to_block::fast_forward_to_block; + use dapi_grpc::platform::v0::{ + get_total_credits_in_platform_request, get_total_credits_in_platform_response, + GetTotalCreditsInPlatformRequest, GetTotalCreditsInPlatformResponse, + }; use dpp::block::epoch::EpochIndex; use dpp::dashcore::Network; + use dpp::data_contract::{DataContract, TokenConfiguration}; use dpp::fee::Credits; + use dpp::identifier::Identifier; use dpp::prelude::CoreBlockHeight; use drive::drive::Drive; + use drive_proof_verifier::types::TotalCreditsInPlatform; + use drive_proof_verifier::{ContextProvider, ContextProviderError, FromProof}; + use std::sync::atomic::{AtomicBool, Ordering}; + use std::sync::Arc; fn test_query_total_system_credits( epoch_index: EpochIndex, @@ -215,12 +225,17 @@ mod tests { credits } - fn test_proved_query_total_system_credits( + /// The proved answer to a total credits query on a platform whose unpaid epoch is + /// `epoch_index`, and the platform version it was answered at. + fn proved_total_credits_response( epoch_index: EpochIndex, activation_core_height: CoreBlockHeight, epoch_core_start_height: CoreBlockHeight, current_core_height: CoreBlockHeight, - ) -> Credits { + ) -> ( + GetTotalCreditsInPlatformResponseV0, + &'static PlatformVersion, + ) { let (platform, _state, platform_version) = setup_platform(Some((1, activation_core_height)), Network::Regtest, None); @@ -257,7 +272,24 @@ mod tests { .query_total_credits_in_platform_v0(request, &state, platform_version) .expect("expected query to succeed"); - let response_data = response.into_data().expect("expected data"); + ( + response.into_data().expect("expected data"), + platform_version, + ) + } + + fn test_proved_query_total_system_credits( + epoch_index: EpochIndex, + activation_core_height: CoreBlockHeight, + epoch_core_start_height: CoreBlockHeight, + current_core_height: CoreBlockHeight, + ) -> Credits { + let (response_data, platform_version) = proved_total_credits_response( + epoch_index, + activation_core_height, + epoch_core_start_height, + current_core_height, + ); let get_total_credits_in_platform_response_v0::Result::Proof(proof) = response_data.result.expect("expected a result") @@ -334,4 +366,109 @@ mod tests { let proved = test_proved_query_total_system_credits(1, 1500, 2000, 2500); assert_eq!(non_proved, proved); } + + /// Not configured to give the platform activation height, and records whether it was + /// asked for it. Serves no quorum key, so verification stops at the signature check. + #[derive(Default)] + struct NoActivationHeightProvider { + asked: AtomicBool, + } + + impl ContextProvider for NoActivationHeightProvider { + fn get_data_contract( + &self, + _id: &Identifier, + _platform_version: &PlatformVersion, + ) -> Result>, ContextProviderError> { + Ok(None) + } + + fn get_token_configuration( + &self, + _token_id: &Identifier, + ) -> Result, ContextProviderError> { + Ok(None) + } + + fn get_quorum_public_key( + &self, + _quorum_type: u32, + _quorum_hash: [u8; 32], + _core_chain_locked_height: u32, + ) -> Result<[u8; 48], ContextProviderError> { + Err(ContextProviderError::InvalidQuorum( + "no quorum keys in this test".to_string(), + )) + } + + fn get_platform_activation_height(&self) -> Result { + self.asked.store(true, Ordering::SeqCst); + Err(ContextProviderError::Config( + "activation height is not configured".to_string(), + )) + } + } + + /// Verifies the proved answer for a platform whose unpaid epoch is `epoch_index` with + /// [`NoActivationHeightProvider`]: the verifier's error, and whether the provider was + /// asked for the activation height. + fn verify_without_activation_height( + epoch_index: EpochIndex, + activation_core_height: CoreBlockHeight, + epoch_core_start_height: CoreBlockHeight, + current_core_height: CoreBlockHeight, + ) -> (drive_proof_verifier::Error, bool) { + let (response, platform_version) = proved_total_credits_response( + epoch_index, + activation_core_height, + epoch_core_start_height, + current_core_height, + ); + let provider = NoActivationHeightProvider::default(); + let error = TotalCreditsInPlatform::maybe_from_proof_with_metadata( + GetTotalCreditsInPlatformRequest { + version: Some(get_total_credits_in_platform_request::Version::V0( + GetTotalCreditsInPlatformRequestV0 { prove: true }, + )), + }, + GetTotalCreditsInPlatformResponse { + version: Some(get_total_credits_in_platform_response::Version::V0( + response, + )), + }, + Network::Regtest, + platform_version, + &provider, + ) + .expect_err("no answer verifies without the activation height or a quorum key"); + (error, provider.asked.load(Ordering::SeqCst)) + } + + /// The first epoch's rewards start at the platform's activation height, which only the + /// context provider gives. A provider not configured to give it fails every node's answer + /// alike, so the verifier reports the provider's configuration error, for which the SDK + /// asks no other node and bans none. + #[test] + fn should_report_an_unconfigured_activation_height_as_the_provider_error() { + let (error, asked) = verify_without_activation_height(0, 1500, 1500, 1500); + assert!(asked, "the first epoch needs the activation height"); + assert!( + matches!( + &error, + drive_proof_verifier::Error::ContextProviderError(ContextProviderError::Config( + reason + )) if reason == "activation height is not configured" + ), + "{error:?}" + ); + } + + /// A later epoch's rewards start at a height the proof holds, so the activation height is + /// not asked for, and the Drive part of the proof verifies without it. + #[test] + fn should_not_ask_for_the_activation_height_after_the_first_epoch() { + let (error, asked) = verify_without_activation_height(1, 1500, 2000, 2500); + assert!(!asked, "a later epoch's start is in the proof"); + assert_drive_part_of_proof_verified(error); + } } diff --git a/packages/rs-drive-proof-verifier/src/proof.rs b/packages/rs-drive-proof-verifier/src/proof.rs index 3ea3056817f..761bba2b96e 100644 --- a/packages/rs-drive-proof-verifier/src/proof.rs +++ b/packages/rs-drive-proof-verifier/src/proof.rs @@ -56,7 +56,7 @@ use crate::from_request::TryFromRequest; use crate::verify::{ document_query_proof_bytes, supported_grovedb_proof_bytes, require_supported_grovedb_proof_bytes, verify_page_drive_proves, verify_tenderdash_proof, verify_tenderdash_signature, }; -use crate::{types::*, ContextProvider, DataContractProvider, Error}; +use crate::{types::*, ContextProvider, ContextProviderError, Error}; use dapi_grpc::platform::v0::get_evonodes_proposed_epoch_blocks_by_range_request::get_evonodes_proposed_epoch_blocks_by_range_request_v0::Start; use dapi_grpc::platform::v0::get_identities_contract_keys_request::GetIdentitiesContractKeysRequestV0; use dapi_grpc::platform::v0::get_identity_by_non_unique_public_key_hash_response::{ @@ -113,9 +113,10 @@ use drive::query::vote_poll_vote_state_query::{ use drive::query::vote_polls_by_document_type_query::{ ResolvedVotePollsByDocumentTypeQuery, VotePollsByDocumentTypeQuery, }; -use drive::query::{DriveDocumentQuery, VotePollsByEndDateDriveQuery}; +use drive::query::{ContractLookupFn, DriveDocumentQuery, VotePollsByEndDateDriveQuery}; use indexmap::IndexMap; use std::array::TryFromSliceError; +use std::cell::RefCell; use std::collections::BTreeMap; use std::num::TryFromIntError; use crate::error::MapGroveDbError; @@ -466,6 +467,57 @@ fn proof_query_platform_version( }) } +/// A context provider's configuration error, kept aside while Drive, whose errors cannot +/// carry it, verifies a proof with what the provider answers. +/// +/// The provider is set up so that it cannot serve what Drive asked for, whichever node's +/// answer is verified with it, so the error replaces the verification failure it caused. +#[derive(Default)] +struct ProviderMisconfiguration(RefCell>); + +impl ProviderMisconfiguration { + /// The text Drive is given of the provider's `error`; a configuration error is kept. + fn describe(&self, error: ContextProviderError) -> String { + let reason = error.to_string(); + if matches!(error, ContextProviderError::Config(_)) { + *self.0.borrow_mut() = Some(error); + } + reason + } + + /// `result`, or the kept configuration error in place of the failure it caused. + fn in_place_of_failure(self, result: Result) -> Result { + match (result, self.0.into_inner()) { + (Err(_), Some(error)) => Err(Error::ContextProviderError(error)), + (result, _) => result, + } + } +} + +/// Runs `verify` with a lookup of the data contracts it needs in `provider`. +/// +/// The lookup gives Drive a failed lookup as text, as +/// [`crate::DataContractProvider::as_contract_lookup_fn`] does, and a configuration error +/// is reported in place of the failure it caused ([`ProviderMisconfiguration`]). +fn with_contract_lookup( + provider: &dyn ContextProvider, + platform_version: &PlatformVersion, + verify: impl FnOnce(&ContractLookupFn) -> Result, +) -> Result { + let misconfiguration = ProviderMisconfiguration::default(); + let lookup = |id: &Identifier| { + provider + .get_data_contract(id, platform_version) + .map_err(|error| { + drive::error::Error::Proof(ProofError::ErrorRetrievingContract( + misconfiguration.describe(error), + )) + }) + }; + let result = verify(&lookup); + misconfiguration.in_place_of_failure(result) +} + impl FromProof for Identity { type Request = platform::GetIdentityByNonUniquePublicKeyHashRequest; type Response = platform::GetIdentityByNonUniquePublicKeyHashResponse; @@ -1596,8 +1648,6 @@ impl FromProof for StateTransitionPro let query_platform_version = proof_query_platform_version(mtd)?; - let contracts_provider_fn = provider.as_contract_lookup_fn(platform_version); - // Transition families whose proof cannot be bound to execution // (balance top-ups, credit transfers/withdrawals, address funds // movements, shields, no-history token operations) yield a verified @@ -1607,15 +1657,17 @@ impl FromProof for StateTransitionPro // guarantee: strict waits reject snapshots, snapshot waits treat // them as height-pinned state, never as execution evidence. let (root_hash, outcome) = - Drive::verify_state_transition_was_executed_with_proof_for_query_version( - &state_transition, - &block_info, - supported_grovedb_proof_bytes(proof)?, - &contracts_provider_fn, - query_platform_version, - platform_version, - ) - .map_drive_error(proof, mtd)?; + with_contract_lookup(provider, platform_version, |contracts_provider_fn| { + Drive::verify_state_transition_was_executed_with_proof_for_query_version( + &state_transition, + &block_info, + supported_grovedb_proof_bytes(proof)?, + contracts_provider_fn, + query_platform_version, + platform_version, + ) + .map_drive_error(proof, mtd) + })?; verify_tenderdash_proof(proof, mtd, &root_hash, provider)?; @@ -2093,9 +2145,9 @@ impl FromProof for ContestedResources { // Decode request to get drive query let drive_query = VotePollsByDocumentTypeQuery::try_from_request(request)?; - let resolved_request = drive_query.resolve_with_known_contracts_provider( - &provider.as_contract_lookup_fn(platform_version), - )?; + let resolved_request = with_contract_lookup(provider, platform_version, |lookup| { + Ok(drive_query.resolve_with_known_contracts_provider(lookup)?) + })?; // Parse response to read proof and metadata let proof = response.proof().or(Err(Error::NoProofInResult))?; @@ -2141,9 +2193,9 @@ impl FromProof for Contenders { let drive_query = ContestedDocumentVotePollDriveQuery::try_from_request(request)?; // Resolve request to get verify_*_proof - let contracts_provider = provider.as_contract_lookup_fn(platform_version); - let resolved_request = - drive_query.resolve_with_known_contracts_provider(&contracts_provider)?; + let resolved_request = with_contract_lookup(provider, platform_version, |lookup| { + Ok(drive_query.resolve_with_known_contracts_provider(lookup)?) + })?; // Parse response to read proof and metadata let proof = response.proof().or(Err(Error::NoProofInResult))?; @@ -2199,10 +2251,9 @@ impl FromProof for Voters { let drive_query = ContestedDocumentVotePollVotesDriveQuery::try_from_request(request)?; // Parse request to get resolved contract that implements verify_*_proof - let contracts_provider = provider.as_contract_lookup_fn(platform_version); - - let resolved_request = - drive_query.resolve_with_known_contracts_provider(&contracts_provider)?; + let resolved_request = with_contract_lookup(provider, platform_version, |lookup| { + Ok(drive_query.resolve_with_known_contracts_provider(lookup)?) + })?; // Parse response to read proof and metadata let proof = response.proof().or(Err(Error::NoProofInResult))?; @@ -2255,19 +2306,21 @@ impl FromProof for ResourceV let grovedb_proof = supported_grovedb_proof_bytes(proof)?; - let contract_provider_fn = provider.as_contract_lookup_fn(platform_version); - let (root_hash, voters) = verify_page_drive_proves(drive_query.limit, |limit| { - ContestedResourceVotesGivenByIdentityQuery { - limit, - ..drive_query.clone() - } - .verify_identity_votes_given_proof::>( - grovedb_proof, - &contract_provider_fn, - platform_version, - ) - }) - .map_drive_error(proof, mtd)?; + let (root_hash, voters) = + with_contract_lookup(provider, platform_version, |contract_provider_fn| { + verify_page_drive_proves(drive_query.limit, |limit| { + ContestedResourceVotesGivenByIdentityQuery { + limit, + ..drive_query.clone() + } + .verify_identity_votes_given_proof::>( + grovedb_proof, + contract_provider_fn, + platform_version, + ) + }) + .map_drive_error(proof, mtd) + })?; verify_tenderdash_proof(proof, mtd, &root_hash, provider)?; @@ -2465,18 +2518,23 @@ impl FromProof for TotalCreditsInPla let core_subsidy_halving_interval = network.core_subsidy_halving_interval(); - let (root_hash, credits) = Drive::verify_total_credits_in_system( + // Drive asks for the activation height only when the unpaid epoch is the first one. + let misconfiguration = ProviderMisconfiguration::default(); + let verified = Drive::verify_total_credits_in_system( supported_grovedb_proof_bytes(proof)?, core_subsidy_halving_interval, || { provider.get_platform_activation_height().map_err(|e| { - drive::error::Error::Proof(ProofError::MissingContextRequirement(e.to_string())) + drive::error::Error::Proof(ProofError::MissingContextRequirement( + misconfiguration.describe(e), + )) }) }, mtd.core_chain_locked_height, platform_version, ) - .map_drive_error(proof, mtd)?; + .map_drive_error(proof, mtd); + let (root_hash, credits) = misconfiguration.in_place_of_failure(verified)?; verify_tenderdash_proof(proof, mtd, &root_hash, provider)?; @@ -3550,6 +3608,93 @@ mod tests { } } + /// Answers every data contract lookup with the error its function makes. + struct FailingContractProvider(fn() -> ContextProviderError); + + impl dash_context_provider::ContextProvider for FailingContractProvider { + fn get_data_contract( + &self, + _id: &dpp::prelude::Identifier, + _platform_version: &PlatformVersion, + ) -> Result>, ContextProviderError> { + Err((self.0)()) + } + + fn get_token_configuration( + &self, + _token_id: &dpp::prelude::Identifier, + ) -> Result, ContextProviderError> { + panic!("token configuration should not be requested") + } + + fn get_quorum_public_key( + &self, + _quorum_type: u32, + _quorum_hash: [u8; 32], + _core_chain_locked_height: u32, + ) -> Result<[u8; 48], ContextProviderError> { + panic!("quorum public key should not be requested") + } + + fn get_platform_activation_height( + &self, + ) -> Result { + panic!("platform activation height should not be requested") + } + } + + fn no_contract_source() -> ContextProviderError { + ContextProviderError::Config("no contract source".to_string()) + } + + /// Drive verifies some proofs without the contract a failed lookup could not give, such + /// as a deletion a removal record proves. A configuration error then changes nothing: + /// the verification's own result is kept. + #[test] + fn should_keep_a_verification_that_succeeds_after_a_failed_contract_lookup() { + let provider = FailingContractProvider(no_contract_source); + let result = with_contract_lookup(&provider, PlatformVersion::latest(), |lookup| { + assert!(lookup(&Identifier::new([1; 32])).is_err()); + Ok(7) + }); + assert!(matches!(result, Ok(7)), "{result:?}"); + } + + /// A verification that fails after the provider refused a lookup with a configuration + /// error fails with that error, which the SDK attributes to its own setup. Any other + /// provider failure stays the Drive error it was. + #[test] + fn should_report_only_a_configuration_error_in_place_of_the_failure_it_caused() { + let verify = |provider: &dyn ContextProvider| { + with_contract_lookup(provider, PlatformVersion::latest(), |lookup| { + lookup(&Identifier::new([1; 32]))?; + Ok(()) + }) + }; + + let misconfigured = verify(&FailingContractProvider(no_contract_source)); + assert!( + matches!( + &misconfigured, + Err(Error::ContextProviderError(ContextProviderError::Config(reason))) + if reason == "no contract source" + ), + "{misconfigured:?}" + ); + + let unavailable = verify(&FailingContractProvider(|| { + ContextProviderError::Generic("timed out".to_string()) + })); + assert!( + matches!( + &unavailable, + Err(Error::DriveError { error }) + if error.contains("could not be retrieved") && error.contains("timed out") + ), + "{unavailable:?}" + ); + } + /// Build a fully-populated `GetIdentityResponse` shell so that /// `response.proof()` and `response.metadata()` both succeed. The /// enclosed proof is empty, so any real verification would fail — but diff --git a/packages/rs-sdk-ffi/src/error.rs b/packages/rs-sdk-ffi/src/error.rs index cd16db11c0f..493c03508cb 100644 --- a/packages/rs-sdk-ffi/src/error.rs +++ b/packages/rs-sdk-ffi/src/error.rs @@ -206,9 +206,20 @@ fn consensus_code_of(error: &dash_sdk::Error) -> Option { } } +/// Whether the SDK has no context provider, or one set up so that it cannot serve: the host +/// has to configure the SDK differently, and no node or retry changes that, whatever words +/// the message holds. +fn is_context_provider_misconfigured(error: &dash_sdk::Error) -> bool { + matches!( + error, + dash_sdk::Error::ContextProviderError(dash_sdk::error::ContextProviderError::Config(_)) + ) +} + impl FFIError { /// `source` with the message `"{context}: {source}"`, keeping the SDK - /// error so its consensus code and quorum-source category reach the host. + /// error so its consensus code, quorum-source category and context-provider + /// misconfiguration reach the host. pub fn sdk_call_failed(context: impl Into, source: dash_sdk::Error) -> Self { FFIError::SDKCallFailed { context: context.into(), @@ -224,6 +235,8 @@ impl From for DashSDKError { FFIError::SDKCallFailed { source, .. } => { let code = if source.is_quorum_source_unavailable() { DashSDKErrorCode::NetworkError + } else if is_context_provider_misconfigured(source) { + DashSDKErrorCode::InvalidState } else { DashSDKErrorCode::InternalError }; @@ -285,6 +298,8 @@ impl From for DashSDKError { // answer, so a proof could not be checked: transient and // network-side, whatever words its message happens to hold. (DashSDKErrorCode::NetworkError, error_str) + } else if is_context_provider_misconfigured(sdk_err) { + (DashSDKErrorCode::InvalidState, error_str) } else if matches!(sdk_err, dash_sdk::Error::TimeoutReached(_, _)) || error_str.contains("timeout") || error_str.contains("Timeout") @@ -399,6 +414,42 @@ mod tests { code } + /// An SDK without a context provider cannot verify any proof. The host has to set the + /// SDK up differently, so it reads an invalid state that says what is missing, not a + /// proof failure it might blame on the network, also when the error carries the context + /// of the operation that failed. + #[test] + fn should_map_a_missing_context_provider_to_invalid_state() { + let missing = || dash_sdk::Error::from(dash_sdk::ProofVerifierError::ContextProviderNotSet); + for contextual in [false, true] { + let error = if contextual { + FFIError::sdk_call_failed("Failed to put identity and wait", missing()) + } else { + FFIError::SDKError(missing()) + }; + let expected_message = if contextual { + error.to_string() + } else { + missing().to_string() + }; + let dash_sdk_error: DashSDKError = error.into(); + let message = unsafe { + let message = CStr::from_ptr(dash_sdk_error.message) + .to_string_lossy() + .into_owned(); + let _ = CString::from_raw(dash_sdk_error.message); + message + }; + assert_eq!( + dash_sdk_error.code, + DashSDKErrorCode::InvalidState, + "contextual {contextual}: {message}" + ); + assert_eq!(message, expected_message); + assert!(message.contains("context provider is not set"), "{message}"); + } + } + /// The quorum service that vouches for quorum keys gave no answer: a /// network problem the app can retry, not an internal error. #[test] diff --git a/packages/rs-sdk/src/error.rs b/packages/rs-sdk/src/error.rs index 899bccfa103..8f501e5d99c 100644 --- a/packages/rs-sdk/src/error.rs +++ b/packages/rs-sdk/src/error.rs @@ -230,7 +230,6 @@ impl Error { fn cannot_verify_answers(&self) -> bool { match self { Self::NoAvailableAddressesToRetry(last_error) => last_error.cannot_verify_answers(), - Self::Proof(drive_proof_verifier::Error::ContextProviderNotSet) => true, Self::Proof(drive_proof_verifier::Error::QuorumKeyUnavailable { error, .. }) | Self::ContextProviderError(error) => { matches!(error, ContextProviderError::Config(_)) @@ -299,10 +298,14 @@ impl Error { } /// A trusted source outage is not the responding node's fault. Preserve that -/// attribution and quorum context; so is a data contract the client's context cannot -/// give as the request needs it, which every node's answer fails on alike. A verified -/// result no node can return as the requested type is the request's to change -/// ([`Error::InvalidRequest`]); every other verifier failure stays `Proof`. +/// attribution and quorum context. A missing context provider, or one configured so that +/// it cannot serve a lookup the verifier makes (a quorum key, or a data contract or token +/// configuration a proof is read with), is this SDK's own setup, which no node can change: +/// it is a configuration error that is not retried and bans no node. A data contract the +/// client's context cannot give as the request needs it fails every node's answer alike, +/// and is not retried either. A verified result no node can return as the requested type +/// is the request's to change ([`Error::InvalidRequest`]); every other verifier failure +/// stays `Proof`. impl From for Error { fn from(value: drive_proof_verifier::Error) -> Self { match value { @@ -315,6 +318,20 @@ impl From for Error { "quorum {quorum_type}:{} at Core chain-locked height {core_chain_locked_height}: {reason}", hex::encode(quorum_hash) ))), + drive_proof_verifier::Error::QuorumKeyUnavailable { + error: error @ ContextProviderError::Config(_), + .. + } + | drive_proof_verifier::Error::ContextProviderError( + error @ ContextProviderError::Config(_), + ) => Self::ContextProviderError(error), + drive_proof_verifier::Error::ContextProviderNotSet => { + Self::ContextProviderError(ContextProviderError::Config( + "context provider is not set, so no proof can be verified; set one with \ + SdkBuilder::with_context_provider() or Sdk::set_context_provider()" + .to_string(), + )) + } drive_proof_verifier::Error::ContextProviderError( error @ ContextProviderError::DataContractFailure(_), ) => Self::ContextProviderError(error), @@ -717,6 +734,25 @@ mod tests { ); } + /// A context provider configured so that it cannot serve a lookup the verifier makes, + /// such as the data contract a document history proof is read with, fails alike for + /// every node's answer: the request is not retried and no node is banned for it. + #[test] + fn should_not_retry_a_lookup_the_context_provider_is_configured_not_to_serve() { + let error = Error::from(drive_proof_verifier::Error::ContextProviderError( + ContextProviderError::Config("dump dir not set".to_string()), + )); + assert!( + matches!( + &error, + Error::ContextProviderError(ContextProviderError::Config(reason)) + if reason == "dump dir not set" + ), + "{error:?}" + ); + assert!(!error.can_retry()); + } + /// A result that verified but cannot be returned as the requested type is the same from /// every honest node: the request fails without being retried, and the node is not banned. #[test] @@ -790,7 +826,7 @@ mod tests { ); } let permanent = [ - Error::Proof(drive_proof_verifier::Error::ContextProviderNotSet), + Error::from(drive_proof_verifier::Error::ContextProviderNotSet), quorum_key(ContextProviderError::Config( "Non-trusted mode is not supported".to_string(), )), diff --git a/packages/rs-sdk/src/sdk/protocol_gate.rs b/packages/rs-sdk/src/sdk/protocol_gate.rs index 7be2d4f8e46..f40ceb1a616 100644 --- a/packages/rs-sdk/src/sdk/protocol_gate.rs +++ b/packages/rs-sdk/src/sdk/protocol_gate.rs @@ -178,8 +178,8 @@ pub(super) fn decide(required: u32, state: &GateState<'_>) -> Gate { } // Asking raises the verified version, and the version of an unpinned SDK; a pinned SDK // below `required` stays below it whatever the answer. Without a context provider the - // answer cannot be verified, and an answer the SDK cannot verify bans the node that - // sent it. While a probe's epoch has not ended, asking again would show the same version. + // answer cannot be verified, so asking cannot show the network's version. While a + // probe's epoch has not ended, asking again would show the same version. if pinned_below(required, state) || !state.has_context_provider || state.hold.is_some_and(|hold| { diff --git a/packages/rs-sdk/src/sdk/protocol_gate_tests.rs b/packages/rs-sdk/src/sdk/protocol_gate_tests.rs index 09246968eec..666ff6bff91 100644 --- a/packages/rs-sdk/src/sdk/protocol_gate_tests.rs +++ b/packages/rs-sdk/src/sdk/protocol_gate_tests.rs @@ -40,6 +40,9 @@ use crate::platform::{ }; use crate::SdkBuilder; use dapi_grpc::mock::Mockable; +use dapi_grpc::platform::v0::get_contested_resources_response::{ + get_contested_resources_response_v0, GetContestedResourcesResponseV0, +}; use dapi_grpc::platform::v0::get_contract_group_info_response::GetContractGroupInfoResponseV0; use dapi_grpc::platform::v0::get_data_contracts_latest_versions_response::{ get_data_contracts_latest_versions_response_v0::Result as LatestVersionsResult, @@ -47,6 +50,9 @@ use dapi_grpc::platform::v0::get_data_contracts_latest_versions_response::{ GetDataContractsLatestVersionsResponseV0, }; use dapi_grpc::platform::v0::get_documents_request::WhereClause; +use dapi_grpc::platform::v0::{ + get_contested_resources_response, GetContestedResourcesRequest, GetContestedResourcesResponse, +}; use dapi_grpc::platform::v0::{ get_contract_group_info_request, get_contract_group_info_response, get_data_contracts_by_range_request, get_data_contracts_latest_versions_request, @@ -66,7 +72,7 @@ use dapi_grpc::platform::v0::{ GetIdentityKeysRemainingBudgetsRequest, GetMasternodeYesNoVoteRequest, GetMostRecentShieldedAnchorRequest, GetPrivateDocumentEntriesRequest, GetShieldedAnchorsRequest, GetShieldedEncryptedNotesRequest, GetShieldedNotesCountRequest, - GetShieldedNullifiersRequest, GetShieldedPoolStateRequest, GetYesNoVotePollStateRequest, + GetShieldedNullifiersRequest, GetShieldedPoolStateRequest, GetYesNoVotePollStateRequest, Proof, ResponseMetadata, }; use dapi_grpc::tonic::Status; @@ -87,13 +93,14 @@ use dpp::version::{PlatformVersion, PLATFORM_VERSIONS}; use dpp::voting::vote_polls::yes_no_vote_poll::{ YesNoMinimumVotingPower, YesNoVotePoll, YesNoVotePollPurpose, }; +use drive::query::vote_polls_by_document_type_query::VotePollsByDocumentTypeQuery; use drive::query::{ HavingAggregate, HavingAggregateFunction, HavingClause, HavingOperator, HavingRightOperand, SelectProjection, TimeRangeSelector, WhereClause as DriveWhereClause, WhereOperator, }; use drive_proof_verifier::types::{ - Documents, MostRecentShieldedAnchor, ShieldedAnchors, ShieldedEncryptedNotes, - ShieldedNotesCount, ShieldedNullifierStatuses, ShieldedPoolState, + ContestedResource, Documents, MostRecentShieldedAnchor, ShieldedAnchors, + ShieldedEncryptedNotes, ShieldedNotesCount, ShieldedNullifierStatuses, ShieldedPoolState, }; use drive_proof_verifier::{ DocumentAverage, DocumentCount, DocumentHavingEntries, DocumentRankedEntries, @@ -188,6 +195,71 @@ impl ContextProvider for NoQuorumKeys { } } +/// Configured so that it can never give a quorum key, as wasm-sdk's context without a +/// trusted quorum source. +struct NoQuorumSource; +impl ContextProvider for NoQuorumSource { + fn get_data_contract( + &self, + _: &Identifier, + _: &PlatformVersion, + ) -> Result>, ContextProviderError> { + Ok(None) + } + fn get_token_configuration( + &self, + _: &Identifier, + ) -> Result, ContextProviderError> { + Ok(None) + } + fn get_quorum_public_key( + &self, + _: u32, + _: [u8; 32], + _: u32, + ) -> Result<[u8; 48], ContextProviderError> { + Err(ContextProviderError::Config( + "no quorum source is configured".to_string(), + )) + } + fn get_platform_activation_height(&self) -> Result { + Ok(1) + } +} + +/// Configured so that it can never give a data contract. +struct NoContractSource; +impl ContextProvider for NoContractSource { + fn get_data_contract( + &self, + _: &Identifier, + _: &PlatformVersion, + ) -> Result>, ContextProviderError> { + Err(ContextProviderError::Config( + "no data contract source is configured".to_string(), + )) + } + fn get_token_configuration( + &self, + _: &Identifier, + ) -> Result, ContextProviderError> { + Ok(None) + } + fn get_quorum_public_key( + &self, + _: u32, + _: [u8; 32], + _: u32, + ) -> Result<[u8; 48], ContextProviderError> { + Err(ContextProviderError::InvalidQuorum( + "no quorum keys here".to_string(), + )) + } + fn get_platform_activation_height(&self) -> Result { + Ok(1) + } +} + /// The node every answer comes from. It is in the SDK's address list, so a ban shows. fn node() -> Address { "http://127.0.0.1:9000".parse().unwrap() @@ -597,8 +669,8 @@ async fn should_refuse_without_asking_when_pinned_below_the_version() { assert_eq!(sent(&sdk, &fee_pots()).await, 0); } -/// Without a context provider the answer to the probe cannot be verified, and an answer the -/// SDK cannot verify bans the node that sent it: refuse without asking. +/// Without a context provider the answer to the probe cannot be verified, so asking cannot +/// show the network's version: refuse without asking. #[tokio::test] async fn should_refuse_without_asking_when_answers_cannot_be_verified() { let mut sdk = mock_sdk(V13, false, 0); @@ -616,6 +688,100 @@ async fn should_refuse_without_asking_when_answers_cannot_be_verified() { assert_eq!(sent(&sdk, &fee_pots()).await, 0); } +/// A proved fetch the node answered fails with a configuration error naming `reason`, after +/// one attempt, and bans no node. +async fn assert_fails_on_the_sdk_setup(sdk: &Sdk, reason: &str) { + let result = ExtendedEpochInfo::fetch_with_metadata(sdk, probe_request(), None).await; + assert_failed_on_the_sdk_setup(sdk, result, probes(sdk).await, reason); +} + +/// `result`, of a proved fetch the node answered `sent` times, is a configuration error +/// naming `reason`, the fetch was not retried, and no node was banned for it. +fn assert_failed_on_the_sdk_setup( + sdk: &Sdk, + result: Result, + sent: usize, + reason: &str, +) { + let banned = sdk.address_list().is_banned(&node()); + assert!( + matches!( + &result, + Err(Error::ContextProviderError(ContextProviderError::Config(message))) + if message.contains(reason) + ), + "{result:?}, sent {sent} times, node banned: {banned}" + ); + assert_eq!(sent, 1, "sent once, never retried"); + assert!(!banned); +} + +/// Without a context provider the SDK cannot check any answer, whichever node sent it. The +/// fault is the SDK's own setup: a proved fetch fails on its first answer with a +/// configuration error, is not sent to another node, and bans no node. +#[tokio::test] +async fn should_fail_a_proved_fetch_once_and_ban_no_node_without_a_context_provider() { + let sdk = mock_sdk(V13, false, 0); + answer_probe(&sdk, "pv13").await; + sdk.context_provider.store(None); + assert_fails_on_the_sdk_setup(&sdk, "context provider is not set").await; +} + +/// A context provider set up so that it can never give a quorum key cannot check any answer +/// either, so another node's answer would fail alike: the fetch fails with the provider's +/// configuration error, is not sent to another node, and bans no node. +#[tokio::test] +async fn should_fail_a_proved_fetch_once_and_ban_no_node_when_the_provider_has_no_quorum_source() { + let sdk = sdk_with_provider(V13, false, 0, true, NoQuorumSource); + answer_probe(&sdk, "pv13").await; + assert_fails_on_the_sdk_setup(&sdk, "no quorum source is configured").await; +} + +/// A context provider set up so that it can never give a data contract fails alike for every +/// node's answer, also where Drive looks the contract up through the provider and its own +/// errors cannot carry the provider's: the fetch fails with the provider's configuration +/// error, is not sent to another node, and bans no node. +#[tokio::test] +async fn should_fail_a_proved_fetch_once_and_ban_no_node_when_the_provider_has_no_contract_source() +{ + let sdk = sdk_with_provider(V13, false, 0, true, NoContractSource); + let request: GetContestedResourcesRequest = VotePollsByDocumentTypeQuery { + contract_id: dpns().id(), + document_type_name: "domain".to_string(), + index_name: "parentNameAndLabel".to_string(), + start_at_value: None, + start_index_values: vec![dpp::platform_value::Value::Text("dash".to_string())], + end_index_values: vec![], + limit: None, + order_ascending: true, + } + .query(&QuerySettings { + request_settings: &RequestSettings::default(), + protocol_version: PlatformVersion::latest(), + verified_protocol_version: 0, + prove: true, + }) + .unwrap(); + // Drive looks the contract up before it reads the proof, so no real proof is needed. + let response = GetContestedResourcesResponse { + version: Some(get_contested_resources_response::Version::V0( + GetContestedResourcesResponseV0 { + result: Some(get_contested_resources_response_v0::Result::Proof( + Proof::default(), + )), + metadata: Some(ResponseMetadata { + protocol_version: V13, + ..Default::default() + }), + }, + )), + }; + answer(&sdk, &request, Ok(response)).await; + let result = ContestedResource::fetch_many(&sdk, request.clone()).await; + let sent = sent(&sdk, &request).await; + assert_failed_on_the_sdk_setup(&sdk, result, sent, "no data contract source is configured"); +} + /// An SDK without proofs still learns the network's version from a proved probe. #[tokio::test] async fn should_ask_with_a_proof_when_the_sdk_does_not_request_proofs() { diff --git a/packages/rs-unified-sdk-jni/src/tokens.rs b/packages/rs-unified-sdk-jni/src/tokens.rs index d16b4cc9081..438c10a45cf 100644 --- a/packages/rs-unified-sdk-jni/src/tokens.rs +++ b/packages/rs-unified-sdk-jni/src/tokens.rs @@ -1625,12 +1625,35 @@ unsafe fn take_identifier_array_blob( .unwrap_or(ptr::null_mut()) } +/// Destroy every `ContactRequest` handle in a sync result, then free the +/// array buffer. The sync bridges below call the FFI only for its side effect +/// on wallet state and never hand these handles to Kotlin, so this is the +/// only place that can release them; freeing just the buffer would leave one +/// `CONTACT_REQUEST_STORAGE` entry per returned request on every sync. +/// +/// # Safety +/// `array` must be the (possibly empty) array a contact request sync wrote, +/// not yet freed, whose handles nobody else holds. +unsafe fn release_contact_request_handles( + array: &mut platform_wallet_ffi::ContactRequestHandleArray, +) { + if !array.handles.is_null() && array.count > 0 { + let handles = std::slice::from_raw_parts(array.handles, array.count); + for &handle in handles { + let mut result = platform_wallet_ffi::contact_request_destroy(handle); + platform_wallet_ffi_result_free(&mut result); + } + } + platform_wallet_ffi::platform_wallet_contact_request_handle_array_free( + array as *mut platform_wallet_ffi::ContactRequestHandleArray, + ); +} + /// Sync incoming contact requests from Platform for every managed identity /// on the wallet (bridges `platform_wallet_sync_contact_requests`). Applies /// them to the wallet's in-memory state (the side effect that /// [`getManagedIdentity`] and the id readers then observe); the returned -/// handle array is freed here (the underlying `ContactRequest` handles stay -/// in native storage). Blocking. +/// handles and their array are released here. Blocking. #[no_mangle] pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TokensNative_syncContactRequests( mut env: JNIEnv, @@ -1648,21 +1671,17 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TokensNative_syncCont &mut array as *mut platform_wallet_ffi::ContactRequestHandleArray, ) }; - // Free the array regardless of outcome (the handles it references - // remain valid in native storage; we only own the buffer). - unsafe { - platform_wallet_ffi::platform_wallet_contact_request_handle_array_free( - &mut array as *mut platform_wallet_ffi::ContactRequestHandleArray, - ) - }; + // Release regardless of outcome: on error the FFI leaves the empty + // sentinel, which this no-ops on. + unsafe { release_contact_request_handles(&mut array) }; let _ = take_pwffi_error(env, result); }) } /// Fetch the contact requests sent by `identityId` from Platform (bridges /// `platform_wallet_fetch_sent_contact_requests`). Applies them to the -/// wallet's in-memory state; the returned handle array is freed here. -/// Blocking. +/// wallet's in-memory state; the returned handles and their array are +/// released here. Blocking. #[no_mangle] pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TokensNative_fetchSentContactRequests( mut env: JNIEnv, @@ -1685,11 +1704,7 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TokensNative_fetchSen &mut array as *mut platform_wallet_ffi::ContactRequestHandleArray, ) }; - unsafe { - platform_wallet_ffi::platform_wallet_contact_request_handle_array_free( - &mut array as *mut platform_wallet_ffi::ContactRequestHandleArray, - ) - }; + unsafe { release_contact_request_handles(&mut array) }; let _ = take_pwffi_error(env, result); }) } @@ -1963,10 +1978,71 @@ pub extern "system" fn Java_org_dashfoundation_dashsdk_ffi_TokensNative_getIncom #[cfg(test)] mod tests { use super::*; + use platform_wallet_ffi::contact_request::CONTACT_REQUEST_STORAGE; + use platform_wallet_ffi::ContactRequestHandleArray; // profile_to_json is pure marshalling logic (no JNIEnv), so it is unit // testable on the JVM-free host. The natives above need a device. + /// Store a contact request through the public FFI, as a sync does, and + /// return its handle. + fn stored_contact_request(seed: u8) -> Handle { + let sender = [seed; 32]; + let recipient = [seed.wrapping_add(1); 32]; + let encrypted_key = [seed; 96]; + let mut handle: Handle = 0; + let mut result = unsafe { + platform_wallet_ffi::contact_request_create( + sender.as_ptr(), + recipient.as_ptr(), + 0, + 1, + 0, + encrypted_key.as_ptr(), + encrypted_key.len(), + 100_000, + 1_700_000_000, + &mut handle, + ) + }; + assert_eq!(result.code, PlatformWalletFFIResultCode::Success); + unsafe { platform_wallet_ffi_result_free(&mut result) }; + handle + } + + fn is_stored(handle: Handle) -> bool { + CONTACT_REQUEST_STORAGE.with_item(handle, |_| ()).is_some() + } + + #[test] + fn should_destroy_every_contact_request_handle_a_sync_returned() { + let handles: Vec = (1..=3).map(stored_contact_request).collect(); + assert!(handles.iter().all(|&handle| is_stored(handle))); + // Same buffer layout `ContactRequestHandleArray::from_requests` builds. + let mut array = ContactRequestHandleArray { + handles: Box::into_raw(handles.clone().into_boxed_slice()) as *mut Handle, + count: handles.len(), + }; + + unsafe { release_contact_request_handles(&mut array) }; + + for handle in handles { + assert!(!is_stored(handle), "handle {handle} still in storage"); + } + assert!(array.handles.is_null()); + assert_eq!(array.count, 0); + } + + #[test] + fn should_no_op_on_the_empty_array_a_failed_sync_leaves() { + let mut array = ContactRequestHandleArray::empty(); + + unsafe { release_contact_request_handles(&mut array) }; + + assert!(array.handles.is_null()); + assert_eq!(array.count, 0); + } + #[test] fn token_jlong_raw_bits_cover_the_full_u64_domain() { let cases = [ diff --git a/packages/wasm-sdk/src/context_provider.rs b/packages/wasm-sdk/src/context_provider.rs index 39d4371b2be..be5c1809290 100644 --- a/packages/wasm-sdk/src/context_provider.rs +++ b/packages/wasm-sdk/src/context_provider.rs @@ -801,6 +801,93 @@ mod tests { assert_eq!(key, Some(quorum_key(0x43))); server.join().expect("the endpoint served both refreshes"); } + + /// Without a trusted context, the default context gives no quorum key, so no answer can + /// be verified, whichever node sent it. A proved fetch fails on its first answer with a + /// context provider error that says what to attach, is not sent to another node, bans no + /// node, and is not reported to JS as retriable. + #[cfg(not(target_arch = "wasm32"))] + #[tokio::test] + async fn should_fail_a_proved_fetch_once_and_ban_no_node_without_a_trusted_context() { + use crate::error::WasmSdkErrorKind; + use dapi_grpc::platform::v0::{ + get_epochs_info_request, GetEpochsInfoRequest, GetEpochsInfoResponse, + }; + use dapi_grpc::Message; + use dash_sdk::dpp::block::extended_epoch_info::ExtendedEpochInfo; + use dash_sdk::platform::Fetch; + use dash_sdk::SdkBuilder; + use rs_dapi_client::mock::MockResult; + use rs_dapi_client::{Address, DumpData, ExecutionResponse}; + + // The genesis epoch, signed at protocol version 13 by drive-abci's test quorum. + let vector = std::fs::read(concat!( + env!("CARGO_MANIFEST_DIR"), + "/../rs-drive-proof-verifier/tests/vectors/protocol-gate/epoch-probe-pv13.bin" + )) + .expect("signed genesis epoch"); + let response = GetEpochsInfoResponse::decode(vector.as_slice()).expect("epochs response"); + let request = GetEpochsInfoRequest { + version: Some(get_epochs_info_request::Version::V0( + get_epochs_info_request::GetEpochsInfoRequestV0 { + start_epoch: Some(0), + count: 1, + ascending: true, + prove: true, + }, + )), + }; + let node: Address = "http://127.0.0.1:9000".parse().expect("node address"); + + let mut sdk = SdkBuilder::new_mock() + .with_network(Network::Testnet) + .with_context_provider(WasmContext {}) + .with_initial_version(PlatformVersion::get(13).expect("protocol version 13")) + // The vector is signed at height 10, mock answers start at 0. + .with_height_tolerance(None) + .build() + .expect("mock SDK"); + let mut addresses = sdk.address_list().clone(); + addresses.add(node.clone()); + let directory = tempfile::TempDir::new().expect("transport fixture directory"); + let answer: MockResult = Ok(ExecutionResponse { + inner: response, + retries: 0, + address: node.clone(), + }); + let dump = DumpData::new(&request, &answer); + dump.save( + &directory + .path() + .join(dump.filename().expect("dump filename")), + ) + .expect("raw transport answer"); + sdk.mock() + .load_expectations_sync(directory.path()) + .expect("load the node's answer"); + + let error = ExtendedEpochInfo::fetch_with_metadata(&sdk, request, None) + .await + .expect_err("no answer verifies without quorum keys"); + let sent = sdk.mock().request_count(&request).await; + let banned = sdk.address_list().is_banned(&node); + let error = WasmSdkError::from(error); + + assert_eq!( + error.kind(), + WasmSdkErrorKind::ContextProviderError, + "{}, sent {sent} times, node banned: {banned}", + error.message() + ); + assert!( + error.message().contains("WasmTrustedContext"), + "{}", + error.message() + ); + assert!(!error.is_retriable()); + assert_eq!(sent, 1, "sent once, never retried"); + assert!(!banned); + } } #[cfg(all(test, target_arch = "wasm32"))] diff --git a/packages/wasm-sdk/src/error.rs b/packages/wasm-sdk/src/error.rs index a93fd6e9a1c..e248486770b 100644 --- a/packages/wasm-sdk/src/error.rs +++ b/packages/wasm-sdk/src/error.rs @@ -535,6 +535,25 @@ mod tests { assert_eq!(error.message(), message); } + /// An SDK without a context provider cannot verify any proof, and retrying cannot change + /// that: JS reads a context provider error that says what is missing, not a proof failure, + /// and is not told to retry. + #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)] + #[cfg_attr(not(target_arch = "wasm32"), test)] + fn should_report_a_missing_context_provider_as_a_non_retriable_context_provider_error() { + let error = WasmSdkError::from(SdkError::from( + dash_sdk::ProofVerifierError::ContextProviderNotSet, + )); + + assert_eq!(error.kind(), WasmSdkErrorKind::ContextProviderError); + assert!(!error.is_retriable()); + assert!( + error.message().contains("context provider is not set"), + "{}", + error.message() + ); + } + /// What the SDK's retry loop ends a document request with when its node answered at an /// older protocol version than the SDK's and then no node was left to ask. #[cfg(not(target_arch = "wasm32"))]