From 9803ab6697878d8b53ee64a23a65de8ed6307928 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 13:18:33 +0200 Subject: [PATCH 01/19] feat(platform-wallet): top up an identity the wallet does not manage from Platform addresses top_up_from_addresses reads the identity from the wallet's identity manager and returns IdentityNotFound for any other identity, so a wallet could not pay credits from its Platform addresses to someone else's identity. - IdentityWallet::top_up_external_from_addresses fetches the identity from Platform and runs the same transition; it never adds the identity to the manager or persists anything about it. An unknown identity is IdentityNotFound with nothing signed or broadcast. - PlatformWallet::top_up_external_identity_from_addresses reconciles the spent addresses through the same path as the managed composite. - FFI: platform_wallet_top_up_external_identity_from_addresses_with_signer, sharing the input marshalling with the managed export. - The build/broadcast/error mapping is shared by both paths. Co-Authored-By: Claude Opus 5.5 --- .../src/identity_top_up.rs | 114 ++++++- .../external_identity_tests.rs | 187 +++++++++++ .../identity/network/top_up_from_addresses.rs | 80 ++++- .../external_identity_tests.rs | 311 ++++++++++++++++++ .../src/wallet/platform_wallet.rs | 27 ++ 5 files changed, 689 insertions(+), 30 deletions(-) create mode 100644 packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs create mode 100644 packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs index 49c51337af8..141a632b419 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs @@ -43,6 +43,8 @@ use crate::identity_registration::IdentityFundingInputFFI; use crate::runtime::block_on_worker; use crate::{unwrap_option_or_return, unwrap_result_or_return}; +#[cfg(test)] +mod external_identity_tests; #[cfg(test)] mod submission_result_tests; @@ -82,16 +84,56 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( check_ptr!(inputs); check_ptr!(signer_address_handle); check_ptr!(out_new_balance); + let identity_id_bytes: [u8; 32] = *identity_id; + let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); + let input_map = match input_map(inputs, inputs_count) { + Ok(input_map) => input_map, + Err(error) => return error, + }; + + // Round-trip the signer pointer through `usize` so the spawned + // future's capture is `Send + 'static` (the raw pointer is `!Send`, + // but `usize` is). The underlying `Inner::Callback { ctx, vtable }` + // is `Send + Sync` — see the unsafe impls in `rs-sdk-ffi/src/signer.rs`. + let signer_addr = signer_address_handle as usize; + + let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { + let wallet = wallet.clone(); + block_on_worker(async move { + let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; + // The composite tops up the identity AND reconciles the spent + // platform-address balances from the proof, so the wallet's + // displayed balance and next input selection reflect the spend + // (covering addresses restored from disk that are no longer in + // a live derived pool). + wallet + .top_up_from_addresses(&identity_id, input_map, address_signer, None) + .await + }) + }); + let result = unwrap_option_or_return!(option); + let new_balance = unwrap_result_or_return!(result); + *out_new_balance = new_balance; + PlatformWalletFFIResult::ok() +} + +/// Marshal the address-input rows of an address-funded top-up into the +/// input map the library takes. +/// +/// # Safety +/// `inputs` must point at a valid `[IdentityFundingInputFFI; inputs_count]` +/// array. +unsafe fn input_map( + inputs: *const IdentityFundingInputFFI, + inputs_count: usize, +) -> Result, PlatformWalletFFIResult> { if inputs_count == 0 { - return PlatformWalletFFIResult::err( + return Err(PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorInvalidParameter, "`inputs_count` is zero", - ); + )); } - let identity_id_bytes: [u8; 32] = *identity_id; - let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); - let entries = slice::from_raw_parts(inputs, inputs_count); let mut input_map: BTreeMap = BTreeMap::new(); for entry in entries { @@ -99,10 +141,10 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( 0 => PlatformAddress::P2pkh(entry.hash), 1 => PlatformAddress::P2sh(entry.hash), _ => { - return PlatformWalletFFIResult::err( + return Err(PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorInvalidParameter, "invalid address_type (expected 0 or 1)", - ); + )); } }; // Caller may pass the same address twice (the Swift inputs @@ -118,24 +160,62 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( .and_modify(|existing| *existing = existing.saturating_add(entry.credits)) .or_insert(entry.credits); } + Ok(input_map) +} - // Round-trip the signer pointer through `usize` so the spawned - // future's capture is `Send + 'static` (the raw pointer is `!Send`, - // but `usize` is). The underlying `Inner::Callback { ctx, vtable }` - // is `Send + Sync` — see the unsafe impls in `rs-sdk-ffi/src/signer.rs`. +/// Top up an identity this wallet does **not** manage (someone else's) +/// from one or more Platform addresses, using an external `SignerHandle` +/// for the per-address funding signatures. +/// +/// Wraps the composite +/// [`PlatformWallet::top_up_external_identity_from_addresses`](platform_wallet::PlatformWallet::top_up_external_identity_from_addresses): +/// the identity is fetched from Platform rather than read from the wallet, +/// is never added to the wallet's identity manager, and the spent +/// platform-address balances are reconciled as for +/// [`platform_wallet_top_up_from_addresses_with_signer`]. +/// +/// On success `out_new_balance` is populated with the identity's +/// post-transition credit balance returned by Platform. An identity +/// Platform does not know returns `ErrorIdentityNotFound` before anything +/// is signed or broadcast. +/// +/// # Safety +/// Same contract as [`platform_wallet_top_up_from_addresses_with_signer`]. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_top_up_external_identity_from_addresses_with_signer( + wallet_handle: Handle, + identity_id: *const [u8; 32], + inputs: *const IdentityFundingInputFFI, + inputs_count: usize, + signer_address_handle: *mut SignerHandle, + out_new_balance: *mut u64, +) -> PlatformWalletFFIResult { + check_ptr!(identity_id); + check_ptr!(inputs); + check_ptr!(signer_address_handle); + check_ptr!(out_new_balance); + let identity_id_bytes: [u8; 32] = *identity_id; + let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); + let input_map = match input_map(inputs, inputs_count) { + Ok(input_map) => input_map, + Err(error) => return error, + }; + + // `usize` round-trip keeps the spawned future `Send + 'static`; see + // `platform_wallet_top_up_from_addresses_with_signer`. let signer_addr = signer_address_handle as usize; let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { let wallet = wallet.clone(); block_on_worker(async move { let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; - // The composite tops up the identity AND reconciles the spent - // platform-address balances from the proof, so the wallet's - // displayed balance and next input selection reflect the spend - // (covering addresses restored from disk that are no longer in - // a live derived pool). wallet - .top_up_from_addresses(&identity_id, input_map, address_signer, None) + .top_up_external_identity_from_addresses( + &identity_id, + input_map, + address_signer, + None, + ) .await }) }); diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs new file mode 100644 index 00000000000..44531b678e1 --- /dev/null +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs @@ -0,0 +1,187 @@ +//! The external-identity top-up export: its argument guards, and an identity +//! Platform does not know reported as code 7 through the real wallet handle. + +use std::ptr::NonNull; +use std::sync::Arc; + +use dpp::address_funds::AddressWitness; +use dpp::identity::signer::Signer; +use dpp::identity::{Identity, IdentityPublicKey}; +use dpp::platform_value::BinaryData; +use dpp::prelude::Identifier; +use dpp::ProtocolError; +use key_wallet::wallet::initialization::WalletAccountCreationOptions; +use rs_sdk_ffi::{SignerHandle, VTableSigner}; + +use super::platform_wallet_top_up_external_identity_from_addresses_with_signer as top_up; +use crate::error::PlatformWalletFFIResultCode; +use crate::handle::PLATFORM_WALLET_STORAGE; +use crate::identity_registration::IdentityFundingInputFFI; +use crate::runtime::runtime; +use crate::test_fixtures::mock_manager; + +const IDENTITY: [u8; 32] = [9; 32]; +const UNTOUCHED: u64 = 0xDEAD; + +fn input(address_type: u8) -> IdentityFundingInputFFI { + IdentityFundingInputFFI { + address_type, + hash: [7; 20], + credits: 100_000_000, + } +} + +/// Never asked to sign: every scenario here ends before signing. +#[derive(Debug)] +struct UnusedSigner; + +#[async_trait::async_trait] +impl Signer for UnusedSigner { + async fn sign(&self, _: &IdentityPublicKey, _: &[u8]) -> Result { + Err(ProtocolError::Generic("not expected to sign".into())) + } + + async fn sign_create_witness( + &self, + _: &IdentityPublicKey, + _: &[u8], + ) -> Result { + Err(ProtocolError::Generic("not expected to sign".into())) + } + + fn can_sign_with(&self, _: &IdentityPublicKey) -> bool { + false + } +} + +fn dangling_signer() -> *mut SignerHandle { + NonNull::::dangling().as_ptr() +} + +#[test] +fn should_refuse_null_pointers() { + let id = IDENTITY; + let inputs = [input(0)]; + let mut balance = UNTOUCHED; + let calls = [ + unsafe { + top_up( + 0, + std::ptr::null(), + inputs.as_ptr(), + 1, + dangling_signer(), + &mut balance, + ) + }, + unsafe { top_up(0, &id, std::ptr::null(), 1, dangling_signer(), &mut balance) }, + unsafe { + top_up( + 0, + &id, + inputs.as_ptr(), + 1, + std::ptr::null_mut(), + &mut balance, + ) + }, + unsafe { + top_up( + 0, + &id, + inputs.as_ptr(), + 1, + dangling_signer(), + std::ptr::null_mut(), + ) + }, + ]; + for result in calls { + assert_eq!(result.code, PlatformWalletFFIResultCode::ErrorNullPointer); + } + assert_eq!(balance, UNTOUCHED); +} + +#[test] +fn should_refuse_empty_inputs_and_an_unknown_address_type() { + let id = IDENTITY; + let mut balance = UNTOUCHED; + let empty = unsafe { + top_up( + 0, + &id, + [input(0)].as_ptr(), + 0, + dangling_signer(), + &mut balance, + ) + }; + let unknown_type = unsafe { + top_up( + 0, + &id, + [input(2)].as_ptr(), + 1, + dangling_signer(), + &mut balance, + ) + }; + assert_eq!( + empty.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + assert_eq!( + unknown_type.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + assert_eq!(balance, UNTOUCHED); +} + +/// The identity is looked up on Platform, not in the wallet: an identity +/// Platform does not know is `ErrorIdentityNotFound` (7), the balance out +/// is not written, and the wallet still manages no identity. +#[test] +fn should_report_an_identity_platform_does_not_know_as_not_found() { + let manager = mock_manager(); + let mut sdk = manager.sdk().clone(); + runtime() + .block_on( + sdk.mock() + .expect_fetch::(Identifier::from(IDENTITY), None), + ) + .expect("the fetch expectation"); + let wallet = runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + )) + .expect("a wallet"); + let handle = PLATFORM_WALLET_STORAGE.insert(wallet.clone()); + let signer = Box::into_raw(Box::new(VTableSigner::from_native(Arc::new(UnusedSigner)))) + as *mut SignerHandle; + + let id = IDENTITY; + let mut balance = UNTOUCHED; + let result = unsafe { top_up(handle, &id, [input(0)].as_ptr(), 1, signer, &mut balance) }; + + let _ = PLATFORM_WALLET_STORAGE.remove(handle); + drop(unsafe { Box::from_raw(signer as *mut VTableSigner) }); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorIdentityNotFound + ); + assert_eq!(balance, UNTOUCHED); + let identities = runtime().block_on(async { + wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&wallet.wallet_id()) + .expect("the wallet's info") + .identity_manager + .identity_count() + }); + assert_eq!(identities, 0); +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 39f62c43954..46a703a17b5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -3,10 +3,13 @@ use std::collections::BTreeMap; use dpp::identity::signer::Signer; +use dpp::identity::Identity; use dpp::prelude::Identifier; +use dash_sdk::dapi_grpc::platform::v0::ResponseMetadata; use dash_sdk::platform::transition::put_settings::PutSettings; use dash_sdk::platform::transition::top_up_identity_from_addresses::TopUpIdentityFromAddressesWithMetadata; +use dash_sdk::platform::Fetch; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; @@ -20,6 +23,9 @@ use crate::BlockTime; use super::*; +#[cfg(test)] +mod external_identity_tests; + // --------------------------------------------------------------------------- // Top-up from platform addresses // --------------------------------------------------------------------------- @@ -74,19 +80,9 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))? }; - let (address_infos, mut new_balance, metadata) = identity - .top_up_from_addresses_with_metadata(&self.sdk, inputs, address_signer, settings) - .await - .map_err(|e| { - preserve_signer_key_unavailable_or(e, |e| { - promote_address_nonce_error(&e).unwrap_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to top up identity from addresses: {}", - e - )) - }) - }) - })?; + let (address_infos, mut new_balance, metadata) = self + .submit_top_up_from_addresses(&identity, inputs, address_signer, settings) + .await?; let proof_height = metadata.height; @@ -113,4 +109,62 @@ impl IdentityWallet { // shared reconciliation seam. Ok((address_infos, new_balance, proof_height)) } + + /// Top up an identity this wallet does not manage by spending platform + /// address balances. + /// + /// The identity is fetched from Platform (proved) rather than read from + /// the identity manager, and the identity manager is neither read nor + /// written: someone else's identity is never recorded as the wallet's + /// own. Returns the same proof-attested post-spend `AddressInfos`, new + /// identity balance and proof height as + /// [`Self::top_up_from_addresses`]; prefer the composite + /// [`PlatformWallet::top_up_external_identity_from_addresses`], which + /// also reconciles the spent addresses. + /// + /// Returns [`PlatformWalletError::IdentityNotFound`] before anything is + /// signed or broadcast when Platform has no identity with this id. + /// + /// [`PlatformWallet::top_up_external_identity_from_addresses`]: + /// crate::wallet::PlatformWallet::top_up_external_identity_from_addresses + pub async fn top_up_external_from_addresses + Send + Sync>( + &self, + identity_id: &Identifier, + inputs: BTreeMap, + address_signer: &S, + settings: Option, + ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> { + let identity = Identity::fetch(&self.sdk, *identity_id) + .await? + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; + + let (address_infos, new_balance, metadata) = self + .submit_top_up_from_addresses(&identity, inputs, address_signer, settings) + .await?; + Ok((address_infos, new_balance, metadata.height)) + } + + /// Build, sign, broadcast and wait for the top-up of `identity` from + /// `inputs`, mapping the SDK error the way every address top-up reports it. + async fn submit_top_up_from_addresses + Send + Sync>( + &self, + identity: &Identity, + inputs: BTreeMap, + address_signer: &S, + settings: Option, + ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + identity + .top_up_from_addresses_with_metadata(&self.sdk, inputs, address_signer, settings) + .await + .map_err(|e| { + preserve_signer_key_unavailable_or(e, |e| { + promote_address_nonce_error(&e).unwrap_or_else(|| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to top up identity from addresses: {}", + e + )) + }) + }) + }) + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs new file mode 100644 index 00000000000..96b18e90cba --- /dev/null +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -0,0 +1,311 @@ +//! Top-up of an identity the wallet does not manage, against mock DAPI +//! expectations. +//! +//! What is real and what is modelled: +//! - The identity fetch, the address-nonce lookup, the transition build, +//! its signing and its broadcast are real, answered by mock expectations. +//! The broadcast expectation is keyed by the exact bytes of the transition +//! built from the identity Platform returned. +//! - The mock SDK cannot answer the result wait with a verifiable proof, so +//! no scenario here reaches the success branch (and so the reconciliation +//! of the spent addresses, which only runs on success). The submitted +//! top-up ends `StateTransitionResultUnconfirmed`. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::atomic::{AtomicUsize, Ordering}; +use std::sync::Arc; + +use dash_sdk::dapi_client::mock::MockResult; +use dash_sdk::dapi_client::transport::TransportRequest; +use dash_sdk::dapi_client::{DumpData, ExecutionResponse}; +use dash_sdk::dapi_grpc::platform::v0::wait_for_state_transition_result_response::{ + wait_for_state_transition_result_response_v0::Result as WaitResult, Version as WaitVersion, + WaitForStateTransitionResultResponseV0, +}; +use dash_sdk::dapi_grpc::platform::v0::{ + BroadcastStateTransitionRequest, BroadcastStateTransitionResponse, Proof, ResponseMetadata, + WaitForStateTransitionResultRequest, WaitForStateTransitionResultResponse, +}; +use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; +use dash_sdk::platform::transition::put_settings::PutSettings; +use dash_sdk::query_types::{AddressInfo, AddressInfos}; +use dash_sdk::{RequestSettings, Sdk, SdkBuilder}; +use dpp::address_funds::{AddressWitness, PlatformAddress}; +use dpp::identity::accessors::IdentityGettersV0; +use dpp::identity::signer::Signer; +use dpp::identity::{Identity, IdentityV0}; +use dpp::platform_value::BinaryData; +use dpp::prelude::Identifier; +use dpp::state_transition::identity_topup_from_addresses_transition::methods::IdentityTopUpFromAddressesTransitionMethodsV0; +use dpp::state_transition::identity_topup_from_addresses_transition::IdentityTopUpFromAddressesTransition; +use dpp::version::PlatformVersion; +use dpp::ProtocolError; +use key_wallet::wallet::initialization::WalletAccountCreationOptions; + +use crate::error::PlatformWalletError; +use crate::events::{EventHandler, PlatformEventHandler}; +use crate::wallet::persister::NoPlatformPersistence; +use crate::{PlatformWallet, PlatformWalletManager}; + +const ADDRESS: PlatformAddress = PlatformAddress::P2pkh([7; 20]); +const AMOUNT: u64 = 100_000_000; +const BALANCE: u64 = 123_000; +/// An identity the wallet manages, unrelated to the one topped up. +const OWN_IDENTITY: [u8; 32] = [3; 32]; + +#[derive(Debug, Default)] +struct AddressSigner(AtomicUsize); + +#[async_trait::async_trait] +impl Signer for AddressSigner { + async fn sign(&self, _: &PlatformAddress, _: &[u8]) -> Result { + self.0.fetch_add(1, Ordering::SeqCst); + Ok(vec![7; 65].into()) + } + + async fn sign_create_witness( + &self, + key: &PlatformAddress, + data: &[u8], + ) -> Result { + Ok(AddressWitness::P2pkh { + signature: self.sign(key, data).await?, + }) + } + + fn can_sign_with(&self, _: &PlatformAddress) -> bool { + true + } +} + +struct NoopEvents; +impl EventHandler for NoopEvents {} +impl PlatformEventHandler for NoopEvents {} + +fn identity(id: [u8; 32]) -> Identity { + Identity::V0(IdentityV0 { + id: Identifier::from(id), + public_keys: Default::default(), + balance: BALANCE, + revision: 0, + }) +} + +fn save(directory: &tempfile::TempDir, request: &R, response: &MockResult) { + let dump = DumpData::new(request, response); + dump.save(&directory.path().join(dump.filename().unwrap())) + .unwrap(); +} + +fn response(inner: R) -> ExecutionResponse { + ExecutionResponse { + inner, + retries: 0, + address: "http://127.0.0.1".parse().unwrap(), + } +} + +/// A wallet managing [`OWN_IDENTITY`], with Platform knowing `on_platform` +/// (or nothing) under `target`, and a funded [`ADDRESS`]. +struct Fixture { + wallet: Arc, + sdk: Sdk, + target: Identifier, + broadcast: BroadcastStateTransitionRequest, + wait: WaitForStateTransitionResultRequest, + signer: AddressSigner, +} + +impl Fixture { + async fn new(on_platform: bool) -> Self { + let mut sdk = SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .with_time_tolerance(None) + .with_settings(RequestSettings { + retries: Some(0), + ..Default::default() + }) + .build() + .unwrap(); + let target = identity([9; 32]); + let transition = IdentityTopUpFromAddressesTransition::try_from_inputs_with_signer( + &target, + BTreeMap::from([(ADDRESS, (1, AMOUNT))]), + &AddressSigner::default(), + 0, + sdk.version(), + None, + ) + .await + .unwrap(); + let broadcast = transition.broadcast_request_for_state_transition().unwrap(); + let wait = transition + .wait_for_state_transition_result_request() + .unwrap(); + let directory = tempfile::tempdir().unwrap(); + save( + &directory, + &broadcast, + &Ok(response(BroadcastStateTransitionResponse {})), + ); + // A proof the mock cannot verify: the submitted top-up stays unconfirmed. + save( + &directory, + &wait, + &Ok(response(WaitForStateTransitionResultResponse { + version: Some(WaitVersion::V0(WaitForStateTransitionResultResponseV0 { + result: Some(WaitResult::Proof(Proof::default())), + metadata: Some(ResponseMetadata { + protocol_version: PlatformVersion::latest().protocol_version, + ..Default::default() + }), + })), + })), + ); + sdk.mock().load_expectations_sync(directory.path()).unwrap(); + sdk.mock() + .expect_fetch(target.id(), on_platform.then(|| target.clone())) + .await + .unwrap(); + sdk.mock() + .expect_fetch_many::( + BTreeSet::from([ADDRESS]), + Some(AddressInfos::from_iter([( + ADDRESS, + Some(AddressInfo { + address: ADDRESS, + nonce: 0, + balance: AMOUNT, + }), + )])), + ) + .await + .unwrap(); + let manager = PlatformWalletManager::new( + Arc::new(sdk.clone()), + Arc::new(NoPlatformPersistence), + Arc::new(NoopEvents), + ); + let wallet = manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + wallet + .wallet_manager() + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity( + identity(OWN_IDENTITY), + 0, + wallet.wallet_id(), + wallet.persister(), + ) + .unwrap(); + Self { + wallet, + sdk, + target: target.id(), + broadcast, + wait, + signer: AddressSigner::default(), + } + } + + async fn top_up(&self) -> Result { + self.wallet + .top_up_external_identity_from_addresses( + &self.target, + BTreeMap::from([(ADDRESS, AMOUNT)]), + &self.signer, + Some(PutSettings { + request_settings: RequestSettings { + retries: Some(0), + ..Default::default() + }, + ..Default::default() + }), + ) + .await + } + + async fn managed_identity_ids(&self) -> Vec { + self.wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&self.wallet.wallet_id()) + .unwrap() + .identity_manager + .identity_ids() + } + + async fn submissions(&mut self) -> (usize, usize, usize) { + let broadcasts = self.sdk.mock().request_count(&self.broadcast).await; + let waits = self.sdk.mock().request_count(&self.wait).await; + (broadcasts, waits, self.signer.0.load(Ordering::SeqCst)) + } +} + +/// The top-up of an identity the wallet does not manage is built from the +/// identity Platform returned, signed once and submitted, instead of being +/// refused for not being in the identity manager. +#[tokio::test(flavor = "multi_thread")] +async fn should_submit_a_top_up_for_an_identity_the_wallet_does_not_manage() { + let mut fixture = Fixture::new(true).await; + + let error = fixture + .top_up() + .await + .expect_err("the mock cannot prove the result"); + + assert!( + matches!( + error, + PlatformWalletError::Sdk(dash_sdk::Error::StateTransitionResultUnconfirmed(_)) + ), + "the top-up must be submitted, got {error:?}" + ); + assert_eq!(fixture.submissions().await, (1, 1, 1)); +} + +/// Topping up someone else's identity never records it as the wallet's own. +#[tokio::test(flavor = "multi_thread")] +async fn should_leave_the_identity_manager_unchanged() { + let fixture = Fixture::new(true).await; + let before = fixture.managed_identity_ids().await; + + let _ = fixture.top_up().await; + + assert_eq!(fixture.managed_identity_ids().await, before); + assert_eq!(before, vec![Identifier::from(OWN_IDENTITY)]); +} + +/// An identity Platform does not know is refused with the typed not-found +/// error before anything is signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_refuse_an_identity_platform_does_not_know_without_submitting() { + let mut fixture = Fixture::new(false).await; + + let error = fixture + .top_up() + .await + .expect_err("an unknown identity cannot be topped up"); + + assert!( + matches!(error, PlatformWalletError::IdentityNotFound(id) if id == fixture.target), + "got {error:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); + assert_eq!( + fixture.managed_identity_ids().await, + vec![Identifier::from(OWN_IDENTITY)] + ); +} diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 0797bb46ca1..b9dc1dfe149 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -602,6 +602,33 @@ impl PlatformWallet { Ok(new_balance) } + /// Top up an identity this wallet does not manage by spending platform + /// address balances, then reconcile the spent addresses exactly as + /// [`Self::top_up_from_addresses`] does. + /// + /// See [`IdentityWallet::top_up_external_from_addresses`]: the identity + /// is fetched from Platform and never added to the identity manager. + /// + /// Returns the identity's new credit balance. + pub async fn top_up_external_identity_from_addresses< + S: Signer + Send + Sync, + >( + &self, + identity_id: &Identifier, + inputs: BTreeMap, + address_signer: &S, + settings: Option, + ) -> Result { + let (address_infos, new_balance, proof_height) = self + .identity + .top_up_external_from_addresses(identity_id, inputs, address_signer, settings) + .await?; + self.platform + .reconcile_address_infos(&address_infos, proof_height, "external identity top-up") + .await; + Ok(new_balance) + } + /// Register a new identity funded by platform-address balances, then /// reconcile the spent funding addresses' local balances and nonces /// from the proof-attested post-spend `AddressInfos`. From b1b712988ebe874094d59a5f1489fb7631ea1096 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 13:42:39 +0200 Subject: [PATCH 02/19] feat(swift-sdk): topUpExternalIdentityFromAddresses Swift wrapper over platform_wallet_top_up_external_identity_from_addresses_with_signer: tops up an identity the wallet does not manage from the wallet's Platform addresses and returns the identity's new balance. It writes nothing to SwiftData. The managed and external wrappers share one marshalling helper. The parity manifest records the capability as unsupported in Kotlin. Co-Authored-By: Claude Opus 5.5 --- docs/sdk/sdk-parity-manifest.json | 34 ++++ packages/kotlin-sdk/PARITY_SUMMARY.md | 15 +- .../ManagedPlatformWallet.swift | 67 +++++++- .../ExternalIdentityTopUpTests.swift | 148 ++++++++++++++++++ 4 files changed, 250 insertions(+), 14 deletions(-) create mode 100644 packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index addcb451cca..844c8c6c531 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -67,6 +67,7 @@ "platform_wallet_token_purchase": "packages/rs-platform-wallet-ffi/src/tokens/purchase.rs", "platform_wallet_token_transfer": "packages/rs-platform-wallet-ffi/src/tokens/transfer.rs", "platform_wallet_token_update_config": "packages/rs-platform-wallet-ffi/src/tokens/update_config.rs", + "platform_wallet_top_up_external_identity_from_addresses_with_signer": "packages/rs-platform-wallet-ffi/src/identity_top_up.rs", "platform_wallet_top_up_from_addresses_with_signer": "packages/rs-platform-wallet-ffi/src/identity_top_up.rs", "platform_wallet_topup_identity_with_existing_asset_lock_signer": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", "platform_wallet_tracked_asset_locks_free": "packages/rs-platform-wallet-ffi/src/manager_diagnostics.rs", @@ -1464,6 +1465,39 @@ } ] }, + { + "id": "identity.external_top_up_from_addresses", + "title": "Top up an identity the wallet does not manage from Platform addresses", + "area": "correctness", + "shared_apis": [ + "platform_wallet_top_up_external_identity_from_addresses_with_signer" + ], + "required_persistence_capabilities": [], + "hosts": { + "swift": { + "sdk": "supported", + "example_app": "unsupported", + "restart": "not_applicable", + "reason": "ManagedPlatformWallet.topUpExternalIdentityFromAddresses bridges the export; the example app has no screen that pays to someone else's identity." + }, + "kotlin": { + "sdk": "unsupported", + "example_app": "unsupported", + "restart": "not_applicable", + "reason": "No JNI bridge or Kotlin wrapper for the external identity top-up yet." + } + }, + "verification": [ + { + "host": "swift", + "kind": "unit", + "file": "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift", + "id": "testMarshalsArgumentsAndReturnsTheBalanceTheExportWrites", + "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -destination 'platform=iOS Simulator,name=iPhone 17 Pro' -only-testing:SwiftDashSDKTests/ExternalIdentityTopUpTests", + "covers_restart": false + } + ] + }, { "id": "tokens.authorization_decisions", "title": "Shared token authorization and group-proposal decisions", diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index 7bc14e553d1..75cfc041549 100644 --- a/packages/kotlin-sdk/PARITY_SUMMARY.md +++ b/packages/kotlin-sdk/PARITY_SUMMARY.md @@ -2,23 +2,23 @@ # Kotlin/Swift executable parity summary Audit baseline: `PR #3999 @ 6dbc72a54df72d26eb9c4a014b425d2b95134e4e` -Capabilities tracked: **29** +Capabilities tracked: **30** ## Status counts | Host | Surface | Supported | Partial | Unsupported | Not applicable | | --- | --- | ---: | ---: | ---: | ---: | -| Swift | SDK | 16 | 11 | 1 | 1 | -| Swift | Example app | 4 | 14 | 2 | 9 | -| Kotlin | SDK | 13 | 14 | 1 | 1 | -| Kotlin | Example app | 5 | 13 | 1 | 10 | +| Swift | SDK | 17 | 11 | 1 | 1 | +| Swift | Example app | 4 | 14 | 3 | 9 | +| Kotlin | SDK | 13 | 14 | 2 | 1 | +| Kotlin | Example app | 5 | 13 | 2 | 10 | ## Restart coverage | Host | Tested | Required | Not applicable | | --- | ---: | ---: | ---: | -| Swift | 1 | 10 | 18 | -| Kotlin | 4 | 8 | 17 | +| Swift | 1 | 10 | 19 | +| Kotlin | 4 | 8 | 18 | ## Capability status @@ -42,6 +42,7 @@ Capabilities tracked: **29** | `persistence.dashpay_payment_history` | partial / not-applicable / required | not-applicable / not-applicable / not_applicable | | `network.masternode_discovery` | partial / not-applicable / not_applicable | partial / not-applicable / not_applicable | | `identity.platform_address_auto_funding` | partial / partial / not_applicable | partial / partial / not_applicable | +| `identity.external_top_up_from_addresses` | supported / unsupported / not_applicable | unsupported / unsupported / not_applicable | | `tokens.authorization_decisions` | partial / partial / not_applicable | partial / partial / not_applicable | | `tokens.direct_purchase_quote` | partial / partial / not_applicable | partial / partial / not_applicable | | `protocol.address_validation` | supported / supported / not_applicable | partial / partial / not_applicable | diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index ed6400305fd..e439ad482d8 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -774,6 +774,64 @@ public final class ManagedPlatformWallet: @unchecked Sendable { identityId: Data, inputs: [IdentityAddressInput], addressSigner: KeychainSigner + ) async throws -> UInt64 { + try await topUpFromAddresses( + identityId: identityId, + inputs: inputs, + addressSigner: addressSigner, + call: platform_wallet_top_up_from_addresses_with_signer + ) + } + + /// Top up an identity this wallet does **not** manage (someone + /// else's) from one or more Platform addresses. + /// + /// Bridges `platform_wallet_top_up_external_identity_from_addresses_with_signer`: + /// Rust fetches the identity from Platform and never adds it to the + /// wallet's identities, so nothing about it is persisted here either. + /// Arguments, signer handling and error mapping match + /// `topUpFromAddresses`; an identity Platform does not know throws + /// `PlatformWalletError.identityNotFound` before anything is signed. + /// + /// - Returns: the identity's new credit balance reported by Platform. + public func topUpExternalIdentityFromAddresses( + identityId: Data, + inputs: [IdentityAddressInput], + addressSigner: KeychainSigner + ) async throws -> UInt64 { + try await topUpFromAddresses( + identityId: identityId, + inputs: inputs, + addressSigner: addressSigner, + call: platform_wallet_top_up_external_identity_from_addresses_with_signer + ) + } + + /// Signature shared by the two address-funded top-up exports. + typealias AddressTopUpCall = @Sendable ( + Handle, + UnsafePointer?, + UnsafePointer?, + UInt, + OpaquePointer?, + UnsafeMutablePointer? + ) -> PlatformWalletFFIResult + + typealias IdentityIdBytes = ( + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, + UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8 + ) + + /// Guards and marshalling shared by the address-funded top-ups; + /// `call` is the export to hand the marshalled arguments to. + /// `internal` so tests can observe the marshalling. + func topUpFromAddresses( + identityId: Data, + inputs: [IdentityAddressInput], + addressSigner: KeychainSigner, + call: @escaping AddressTopUpCall ) async throws -> UInt64 { guard identityId.count == 32 else { throw PlatformWalletError.invalidParameter( @@ -806,12 +864,7 @@ public final class ManagedPlatformWallet: @unchecked Sendable { // the Swift owner stays alive across this detached work. _ = addressSigner - var idTuple: ( - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, - UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8 - ) = ( + var idTuple: IdentityIdBytes = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -842,7 +895,7 @@ public final class ManagedPlatformWallet: @unchecked Sendable { let result = ffiInputs.withUnsafeBufferPointer { inputsBuf in withUnsafePointer(to: &idTuple) { idPtr in - platform_wallet_top_up_from_addresses_with_signer( + call( handle, idPtr, inputsBuf.baseAddress, diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift new file mode 100644 index 00000000000..b764142aa0b --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift @@ -0,0 +1,148 @@ +import DashSDKFFI +import Foundation +import XCTest +@testable import SwiftDashSDK + +/// `topUpExternalIdentityFromAddresses` is a bridge to +/// `platform_wallet_top_up_external_identity_from_addresses_with_signer`: +/// it rejects malformed arguments before the FFI, hands the rest to the +/// export and maps the export's result code. Nothing here reaches Platform. +final class ExternalIdentityTopUpTests: XCTestCase { + + private let identityId = Data((0..<32).map { UInt8($0) }) + private let input = ManagedPlatformWallet.IdentityAddressInput( + addressType: 0, hash: Data(repeating: 0xAB, count: 20), credits: 1_000 + ) + + private func wallet() -> ManagedPlatformWallet { + ManagedPlatformWallet(handle: NULL_HANDLE, walletId: Data()) + } + + private func signer() throws -> KeychainSigner { + KeychainSigner(modelContainer: try DashModelContainer.createInMemory(), network: .testnet) + } + + private func assertInvalidParameter( + identityId: Data, + inputs: [ManagedPlatformWallet.IdentityAddressInput], + contains expected: String, + file: StaticString = #filePath, + line: UInt = #line + ) async throws { + do { + _ = try await wallet().topUpExternalIdentityFromAddresses( + identityId: identityId, inputs: inputs, addressSigner: try signer() + ) + XCTFail("expected invalidParameter", file: file, line: line) + } catch PlatformWalletError.invalidParameter(let message) { + XCTAssertTrue(message.contains(expected), "got \(message)", file: file, line: line) + } catch { + XCTFail("expected invalidParameter, got \(error)", file: file, line: line) + } + } + + func testRejectsIdentityIdThatIsNot32BytesBeforeTheFFI() async throws { + try await assertInvalidParameter( + identityId: Data(repeating: 1, count: 31), inputs: [input], + contains: "identityId must be 32 bytes, got 31" + ) + } + + func testRejectsEmptyInputsBeforeTheFFI() async throws { + try await assertInvalidParameter( + identityId: identityId, inputs: [], contains: "inputs is empty" + ) + } + + func testRejectsMalformedAddressHashBeforeTheFFI() async throws { + let short = ManagedPlatformWallet.IdentityAddressInput( + addressType: 0, hash: Data(repeating: 0xAB, count: 19), credits: 1 + ) + try await assertInvalidParameter( + identityId: identityId, inputs: [input, short], + contains: "input hash must be 20 bytes, got 19" + ) + } + + /// Well-formed arguments reach the real export, which resolves the wallet + /// handle first: an unknown handle comes back as the registry's `notFound`. + func testWellFormedCallReachesTheExportAndMapsItsCode() async throws { + do { + _ = try await wallet().topUpExternalIdentityFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) + XCTFail("a null wallet handle must not report a balance") + } catch PlatformWalletError.notFound { + } catch { + XCTFail("expected notFound from the export, got \(error)") + } + } + + // MARK: - Marshalling through the shared helper + + func testMarshalsArgumentsAndReturnsTheBalanceTheExportWrites() async throws { + let signer = try signer() + let recorder = Recorder() + let inputs = [ + input, + .init(addressType: 1, hash: Data(repeating: 0xCD, count: 20), credits: 7) + ] + let balance = try await ManagedPlatformWallet(handle: 42, walletId: Data()) + .topUpFromAddresses( + identityId: identityId, inputs: inputs, addressSigner: signer + ) { handle, idPtr, inputsPtr, count, signerHandle, outBalance in + recorder.record( + handle: handle, + id: withUnsafeBytes(of: idPtr!.pointee) { Data($0) }, + rows: Array(UnsafeBufferPointer(start: inputsPtr, count: Int(count))), + signer: signerHandle + ) + outBalance!.pointee = 123_456 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + + XCTAssertEqual(balance, 123_456) + XCTAssertEqual(recorder.handle, 42) + XCTAssertEqual(recorder.id, identityId) + XCTAssertEqual(recorder.signer, signer.handle) + XCTAssertEqual(recorder.rows.map(\.address_type), [0, 1]) + XCTAssertEqual(recorder.rows.map(\.credits), [1_000, 7]) + XCTAssertEqual( + recorder.rows.map { row in withUnsafeBytes(of: row.hash) { Data($0) } }, + [Data(repeating: 0xAB, count: 20), Data(repeating: 0xCD, count: 20)] + ) + } + + func testIdentityNotFoundCodeMapsToIdentityNotFound() async throws { + XCTAssertEqual(PlatformWalletResultCode.errorIdentityNotFound.rawValue, 7) + do { + _ = try await wallet().topUpFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) { _, _, _, _, _, _ in + PlatformWalletFFIResult( + code: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_IDENTITY_NOT_FOUND, + message: strdup("identity not found on Platform") + ) + } + XCTFail("code 7 must throw") + } catch PlatformWalletError.identityNotFound(let message) { + XCTAssertEqual(message, "identity not found on Platform") + } catch { + XCTFail("expected identityNotFound, got \(error)") + } + } + + private final class Recorder: @unchecked Sendable { + var handle: Handle = NULL_HANDLE + var id = Data() + var rows: [IdentityFundingInputFFI] = [] + var signer: OpaquePointer? + + func record(handle: Handle, id: Data, rows: [IdentityFundingInputFFI], signer: OpaquePointer?) { + self.handle = handle + self.id = id + self.rows = rows + self.signer = signer + } + } +} From 2271e8cd43b08ddabf0311fd2e2cc4d843097c96 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 16:29:44 +0200 Subject: [PATCH 03/19] fix(platform-wallet): fence the external identity top-up and own the funding-row policy Review fixes for the external identity top-up: - The external composite takes the wallet generation's payment guard and checks the generation is current before fetching the identity, holding it through signing, broadcast and reconcile; a removed or recreated wallet gets WalletRemovedBeforeSend with nothing signed or sent. - platform-wallet now takes the funding rows, sums repeated addresses and refuses an overflowing sum with InvalidParameter; the FFI only converts row types, for both the managed and the external export. The managed export now errors on overflow instead of saturating, and its empty-input check moves to the library. - The SDK's TransitionNoInputsError maps to InvalidParameter on both routes. - Swift: the shared helper pins addressSigner with withExtendedLifetime across the synchronous FFI call; the exports are injectable and a test through both public wrappers shows each calls its own export. - A composite seam test covers a confirmed external top-up: balance returned, spent address reconciled and persisted at the proof height, identity manager unchanged. Co-Authored-By: Claude Opus 5.5 --- .../src/identity_top_up.rs | 70 +--- .../external_identity_tests.rs | 114 +++++- .../identity/network/top_up_from_addresses.rs | 74 +++- .../external_identity_tests.rs | 370 +++++++++++++++++- .../src/wallet/platform_wallet.rs | 57 ++- .../ManagedPlatformWallet.swift | 48 ++- .../ExternalIdentityTopUpTests.swift | 29 ++ 7 files changed, 644 insertions(+), 118 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs index 141a632b419..4dbf755007e 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs @@ -27,7 +27,6 @@ //! callers can re-read the balance via `ManagedIdentity` once this //! returns. -use std::collections::BTreeMap; use std::slice; use dpp::address_funds::PlatformAddress; @@ -86,8 +85,8 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( check_ptr!(out_new_balance); let identity_id_bytes: [u8; 32] = *identity_id; let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); - let input_map = match input_map(inputs, inputs_count) { - Ok(input_map) => input_map, + let rows = match funding_rows(inputs, inputs_count) { + Ok(rows) => rows, Err(error) => return error, }; @@ -107,7 +106,7 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( // (covering addresses restored from disk that are no longer in // a live derived pool). wallet - .top_up_from_addresses(&identity_id, input_map, address_signer, None) + .top_up_from_addresses(&identity_id, rows, address_signer, None) .await }) }); @@ -118,49 +117,27 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( } /// Marshal the address-input rows of an address-funded top-up into the -/// input map the library takes. +/// funding rows the library takes; the library sums rows naming the same +/// address and refuses what it cannot act on. /// /// # Safety /// `inputs` must point at a valid `[IdentityFundingInputFFI; inputs_count]` /// array. -unsafe fn input_map( +unsafe fn funding_rows( inputs: *const IdentityFundingInputFFI, inputs_count: usize, -) -> Result, PlatformWalletFFIResult> { - if inputs_count == 0 { - return Err(PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidParameter, - "`inputs_count` is zero", - )); - } - - let entries = slice::from_raw_parts(inputs, inputs_count); - let mut input_map: BTreeMap = BTreeMap::new(); - for entry in entries { - let address = match entry.address_type { - 0 => PlatformAddress::P2pkh(entry.hash), - 1 => PlatformAddress::P2sh(entry.hash), - _ => { - return Err(PlatformWalletFFIResult::err( - PlatformWalletFFIResultCode::ErrorInvalidParameter, - "invalid address_type (expected 0 or 1)", - )); - } - }; - // Caller may pass the same address twice (the Swift inputs - // builder is greedy and could legitimately split a single - // address across multiple rows in a future shape). Sum the - // contributions rather than overwriting — `BTreeMap::insert` - // would silently keep only the last credit value, causing - // the top-up to under-fund the identity by the difference. - // Saturating add keeps a pathological caller from looping - // overflow back to a small value. - input_map - .entry(address) - .and_modify(|existing| *existing = existing.saturating_add(entry.credits)) - .or_insert(entry.credits); - } - Ok(input_map) +) -> Result, PlatformWalletFFIResult> { + slice::from_raw_parts(inputs, inputs_count) + .iter() + .map(|entry| match entry.address_type { + 0 => Ok((PlatformAddress::P2pkh(entry.hash), entry.credits)), + 1 => Ok((PlatformAddress::P2sh(entry.hash), entry.credits)), + _ => Err(PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "invalid address_type (expected 0 or 1)", + )), + }) + .collect() } /// Top up an identity this wallet does **not** manage (someone else's) @@ -196,8 +173,8 @@ pub unsafe extern "C" fn platform_wallet_top_up_external_identity_from_addresses check_ptr!(out_new_balance); let identity_id_bytes: [u8; 32] = *identity_id; let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); - let input_map = match input_map(inputs, inputs_count) { - Ok(input_map) => input_map, + let rows = match funding_rows(inputs, inputs_count) { + Ok(rows) => rows, Err(error) => return error, }; @@ -210,12 +187,7 @@ pub unsafe extern "C" fn platform_wallet_top_up_external_identity_from_addresses block_on_worker(async move { let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; wallet - .top_up_external_identity_from_addresses( - &identity_id, - input_map, - address_signer, - None, - ) + .top_up_external_identity_from_addresses(&identity_id, rows, address_signer, None) .await }) }); diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs index 44531b678e1..9900a792456 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs @@ -6,7 +6,7 @@ use std::sync::Arc; use dpp::address_funds::AddressWitness; use dpp::identity::signer::Signer; -use dpp::identity::{Identity, IdentityPublicKey}; +use dpp::identity::{Identity, IdentityPublicKey, IdentityV0}; use dpp::platform_value::BinaryData; use dpp::prelude::Identifier; use dpp::ProtocolError; @@ -14,8 +14,9 @@ use key_wallet::wallet::initialization::WalletAccountCreationOptions; use rs_sdk_ffi::{SignerHandle, VTableSigner}; use super::platform_wallet_top_up_external_identity_from_addresses_with_signer as top_up; +use super::platform_wallet_top_up_from_addresses_with_signer; use crate::error::PlatformWalletFFIResultCode; -use crate::handle::PLATFORM_WALLET_STORAGE; +use crate::handle::{Handle, PLATFORM_WALLET_STORAGE}; use crate::identity_registration::IdentityFundingInputFFI; use crate::runtime::runtime; use crate::test_fixtures::mock_manager; @@ -103,19 +104,9 @@ fn should_refuse_null_pointers() { } #[test] -fn should_refuse_empty_inputs_and_an_unknown_address_type() { +fn should_refuse_an_unknown_address_type() { let id = IDENTITY; let mut balance = UNTOUCHED; - let empty = unsafe { - top_up( - 0, - &id, - [input(0)].as_ptr(), - 0, - dangling_signer(), - &mut balance, - ) - }; let unknown_type = unsafe { top_up( 0, @@ -127,16 +118,109 @@ fn should_refuse_empty_inputs_and_an_unknown_address_type() { ) }; assert_eq!( - empty.code, + unknown_type.code, PlatformWalletFFIResultCode::ErrorInvalidParameter ); + assert_eq!(balance, UNTOUCHED); +} + +/// A wallet handle over a mock SDK that knows `on_platform` under +/// [`IDENTITY`], and a signer that is never asked to sign. +fn wallet_handle(on_platform: Option) -> (Handle, *mut SignerHandle) { + let manager = mock_manager(); + let mut sdk = manager.sdk().clone(); + runtime() + .block_on( + sdk.mock() + .expect_fetch::(Identifier::from(IDENTITY), on_platform), + ) + .expect("the fetch expectation"); + let wallet = runtime() + .block_on(manager.create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + )) + .expect("a wallet"); + let signer = Box::into_raw(Box::new(VTableSigner::from_native(Arc::new(UnusedSigner)))) + as *mut SignerHandle; + (PLATFORM_WALLET_STORAGE.insert(wallet), signer) +} + +fn release(handle: Handle, signer: *mut SignerHandle) { + let _ = PLATFORM_WALLET_STORAGE.remove(handle); + drop(unsafe { Box::from_raw(signer as *mut VTableSigner) }); +} + +/// Rows naming one address whose sum overflows reach the library, which +/// refuses them as an invalid parameter on both exports instead of +/// saturating the amount. +#[test] +fn should_refuse_an_overflowing_funding_sum_on_both_exports() { + let (handle, signer) = wallet_handle(Some(platform_identity())); + let rows = [ + IdentityFundingInputFFI { + credits: u64::MAX, + ..input(0) + }, + IdentityFundingInputFFI { + credits: 1, + ..input(0) + }, + ]; + let id = IDENTITY; + let mut balance = UNTOUCHED; + + let external = unsafe { top_up(handle, &id, rows.as_ptr(), 2, signer, &mut balance) }; + let managed = unsafe { + platform_wallet_top_up_from_addresses_with_signer( + handle, + &id, + rows.as_ptr(), + 2, + signer, + &mut balance, + ) + }; + + release(handle, signer); + for result in [external, managed] { + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorInvalidParameter + ); + } + assert_eq!(balance, UNTOUCHED); +} + +/// No funding rows reach the library, whose refusal (the SDK's own +/// empty-input check) comes back as an invalid parameter. +#[test] +fn should_report_empty_inputs_as_an_invalid_parameter() { + let (handle, signer) = wallet_handle(Some(platform_identity())); + let id = IDENTITY; + let mut balance = UNTOUCHED; + + let result = unsafe { top_up(handle, &id, [input(0)].as_ptr(), 0, signer, &mut balance) }; + + release(handle, signer); assert_eq!( - unknown_type.code, + result.code, PlatformWalletFFIResultCode::ErrorInvalidParameter ); assert_eq!(balance, UNTOUCHED); } +fn platform_identity() -> Identity { + Identity::V0(IdentityV0 { + id: Identifier::from(IDENTITY), + public_keys: Default::default(), + balance: 0, + revision: 0, + }) +} + /// The identity is looked up on Platform, not in the wallet: an identity /// Platform does not know is `ErrorIdentityNotFound` (7), the balance out /// is not written, and the wallet still manages no identity. diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 46a703a17b5..3b7e8a1f873 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -12,6 +12,8 @@ use dash_sdk::platform::transition::top_up_identity_from_addresses::TopUpIdentit use dash_sdk::platform::Fetch; use dpp::address_funds::PlatformAddress; +use dpp::consensus::basic::BasicError; +use dpp::consensus::ConsensusError; use dpp::fee::Credits; use dash_sdk::query_types::AddressInfos; @@ -54,18 +56,25 @@ impl IdentityWallet { /// # Arguments /// /// * `identity_id` - The identity to top up. - /// * `inputs` - Map of platform addresses to credit amounts to spend. + /// * `inputs` - Funding rows: platform addresses and the credits to + /// spend from each. Rows naming the same address are summed; a sum + /// that overflows is refused as an invalid parameter. /// * `address_signer` - Produces ECDSA signatures for the input /// [`PlatformAddress`]es. Construction is the caller's concern — /// seed-backed, hardware, FFI trampoline, whatever — the wallet /// struct carries no key material itself. - pub async fn top_up_from_addresses + Send + Sync>( + pub async fn top_up_from_addresses( &self, identity_id: &Identifier, - inputs: BTreeMap, + inputs: I, address_signer: &S, settings: Option, - ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> { + ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> + where + S: Signer + Send + Sync, + I: IntoIterator + Send, + { + let inputs = funding_inputs(inputs)?; let identity = { let wm = self.wallet_manager.read().await; let info = wm.get_wallet_info(&self.wallet_id).ok_or_else(|| { @@ -124,16 +133,22 @@ impl IdentityWallet { /// /// Returns [`PlatformWalletError::IdentityNotFound`] before anything is /// signed or broadcast when Platform has no identity with this id. + /// `inputs` are funding rows as for [`Self::top_up_from_addresses`]. /// /// [`PlatformWallet::top_up_external_identity_from_addresses`]: /// crate::wallet::PlatformWallet::top_up_external_identity_from_addresses - pub async fn top_up_external_from_addresses + Send + Sync>( + pub async fn top_up_external_from_addresses( &self, identity_id: &Identifier, - inputs: BTreeMap, + inputs: I, address_signer: &S, settings: Option, - ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> { + ) -> Result<(AddressInfos, Credits, u64), PlatformWalletError> + where + S: Signer + Send + Sync, + I: IntoIterator + Send, + { + let inputs = funding_inputs(inputs)?; let identity = Identity::fetch(&self.sdk, *identity_id) .await? .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; @@ -158,13 +173,46 @@ impl IdentityWallet { .await .map_err(|e| { preserve_signer_key_unavailable_or(e, |e| { - promote_address_nonce_error(&e).unwrap_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to top up identity from addresses: {}", - e - )) - }) + promote_address_nonce_error(&e) + .or_else(|| no_inputs_as_invalid_parameter(&e)) + .unwrap_or_else(|| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to top up identity from addresses: {}", + e + )) + }) }) }) } } + +/// The input map of an address-funded top-up from its funding rows: rows +/// naming the same address are one input of their sum. A sum that overflows +/// is refused with [`PlatformWalletError::InvalidParameter`]. No rows make an +/// empty map, which the SDK refuses as a transition without inputs. +pub(crate) fn funding_inputs( + rows: impl IntoIterator, +) -> Result, PlatformWalletError> { + let mut inputs = BTreeMap::new(); + for (address, credits) in rows { + let sum: &mut Credits = inputs.entry(address).or_default(); + *sum = sum.checked_add(credits).ok_or_else(|| { + PlatformWalletError::InvalidParameter(format!( + "the funding amounts for {address:?} overflow" + )) + })?; + } + Ok(inputs) +} + +/// The SDK's refusal of a transition without inputs, reported as the +/// caller's mistake it is. +fn no_inputs_as_invalid_parameter(error: &dash_sdk::Error) -> Option { + matches!( + error.consensus_error(), + Some(ConsensusError::BasicError( + BasicError::TransitionNoInputsError(_) + )) + ) + .then(|| PlatformWalletError::InvalidParameter(error.to_string())) +} diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index 96b18e90cba..a88f2eb5531 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -13,7 +13,8 @@ use std::collections::{BTreeMap, BTreeSet}; use std::sync::atomic::{AtomicUsize, Ordering}; -use std::sync::Arc; +use std::sync::{Arc, Mutex}; +use std::time::Duration; use dash_sdk::dapi_client::mock::MockResult; use dash_sdk::dapi_client::transport::TransportRequest; @@ -40,11 +41,17 @@ use dpp::state_transition::identity_topup_from_addresses_transition::methods::Id use dpp::state_transition::identity_topup_from_addresses_transition::IdentityTopUpFromAddressesTransition; use dpp::version::PlatformVersion; use dpp::ProtocolError; +use key_wallet::account::account_collection::PlatformPaymentAccountKey; use key_wallet::wallet::initialization::WalletAccountCreationOptions; +use tokio::sync::{Notify, Semaphore}; +use crate::changeset::{ + ClientStartState, PersistenceError, PlatformWalletChangeSet, PlatformWalletPersistence, +}; use crate::error::PlatformWalletError; use crate::events::{EventHandler, PlatformEventHandler}; use crate::wallet::persister::NoPlatformPersistence; +use crate::wallet::platform_wallet::WalletId; use crate::{PlatformWallet, PlatformWalletManager}; const ADDRESS: PlatformAddress = PlatformAddress::P2pkh([7; 20]); @@ -91,6 +98,16 @@ fn identity(id: [u8; 32]) -> Identity { }) } +fn settings() -> Option { + Some(PutSettings { + request_settings: RequestSettings { + retries: Some(0), + ..Default::default() + }, + ..Default::default() + }) +} + fn save(directory: &tempfile::TempDir, request: &R, response: &MockResult) { let dump = DumpData::new(request, response); dump.save(&directory.path().join(dump.filename().unwrap())) @@ -108,6 +125,7 @@ fn response(inner: R) -> ExecutionResponse { /// A wallet managing [`OWN_IDENTITY`], with Platform knowing `on_platform` /// (or nothing) under `target`, and a funded [`ADDRESS`]. struct Fixture { + manager: Arc>, wallet: Arc, sdk: Sdk, target: Identifier, @@ -181,11 +199,11 @@ impl Fixture { ) .await .unwrap(); - let manager = PlatformWalletManager::new( + let manager = Arc::new(PlatformWalletManager::new( Arc::new(sdk.clone()), Arc::new(NoPlatformPersistence), Arc::new(NoopEvents), - ); + )); let wallet = manager .create_wallet_from_seed_bytes( key_wallet::Network::Testnet, @@ -210,6 +228,7 @@ impl Fixture { ) .unwrap(); Self { + manager, wallet, sdk, target: target.id(), @@ -220,18 +239,29 @@ impl Fixture { } async fn top_up(&self) -> Result { + self.top_up_with(vec![(ADDRESS, AMOUNT)]).await + } + + async fn top_up_with( + &self, + inputs: Vec<(PlatformAddress, u64)>, + ) -> Result { self.wallet - .top_up_external_identity_from_addresses( - &self.target, - BTreeMap::from([(ADDRESS, AMOUNT)]), + .top_up_external_identity_from_addresses(&self.target, inputs, &self.signer, settings()) + .await + } + + /// The managed route, topping up [`OWN_IDENTITY`]. + async fn top_up_own_with( + &self, + inputs: Vec<(PlatformAddress, u64)>, + ) -> Result { + self.wallet + .top_up_from_addresses( + &Identifier::from(OWN_IDENTITY), + inputs, &self.signer, - Some(PutSettings { - request_settings: RequestSettings { - retries: Some(0), - ..Default::default() - }, - ..Default::default() - }), + settings(), ) .await } @@ -309,3 +339,317 @@ async fn should_refuse_an_identity_platform_does_not_know_without_submitting() { vec![Identifier::from(OWN_IDENTITY)] ); } + +/// An empty funding map is the caller's mistake on both routes: the SDK's +/// own empty-input refusal comes back as `InvalidParameter`, with nothing +/// signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_report_empty_inputs_as_an_invalid_parameter_on_both_routes() { + let mut fixture = Fixture::new(true).await; + + let external = fixture.top_up_with(Vec::new()).await; + let managed = fixture.top_up_own_with(Vec::new()).await; + + for result in [external, managed] { + assert!( + matches!(result, Err(PlatformWalletError::InvalidParameter(_))), + "got {result:?}" + ); + } + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} + +/// A handle to a wallet removed, or re-created under the same id, since it +/// was taken tops up nothing: refused before the identity is fetched, +/// anything is signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_refuse_a_top_up_from_a_wallet_no_longer_current() { + let mut fixture = Fixture::new(true).await; + let wallet_id = fixture.wallet.wallet_id(); + fixture + .manager + .remove_wallet(&wallet_id) + .await + .expect("removed"); + + let removed = fixture.top_up().await; + assert!( + matches!(&removed, Err(PlatformWalletError::WalletRemovedBeforeSend(id)) + if *id == hex::encode(wallet_id)), + "{removed:?}" + ); + + let recreated = fixture + .manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .expect("re-created"); + assert_eq!(recreated.wallet_id(), wallet_id); + let superseded = fixture.top_up().await; + assert!( + matches!( + superseded, + Err(PlatformWalletError::WalletRemovedBeforeSend(_)) + ), + "{superseded:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} + +/// Signs like [`AddressSigner`], but only once released: holds a top-up in +/// its signing step. +#[derive(Debug)] +struct HeldSigner { + entered: Notify, + release: Semaphore, +} + +impl Default for HeldSigner { + fn default() -> Self { + Self { + entered: Notify::new(), + release: Semaphore::new(0), + } + } +} + +#[async_trait::async_trait] +impl Signer for HeldSigner { + async fn sign(&self, key: &PlatformAddress, data: &[u8]) -> Result { + self.entered.notify_one(); + self.release + .acquire() + .await + .map_err(|e| ProtocolError::Generic(e.to_string()))? + .forget(); + AddressSigner::default().sign(key, data).await + } + + async fn sign_create_witness( + &self, + key: &PlatformAddress, + data: &[u8], + ) -> Result { + Ok(AddressWitness::P2pkh { + signature: self.sign(key, data).await?, + }) + } + + fn can_sign_with(&self, _: &PlatformAddress) -> bool { + true + } +} + +/// A removal waits for an external top-up that entered its fenced section, +/// here held while signing, and completes once the top-up returns. +#[tokio::test(flavor = "multi_thread")] +async fn should_hold_a_wallets_removal_until_its_top_up_returns() { + let fixture = Fixture::new(true).await; + let wallet_id = fixture.wallet.wallet_id(); + let signer = Arc::new(HeldSigner::default()); + let top_up = { + let wallet = Arc::clone(&fixture.wallet); + let signer = Arc::clone(&signer); + let target = fixture.target; + tokio::spawn(async move { + wallet + .top_up_external_identity_from_addresses( + &target, + BTreeMap::from([(ADDRESS, AMOUNT)]), + &*signer, + settings(), + ) + .await + }) + }; + signer.entered.notified().await; + + let removal = { + let manager = Arc::clone(&fixture.manager); + tokio::spawn(async move { manager.remove_wallet(&wallet_id).await.map(|_| ()) }) + }; + tokio::time::sleep(Duration::from_millis(200)).await; + assert!( + !removal.is_finished(), + "the removal waits for the top-up being signed" + ); + assert!(fixture.wallet.core().is_current_generation().await); + + signer.release.add_permits(1); + let topped_up = top_up.await.expect("top-up task"); + assert!( + !matches!( + topped_up, + Err(PlatformWalletError::WalletRemovedBeforeSend(_)) + ), + "the wallet was current when it was checked: {topped_up:?}" + ); + removal + .await + .expect("removal task") + .expect("the removal completes"); + assert!(!fixture.wallet.core().is_current_generation().await); +} + +/// Records every store round. +#[derive(Default)] +struct RecordingPersister(Mutex>); + +impl PlatformWalletPersistence for RecordingPersister { + fn store( + &self, + _: WalletId, + changeset: PlatformWalletChangeSet, + ) -> Result<(), PersistenceError> { + self.0.lock().unwrap().push(changeset); + Ok(()) + } + + fn flush(&self, _: WalletId) -> Result<(), PersistenceError> { + Ok(()) + } + + fn load(&self) -> Result { + Ok(ClientStartState::default()) + } +} + +/// A confirmed external top-up, through the composite's seam with a +/// proof-attested result in place of the network: the identity's new +/// balance is returned, the spent wallet address is reconciled and +/// persisted pinned at the proof's height, and the identity manager is +/// still unchanged. +#[tokio::test(flavor = "multi_thread")] +async fn should_reconcile_the_spent_addresses_of_a_confirmed_top_up() { + const NEW_BALANCE: u64 = 777_000; + const PROOF_HEIGHT: u64 = 4_242; + let persister = Arc::new(RecordingPersister::default()); + let manager = PlatformWalletManager::new( + Arc::new(dash_sdk::Sdk::new_mock()), + Arc::clone(&persister), + Arc::new(NoopEvents), + ); + let wallet = manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[42; 64], + WalletAccountCreationOptions::Default, + Some(0), + ) + .await + .expect("a wallet"); + let spent = wallet + .platform() + .next_unused_receive_address(PlatformPaymentAccountKey { + account: 0, + key_class: 0, + }) + .await + .expect("a wallet address"); + let identities_before = wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&wallet.wallet_id()) + .unwrap() + .identity_manager + .identity_ids(); + persister.0.lock().unwrap().clear(); + + let confirmed = AddressInfos::from_iter([( + spent, + Some(AddressInfo { + address: spent, + nonce: 4, + balance: 5, + }), + )]); + let new_balance = wallet + .top_up_external_identity_with(async { Ok((confirmed, NEW_BALANCE, PROOF_HEIGHT)) }) + .await + .expect("a confirmed top-up"); + + assert_eq!(new_balance, NEW_BALANCE); + assert!(wallet + .platform() + .addresses_with_balances() + .await + .contains(&(spent, 5))); + { + let stored = persister.0.lock().unwrap(); + let entry = stored + .iter() + .filter_map(|changeset| changeset.platform_addresses.as_ref()) + .flat_map(|addresses| addresses.addresses.iter()) + .find(|entry| PlatformAddress::P2pkh(entry.address.to_bytes()) == spent) + .expect("the spent address persisted"); + assert_eq!( + ( + entry.funds.balance, + entry.funds.nonce, + entry.funds.as_of_height + ), + (5, 4, PROOF_HEIGHT) + ); + assert!(stored + .iter() + .all(|changeset| changeset.identities.is_none())); + } + assert_eq!( + wallet + .wallet_manager() + .read() + .await + .get_wallet_info(&wallet.wallet_id()) + .unwrap() + .identity_manager + .identity_ids(), + identities_before + ); +} + +/// Funding rows naming the same address are one input of their sum: the +/// submitted transition is the one built from the single summed input. +#[tokio::test(flavor = "multi_thread")] +async fn should_sum_repeated_funding_rows_into_one_input() { + let mut fixture = Fixture::new(true).await; + + let error = fixture + .top_up_with(vec![(ADDRESS, AMOUNT - 1), (ADDRESS, 1)]) + .await + .expect_err("the mock cannot prove the result"); + + assert!( + matches!( + error, + PlatformWalletError::Sdk(dash_sdk::Error::StateTransitionResultUnconfirmed(_)) + ), + "the summed top-up must be submitted, got {error:?}" + ); + assert_eq!(fixture.submissions().await, (1, 1, 1)); +} + +/// Rows whose sum for one address overflows are refused as the caller's +/// mistake on both routes, never saturated, with nothing signed or +/// submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_refuse_an_overflowing_funding_sum_on_both_routes() { + let mut fixture = Fixture::new(true).await; + let rows = vec![(ADDRESS, u64::MAX), (ADDRESS, 1)]; + + let external = fixture.top_up_with(rows.clone()).await; + let managed = fixture.top_up_own_with(rows).await; + + for result in [external, managed] { + assert!( + matches!(result, Err(PlatformWalletError::InvalidParameter(_))), + "got {result:?}" + ); + } + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index b9dc1dfe149..0ae7ace84f7 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -1,6 +1,7 @@ //! The main PlatformWallet struct combining core, identity (+DashPay), and platform sub-wallets. use std::collections::BTreeMap; +use std::future::Future; use std::ops::{Deref, DerefMut}; use std::sync::Arc; @@ -39,6 +40,7 @@ use crate::changeset::{ }; use crate::error::PlatformWalletError; use dash_sdk::platform::transition::put_settings::PutSettings; +use dash_sdk::query_types::AddressInfos; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; use dpp::identity::signer::Signer; @@ -582,13 +584,17 @@ impl PlatformWallet { /// a later sync reconciles. /// /// Returns the identity's new credit balance. - pub async fn top_up_from_addresses + Send + Sync>( + pub async fn top_up_from_addresses( &self, identity_id: &Identifier, - inputs: BTreeMap, + inputs: I, address_signer: &S, settings: Option, - ) -> Result { + ) -> Result + where + S: Signer + Send + Sync, + I: IntoIterator + Send, + { let (address_infos, new_balance, proof_height) = self .identity .top_up_from_addresses(identity_id, inputs, address_signer, settings) @@ -609,20 +615,49 @@ impl PlatformWallet { /// See [`IdentityWallet::top_up_external_from_addresses`]: the identity /// is fetched from Platform and never added to the identity manager. /// + /// Holds the wallet generation's lifecycle gate from the liveness check + /// through the fetch, signing, broadcast and reconciliation, so a + /// removal waits for it. A wallet removed or re-created since this + /// handle was taken is refused with + /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing + /// fetched, signed or broadcast. A caller must not hold the gate. + /// /// Returns the identity's new credit balance. - pub async fn top_up_external_identity_from_addresses< - S: Signer + Send + Sync, - >( + pub async fn top_up_external_identity_from_addresses( &self, identity_id: &Identifier, - inputs: BTreeMap, + inputs: I, address_signer: &S, settings: Option, + ) -> Result + where + S: Signer + Send + Sync, + I: IntoIterator + Send, + { + self.top_up_external_identity_with(self.identity.top_up_external_from_addresses( + identity_id, + inputs, + address_signer, + settings, + )) + .await + } + + /// The external top-up around its submission `top_up` (not yet + /// started): the lifecycle gate and liveness check, then the + /// reconciliation of the spent addresses at the proof's height. A seam + /// so a test can hand in a confirmed result the mock SDK cannot prove. + pub(crate) async fn top_up_external_identity_with( + &self, + top_up: impl Future>, ) -> Result { - let (address_infos, new_balance, proof_height) = self - .identity - .top_up_external_from_addresses(identity_id, inputs, address_signer, settings) - .await?; + let _lifecycle = self.core().generation_payment_guard().await; + if !self.core().is_current_generation().await { + return Err(PlatformWalletError::WalletRemovedBeforeSend(hex::encode( + self.wallet_id, + ))); + } + let (address_infos, new_balance, proof_height) = top_up.await?; self.platform .reconcile_address_infos(&address_infos, proof_height, "external identity top-up") .await; diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index e439ad482d8..add95fbaca4 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -779,7 +779,7 @@ public final class ManagedPlatformWallet: @unchecked Sendable { identityId: identityId, inputs: inputs, addressSigner: addressSigner, - call: platform_wallet_top_up_from_addresses_with_signer + call: addressTopUpExports.managed ) } @@ -803,10 +803,21 @@ public final class ManagedPlatformWallet: @unchecked Sendable { identityId: identityId, inputs: inputs, addressSigner: addressSigner, - call: platform_wallet_top_up_external_identity_from_addresses_with_signer + call: addressTopUpExports.external ) } + /// The two address-funded top-up exports each public wrapper hands its + /// arguments to. A stored property so tests can swap in fakes and see + /// which export a wrapper dispatches to. + struct AddressTopUpExports { + var managed: AddressTopUpCall = platform_wallet_top_up_from_addresses_with_signer + var external: AddressTopUpCall = + platform_wallet_top_up_external_identity_from_addresses_with_signer + } + + var addressTopUpExports = AddressTopUpExports() + /// Signature shared by the two address-funded top-up exports. typealias AddressTopUpCall = @Sendable ( Handle, @@ -859,11 +870,6 @@ public final class ManagedPlatformWallet: @unchecked Sendable { let addressSignerHandle = addressSigner.handle return try await Task.detached(priority: .userInitiated) { () -> UInt64 in - // Keepalive — see `registerIdentityFromAddresses` for - // rationale. The trampoline ctx pointer dangles unless - // the Swift owner stays alive across this detached work. - _ = addressSigner - var idTuple: IdentityIdBytes = ( 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, @@ -893,16 +899,24 @@ public final class ManagedPlatformWallet: @unchecked Sendable { var newBalance: UInt64 = 0 - let result = ffiInputs.withUnsafeBufferPointer { inputsBuf in - withUnsafePointer(to: &idTuple) { idPtr in - call( - handle, - idPtr, - inputsBuf.baseAddress, - UInt(inputsBuf.count), - addressSignerHandle, - &newBalance - ) + // `KeychainSigner` registers itself with the Rust signer as a + // `passUnretained` ctx and destroys the handle in `deinit`, and + // Swift lifetimes end at last use, not at scope end — a bare + // `_ = addressSigner` is no fence. `withExtendedLifetime` pins + // it across the whole synchronous FFI call (lookup, signing, + // broadcast and wait) and its buffer pinning. + let result = withExtendedLifetime(addressSigner) { + ffiInputs.withUnsafeBufferPointer { inputsBuf in + withUnsafePointer(to: &idTuple) { idPtr in + call( + handle, + idPtr, + inputsBuf.baseAddress, + UInt(inputsBuf.count), + addressSignerHandle, + &newBalance + ) + } } } diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift index b764142aa0b..45e88fc19a8 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ExternalIdentityTopUpTests.swift @@ -78,6 +78,35 @@ final class ExternalIdentityTopUpTests: XCTestCase { } } + // MARK: - Export selection + + /// Each public wrapper hands its arguments to its own export: the + /// external top-up never reaches the managed one, which would refuse an + /// identity the wallet does not manage. + func testEachWrapperDispatchesToItsOwnExport() async throws { + let wallet = ManagedPlatformWallet(handle: 42, walletId: Data()) + wallet.addressTopUpExports = .init( + managed: { _, _, _, _, _, outBalance in + outBalance!.pointee = 1 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + }, + external: { _, _, _, _, _, outBalance in + outBalance!.pointee = 2 + return PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + ) + + let external = try await wallet.topUpExternalIdentityFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) + let managed = try await wallet.topUpFromAddresses( + identityId: identityId, inputs: [input], addressSigner: try signer() + ) + + XCTAssertEqual(external, 2, "the external wrapper must call the external export") + XCTAssertEqual(managed, 1, "the managed wrapper must call the managed export") + } + // MARK: - Marshalling through the shared helper func testMarshalsArgumentsAndReturnsTheBalanceTheExportWrites() async throws { From 77c2161ad5fa9ff3640905d05a71590a8530c417 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 11:17:58 +0200 Subject: [PATCH 04/19] fix(platform-wallet-ffi): release the wallet registry before waiting on the signer Both address top-up exports ran block_on_worker inside PLATFORM_WALLET_STORAGE.with_item, so the registry read guard stayed held while the host signed. A wallet handle destroy (write lock) queued behind it, and any registry read queued behind that destroy, so a signing completion that reads a balance could never finish. Clone the wallet Arc in a short with_item and wait on the signer after it returns. The regression test holds a callback signer pending, then destroys a second wallet handle and reads a balance; both must finish before the signer is answered, for both exports. Co-Authored-By: Claude Opus 5.5 --- .../src/identity_top_up.rs | 46 +-- .../identity_top_up/registry_release_tests.rs | 269 ++++++++++++++++++ 2 files changed, 292 insertions(+), 23 deletions(-) create mode 100644 packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs index 4dbf755007e..5ac03e5d38b 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs @@ -45,6 +45,8 @@ use crate::{unwrap_option_or_return, unwrap_result_or_return}; #[cfg(test)] mod external_identity_tests; #[cfg(test)] +mod registry_release_tests; +#[cfg(test)] mod submission_result_tests; /// Top up an existing identity's credit balance from one or more @@ -96,21 +98,21 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( // is `Send + Sync` — see the unsafe impls in `rs-sdk-ffi/src/signer.rs`. let signer_addr = signer_address_handle as usize; - let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { - let wallet = wallet.clone(); - block_on_worker(async move { - let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; - // The composite tops up the identity AND reconciles the spent - // platform-address balances from the proof, so the wallet's - // displayed balance and next input selection reflect the spend - // (covering addresses restored from disk that are no longer in - // a live derived pool). - wallet - .top_up_from_addresses(&identity_id, rows, address_signer, None) - .await - }) + // Take the wallet out of the registry in a short read, so the registry + // is not locked while the host signs. + let wallet = + unwrap_option_or_return!(PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone())); + let result = block_on_worker(async move { + let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; + // The composite tops up the identity AND reconciles the spent + // platform-address balances from the proof, so the wallet's + // displayed balance and next input selection reflect the spend + // (covering addresses restored from disk that are no longer in + // a live derived pool). + wallet + .top_up_from_addresses(&identity_id, rows, address_signer, None) + .await }); - let result = unwrap_option_or_return!(option); let new_balance = unwrap_result_or_return!(result); *out_new_balance = new_balance; PlatformWalletFFIResult::ok() @@ -182,16 +184,14 @@ pub unsafe extern "C" fn platform_wallet_top_up_external_identity_from_addresses // `platform_wallet_top_up_from_addresses_with_signer`. let signer_addr = signer_address_handle as usize; - let option = PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |wallet| { - let wallet = wallet.clone(); - block_on_worker(async move { - let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; - wallet - .top_up_external_identity_from_addresses(&identity_id, rows, address_signer, None) - .await - }) + let wallet = + unwrap_option_or_return!(PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone())); + let result = block_on_worker(async move { + let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; + wallet + .top_up_external_identity_from_addresses(&identity_id, rows, address_signer, None) + .await }); - let result = unwrap_option_or_return!(option); let new_balance = unwrap_result_or_return!(result); *out_new_balance = new_balance; PlatformWalletFFIResult::ok() diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs new file mode 100644 index 00000000000..98a647bfcdc --- /dev/null +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs @@ -0,0 +1,269 @@ +//! Both address top-up exports wait for the host signer without holding the +//! wallet handle registry: while a signature is pending, destroying another +//! wallet handle and reading a balance must both complete. + +use std::collections::{BTreeMap, BTreeSet}; +use std::ffi::c_void; +use std::os::raw::c_char; +use std::sync::mpsc::{channel, Sender}; +use std::sync::{Arc, Mutex}; +use std::thread; +use std::time::Duration; + +use dash_sdk::query_types::{AddressInfo, AddressInfos}; +use dash_sdk::SdkBuilder; +use dpp::address_funds::PlatformAddress; +use dpp::identity::{Identity, IdentityV0}; +use dpp::prelude::Identifier; +use dpp::version::PlatformVersion; +use key_wallet::wallet::initialization::WalletAccountCreationOptions; +use platform_wallet::events::{EventHandler, PlatformEventHandler}; +use platform_wallet::wallet::persister::NoPlatformPersistence; +use platform_wallet::PlatformWalletManager; +use rs_sdk_ffi::{ + dash_sdk_signer_create_with_ctx, dash_sdk_signer_destroy, SignCompletionCallback, SignerHandle, +}; + +use super::{ + platform_wallet_top_up_external_identity_from_addresses_with_signer as top_up_external, + platform_wallet_top_up_from_addresses_with_signer as top_up_managed, +}; +use crate::error::PlatformWalletFFIResult; +use crate::handle::{Handle, PLATFORM_WALLET_STORAGE}; +use crate::identity_registration::IdentityFundingInputFFI; +use crate::runtime::runtime; +use crate::wallet::{platform_wallet_destroy, platform_wallet_get_balance}; + +const IDENTITY: [u8; 32] = [9; 32]; +const ADDRESS_HASH: [u8; 20] = [7; 20]; +const AMOUNT: u64 = 100_000_000; +/// Long enough for a loaded CI machine to reach the signer, short enough to +/// fail instead of hanging when the registry is held. +const SIGNER_REACHED: Duration = Duration::from_secs(60); +const REGISTRY_FREE: Duration = Duration::from_secs(5); + +struct NoopEvents; +impl EventHandler for NoopEvents {} +impl PlatformEventHandler for NoopEvents {} + +/// A pending signature request the host has not answered yet. +struct PendingSignature { + completion_ctx: usize, + completion: SignCompletionCallback, +} + +struct SignerContext { + requests: Mutex>, +} + +unsafe extern "C" fn sign_async( + signer: *const c_void, + _pubkey_bytes: *const u8, + _pubkey_len: usize, + _key_type: u8, + _data: *const u8, + _data_len: usize, + completion_ctx: *mut c_void, + completion: SignCompletionCallback, +) { + let context = &*(signer as *const SignerContext); + let _ = context.requests.lock().unwrap().send(PendingSignature { + completion_ctx: completion_ctx as usize, + completion, + }); +} + +unsafe extern "C" fn can_sign_with(_: *const c_void, _: *const u8, _: usize, _: u8) -> bool { + true +} + +unsafe extern "C" fn destroy(signer: *mut c_void) { + drop(Box::from_raw(signer as *mut SignerContext)); +} + +fn pending_signer() -> ( + *mut SignerHandle, + std::sync::mpsc::Receiver, +) { + let (requests, pending) = channel(); + let context = Box::into_raw(Box::new(SignerContext { + requests: Mutex::new(requests), + })); + let signer = unsafe { + dash_sdk_signer_create_with_ctx( + context as *mut c_void, + sign_async, + can_sign_with, + Some(destroy), + ) + }; + (signer, pending) +} + +/// The wallet the export runs on (funded address, identity known both to the +/// wallet and to the mock Platform) and a second wallet to destroy. +async fn wallets() -> (Handle, Handle) { + let mut sdk = SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .with_time_tolerance(None) + .build() + .unwrap(); + let address = PlatformAddress::P2pkh(ADDRESS_HASH); + sdk.mock() + .expect_fetch_many::( + BTreeSet::from([address]), + Some(AddressInfos::from_iter([( + address, + Some(AddressInfo { + address, + nonce: 0, + balance: AMOUNT, + }), + )])), + ) + .await + .unwrap(); + let identity = Identity::V0(IdentityV0 { + id: Identifier::from(IDENTITY), + public_keys: BTreeMap::new(), + balance: 0, + revision: 0, + }); + sdk.mock() + .expect_fetch::(Identifier::from(IDENTITY), Some(identity.clone())) + .await + .unwrap(); + let manager = PlatformWalletManager::new( + Arc::new(sdk), + Arc::new(NoPlatformPersistence), + Arc::new(NoopEvents), + ); + let mut handles = Vec::new(); + for seed in [42u8, 43] { + let wallet = manager + .create_wallet_from_seed_bytes( + key_wallet::Network::Testnet, + &[seed; 64], + WalletAccountCreationOptions::None, + Some(0), + ) + .await + .unwrap(); + if seed == 42 { + wallet + .wallet_manager() + .write() + .await + .get_wallet_info_mut(&wallet.wallet_id()) + .unwrap() + .identity_manager + .add_identity(identity.clone(), 0, wallet.wallet_id(), wallet.persister()) + .unwrap(); + } + handles.push(PLATFORM_WALLET_STORAGE.insert(wallet)); + } + (handles[0], handles[1]) +} + +type Export = unsafe extern "C" fn( + Handle, + *const [u8; 32], + *const IdentityFundingInputFFI, + usize, + *mut SignerHandle, + *mut u64, +) -> PlatformWalletFFIResult; + +/// Holds the signer while the export waits on it, destroys the second wallet +/// handle and reads a balance, and reports whether both finished before the +/// signer was answered. +fn registry_is_free_while_the_signer_is_pending(export: Export) { + let (export_handle, other_handle) = runtime().block_on(wallets()); + let (signer, pending) = pending_signer(); + + let signer_addr = signer as usize; + let exporting = thread::spawn(move || { + let row = IdentityFundingInputFFI { + address_type: 0, + hash: ADDRESS_HASH, + credits: AMOUNT, + }; + let id = IDENTITY; + let mut balance = 0u64; + unsafe { + export( + export_handle, + &id, + &row, + 1, + signer_addr as *mut SignerHandle, + &mut balance, + ) + }; + }); + let request = pending + .recv_timeout(SIGNER_REACHED) + .expect("the export never asked the signer for a signature"); + + let (finished, finishes) = channel(); + let destroyed = finished.clone(); + thread::spawn(move || { + unsafe { platform_wallet_destroy(other_handle) }; + let _ = destroyed.send("destroy"); + }); + thread::spawn(move || { + let mut confirmed = 0u64; + unsafe { + platform_wallet_get_balance( + export_handle, + &mut confirmed, + std::ptr::null_mut(), + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }; + let _ = finished.send("balance read"); + }); + let mut done_before_release = Vec::new(); + while done_before_release.len() < 2 { + match finishes.recv_timeout(REGISTRY_FREE) { + Ok(name) => done_before_release.push(name), + Err(_) => break, + } + } + + // Answer the signer whatever happened, so no thread outlives the test. + let signature = [0u8; 65]; + unsafe { + (request.completion)( + request.completion_ctx as *mut c_void, + signature.as_ptr(), + signature.len(), + 0, + std::ptr::null::(), + ) + }; + exporting.join().unwrap(); + for _ in done_before_release.len()..2 { + finishes.recv_timeout(SIGNER_REACHED).unwrap(); + } + let _ = PLATFORM_WALLET_STORAGE.remove(export_handle); + unsafe { dash_sdk_signer_destroy(signer) }; + + assert_eq!( + done_before_release.len(), + 2, + "only {done_before_release:?} finished while the export waited for the signer: \ + the wallet registry stayed locked" + ); +} + +#[test] +fn should_not_hold_the_wallet_registry_while_the_external_top_up_waits_for_the_signer() { + registry_is_free_while_the_signer_is_pending(top_up_external); +} + +#[test] +fn should_not_hold_the_wallet_registry_while_the_managed_top_up_waits_for_the_signer() { + registry_is_free_while_the_signer_is_pending(top_up_managed); +} From a982205df7a2454e5bc05bd4e1f2c255b60beb15 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 11:27:09 +0200 Subject: [PATCH 05/19] fix(platform-wallet): keep the external identity top-up behind the gated composite Make IdentityWallet::top_up_external_from_addresses crate-private so the only public route to topping up someone else's identity is PlatformWallet::top_up_external_identity_from_addresses, which holds the wallet lifecycle gate and refuses a removed or re-created wallet. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/identity/network/top_up_from_addresses.rs | 9 ++++++--- .../rs-platform-wallet/src/wallet/platform_wallet.rs | 4 ++-- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 3b7e8a1f873..d9eb7929066 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -127,9 +127,12 @@ impl IdentityWallet { /// written: someone else's identity is never recorded as the wallet's /// own. Returns the same proof-attested post-spend `AddressInfos`, new /// identity balance and proof height as - /// [`Self::top_up_from_addresses`]; prefer the composite + /// [`Self::top_up_from_addresses`]. + /// + /// Crate-private: it does not check the wallet generation or reconcile + /// the spent addresses. Callers outside the crate use /// [`PlatformWallet::top_up_external_identity_from_addresses`], which - /// also reconciles the spent addresses. + /// holds the lifecycle gate and reconciles. /// /// Returns [`PlatformWalletError::IdentityNotFound`] before anything is /// signed or broadcast when Platform has no identity with this id. @@ -137,7 +140,7 @@ impl IdentityWallet { /// /// [`PlatformWallet::top_up_external_identity_from_addresses`]: /// crate::wallet::PlatformWallet::top_up_external_identity_from_addresses - pub async fn top_up_external_from_addresses( + pub(crate) async fn top_up_external_from_addresses( &self, identity_id: &Identifier, inputs: I, diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 0ae7ace84f7..20cde4f0092 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -612,8 +612,8 @@ impl PlatformWallet { /// address balances, then reconcile the spent addresses exactly as /// [`Self::top_up_from_addresses`] does. /// - /// See [`IdentityWallet::top_up_external_from_addresses`]: the identity - /// is fetched from Platform and never added to the identity manager. + /// The identity is fetched from Platform and never added to the identity + /// manager. /// /// Holds the wallet generation's lifecycle gate from the liveness check /// through the fetch, signing, broadcast and reconciliation, so a From ccf95e59866a55f0533bcfcc14b8c7f859966c34 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 08:45:41 +0200 Subject: [PATCH 06/19] fix(platform-wallet): report a failed recipient lookup in the external top-up as not sent A failed `Identity::fetch` on the external identity top-up surfaced as a generic `Sdk` error although nothing had been signed or broadcast, which a host treating unknown errors as "may have gone through" cannot tell from a failure after a dispatch. It is now `PlatformWalletError::IdentityLookupFailed`, mapped to the new FFI code 77 `ErrorIdentityLookupFailed` and mirrored in Swift and Kotlin. A missing identity keeps `IdentityNotFound` (7). No existing code meant "refused before anything was sent" for a Platform state transition. Co-Authored-By: Claude Opus 5.5 --- .../dashsdk/errors/DashSdkError.kt | 12 +++++++ .../dashsdk/errors/DashSdkErrorTest.kt | 13 +++++++ .../ERROR_CODE_REGISTRY.md | 5 +-- packages/rs-platform-wallet-ffi/src/error.rs | 29 +++++++++++++++ packages/rs-platform-wallet/src/error.rs | 14 ++++++++ .../identity/network/top_up_from_addresses.rs | 10 ++++-- .../external_identity_tests.rs | 36 ++++++++++++++++--- .../PlatformWallet/PlatformWalletResult.swift | 15 +++++++- .../ErrorHandlingTests.swift | 17 +++++++++ 9 files changed, 142 insertions(+), 9 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt index 91547fb3e1d..3726f4d5f0b 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt @@ -795,6 +795,17 @@ sealed class DashSdkError( class PublicContactRequestUnconfirmed(message: String, cause: Throwable? = null) : PlatformWallet(message, cause) + /** + * `ErrorIdentityLookupFailed` (native code 77). Platform could not be + * asked for an identity the operation names (the lookup failed, which + * is not Platform's answer that it does not exist, code 7). Nothing + * was signed, reserved or broadcast, so the operation may be retried + * as it is and is never a possibly delivered one. + * ← Swift `PlatformWalletError.identityLookupFailed`. + */ + class IdentityLookupFailed(message: String, cause: Throwable? = null) : + PlatformWallet(message, cause) + /** * Any other `PlatformWalletFFIResultCode` without a dedicated type. * Carries the platform-wallet [nativeCode] (already de-offset) and @@ -1004,6 +1015,7 @@ sealed class DashSdkError( 74 -> PlatformWallet.PrivateContactStoreNotRead(message, cause) // ErrorPrivateContactStoreNotRead 75 -> PlatformWallet.SdkPinnedBelowProtocolVersion(message, cause) // ErrorSdkPinnedBelowProtocolVersion 76 -> PlatformWallet.PublicContactRequestUnconfirmed(message, cause) // ErrorPublicContactRequestUnconfirmed + 77 -> PlatformWallet.IdentityLookupFailed(message, cause) // ErrorIdentityLookupFailed else -> // @Deprecated fallback — see the code-6 arm; code 31 is the // real discriminator. diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt index f56f0736e5e..360fb0334b7 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt @@ -400,6 +400,19 @@ class DashSdkErrorTest { assertFalse("a sync settles it, not a retry", mapped.isRetryable) } + /** + * A failed identity lookup sent nothing: its own code, retryable as it is, + * apart from the unmapped SDK errors a host reads as possibly delivered. + */ + @Test + fun shouldReportAFailedIdentityLookupByItsOwnCode() { + val detail = "could not look up identity on Platform; nothing was sent" + val native = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 77, detail) + val mapped = DashSdkError.fromNative(native) + assertTrue(mapped is DashSdkError.PlatformWallet.IdentityLookupFailed) + assertEquals(detail, mapped.message) + } + @Test fun platformShieldCapacityCode41MapsTyped() { val message = diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index a5655430abd..735aea5d2b5 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -114,7 +114,7 @@ These are shipped ABI. Do not renumber. | 98 | `NotFound` | Sentinel — `Option` returned as an error | | 99 | `ErrorUnknown` | Sentinel — unmapped/flattened errors | -**Next allocatable integer: 77**: 27–76 are all claimed (27, 29, 31, 34–42 +**Next allocatable integer: 78**: 27–77 are all claimed (27, 29, 31, 34–42 and 46 merged; 43–45 proposed by active #4313 at head `0302b188ab`; 47 and 48 proposed by active #4356 (47 renumbered from 42, 48 from 43 — see their rows below); 49–54 proposed by active #4586 (the persister @@ -128,7 +128,7 @@ renumbered from 59 when #5322 took that number on `v5.1-dev`); 61 proposed by by open branches with no row here yet (62 both `ErrorShieldedClaimBindingMismatch` and `ErrorIdentityRevisionMismatch`, 63–66 the invitation-claim preflight, 67 `ErrorShieldedTreeInconsistent`); 68 -to 76 proposed for DashPay private contact requests; 28, 30, +to 76 proposed for DashPay private contact requests; 77 proposed for the failed recipient lookup of the external identity top-up; 28, 30, 32 and 33 reserved). **28, 30, 32 and 33 are RESERVED, not free**: 28 and 30 were vacated when the reservation trio moved to 34–36; 32 and 33 lapsed when their in-repo owners @@ -192,6 +192,7 @@ Fork-era numbers remain in the collision history, which is immutable record. | 74 | `ErrorPrivateContactStoreNotRead` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactStoreNotRead`: DashPay's private contact request store was not read to its end for the identity, with the keys Platform proves it holds, before a contact request or acceptance, public or private, was decided (every one reads it from the identity's cursor first). Nothing was reserved, sealed, paid or broadcast; calling again continues the read from where it stopped. A node behind the store already seen, or keys that kept changing, stop it. It was reported as 71 before, which says not to submit again. Mapped by the blanket conversion and kept by the shielded spend contract (`map_spend_result`). Swift types it (`PlatformWalletError.privateContactStoreNotRead`, `ErrorHandlingTests` pin) and SwiftExampleApp offers a retry with no pending row; Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactStoreNotRead`, `DashSdkErrorTest` pin) and KotlinExampleApp offers a retry with no pending row | | 75 | `ErrorSdkPinnedBelowProtocolVersion` | DashPay private contact requests | Proposed. The SDK refused a request without sending it because the SDK itself is pinned below the protocol version the request needs (`dash_sdk::Error::ProtocolVersionNotActive` with `pinned`), whatever the network runs: for example every contact request's private store read with the SDK pinned below protocol version 15 on a network at 15. A network upgrade does not lift it; only raising or removing the pin does. Before, it shared 70 with a network proven below the version, which lifts by itself. Mapped by the blanket conversion. Swift types it (`PlatformWalletError.sdkPinnedBelowProtocolVersion`, `ErrorHandlingTests` pin) and SwiftExampleApp shows a developer-facing message; Kotlin types it (`DashSdkError.PlatformWallet.SdkPinnedBelowProtocolVersion`, `DashSdkErrorTest` pin) and KotlinExampleApp shows a developer-facing message | | 76 | `ErrorPublicContactRequestUnconfirmed` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PublicContactRequestUnconfirmed`: a public contact request to that identity was broadcast and may have been delivered, and no proof settled its outcome yet, so the wallet holds the pair and signs nothing new to it, public or private. The send or accept that broadcast it reported 20; every later one is refused with 76 until a public contact request sync settles it (its document proved on Platform: recorded as sent; its transition proved unable to write it: the pair freed), broadcasting the same signed bytes again meanwhile. Not a private request pending (71). Mapped by the blanket conversion and by `map_spend_result`. `platform_wallet_get_public_contact_request_unconfirmed` reads the hold per pair (`DashPayView::public_contact_request_unconfirmed`; 7 for a sender the wallet does not hold). Swift types it (`PlatformWalletError.publicContactRequestUnconfirmed`, `ErrorHandlingTests` pin) and wraps the read (`ManagedPlatformWallet.publicContactRequestUnconfirmed`); SwiftExampleApp shows the pair as being checked, with no request or accept offered, until the read says settled, and its refreshes run the DashPay sync that settles it; Kotlin types it (`DashSdkError.PlatformWallet.PublicContactRequestUnconfirmed`, `DashSdkErrorTest` pin), bridges the read (`DashpayNative.publicContactRequestUnconfirmed`, `Dashpay.publicContactRequestsUnconfirmed`), and KotlinExampleApp shows the pair as SwiftExampleApp does | +| 77 | `ErrorIdentityLookupFailed` | External identity top-up from Platform addresses | Proposed. Maps `PlatformWalletError::IdentityLookupFailed`: Platform could not be asked for the identity the operation names (the lookup failed in transport or proof, not Platform's answer that it does not exist, which stays 7). Nothing was signed, reserved or broadcast, so the call may be retried as it is; no existing code meant "refused before anything was sent" for a Platform state transition (16 is the shielded broadcast refusal), so it takes the next free number. Returned by `platform_wallet_top_up_external_identity_from_addresses_with_signer`; before, such a failure reached a host as an unmapped SDK error. Swift types it (`PlatformWalletError.identityLookupFailed`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.IdentityLookupFailed`, `DashSdkErrorTest` pin) | **Code 31 left this table on 2026-08-04.** `ErrorSigningKeyUnavailable` sat here as #4183's proposal until #4183 merged (`189a3abb1c`); it is now in the merged diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 58194bf7197..9aec4e073d5 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -768,6 +768,15 @@ pub enum PlatformWalletFFIResultCode { /// [`Self::ErrorPrivateContactRequestPending`] (71). ErrorPublicContactRequestUnconfirmed = 76, + /// Maps `PlatformWalletError::IdentityLookupFailed`: Platform could not be + /// asked for an identity the operation names (a transport or proof + /// failure of the lookup, not Platform's answer that the identity does not + /// exist, which is [`Self::ErrorIdentityNotFound`] (7)). Nothing was + /// signed, reserved or broadcast, so the operation may be retried as it + /// is; a host need not treat it as possibly delivered. Returned by the + /// external identity top-up from Platform addresses. + ErrorIdentityLookupFailed = 77, + /// The named thing does not exist. /// /// Originally (and still mostly) the code for every `Option` returned as an @@ -1248,6 +1257,11 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::PublicContactRequestUnconfirmed(..) => { PlatformWalletFFIResultCode::ErrorPublicContactRequestUnconfirmed } + // The recipient lookup failed before anything was signed or + // sent: a not-sent refusal, not an ambiguous SDK error. + PlatformWalletError::IdentityLookupFailed { .. } => { + PlatformWalletFFIResultCode::ErrorIdentityLookupFailed + } // The wallet's private payments from an earlier process are not // restored yet: wallet readiness, not one contact's pending request. PlatformWalletError::PrivateContactPaymentsNotRestored => { @@ -3170,6 +3184,21 @@ mod private_contact_request_error_tests { ); } + /// A failed identity lookup, which sent nothing, reaches the host by its + /// own code rather than as the SDK error it wraps. + #[test] + fn should_report_a_failed_identity_lookup_by_its_own_code() { + let result = PlatformWalletFFIResult::from(PlatformWalletError::IdentityLookupFailed { + identity_id: [7; 32].into(), + source: dash_sdk::Error::Generic("unreachable".to_string()), + }); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorIdentityLookupFailed + ); + assert_eq!(result.code as u32, 77); + } + /// A public contact request a loaded wallet refuses until its private /// payments are restored reaches the host by its own code, not as a /// contact's pending request. diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index f9ed4a5b60f..08cc996a911 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -678,6 +678,20 @@ pub enum PlatformWalletError { #[error("SDK error: {0}")] Sdk(#[from] dash_sdk::Error), + /// Platform could not be asked for an identity an operation names, so + /// nothing was signed, reserved or broadcast: the operation never + /// started and may be retried as it is. Distinct from [`Self::Sdk`], + /// which a host that treats an unknown error as "may have gone through" + /// cannot tell from a failure after a dispatch, and from + /// [`Self::IdentityNotFound`], which is Platform's answer that the + /// identity does not exist. `source` is the SDK's error. + #[error("could not look up identity {identity_id} on Platform; nothing was sent: {source}")] + IdentityLookupFailed { + identity_id: Identifier, + #[source] + source: dash_sdk::Error, + }, + /// The contact requests with this identity came or went privately /// (protocol version 15): a `contactRequest` document to it, in reply or /// as a rotation, would publish the relationship, so it is sent privately. diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index d9eb7929066..8a46f645dbb 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -135,7 +135,9 @@ impl IdentityWallet { /// holds the lifecycle gate and reconciles. /// /// Returns [`PlatformWalletError::IdentityNotFound`] before anything is - /// signed or broadcast when Platform has no identity with this id. + /// signed or broadcast when Platform has no identity with this id, and + /// [`PlatformWalletError::IdentityLookupFailed`], likewise before + /// anything is signed or broadcast, when the lookup itself fails. /// `inputs` are funding rows as for [`Self::top_up_from_addresses`]. /// /// [`PlatformWallet::top_up_external_identity_from_addresses`]: @@ -153,7 +155,11 @@ impl IdentityWallet { { let inputs = funding_inputs(inputs)?; let identity = Identity::fetch(&self.sdk, *identity_id) - .await? + .await + .map_err(|source| PlatformWalletError::IdentityLookupFailed { + identity_id: *identity_id, + source, + })? .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; let (address_infos, new_balance, metadata) = self diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index a88f2eb5531..c2f2f1f2e3c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -136,6 +136,12 @@ struct Fixture { impl Fixture { async fn new(on_platform: bool) -> Self { + Self::build(Some(on_platform)).await + } + + /// `on_platform` `None`: Platform cannot be reached to look the + /// identity up, there is no expectation for the request. + async fn build(on_platform: Option) -> Self { let mut sdk = SdkBuilder::new_mock() .with_version(PlatformVersion::latest()) .with_time_tolerance(None) @@ -181,10 +187,12 @@ impl Fixture { })), ); sdk.mock().load_expectations_sync(directory.path()).unwrap(); - sdk.mock() - .expect_fetch(target.id(), on_platform.then(|| target.clone())) - .await - .unwrap(); + if let Some(on_platform) = on_platform { + sdk.mock() + .expect_fetch(target.id(), on_platform.then(|| target.clone())) + .await + .unwrap(); + } sdk.mock() .expect_fetch_many::( BTreeSet::from([ADDRESS]), @@ -340,6 +348,26 @@ async fn should_refuse_an_identity_platform_does_not_know_without_submitting() { ); } +/// A recipient lookup that fails (here a transport error) is reported as its +/// own not-sent error, not as a generic SDK error a host must read as "may +/// have gone through", with nothing signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_report_a_failed_recipient_lookup_as_not_sent() { + let mut fixture = Fixture::build(None).await; + + let error = fixture + .top_up() + .await + .expect_err("the identity cannot be looked up"); + + assert!( + matches!(&error, PlatformWalletError::IdentityLookupFailed { identity_id, .. } + if *identity_id == fixture.target), + "got {error:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} + /// An empty funding map is the caller's mistake on both routes: the SDK's /// own empty-input refusal comes back as `InvalidParameter`, with nothing /// signed or submitted. diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index ee130585d2d..eff88b0d9a2 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -322,6 +322,10 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// outcome yet. Nothing new was signed. Unconfirmed, not failed: do not /// submit it again; a public contact request sync settles it. case errorPublicContactRequestUnconfirmed = 76 + /// Platform could not be asked for an identity the operation names (the + /// lookup failed, which is not Platform's answer that it does not exist, + /// 7). Nothing was signed, reserved or broadcast: retry as it is. + case errorIdentityLookupFailed = 77 /// The named thing does not exist. Besides the handle/lookup failures this /// has always covered, BOTH deferred-send paths report the /// wallet-was-REMOVED case here. @@ -473,6 +477,8 @@ public enum PlatformWalletResultCode: Int32, Sendable { self = .errorSdkPinnedBelowProtocolVersion case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_PUBLIC_CONTACT_REQUEST_UNCONFIRMED: self = .errorPublicContactRequestUnconfirmed + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_IDENTITY_LOOKUP_FAILED: + self = .errorIdentityLookupFailed case PLATFORM_WALLET_FFI_RESULT_CODE_NOT_FOUND: self = .notFound case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_UNKNOWN: @@ -743,6 +749,11 @@ public enum PlatformWalletError: LocalizedError { /// `ManagedPlatformWallet.publicContactRequestUnconfirmed(senderId:recipientId:)` /// reads whether the pair is still held so. case publicContactRequestUnconfirmed(String) + /// Platform could not be asked for an identity the operation names (code + /// 77): the lookup itself failed, before anything was signed, reserved or + /// broadcast. Not sent, so it may be retried as it is; unlike an unmapped + /// SDK error it is never a possibly delivered operation. + case identityLookupFailed(String) case walletAlreadyExists(String) /// Definitive shielded-broadcast failure: the shielded transition never /// left the wallet (refused before anything was sent), so it cannot @@ -976,7 +987,7 @@ public enum PlatformWalletError: LocalizedError { .privateContactRequestPending(let m), .privateContactPaymentsNotRestored(let m), .privateContactRecoveryUnsupported(let m), .privateContactStoreNotRead(let m), .sdkPinnedBelowProtocolVersion(let m), - .publicContactRequestUnconfirmed(let m), + .publicContactRequestUnconfirmed(let m), .identityLookupFailed(let m), .walletAlreadyExists(let m), .shieldedBroadcastFailed(let m), .shieldedBroadcastUnconfirmed(let m), .shieldedSpendUnconfirmed(let m), .shieldedNoRecordedAnchor(let m), .shieldedInsufficientBalance(let m), @@ -1114,6 +1125,8 @@ public enum PlatformWalletError: LocalizedError { self = .sdkPinnedBelowProtocolVersion(detail) case .errorPublicContactRequestUnconfirmed: self = .publicContactRequestUnconfirmed(detail) + case .errorIdentityLookupFailed: + self = .identityLookupFailed(detail) case .errorWalletAlreadyExists: self = .walletAlreadyExists(detail) case .errorShieldedBroadcastFailed: self = .shieldedBroadcastFailed(detail) case .errorShieldedBroadcastUnconfirmed: self = .shieldedBroadcastUnconfirmed(detail) diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift index b3bbb2a7d64..9838d72b66c 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -604,6 +604,23 @@ final class ErrorHandlingTests: XCTestCase { XCTAssertEqual(message, detail) } + /// A failed identity lookup, which sent nothing, has its own code and + /// typed case, apart from the unmapped SDK errors a host reads as possibly + /// delivered. + func testShouldReportAFailedIdentityLookupByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_IDENTITY_LOOKUP_FAILED + ) + XCTAssertEqual(code, .errorIdentityLookupFailed) + XCTAssertEqual(code.rawValue, 77) + let detail = "could not look up identity 9fRYTJZW on Platform; nothing was sent" + guard case .identityLookupFailed(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed identity-lookup-failed error") + } + XCTAssertEqual(message, detail) + } + func testShouldReadEveryFieldOfThePrivateContactReadiness() { var ffi = PrivateContactReadinessFFI() ffi.private_payments_restored = false From a08f7ff99392719d15dfb927bcdf6a0d06d8cb43 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 11:47:50 +0200 Subject: [PATCH 07/19] fix(platform-wallet-ffi): number the identity lookup failure 80, clear of the shielded spend plan codes The failed identity lookup code was 77, which the shielded spend plan PR already uses (77 plan changed, 78 too many notes, 79 withdrawal amount out of range). Renumber it to 80 in the FFI enum, the registry (next free is now 81), the Swift result code and the Kotlin error mapping, and update the Rust, Swift and Kotlin pin tests. Co-Authored-By: Claude Opus 5.5 --- .../org/dashfoundation/dashsdk/errors/DashSdkError.kt | 4 ++-- .../org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt | 2 +- packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md | 8 ++++---- packages/rs-platform-wallet-ffi/src/error.rs | 4 ++-- .../PlatformWallet/PlatformWalletResult.swift | 4 ++-- .../SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift | 2 +- 6 files changed, 12 insertions(+), 12 deletions(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt index 3726f4d5f0b..459c1ac6bd6 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt @@ -796,7 +796,7 @@ sealed class DashSdkError( PlatformWallet(message, cause) /** - * `ErrorIdentityLookupFailed` (native code 77). Platform could not be + * `ErrorIdentityLookupFailed` (native code 80). Platform could not be * asked for an identity the operation names (the lookup failed, which * is not Platform's answer that it does not exist, code 7). Nothing * was signed, reserved or broadcast, so the operation may be retried @@ -1015,7 +1015,7 @@ sealed class DashSdkError( 74 -> PlatformWallet.PrivateContactStoreNotRead(message, cause) // ErrorPrivateContactStoreNotRead 75 -> PlatformWallet.SdkPinnedBelowProtocolVersion(message, cause) // ErrorSdkPinnedBelowProtocolVersion 76 -> PlatformWallet.PublicContactRequestUnconfirmed(message, cause) // ErrorPublicContactRequestUnconfirmed - 77 -> PlatformWallet.IdentityLookupFailed(message, cause) // ErrorIdentityLookupFailed + 80 -> PlatformWallet.IdentityLookupFailed(message, cause) // ErrorIdentityLookupFailed else -> // @Deprecated fallback — see the code-6 arm; code 31 is the // real discriminator. diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt index 360fb0334b7..d56acd298b6 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt @@ -407,7 +407,7 @@ class DashSdkErrorTest { @Test fun shouldReportAFailedIdentityLookupByItsOwnCode() { val detail = "could not look up identity on Platform; nothing was sent" - val native = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 77, detail) + val native = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 80, detail) val mapped = DashSdkError.fromNative(native) assertTrue(mapped is DashSdkError.PlatformWallet.IdentityLookupFailed) assertEquals(detail, mapped.message) diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index 735aea5d2b5..7757bbbc2bf 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -114,7 +114,7 @@ These are shipped ABI. Do not renumber. | 98 | `NotFound` | Sentinel — `Option` returned as an error | | 99 | `ErrorUnknown` | Sentinel — unmapped/flattened errors | -**Next allocatable integer: 78**: 27–77 are all claimed (27, 29, 31, 34–42 +**Next allocatable integer: 81**: 27–80 are all claimed (27, 29, 31, 34–42 and 46 merged; 43–45 proposed by active #4313 at head `0302b188ab`; 47 and 48 proposed by active #4356 (47 renumbered from 42, 48 from 43 — see their rows below); 49–54 proposed by active #4586 (the persister @@ -128,7 +128,7 @@ renumbered from 59 when #5322 took that number on `v5.1-dev`); 61 proposed by by open branches with no row here yet (62 both `ErrorShieldedClaimBindingMismatch` and `ErrorIdentityRevisionMismatch`, 63–66 the invitation-claim preflight, 67 `ErrorShieldedTreeInconsistent`); 68 -to 76 proposed for DashPay private contact requests; 77 proposed for the failed recipient lookup of the external identity top-up; 28, 30, +to 76 proposed for DashPay private contact requests; 77–79 proposed by #5865 for the shielded spend plan (`ErrorShieldedPlanChanged`, `ErrorShieldedSpendTooManyNotes`, `ErrorShieldedWithdrawalAmountOutOfRange`); 80 proposed for the failed recipient lookup of the external identity top-up; 28, 30, 32 and 33 reserved). **28, 30, 32 and 33 are RESERVED, not free**: 28 and 30 were vacated when the reservation trio moved to 34–36; 32 and 33 lapsed when their in-repo owners @@ -184,7 +184,7 @@ Fork-era numbers remain in the collision history, which is immutable record. | 60 | `ErrorAssetLockTooManyInputs` | Core-to-shielded pooled Max | Proposed — an asset lock needs more inputs than one may carry (100 on Dash Core relay policy, and in Platform consensus for an instant proof): the full drain, or since #5712 a fixed amount held only in many small coins (identity registration, top-up, invitation, platform-address funding). Two meanings. On a build: nothing was broadcast, the reservation is released, no partial drain, and a rebuild after consolidating is safe. On the resume of a tracked `Built` / `Broadcast` lock over the cap (since #5714): it is not re-sent, but an earlier attempt may have reached peers; the row stays tracked and nothing is released. Rust, Swift and Kotlin retain the typed refusal. Renumbered from 59 after #5322 claimed it | | 61 | `ErrorAssetLockRecipientMismatch` | dashpay/platform#5603 (tracked-lock shielded recipient) | Proposed — a shielded fund-from-asset-lock resume (the generic outpoint resume or a repeated-UUID wallet drain) names a different Orchard recipient than the one the tracked lock recorded when it was built. Nothing was submitted or paid; resume with the recorded recipient, which the row and `TrackedAssetLockFFI` expose. Rows tracked before recipients were recorded carry none and accept the caller's. Typed in Rust, Swift and Kotlin | | 68 | `ErrorPrivateContactRequestNeedsPrivateReply` | DashPay private contact requests | Proposed. The contact requests with that identity came or went privately (protocol version 15), so a `contactRequest` document to it, in reply or as a rotation, would publish the relationship: the public accept refuses a reply, and the public send refuses a request or a rotation. Nothing was sent; the request goes privately instead, and the in-kind accept picks the private reply itself. The shielded spend contract (`map_spend_result`) keeps the code, as the in-kind accept can raise it. Taken above 61–67, which open branches already hold. Returned by the public send and accept; the host sends with `platform_wallet_manager_send_private_contact_request`, or accepts with `platform_wallet_manager_accept_contact_request_replying_in_kind` (which picks the reply itself, so a host calling it does not route on 68) or `platform_wallet_manager_accept_private_contact_request`. Swift types it (`PlatformWalletError.privateContactRequestNeedsPrivateReply`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactRequestNeedsPrivateReply`, `DashSdkErrorTest` pin) | -| 69 | `ErrorShieldedBuildRequired` | DashPay private contact requests | Proposed. The operation needs the shielded pool and the library was built without the `shielded` feature: accepting in kind a request that came privately, whose private reply is paid from the pool. Nothing was sent; a public or adopted reply works on such a build. Not retryable on the same build. No existing code meant "shielded unsupported" (`ErrorWalletOperation` with a not-configured message is a runtime state of a shielded build), so it takes the next free number. Returned by `platform_wallet_manager_accept_contact_request_replying_in_kind`, exported in every build. Swift types it (`PlatformWalletError.shieldedBuildRequired`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedBuildRequired`, `DashSdkErrorTest` pin) | +| 69 | `ErrorShieldedBuildRequired` | DashPay private contact requests | Proposed. The operation needs the shielded pool and the library was built without the `shielded` feature: accepting in kind a request that came privately, whose private reply is paid from the pool. Nothing was sent; a public or adopted reply works on such a build. Not retryable on the same build. No existing code meant "shielded unsupported" (`ErrorWalletOperation` with a not-configured message is a runtime state of a shielded build), so it takes the next free number after 77–79, which the shielded spend plan PR (#5865) holds. Returned by `platform_wallet_manager_accept_contact_request_replying_in_kind`, exported in every build. Swift types it (`PlatformWalletError.shieldedBuildRequired`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedBuildRequired`, `DashSdkErrorTest` pin) | | 70 | `ErrorProtocolVersionNotActive` | DashPay private contact requests | Proposed. The SDK refused a request without sending it (`dash_sdk::Error::ProtocolVersionNotActive`, not pinned) because the network is proven at a protocol version below the one that serves it: for example the private contact request sync on a network before protocol version 15. Expected on such a network, so a host may stay quiet about it; it lifts when the network upgrades. An SDK pinned below the required version has its own code, 75. Mapped by the blanket conversion for every operation that propagates the SDK error. A refusal that may lift sooner (`is_transient_protocol_version_refusal`: the network's version could not be confirmed) keeps the catch-all `ErrorUnknown`, as before. Previously both fell to `ErrorUnknown`. Swift types it (`PlatformWalletError.protocolVersionNotActive`, `ErrorHandlingTests` pin) and SwiftExampleApp keeps a refresh quiet on it; Kotlin types it (`DashSdkError.PlatformWallet.ProtocolVersionNotActive`, `DashSdkErrorTest` pin) and KotlinExampleApp keeps a refresh quiet on it | | 71 | `ErrorPrivateContactRequestPending` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactRequestPending`: a private contact request to that identity is in flight (another private send or reply reserved it before sealing), or was paid for and a short read-back sync did not find the entry in the store yet, or a private payment the shielded store's journal keeps unresolved holds the pair. Nothing new was paid; a later private contact request sync settles it once the entry is read back, and the shielded sync once the payment provably never executes. Pending, not failed: the host must not submit it again. A private store read that did not finish before the request was decided is 74, not 71. The shielded spend contract (`map_spend_result`) keeps the code rather than flattening it to `ErrorWalletOperation`. Returned by the private send, the private accept and the in-kind accept, and by a public send or accept the pair holds; `platform_wallet_get_private_pair_held` reads one pair's hold as a send decides it. Swift types it (`PlatformWalletError.privateContactRequestPending`, `ErrorHandlingTests` pin; `ManagedPlatformWallet.privatePairHeld`), and SwiftExampleApp keeps the pair pending until that read says free; Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactRequestPending`, `DashSdkErrorTest` pin; `Dashpay.privateRepliesPending` reads the pair's hold through JNI `DashpayNative.privatePairHeld`), and KotlinExampleApp keeps the pair pending until that read says free | | 72 | `ErrorPrivateContactPaymentsNotRestored` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactPaymentsNotRestored`: wallet readiness, not one contact's pending request (71). The wallet's unconfirmed private payments may hold pairs no reservation shows yet, which only a restoration from the shielded store's journal shows. In a build with the `shielded` feature: the wallet was published (created or loaded) while no shielded store was configured, its persister declaring the private scan state (bit 15), which holds a wallet removed and registered again from the same seed, in this process or a new one; it was loaded after binding a shielded account in an earlier process; or its last restoration failed, or waits for a busy store. In every build: the identity was loaded with its private scan state marking a private payment that may be unresolved, or was added to a wallet whose backend kept its record marked after an earlier wallet under the id was removed (`ClientStartState::retained_private_contact_scan_states`). Contact requests and acceptances, public and private, are refused with nothing read, signed or broadcast until they are restored: configuring the shielded store restores them with no keys, as binding the wallet's shielded account does, and a contact request first retries a restoration once without waiting on the store; a private sync does not, and a build without the `shielded` feature never does. A host whose persister declares the private scan state configures the shielded store when it activates the manager, before loading or creating wallets: until it does, and while a failed configure is not retried, 72 holds. `platform_wallet_get_private_contact_readiness` reads whether the payments are restored and whether the last restoration failed (`private_payments_restore_failed`; the wallet's `PrivateContactReadiness::private_payments_restore_failure` holds the reason). `platform_wallet_get_private_payments_restore_failure` gives that reason. Swift types it (`PlatformWalletError.privateContactPaymentsNotRestored`, `ErrorHandlingTests` pin) and binds both reads (`ManagedPlatformWallet.privateContactReadiness`, `privatePaymentsRestoreFailure`); SwiftExampleApp configures the shielded store when it activates a manager, before loading wallets; on each DashPay refresh while the store did not open or the readiness reads not restored, it configures the store again (on a store already open, the wallet's own retry of every wallet still held, a restoration that failed after the open included) and reads the readiness after that, refreshing again on a timer (every 3 s for a minute, then every 15 s) for as long as the view is shown and the payments stay unrestored, and when a shielded sync pass ends; it shows "setting up" or the failure's reason until the readiness reads restored. Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactPaymentsNotRestored`, `DashSdkErrorTest` pin) and binds both reads (`Dashpay.privateContactReadiness`, `privatePaymentsRestoreFailure`); KotlinExampleApp configures the shielded store before loading wallets and on each DashPay refresh retries as SwiftExampleApp does, showing "setting up" or the failure's reason | @@ -192,7 +192,7 @@ Fork-era numbers remain in the collision history, which is immutable record. | 74 | `ErrorPrivateContactStoreNotRead` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PrivateContactStoreNotRead`: DashPay's private contact request store was not read to its end for the identity, with the keys Platform proves it holds, before a contact request or acceptance, public or private, was decided (every one reads it from the identity's cursor first). Nothing was reserved, sealed, paid or broadcast; calling again continues the read from where it stopped. A node behind the store already seen, or keys that kept changing, stop it. It was reported as 71 before, which says not to submit again. Mapped by the blanket conversion and kept by the shielded spend contract (`map_spend_result`). Swift types it (`PlatformWalletError.privateContactStoreNotRead`, `ErrorHandlingTests` pin) and SwiftExampleApp offers a retry with no pending row; Kotlin types it (`DashSdkError.PlatformWallet.PrivateContactStoreNotRead`, `DashSdkErrorTest` pin) and KotlinExampleApp offers a retry with no pending row | | 75 | `ErrorSdkPinnedBelowProtocolVersion` | DashPay private contact requests | Proposed. The SDK refused a request without sending it because the SDK itself is pinned below the protocol version the request needs (`dash_sdk::Error::ProtocolVersionNotActive` with `pinned`), whatever the network runs: for example every contact request's private store read with the SDK pinned below protocol version 15 on a network at 15. A network upgrade does not lift it; only raising or removing the pin does. Before, it shared 70 with a network proven below the version, which lifts by itself. Mapped by the blanket conversion. Swift types it (`PlatformWalletError.sdkPinnedBelowProtocolVersion`, `ErrorHandlingTests` pin) and SwiftExampleApp shows a developer-facing message; Kotlin types it (`DashSdkError.PlatformWallet.SdkPinnedBelowProtocolVersion`, `DashSdkErrorTest` pin) and KotlinExampleApp shows a developer-facing message | | 76 | `ErrorPublicContactRequestUnconfirmed` | DashPay private contact requests | Proposed. Maps `PlatformWalletError::PublicContactRequestUnconfirmed`: a public contact request to that identity was broadcast and may have been delivered, and no proof settled its outcome yet, so the wallet holds the pair and signs nothing new to it, public or private. The send or accept that broadcast it reported 20; every later one is refused with 76 until a public contact request sync settles it (its document proved on Platform: recorded as sent; its transition proved unable to write it: the pair freed), broadcasting the same signed bytes again meanwhile. Not a private request pending (71). Mapped by the blanket conversion and by `map_spend_result`. `platform_wallet_get_public_contact_request_unconfirmed` reads the hold per pair (`DashPayView::public_contact_request_unconfirmed`; 7 for a sender the wallet does not hold). Swift types it (`PlatformWalletError.publicContactRequestUnconfirmed`, `ErrorHandlingTests` pin) and wraps the read (`ManagedPlatformWallet.publicContactRequestUnconfirmed`); SwiftExampleApp shows the pair as being checked, with no request or accept offered, until the read says settled, and its refreshes run the DashPay sync that settles it; Kotlin types it (`DashSdkError.PlatformWallet.PublicContactRequestUnconfirmed`, `DashSdkErrorTest` pin), bridges the read (`DashpayNative.publicContactRequestUnconfirmed`, `Dashpay.publicContactRequestsUnconfirmed`), and KotlinExampleApp shows the pair as SwiftExampleApp does | -| 77 | `ErrorIdentityLookupFailed` | External identity top-up from Platform addresses | Proposed. Maps `PlatformWalletError::IdentityLookupFailed`: Platform could not be asked for the identity the operation names (the lookup failed in transport or proof, not Platform's answer that it does not exist, which stays 7). Nothing was signed, reserved or broadcast, so the call may be retried as it is; no existing code meant "refused before anything was sent" for a Platform state transition (16 is the shielded broadcast refusal), so it takes the next free number. Returned by `platform_wallet_top_up_external_identity_from_addresses_with_signer`; before, such a failure reached a host as an unmapped SDK error. Swift types it (`PlatformWalletError.identityLookupFailed`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.IdentityLookupFailed`, `DashSdkErrorTest` pin) | +| 80 | `ErrorIdentityLookupFailed` | External identity top-up from Platform addresses | Proposed. Maps `PlatformWalletError::IdentityLookupFailed`: Platform could not be asked for the identity the operation names (the lookup failed in transport or proof, not Platform's answer that it does not exist, which stays 7). Nothing was signed, reserved or broadcast, so the call may be retried as it is; no existing code meant "refused before anything was sent" for a Platform state transition (16 is the shielded broadcast refusal), so it takes the next free number after 77–79, which the shielded spend plan PR (#5865) holds. Returned by `platform_wallet_top_up_external_identity_from_addresses_with_signer`; before, such a failure reached a host as an unmapped SDK error. Swift types it (`PlatformWalletError.identityLookupFailed`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.IdentityLookupFailed`, `DashSdkErrorTest` pin) | **Code 31 left this table on 2026-08-04.** `ErrorSigningKeyUnavailable` sat here as #4183's proposal until #4183 merged (`189a3abb1c`); it is now in the merged diff --git a/packages/rs-platform-wallet-ffi/src/error.rs b/packages/rs-platform-wallet-ffi/src/error.rs index 9aec4e073d5..7eb18c228f8 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -775,7 +775,7 @@ pub enum PlatformWalletFFIResultCode { /// signed, reserved or broadcast, so the operation may be retried as it /// is; a host need not treat it as possibly delivered. Returned by the /// external identity top-up from Platform addresses. - ErrorIdentityLookupFailed = 77, + ErrorIdentityLookupFailed = 80, /// The named thing does not exist. /// @@ -3196,7 +3196,7 @@ mod private_contact_request_error_tests { result.code, PlatformWalletFFIResultCode::ErrorIdentityLookupFailed ); - assert_eq!(result.code as u32, 77); + assert_eq!(result.code as u32, 80); } /// A public contact request a loaded wallet refuses until its private diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index eff88b0d9a2..c83d3063322 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -325,7 +325,7 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// Platform could not be asked for an identity the operation names (the /// lookup failed, which is not Platform's answer that it does not exist, /// 7). Nothing was signed, reserved or broadcast: retry as it is. - case errorIdentityLookupFailed = 77 + case errorIdentityLookupFailed = 80 /// The named thing does not exist. Besides the handle/lookup failures this /// has always covered, BOTH deferred-send paths report the /// wallet-was-REMOVED case here. @@ -750,7 +750,7 @@ public enum PlatformWalletError: LocalizedError { /// reads whether the pair is still held so. case publicContactRequestUnconfirmed(String) /// Platform could not be asked for an identity the operation names (code - /// 77): the lookup itself failed, before anything was signed, reserved or + /// 80): the lookup itself failed, before anything was signed, reserved or /// broadcast. Not sent, so it may be retried as it is; unlike an unmapped /// SDK error it is never a possibly delivered operation. case identityLookupFailed(String) diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift index 9838d72b66c..2702949f8ae 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -612,7 +612,7 @@ final class ErrorHandlingTests: XCTestCase { ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_IDENTITY_LOOKUP_FAILED ) XCTAssertEqual(code, .errorIdentityLookupFailed) - XCTAssertEqual(code.rawValue, 77) + XCTAssertEqual(code.rawValue, 80) let detail = "could not look up identity 9fRYTJZW on Platform; nothing was sent" guard case .identityLookupFailed(let message) = PlatformWalletError(code: code, message: detail) else { From 091026ef05cbcdc3e482ea620e2853a10a3f6718 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 11:58:53 +0200 Subject: [PATCH 08/19] fix(platform-wallet): do not report an address top-up as done from an unbound state snapshot The result proof of an identity top-up from addresses authenticates only the identity and address state at the proof's block, not that this transition executed. The wallet now signs with nonces it looked up itself and keeps the result only when the proof shows every input address at or past its submitted nonce. A snapshot from before is reported as the SDK's unconfirmed outcome, with nothing reconciled from it, on both the managed and the external top-up. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/top_up_from_addresses.rs | 162 ++++++++++++++++-- .../src/wallet/platform_wallet.rs | 14 ++ 2 files changed, 162 insertions(+), 14 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 8a46f645dbb..a9a2ec579cb 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -4,9 +4,10 @@ use std::collections::BTreeMap; use dpp::identity::signer::Signer; use dpp::identity::Identity; -use dpp::prelude::Identifier; +use dpp::prelude::{AddressNonce, Identifier}; use dash_sdk::dapi_grpc::platform::v0::ResponseMetadata; +use dash_sdk::platform::transition::fetch_inputs_with_nonce; use dash_sdk::platform::transition::put_settings::PutSettings; use dash_sdk::platform::transition::top_up_identity_from_addresses::TopUpIdentityFromAddressesWithMetadata; use dash_sdk::platform::Fetch; @@ -170,6 +171,14 @@ impl IdentityWallet { /// Build, sign, broadcast and wait for the top-up of `identity` from /// `inputs`, mapping the SDK error the way every address top-up reports it. + /// + /// The result proof of this transition authenticates only the state it + /// affects (the identity's balance and the input addresses as of the + /// proof's block), not that this transition executed. The result stands + /// only once the proof shows every input address at or past the nonce + /// this transition was signed with ([`bind_to_submitted_nonces`]); + /// otherwise the top-up is reported unconfirmed and nothing is + /// reconciled from it. async fn submit_top_up_from_addresses + Send + Sync>( &self, identity: &Identity, @@ -177,24 +186,50 @@ impl IdentityWallet { address_signer: &S, settings: Option, ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { - identity - .top_up_from_addresses_with_metadata(&self.sdk, inputs, address_signer, settings) + let inputs = fetch_inputs_with_nonce(&self.sdk, &inputs) .await - .map_err(|e| { - preserve_signer_key_unavailable_or(e, |e| { - promote_address_nonce_error(&e) - .or_else(|| no_inputs_as_invalid_parameter(&e)) - .unwrap_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to top up identity from addresses: {}", - e - )) - }) - }) + .map_err(top_up_error)? + .into_iter() + .map(|(address, (nonce, credits))| { + let next = nonce.checked_add(1).ok_or_else(|| { + PlatformWalletError::InvalidParameter(format!( + "{address:?} has used every nonce and can fund nothing more" + )) + })?; + Ok((address, (next, credits))) }) + .collect::, PlatformWalletError>>()?; + let submitted = inputs + .iter() + .map(|(address, (nonce, _))| (*address, *nonce)) + .collect(); + let confirmed = identity + .top_up_from_addresses_with_nonce_with_metadata( + &self.sdk, + inputs, + address_signer, + settings, + ) + .await + .map_err(top_up_error)?; + bind_to_submitted_nonces(&submitted, confirmed) } } +/// An SDK error of an address top-up as the wallet reports it. +fn top_up_error(e: dash_sdk::Error) -> PlatformWalletError { + preserve_signer_key_unavailable_or(e, |e| { + promote_address_nonce_error(&e) + .or_else(|| no_inputs_as_invalid_parameter(&e)) + .unwrap_or_else(|| { + PlatformWalletError::InvalidIdentityData(format!( + "Failed to top up identity from addresses: {}", + e + )) + }) + }) +} + /// The input map of an address-funded top-up from its funding rows: rows /// naming the same address are one input of their sum. A sum that overflows /// is refused with [`PlatformWalletError::InvalidParameter`]. No rows make an @@ -225,3 +260,102 @@ fn no_inputs_as_invalid_parameter(error: &dash_sdk::Error) -> Option, + confirmed: (AddressInfos, Credits, ResponseMetadata), +) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + for (address, nonce) in submitted { + let proved = confirmed.0.get(address).and_then(|info| info.as_ref()); + if proved.is_none_or(|info| info.nonce < *nonce) { + return Err(PlatformWalletError::Sdk( + dash_sdk::Error::StateTransitionResultUnconfirmed(Box::new( + dash_sdk::Error::ExecutionNotProved(format!( + "the identity top-up proof shows {address:?} at nonce {:?}, before \ + the submitted nonce {nonce}", + proved.map(|info| info.nonce) + )), + )), + )); + } + } + Ok(confirmed) +} + +#[cfg(test)] +mod nonce_binding_tests { + use super::*; + use dash_sdk::query_types::AddressInfo; + + const FIRST: PlatformAddress = PlatformAddress::P2pkh([1; 20]); + const SECOND: PlatformAddress = PlatformAddress::P2pkh([2; 20]); + + fn proved(nonces: &[(PlatformAddress, Option)]) -> AddressInfos { + AddressInfos::from_iter(nonces.iter().map(|(address, nonce)| { + ( + *address, + nonce.map(|nonce| AddressInfo { + address: *address, + nonce, + balance: 5, + }), + ) + })) + } + + fn bind( + proved_nonces: &[(PlatformAddress, Option)], + ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + let submitted = BTreeMap::from([(FIRST, 4), (SECOND, 9)]); + bind_to_submitted_nonces( + &submitted, + (proved(proved_nonces), 777, ResponseMetadata::default()), + ) + } + + /// A proof that shows an input address before the nonce this top-up + /// was signed with is a snapshot from before it executed: the top-up + /// may still execute, so it is reported unconfirmed, not done. + #[test] + fn should_report_a_snapshot_before_the_submitted_nonces_as_unconfirmed() { + for proved_nonces in [ + [(FIRST, Some(3)), (SECOND, Some(8))], + [(FIRST, Some(4)), (SECOND, Some(8))], + [(FIRST, Some(4)), (SECOND, None)], + ] { + let result = bind(&proved_nonces); + assert!( + matches!( + &result, + Err(PlatformWalletError::Sdk(e)) if e.is_state_transition_result_unconfirmed() + ), + "{proved_nonces:?}: {result:?}" + ); + } + } + + /// Every input address at (or past) the nonce this top-up was signed + /// with: the nonces it used are consumed, so the result stands. + #[test] + fn should_keep_a_result_whose_proof_shows_the_submitted_nonces_used() { + for proved_nonces in [ + [(FIRST, Some(4)), (SECOND, Some(9))], + [(FIRST, Some(5)), (SECOND, Some(9))], + ] { + let (_, balance, _) = bind(&proved_nonces).expect("bound to the submitted nonces"); + assert_eq!(balance, 777); + } + } +} diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 238aeea831c..8550bc7959a 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -595,6 +595,13 @@ impl PlatformWallet { /// rather than propagated — Platform already accepted the top-up, and /// a later sync reconciles. /// + /// A result proof that does not show the input addresses' nonces this + /// top-up was signed with as used does not prove it executed: it is + /// reported as `PlatformWalletError::Sdk` holding + /// `dash_sdk::Error::StateTransitionResultUnconfirmed` (it may still + /// execute, so do not submit it again), and neither the identity balance + /// nor the addresses are updated from it; the next sync settles them. + /// /// Returns the identity's new credit balance. pub async fn top_up_from_addresses( &self, @@ -634,6 +641,13 @@ impl PlatformWallet { /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing /// fetched, signed or broadcast. A caller must not hold the gate. /// + /// A result proof that does not show the input addresses' nonces this + /// top-up was signed with as used does not prove it executed: it is + /// reported as `PlatformWalletError::Sdk` holding + /// `dash_sdk::Error::StateTransitionResultUnconfirmed` (it may still + /// execute, so do not submit it again), and the addresses are not + /// updated from it; the next sync settles them. + /// /// Returns the identity's new credit balance. pub async fn top_up_external_identity_from_addresses( &self, From 3cfd9525760aefcb8b01a22aba28a3c9b02e4185 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 12:04:08 +0200 Subject: [PATCH 09/19] fix(platform-wallet-ffi): turn a panic in the address top-up exports into a result code Both address top-up exports ran the composite through block_on_worker, which re-panics a worker panic inside the extern "C" function and ends the host. Their bodies now run under catch_panic_to_code and report ErrorTransactionBroadcastUnconfirmed (20): the panic may strike after signing or broadcast, so the top-up may still execute and must not be submitted again. Co-Authored-By: Claude Opus 5.5 --- .../src/identity_top_up.rs | 163 ++++++++++++------ .../external_identity_tests.rs | 45 +++++ 2 files changed, 151 insertions(+), 57 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs index 5ac03e5d38b..4f7a2a01c08 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs @@ -49,6 +49,28 @@ mod registry_release_tests; #[cfg(test)] mod submission_result_tests; +/// What a host should know after an address top-up export panicked. +const ADDRESS_TOP_UP_PANIC_GUIDANCE: &str = "The top-up may have been signed and broadcast \ + and may still execute: do NOT submit it again; the next sync settles the outcome."; + +/// [`catch_panic_to_code`] for the address top-up exports. A panic can strike +/// in the identity lookup, the signing, after the broadcast or in the +/// reconciliation, so it is reported as +/// [`PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed`], +/// the code of a top-up whose execution is not proved, never as a definitive +/// unsent failure. +fn catch_address_top_up_panic( + operation: &str, + body: impl FnOnce() -> PlatformWalletFFIResult, +) -> PlatformWalletFFIResult { + catch_panic_to_code( + operation, + PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed, + ADDRESS_TOP_UP_PANIC_GUIDANCE, + body, + ) +} + /// Top up an existing identity's credit balance from one or more /// Platform addresses, using an external `SignerHandle` for the /// per-address funding signatures. @@ -60,6 +82,12 @@ mod submission_result_tests; /// `ManagedIdentity::balance` read on the same handle reflects the /// new value without an extra round trip. /// +/// `ErrorTransactionBroadcastUnconfirmed` (20) means the top-up may have +/// executed or may still execute: its result was not proved (including a +/// result proof that does not show this top-up's address nonces used), or +/// the call panicked, possibly after signing or broadcast. The host must not +/// submit it again; the next sync settles the outcome. +/// /// # Safety /// - `wallet_handle` must come from the platform-wallet handle registry. /// - `identity_id` must point at a 32-byte identity id buffer for @@ -81,41 +109,44 @@ pub unsafe extern "C" fn platform_wallet_top_up_from_addresses_with_signer( signer_address_handle: *mut SignerHandle, out_new_balance: *mut u64, ) -> PlatformWalletFFIResult { - check_ptr!(identity_id); - check_ptr!(inputs); - check_ptr!(signer_address_handle); - check_ptr!(out_new_balance); - let identity_id_bytes: [u8; 32] = *identity_id; - let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); - let rows = match funding_rows(inputs, inputs_count) { - Ok(rows) => rows, - Err(error) => return error, - }; + catch_address_top_up_panic("platform_wallet_top_up_from_addresses_with_signer", || { + check_ptr!(identity_id); + check_ptr!(inputs); + check_ptr!(signer_address_handle); + check_ptr!(out_new_balance); + let identity_id_bytes: [u8; 32] = *identity_id; + let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); + let rows = match funding_rows(inputs, inputs_count) { + Ok(rows) => rows, + Err(error) => return error, + }; - // Round-trip the signer pointer through `usize` so the spawned - // future's capture is `Send + 'static` (the raw pointer is `!Send`, - // but `usize` is). The underlying `Inner::Callback { ctx, vtable }` - // is `Send + Sync` — see the unsafe impls in `rs-sdk-ffi/src/signer.rs`. - let signer_addr = signer_address_handle as usize; + // Round-trip the signer pointer through `usize` so the spawned + // future's capture is `Send + 'static` (the raw pointer is `!Send`, + // but `usize` is). The underlying `Inner::Callback { ctx, vtable }` + // is `Send + Sync` — see the unsafe impls in `rs-sdk-ffi/src/signer.rs`. + let signer_addr = signer_address_handle as usize; - // Take the wallet out of the registry in a short read, so the registry - // is not locked while the host signs. - let wallet = - unwrap_option_or_return!(PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone())); - let result = block_on_worker(async move { - let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; - // The composite tops up the identity AND reconciles the spent - // platform-address balances from the proof, so the wallet's - // displayed balance and next input selection reflect the spend - // (covering addresses restored from disk that are no longer in - // a live derived pool). - wallet - .top_up_from_addresses(&identity_id, rows, address_signer, None) - .await - }); - let new_balance = unwrap_result_or_return!(result); - *out_new_balance = new_balance; - PlatformWalletFFIResult::ok() + // Take the wallet out of the registry in a short read, so the registry + // is not locked while the host signs. + let wallet = unwrap_option_or_return!( + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone()) + ); + let result = block_on_worker(async move { + let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; + // The composite tops up the identity AND reconciles the spent + // platform-address balances from the proof, so the wallet's + // displayed balance and next input selection reflect the spend + // (covering addresses restored from disk that are no longer in + // a live derived pool). + wallet + .top_up_from_addresses(&identity_id, rows, address_signer, None) + .await + }); + let new_balance = unwrap_result_or_return!(result); + *out_new_balance = new_balance; + PlatformWalletFFIResult::ok() + }) } /// Marshal the address-input rows of an address-funded top-up into the @@ -158,6 +189,12 @@ unsafe fn funding_rows( /// Platform does not know returns `ErrorIdentityNotFound` before anything /// is signed or broadcast. /// +/// `ErrorTransactionBroadcastUnconfirmed` (20) means the top-up may have +/// executed or may still execute: its result was not proved (including a +/// result proof that does not show this top-up's address nonces used), or +/// the call panicked, possibly after signing or broadcast. The host must not +/// submit it again; the next sync settles the outcome. +/// /// # Safety /// Same contract as [`platform_wallet_top_up_from_addresses_with_signer`]. #[no_mangle] @@ -169,32 +206,44 @@ pub unsafe extern "C" fn platform_wallet_top_up_external_identity_from_addresses signer_address_handle: *mut SignerHandle, out_new_balance: *mut u64, ) -> PlatformWalletFFIResult { - check_ptr!(identity_id); - check_ptr!(inputs); - check_ptr!(signer_address_handle); - check_ptr!(out_new_balance); - let identity_id_bytes: [u8; 32] = *identity_id; - let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); - let rows = match funding_rows(inputs, inputs_count) { - Ok(rows) => rows, - Err(error) => return error, - }; + catch_address_top_up_panic( + "platform_wallet_top_up_external_identity_from_addresses_with_signer", + || { + check_ptr!(identity_id); + check_ptr!(inputs); + check_ptr!(signer_address_handle); + check_ptr!(out_new_balance); + let identity_id_bytes: [u8; 32] = *identity_id; + let identity_id = Identifier::from_bytes(&identity_id_bytes).unwrap_or_default(); + let rows = match funding_rows(inputs, inputs_count) { + Ok(rows) => rows, + Err(error) => return error, + }; - // `usize` round-trip keeps the spawned future `Send + 'static`; see - // `platform_wallet_top_up_from_addresses_with_signer`. - let signer_addr = signer_address_handle as usize; + // `usize` round-trip keeps the spawned future `Send + 'static`; see + // `platform_wallet_top_up_from_addresses_with_signer`. + let signer_addr = signer_address_handle as usize; - let wallet = - unwrap_option_or_return!(PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone())); - let result = block_on_worker(async move { - let address_signer: &VTableSigner = unsafe { &*(signer_addr as *const VTableSigner) }; - wallet - .top_up_external_identity_from_addresses(&identity_id, rows, address_signer, None) - .await - }); - let new_balance = unwrap_result_or_return!(result); - *out_new_balance = new_balance; - PlatformWalletFFIResult::ok() + let wallet = unwrap_option_or_return!( + PLATFORM_WALLET_STORAGE.with_item(wallet_handle, |w| w.clone()) + ); + let result = block_on_worker(async move { + let address_signer: &VTableSigner = + unsafe { &*(signer_addr as *const VTableSigner) }; + wallet + .top_up_external_identity_from_addresses( + &identity_id, + rows, + address_signer, + None, + ) + .await + }); + let new_balance = unwrap_result_or_return!(result); + *out_new_balance = new_balance; + PlatformWalletFFIResult::ok() + }, + ) } /// Minimum asset-lock funding for a Core-funded identity top-up, in duffs. diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs index 9900a792456..1b301adca68 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs @@ -1,5 +1,6 @@ //! The external-identity top-up export: its argument guards, and an identity //! Platform does not know reported as code 7 through the real wallet handle. +//! A panic in either address top-up export is reported as code 20. use std::ptr::NonNull; use std::sync::Arc; @@ -269,3 +270,47 @@ fn should_report_an_identity_platform_does_not_know_as_not_found() { }); assert_eq!(identities, 0); } + +/// A panic inside either address top-up export (here its blocking wait, +/// entered from inside a runtime) comes back as the "may have executed" +/// code 20, not as an unwind through the C ABI that ends the host, and the +/// balance out is not written. +#[test] +fn should_turn_a_panic_in_either_export_into_the_unconfirmed_code() { + let (handle, signer) = wallet_handle(Some(platform_identity())); + let id = IDENTITY; + let rows = [input(0)]; + let mut balance = UNTOUCHED; + let out: *mut u64 = &mut balance; + + let (external, managed) = tokio::runtime::Runtime::new() + .expect("a runtime") + .block_on(async { + let external = unsafe { top_up(handle, &id, rows.as_ptr(), 1, signer, out) }; + let managed = unsafe { + platform_wallet_top_up_from_addresses_with_signer( + handle, + &id, + rows.as_ptr(), + 1, + signer, + out, + ) + }; + (external, managed) + }); + + release(handle, signer); + for mut result in [external, managed] { + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorTransactionBroadcastUnconfirmed + ); + let message = unsafe { std::ffi::CStr::from_ptr(result.message) } + .to_string_lossy() + .into_owned(); + assert!(message.contains("panicked"), "{message}"); + unsafe { crate::error::platform_wallet_ffi_result_free(&mut result) }; + } + assert_eq!(balance, UNTOUCHED); +} From df3000af7d0c799d2872ac971db8a3f773e038d4 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 12:12:17 +0200 Subject: [PATCH 10/19] fix(platform-wallet): keep unpromoted SDK errors in the address top-up The address top-up promotes a nonce race and an empty input map to their own errors; every other SDK error was flattened into an InvalidIdentityData string, losing its typed variant and consensus cause. It is now kept as PlatformWalletError::Sdk. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/top_up_from_addresses.rs | 11 +++---- .../external_identity_tests.rs | 30 ++++++++++++++++--- 2 files changed, 30 insertions(+), 11 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index a9a2ec579cb..95c6202b85c 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -216,17 +216,14 @@ impl IdentityWallet { } } -/// An SDK error of an address top-up as the wallet reports it. +/// An SDK error of an address top-up as the wallet reports it: a nonce +/// race and an empty input map promoted to their own errors, every other +/// error kept typed under [`PlatformWalletError::Sdk`]. fn top_up_error(e: dash_sdk::Error) -> PlatformWalletError { preserve_signer_key_unavailable_or(e, |e| { promote_address_nonce_error(&e) .or_else(|| no_inputs_as_invalid_parameter(&e)) - .unwrap_or_else(|| { - PlatformWalletError::InvalidIdentityData(format!( - "Failed to top up identity from addresses: {}", - e - )) - }) + .unwrap_or(PlatformWalletError::Sdk(e)) }) } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index c2f2f1f2e3c..bf80d4d40b4 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -32,6 +32,8 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use dash_sdk::query_types::{AddressInfo, AddressInfos}; use dash_sdk::{RequestSettings, Sdk, SdkBuilder}; use dpp::address_funds::{AddressWitness, PlatformAddress}; +use dpp::consensus::state::state_error::StateError; +use dpp::consensus::ConsensusError; use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; use dpp::identity::{Identity, IdentityV0}; @@ -136,12 +138,13 @@ struct Fixture { impl Fixture { async fn new(on_platform: bool) -> Self { - Self::build(Some(on_platform)).await + Self::build(Some(on_platform), AMOUNT).await } /// `on_platform` `None`: Platform cannot be reached to look the /// identity up, there is no expectation for the request. - async fn build(on_platform: Option) -> Self { + /// `address_balance` is what Platform holds on [`ADDRESS`]. + async fn build(on_platform: Option, address_balance: u64) -> Self { let mut sdk = SdkBuilder::new_mock() .with_version(PlatformVersion::latest()) .with_time_tolerance(None) @@ -201,7 +204,7 @@ impl Fixture { Some(AddressInfo { address: ADDRESS, nonce: 0, - balance: AMOUNT, + balance: address_balance, }), )])), ) @@ -353,7 +356,7 @@ async fn should_refuse_an_identity_platform_does_not_know_without_submitting() { /// have gone through", with nothing signed or submitted. #[tokio::test(flavor = "multi_thread")] async fn should_report_a_failed_recipient_lookup_as_not_sent() { - let mut fixture = Fixture::build(None).await; + let mut fixture = Fixture::build(None, AMOUNT).await; let error = fixture .top_up() @@ -681,3 +684,22 @@ async fn should_refuse_an_overflowing_funding_sum_on_both_routes() { } assert_eq!(fixture.submissions().await, (0, 0, 0)); } + +/// An SDK error the top-up does not promote keeps its typed variant, here +/// the SDK's own refusal of an address short of the amount, with nothing +/// signed or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_keep_an_unpromoted_sdk_error_typed() { + let mut fixture = Fixture::build(Some(true), AMOUNT - 1).await; + + let error = fixture.top_up().await.expect_err("the address is short"); + + assert!( + matches!(&error, PlatformWalletError::Sdk(e) if matches!( + e.consensus_error(), + Some(ConsensusError::StateError(StateError::AddressNotEnoughFundsError(_))) + )), + "got {error:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} From 46428085d636b15fc8502095913c025758b38b9e Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 12:14:39 +0200 Subject: [PATCH 11/19] fix(kotlin-sdk): mark a failed identity lookup as retryable IdentityLookupFailed (code 80) means nothing was signed, reserved or broadcast, so the operation may be retried as it is; isRetryable now says so, as the code-80 mapping test asserts. Co-Authored-By: Claude Opus 5.5 --- .../kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt | 4 +++- .../org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt | 1 + 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt index 459c1ac6bd6..0b5297dcd44 100644 --- a/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt +++ b/packages/kotlin-sdk/sdk/src/main/kotlin/org/dashfoundation/dashsdk/errors/DashSdkError.kt @@ -804,7 +804,9 @@ sealed class DashSdkError( * ← Swift `PlatformWalletError.identityLookupFailed`. */ class IdentityLookupFailed(message: String, cause: Throwable? = null) : - PlatformWallet(message, cause) + PlatformWallet(message, cause) { + override val isRetryable: Boolean get() = true + } /** * Any other `PlatformWalletFFIResultCode` without a dedicated type. diff --git a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt index d56acd298b6..946d2a0882d 100644 --- a/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt +++ b/packages/kotlin-sdk/sdk/src/test/kotlin/org/dashfoundation/dashsdk/errors/DashSdkErrorTest.kt @@ -411,6 +411,7 @@ class DashSdkErrorTest { val mapped = DashSdkError.fromNative(native) assertTrue(mapped is DashSdkError.PlatformWallet.IdentityLookupFailed) assertEquals(detail, mapped.message) + assertTrue("nothing was sent, so it may be retried as it is", mapped.isRetryable) } @Test From 69ffa8459827ea8dc5de0938ca5096fd26502084 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 15:52:23 +0200 Subject: [PATCH 12/19] fix(platform-wallet): report an address top-up whose identity balance did not grow as unconfirmed Used input nonces show that a transition this wallet signed with them executed, not that it paid the identity: another transition with the same nonces could have spent them elsewhere. The result now also needs the proved identity balance above the one the top-up started from; otherwise it is StateTransitionResultUnconfirmed(ExecutionNotProved) (FFI 20) and nothing is reconciled. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/top_up_from_addresses.rs | 92 +++++++++++++++---- 1 file changed, 72 insertions(+), 20 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 95c6202b85c..4ef42868df0 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -2,6 +2,7 @@ use std::collections::BTreeMap; +use dpp::identity::accessors::IdentityGettersV0; use dpp::identity::signer::Signer; use dpp::identity::Identity; use dpp::prelude::{AddressNonce, Identifier}; @@ -176,9 +177,9 @@ impl IdentityWallet { /// affects (the identity's balance and the input addresses as of the /// proof's block), not that this transition executed. The result stands /// only once the proof shows every input address at or past the nonce - /// this transition was signed with ([`bind_to_submitted_nonces`]); - /// otherwise the top-up is reported unconfirmed and nothing is - /// reconciled from it. + /// this transition was signed with and the identity balance above the + /// one `identity` carries ([`bind_to_submitted_nonces`]); otherwise the + /// top-up is reported unconfirmed and nothing is reconciled from it. async fn submit_top_up_from_addresses + Send + Sync>( &self, identity: &Identity, @@ -212,7 +213,7 @@ impl IdentityWallet { ) .await .map_err(top_up_error)?; - bind_to_submitted_nonces(&submitted, confirmed) + bind_to_submitted_nonces(&submitted, identity.balance(), confirmed) } } @@ -259,38 +260,57 @@ fn no_inputs_as_invalid_parameter(error: &dash_sdk::Error) -> Option, + balance_before: Credits, confirmed: (AddressInfos, Credits, ResponseMetadata), ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + if confirmed.1 <= balance_before { + return Err(unconfirmed(format!( + "the identity top-up proof shows the identity balance at {}, not above the {} it \ + started from", + confirmed.1, balance_before + ))); + } for (address, nonce) in submitted { let proved = confirmed.0.get(address).and_then(|info| info.as_ref()); if proved.is_none_or(|info| info.nonce < *nonce) { - return Err(PlatformWalletError::Sdk( - dash_sdk::Error::StateTransitionResultUnconfirmed(Box::new( - dash_sdk::Error::ExecutionNotProved(format!( - "the identity top-up proof shows {address:?} at nonce {:?}, before \ - the submitted nonce {nonce}", - proved.map(|info| info.nonce) - )), - )), - )); + return Err(unconfirmed(format!( + "the identity top-up proof shows {address:?} at nonce {:?}, before the \ + submitted nonce {nonce}", + proved.map(|info| info.nonce) + ))); } } Ok(confirmed) } +/// The SDK's unconfirmed outcome for a proof that does not show this top-up. +fn unconfirmed(reason: String) -> PlatformWalletError { + PlatformWalletError::Sdk(dash_sdk::Error::StateTransitionResultUnconfirmed(Box::new( + dash_sdk::Error::ExecutionNotProved(reason), + ))) +} + #[cfg(test)] mod nonce_binding_tests { use super::*; @@ -312,16 +332,30 @@ mod nonce_binding_tests { })) } - fn bind( + const BALANCE_BEFORE: Credits = 700; + + fn bind_with_balance( proved_nonces: &[(PlatformAddress, Option)], + proved_balance: Credits, ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { let submitted = BTreeMap::from([(FIRST, 4), (SECOND, 9)]); bind_to_submitted_nonces( &submitted, - (proved(proved_nonces), 777, ResponseMetadata::default()), + BALANCE_BEFORE, + ( + proved(proved_nonces), + proved_balance, + ResponseMetadata::default(), + ), ) } + fn bind( + proved_nonces: &[(PlatformAddress, Option)], + ) -> Result<(AddressInfos, Credits, ResponseMetadata), PlatformWalletError> { + bind_with_balance(proved_nonces, 777) + } + /// A proof that shows an input address before the nonce this top-up /// was signed with is a snapshot from before it executed: the top-up /// may still execute, so it is reported unconfirmed, not done. @@ -355,4 +389,22 @@ mod nonce_binding_tests { assert_eq!(balance, 777); } } + + /// The submitted nonces are used but the identity balance did not grow: + /// another transition this wallet signed with the same nonces took them + /// and paid elsewhere. This top-up did not reach the identity, so the + /// result is unconfirmed, not done. + #[test] + fn should_report_used_nonces_without_a_higher_identity_balance_as_unconfirmed() { + for proved_balance in [BALANCE_BEFORE, BALANCE_BEFORE - 1] { + let result = bind_with_balance(&[(FIRST, Some(4)), (SECOND, Some(9))], proved_balance); + assert!( + matches!( + &result, + Err(PlatformWalletError::Sdk(e)) if e.is_state_transition_result_unconfirmed() + ), + "{proved_balance}: {result:?}" + ); + } + } } From 94708443ac24ffbd6c1e337f6b4efd3bacaac396 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 15:52:23 +0200 Subject: [PATCH 13/19] fix(swift-sdk): pin the wallet across the address top-up export call The detached call copies the wallet handle that ManagedPlatformWallet's deinit destroys; pin the wallet together with the signer for the whole synchronous FFI call, as refreshIdentityBalance does. Co-Authored-By: Claude Opus 5.5 --- .../SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift index 85c05196e5c..3f037a89cb4 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/ManagedPlatformWallet.swift @@ -904,8 +904,9 @@ public final class ManagedPlatformWallet: @unchecked Sendable { // Swift lifetimes end at last use, not at scope end — a bare // `_ = addressSigner` is no fence. `withExtendedLifetime` pins // it across the whole synchronous FFI call (lookup, signing, - // broadcast and wait) and its buffer pinning. - let result = withExtendedLifetime(addressSigner) { + // broadcast and wait) and its buffer pinning. The wallet is + // pinned with it: its `deinit` destroys `handle`. + let result = withExtendedLifetime((self, addressSigner)) { ffiInputs.withUnsafeBufferPointer { inputsBuf in withUnsafePointer(to: &idTuple) { idPtr in call( From d448bb9da85c703126c9983d65e226d9f6ec3f48 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 16:12:10 +0200 Subject: [PATCH 14/19] fix(platform-wallet): fence the managed address top-up against wallet removal PlatformWallet::top_up_from_addresses now runs through the same seam as the external top-up (top_up_identity_with): it holds the generation's lifecycle gate from the liveness check through signing, broadcast and reconciliation, and a wallet removed or re-created since the handle was taken is refused with WalletRemovedBeforeSend, nothing signed or sent. Co-Authored-By: Claude Opus 5.5 --- .../external_identity_tests.rs | 21 +++++++- .../src/wallet/platform_wallet.rs | 53 +++++++++++-------- 2 files changed, 49 insertions(+), 25 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index bf80d4d40b4..48c8d0cc52d 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -394,7 +394,7 @@ async fn should_report_empty_inputs_as_an_invalid_parameter_on_both_routes() { /// was taken tops up nothing: refused before the identity is fetched, /// anything is signed or submitted. #[tokio::test(flavor = "multi_thread")] -async fn should_refuse_a_top_up_from_a_wallet_no_longer_current() { +async fn should_refuse_a_top_up_from_a_wallet_no_longer_current_on_both_routes() { let mut fixture = Fixture::new(true).await; let wallet_id = fixture.wallet.wallet_id(); fixture @@ -409,6 +409,12 @@ async fn should_refuse_a_top_up_from_a_wallet_no_longer_current() { if *id == hex::encode(wallet_id)), "{removed:?}" ); + let removed_own = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; + assert!( + matches!(&removed_own, Err(PlatformWalletError::WalletRemovedBeforeSend(id)) + if *id == hex::encode(wallet_id)), + "managed route: {removed_own:?}" + ); let recreated = fixture .manager @@ -429,6 +435,14 @@ async fn should_refuse_a_top_up_from_a_wallet_no_longer_current() { ), "{superseded:?}" ); + let superseded_own = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; + assert!( + matches!( + superseded_own, + Err(PlatformWalletError::WalletRemovedBeforeSend(_)) + ), + "managed route: {superseded_own:?}" + ); assert_eq!(fixture.submissions().await, (0, 0, 0)); } @@ -601,7 +615,10 @@ async fn should_reconcile_the_spent_addresses_of_a_confirmed_top_up() { }), )]); let new_balance = wallet - .top_up_external_identity_with(async { Ok((confirmed, NEW_BALANCE, PROOF_HEIGHT)) }) + .top_up_identity_with( + async { Ok((confirmed, NEW_BALANCE, PROOF_HEIGHT)) }, + "external identity top-up", + ) .await .expect("a confirmed top-up"); diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 8550bc7959a..ff9774a2f0b 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -602,6 +602,12 @@ impl PlatformWallet { /// execute, so do not submit it again), and neither the identity balance /// nor the addresses are updated from it; the next sync settles them. /// + /// Holds the wallet generation's lifecycle gate like + /// [`Self::top_up_external_identity_from_addresses`]: a wallet removed or + /// re-created since this handle was taken is refused with + /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing signed or + /// broadcast. A caller must not hold the gate. + /// /// Returns the identity's new credit balance. pub async fn top_up_from_addresses( &self, @@ -614,17 +620,12 @@ impl PlatformWallet { S: Signer + Send + Sync, I: IntoIterator + Send, { - let (address_infos, new_balance, proof_height) = self - .identity - .top_up_from_addresses(identity_id, inputs, address_signer, settings) - .await?; - // The reconciled absolutes are pinned at the proof's block height - // (`AddressFunds::as_of_height`), so the sync's delta replay can - // never re-apply this transition's on-chain ops on top of them. - self.platform - .reconcile_address_infos(&address_infos, proof_height, "identity top-up") - .await; - Ok(new_balance) + self.top_up_identity_with( + self.identity + .top_up_from_addresses(identity_id, inputs, address_signer, settings), + "identity top-up", + ) + .await } /// Top up an identity this wallet does not manage by spending platform @@ -660,22 +661,28 @@ impl PlatformWallet { S: Signer + Send + Sync, I: IntoIterator + Send, { - self.top_up_external_identity_with(self.identity.top_up_external_from_addresses( - identity_id, - inputs, - address_signer, - settings, - )) + self.top_up_identity_with( + self.identity.top_up_external_from_addresses( + identity_id, + inputs, + address_signer, + settings, + ), + "external identity top-up", + ) .await } - /// The external top-up around its submission `top_up` (not yet - /// started): the lifecycle gate and liveness check, then the - /// reconciliation of the spent addresses at the proof's height. A seam - /// so a test can hand in a confirmed result the mock SDK cannot prove. - pub(crate) async fn top_up_external_identity_with( + /// An address top-up around its submission `top_up` (not yet started): + /// the lifecycle gate and liveness check, then the reconciliation of the + /// spent addresses at the proof's height (`AddressFunds::as_of_height`, + /// so the sync's delta replay never re-applies this transition's ops on + /// top of them). A seam so a test can hand in a confirmed result the + /// mock SDK cannot prove. + pub(crate) async fn top_up_identity_with( &self, top_up: impl Future>, + label: &'static str, ) -> Result { let _lifecycle = self.core().generation_payment_guard().await; if !self.core().is_current_generation().await { @@ -685,7 +692,7 @@ impl PlatformWallet { } let (address_infos, new_balance, proof_height) = top_up.await?; self.platform - .reconcile_address_infos(&address_infos, proof_height, "external identity top-up") + .reconcile_address_infos(&address_infos, proof_height, label) .await; Ok(new_balance) } From 12b698ea3caf08ace278e0ee65812e4c351a8344 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 21:02:26 +0200 Subject: [PATCH 15/19] fix(platform-wallet): refuse an address top-up without funding rows before any lookup An empty row list was accepted and only refused later by the SDK, after the external route's identity fetch, so it could surface as IdentityLookupFailed or IdentityNotFound instead of InvalidParameter. `funding_inputs` now refuses it on both routes before any network I/O, which leaves the SDK's empty-input refusal unreachable from the top-up; its promotion is removed. Co-Authored-By: Claude Opus 5.5 --- .../external_identity_tests.rs | 4 +-- .../identity/network/top_up_from_addresses.rs | 32 ++++++----------- .../external_identity_tests.rs | 36 +++++++++++-------- 3 files changed, 35 insertions(+), 37 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs index 1b301adca68..c04819b9ce0 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/external_identity_tests.rs @@ -195,8 +195,8 @@ fn should_refuse_an_overflowing_funding_sum_on_both_exports() { assert_eq!(balance, UNTOUCHED); } -/// No funding rows reach the library, whose refusal (the SDK's own -/// empty-input check) comes back as an invalid parameter. +/// No funding rows reach the library, which refuses them as an invalid +/// parameter before looking the identity up. #[test] fn should_report_empty_inputs_as_an_invalid_parameter() { let (handle, signer) = wallet_handle(Some(platform_identity())); diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 4ef42868df0..7915ab3fba9 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -14,8 +14,6 @@ use dash_sdk::platform::transition::top_up_identity_from_addresses::TopUpIdentit use dash_sdk::platform::Fetch; use dpp::address_funds::PlatformAddress; -use dpp::consensus::basic::BasicError; -use dpp::consensus::ConsensusError; use dpp::fee::Credits; use dash_sdk::query_types::AddressInfos; @@ -218,20 +216,19 @@ impl IdentityWallet { } /// An SDK error of an address top-up as the wallet reports it: a nonce -/// race and an empty input map promoted to their own errors, every other -/// error kept typed under [`PlatformWalletError::Sdk`]. +/// race promoted to its own error, every other error kept typed under +/// [`PlatformWalletError::Sdk`]. fn top_up_error(e: dash_sdk::Error) -> PlatformWalletError { preserve_signer_key_unavailable_or(e, |e| { - promote_address_nonce_error(&e) - .or_else(|| no_inputs_as_invalid_parameter(&e)) - .unwrap_or(PlatformWalletError::Sdk(e)) + promote_address_nonce_error(&e).unwrap_or(PlatformWalletError::Sdk(e)) }) } /// The input map of an address-funded top-up from its funding rows: rows /// naming the same address are one input of their sum. A sum that overflows -/// is refused with [`PlatformWalletError::InvalidParameter`]. No rows make an -/// empty map, which the SDK refuses as a transition without inputs. +/// is refused with [`PlatformWalletError::InvalidParameter`], and so are no +/// rows at all: both routes call this before any network I/O, so an empty +/// top-up is the caller's mistake whatever the identity lookup would say. pub(crate) fn funding_inputs( rows: impl IntoIterator, ) -> Result, PlatformWalletError> { @@ -244,21 +241,14 @@ pub(crate) fn funding_inputs( )) })?; } + if inputs.is_empty() { + return Err(PlatformWalletError::InvalidParameter( + "no funding rows were provided".to_string(), + )); + } Ok(inputs) } -/// The SDK's refusal of a transition without inputs, reported as the -/// caller's mistake it is. -fn no_inputs_as_invalid_parameter(error: &dash_sdk::Error) -> Option { - matches!( - error.consensus_error(), - Some(ConsensusError::BasicError( - BasicError::TransitionNoInputsError(_) - )) - ) - .then(|| PlatformWalletError::InvalidParameter(error.to_string())) -} - /// The submitted top-up's result once its proof is bound to this /// transition's address nonces (`submitted`) and to the identity balance /// it started from (`balance_before`). diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index 48c8d0cc52d..ee63d00d3b5 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -371,23 +371,31 @@ async fn should_report_a_failed_recipient_lookup_as_not_sent() { assert_eq!(fixture.submissions().await, (0, 0, 0)); } -/// An empty funding map is the caller's mistake on both routes: the SDK's -/// own empty-input refusal comes back as `InvalidParameter`, with nothing -/// signed or submitted. +/// An empty funding map is the caller's mistake on both routes, refused as +/// `InvalidParameter` before any network I/O, with nothing signed or +/// submitted: whether Platform knows the identity, does not know it, or +/// cannot be asked, the lookup never decides the error. #[tokio::test(flavor = "multi_thread")] async fn should_report_empty_inputs_as_an_invalid_parameter_on_both_routes() { - let mut fixture = Fixture::new(true).await; - - let external = fixture.top_up_with(Vec::new()).await; - let managed = fixture.top_up_own_with(Vec::new()).await; - - for result in [external, managed] { - assert!( - matches!(result, Err(PlatformWalletError::InvalidParameter(_))), - "got {result:?}" - ); + for on_platform in [Some(false), None, Some(true)] { + let mut fixture = Fixture::build(on_platform, AMOUNT).await; + + let external = fixture.top_up_with(Vec::new()).await; + let managed = fixture.top_up_own_with(Vec::new()).await; + let managed_unknown = fixture + .wallet + .top_up_from_addresses(&fixture.target, Vec::new(), &fixture.signer, settings()) + .await; + + for result in [external, managed, managed_unknown] { + assert!( + matches!(&result, Err(PlatformWalletError::InvalidParameter(reason)) + if reason == "no funding rows were provided"), + "{on_platform:?}: got {result:?}" + ); + } + assert_eq!(fixture.submissions().await, (0, 0, 0)); } - assert_eq!(fixture.submissions().await, (0, 0, 0)); } /// A handle to a wallet removed, or re-created under the same id, since it From d41a053f623e6f2dd38b70c6ac55bfc3e5deb5b0 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 21:08:48 +0200 Subject: [PATCH 16/19] fix(platform-wallet): measure a managed address top-up against Platform's balance The managed route took the balance the top-up must grow from the identity manager's cache. A cache above Platform's value (credits spent from another device, not yet synced) made an executed top-up report unconfirmed. The managed route now reads the identity's balance from Platform before signing and binds the proof to it, as the external route already does through its identity fetch. A failed read is IdentityLookupFailed and an unknown identity IdentityNotFound, both before anything is signed; the managed identity is still the one signed for and reconciled. Co-Authored-By: Claude Opus 5.5 --- .../identity_top_up/registry_release_tests.rs | 7 +- .../submission_result_tests.rs | 7 +- .../identity/network/top_up_from_addresses.rs | 77 +++++++++++++++++-- .../external_identity_tests.rs | 33 +++++++- 4 files changed, 114 insertions(+), 10 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs index 98a647bfcdc..01043843a8b 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/registry_release_tests.rs @@ -10,7 +10,7 @@ use std::sync::{Arc, Mutex}; use std::thread; use std::time::Duration; -use dash_sdk::query_types::{AddressInfo, AddressInfos}; +use dash_sdk::query_types::{AddressInfo, AddressInfos, IdentityBalance}; use dash_sdk::SdkBuilder; use dpp::address_funds::PlatformAddress; use dpp::identity::{Identity, IdentityV0}; @@ -133,6 +133,11 @@ async fn wallets() -> (Handle, Handle) { .expect_fetch::(Identifier::from(IDENTITY), Some(identity.clone())) .await .unwrap(); + // The managed route reads Platform's balance before signing. + sdk.mock() + .expect_fetch::(Identifier::from(IDENTITY), Some(0)) + .await + .unwrap(); let manager = PlatformWalletManager::new( Arc::new(sdk), Arc::new(NoPlatformPersistence), diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs index f0ebd8ebee1..ff18c8aad7c 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up/submission_result_tests.rs @@ -17,7 +17,7 @@ use dash_sdk::dapi_grpc::tonic::metadata::MetadataValue; use dash_sdk::dapi_grpc::tonic::Status; use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; use dash_sdk::platform::transition::put_settings::PutSettings; -use dash_sdk::query_types::{AddressInfo, AddressInfos}; +use dash_sdk::query_types::{AddressInfo, AddressInfos, IdentityBalance}; use dash_sdk::{Error as SdkError, RequestSettings, Sdk, SdkBuilder}; use dpp::address_funds::{AddressWitness, PlatformAddress}; use dpp::consensus::state::address_funds::AddressInvalidNonceError; @@ -180,6 +180,11 @@ impl Fixture { .map_err(|status| transport_error(&wait_request, status)), ); sdk.mock().load_expectations_sync(directory.path()).unwrap(); + // The managed route reads Platform's balance before signing. + sdk.mock() + .expect_fetch::(identity.id(), Some(identity.balance())) + .await + .unwrap(); sdk.mock() .expect_fetch_many::( BTreeSet::from([ADDRESS]), diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 7915ab3fba9..e5beda3b8ac 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -16,7 +16,7 @@ use dash_sdk::platform::Fetch; use dpp::address_funds::PlatformAddress; use dpp::fee::Credits; -use dash_sdk::query_types::AddressInfos; +use dash_sdk::query_types::{AddressInfos, IdentityBalance}; use crate::error::{ preserve_signer_key_unavailable_or, promote_address_nonce_error, PlatformWalletError, @@ -53,6 +53,14 @@ impl IdentityWallet { /// [`PlatformAddressWallet::reconcile_address_infos`]: /// crate::wallet::PlatformAddressWallet::reconcile_address_infos /// + /// The identity is signed for and reconciled as the identity manager + /// holds it, but the balance the top-up must grow is read from Platform + /// before anything is signed, so a cached balance above Platform's + /// cannot make an executed top-up look unconfirmed. A failed read is + /// [`PlatformWalletError::IdentityLookupFailed`], and Platform not + /// knowing the identity [`PlatformWalletError::IdentityNotFound`], both + /// before anything is signed or broadcast. + /// /// # Arguments /// /// * `identity_id` - The identity to top up. @@ -88,9 +96,25 @@ impl IdentityWallet { .map(|m| m.identity.clone()) .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))? }; + // The cached balance can sit above Platform's (credits spent from + // another device, not yet synced): growth is measured against + // Platform's own balance, read before anything is signed. + let balance_before = IdentityBalance::fetch(&self.sdk, *identity_id) + .await + .map_err(|source| PlatformWalletError::IdentityLookupFailed { + identity_id: *identity_id, + source, + })? + .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; let (address_infos, mut new_balance, metadata) = self - .submit_top_up_from_addresses(&identity, inputs, address_signer, settings) + .submit_top_up_from_addresses( + &identity, + balance_before, + inputs, + address_signer, + settings, + ) .await?; let proof_height = metadata.height; @@ -163,7 +187,13 @@ impl IdentityWallet { .ok_or(PlatformWalletError::IdentityNotFound(*identity_id))?; let (address_infos, new_balance, metadata) = self - .submit_top_up_from_addresses(&identity, inputs, address_signer, settings) + .submit_top_up_from_addresses( + &identity, + identity.balance(), + inputs, + address_signer, + settings, + ) .await?; Ok((address_infos, new_balance, metadata.height)) } @@ -175,12 +205,14 @@ impl IdentityWallet { /// affects (the identity's balance and the input addresses as of the /// proof's block), not that this transition executed. The result stands /// only once the proof shows every input address at or past the nonce - /// this transition was signed with and the identity balance above the - /// one `identity` carries ([`bind_to_submitted_nonces`]); otherwise the - /// top-up is reported unconfirmed and nothing is reconciled from it. + /// this transition was signed with and the identity balance above + /// `balance_before`, Platform's balance of the identity read before + /// signing ([`bind_to_submitted_nonces`]); otherwise the top-up is + /// reported unconfirmed and nothing is reconciled from it. async fn submit_top_up_from_addresses + Send + Sync>( &self, identity: &Identity, + balance_before: Credits, inputs: BTreeMap, address_signer: &S, settings: Option, @@ -211,7 +243,7 @@ impl IdentityWallet { ) .await .map_err(top_up_error)?; - bind_to_submitted_nonces(&submitted, identity.balance(), confirmed) + bind_to_submitted_nonces(&submitted, balance_before, confirmed) } } @@ -397,4 +429,35 @@ mod nonce_binding_tests { ); } } + + /// The baseline is Platform's balance read before signing, not a cached + /// one: with the cache above Platform's value (credits spent from + /// another device, not yet synced), a top-up that grew the identity + /// above Platform's balance stands, where the stale cache as baseline + /// would have reported it unconfirmed. + #[test] + fn should_keep_growth_over_platforms_balance_that_a_stale_cache_hides() { + const STALE_CACHE: Credits = 800; + const PROVED: Credits = 750; + let submitted = BTreeMap::from([(FIRST, 4), (SECOND, 9)]); + let proof = || { + ( + proved(&[(FIRST, Some(4)), (SECOND, Some(9))]), + PROVED, + ResponseMetadata::default(), + ) + }; + + let (_, balance, _) = bind_to_submitted_nonces(&submitted, BALANCE_BEFORE, proof()) + .expect("growth over Platform's balance stands"); + assert_eq!(balance, PROVED); + let against_cache = bind_to_submitted_nonces(&submitted, STALE_CACHE, proof()); + assert!( + matches!( + &against_cache, + Err(PlatformWalletError::Sdk(e)) if e.is_state_transition_result_unconfirmed() + ), + "{against_cache:?}" + ); + } } diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs index ee63d00d3b5..27cb509f8ee 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses/external_identity_tests.rs @@ -29,7 +29,7 @@ use dash_sdk::dapi_grpc::platform::v0::{ }; use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; use dash_sdk::platform::transition::put_settings::PutSettings; -use dash_sdk::query_types::{AddressInfo, AddressInfos}; +use dash_sdk::query_types::{AddressInfo, AddressInfos, IdentityBalance}; use dash_sdk::{RequestSettings, Sdk, SdkBuilder}; use dpp::address_funds::{AddressWitness, PlatformAddress}; use dpp::consensus::state::state_error::StateError; @@ -398,6 +398,37 @@ async fn should_report_empty_inputs_as_an_invalid_parameter_on_both_routes() { } } +/// The managed route reads the identity's balance from Platform before +/// signing, the baseline its growth is measured against: a read that fails +/// (here no answer to the request) is the not-sent lookup failure, and +/// Platform not knowing the identity is not-found, both with nothing signed +/// or submitted. +#[tokio::test(flavor = "multi_thread")] +async fn should_read_the_managed_identitys_balance_from_platform_before_signing() { + let own = Identifier::from(OWN_IDENTITY); + let mut fixture = Fixture::new(true).await; + + let unreachable = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; + assert!( + matches!(&unreachable, Err(PlatformWalletError::IdentityLookupFailed { identity_id, .. }) + if *identity_id == own), + "got {unreachable:?}" + ); + + fixture + .sdk + .mock() + .expect_fetch::(own, None) + .await + .unwrap(); + let unknown = fixture.top_up_own_with(vec![(ADDRESS, AMOUNT)]).await; + assert!( + matches!(&unknown, Err(PlatformWalletError::IdentityNotFound(id)) if *id == own), + "got {unknown:?}" + ); + assert_eq!(fixture.submissions().await, (0, 0, 0)); +} + /// A handle to a wallet removed, or re-created under the same id, since it /// was taken tops up nothing: refused before the identity is fetched, /// anything is signed or submitted. From bb2e0f2f963c2ea4c607eef4e512f61a24fc9d3f Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 21:09:21 +0200 Subject: [PATCH 17/19] docs(platform-wallet): state the balance-growth condition of an unconfirmed address top-up The composite and FFI export docs described the unconfirmed outcome (FFI 20) as nonces-only. A result stands only when its proof shows every input address at or past its submitted nonce and the identity balance above the balance the top-up started from, a fresh Platform read taken before signing on both routes; otherwise it is 20 and nothing is reconciled. The managed export also documents its new balance-read errors. Co-Authored-By: Claude Opus 5.5 --- .../src/identity_top_up.rs | 26 +++++++++++++------ .../src/wallet/platform_wallet.rs | 16 ++++++++---- 2 files changed, 29 insertions(+), 13 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs index 4f7a2a01c08..e5642be3990 100644 --- a/packages/rs-platform-wallet-ffi/src/identity_top_up.rs +++ b/packages/rs-platform-wallet-ffi/src/identity_top_up.rs @@ -82,11 +82,18 @@ fn catch_address_top_up_panic( /// `ManagedIdentity::balance` read on the same handle reflects the /// new value without an extra round trip. /// +/// The identity's balance is read from Platform before anything is signed: +/// a failed read is `ErrorIdentityLookupFailed` (80) and an identity +/// Platform does not know `ErrorIdentityNotFound` (7), nothing sent. +/// /// `ErrorTransactionBroadcastUnconfirmed` (20) means the top-up may have -/// executed or may still execute: its result was not proved (including a -/// result proof that does not show this top-up's address nonces used), or -/// the call panicked, possibly after signing or broadcast. The host must not -/// submit it again; the next sync settles the outcome. +/// executed or may still execute: its result was not proved, or the call +/// panicked, possibly after signing or broadcast. A result proof counts only +/// when it shows every input address at or past the nonce this top-up was +/// signed with AND the identity balance above the balance the top-up started +/// from, a fresh read from Platform taken before signing; any other proof is +/// 20 and nothing is reconciled from it. The host must not submit it again; +/// the next sync settles the outcome. /// /// # Safety /// - `wallet_handle` must come from the platform-wallet handle registry. @@ -190,10 +197,13 @@ unsafe fn funding_rows( /// is signed or broadcast. /// /// `ErrorTransactionBroadcastUnconfirmed` (20) means the top-up may have -/// executed or may still execute: its result was not proved (including a -/// result proof that does not show this top-up's address nonces used), or -/// the call panicked, possibly after signing or broadcast. The host must not -/// submit it again; the next sync settles the outcome. +/// executed or may still execute: its result was not proved, or the call +/// panicked, possibly after signing or broadcast. A result proof counts only +/// when it shows every input address at or past the nonce this top-up was +/// signed with AND the identity balance above the balance the top-up started +/// from, a fresh read from Platform taken before signing; any other proof is +/// 20 and nothing is reconciled from it. The host must not submit it again; +/// the next sync settles the outcome. /// /// # Safety /// Same contract as [`platform_wallet_top_up_from_addresses_with_signer`]. diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index ff9774a2f0b..0e9b53a8962 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -595,8 +595,11 @@ impl PlatformWallet { /// rather than propagated — Platform already accepted the top-up, and /// a later sync reconciles. /// - /// A result proof that does not show the input addresses' nonces this - /// top-up was signed with as used does not prove it executed: it is + /// The result stands only when its proof shows every input address at or + /// past the nonce this top-up was signed with AND the identity balance + /// above the balance the top-up started from, a fresh read from Platform + /// taken before signing (not the identity manager's cached balance). + /// Otherwise the proof does not prove this top-up executed: it is /// reported as `PlatformWalletError::Sdk` holding /// `dash_sdk::Error::StateTransitionResultUnconfirmed` (it may still /// execute, so do not submit it again), and neither the identity balance @@ -642,9 +645,12 @@ impl PlatformWallet { /// [`PlatformWalletError::WalletRemovedBeforeSend`], with nothing /// fetched, signed or broadcast. A caller must not hold the gate. /// - /// A result proof that does not show the input addresses' nonces this - /// top-up was signed with as used does not prove it executed: it is - /// reported as `PlatformWalletError::Sdk` holding + /// The result stands only when its proof shows every input address at or + /// past the nonce this top-up was signed with AND the identity balance + /// above the balance the top-up started from, the one in the identity + /// fetched from Platform before signing. Otherwise the proof does not + /// prove this top-up executed: it is reported as + /// `PlatformWalletError::Sdk` holding /// `dash_sdk::Error::StateTransitionResultUnconfirmed` (it may still /// execute, so do not submit it again), and the addresses are not /// updated from it; the next sync settles them. From 8089a7e53141ad6c3052f07c546d922218ad8b57 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 21:09:46 +0200 Subject: [PATCH 18/19] docs(platform-wallet): state the residual limit of binding a top-up proof to its nonces A competing transition signed by the same seam with the same nonces plus an unrelated credit to the same identity still satisfies both checks; closing that needs an execution-bound proof of this transition. The doc also states that the wallet does not serialise address spends per input address in-process: the address top-up holds only the shared lifecycle read guard, and shield_guard covers shield-class operations only. Co-Authored-By: Claude Opus 5.5 --- .../identity/network/top_up_from_addresses.rs | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index e5beda3b8ac..8f2f0953f19 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -286,10 +286,11 @@ pub(crate) fn funding_inputs( /// it started from (`balance_before`). /// /// An address nonce is used exactly once and only in order (Platform takes -/// stored + 1), and only this wallet can sign for its input addresses. A -/// proof showing every input address at or past the submitted nonce shows -/// those nonces consumed: this top-up executed, or a transition this wallet -/// signed with the same nonces did and this one never can. Either way it can +/// stored + 1), and only the holder of the input addresses' keys (the +/// signer seam this top-up was signed through) can sign for them. A proof +/// showing every input address at or past the submitted nonce shows those +/// nonces consumed: this top-up executed, or a transition signed by the same +/// seam with the same nonces did and this one never can. Either way it can /// no longer execute later. A proof showing an input address before its /// submitted nonce (or not at all) is a snapshot that does not reflect this /// top-up, which may still execute. @@ -301,6 +302,19 @@ pub(crate) fn funding_inputs( /// (or of an identity that spent meanwhile, which reads the same way and /// errs on the safe side). Every refusal is the SDK's unconfirmed outcome, /// never done: the host must not pay again. +/// +/// Residual limit: the two checks bind the proof to this transition's +/// nonces and to some credit of the identity, not to this transition's +/// execution. A competing transition signed by the same signer seam with +/// the same nonces (which spends them elsewhere) together with an unrelated +/// credit to the same identity in the same window satisfies both, and an +/// unexecuted top-up is then reported done. Closing that fully needs an +/// execution-bound proof of this transition. The wallet does not serialise +/// address spends per input address in-process: the address top-up holds +/// only the wallet generation's shared lifecycle gate (a read guard), and +/// the per-wallet `shield_guard` single-flight covers the shield-class +/// operations, not this path, so two concurrent spends from one address +/// in one process can be signed with the same nonce. fn bind_to_submitted_nonces( submitted: &BTreeMap, balance_before: Credits, From 2ce86e84306ae95656ef86ea73476df6479846d3 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 23:34:02 +0200 Subject: [PATCH 19/19] fix(platform-wallet): keep the managed address top-up behind the lifecycle gate `IdentityWallet::top_up_from_addresses` was public and reachable through `PlatformWallet::identity()`, so a retained identity handle could spend around the wallet-generation gate the composite holds. It is now crate-private, as the external route's identity-side method already is; callers outside the crate use `PlatformWallet::top_up_from_addresses`. Co-Authored-By: Claude Opus 5.5 --- .../wallet/identity/network/top_up_from_addresses.rs | 11 ++++++++--- .../rs-platform-wallet/src/wallet/platform_wallet.rs | 8 ++++---- 2 files changed, 12 insertions(+), 7 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs index 8f2f0953f19..500acb46d89 100644 --- a/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs +++ b/packages/rs-platform-wallet/src/wallet/identity/network/top_up_from_addresses.rs @@ -40,14 +40,19 @@ impl IdentityWallet { /// /// This method owns only the identity-side balance update and returns /// the proof-attested post-spend `AddressInfos` alongside the new - /// identity balance. Prefer the composite - /// [`PlatformWallet::top_up_from_addresses`], which feeds the returned + /// identity balance. The composite + /// [`PlatformWallet::top_up_from_addresses`] feeds the returned /// `AddressInfos` through /// [`PlatformAddressWallet::reconcile_address_infos`] — the /// platform-address wallet holds the address provider needed to map a /// spent address back to its derivation index (including addresses /// restored from disk that are no longer in a live derived pool). /// + /// Crate-private: it does not check the wallet generation or reconcile + /// the spent addresses. Callers outside the crate use + /// [`PlatformWallet::top_up_from_addresses`], which holds the lifecycle + /// gate and reconciles. + /// /// [`PlatformWallet::top_up_from_addresses`]: /// crate::wallet::PlatformWallet::top_up_from_addresses /// [`PlatformAddressWallet::reconcile_address_infos`]: @@ -71,7 +76,7 @@ impl IdentityWallet { /// [`PlatformAddress`]es. Construction is the caller's concern — /// seed-backed, hardware, FFI trampoline, whatever — the wallet /// struct carries no key material itself. - pub async fn top_up_from_addresses( + pub(crate) async fn top_up_from_addresses( &self, identity_id: &Identifier, inputs: I, diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 0e9b53a8962..88f3bee5afb 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -590,10 +590,10 @@ impl PlatformWallet { /// balances and nonces from the proof-attested post-spend /// `AddressInfos`. /// - /// See [`IdentityWallet::top_up_from_addresses`] for the identity-side - /// semantics. Reconciliation failures are logged inside the seam - /// rather than propagated — Platform already accepted the top-up, and - /// a later sync reconciles. + /// The identity-side semantics are those of the crate-private + /// `IdentityWallet::top_up_from_addresses`. Reconciliation failures are + /// logged inside the seam rather than propagated — Platform already + /// accepted the top-up, and a later sync reconciles. /// /// The result stands only when its proof shows every input address at or /// past the nonce this top-up was signed with AND the identity balance