From fc16a19ecbae19248271716fb8ba811a68903bd3 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 14:50:42 +0200 Subject: [PATCH 01/20] feat(platform-wallet): plan a shielded spend with its exact fee and spend against the plan A shielded spend selects its notes at submit time and its fee grows with the number of notes selected, so a host could only show a fee for a fixed action count, which can be half of what the spend is charged. - plan_spend runs the spends' own select_notes_with_fee for a kind (transfer, unshield, withdrawal, identity top-up from the pool) and an exact amount or a sweep, and returns the selected nullifiers, the exact fee, the total debited and a digest. It only reads the store. - Each spend has a _with_plan variant: under the same lock that reserves the notes, before anything is marked pending, a fresh selection whose digest differs from the plan is refused with ShieldedPlanChanged. The existing spend signatures are unchanged. - FFI: platform_wallet_manager_shielded_plan_spend, _with_plan siblings of the four spend exports, and result code 77 ErrorShieldedPlanChanged (registry row added). Co-Authored-By: Claude Opus 5.5 --- .../ERROR_CODE_REGISTRY.md | 6 +- packages/rs-platform-wallet-ffi/src/error.rs | 11 + .../src/shielded_send.rs | 483 +++++++++++++++++- .../src/shielded_types.rs | 23 + packages/rs-platform-wallet/src/error.rs | 13 + .../src/wallet/platform_wallet.rs | 168 +++++- .../src/wallet/shielded/note_selection.rs | 396 ++++++++++++++ .../src/wallet/shielded/operations.rs | 393 +++++++++++++- 8 files changed, 1470 insertions(+), 23 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md index a5655430abd..1a5c97036ec 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,8 @@ 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 a +shielded spend plan that changed; 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 +193,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 | `ErrorShieldedPlanChanged` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedPlanChanged`: a shielded spend run against a plan (`platform_wallet_manager_shielded_plan_spend`, then a `_with_plan` transfer, unshield, withdraw or identity top-up export) selected different notes or a different fee than the plan, as the wallet's notes changed since. Nothing was reserved, built or broadcast; plan again and confirm the new fee. Mapped by the blanket conversion and kept by `map_spend_result`. Swift and Kotlin mirrors follow with the Swift wrapper of the plan | **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 fbd1b5b2b37..477417bfe7c 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -768,6 +768,14 @@ pub enum PlatformWalletFFIResultCode { /// [`Self::ErrorPrivateContactRequestPending`] (71). ErrorPublicContactRequestUnconfirmed = 76, + /// Maps `PlatformWalletError::ShieldedPlanChanged`: a shielded spend run + /// against a plan (`platform_wallet_manager_shielded_plan_spend`, then a + /// `_with_plan` spend export) selected different notes or a different fee + /// than the plan, as the wallet's notes changed since (a sync added or + /// spent one, or another spend reserved one). Nothing was reserved, built + /// or broadcast. Plan again and have the new fee confirmed. + ErrorShieldedPlanChanged = 77, + /// The named thing does not exist. /// /// Originally (and still mostly) the code for every `Option` returned as an @@ -1102,6 +1110,9 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::PlatformShieldCapacityExceeded { .. } => { PlatformWalletFFIResultCode::ErrorShieldedInsufficientBalance } + PlatformWalletError::ShieldedPlanChanged { .. } => { + PlatformWalletFFIResultCode::ErrorShieldedPlanChanged + } // The core-transaction sibling of the shielded pair above: the // do-not-retry signal must survive the boundary as a typed code // so hosts can distinguish it from a definitive rejection. diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 00161411428..53c290e858d 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -51,6 +51,9 @@ use dpp::shielded::{ use dpp::state_transition::public_key_in_creation::IdentityPublicKeyInCreation; use dpp::ProtocolError; use platform_wallet::wallet::asset_lock::AssetLockFunding; +use platform_wallet::wallet::shielded::note_selection::{ + ShieldedSpendAmount, ShieldedSpendKind, ShieldedSpendPlan, +}; use platform_wallet::wallet::shielded::CachedOrchardProver; use platform_wallet::PlatformWalletError; use rs_sdk_ffi::{ @@ -65,7 +68,9 @@ use crate::error::*; use crate::handle::*; use crate::identity_registration_with_signer::{decode_identity_pubkeys, IdentityPubkeyFFI}; use crate::runtime::{block_on_worker, runtime}; -use crate::shielded_types::{ShieldedIdentityDebitRecoveryRecordFFI, ShieldedShieldPreflightFFI}; +use crate::shielded_types::{ + ShieldedIdentityDebitRecoveryRecordFFI, ShieldedShieldPreflightFFI, ShieldedSpendPlanFFI, +}; use crate::types::read_identifier; use crate::unwrap_result_or_return; @@ -255,6 +260,117 @@ pub unsafe extern "C" fn platform_wallet_shielded_estimate_fee( } } +/// Map a spend `kind` byte, numbered as [`shielded_fee_formula`] numbers the +/// spends' fee kinds, to the spend it plans; `None` for any other byte. +fn shielded_spend_kind(kind: u8) -> Option { + match kind { + 0 => Some(ShieldedSpendKind::Transfer), + 1 => Some(ShieldedSpendKind::Unshield), + 2 => Some(ShieldedSpendKind::Withdrawal), + 4 => Some(ShieldedSpendKind::IdentityTopUp), + _ => None, + } +} + +impl From<&ShieldedSpendPlan> for ShieldedSpendPlanFFI { + fn from(plan: &ShieldedSpendPlan) -> Self { + Self { + kind: match plan.kind { + ShieldedSpendKind::Transfer => 0, + ShieldedSpendKind::Unshield => 1, + ShieldedSpendKind::Withdrawal => 2, + ShieldedSpendKind::IdentityTopUp => 4, + }, + amount: plan.amount, + fee: plan.fee, + total_input: plan.total_input, + total_debited: plan.total_debited(), + // A spend's notes are bounded far below u32::MAX by the transition's action cap. + note_count: u32::try_from(plan.note_count()).unwrap_or(u32::MAX), + digest: plan.digest, + } + } +} + +/// Read a 32-byte plan digest. +/// +/// # Safety +/// `digest` must point to 32 readable bytes. +unsafe fn read_plan_digest(digest: *const u8) -> [u8; 32] { + let mut out = [0u8; 32]; + std::ptr::copy_nonoverlapping(digest, out.as_mut_ptr(), 32); + out +} + +/// Plan a shielded spend from `account`'s notes before it is confirmed: the +/// notes the spend would select now and their exact fee, which grows with the +/// number of notes. Nothing is reserved or broadcast. +/// +/// `kind` numbers the spend as `platform_wallet_shielded_estimate_fee` does: +/// `0` transfer, `1` unshield, `2` withdrawal, `4` identity top-up (`3`, the +/// shield from an identity, spends no notes). With `sweep_all`, the spend +/// sends every spendable note minus the fee for all of them, and `amount` must +/// be `0`; otherwise it sends `amount` credits and the fee comes on top. +/// +/// Writes the plan to `out_plan`. Run it with the spend's `_with_plan` export +/// and the plan's `digest`, which refuses with `ErrorShieldedPlanChanged` +/// when the notes moved since. An unknown `kind`, or a sweep with an amount, +/// returns `ErrorInvalidParameter`; notes that cannot pay the amount and its +/// fee, or a zero amount, return `ErrorWalletOperation`, as the spends do. +/// +/// # Safety +/// - `wallet_id_bytes` must point to 32 readable bytes. +/// - `out_plan` must point to a writable `ShieldedSpendPlanFFI`. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_shielded_plan_spend( + handle: Handle, + wallet_id_bytes: *const u8, + account: u32, + kind: u8, + amount: u64, + sweep_all: bool, + out_plan: *mut ShieldedSpendPlanFFI, +) -> PlatformWalletFFIResult { + check_ptr!(wallet_id_bytes); + check_ptr!(out_plan); + + let Some(kind) = shielded_spend_kind(kind) else { + return PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + format!("unknown shielded spend kind {kind} (expected 0/1/2/4)"), + ); + }; + let amount = match (sweep_all, amount) { + (false, amount) => ShieldedSpendAmount::Exact(amount), + (true, 0) => ShieldedSpendAmount::Sweep, + (true, _) => { + return PlatformWalletFFIResult::err( + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "a sweep_all plan takes amount 0", + ); + } + }; + let mut wallet_id = [0u8; 32]; + std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); + + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(p) => p, + Err(result) => return result, + }; + let result = block_on_worker(async move { + wallet + .shielded_plan_spend(&coordinator, account, kind, amount) + .await + }); + match result { + Ok(plan) => { + *out_plan = ShieldedSpendPlanFFI::from(&plan); + PlatformWalletFFIResult::ok() + } + Err(e) => map_spend_result(Err(e), "shielded spend plan"), + } +} + /// Encode an optional host-supplied memo string into the on-chain /// 36-byte `DashMemo` layout via [`ShieldedMemo`]. /// @@ -323,6 +439,66 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_transfer( recipient_raw_43: *const u8, amount: u64, memo_text: *const c_char, +) -> PlatformWalletFFIResult { + shielded_transfer_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + recipient_raw_43, + amount, + memo_text, + None, + ) +} + +/// [`platform_wallet_manager_shielded_transfer`] against a plan from +/// [`platform_wallet_manager_shielded_plan_spend`]: when the wallet's notes no +/// longer select the plan `expected_plan_digest` names, the transfer is +/// refused with `ErrorShieldedPlanChanged` before anything is reserved, +/// built or broadcast. +/// +/// # Safety +/// As [`platform_wallet_manager_shielded_transfer`], and +/// `expected_plan_digest` must point to 32 readable bytes. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_shielded_transfer_with_plan( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + recipient_raw_43: *const u8, + amount: u64, + memo_text: *const c_char, + expected_plan_digest: *const u8, +) -> PlatformWalletFFIResult { + check_ptr!(expected_plan_digest); + shielded_transfer_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + recipient_raw_43, + amount, + memo_text, + Some(read_plan_digest(expected_plan_digest)), + ) +} + +/// Body of the transfer exports; `expected_plan` is the plan digest, if any. +/// +/// # Safety +/// Identical contract to [`platform_wallet_manager_shielded_transfer`]. +#[allow(clippy::too_many_arguments)] +unsafe fn shielded_transfer_inner( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + recipient_raw_43: *const u8, + amount: u64, + memo_text: *const c_char, + expected_plan: Option<[u8; 32]>, ) -> PlatformWalletFFIResult { check_ptr!(wallet_id_bytes); check_ptr!(mnemonic_resolver_handle); @@ -376,7 +552,7 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_transfer( let result = block_on_worker(async move { let prover = CachedOrchardProver::new(); let r = wallet - .shielded_transfer_to( + .shielded_transfer_to_with_plan( &coordinator, seed.as_ref(), account, @@ -384,6 +560,7 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_transfer( amount, memo, &prover, + expected_plan.as_ref(), ) .await; poke_sync_on_unconfirmed(&r, handle); @@ -421,6 +598,58 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_unshield( account: u32, to_platform_addr_cstr: *const c_char, amount: u64, +) -> PlatformWalletFFIResult { + shielded_unshield_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + to_platform_addr_cstr, + amount, + None, + ) +} + +/// [`platform_wallet_manager_shielded_unshield`] against a plan, refused as +/// [`platform_wallet_manager_shielded_transfer_with_plan`] is when it moved. +/// +/// # Safety +/// As [`platform_wallet_manager_shielded_unshield`], and +/// `expected_plan_digest` must point to 32 readable bytes. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_shielded_unshield_with_plan( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + to_platform_addr_cstr: *const c_char, + amount: u64, + expected_plan_digest: *const u8, +) -> PlatformWalletFFIResult { + check_ptr!(expected_plan_digest); + shielded_unshield_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + to_platform_addr_cstr, + amount, + Some(read_plan_digest(expected_plan_digest)), + ) +} + +/// Body of the unshield exports; `expected_plan` is the plan digest, if any. +/// +/// # Safety +/// Identical contract to [`platform_wallet_manager_shielded_unshield`]. +unsafe fn shielded_unshield_inner( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + to_platform_addr_cstr: *const c_char, + amount: u64, + expected_plan: Option<[u8; 32]>, ) -> PlatformWalletFFIResult { check_ptr!(wallet_id_bytes); check_ptr!(mnemonic_resolver_handle); @@ -454,13 +683,14 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_unshield( let result = block_on_worker(async move { let prover = CachedOrchardProver::new(); let r = wallet - .shielded_unshield_to( + .shielded_unshield_to_with_plan( &coordinator, seed.as_ref(), account, &to_addr_str, amount, &prover, + expected_plan.as_ref(), ) .await; poke_sync_on_unconfirmed(&r, handle); @@ -495,6 +725,64 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_withdraw( to_core_address_cstr: *const c_char, amount: u64, core_fee_per_byte: u32, +) -> PlatformWalletFFIResult { + shielded_withdraw_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + to_core_address_cstr, + amount, + core_fee_per_byte, + None, + ) +} + +/// [`platform_wallet_manager_shielded_withdraw`] against a plan, refused as +/// [`platform_wallet_manager_shielded_transfer_with_plan`] is when it moved. +/// +/// # Safety +/// As [`platform_wallet_manager_shielded_withdraw`], and +/// `expected_plan_digest` must point to 32 readable bytes. +#[no_mangle] +#[allow(clippy::too_many_arguments)] +pub unsafe extern "C" fn platform_wallet_manager_shielded_withdraw_with_plan( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + to_core_address_cstr: *const c_char, + amount: u64, + core_fee_per_byte: u32, + expected_plan_digest: *const u8, +) -> PlatformWalletFFIResult { + check_ptr!(expected_plan_digest); + shielded_withdraw_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + to_core_address_cstr, + amount, + core_fee_per_byte, + Some(read_plan_digest(expected_plan_digest)), + ) +} + +/// Body of the withdraw exports; `expected_plan` is the plan digest, if any. +/// +/// # Safety +/// Identical contract to [`platform_wallet_manager_shielded_withdraw`]. +#[allow(clippy::too_many_arguments)] +unsafe fn shielded_withdraw_inner( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + to_core_address_cstr: *const c_char, + amount: u64, + core_fee_per_byte: u32, + expected_plan: Option<[u8; 32]>, ) -> PlatformWalletFFIResult { check_ptr!(wallet_id_bytes); check_ptr!(mnemonic_resolver_handle); @@ -528,7 +816,7 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_withdraw( let result = block_on_worker(async move { let prover = CachedOrchardProver::new(); let r = wallet - .shielded_withdraw_to( + .shielded_withdraw_to_with_plan( &coordinator, seed.as_ref(), account, @@ -536,6 +824,7 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_withdraw( amount, core_fee_per_byte, &prover, + expected_plan.as_ref(), ) .await; poke_sync_on_unconfirmed(&r, handle); @@ -650,6 +939,9 @@ pub(crate) fn map_spend_result( | Err(e @ PlatformWalletError::Sdk(dash_sdk::Error::ProtocolVersionNotActive { .. })) => { e.into() } + // The notes moved since the spend was planned: nothing was reserved + // or built; the host plans again and confirms the new fee. + Err(e @ PlatformWalletError::ShieldedPlanChanged { .. }) => e.into(), // Retryable: the wallet couldn't build the spend against any // Platform-recorded anchor yet (its commitment tree is mid-block after // an index-chunk sync). Nothing was broadcast and the notes were @@ -1385,6 +1677,39 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_identity_top_up_from_p account, identity_id, amount, + None, + ) + }) +} + +/// [`platform_wallet_manager_shielded_identity_top_up_from_pool`] against a +/// plan, refused as [`platform_wallet_manager_shielded_transfer_with_plan`] +/// is when it moved. +/// +/// # Safety +/// As [`platform_wallet_manager_shielded_identity_top_up_from_pool`], and +/// `expected_plan_digest` must point to 32 readable bytes. +#[no_mangle] +pub unsafe extern "C" fn platform_wallet_manager_shielded_identity_top_up_from_pool_with_plan( + handle: Handle, + wallet_id_bytes: *const u8, + mnemonic_resolver_handle: *mut MnemonicResolverHandle, + account: u32, + identity_id: *const u8, + amount: u64, + expected_plan_digest: *const u8, +) -> PlatformWalletFFIResult { + check_ptr!(expected_plan_digest); + let expected_plan = read_plan_digest(expected_plan_digest); + catch_spend_panic("shielded identity top up from pool", || { + shielded_identity_top_up_from_pool_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + identity_id, + amount, + Some(expected_plan), ) }) } @@ -1401,6 +1726,7 @@ unsafe fn shielded_identity_top_up_from_pool_inner( account: u32, identity_id: *const u8, amount: u64, + expected_plan: Option<[u8; 32]>, ) -> PlatformWalletFFIResult { check_ptr!(wallet_id_bytes); check_ptr!(mnemonic_resolver_handle); @@ -1426,13 +1752,14 @@ unsafe fn shielded_identity_top_up_from_pool_inner( let result = block_on_worker(async move { let prover = CachedOrchardProver::new(); let r = wallet - .shielded_identity_top_up_from_pool( + .shielded_identity_top_up_from_pool_with_plan( &coordinator, seed.as_ref(), account, &identity_id, amount, &prover, + expected_plan.as_ref(), ) .await; poke_sync_on_unconfirmed(&r, handle); @@ -2861,6 +3188,152 @@ mod tests { } } + #[test] + fn should_reject_a_spend_plan_with_null_pointers_or_an_unknown_kind() { + unsafe { + let wallet_id = [0u8; 32]; + let mut out = ShieldedSpendPlanFFI::default(); + let plan = |wallet_id: *const u8, kind: u8, amount: u64, sweep: bool, out| { + platform_wallet_manager_shielded_plan_spend( + 0, wallet_id, 0, kind, amount, sweep, out, + ) + .code + }; + assert_eq!( + plan(std::ptr::null(), 0, 1, false, &mut out), + PlatformWalletFFIResultCode::ErrorNullPointer + ); + assert_eq!( + plan(wallet_id.as_ptr(), 0, 1, false, std::ptr::null_mut()), + PlatformWalletFFIResultCode::ErrorNullPointer + ); + // Kind 3 is the shield from an identity, which spends no notes. + for kind in [3, 5, 255] { + assert_eq!( + plan(wallet_id.as_ptr(), kind, 1, false, &mut out), + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "kind {kind}" + ); + } + assert_eq!( + plan(wallet_id.as_ptr(), 0, 1, true, &mut out), + PlatformWalletFFIResultCode::ErrorInvalidParameter, + "a sweep names no amount" + ); + assert_eq!( + plan(wallet_id.as_ptr(), 0, 1, false, &mut out), + PlatformWalletFFIResultCode::ErrorInvalidHandle + ); + assert_eq!(out, ShieldedSpendPlanFFI::default(), "nothing written"); + } + } + + #[test] + fn should_marshal_a_spend_plan_with_the_fee_kind_numbering() { + for (kind, byte) in [ + (ShieldedSpendKind::Transfer, 0), + (ShieldedSpendKind::Unshield, 1), + (ShieldedSpendKind::Withdrawal, 2), + (ShieldedSpendKind::IdentityTopUp, 4), + ] { + assert_eq!(shielded_spend_kind(byte), Some(kind)); + let plan = ShieldedSpendPlan { + kind, + amount: 10, + fee: 3, + total_input: 20, + nullifiers: vec![[1; 32], [2; 32]], + digest: [9; 32], + }; + assert_eq!( + ShieldedSpendPlanFFI::from(&plan), + ShieldedSpendPlanFFI { + kind: byte, + amount: 10, + fee: 3, + total_input: 20, + total_debited: 13, + note_count: 2, + digest: [9; 32], + } + ); + } + } + + #[test] + fn should_reject_a_plan_spend_without_its_digest() { + unsafe { + let wallet_id = [0u8; 32]; + let bytes = [0u8; 43]; + let text = c"x"; + let resolver = std::ptr::NonNull::::dangling().as_ptr(); + let codes = [ + platform_wallet_manager_shielded_transfer_with_plan( + 0, + wallet_id.as_ptr(), + resolver, + 0, + bytes.as_ptr(), + 1, + std::ptr::null(), + std::ptr::null(), + ) + .code, + platform_wallet_manager_shielded_unshield_with_plan( + 0, + wallet_id.as_ptr(), + resolver, + 0, + text.as_ptr(), + 1, + std::ptr::null(), + ) + .code, + platform_wallet_manager_shielded_withdraw_with_plan( + 0, + wallet_id.as_ptr(), + resolver, + 0, + text.as_ptr(), + 1, + 1, + std::ptr::null(), + ) + .code, + platform_wallet_manager_shielded_identity_top_up_from_pool_with_plan( + 0, + wallet_id.as_ptr(), + resolver, + 0, + bytes.as_ptr(), + 1, + std::ptr::null(), + ) + .code, + ]; + assert_eq!(codes, [PlatformWalletFFIResultCode::ErrorNullPointer; 4]); + } + } + + #[test] + fn should_keep_a_changed_plan_at_its_own_code() { + let changed = || PlatformWalletError::ShieldedPlanChanged { + fresh_fee: 225_000_000, + fresh_note_count: 5, + }; + let result = map_spend_result(Err(changed()), "shielded transfer"); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedPlanChanged + ); + assert_eq!(result.code as i32, 77); + assert!(message_of(&result).contains("plan the spend again")); + assert_eq!( + PlatformWalletFFIResult::from(changed()).code, + PlatformWalletFFIResultCode::ErrorShieldedPlanChanged + ); + } + #[test] fn shield_preflight_rejects_null_abi_pointers() { unsafe { diff --git a/packages/rs-platform-wallet-ffi/src/shielded_types.rs b/packages/rs-platform-wallet-ffi/src/shielded_types.rs index 156d25b352a..63c2a78eead 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_types.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_types.rs @@ -87,6 +87,29 @@ pub struct ShieldedShieldPreflightFFI { pub max_shieldable_credits: u64, } +/// A shielded spend planned ahead of the spend +/// (`platform_wallet_manager_shielded_plan_spend`): the notes it selects, by +/// count and digest, and their exact fee. All amounts are credits. +/// +/// `kind` is the spend's fee kind as `platform_wallet_shielded_estimate_fee` +/// numbers it: `0` transfer, `1` unshield, `2` withdrawal, `4` identity top-up. +/// Pass `digest` to the spend's `_with_plan` export to run exactly this plan. +#[repr(C)] +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct ShieldedSpendPlanFFI { + pub kind: u8, + /// What the recipient gets. + pub amount: u64, + /// The exact fee for the selected notes. + pub fee: u64, + /// The sum of the selected notes. + pub total_input: u64, + /// What leaves the pool: `amount + fee` (any rest returns as change). + pub total_debited: u64, + pub note_count: u32, + pub digest: [u8; 32], +} + /// Per-wallet outcome from a completed shielded sync pass. /// /// Mirrors diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index f9ed4a5b60f..071d1c9d6f5 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -1063,6 +1063,19 @@ pub enum PlatformWalletError { #[error("Insufficient shielded balance: available {available}, required {required}")] ShieldedInsufficientBalance { available: u64, required: u64 }, + /// A spend run against a `ShieldedSpendPlan` selected different notes, or a + /// different fee, than the plan: the wallet's notes changed since it was made (a sync + /// added or spent one, or another spend reserved one). Refused before any note was + /// reserved or anything built; plan again and confirm the new fee. + #[error( + "Shielded spend plan changed: the notes now select {fresh_note_count} notes for a fee \ + of {fresh_fee}; plan the spend again" + )] + ShieldedPlanChanged { + fresh_fee: u64, + fresh_note_count: usize, + }, + /// A Platform Payment-account shield cannot be represented from the /// wallet's deterministic address-input set at the requested amount. /// Distinct from [`ShieldedInsufficientBalance`](Self::ShieldedInsufficientBalance), diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index 0797bb46ca1..d15df075a30 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -1538,6 +1538,76 @@ impl PlatformWallet { amount: u64, memo: [u8; 36], prover: P, + ) -> Result<(), PlatformWalletError> { + self.shielded_transfer_to_with_plan( + coordinator, + seed, + account, + recipient_raw_43, + amount, + memo, + prover, + None, + ) + .await + } + + /// Plan a shielded spend of `kind` from `account`'s notes: the notes the + /// spend would select now, their exact fee, the amount and what leaves the + /// pool. Nothing is reserved. Pass the plan's + /// [`digest`](super::shielded::note_selection::ShieldedSpendPlan::digest) + /// to the spend's `_with_plan` variant (for example + /// [`shielded_transfer_to_with_plan`](Self::shielded_transfer_to_with_plan)) + /// to run exactly that selection, or have it refused with + /// [`PlatformWalletError::ShieldedPlanChanged`] when the notes moved. + #[cfg(feature = "shielded")] + pub async fn shielded_plan_spend( + &self, + coordinator: &Arc, + account: u32, + kind: super::shielded::note_selection::ShieldedSpendKind, + amount: super::shielded::note_selection::ShieldedSpendAmount, + ) -> Result { + let bound = self + .shielded_keys + .read() + .await + .as_ref() + .ok_or(PlatformWalletError::ShieldedNotBound)? + .contains_key(&account); + if !bound { + return Err(PlatformWalletError::ShieldedKeyDerivation(format!( + "shielded account {account} not bound" + ))); + } + super::shielded::operations::plan_spend( + &self.sdk, + coordinator.store(), + self.wallet_id, + account, + kind, + amount, + ) + .await + } + + /// [`shielded_transfer_to`](Self::shielded_transfer_to) against a plan + /// from [`shielded_plan_spend`](Self::shielded_plan_spend): with + /// `expected_plan`, a selection that no longer matches it is refused with + /// [`PlatformWalletError::ShieldedPlanChanged`] before anything is + /// reserved or built. + #[cfg(feature = "shielded")] + #[allow(clippy::too_many_arguments)] + pub async fn shielded_transfer_to_with_plan( + &self, + coordinator: &Arc, + seed: &[u8], + account: u32, + recipient_raw_43: &[u8; 43], + amount: u64, + memo: [u8; 36], + prover: P, + expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { let keyset = self.derive_spend_keyset(seed, account).await?; let recipient = Option::::from( @@ -1548,7 +1618,7 @@ impl PlatformWallet { "invalid Orchard payment address bytes".to_string(), ) })?; - super::shielded::operations::transfer( + super::shielded::operations::transfer_with_plan( &self.sdk, coordinator.store(), Some(&self.persister), @@ -1559,6 +1629,7 @@ impl PlatformWallet { amount, memo, &prover, + expected_plan, ) .await } @@ -1579,6 +1650,34 @@ impl PlatformWallet { to_platform_addr_bech32m: &str, amount: u64, prover: P, + ) -> Result<(), PlatformWalletError> { + self.shielded_unshield_to_with_plan( + coordinator, + seed, + account, + to_platform_addr_bech32m, + amount, + prover, + None, + ) + .await + } + + /// [`shielded_unshield_to`](Self::shielded_unshield_to) against a plan, + /// refused as + /// [`shielded_transfer_to_with_plan`](Self::shielded_transfer_to_with_plan) + /// is when it moved. + #[cfg(feature = "shielded")] + #[allow(clippy::too_many_arguments)] + pub async fn shielded_unshield_to_with_plan( + &self, + coordinator: &Arc, + seed: &[u8], + account: u32, + to_platform_addr_bech32m: &str, + amount: u64, + prover: P, + expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { let keyset = self.derive_spend_keyset(seed, account).await?; // The decoder is network-agnostic, so guard the recipient's HRP class @@ -1588,7 +1687,7 @@ impl PlatformWallet { .map_err(|e| { PlatformWalletError::ShieldedBuildError(format!("invalid platform address: {e}")) })?; - super::shielded::operations::unshield( + super::shielded::operations::unshield_with_plan( &self.sdk, coordinator.store(), Some(&self.persister), @@ -1598,6 +1697,7 @@ impl PlatformWallet { &to, amount, &prover, + expected_plan, ) .await } @@ -1617,6 +1717,36 @@ impl PlatformWallet { identity_id: &Identifier, amount: u64, prover: P, + ) -> Result, PlatformWalletError> { + self.shielded_identity_top_up_from_pool_with_plan( + coordinator, + seed, + account, + identity_id, + amount, + prover, + None, + ) + .await + } + + /// [`shielded_identity_top_up_from_pool`](Self::shielded_identity_top_up_from_pool) + /// against a plan, refused as + /// [`shielded_transfer_to_with_plan`](Self::shielded_transfer_to_with_plan) + /// is when it moved. + #[cfg(feature = "shielded")] + #[allow(clippy::too_many_arguments)] + pub async fn shielded_identity_top_up_from_pool_with_plan< + P: dpp::shielded::builder::OrchardProver, + >( + &self, + coordinator: &Arc, + seed: &[u8], + account: u32, + identity_id: &Identifier, + amount: u64, + prover: P, + expected_plan: Option<&[u8; 32]>, ) -> Result, PlatformWalletError> { // A zero amount must not queue behind a long-running shielded operation. ensure_positive_amount(amount)?; @@ -1641,6 +1771,7 @@ impl PlatformWallet { *identity_id, amount, &prover, + expected_plan, ) .await?; @@ -2122,6 +2253,36 @@ impl PlatformWallet { amount: u64, core_fee_per_byte: u32, prover: P, + ) -> Result<(), PlatformWalletError> { + self.shielded_withdraw_to_with_plan( + coordinator, + seed, + account, + to_core_address, + amount, + core_fee_per_byte, + prover, + None, + ) + .await + } + + /// [`shielded_withdraw_to`](Self::shielded_withdraw_to) against a plan, + /// refused as + /// [`shielded_transfer_to_with_plan`](Self::shielded_transfer_to_with_plan) + /// is when it moved. + #[cfg(feature = "shielded")] + #[allow(clippy::too_many_arguments)] + pub async fn shielded_withdraw_to_with_plan( + &self, + coordinator: &Arc, + seed: &[u8], + account: u32, + to_core_address: &str, + amount: u64, + core_fee_per_byte: u32, + prover: P, + expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { let keyset = self.derive_spend_keyset(seed, account).await?; let network = self.sdk.network; @@ -2136,7 +2297,7 @@ impl PlatformWallet { "core address network mismatch: {e}" )) })?; - super::shielded::operations::withdraw( + super::shielded::operations::withdraw_with_plan( &self.sdk, coordinator.store(), Some(&self.persister), @@ -2147,6 +2308,7 @@ impl PlatformWallet { amount, core_fee_per_byte, &prover, + expected_plan, ) .await } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs index 86f1b1fe593..f8a13c18166 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs @@ -15,6 +15,7 @@ use dpp::shielded::{ }; use dpp::version::PlatformVersion; use dpp::ProtocolError; +use sha2::{Digest, Sha256}; /// Which consensus fee formula the wallet must reserve notes against for a spend. /// @@ -224,6 +225,199 @@ pub fn select_notes_with_fee<'a>( Ok((selected, total, exact_fee)) } +/// The minimum Orchard action count of an amount-based spend: one spend plus the recipient +/// output, so a single note is still charged for two actions. +pub const SPEND_MIN_ACTIONS: usize = 2; + +/// An amount-based spend from the shielded pool, whose fee depends on the notes it selects. +/// +/// `IdentityCreateFromShieldedPool` is not one: its whole denomination leaves the pool and the +/// fee is metered from it at execution ([`select_notes_for_denomination`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShieldedSpendKind { + /// ShieldedTransfer to an Orchard address. + Transfer, + /// Unshield to a Platform address. + Unshield, + /// ShieldedWithdrawal to a Core address. + Withdrawal, + /// IdentityTopUpFromShieldedPool. + IdentityTopUp, +} + +impl ShieldedSpendKind { + /// The fee formula the spend reserves its notes against. + pub fn fee_kind(self) -> ShieldedFeeKind { + match self { + ShieldedSpendKind::Transfer => ShieldedFeeKind::Base, + ShieldedSpendKind::Unshield => ShieldedFeeKind::Unshield, + ShieldedSpendKind::Withdrawal => ShieldedFeeKind::Withdrawal, + ShieldedSpendKind::IdentityTopUp => ShieldedFeeKind::IdentityTopUp, + } + } + + fn tag(self) -> u8 { + match self { + ShieldedSpendKind::Transfer => 0, + ShieldedSpendKind::Unshield => 1, + ShieldedSpendKind::Withdrawal => 2, + ShieldedSpendKind::IdentityTopUp => 3, + } + } +} + +/// What a planned spend sends. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShieldedSpendAmount { + /// Exactly this many credits reach the recipient; the fee comes on top. + Exact(Credits), + /// Every spendable note: the recipient gets their sum minus the fee for all of them. + Sweep, +} + +/// A spend's note selection made ahead of the spend, with the exact fee it pays. +/// +/// Made by [`plan_spend`] from the same selection the spend runs; nothing is reserved. A spend +/// given the plan's [`digest`](Self::digest) refuses with +/// [`PlatformWalletError::ShieldedPlanChanged`] when its own selection differs. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ShieldedSpendPlan { + pub kind: ShieldedSpendKind, + /// What the recipient gets. + pub amount: Credits, + /// The exact fee for the selected notes. + pub fee: Credits, + /// The sum of the selected notes. + pub total_input: Credits, + /// The selected notes' nullifiers, sorted. + pub nullifiers: Vec<[u8; 32]>, + /// Commits to the kind, the amount, the fee and the selected notes. + pub digest: [u8; 32], +} + +impl ShieldedSpendPlan { + fn new( + kind: ShieldedSpendKind, + amount: Credits, + fee: Credits, + total_input: Credits, + mut nullifiers: Vec<[u8; 32]>, + ) -> Self { + nullifiers.sort_unstable(); + let mut hasher = Sha256::new(); + hasher.update(b"shielded-spend-plan"); + hasher.update([kind.tag()]); + hasher.update(amount.to_le_bytes()); + hasher.update(fee.to_le_bytes()); + for nullifier in &nullifiers { + hasher.update(nullifier); + } + Self { + kind, + amount, + fee, + total_input, + nullifiers, + digest: hasher.finalize().into(), + } + } + + /// How many notes the spend consumes. + pub fn note_count(&self) -> usize { + self.nullifiers.len() + } + + /// What leaves the pool: the amount plus the fee (any rest returns as change). + pub fn total_debited(&self) -> Credits { + // Selection guarantees `amount + fee <= total_input`, so this cannot overflow. + self.amount.saturating_add(self.fee) + } +} + +/// Plan a `kind` spend of `amount` from `unspent`: the notes the spend would select +/// ([`select_notes_with_fee`] at [`SPEND_MIN_ACTIONS`]) and their exact fee. +/// +/// A [`ShieldedSpendAmount::Sweep`] sends the sum of every spendable note minus the fee for all +/// of them. +pub fn plan_spend( + unspent: &[ShieldedNote], + kind: ShieldedSpendKind, + amount: ShieldedSpendAmount, + platform_version: &PlatformVersion, +) -> Result { + let fee_kind = kind.fee_kind(); + let amount = match amount { + ShieldedSpendAmount::Exact(amount) => amount, + ShieldedSpendAmount::Sweep => { + let spendable: Vec<&ShieldedNote> = unspent.iter().filter(|n| !n.is_spent).collect(); + if spendable.is_empty() { + return Err(PlatformWalletError::ShieldedNoUnspentNotes); + } + let balance = spendable + .iter() + .try_fold(0u64, |acc, n| acc.checked_add(n.value)) + .ok_or_else(|| { + PlatformWalletError::ShieldedBuildError( + "shielded note values sum overflows u64".to_string(), + ) + })?; + let fee = fee_kind + .compute(spendable.len().max(SPEND_MIN_ACTIONS), platform_version) + .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; + match balance.checked_sub(fee) { + Some(amount) if amount > 0 => amount, + _ => { + return Err(PlatformWalletError::ShieldedInsufficientBalance { + available: balance, + required: fee.saturating_add(1), + }) + } + } + } + }; + ensure_positive_amount(amount)?; + let (selected, total_input, fee) = select_notes_with_fee( + unspent, + amount, + SPEND_MIN_ACTIONS, + fee_kind, + platform_version, + )?; + Ok(ShieldedSpendPlan::new( + kind, + amount, + fee, + total_input, + selected.iter().map(|n| n.nullifier).collect(), + )) +} + +/// Refuse a spend whose fresh selection (`selected`, `total_input`, `fee` for `kind` and +/// `amount`) does not match the plan whose digest is `expected`. +pub(crate) fn ensure_plan_holds( + expected: &[u8; 32], + kind: ShieldedSpendKind, + amount: Credits, + fee: Credits, + total_input: Credits, + selected: &[ShieldedNote], +) -> Result<(), PlatformWalletError> { + let fresh = ShieldedSpendPlan::new( + kind, + amount, + fee, + total_input, + selected.iter().map(|n| n.nullifier).collect(), + ); + if fresh.digest != *expected { + return Err(PlatformWalletError::ShieldedPlanChanged { + fresh_fee: fresh.fee, + fresh_note_count: fresh.note_count(), + }); + } + Ok(()) +} + /// Reject a zero spend `amount`. Lock-free, so callers can run it before taking the store lock /// or `shield_guard`. pub(crate) fn ensure_positive_amount(amount: u64) -> Result<(), PlatformWalletError> { @@ -634,4 +828,206 @@ mod tests { Err(PlatformWalletError::ShieldedInsufficientBalance { .. }) )); } + + /// A note worth 1 DASH, so the fee never decides how many notes an amount needs. + const NOTE: u64 = 100_000_000_000; + + /// An amount that needs five notes is planned at the fee for five actions, not two, and + /// lists exactly those five notes. + #[test] + fn should_plan_a_five_note_spend_at_the_five_action_fee() { + let platform_version = PlatformVersion::latest(); + let notes: Vec = (0..6).map(|i| test_note(NOTE, i)).collect(); + let amount = 4 * NOTE + 1; + + let plan = plan_spend( + ¬es, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Exact(amount), + platform_version, + ) + .expect("five notes cover the amount"); + + let five_action_fee = compute_minimum_shielded_fee(5, platform_version).expect("fee"); + assert_eq!(plan.fee, five_action_fee); + assert!(plan.fee > compute_minimum_shielded_fee(2, platform_version).expect("fee")); + assert_eq!(plan.note_count(), 5); + assert_eq!(plan.amount, amount); + assert_eq!(plan.total_input, 5 * NOTE); + assert_eq!(plan.total_debited(), amount + five_action_fee); + // The plan is the spend's own selection. + let (selected, total, fee) = select_notes_with_fee( + ¬es, + amount, + SPEND_MIN_ACTIONS, + ShieldedFeeKind::Base, + platform_version, + ) + .expect("selects"); + let mut nullifiers: Vec<[u8; 32]> = selected.iter().map(|n| n.nullifier).collect(); + nullifiers.sort_unstable(); + assert_eq!( + (plan.nullifiers, plan.total_input, plan.fee), + (nullifiers, total, fee) + ); + } + + /// Each kind plans against its own fee formula. + #[test] + fn should_plan_each_kind_against_its_spend_fee() { + let platform_version = PlatformVersion::latest(); + let notes = vec![test_note(NOTE, 0)]; + for (kind, fee) in [ + ( + ShieldedSpendKind::Transfer, + compute_minimum_shielded_fee(2, platform_version), + ), + ( + ShieldedSpendKind::Unshield, + compute_shielded_unshield_fee(2, platform_version), + ), + ( + ShieldedSpendKind::Withdrawal, + compute_shielded_withdrawal_fee(2, platform_version), + ), + ( + ShieldedSpendKind::IdentityTopUp, + compute_shielded_identity_top_up_fee(2, platform_version), + ), + ] { + let plan = plan_spend( + ¬es, + kind, + ShieldedSpendAmount::Exact(1), + platform_version, + ) + .expect("one note covers it"); + assert_eq!(plan.fee, fee.expect("fee"), "{kind:?}"); + assert_eq!((plan.kind, plan.note_count()), (kind, 1)); + } + } + + /// A sweep sends the balance minus the fee for every spendable note. + #[test] + fn should_plan_a_sweep_as_the_balance_minus_the_fee_for_every_note() { + let platform_version = PlatformVersion::latest(); + let mut notes: Vec = (0..3).map(|i| test_note(NOTE + i, i)).collect(); + let mut spent = test_note(NOTE, 9); + spent.is_spent = true; + notes.push(spent); + let balance = 3 * NOTE + 3; + + let plan = plan_spend( + ¬es, + ShieldedSpendKind::Unshield, + ShieldedSpendAmount::Sweep, + platform_version, + ) + .expect("the notes cover their own fee"); + + let fee = compute_shielded_unshield_fee(3, platform_version).expect("fee"); + assert_eq!(plan.amount, balance - fee); + assert_eq!(plan.fee, fee); + assert_eq!(plan.total_debited(), balance); + assert_eq!(plan.note_count(), 3); + } + + /// Notes worth no more than their fee cannot be swept. + #[test] + fn should_refuse_a_sweep_the_fee_eats() { + let platform_version = PlatformVersion::latest(); + let fee = compute_minimum_shielded_fee(2, platform_version).expect("fee"); + let notes = vec![test_note(fee, 0)]; + assert!(matches!( + plan_spend( + ¬es, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Sweep, + platform_version, + ), + Err(PlatformWalletError::ShieldedInsufficientBalance { .. }) + )); + assert!(matches!( + plan_spend( + &[], + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Sweep, + platform_version, + ), + Err(PlatformWalletError::ShieldedNoUnspentNotes) + )); + } + + /// A zero amount is refused as the spend refuses it. + #[test] + fn should_refuse_to_plan_a_zero_amount() { + let notes = vec![test_note(NOTE, 0)]; + assert!(matches!( + plan_spend( + ¬es, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Exact(0), + PlatformVersion::latest(), + ), + Err(PlatformWalletError::ShieldedBuildError(_)) + )); + } + + /// The digest changes with the selection, and the plan check refuses a selection that + /// moved while accepting the one planned. + #[test] + fn should_hold_a_plan_only_for_its_own_selection() { + let platform_version = PlatformVersion::latest(); + let kind = ShieldedSpendKind::Transfer; + let notes: Vec = (0..3).map(|i| test_note(NOTE, i)).collect(); + let amount = ShieldedSpendAmount::Exact(2 * NOTE); + let plan = plan_spend(¬es, kind, amount, platform_version).expect("plans"); + let selected = |notes: &[ShieldedNote]| -> (Vec, u64, u64) { + let (refs, total, fee) = + select_notes_with_fee(notes, 2 * NOTE, 2, kind.fee_kind(), platform_version) + .expect("selects"); + (refs.into_iter().cloned().collect(), total, fee) + }; + + let (same, total, fee) = selected(¬es); + ensure_plan_holds(&plan.digest, kind, 2 * NOTE, fee, total, &same) + .expect("an unchanged selection holds"); + + // A larger note arrives: one note now covers it, at a different fee. + let mut grown = notes.clone(); + grown.push(test_note(10 * NOTE, 7)); + let (moved, total, fee) = selected(&grown); + let err = ensure_plan_holds(&plan.digest, kind, 2 * NOTE, fee, total, &moved) + .expect_err("a moved selection must not hold"); + assert!( + matches!( + err, + PlatformWalletError::ShieldedPlanChanged { + fresh_note_count: 1, + .. + } + ), + "got {err:?}" + ); + assert_ne!( + plan_spend(&grown, kind, amount, platform_version) + .expect("plans") + .digest, + plan.digest + ); + // The same notes for another kind or amount are another plan. + let err = ensure_plan_holds( + &plan.digest, + kind, + 2 * NOTE - 1, + plan.fee, + plan.total_input, + &same, + ) + .expect_err("another amount"); + assert!(matches!( + err, + PlatformWalletError::ShieldedPlanChanged { .. } + )); + } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index c213918b251..937116323bd 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -25,8 +25,9 @@ use super::activity_recorder::{ }; use super::keys::{AccountViewingKeys, OrchardKeySet}; use super::note_selection::{ - ensure_allowed_denomination, ensure_positive_amount, select_notes_for_denomination, - select_notes_with_fee, ShieldedFeeKind, + ensure_allowed_denomination, ensure_plan_holds, ensure_positive_amount, + select_notes_for_denomination, select_notes_with_fee, ShieldedFeeKind, ShieldedSpendAmount, + ShieldedSpendKind, ShieldedSpendPlan, SPEND_MIN_ACTIONS, }; use super::store::{ PendingRedrive, PrivateContactPayment, PrivatePaymentEntry, ShieldedNote, ShieldedStore, @@ -1514,6 +1515,7 @@ pub async fn identity_top_up_from_pool( identity_id, amount, prover, + None, ) .await .map(|(result, _)| result) @@ -1533,13 +1535,21 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< identity_id: Identifier, amount: u64, prover: &P, + expected_plan: Option<&[u8; 32]>, ) -> Result<(Option, ResponseMetadata), PlatformWalletError> { let views = keys.viewing_keys(); let change_addr = default_orchard_address(&views)?; let id = SubwalletId::new(wallet_id, account); - let (selected_notes, total_input, exact_fee, mut reservation) = - reserve_unspent_notes(sdk, store, id, amount, 2, ShieldedFeeKind::IdentityTopUp).await?; + let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( + sdk, + store, + id, + amount, + ShieldedSpendKind::IdentityTopUp, + expected_plan, + ) + .await?; info!( account, @@ -2260,6 +2270,26 @@ pub async fn unshield( to_address: &PlatformAddress, amount: u64, prover: &P, +) -> Result<(), PlatformWalletError> { + unshield_with_plan( + sdk, store, persister, wallet_id, keys, account, to_address, amount, prover, None, + ) + .await +} + +/// [`unshield`] against a plan, refused as [`transfer_with_plan`] is when it moved. +#[allow(clippy::too_many_arguments)] +pub async fn unshield_with_plan( + sdk: &Arc, + store: &Arc>, + persister: Option<&WalletPersister>, + wallet_id: WalletId, + keys: &OrchardKeySet, + account: u32, + to_address: &PlatformAddress, + amount: u64, + prover: &P, + expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { let views = keys.viewing_keys(); let change_addr = default_orchard_address(&views)?; @@ -2273,8 +2303,15 @@ pub async fn unshield( // reserve against `ShieldedFeeKind::Unshield` — reserving the base fee here would under-fund the // address-write cost and the builder would reject the spend (and the `fee_used == exact_fee` // debug assert below would fire). - let (selected_notes, total_input, exact_fee, mut reservation) = - reserve_unspent_notes(sdk, store, id, amount, 2, ShieldedFeeKind::Unshield).await?; + let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( + sdk, + store, + id, + amount, + ShieldedSpendKind::Unshield, + expected_plan, + ) + .await?; info!( account, @@ -2445,6 +2482,29 @@ pub async fn transfer( amount: u64, memo: [u8; 36], prover: &P, +) -> Result<(), PlatformWalletError> { + transfer_with_plan( + sdk, store, persister, wallet_id, keys, account, to_address, amount, memo, prover, None, + ) + .await +} + +/// [`transfer`], refused with [`PlatformWalletError::ShieldedPlanChanged`] before anything is +/// reserved or built when `expected_plan` is given and its notes no longer select the +/// [`ShieldedSpendPlan::digest`] it names ([`plan_spend`]). +#[allow(clippy::too_many_arguments)] +pub async fn transfer_with_plan( + sdk: &Arc, + store: &Arc>, + persister: Option<&WalletPersister>, + wallet_id: WalletId, + keys: &OrchardKeySet, + account: u32, + to_address: &PaymentAddress, + amount: u64, + memo: [u8; 36], + prover: &P, + expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { let recipient_addr = payment_address_to_orchard(to_address)?; let views = keys.viewing_keys(); @@ -2453,8 +2513,15 @@ pub async fn transfer( // ShieldedTransfer is carved with the base `compute_minimum_shielded_fee`, so reserve // against `ShieldedFeeKind::Base`. - let (selected_notes, total_input, exact_fee, mut reservation) = - reserve_unspent_notes(sdk, store, id, amount, 2, ShieldedFeeKind::Base).await?; + let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( + sdk, + store, + id, + amount, + ShieldedSpendKind::Transfer, + expected_plan, + ) + .await?; info!( account, @@ -2599,6 +2666,37 @@ pub async fn withdraw( amount: u64, core_fee_per_byte: u32, prover: &P, +) -> Result<(), PlatformWalletError> { + withdraw_with_plan( + sdk, + store, + persister, + wallet_id, + keys, + account, + to_address, + amount, + core_fee_per_byte, + prover, + None, + ) + .await +} + +/// [`withdraw`] against a plan, refused as [`transfer_with_plan`] is when it moved. +#[allow(clippy::too_many_arguments)] +pub async fn withdraw_with_plan( + sdk: &Arc, + store: &Arc>, + persister: Option<&WalletPersister>, + wallet_id: WalletId, + keys: &OrchardKeySet, + account: u32, + to_address: &dashcore::Address, + amount: u64, + core_fee_per_byte: u32, + prover: &P, + expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { let views = keys.viewing_keys(); let change_addr = default_orchard_address(&views)?; @@ -2613,8 +2711,15 @@ pub async fn withdraw( // `ShieldedFeeKind::Withdrawal` — reserving the base fee here would under-fund the document // cost and the builder would reject the spend (and the `fee_used == exact_fee` debug assert // below would fire). - let (selected_notes, total_input, exact_fee, mut reservation) = - reserve_unspent_notes(sdk, store, id, amount, 2, ShieldedFeeKind::Withdrawal).await?; + let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( + sdk, + store, + id, + amount, + ShieldedSpendKind::Withdrawal, + expected_plan, + ) + .await?; info!( account, @@ -3503,17 +3608,48 @@ async fn mark_notes_spent( /// (on failure); until the notes are handed over /// ([`NoteReservation::hand_over`]), the returned guard releases them when /// the spend is dropped. +/// +/// With `expected_plan`, a selection that does not match that [`ShieldedSpendPlan::digest`] +/// is refused with [`PlatformWalletError::ShieldedPlanChanged`] before any note is reserved. async fn reserve_unspent_notes( sdk: &Arc, store: &Arc>, id: SubwalletId, amount: u64, - outputs: usize, - fee_kind: ShieldedFeeKind, + kind: ShieldedSpendKind, + expected_plan: Option<&[u8; 32]>, ) -> Result<(Vec, u64, u64, NoteReservation), PlatformWalletError> { // All amount-based spends reject zero before waiting on a concurrent sync's store lock. ensure_positive_amount(amount)?; - reserve_notes_covering(sdk, store, id, amount, outputs, fee_kind).await + reserve_notes_matching( + sdk, + store, + id, + amount, + SPEND_MIN_ACTIONS, + kind.fee_kind(), + expected_plan.map(|digest| (kind, digest)), + ) + .await +} + +/// Plan a `kind` spend of `amount` from `account`'s notes: the notes the spend would select +/// now and their exact fee ([`note_selection::plan_spend`](super::note_selection::plan_spend)). +/// Reads the store only; nothing is reserved. +pub async fn plan_spend( + sdk: &Arc, + store: &Arc>, + wallet_id: WalletId, + account: u32, + kind: ShieldedSpendKind, + amount: ShieldedSpendAmount, +) -> Result { + let unspent = store + .read() + .await + .get_unspent_notes(SubwalletId::new(wallet_id, account)) + .map_err(|e| PlatformWalletError::ShieldedStoreError(e.to_string()))?; + super::note_selection::plan_spend(&unspent, kind, amount, sdk.version()) } /// Select and reserve, in one write-locked critical section, notes covering @@ -3529,6 +3665,21 @@ async fn reserve_notes_covering( amount: u64, outputs: usize, fee_kind: ShieldedFeeKind, +) -> Result<(Vec, u64, u64, NoteReservation), PlatformWalletError> { + reserve_notes_matching(sdk, store, id, amount, outputs, fee_kind, None).await +} + +/// [`reserve_notes_covering`], refusing with [`PlatformWalletError::ShieldedPlanChanged`], +/// before any note is reserved, a selection that does not match `expected_plan`: the plan +/// digest of a spend of that kind. +async fn reserve_notes_matching( + sdk: &Arc, + store: &Arc>, + id: SubwalletId, + amount: u64, + outputs: usize, + fee_kind: ShieldedFeeKind, + expected_plan: Option<(ShieldedSpendKind, &[u8; 32])>, ) -> Result<(Vec, u64, u64, NoteReservation), PlatformWalletError> { let mut guard = store.write().await; let unspent = guard @@ -3536,6 +3687,9 @@ async fn reserve_notes_covering( .map_err(|e| PlatformWalletError::ShieldedStoreError(e.to_string()))?; let (selected, total_input, exact_fee) = select_notes_with_fee(&unspent, amount, outputs, fee_kind, sdk.version())?.into_owned(); + if let Some((kind, expected)) = expected_plan { + ensure_plan_holds(expected, kind, amount, exact_fee, total_input, &selected)?; + } let reservation = mark_notes_pending(&mut *guard, store, id, &selected)?; Ok((selected, total_input, exact_fee, reservation)) } @@ -8173,3 +8327,216 @@ mod select_recorded_spends_tests { } } } + +#[cfg(test)] +mod spend_plan_tests { + use super::*; + use crate::wallet::shielded::store::InMemoryShieldedStore; + use dashcore::Network; + use dpp::shielded::compute_minimum_shielded_fee; + use dpp::version::PlatformVersion; + use grovedb_commitment_tree::ProvingKey; + + /// A note worth 1 DASH, so the fee never decides how many notes an amount needs. + const NOTE: u64 = 100_000_000_000; + const WALLET_ID: WalletId = [0x71; 32]; + const ID: SubwalletId = SubwalletId { + wallet_id: WALLET_ID, + account_index: 0, + }; + + struct UnreachableProver; + impl OrchardProver for UnreachableProver { + fn proving_key(&self) -> &ProvingKey { + panic!("nothing is proved") + } + } + + fn note(position: u8, value: u64) -> ShieldedNote { + ShieldedNote { + position: position.into(), + cmx: [position; 32], + nullifier: [position; 32], + block_height: 1, + is_spent: false, + value, + note_data: vec![], + } + } + + fn sdk() -> Arc { + Arc::new( + dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::latest()) + .build() + .expect("a mock SDK"), + ) + } + + async fn store_with(notes: &[ShieldedNote]) -> Arc> { + let store = Arc::new(RwLock::new(InMemoryShieldedStore::new())); + for note in notes { + store.write().await.save_note(ID, note).expect("a note"); + } + store + } + + async fn unspent(store: &Arc>) -> usize { + store + .read() + .await + .get_unspent_notes(ID) + .expect("notes") + .len() + } + + async fn plan(store: &Arc>, amount: u64) -> ShieldedSpendPlan { + plan_spend( + &sdk(), + store, + WALLET_ID, + 0, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Exact(amount), + ) + .await + .expect("plans") + } + + /// Planning an amount that needs five notes prices five actions and reserves nothing. + #[tokio::test] + async fn should_plan_five_notes_at_their_fee_without_reserving_them() { + let store = store_with(&(0..6).map(|i| note(i, NOTE)).collect::>()).await; + + let plan = plan(&store, 4 * NOTE + 1).await; + + assert_eq!(plan.note_count(), 5); + assert_eq!( + plan.fee, + compute_minimum_shielded_fee(5, PlatformVersion::latest()).expect("fee") + ); + assert_eq!(unspent(&store).await, 6, "a plan reserves nothing"); + } + + /// A spend whose notes did not move since the plan reserves exactly the planned notes. + #[tokio::test] + async fn should_reserve_the_planned_notes_when_nothing_moved() { + let store = store_with(&(0..6).map(|i| note(i, NOTE)).collect::>()).await; + let amount = 4 * NOTE + 1; + let plan = plan(&store, amount).await; + + let (selected, total_input, fee, reservation) = reserve_unspent_notes( + &sdk(), + &store, + ID, + amount, + ShieldedSpendKind::Transfer, + Some(&plan.digest), + ) + .await + .expect("the plan holds"); + + let mut nullifiers: Vec<[u8; 32]> = selected.iter().map(|n| n.nullifier).collect(); + nullifiers.sort_unstable(); + assert_eq!( + (nullifiers, total_input, fee), + (plan.nullifiers.clone(), plan.total_input, plan.fee) + ); + assert_eq!(unspent(&store).await, 1, "the planned notes are reserved"); + reservation.cancel().await; + } + + /// A note added or spent after the plan moves the selection: the spend is refused and + /// no note is left reserved. + #[tokio::test] + async fn should_refuse_a_plan_whose_notes_moved_and_reserve_nothing() { + let amount = 4 * NOTE + 1; + for change in ["added", "spent"] { + let store = store_with(&(0..6).map(|i| note(i, NOTE)).collect::>()).await; + let plan = plan(&store, amount).await; + match change { + "added" => store + .write() + .await + .save_note(ID, ¬e(9, 10 * NOTE)) + .expect("a note"), + _ => { + store + .write() + .await + .mark_spent(ID, &plan.nullifiers[0]) + .expect("spent"); + } + } + let before = unspent(&store).await; + + let refused = reserve_unspent_notes( + &sdk(), + &store, + ID, + amount, + ShieldedSpendKind::Transfer, + Some(&plan.digest), + ) + .await; + + assert!( + matches!( + refused, + Err(PlatformWalletError::ShieldedPlanChanged { .. }) + ), + "a note {change} after the plan must refuse it, got {:?}", + refused.map(|(selected, ..)| selected.len()) + ); + assert_eq!(unspent(&store).await, before, "nothing reserved ({change})"); + } + } + + /// The spend itself runs the check before it builds anything: a moved plan is refused + /// with its notes left spendable, and a plan that holds goes on to build (here refused + /// later by the mock's anchor fetch, never by the plan check). + #[tokio::test] + async fn should_run_a_transfer_against_its_plan_or_refuse_it_unbuilt() { + let keys = OrchardKeySet::from_seed(&[0x42; 64], Network::Testnet, 0).expect("keys"); + let store = store_with(&(0..3).map(|i| note(i, NOTE)).collect::>()).await; + let amount = NOTE; + let plan = plan(&store, amount).await; + let transfer = |expected: [u8; 32]| { + let (store, keys) = (Arc::clone(&store), &keys); + async move { + transfer_with_plan( + &sdk(), + &store, + None, + WALLET_ID, + keys, + 0, + &keys.default_address, + amount, + [0; 36], + &UnreachableProver, + Some(&expected), + ) + .await + } + }; + + let held = transfer(plan.digest).await; + assert!( + !matches!(held, Err(PlatformWalletError::ShieldedPlanChanged { .. })), + "a plan that holds proceeds, got {held:?}" + ); + + store + .write() + .await + .save_note(ID, ¬e(9, 10 * NOTE)) + .expect("a note"); + let moved = transfer(plan.digest).await; + assert!( + matches!(moved, Err(PlatformWalletError::ShieldedPlanChanged { .. })), + "got {moved:?}" + ); + assert_eq!(unspent(&store).await, 4, "nothing reserved"); + } +} From dc97f28e22b44177457a15fda8a9424d2ecc4066 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 15:07:28 +0200 Subject: [PATCH 02/20] feat(swift-sdk): plan a shielded spend and spend against the plan - shieldedPlanSpend(walletId:account:kind:amount:) returns a ShieldedSpendPlan (kind, amount, fee, totalInput, totalDebited, noteCount, digest) from platform_wallet_manager_shielded_plan_spend; amount is exact or sweepAll. - shieldedTransfer, shieldedUnshield, shieldedWithdraw and shieldedIdentityTopUpFromPool take an optional plan; with one they call the _with_plan export, after checking the digest is 32 bytes. Existing callers are unchanged. - Result code 77 maps to PlatformWalletError.shieldedPlanChanged in Swift and DashSdkError.PlatformWallet.ShieldedPlanChanged in Kotlin (no JNI binding); the registry row lists both mirrors. The parity manifest records shielded.spend_plan, Kotlin unsupported. Co-Authored-By: Claude Opus 5.5 --- docs/sdk/sdk-parity-manifest.json | 74 +++++++ packages/kotlin-sdk/PARITY_SUMMARY.md | 15 +- .../dashsdk/errors/DashSdkError.kt | 12 ++ .../dashsdk/errors/DashSdkErrorTest.kt | 16 ++ .../ERROR_CODE_REGISTRY.md | 2 +- .../PlatformWalletManagerShieldedSync.swift | 193 ++++++++++++++++-- .../PlatformWallet/PlatformWalletResult.swift | 15 +- .../ErrorHandlingTests.swift | 16 ++ .../ShieldedSpendPlanTests.swift | 174 ++++++++++++++++ 9 files changed, 490 insertions(+), 27 deletions(-) create mode 100644 packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index addcb451cca..68eb3483c10 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -57,8 +57,13 @@ "platform_wallet_manager_persistence_capabilities": "packages/rs-platform-wallet-ffi/src/manager.rs", "platform_wallet_manager_send_private_contact_request": "packages/rs-platform-wallet-ffi/src/private_contact_request.rs", "platform_wallet_manager_shielded_fund_from_wallet_drain": "packages/rs-platform-wallet-ffi/src/shielded_wallet_drain.rs", + "platform_wallet_manager_shielded_identity_top_up_from_pool_with_plan": "packages/rs-platform-wallet-ffi/src/shielded_send.rs", + "platform_wallet_manager_shielded_plan_spend": "packages/rs-platform-wallet-ffi/src/shielded_send.rs", + "platform_wallet_manager_shielded_transfer_with_plan": "packages/rs-platform-wallet-ffi/src/shielded_send.rs", + "platform_wallet_manager_shielded_unshield_with_plan": "packages/rs-platform-wallet-ffi/src/shielded_send.rs", "platform_wallet_manager_shielded_wallet_drain_preview": "packages/rs-platform-wallet-ffi/src/shielded_wallet_drain.rs", "platform_wallet_manager_shielded_wallet_drain_status": "packages/rs-platform-wallet-ffi/src/shielded_wallet_drain.rs", + "platform_wallet_manager_shielded_withdraw_with_plan": "packages/rs-platform-wallet-ffi/src/shielded_send.rs", "platform_wallet_manager_spv_rescan_filters": "packages/rs-platform-wallet-ffi/src/spv.rs", "platform_wallet_manager_sync_fault_detected": "packages/rs-platform-wallet-ffi/src/manager.rs", "platform_wallet_resume_identity_with_existing_asset_lock_signer": "packages/rs-platform-wallet-ffi/src/identity_registration_funded_with_signer.rs", @@ -1974,6 +1979,75 @@ "covers_restart": false } ] + }, + { + "id": "shielded.spend_plan", + "title": "Plan a shielded spend with its exact fee and spend against that plan (code 77)", + "area": "correctness", + "shared_apis": [ + "platform_wallet_manager_shielded_plan_spend", + "platform_wallet_manager_shielded_transfer_with_plan", + "platform_wallet_manager_shielded_unshield_with_plan", + "platform_wallet_manager_shielded_withdraw_with_plan", + "platform_wallet_manager_shielded_identity_top_up_from_pool_with_plan" + ], + "required_persistence_capabilities": [], + "hosts": { + "swift": { + "sdk": "supported", + "example_app": "unsupported", + "restart": "not_applicable", + "reason": "PlatformWalletManager.shieldedPlanSpend returns a ShieldedSpendPlan (kind, amount, exact fee, total input and debited, note count, digest) for an exact amount or a sweep, and shieldedTransfer, shieldedUnshield, shieldedWithdraw and shieldedIdentityTopUpFromPool take an optional plan whose digest goes to the _with_plan export; code 77 is typed as PlatformWalletError.shieldedPlanChanged (ErrorHandlingTests pin). A plan is read-only, so there is nothing to resume after a restart. SwiftExampleApp does not plan its shielded spends." + }, + "kotlin": { + "sdk": "unsupported", + "example_app": "unsupported", + "restart": "not_applicable", + "reason": "Code 77 maps to DashSdkError.PlatformWallet.ShieldedPlanChanged (DashSdkErrorTest), but no JNI wrapper plans a shielded spend or spends against a plan." + } + }, + "verification": [ + { + "host": "swift", + "kind": "unit", + "file": "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift", + "id": "testShouldDecodeEveryFieldOfThePlan", + "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -sdk iphonesimulator -destination \"platform=iOS Simulator,name=iPhone 17\" ARCHS=arm64 -only-testing:SwiftDashSDKTests/ShieldedSpendPlanTests", + "covers_restart": false + }, + { + "host": "swift", + "kind": "unit", + "file": "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift", + "id": "testShouldPassAPlanToEverySpendsFFI", + "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -sdk iphonesimulator -destination \"platform=iOS Simulator,name=iPhone 17\" ARCHS=arm64 -only-testing:SwiftDashSDKTests/ShieldedSpendPlanTests", + "covers_restart": false + }, + { + "host": "swift", + "kind": "unit", + "file": "packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift", + "id": "testShouldReportAChangedShieldedPlanByItsOwnCode", + "command": "cd packages/swift-sdk && xcodebuild test -scheme SwiftDashSDK -sdk iphonesimulator -destination \"platform=iOS Simulator,name=iPhone 17\" ARCHS=arm64 -only-testing:SwiftDashSDKTests/ErrorHandlingTests", + "covers_restart": false + }, + { + "host": "shared", + "kind": "unit", + "file": "packages/rs-platform-wallet/src/wallet/shielded/operations.rs", + "id": "should_refuse_a_plan_whose_notes_moved_and_reserve_nothing", + "command": "cargo test -p platform-wallet --features shielded --lib should_refuse_a_plan_whose_notes_moved_and_reserve_nothing", + "covers_restart": false + }, + { + "host": "shared", + "kind": "unit", + "file": "packages/rs-platform-wallet-ffi/src/shielded_send.rs", + "id": "should_reject_a_spend_plan_with_null_pointers_or_an_unknown_kind", + "command": "cargo test -p platform-wallet-ffi --features platform-wallet-ffi/shielded --lib should_reject_a_spend_plan_with_null_pointers_or_an_unknown_kind", + "covers_restart": false + } + ] } ] } diff --git a/packages/kotlin-sdk/PARITY_SUMMARY.md b/packages/kotlin-sdk/PARITY_SUMMARY.md index 7bc14e553d1..141c4844492 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 @@ -53,6 +53,7 @@ Capabilities tracked: **29** | `persistence.pending_identity_key_repair` | unsupported / unsupported / not_applicable | supported / not-applicable / tested | | `errors.signing_key_unavailable_discriminator` | supported / not-applicable / not_applicable | supported / not-applicable / not_applicable | | `shielded.core_wallet_drain` | supported / unsupported / tested | unsupported / unsupported / not_applicable | +| `shielded.spend_plan` | supported / unsupported / not_applicable | unsupported / unsupported / not_applicable | Source: [`docs/sdk/sdk-parity-manifest.json`](../../docs/sdk/sdk-parity-manifest.json). Detailed legacy view mapping remains in [`PARITY.md`](PARITY.md), but its manual totals are not authoritative. 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..0f5e5a81f39 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) + /** + * `ErrorShieldedPlanChanged` (native code 77). A shielded spend run + * against a plan (`platform_wallet_manager_shielded_plan_spend`, then + * a `_with_plan` spend) selected different notes or a different fee + * than the plan, as the wallet's notes changed since. Nothing was + * reserved, built or broadcast: plan again and confirm the new fee. + * ← Swift `PlatformWalletError.shieldedPlanChanged`. + */ + class ShieldedPlanChanged(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.ShieldedPlanChanged(message, cause) // ErrorShieldedPlanChanged 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..2fd7c51056d 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,22 @@ class DashSdkErrorTest { assertFalse("a sync settles it, not a retry", mapped.isRetryable) } + /** + * A shielded spend run against a plan whose notes moved since has its own + * code, apart from an unconfirmed spend (18): nothing was sent, and the + * spend needs a new plan and a new confirmation, not a retry. + */ + @Test + fun shouldReportAChangedShieldedPlanByItsOwnCode() { + val detail = "the shielded spend no longer selects the planned notes" + val native = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 77, detail) + val mapped = DashSdkError.fromNative(native) + assertTrue(mapped is DashSdkError.PlatformWallet.ShieldedPlanChanged) + assertFalse(mapped is DashSdkError.PlatformWallet.ShieldedSpendUnconfirmed) + assertEquals(detail, mapped.message) + assertFalse("plan again and confirm, not a retry", mapped.isRetryable) + } + @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 1a5c97036ec..30e2880c8bc 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -193,7 +193,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 | `ErrorShieldedPlanChanged` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedPlanChanged`: a shielded spend run against a plan (`platform_wallet_manager_shielded_plan_spend`, then a `_with_plan` transfer, unshield, withdraw or identity top-up export) selected different notes or a different fee than the plan, as the wallet's notes changed since. Nothing was reserved, built or broadcast; plan again and confirm the new fee. Mapped by the blanket conversion and kept by `map_spend_result`. Swift and Kotlin mirrors follow with the Swift wrapper of the plan | +| 77 | `ErrorShieldedPlanChanged` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedPlanChanged`: a shielded spend run against a plan (`platform_wallet_manager_shielded_plan_spend`, then a `_with_plan` transfer, unshield, withdraw or identity top-up export) selected different notes or a different fee than the plan, as the wallet's notes changed since. Nothing was reserved, built or broadcast; plan again and confirm the new fee. Mapped by the blanket conversion and kept by `map_spend_result`. Swift types it (`PlatformWalletError.shieldedPlanChanged`, `ErrorHandlingTests` pin) and wraps the plan (`PlatformWalletManager.shieldedPlanSpend`, an optional `plan:` on the four spends); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedPlanChanged`, `DashSdkErrorTest` pin) with no JNI binding of the plan | **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/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index a6feb022840..7fd7b4b66c3 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -82,6 +82,81 @@ public struct ShieldedSyncEvent: Sendable { } } +/// The shielded spend a `ShieldedSpendPlan` plans, numbered as the FFI's +/// `kind` byte numbers it (`3`, the shield from an identity, spends no notes). +public enum ShieldedSpendKind: UInt8, Sendable { + case transfer = 0 + case unshield = 1 + case withdrawal = 2 + case identityTopUp = 4 +} + +/// What a planned shielded spend sends: an exact amount with the fee on top, +/// or every spendable note minus the fee for all of them. +public enum ShieldedSpendAmount: Sendable, Equatable { + case exact(UInt64) + case sweepAll +} + +/// A shielded spend planned before it is confirmed +/// (`PlatformWalletManager.shieldedPlanSpend`): the notes Rust would select +/// now, by count and digest, and their exact fee. All amounts are credits. +/// Pass it as `plan:` to the spend to run exactly this plan; the spend throws +/// `PlatformWalletError.shieldedPlanChanged` when the notes moved since. +public struct ShieldedSpendPlan: Sendable, Equatable { + public let kind: ShieldedSpendKind + /// What the recipient gets. + public let amount: UInt64 + /// The exact fee for the selected notes. + public let fee: UInt64 + /// The sum of the selected notes. + public let totalInput: UInt64 + /// What leaves the pool: `amount + fee` (any rest returns as change). + public let totalDebited: UInt64 + public let noteCount: UInt32 + /// 32 bytes naming the selection; opaque to the host. + public let digest: Data +} + +extension ShieldedSpendPlan { + init(ffi: ShieldedSpendPlanFFI) throws { + guard let kind = ShieldedSpendKind(rawValue: ffi.kind) else { + throw PlatformWalletError.deserialization( + "unknown shielded spend plan kind \(ffi.kind)" + ) + } + self.init( + kind: kind, + amount: ffi.amount, + fee: ffi.fee, + totalInput: ffi.total_input, + totalDebited: ffi.total_debited, + noteCount: ffi.note_count, + digest: withUnsafeBytes(of: ffi.digest) { Data($0) } + ) + } +} + +/// Run `body` with a pointer to `plan`'s 32-byte digest, or `nil` with no +/// plan; a digest of any other length throws before any FFI call. +private func withPlanDigest( + _ plan: ShieldedSpendPlan?, + _ body: (UnsafePointer?) throws -> R +) throws -> R { + guard let plan else { return try body(nil) } + guard plan.digest.count == 32 else { + throw PlatformWalletError.invalidParameter( + "plan digest must be exactly 32 bytes" + ) + } + return try plan.digest.withUnsafeBytes { raw in + guard let ptr = raw.baseAddress?.assumingMemoryBound(to: UInt8.self) else { + throw PlatformWalletError.invalidParameter("plan digest baseAddress is nil") + } + return try body(ptr) + } +} + extension PlatformWalletManager { /// Shutdown leaves the handle live for admitted operations after its /// early shielded stop. Do not restart or mutate that lifecycle while @@ -658,6 +733,54 @@ extension PlatformWalletManager { return fee } + /// Plan a shielded spend from `account`'s notes before it is confirmed: + /// the notes Rust would select now and their exact fee, which grows with + /// the number of notes. Nothing is reserved or broadcast. Pass the plan + /// as `plan:` to the matching spend to run exactly it. + /// + /// Throws `invalidParameter` for a kind or amount Rust refuses, and + /// `walletOperation` when the notes cannot pay the amount and its fee + /// (or the amount is zero), as the spends do. + public func shieldedPlanSpend( + walletId: Data, + account: UInt32 = 0, + kind: ShieldedSpendKind, + amount: ShieldedSpendAmount + ) async throws -> ShieldedSpendPlan { + guard isConfigured, handle != NULL_HANDLE else { + throw PlatformWalletError.invalidHandle( + "PlatformWalletManager not configured" + ) + } + guard walletId.count == 32 else { + throw PlatformWalletError.invalidParameter( + "walletId must be exactly 32 bytes" + ) + } + let (credits, sweepAll): (UInt64, Bool) + switch amount { + case .exact(let value): (credits, sweepAll) = (value, false) + case .sweepAll: (credits, sweepAll) = (0, true) + } + + let handle = self.handle + // The plan reads the shielded store under its lock: off the caller's actor. + return try await Task.detached(priority: .userInitiated) { + try walletId.withUnsafeBytes { widRaw in + guard let widPtr = widRaw.baseAddress?.assumingMemoryBound(to: UInt8.self) + else { + throw PlatformWalletError.invalidParameter("walletId baseAddress is nil") + } + // A plain value struct: nothing in it is allocated by Rust. + var out = ShieldedSpendPlanFFI() + try platform_wallet_manager_shielded_plan_spend( + handle, widPtr, account, kind.rawValue, credits, sweepAll, &out + ).check() + return try ShieldedSpendPlan(ffi: out) + } + }.value + } + /// Shielded → Shielded transfer. Spends notes from `account` /// on `walletId` and creates a new note for `recipientRaw43` /// (the recipient's raw 43-byte Orchard payment address). @@ -683,13 +806,18 @@ extension PlatformWalletManager { /// included): it may already be on chain or may still execute, so the /// caller must NOT retry (the spent notes stay reserved Rust-side /// until a later shielded sync resolves them). + /// + /// With `plan` (from `shieldedPlanSpend`), the spend runs exactly that + /// plan or throws `PlatformWalletError.shieldedPlanChanged`, with nothing + /// reserved or sent, when the wallet's notes no longer select it. public func shieldedTransfer( walletId: Data, resolver: MnemonicResolver, account: UInt32 = 0, recipientRaw43: Data, amount: UInt64, - memo: String? = nil + memo: String? = nil, + plan: ShieldedSpendPlan? = nil ) async throws { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( @@ -738,10 +866,13 @@ extension PlatformWalletManager { // pass the text as a C string. Rust validates the // 32-byte limit and does the 36-byte encoding. let send: (UnsafePointer?) throws -> Void = { memoCStr in - try platform_wallet_manager_shielded_transfer( - handle, widPtr, resolverHandle, account, recipientPtr, amount, - memoCStr - ).check() + try withPlanDigest(plan) { digest in + try (digest.map { + platform_wallet_manager_shielded_transfer_with_plan( + handle, widPtr, resolverHandle, account, recipientPtr, amount, memoCStr, $0) + } ?? platform_wallet_manager_shielded_transfer( + handle, widPtr, resolverHandle, account, recipientPtr, amount, memoCStr)).check() + } } if let memo, !memo.isEmpty { try memo.withCString { try send($0) } @@ -1095,12 +1226,17 @@ extension PlatformWalletManager { /// included): it may already be on chain or may still execute, so the /// caller must NOT retry (the spent notes stay reserved Rust-side /// until a later shielded sync resolves them). + /// + /// With `plan` (from `shieldedPlanSpend`), the spend runs exactly that + /// plan or throws `PlatformWalletError.shieldedPlanChanged`, with nothing + /// reserved or sent, when the wallet's notes no longer select it. public func shieldedUnshield( walletId: Data, resolver: MnemonicResolver, account: UInt32 = 0, toPlatformAddress: String, - amount: UInt64 + amount: UInt64, + plan: ShieldedSpendPlan? = nil ) async throws { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( @@ -1134,9 +1270,13 @@ extension PlatformWalletManager { throw PlatformWalletError.invalidParameter("walletId baseAddress is nil") } try toPlatformAddress.withCString { addrCStr in - try platform_wallet_manager_shielded_unshield( - handle, widPtr, resolverHandle, account, addrCStr, amount - ).check() + try withPlanDigest(plan) { digest in + try (digest.map { + platform_wallet_manager_shielded_unshield_with_plan( + handle, widPtr, resolverHandle, account, addrCStr, amount, $0) + } ?? platform_wallet_manager_shielded_unshield( + handle, widPtr, resolverHandle, account, addrCStr, amount)).check() + } } } } @@ -1162,12 +1302,17 @@ extension PlatformWalletManager { /// included): it may already be on chain or may still execute, so the /// caller must NOT retry (the spent notes stay reserved Rust-side /// until a later shielded sync resolves them). + /// + /// With `plan` (from `shieldedPlanSpend`), the spend runs exactly that + /// plan or throws `PlatformWalletError.shieldedPlanChanged`, with nothing + /// reserved or sent, when the wallet's notes no longer select it. public func shieldedIdentityTopUpFromPool( walletId: Data, resolver: MnemonicResolver, account: UInt32 = 0, identityId: Data, - amount: UInt64 + amount: UInt64, + plan: ShieldedSpendPlan? = nil ) async throws { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( @@ -1208,9 +1353,13 @@ extension PlatformWalletManager { "identityId baseAddress is nil" ) } - try platform_wallet_manager_shielded_identity_top_up_from_pool( - handle, widPtr, resolverHandle, account, idPtr, amount - ).check() + try withPlanDigest(plan) { digest in + try (digest.map { + platform_wallet_manager_shielded_identity_top_up_from_pool_with_plan( + handle, widPtr, resolverHandle, account, idPtr, amount, $0) + } ?? platform_wallet_manager_shielded_identity_top_up_from_pool( + handle, widPtr, resolverHandle, account, idPtr, amount)).check() + } } } } @@ -1231,13 +1380,18 @@ extension PlatformWalletManager { /// included): it may already be on chain or may still execute, so the /// caller must NOT retry (the spent notes stay reserved Rust-side /// until a later shielded sync resolves them). + /// + /// With `plan` (from `shieldedPlanSpend`), the spend runs exactly that + /// plan or throws `PlatformWalletError.shieldedPlanChanged`, with nothing + /// reserved or sent, when the wallet's notes no longer select it. public func shieldedWithdraw( walletId: Data, resolver: MnemonicResolver, account: UInt32 = 0, toCoreAddress: String, amount: UInt64, - coreFeePerByte: UInt32 = 1 + coreFeePerByte: UInt32 = 1, + plan: ShieldedSpendPlan? = nil ) async throws { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( @@ -1266,10 +1420,13 @@ extension PlatformWalletManager { throw PlatformWalletError.invalidParameter("walletId baseAddress is nil") } try toCoreAddress.withCString { addrCStr in - try platform_wallet_manager_shielded_withdraw( - handle, widPtr, resolverHandle, account, addrCStr, amount, - coreFeePerByte - ).check() + try withPlanDigest(plan) { digest in + try (digest.map { + platform_wallet_manager_shielded_withdraw_with_plan( + handle, widPtr, resolverHandle, account, addrCStr, amount, coreFeePerByte, $0) + } ?? platform_wallet_manager_shielded_withdraw( + handle, widPtr, resolverHandle, account, addrCStr, amount, coreFeePerByte)).check() + } } } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index ee130585d2d..1d00305d326 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 + /// A shielded spend run against a plan (`shieldedPlanSpend`) selected + /// different notes or a different fee than the plan, as the wallet's + /// notes changed since. Nothing was reserved, built or broadcast. + case errorShieldedPlanChanged = 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_SHIELDED_PLAN_CHANGED: + self = .errorShieldedPlanChanged 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) + /// A shielded spend run against a `ShieldedSpendPlan` selected different + /// notes or a different fee than the plan, as the wallet's notes changed + /// since (code 77). Nothing was reserved, built or broadcast: plan again + /// and confirm the new fee before spending. + case shieldedPlanChanged(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), .shieldedPlanChanged(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 .errorShieldedPlanChanged: + self = .shieldedPlanChanged(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..a4d8beca63a 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -604,6 +604,22 @@ final class ErrorHandlingTests: XCTestCase { XCTAssertEqual(message, detail) } + /// A spend run against a plan whose notes moved since keeps its own code + /// and typed case, apart from an unconfirmed spend (18): nothing was sent. + func testShouldReportAChangedShieldedPlanByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_PLAN_CHANGED + ) + XCTAssertEqual(code, .errorShieldedPlanChanged) + XCTAssertEqual(code.rawValue, 77) + let detail = "the shielded spend no longer selects the planned notes" + guard case .shieldedPlanChanged(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed plan-changed error") + } + XCTAssertEqual(message, detail) + } + func testShouldReadEveryFieldOfThePrivateContactReadiness() { var ffi = PrivateContactReadinessFFI() ffi.private_payments_restored = false diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift new file mode 100644 index 00000000000..8323d1d89f4 --- /dev/null +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift @@ -0,0 +1,174 @@ +import XCTest +import DashSDKFFI +@testable import SwiftDashSDK + +/// The Swift side of `platform_wallet_manager_shielded_plan_spend` and the +/// `_with_plan` spend exports: the plan decoded from its FFI struct, the +/// guards that run before any FFI call, and what reaches the FFI. +/// +/// The manager here holds a handle no native manager owns, so a call that +/// reaches the FFI comes back `invalidHandle`; a guard or a marshalling the +/// FFI refuses comes back `invalidParameter` instead. +@MainActor +final class ShieldedSpendPlanTests: XCTestCase { + private static let walletId = Data(repeating: 7, count: 32) + + private nonisolated static func noOpCalls() -> PlatformWalletNativeTeardownCalls { + let success: PlatformWalletNativeTeardownCalls.Call = { _ in + PlatformWalletFFIResult(code: PLATFORM_WALLET_FFI_RESULT_CODE_SUCCESS, message: nil) + } + return PlatformWalletNativeTeardownCalls( + spvStop: success, platformAddressSyncStop: success, shieldedSyncStop: success, + dashPaySyncStop: success, dpnsSyncStop: success, destroy: success) + } + + private func makeManager() -> PlatformWalletManager { + PlatformWalletManager.makeForTesting(handle: 71, calls: Self.noOpCalls()) + } + + private func plan(kind: ShieldedSpendKind, digestCount: Int = 32) -> ShieldedSpendPlan { + ShieldedSpendPlan( + kind: kind, amount: 1, fee: 2, totalInput: 3, totalDebited: 3, noteCount: 1, + digest: Data(repeating: 9, count: digestCount)) + } + + private func assertThrows( + _ name: String, + _ expected: (PlatformWalletError) -> Bool, + _ operation: () async throws -> Void, + file: StaticString = #filePath, + line: UInt = #line + ) async { + do { + try await operation() + XCTFail("\(name) did not throw", file: file, line: line) + } catch let error as PlatformWalletError { + XCTAssertTrue(expected(error), "\(name): unexpected \(error)", file: file, line: line) + } catch { + XCTFail("\(name): unexpected \(error)", file: file, line: line) + } + } + + private static func isInvalidHandle(_ error: PlatformWalletError) -> Bool { + if case .invalidHandle = error { return true } + return false + } + + private static func isInvalidParameter(_ error: PlatformWalletError) -> Bool { + if case .invalidParameter = error { return true } + return false + } + + // MARK: - The plan value + + func testShouldNumberSpendKindsAsTheFFIDoes() { + XCTAssertEqual(ShieldedSpendKind.transfer.rawValue, 0) + XCTAssertEqual(ShieldedSpendKind.unshield.rawValue, 1) + XCTAssertEqual(ShieldedSpendKind.withdrawal.rawValue, 2) + XCTAssertEqual(ShieldedSpendKind.identityTopUp.rawValue, 4) + } + + func testShouldDecodeEveryFieldOfThePlan() throws { + var ffi = ShieldedSpendPlanFFI() + ffi.kind = 4 + ffi.amount = 100 + ffi.fee = .max + ffi.total_input = 300 + ffi.total_debited = 200 + ffi.note_count = .max + withUnsafeMutableBytes(of: &ffi.digest) { raw in + for index in raw.indices { raw[index] = UInt8(index) } + } + XCTAssertEqual( + try ShieldedSpendPlan(ffi: ffi), + ShieldedSpendPlan( + kind: .identityTopUp, amount: 100, fee: .max, totalInput: 300, + totalDebited: 200, noteCount: .max, digest: Data((0..<32).map(UInt8.init)))) + } + + func testShouldRejectAPlanKindTheFFINeverWrites() { + var ffi = ShieldedSpendPlanFFI() + ffi.kind = 3 + XCTAssertThrowsError(try ShieldedSpendPlan(ffi: ffi)) + } + + // MARK: - Planning + + func testShouldRejectAnUnconfiguredManagerBeforePlanning() async { + let manager = PlatformWalletManager() + await assertThrows("plan", Self.isInvalidHandle) { + _ = try await manager.shieldedPlanSpend( + walletId: Self.walletId, kind: .transfer, amount: .exact(1)) + } + } + + func testShouldRejectAShortWalletIdBeforePlanning() async { + let manager = makeManager() + await assertThrows("plan", Self.isInvalidParameter) { + _ = try await manager.shieldedPlanSpend( + walletId: Data(repeating: 7, count: 31), kind: .transfer, amount: .exact(1)) + } + await manager.shutdown() + } + + /// The FFI refuses an unknown kind byte, and a sweep with an amount, with + /// `invalidParameter` before it looks the manager up: reaching the handle + /// lookup shows every kind and both amounts were marshalled as it reads them. + func testShouldMarshalEveryKindAndBothAmountsToTheFFI() async { + let manager = makeManager() + let kinds: [ShieldedSpendKind] = [.transfer, .unshield, .withdrawal, .identityTopUp] + let amounts: [ShieldedSpendAmount] = [.exact(5), .sweepAll] + for kind in kinds { + for amount in amounts { + await assertThrows("plan \(kind) \(amount)", Self.isInvalidHandle) { + _ = try await manager.shieldedPlanSpend( + walletId: Self.walletId, account: 3, kind: kind, amount: amount) + } + } + } + await manager.shutdown() + } + + // MARK: - Spending against a plan + + private func spends( + _ manager: PlatformWalletManager, + resolver: MnemonicResolver, + digestCount: Int + ) -> [(String, () async throws -> Void)] { + [ + ("transfer", { try await manager.shieldedTransfer( + walletId: Self.walletId, resolver: resolver, + recipientRaw43: Data(repeating: 1, count: 43), amount: 1, + plan: self.plan(kind: .transfer, digestCount: digestCount)) }), + ("unshield", { try await manager.shieldedUnshield( + walletId: Self.walletId, resolver: resolver, toPlatformAddress: "tdash1x", + amount: 1, plan: self.plan(kind: .unshield, digestCount: digestCount)) }), + ("withdraw", { try await manager.shieldedWithdraw( + walletId: Self.walletId, resolver: resolver, toCoreAddress: "yX", amount: 1, + plan: self.plan(kind: .withdrawal, digestCount: digestCount)) }), + ("top up", { try await manager.shieldedIdentityTopUpFromPool( + walletId: Self.walletId, resolver: resolver, + identityId: Data(repeating: 2, count: 32), amount: 1, + plan: self.plan(kind: .identityTopUp, digestCount: digestCount)) }) + ] + } + + func testShouldRejectAPlanDigestOfTheWrongLengthBeforeAnySpend() async { + let manager = makeManager() + let resolver = MnemonicResolver() + for (name, spend) in spends(manager, resolver: resolver, digestCount: 31) { + await assertThrows(name, Self.isInvalidParameter, spend) + } + await manager.shutdown() + } + + func testShouldPassAPlanToEverySpendsFFI() async { + let manager = makeManager() + let resolver = MnemonicResolver() + for (name, spend) in spends(manager, resolver: resolver, digestCount: 32) { + await assertThrows(name, Self.isInvalidHandle, spend) + } + await manager.shutdown() + } +} From 99877748fcb94bf99525313cedded83ec1c78f8a Mon Sep 17 00:00:00 2001 From: romchornyi Date: Wed, 11 Nov 2026 19:24:13 +0200 Subject: [PATCH 03/20] fix(platform-wallet): bind the planned shielded spend to one protocol version and an executable selection Review fixes for the shielded spend plan: - Each spend reads the protocol version once and uses it to select, check the plan and build; a built fee that differs from the planned fee returns ShieldedPlanChanged before broadcast. - A sweep sends the most the largest notes can send after their own fee: a note joins only if it adds more than its action fee, and the spend reproduces exactly the planned notes. - Note selection is capped at max_shielded_transition_actions for every spend that selects notes (transfer, unshield, withdrawal, identity top-up, private document create): an amount needing more notes is refused at selection with ShieldedSpendTooManyNotes (code 78) instead of being rejected by Platform. - With a plan, running out of notes is reported as ShieldedPlanChanged. - The plan exports are panic-guarded (catch_spend_panic on the spends, a read-only guard on planning). - Swift keeps the original spend signatures; spending against a plan is a separate overload with an explicit plan:. Code 78 is mirrored in Swift and Kotlin. - Public operations::identity_top_up_from_pool_with_plan. - The plan is checked against the borrowed selection before notes are cloned. Co-Authored-By: Claude Opus 5.5 --- docs/sdk/sdk-parity-manifest.json | 2 +- .../dashsdk/errors/DashSdkError.kt | 12 + .../dashsdk/errors/DashSdkErrorTest.kt | 16 + .../ERROR_CODE_REGISTRY.md | 8 +- packages/rs-platform-wallet-ffi/src/error.rs | 10 + .../src/shielded_send.rs | 165 +++++--- packages/rs-platform-wallet/src/error.rs | 6 + .../src/wallet/shielded/note_selection.rs | 368 ++++++++++++++---- .../src/wallet/shielded/operations.rs | 332 +++++++++++++--- .../PlatformWalletManagerShieldedSync.swift | 188 ++++++++- .../PlatformWallet/PlatformWalletResult.swift | 14 + .../ErrorHandlingTests.swift | 16 + .../ShieldedSpendPlanTests.swift | 48 +++ 13 files changed, 995 insertions(+), 190 deletions(-) diff --git a/docs/sdk/sdk-parity-manifest.json b/docs/sdk/sdk-parity-manifest.json index 68eb3483c10..0d2c748db4e 100644 --- a/docs/sdk/sdk-parity-manifest.json +++ b/docs/sdk/sdk-parity-manifest.json @@ -1997,7 +1997,7 @@ "sdk": "supported", "example_app": "unsupported", "restart": "not_applicable", - "reason": "PlatformWalletManager.shieldedPlanSpend returns a ShieldedSpendPlan (kind, amount, exact fee, total input and debited, note count, digest) for an exact amount or a sweep, and shieldedTransfer, shieldedUnshield, shieldedWithdraw and shieldedIdentityTopUpFromPool take an optional plan whose digest goes to the _with_plan export; code 77 is typed as PlatformWalletError.shieldedPlanChanged (ErrorHandlingTests pin). A plan is read-only, so there is nothing to resume after a restart. SwiftExampleApp does not plan its shielded spends." + "reason": "PlatformWalletManager.shieldedPlanSpend returns a ShieldedSpendPlan (kind, amount, exact fee, total input and debited, note count, digest) for an exact amount or a sweep, and shieldedTransfer, shieldedUnshield, shieldedWithdraw and shieldedIdentityTopUpFromPool each have an overload taking an explicit plan, whose digest goes to the _with_plan export, beside their unchanged original signatures; code 77 is typed as PlatformWalletError.shieldedPlanChanged and code 78 (a spend of more notes than one transition spends) as PlatformWalletError.shieldedSpendTooManyNotes (ErrorHandlingTests pins). A plan is read-only, so there is nothing to resume after a restart. SwiftExampleApp does not plan its shielded spends." }, "kotlin": { "sdk": "unsupported", 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 0f5e5a81f39..edc856f1f88 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 @@ -806,6 +806,17 @@ sealed class DashSdkError( class ShieldedPlanChanged(message: String, cause: Throwable? = null) : PlatformWallet(message, cause) + /** + * `ErrorShieldedSpendTooManyNotes` (native code 78). The wallet's + * notes cover a shielded spend, or its plan, only with more notes + * than one shielded transition spends + * (`max_shielded_transition_actions`). Nothing was reserved, built or + * broadcast: a smaller amount fits, or the notes can be merged first. + * ← Swift `PlatformWalletError.shieldedSpendTooManyNotes`. + */ + class ShieldedSpendTooManyNotes(message: String, cause: Throwable? = null) : + PlatformWallet(message, cause) + /** * Any other `PlatformWalletFFIResultCode` without a dedicated type. * Carries the platform-wallet [nativeCode] (already de-offset) and @@ -1016,6 +1027,7 @@ sealed class DashSdkError( 75 -> PlatformWallet.SdkPinnedBelowProtocolVersion(message, cause) // ErrorSdkPinnedBelowProtocolVersion 76 -> PlatformWallet.PublicContactRequestUnconfirmed(message, cause) // ErrorPublicContactRequestUnconfirmed 77 -> PlatformWallet.ShieldedPlanChanged(message, cause) // ErrorShieldedPlanChanged + 78 -> PlatformWallet.ShieldedSpendTooManyNotes(message, cause) // ErrorShieldedSpendTooManyNotes 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 2fd7c51056d..ac3aaf7d290 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 @@ -416,6 +416,22 @@ class DashSdkErrorTest { assertFalse("plan again and confirm, not a retry", mapped.isRetryable) } + /** + * A shielded spend the notes cover only with more notes than one + * transition spends has its own code: nothing was sent, and a smaller + * amount fits, so it is neither a retry nor a balance shortfall (41). + */ + @Test + fun shouldReportAShieldedSpendOfTooManyNotesByItsOwnCode() { + val detail = "Shielded spend needs 17 notes, more than the 16 one transition can spend" + val native = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 78, detail) + val mapped = DashSdkError.fromNative(native) + assertTrue(mapped is DashSdkError.PlatformWallet.ShieldedSpendTooManyNotes) + assertFalse(mapped is DashSdkError.PlatformWallet.PlatformShieldCapacityExceeded) + assertEquals(detail, mapped.message) + assertFalse("a smaller amount fits, not a retry", mapped.isRetryable) + } + @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 30e2880c8bc..c0091610dac 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: 79**: 27–78 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 @@ -129,7 +129,8 @@ 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 a -shielded spend plan that changed; 28, 30, +shielded spend plan that changed; 78 proposed for a shielded spend of more +notes than one transition spends; 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 @@ -193,7 +194,8 @@ 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 | `ErrorShieldedPlanChanged` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedPlanChanged`: a shielded spend run against a plan (`platform_wallet_manager_shielded_plan_spend`, then a `_with_plan` transfer, unshield, withdraw or identity top-up export) selected different notes or a different fee than the plan, as the wallet's notes changed since. Nothing was reserved, built or broadcast; plan again and confirm the new fee. Mapped by the blanket conversion and kept by `map_spend_result`. Swift types it (`PlatformWalletError.shieldedPlanChanged`, `ErrorHandlingTests` pin) and wraps the plan (`PlatformWalletManager.shieldedPlanSpend`, an optional `plan:` on the four spends); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedPlanChanged`, `DashSdkErrorTest` pin) with no JNI binding of the plan | +| 77 | `ErrorShieldedPlanChanged` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedPlanChanged`: a shielded spend run against a plan (`platform_wallet_manager_shielded_plan_spend`, then a `_with_plan` transfer, unshield, withdraw or identity top-up export) selected different notes or a different fee than the plan, as the wallet's notes changed since. Nothing was reserved, built or broadcast; plan again and confirm the new fee. Mapped by the blanket conversion and kept by `map_spend_result`. Swift types it (`PlatformWalletError.shieldedPlanChanged`, `ErrorHandlingTests` pin) and wraps the plan (`PlatformWalletManager.shieldedPlanSpend`, overloads of the four spends taking an explicit `plan:`, beside their unchanged originals); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedPlanChanged`, `DashSdkErrorTest` pin) with no JNI binding of the plan | +| 78 | `ErrorShieldedSpendTooManyNotes` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedSpendTooManyNotes`: the wallet's notes cover a shielded spend (transfer, unshield, withdrawal, identity top-up or private document create from the pool) or its plan (`platform_wallet_manager_shielded_plan_spend`) only with more notes than one shielded transition spends (`max_shielded_transition_actions`, 16). Nothing was reserved, built or broadcast; a smaller amount fits, or the notes can be merged first. Before, the selection took the notes anyway and Platform rejected the transition. Not a balance shortfall (41 is the Platform-address shield's capacity). Mapped by the blanket conversion and kept by `map_spend_result`. Swift types it (`PlatformWalletError.shieldedSpendTooManyNotes`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedSpendTooManyNotes`, `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 477417bfe7c..8486291e04e 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -776,6 +776,13 @@ pub enum PlatformWalletFFIResultCode { /// or broadcast. Plan again and have the new fee confirmed. ErrorShieldedPlanChanged = 77, + /// Maps `PlatformWalletError::ShieldedSpendTooManyNotes`: the wallet's + /// notes cover a shielded spend (or its plan) only with more notes than + /// one shielded transition can spend (`max_shielded_transition_actions`). + /// Nothing was reserved, built or broadcast. A smaller amount fits, or the + /// notes can be merged first. + ErrorShieldedSpendTooManyNotes = 78, + /// The named thing does not exist. /// /// Originally (and still mostly) the code for every `Option` returned as an @@ -1113,6 +1120,9 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::ShieldedPlanChanged { .. } => { PlatformWalletFFIResultCode::ErrorShieldedPlanChanged } + PlatformWalletError::ShieldedSpendTooManyNotes { .. } => { + PlatformWalletFFIResultCode::ErrorShieldedSpendTooManyNotes + } // The core-transaction sibling of the shielded pair above: the // do-not-retry signal must survive the boundary as a typed code // so hosts can distinguish it from a definitive rejection. diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 53c290e858d..e6926d37044 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -316,7 +316,11 @@ unsafe fn read_plan_digest(digest: *const u8) -> [u8; 32] { /// and the plan's `digest`, which refuses with `ErrorShieldedPlanChanged` /// when the notes moved since. An unknown `kind`, or a sweep with an amount, /// returns `ErrorInvalidParameter`; notes that cannot pay the amount and its -/// fee, or a zero amount, return `ErrorWalletOperation`, as the spends do. +/// fee, or a zero amount, return `ErrorWalletOperation`, and an amount only +/// more notes than one transition spends would cover returns +/// `ErrorShieldedSpendTooManyNotes`, as the spends do. A sweep plans the most +/// the notes one transition spends can send. A panic inside returns +/// `ErrorWalletOperation`: planning reserves and sends nothing. /// /// # Safety /// - `wallet_id_bytes` must point to 32 readable bytes. @@ -353,22 +357,24 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_plan_spend( let mut wallet_id = [0u8; 32]; std::ptr::copy_nonoverlapping(wallet_id_bytes, wallet_id.as_mut_ptr(), 32); - let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { - Ok(p) => p, - Err(result) => return result, - }; - let result = block_on_worker(async move { - wallet - .shielded_plan_spend(&coordinator, account, kind, amount) - .await - }); - match result { - Ok(plan) => { - *out_plan = ShieldedSpendPlanFFI::from(&plan); - PlatformWalletFFIResult::ok() + catch_plan_panic("shielded spend plan", || { + let (wallet, coordinator) = match resolve_wallet_and_coordinator(handle, &wallet_id) { + Ok(p) => p, + Err(result) => return result, + }; + let result = block_on_worker(async move { + wallet + .shielded_plan_spend(&coordinator, account, kind, amount) + .await + }); + match result { + Ok(plan) => { + *out_plan = ShieldedSpendPlanFFI::from(&plan); + PlatformWalletFFIResult::ok() + } + Err(e) => map_spend_result(Err(e), "shielded spend plan"), } - Err(e) => map_spend_result(Err(e), "shielded spend plan"), - } + }) } /// Encode an optional host-supplied memo string into the on-chain @@ -473,16 +479,19 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_transfer_with_plan( expected_plan_digest: *const u8, ) -> PlatformWalletFFIResult { check_ptr!(expected_plan_digest); - shielded_transfer_inner( - handle, - wallet_id_bytes, - mnemonic_resolver_handle, - account, - recipient_raw_43, - amount, - memo_text, - Some(read_plan_digest(expected_plan_digest)), - ) + let expected_plan = read_plan_digest(expected_plan_digest); + catch_spend_panic("shielded transfer", || { + shielded_transfer_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + recipient_raw_43, + amount, + memo_text, + Some(expected_plan), + ) + }) } /// Body of the transfer exports; `expected_plan` is the plan digest, if any. @@ -627,15 +636,18 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_unshield_with_plan( expected_plan_digest: *const u8, ) -> PlatformWalletFFIResult { check_ptr!(expected_plan_digest); - shielded_unshield_inner( - handle, - wallet_id_bytes, - mnemonic_resolver_handle, - account, - to_platform_addr_cstr, - amount, - Some(read_plan_digest(expected_plan_digest)), - ) + let expected_plan = read_plan_digest(expected_plan_digest); + catch_spend_panic("shielded unshield", || { + shielded_unshield_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + to_platform_addr_cstr, + amount, + Some(expected_plan), + ) + }) } /// Body of the unshield exports; `expected_plan` is the plan digest, if any. @@ -757,16 +769,19 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_withdraw_with_plan( expected_plan_digest: *const u8, ) -> PlatformWalletFFIResult { check_ptr!(expected_plan_digest); - shielded_withdraw_inner( - handle, - wallet_id_bytes, - mnemonic_resolver_handle, - account, - to_core_address_cstr, - amount, - core_fee_per_byte, - Some(read_plan_digest(expected_plan_digest)), - ) + let expected_plan = read_plan_digest(expected_plan_digest); + catch_spend_panic("shielded withdraw", || { + shielded_withdraw_inner( + handle, + wallet_id_bytes, + mnemonic_resolver_handle, + account, + to_core_address_cstr, + amount, + core_fee_per_byte, + Some(expected_plan), + ) + }) } /// Body of the withdraw exports; `expected_plan` is the plan digest, if any. @@ -942,6 +957,9 @@ pub(crate) fn map_spend_result( // The notes moved since the spend was planned: nothing was reserved // or built; the host plans again and confirms the new fee. Err(e @ PlatformWalletError::ShieldedPlanChanged { .. }) => e.into(), + // More notes than one transition spends: nothing was reserved or + // built; a smaller amount fits. + Err(e @ PlatformWalletError::ShieldedSpendTooManyNotes { .. }) => e.into(), // Retryable: the wallet couldn't build the spend against any // Platform-recorded anchor yet (its commitment tree is mid-block after // an index-chunk sync). Nothing was broadcast and the notes were @@ -1091,6 +1109,21 @@ pub(crate) fn catch_spend_panic( ) } +/// [`catch_panic_to_code`] for planning a shielded spend, which only reads the store: a panic +/// there is a failed read ([`PlatformWalletFFIResultCode::ErrorWalletOperation`]), with nothing +/// reserved or sent. +fn catch_plan_panic( + operation: &str, + body: impl FnOnce() -> PlatformWalletFFIResult, +) -> PlatformWalletFFIResult { + catch_panic_to_code( + operation, + PlatformWalletFFIResultCode::ErrorWalletOperation, + "Planning only reads the notes: nothing was reserved or sent; plan again.", + body, + ) +} + /// Post-panic guidance for the asset-lock funding exports. Paired with /// `ErrorTransactionBroadcastUnconfirmed` in [`catch_funding_panic`]. const FUNDING_PANIC_GUIDANCE: &str = "The asset lock may or may not have been broadcast — do \ @@ -3334,6 +3367,48 @@ mod tests { ); } + /// A spend that needs more notes than one transition spends keeps its own code through + /// the spend contract, the planning export and the blanket conversion alike. + #[test] + fn should_keep_a_spend_of_too_many_notes_at_its_own_code() { + let too_many = || PlatformWalletError::ShieldedSpendTooManyNotes { + needed: 17, + max: 16, + }; + let result = map_spend_result(Err(too_many()), "shielded spend plan"); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedSpendTooManyNotes + ); + assert_eq!(result.code as i32, 78); + assert!(message_of(&result).contains("needs 17 notes")); + assert_eq!(PlatformWalletFFIResult::from(too_many()).code as i32, 78); + } + + /// A panic while planning is caught and reported as a failed read: planning reserves and + /// sends nothing, so it is not the spend's do-not-retry contract. + #[test] + fn should_report_a_panic_while_planning_as_a_failed_read() { + let result = catch_plan_panic("shielded spend plan", || { + panic!("tokio worker panicked"); + }); + + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorWalletOperation + ); + let message = message_of(&result); + assert!( + message.contains("shielded spend plan panicked") + && message.contains("nothing was reserved or sent"), + "{message}" + ); + assert_eq!( + catch_plan_panic("test", PlatformWalletFFIResult::ok).code, + PlatformWalletFFIResultCode::Success + ); + } + #[test] fn shield_preflight_rejects_null_abi_pointers() { unsafe { diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index 071d1c9d6f5..e970cf841d9 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -1076,6 +1076,12 @@ pub enum PlatformWalletError { fresh_note_count: usize, }, + /// The notes cover the spend only with more notes than one shielded transition can spend + /// (`max_shielded_transition_actions`). Refused before any note was reserved or anything + /// built; a smaller amount, or merging notes first, fits. + #[error("Shielded spend needs {needed} notes, more than the {max} one transition can spend")] + ShieldedSpendTooManyNotes { needed: usize, max: usize }, + /// A Platform Payment-account shield cannot be represented from the /// wallet's deterministic address-input set at the requested amount. /// Distinct from [`ShieldedInsufficientBalance`](Self::ShieldedInsufficientBalance), diff --git a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs index f8a13c18166..a7bbc1b922f 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs @@ -164,14 +164,15 @@ pub fn select_notes( Ok(selected) } -/// Select notes with iterative fee convergence. +/// Select the fewest largest notes that cover `amount` plus their own fee. /// -/// The fee depends on the number of actions, which depends on the number of -/// selected notes. This function iterates: -/// 1. Estimate fee for `min_actions` (the builder's minimum action count) -/// 2. Select notes for amount + estimated fee -/// 3. Compute exact fee from actual note count -/// 4. If insufficient, re-select with exact fee; repeat (converges in 2-3 iterations) +/// The fee depends on the number of actions, which depends on the number of selected notes, so +/// the largest-first prefixes are tried in turn and the first whose sum covers `amount` plus the +/// fee for its own action count (at least `min_actions`) is selected. +/// +/// One transition spends at most `max_shielded_transition_actions` notes: an amount that only +/// more notes than that would cover is refused with +/// [`PlatformWalletError::ShieldedSpendTooManyNotes`]. /// /// `fee_kind` selects which consensus fee formula to reserve against: pass /// [`ShieldedFeeKind::Withdrawal`] for a ShieldedWithdrawal (so the flat Core @@ -188,41 +189,105 @@ pub fn select_notes_with_fee<'a>( fee_kind: ShieldedFeeKind, platform_version: &PlatformVersion, ) -> Result<(Vec<&'a ShieldedNote>, u64, u64), PlatformWalletError> { - let mut fee_estimate = fee_kind - .compute(min_actions, platform_version) - .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - - for _ in 0..5 { - let selected = select_notes(unspent, amount, fee_estimate)?; - let total: u64 = selected.iter().map(|n| n.value).sum(); - let num_actions = selected.len().max(min_actions); - let exact_fee = fee_kind - .compute(num_actions, platform_version) + let sorted = spendable_largest_first(unspent)?; + let max_notes = max_notes_per_transition(platform_version); + let mut total = 0u64; + let mut required = amount; + for (index, note) in sorted.iter().enumerate() { + // Checked: a corrupt/crafted store could otherwise overflow u64. + total = total.checked_add(note.value).ok_or_else(|| { + PlatformWalletError::ShieldedBuildError( + "shielded note values sum overflows u64".to_string(), + ) + })?; + let count = index + 1; + let fee = fee_kind + .compute(count.max(min_actions), platform_version) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - - if total >= amount.saturating_add(exact_fee) { - return Ok((selected, total, exact_fee)); + required = amount.checked_add(fee).ok_or_else(|| { + PlatformWalletError::ShieldedBuildError("amount + fee overflows u64".to_string()) + })?; + if total >= required { + if count > max_notes { + return Err(PlatformWalletError::ShieldedSpendTooManyNotes { + needed: count, + max: max_notes, + }); + } + let mut sorted = sorted; + sorted.truncate(count); + return Ok((sorted, total, fee)); } + } + Err(PlatformWalletError::ShieldedInsufficientBalance { + available: total, + required, + }) +} - fee_estimate = exact_fee; +/// The unspent notes of `unspent`, largest first; [`PlatformWalletError::ShieldedNoUnspentNotes`] +/// when there are none. +fn spendable_largest_first( + unspent: &[ShieldedNote], +) -> Result, PlatformWalletError> { + // Filter out any spent notes defensively (callers pass unspent notes only). + let mut sorted: Vec<&ShieldedNote> = unspent.iter().filter(|n| !n.is_spent).collect(); + if sorted.is_empty() { + return Err(PlatformWalletError::ShieldedNoUnspentNotes); } + sorted.sort_by_key(|note| std::cmp::Reverse(note.value)); + Ok(sorted) +} - // Final attempt with last computed fee - let selected = select_notes(unspent, amount, fee_estimate)?; - let total: u64 = selected.iter().map(|n| n.value).sum(); - let num_actions = selected.len().max(min_actions); - let exact_fee = fee_kind - .compute(num_actions, platform_version) - .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; +/// How many notes one shielded transition spends at most: one action per note. +fn max_notes_per_transition(platform_version: &PlatformVersion) -> usize { + usize::from( + platform_version + .system_limits + .max_shielded_transition_actions, + ) +} - if total < amount.saturating_add(exact_fee) { - return Err(PlatformWalletError::ShieldedInsufficientBalance { - available: total, - required: amount.saturating_add(exact_fee), - }); +/// The most a sweep of `unspent` can send: over the largest-first prefixes one transition can +/// spend, the greatest sum minus the fee for that prefix. A note joins only when it adds more +/// than the fee for its action, and the fewest notes win a tie, so [`select_notes_with_fee`] +/// for the returned amount selects exactly that prefix. +fn sweep_amount( + unspent: &[ShieldedNote], + fee_kind: ShieldedFeeKind, + platform_version: &PlatformVersion, +) -> Result { + let sorted = spendable_largest_first(unspent)?; + let max_notes = max_notes_per_transition(platform_version); + let mut total = 0u64; + let mut best: Option = None; + for (index, note) in sorted.iter().take(max_notes).enumerate() { + total = total.checked_add(note.value).ok_or_else(|| { + PlatformWalletError::ShieldedBuildError( + "shielded note values sum overflows u64".to_string(), + ) + })?; + let fee = fee_kind + .compute((index + 1).max(SPEND_MIN_ACTIONS), platform_version) + .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; + if let Some(sent) = total.checked_sub(fee).filter(|sent| *sent > 0) { + if best.is_none_or(|best| sent > best) { + best = Some(sent); + } + } + } + match best { + Some(amount) => Ok(amount), + None => { + let fee = fee_kind + .compute(SPEND_MIN_ACTIONS, platform_version) + .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; + Err(PlatformWalletError::ShieldedInsufficientBalance { + available: total, + required: fee.saturating_add(1), + }) + } } - - Ok((selected, total, exact_fee)) } /// The minimum Orchard action count of an amount-based spend: one spend plus the recipient @@ -271,7 +336,8 @@ impl ShieldedSpendKind { pub enum ShieldedSpendAmount { /// Exactly this many credits reach the recipient; the fee comes on top. Exact(Credits), - /// Every spendable note: the recipient gets their sum minus the fee for all of them. + /// As much as the notes can send: the largest notes that add more than their action's fee, + /// up to what one transition spends; the recipient gets their sum minus their fee. Sweep, } @@ -337,8 +403,8 @@ impl ShieldedSpendPlan { /// Plan a `kind` spend of `amount` from `unspent`: the notes the spend would select /// ([`select_notes_with_fee`] at [`SPEND_MIN_ACTIONS`]) and their exact fee. /// -/// A [`ShieldedSpendAmount::Sweep`] sends the sum of every spendable note minus the fee for all -/// of them. +/// A [`ShieldedSpendAmount::Sweep`] sends the most the notes one transition can spend send after +/// their fee ([`sweep_amount`]); the plan selects exactly those notes. pub fn plan_spend( unspent: &[ShieldedNote], kind: ShieldedSpendKind, @@ -348,32 +414,7 @@ pub fn plan_spend( let fee_kind = kind.fee_kind(); let amount = match amount { ShieldedSpendAmount::Exact(amount) => amount, - ShieldedSpendAmount::Sweep => { - let spendable: Vec<&ShieldedNote> = unspent.iter().filter(|n| !n.is_spent).collect(); - if spendable.is_empty() { - return Err(PlatformWalletError::ShieldedNoUnspentNotes); - } - let balance = spendable - .iter() - .try_fold(0u64, |acc, n| acc.checked_add(n.value)) - .ok_or_else(|| { - PlatformWalletError::ShieldedBuildError( - "shielded note values sum overflows u64".to_string(), - ) - })?; - let fee = fee_kind - .compute(spendable.len().max(SPEND_MIN_ACTIONS), platform_version) - .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - match balance.checked_sub(fee) { - Some(amount) if amount > 0 => amount, - _ => { - return Err(PlatformWalletError::ShieldedInsufficientBalance { - available: balance, - required: fee.saturating_add(1), - }) - } - } - } + ShieldedSpendAmount::Sweep => sweep_amount(unspent, fee_kind, platform_version)?, }; ensure_positive_amount(amount)?; let (selected, total_input, fee) = select_notes_with_fee( @@ -393,14 +434,15 @@ pub fn plan_spend( } /// Refuse a spend whose fresh selection (`selected`, `total_input`, `fee` for `kind` and -/// `amount`) does not match the plan whose digest is `expected`. +/// `amount`) does not match the plan whose digest is `expected`. Reads the borrowed selection +/// only, so nothing is cloned for a selection it refuses. pub(crate) fn ensure_plan_holds( expected: &[u8; 32], kind: ShieldedSpendKind, amount: Credits, fee: Credits, total_input: Credits, - selected: &[ShieldedNote], + selected: &[&ShieldedNote], ) -> Result<(), PlatformWalletError> { let fresh = ShieldedSpendPlan::new( kind, @@ -982,21 +1024,24 @@ mod tests { let notes: Vec = (0..3).map(|i| test_note(NOTE, i)).collect(); let amount = ShieldedSpendAmount::Exact(2 * NOTE); let plan = plan_spend(¬es, kind, amount, platform_version).expect("plans"); - let selected = |notes: &[ShieldedNote]| -> (Vec, u64, u64) { - let (refs, total, fee) = - select_notes_with_fee(notes, 2 * NOTE, 2, kind.fee_kind(), platform_version) - .expect("selects"); - (refs.into_iter().cloned().collect(), total, fee) - }; + // The plan is checked against the borrowed selection, before any note is cloned. + fn selected<'a>( + notes: &'a [ShieldedNote], + kind: ShieldedSpendKind, + platform_version: &PlatformVersion, + ) -> (Vec<&'a ShieldedNote>, u64, u64) { + select_notes_with_fee(notes, 2 * NOTE, 2, kind.fee_kind(), platform_version) + .expect("selects") + } - let (same, total, fee) = selected(¬es); + let (same, total, fee) = selected(¬es, kind, platform_version); ensure_plan_holds(&plan.digest, kind, 2 * NOTE, fee, total, &same) .expect("an unchanged selection holds"); // A larger note arrives: one note now covers it, at a different fee. let mut grown = notes.clone(); grown.push(test_note(10 * NOTE, 7)); - let (moved, total, fee) = selected(&grown); + let (moved, total, fee) = selected(&grown, kind, platform_version); let err = ensure_plan_holds(&plan.digest, kind, 2 * NOTE, fee, total, &moved) .expect_err("a moved selection must not hold"); assert!( @@ -1030,4 +1075,179 @@ mod tests { PlatformWalletError::ShieldedPlanChanged { .. } )); } + + /// Dust that costs more than it adds stays out of a sweep: the large note alone pays its + /// two-action fee, although the fee for every note is more than the balance. + #[test] + fn should_sweep_the_large_note_when_dust_costs_more_than_it_adds() { + let platform_version = PlatformVersion::latest(); + let notes = vec![ + test_note(150_000_000, 0), + test_note(1, 1), + test_note(1, 2), + test_note(1, 3), + ]; + let two_action_fee = compute_minimum_shielded_fee(2, platform_version).expect("fee"); + assert!( + compute_minimum_shielded_fee(4, platform_version).expect("fee") > 150_000_003, + "the fee for every note eats the balance" + ); + + let plan = plan_spend( + ¬es, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Sweep, + platform_version, + ) + .expect("the large note pays its own fee"); + + // A second note is free: one note is already charged for two actions. + assert_eq!(plan.note_count(), 2); + assert!( + plan.nullifiers.contains(&[0; 32]), + "the large note is swept" + ); + assert_eq!(plan.fee, two_action_fee); + assert_eq!(plan.amount, 150_000_001 - two_action_fee); + assert_eq!( + plan.total_debited(), + plan.total_input, + "a sweep leaves no change" + ); + } + + /// A note worth less than the fee for its action is left out of a sweep, and the amount is + /// what the notes the spend selects send, with no change. + #[test] + fn should_sweep_fewer_notes_than_all_when_one_costs_more_than_it_adds() { + let platform_version = PlatformVersion::latest(); + let dust = 1_000; + let notes = vec![ + test_note(NOTE, 0), + test_note(NOTE, 1), + test_note(NOTE, 2), + test_note(dust, 3), + ]; + let fee = |actions| compute_minimum_shielded_fee(actions, platform_version).expect("fee"); + assert!(fee(4) - fee(3) > dust, "the dust costs more than it adds"); + + let plan = plan_spend( + ¬es, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Sweep, + platform_version, + ) + .expect("plans"); + + assert_eq!(plan.note_count(), 3); + assert_eq!(plan.fee, fee(3)); + assert_eq!(plan.amount, 3 * NOTE - fee(3)); + assert_eq!( + plan.total_debited(), + plan.total_input, + "a sweep leaves no change" + ); + // The spend run with the plan's amount selects exactly the planned notes. + let (selected, total, selected_fee) = select_notes_with_fee( + ¬es, + plan.amount, + SPEND_MIN_ACTIONS, + ShieldedFeeKind::Base, + platform_version, + ) + .expect("selects"); + let mut nullifiers: Vec<[u8; 32]> = selected.iter().map(|n| n.nullifier).collect(); + nullifiers.sort_unstable(); + assert_eq!( + (nullifiers, total, selected_fee), + (plan.nullifiers, plan.total_input, plan.fee) + ); + } + + /// One transition spends at most `max_shielded_transition_actions` notes: a sweep of 17 + /// equal notes sweeps 16 of them. + #[test] + fn should_sweep_no_more_notes_than_one_transition_spends() { + let platform_version = PlatformVersion::latest(); + let max = usize::from( + platform_version + .system_limits + .max_shielded_transition_actions, + ); + let notes: Vec = (0..=max as u64).map(|i| test_note(NOTE, i)).collect(); + + for kind in [ + ShieldedSpendKind::Transfer, + ShieldedSpendKind::Unshield, + ShieldedSpendKind::Withdrawal, + ShieldedSpendKind::IdentityTopUp, + ] { + let plan = plan_spend(¬es, kind, ShieldedSpendAmount::Sweep, platform_version) + .expect("plans"); + let fee = kind.fee_kind().compute(max, platform_version).expect("fee"); + assert_eq!(plan.note_count(), max, "{kind:?}"); + assert_eq!(plan.fee, fee, "{kind:?}"); + assert_eq!(plan.amount, max as u64 * NOTE - fee, "{kind:?}"); + } + } + + /// An exact amount the notes cover only with more notes than one transition spends is + /// refused, by the selection every spend runs and by planning alike; one that fits is not. + #[test] + fn should_refuse_an_amount_that_needs_more_notes_than_one_transition_spends() { + let platform_version = PlatformVersion::latest(); + let max = usize::from( + platform_version + .system_limits + .max_shielded_transition_actions, + ); + let notes: Vec = (0..=max as u64).map(|i| test_note(NOTE, i)).collect(); + let too_many = max as u64 * NOTE; + + for kind in [ + ShieldedSpendKind::Transfer, + ShieldedSpendKind::Unshield, + ShieldedSpendKind::Withdrawal, + ShieldedSpendKind::IdentityTopUp, + ] { + let planned = plan_spend( + ¬es, + kind, + ShieldedSpendAmount::Exact(too_many), + platform_version, + ); + assert!( + matches!( + planned, + Err(PlatformWalletError::ShieldedSpendTooManyNotes { needed, max: limit }) + if needed == max + 1 && limit == max + ), + "{kind:?}: got {planned:?}" + ); + let selected = select_notes_with_fee( + ¬es, + too_many, + SPEND_MIN_ACTIONS, + kind.fee_kind(), + platform_version, + ); + assert!( + matches!( + selected, + Err(PlatformWalletError::ShieldedSpendTooManyNotes { .. }) + ), + "{kind:?}: got {:?}", + selected.map(|(notes, ..)| notes.len()) + ); + + let fits = plan_spend( + ¬es, + kind, + ShieldedSpendAmount::Exact((max as u64 - 1) * NOTE), + platform_version, + ) + .expect("fits one transition"); + assert_eq!(fits.note_count(), max, "{kind:?}"); + } + } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index 937116323bd..cfb0b448241 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -1505,7 +1505,7 @@ pub async fn identity_top_up_from_pool( amount: u64, prover: &P, ) -> Result, PlatformWalletError> { - identity_top_up_from_pool_with_metadata( + identity_top_up_from_pool_with_plan( sdk, store, persister, @@ -1518,6 +1518,36 @@ pub async fn identity_top_up_from_pool( None, ) .await +} + +/// [`identity_top_up_from_pool`] against a plan, refused as [`transfer_with_plan`] is when it +/// moved. +#[allow(clippy::too_many_arguments)] +pub async fn identity_top_up_from_pool_with_plan( + sdk: &Arc, + store: &Arc>, + persister: Option<&WalletPersister>, + wallet_id: WalletId, + keys: &OrchardKeySet, + account: u32, + identity_id: Identifier, + amount: u64, + prover: &P, + expected_plan: Option<&[u8; 32]>, +) -> Result, PlatformWalletError> { + identity_top_up_from_pool_with_metadata( + sdk, + store, + persister, + wallet_id, + keys, + account, + identity_id, + amount, + prover, + expected_plan, + ) + .await .map(|(result, _)| result) } @@ -1541,13 +1571,15 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< let change_addr = default_orchard_address(&views)?; let id = SubwalletId::new(wallet_id, account); + // One protocol version selects, checks the plan and builds: the SDK's may move meanwhile. + let platform_version = sdk.version(); let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( - sdk, store, id, amount, ShieldedSpendKind::IdentityTopUp, expected_plan, + platform_version, ) .await?; @@ -1577,13 +1609,12 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< anchor, prover, [0u8; 36], - sdk.version(), + platform_version, ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - debug_assert_eq!( - fee_used, exact_fee, - "builder fee must match the reserved identity top up fee" - ); + // Built at the version the notes were selected and the plan checked at, the fee is + // the selected one; refuse anything else before it is broadcast. + ensure_built_fee(fee_used, exact_fee, selected_notes.len(), expected_plan)?; pending_entry = record_pending_activity( store, @@ -2295,21 +2326,23 @@ pub async fn unshield_with_plan( let change_addr = default_orchard_address(&views)?; let id = SubwalletId::new(wallet_id, account); + // One protocol version selects, checks the plan and builds: the SDK's may move meanwhile. + let platform_version = sdk.version(); // Reserve against the 2-action floor: Orchard's BundleType::DEFAULT pads single-spend // bundles to 2 actions, and the builder prices the fee at spends.len().max(2). Reserving // for 1 would under-fee a single-note transition and the builder would reject it locally. // Unshield is carved with `compute_shielded_unshield_fee` (the base fee PLUS the flat storage // cost of the single `AddBalanceToAddress` write crediting the net to the output address), so // reserve against `ShieldedFeeKind::Unshield` — reserving the base fee here would under-fund the - // address-write cost and the builder would reject the spend (and the `fee_used == exact_fee` - // debug assert below would fire). + // address-write cost and the builder would reject the spend (and the built-fee check below + // would refuse it). let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( - sdk, store, id, amount, ShieldedSpendKind::Unshield, expected_plan, + platform_version, ) .await?; @@ -2351,15 +2384,12 @@ pub async fn unshield_with_plan( anchor, prover, [0u8; 36], - sdk.version(), + platform_version, ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - // The builder's fee and the wallet's reserved `exact_fee` both come from - // compute_shielded_unshield_fee with the same action count; lock that they agree. - debug_assert_eq!( - fee_used, exact_fee, - "builder fee must match the reserved unshield fee" - ); + // Built at the version the notes were selected and the plan checked at, the fee is + // the selected one; refuse anything else before it is broadcast. + ensure_built_fee(fee_used, exact_fee, selected_notes.len(), expected_plan)?; // Live activity: a confirmed Unshield is `direction out`, // counterparty = the 21-byte serialized PlatformAddress, exact @@ -2511,15 +2541,17 @@ pub async fn transfer_with_plan( let change_addr = default_orchard_address(&views)?; let id = SubwalletId::new(wallet_id, account); + // One protocol version selects, checks the plan and builds: the SDK's may move meanwhile. + let platform_version = sdk.version(); // ShieldedTransfer is carved with the base `compute_minimum_shielded_fee`, so reserve // against `ShieldedFeeKind::Base`. let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( - sdk, store, id, amount, ShieldedSpendKind::Transfer, expected_plan, + platform_version, ) .await?; @@ -2553,15 +2585,12 @@ pub async fn transfer_with_plan( anchor, prover, memo, - sdk.version(), + platform_version, ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - // The builder's fee and the wallet's reserved `exact_fee` both come from - // compute_minimum_shielded_fee with the same action count; lock that they agree. - debug_assert_eq!( - fee_used, exact_fee, - "builder fee must match the reserved minimum fee" - ); + // Built at the version the notes were selected and the plan checked at, the fee is + // the selected one; refuse anything else before it is broadcast. + ensure_built_fee(fee_used, exact_fee, selected_notes.len(), expected_plan)?; // Live activity: a confirmed transfer is a `Sent` (direction out), // counterparty = the recipient's 43-byte raw Orchard address, memo @@ -2703,21 +2732,23 @@ pub async fn withdraw_with_plan( let id = SubwalletId::new(wallet_id, account); let output_script = CoreScript::from_bytes(to_address.script_pubkey().to_bytes()); + // One protocol version selects, checks the plan and builds: the SDK's may move meanwhile. + let platform_version = sdk.version(); // Reserve against the 2-action floor: Orchard's BundleType::DEFAULT pads single-spend // bundles to 2 actions, and the builder prices the fee at spends.len().max(2). Reserving // for 1 would under-fee a single-note transition and the builder would reject it locally. // ShieldedWithdrawal is carved with `compute_shielded_withdrawal_fee` (the base fee PLUS the // flat Core withdrawal-document storage cost), so reserve against // `ShieldedFeeKind::Withdrawal` — reserving the base fee here would under-fund the document - // cost and the builder would reject the spend (and the `fee_used == exact_fee` debug assert - // below would fire). + // cost and the builder would reject the spend (and the built-fee check below would refuse + // it). let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( - sdk, store, id, amount, ShieldedSpendKind::Withdrawal, expected_plan, + platform_version, ) .await?; @@ -2759,15 +2790,12 @@ pub async fn withdraw_with_plan( anchor, prover, [0u8; 36], - sdk.version(), + platform_version, ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - // The builder's fee and the wallet's reserved `exact_fee` both come from - // compute_shielded_withdrawal_fee with the same action count; lock that they agree. - debug_assert_eq!( - fee_used, exact_fee, - "builder fee must match the reserved withdrawal fee" - ); + // Built at the version the notes were selected and the plan checked at, the fee is + // the selected one; refuse anything else before it is broadcast. + ensure_built_fee(fee_used, exact_fee, selected_notes.len(), expected_plan)?; // Live activity: a Withdrawal (direction out), counterparty = the // Core output script bytes, exact metered fee. @@ -3611,28 +3639,54 @@ async fn mark_notes_spent( /// /// With `expected_plan`, a selection that does not match that [`ShieldedSpendPlan::digest`] /// is refused with [`PlatformWalletError::ShieldedPlanChanged`] before any note is reserved. +/// +/// `platform_version` is the version the spend captured once: it selects here, checks the plan +/// and builds the transition at it, so an SDK whose version moves meanwhile cannot change the fee. async fn reserve_unspent_notes( - sdk: &Arc, store: &Arc>, id: SubwalletId, amount: u64, kind: ShieldedSpendKind, expected_plan: Option<&[u8; 32]>, + platform_version: &PlatformVersion, ) -> Result<(Vec, u64, u64, NoteReservation), PlatformWalletError> { // All amount-based spends reject zero before waiting on a concurrent sync's store lock. ensure_positive_amount(amount)?; reserve_notes_matching( - sdk, store, id, amount, SPEND_MIN_ACTIONS, kind.fee_kind(), expected_plan.map(|digest| (kind, digest)), + platform_version, ) .await } +/// Refuse, before it is broadcast, a built spend whose fee is not `selected_fee`, the fee its +/// `note_count` notes were selected (and, with `expected_plan`, confirmed) for: with a plan as +/// [`PlatformWalletError::ShieldedPlanChanged`], without one as a build error. +fn ensure_built_fee( + built_fee: Credits, + selected_fee: Credits, + note_count: usize, + expected_plan: Option<&[u8; 32]>, +) -> Result<(), PlatformWalletError> { + if built_fee == selected_fee { + return Ok(()); + } + Err(match expected_plan { + Some(_) => PlatformWalletError::ShieldedPlanChanged { + fresh_fee: built_fee, + fresh_note_count: note_count, + }, + None => PlatformWalletError::ShieldedBuildError(format!( + "the built fee {built_fee} is not the selected fee {selected_fee}" + )), + }) +} + /// Plan a `kind` spend of `amount` from `account`'s notes: the notes the spend would select /// now and their exact fee ([`note_selection::plan_spend`](super::note_selection::plan_spend)). /// Reads the store only; nothing is reserved. @@ -3666,30 +3720,45 @@ async fn reserve_notes_covering( outputs: usize, fee_kind: ShieldedFeeKind, ) -> Result<(Vec, u64, u64, NoteReservation), PlatformWalletError> { - reserve_notes_matching(sdk, store, id, amount, outputs, fee_kind, None).await + reserve_notes_matching(store, id, amount, outputs, fee_kind, None, sdk.version()).await } /// [`reserve_notes_covering`], refusing with [`PlatformWalletError::ShieldedPlanChanged`], /// before any note is reserved, a selection that does not match `expected_plan`: the plan -/// digest of a spend of that kind. +/// digest of a spend of that kind. With a plan, a selection the notes can no longer make (they +/// were spent or reserved since, or no longer cover it) is a changed plan too. +#[allow(clippy::too_many_arguments)] async fn reserve_notes_matching( - sdk: &Arc, store: &Arc>, id: SubwalletId, amount: u64, outputs: usize, fee_kind: ShieldedFeeKind, expected_plan: Option<(ShieldedSpendKind, &[u8; 32])>, + platform_version: &PlatformVersion, ) -> Result<(Vec, u64, u64, NoteReservation), PlatformWalletError> { let mut guard = store.write().await; let unspent = guard .get_unspent_notes(id) .map_err(|e| PlatformWalletError::ShieldedStoreError(e.to_string()))?; - let (selected, total_input, exact_fee) = - select_notes_with_fee(&unspent, amount, outputs, fee_kind, sdk.version())?.into_owned(); + let selection = + match select_notes_with_fee(&unspent, amount, outputs, fee_kind, platform_version) { + Err( + PlatformWalletError::ShieldedNoUnspentNotes + | PlatformWalletError::ShieldedInsufficientBalance { .. }, + ) if expected_plan.is_some() => { + return Err(PlatformWalletError::ShieldedPlanChanged { + fresh_fee: 0, + fresh_note_count: 0, + }) + } + other => other?, + }; if let Some((kind, expected)) = expected_plan { - ensure_plan_holds(expected, kind, amount, exact_fee, total_input, &selected)?; + let (selected, total_input, exact_fee) = &selection; + ensure_plan_holds(expected, kind, amount, *exact_fee, *total_input, selected)?; } + let (selected, total_input, exact_fee) = selection.into_owned(); let reservation = mark_notes_pending(&mut *guard, store, id, &selected)?; Ok((selected, total_input, exact_fee, reservation)) } @@ -8426,12 +8495,12 @@ mod spend_plan_tests { let plan = plan(&store, amount).await; let (selected, total_input, fee, reservation) = reserve_unspent_notes( - &sdk(), &store, ID, amount, ShieldedSpendKind::Transfer, Some(&plan.digest), + PlatformVersion::latest(), ) .await .expect("the plan holds"); @@ -8471,12 +8540,12 @@ mod spend_plan_tests { let before = unspent(&store).await; let refused = reserve_unspent_notes( - &sdk(), &store, ID, amount, ShieldedSpendKind::Transfer, Some(&plan.digest), + PlatformVersion::latest(), ) .await; @@ -8523,8 +8592,8 @@ mod spend_plan_tests { let held = transfer(plan.digest).await; assert!( - !matches!(held, Err(PlatformWalletError::ShieldedPlanChanged { .. })), - "a plan that holds proceeds, got {held:?}" + matches!(held, Err(PlatformWalletError::Sdk(_))), + "an unchanged plan must reach the mocked anchor fetch, got {held:?}" ); store @@ -8539,4 +8608,173 @@ mod spend_plan_tests { ); assert_eq!(unspent(&store).await, 4, "nothing reserved"); } + + /// The spend selects and checks its plan at the protocol version it captured once, not at + /// whatever version the SDK reports by then: a plan made at a version whose fee differs + /// from the SDK's current one holds when the spend runs at that version. + #[tokio::test] + async fn should_check_the_plan_at_the_spends_captured_protocol_version() { + let captured = PlatformVersion::get(13).expect("v13"); + let notes: Vec = (0..13).map(|i| note(i, NOTE)).collect(); + let amount = 11 * NOTE + 1; + assert_ne!( + compute_minimum_shielded_fee(12, captured).expect("fee"), + compute_minimum_shielded_fee(12, sdk().version()).expect("fee"), + "the two versions price the spend differently" + ); + let store = store_with(¬es).await; + let plan = super::super::note_selection::plan_spend( + ¬es, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Exact(amount), + captured, + ) + .expect("plans"); + + let (_, _, fee, reservation) = reserve_unspent_notes( + &store, + ID, + amount, + ShieldedSpendKind::Transfer, + Some(&plan.digest), + captured, + ) + .await + .expect("the plan holds at the captured version"); + + assert_eq!(fee, plan.fee); + reservation.cancel().await; + } + + /// A built transition whose fee is not the planned one is refused before broadcast as a + /// changed plan; without a plan, as a build error. The planned fee passes. + #[test] + fn should_refuse_a_built_fee_other_than_the_planned_one() { + let digest = [7; 32]; + ensure_built_fee(500, 500, 3, Some(&digest)).expect("the planned fee"); + ensure_built_fee(500, 500, 3, None).expect("the selected fee"); + assert!( + matches!( + ensure_built_fee(510, 500, 3, Some(&digest)), + Err(PlatformWalletError::ShieldedPlanChanged { + fresh_fee: 510, + fresh_note_count: 3 + }) + ), + "a planned spend" + ); + assert!( + matches!( + ensure_built_fee(510, 500, 3, None), + Err(PlatformWalletError::ShieldedBuildError(_)) + ), + "an unplanned spend" + ); + } + + /// With a plan, notes another spend took or a balance that no longer covers it are a + /// changed plan, not a failed selection; without one the selection errors stay. + #[tokio::test] + async fn should_report_an_exhausted_selection_as_a_changed_plan() { + let amount = 4 * NOTE + 1; + for (left, unplanned) in [(0, "no unspent notes"), (2, "insufficient balance")] { + let store = store_with(&(0..6).map(|i| note(i, NOTE)).collect::>()).await; + let plan = plan(&store, amount).await; + for position in left..6u8 { + store + .write() + .await + .mark_spent(ID, &[position; 32]) + .expect("spent"); + } + let reserve = |expected: Option<[u8; 32]>| { + let store = Arc::clone(&store); + async move { + reserve_unspent_notes( + &store, + ID, + amount, + ShieldedSpendKind::Transfer, + expected.as_ref(), + PlatformVersion::latest(), + ) + .await + .map(|(selected, ..)| selected.len()) + } + }; + + let planned = reserve(Some(plan.digest)).await; + assert!( + matches!( + planned, + Err(PlatformWalletError::ShieldedPlanChanged { .. }) + ), + "{unplanned} with a plan: got {planned:?}" + ); + let bare = reserve(None).await; + assert!( + matches!( + bare, + Err(PlatformWalletError::ShieldedNoUnspentNotes + | PlatformWalletError::ShieldedInsufficientBalance { .. }) + ), + "{unplanned} without a plan: got {bare:?}" + ); + } + } + + /// The public identity top-up runs against a plan as the other spends do: an unchanged + /// plan reaches the mocked anchor fetch, a moved one is refused with nothing reserved. + #[tokio::test] + async fn should_run_a_public_identity_top_up_against_its_plan() { + let keys = OrchardKeySet::from_seed(&[0x42; 64], Network::Testnet, 0).expect("keys"); + let store = store_with(&(0..3).map(|i| note(i, NOTE)).collect::>()).await; + let amount = NOTE; + let plan = plan_spend( + &sdk(), + &store, + WALLET_ID, + 0, + ShieldedSpendKind::IdentityTopUp, + ShieldedSpendAmount::Exact(amount), + ) + .await + .expect("plans"); + let top_up = |expected: [u8; 32]| { + let (store, keys) = (Arc::clone(&store), &keys); + async move { + identity_top_up_from_pool_with_plan( + &sdk(), + &store, + None, + WALLET_ID, + keys, + 0, + Identifier::new([5; 32]), + amount, + &UnreachableProver, + Some(&expected), + ) + .await + } + }; + + let held = top_up(plan.digest).await; + assert!( + matches!(held, Err(PlatformWalletError::Sdk(_))), + "an unchanged plan must reach the mocked anchor fetch, got {held:?}" + ); + + store + .write() + .await + .save_note(ID, ¬e(9, 10 * NOTE)) + .expect("a note"); + let moved = top_up(plan.digest).await; + assert!( + matches!(moved, Err(PlatformWalletError::ShieldedPlanChanged { .. })), + "got {moved:?}" + ); + assert_eq!(unspent(&store).await, 4, "nothing reserved"); + } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 7fd7b4b66c3..0bc0cab4359 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -806,10 +806,29 @@ extension PlatformWalletManager { /// included): it may already be on chain or may still execute, so the /// caller must NOT retry (the spent notes stay reserved Rust-side /// until a later shielded sync resolves them). - /// - /// With `plan` (from `shieldedPlanSpend`), the spend runs exactly that - /// plan or throws `PlatformWalletError.shieldedPlanChanged`, with nothing - /// reserved or sent, when the wallet's notes no longer select it. + public func shieldedTransfer( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32 = 0, + recipientRaw43: Data, + amount: UInt64, + memo: String? = nil + ) async throws { + try await spendShieldedTransfer( + walletId: walletId, + resolver: resolver, + account: account, + recipientRaw43: recipientRaw43, + amount: amount, + memo: memo, + plan: nil + ) + } + + /// `shieldedTransfer` against a plan from `shieldedPlanSpend`: the spend runs + /// exactly that plan or throws `PlatformWalletError.shieldedPlanChanged`, + /// with nothing reserved or sent, when the wallet's notes no longer + /// select it. public func shieldedTransfer( walletId: Data, resolver: MnemonicResolver, @@ -817,7 +836,27 @@ extension PlatformWalletManager { recipientRaw43: Data, amount: UInt64, memo: String? = nil, - plan: ShieldedSpendPlan? = nil + plan: ShieldedSpendPlan + ) async throws { + try await spendShieldedTransfer( + walletId: walletId, + resolver: resolver, + account: account, + recipientRaw43: recipientRaw43, + amount: amount, + memo: memo, + plan: plan + ) + } + + private func spendShieldedTransfer( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32, + recipientRaw43: Data, + amount: UInt64, + memo: String?, + plan: ShieldedSpendPlan? ) async throws { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( @@ -1226,17 +1265,52 @@ extension PlatformWalletManager { /// included): it may already be on chain or may still execute, so the /// caller must NOT retry (the spent notes stay reserved Rust-side /// until a later shielded sync resolves them). - /// - /// With `plan` (from `shieldedPlanSpend`), the spend runs exactly that - /// plan or throws `PlatformWalletError.shieldedPlanChanged`, with nothing - /// reserved or sent, when the wallet's notes no longer select it. public func shieldedUnshield( walletId: Data, resolver: MnemonicResolver, account: UInt32 = 0, toPlatformAddress: String, + amount: UInt64 + ) async throws { + try await spendShieldedUnshield( + walletId: walletId, + resolver: resolver, + account: account, + toPlatformAddress: toPlatformAddress, + amount: amount, + plan: nil + ) + } + + /// `shieldedUnshield` against a plan from `shieldedPlanSpend`: the spend runs + /// exactly that plan or throws `PlatformWalletError.shieldedPlanChanged`, + /// with nothing reserved or sent, when the wallet's notes no longer + /// select it. + public func shieldedUnshield( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32 = 0, + toPlatformAddress: String, + amount: UInt64, + plan: ShieldedSpendPlan + ) async throws { + try await spendShieldedUnshield( + walletId: walletId, + resolver: resolver, + account: account, + toPlatformAddress: toPlatformAddress, + amount: amount, + plan: plan + ) + } + + private func spendShieldedUnshield( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32, + toPlatformAddress: String, amount: UInt64, - plan: ShieldedSpendPlan? = nil + plan: ShieldedSpendPlan? ) async throws { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( @@ -1302,17 +1376,52 @@ extension PlatformWalletManager { /// included): it may already be on chain or may still execute, so the /// caller must NOT retry (the spent notes stay reserved Rust-side /// until a later shielded sync resolves them). - /// - /// With `plan` (from `shieldedPlanSpend`), the spend runs exactly that - /// plan or throws `PlatformWalletError.shieldedPlanChanged`, with nothing - /// reserved or sent, when the wallet's notes no longer select it. + public func shieldedIdentityTopUpFromPool( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32 = 0, + identityId: Data, + amount: UInt64 + ) async throws { + try await spendShieldedIdentityTopUpFromPool( + walletId: walletId, + resolver: resolver, + account: account, + identityId: identityId, + amount: amount, + plan: nil + ) + } + + /// `shieldedIdentityTopUpFromPool` against a plan from `shieldedPlanSpend`: the spend runs + /// exactly that plan or throws `PlatformWalletError.shieldedPlanChanged`, + /// with nothing reserved or sent, when the wallet's notes no longer + /// select it. public func shieldedIdentityTopUpFromPool( walletId: Data, resolver: MnemonicResolver, account: UInt32 = 0, identityId: Data, amount: UInt64, - plan: ShieldedSpendPlan? = nil + plan: ShieldedSpendPlan + ) async throws { + try await spendShieldedIdentityTopUpFromPool( + walletId: walletId, + resolver: resolver, + account: account, + identityId: identityId, + amount: amount, + plan: plan + ) + } + + private func spendShieldedIdentityTopUpFromPool( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32, + identityId: Data, + amount: UInt64, + plan: ShieldedSpendPlan? ) async throws { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( @@ -1380,10 +1489,29 @@ extension PlatformWalletManager { /// included): it may already be on chain or may still execute, so the /// caller must NOT retry (the spent notes stay reserved Rust-side /// until a later shielded sync resolves them). - /// - /// With `plan` (from `shieldedPlanSpend`), the spend runs exactly that - /// plan or throws `PlatformWalletError.shieldedPlanChanged`, with nothing - /// reserved or sent, when the wallet's notes no longer select it. + public func shieldedWithdraw( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32 = 0, + toCoreAddress: String, + amount: UInt64, + coreFeePerByte: UInt32 = 1 + ) async throws { + try await spendShieldedWithdraw( + walletId: walletId, + resolver: resolver, + account: account, + toCoreAddress: toCoreAddress, + amount: amount, + coreFeePerByte: coreFeePerByte, + plan: nil + ) + } + + /// `shieldedWithdraw` against a plan from `shieldedPlanSpend`: the spend runs + /// exactly that plan or throws `PlatformWalletError.shieldedPlanChanged`, + /// with nothing reserved or sent, when the wallet's notes no longer + /// select it. public func shieldedWithdraw( walletId: Data, resolver: MnemonicResolver, @@ -1391,7 +1519,27 @@ extension PlatformWalletManager { toCoreAddress: String, amount: UInt64, coreFeePerByte: UInt32 = 1, - plan: ShieldedSpendPlan? = nil + plan: ShieldedSpendPlan + ) async throws { + try await spendShieldedWithdraw( + walletId: walletId, + resolver: resolver, + account: account, + toCoreAddress: toCoreAddress, + amount: amount, + coreFeePerByte: coreFeePerByte, + plan: plan + ) + } + + private func spendShieldedWithdraw( + walletId: Data, + resolver: MnemonicResolver, + account: UInt32, + toCoreAddress: String, + amount: UInt64, + coreFeePerByte: UInt32, + plan: ShieldedSpendPlan? ) async throws { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index 1d00305d326..9820fadfec5 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -326,6 +326,10 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// different notes or a different fee than the plan, as the wallet's /// notes changed since. Nothing was reserved, built or broadcast. case errorShieldedPlanChanged = 77 + /// The wallet's notes cover a shielded spend, or its plan, only with more + /// notes than one shielded transition spends. Nothing was reserved, built + /// or broadcast: a smaller amount fits, or the notes can be merged first. + case errorShieldedSpendTooManyNotes = 78 /// 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. @@ -479,6 +483,8 @@ public enum PlatformWalletResultCode: Int32, Sendable { self = .errorPublicContactRequestUnconfirmed case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_PLAN_CHANGED: self = .errorShieldedPlanChanged + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_SPEND_TOO_MANY_NOTES: + self = .errorShieldedSpendTooManyNotes case PLATFORM_WALLET_FFI_RESULT_CODE_NOT_FOUND: self = .notFound case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_UNKNOWN: @@ -754,6 +760,11 @@ public enum PlatformWalletError: LocalizedError { /// since (code 77). Nothing was reserved, built or broadcast: plan again /// and confirm the new fee before spending. case shieldedPlanChanged(String) + /// The wallet's notes cover a shielded spend, or its plan, only with more + /// notes than one shielded transition spends (code 78). Nothing was + /// reserved, built or broadcast: a smaller amount fits, or the notes can + /// be merged first. + case shieldedSpendTooManyNotes(String) case walletAlreadyExists(String) /// Definitive shielded-broadcast failure: the shielded transition never /// left the wallet (refused before anything was sent), so it cannot @@ -988,6 +999,7 @@ public enum PlatformWalletError: LocalizedError { .privateContactRecoveryUnsupported(let m), .privateContactStoreNotRead(let m), .sdkPinnedBelowProtocolVersion(let m), .publicContactRequestUnconfirmed(let m), .shieldedPlanChanged(let m), + .shieldedSpendTooManyNotes(let m), .walletAlreadyExists(let m), .shieldedBroadcastFailed(let m), .shieldedBroadcastUnconfirmed(let m), .shieldedSpendUnconfirmed(let m), .shieldedNoRecordedAnchor(let m), .shieldedInsufficientBalance(let m), @@ -1127,6 +1139,8 @@ public enum PlatformWalletError: LocalizedError { self = .publicContactRequestUnconfirmed(detail) case .errorShieldedPlanChanged: self = .shieldedPlanChanged(detail) + case .errorShieldedSpendTooManyNotes: + self = .shieldedSpendTooManyNotes(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 a4d8beca63a..b6a72fa539e 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -620,6 +620,22 @@ final class ErrorHandlingTests: XCTestCase { XCTAssertEqual(message, detail) } + /// A spend the notes cover only with more notes than one transition spends + /// keeps its own code and typed case, apart from a balance shortfall (41). + func testShouldReportAShieldedSpendOfTooManyNotesByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_SPEND_TOO_MANY_NOTES + ) + XCTAssertEqual(code, .errorShieldedSpendTooManyNotes) + XCTAssertEqual(code.rawValue, 78) + let detail = "Shielded spend needs 17 notes, more than the 16 one transition can spend" + guard case .shieldedSpendTooManyNotes(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed too-many-notes error") + } + XCTAssertEqual(message, detail) + } + func testShouldReadEveryFieldOfThePrivateContactReadiness() { var ffi = PrivateContactReadinessFFI() ffi.private_payments_restored = false diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift index 8323d1d89f4..216ac356014 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift @@ -129,6 +129,54 @@ final class ShieldedSpendPlanTests: XCTestCase { await manager.shutdown() } + // MARK: - Source compatibility + + /// The spends keep their signatures from before plans, so method references to them still + /// resolve; spending against a plan is a separate overload taking an explicit plan. + func testShouldKeepTheOriginalSpendSignaturesBesidePlanOverloads() async { + let manager = makeManager() + let transfer: (Data, MnemonicResolver, UInt32, Data, UInt64, String?) async throws -> Void = + manager.shieldedTransfer(walletId:resolver:account:recipientRaw43:amount:memo:) + let unshield: (Data, MnemonicResolver, UInt32, String, UInt64) async throws -> Void = + manager.shieldedUnshield(walletId:resolver:account:toPlatformAddress:amount:) + let topUp: (Data, MnemonicResolver, UInt32, Data, UInt64) async throws -> Void = + manager.shieldedIdentityTopUpFromPool(walletId:resolver:account:identityId:amount:) + let withdraw: (Data, MnemonicResolver, UInt32, String, UInt64, UInt32) async throws -> Void = + manager.shieldedWithdraw(walletId:resolver:account:toCoreAddress:amount:coreFeePerByte:) + let planned: [Any] = [ + manager.shieldedTransfer(walletId:resolver:account:recipientRaw43:amount:memo:plan:) + as (Data, MnemonicResolver, UInt32, Data, UInt64, String?, ShieldedSpendPlan) + async throws -> Void, + manager.shieldedUnshield(walletId:resolver:account:toPlatformAddress:amount:plan:) + as (Data, MnemonicResolver, UInt32, String, UInt64, ShieldedSpendPlan) + async throws -> Void, + manager.shieldedIdentityTopUpFromPool(walletId:resolver:account:identityId:amount:plan:) + as (Data, MnemonicResolver, UInt32, Data, UInt64, ShieldedSpendPlan) + async throws -> Void, + manager.shieldedWithdraw( + walletId:resolver:account:toCoreAddress:amount:coreFeePerByte:plan:) + as (Data, MnemonicResolver, UInt32, String, UInt64, UInt32, ShieldedSpendPlan) + async throws -> Void + ] + XCTAssertEqual(planned.count, 4) + + // The originals still reach the FFI with no plan. + let resolver = MnemonicResolver() + await assertThrows("transfer", Self.isInvalidHandle) { + try await transfer(Self.walletId, resolver, 0, Data(repeating: 1, count: 43), 1, nil) + } + await assertThrows("unshield", Self.isInvalidHandle) { + try await unshield(Self.walletId, resolver, 0, "tdash1x", 1) + } + await assertThrows("top up", Self.isInvalidHandle) { + try await topUp(Self.walletId, resolver, 0, Data(repeating: 2, count: 32), 1) + } + await assertThrows("withdraw", Self.isInvalidHandle) { + try await withdraw(Self.walletId, resolver, 0, "yX", 1, 1) + } + await manager.shutdown() + } + // MARK: - Spending against a plan private func spends( From b1439deffcec5dde294170cdcc48cf2b8ccf6211 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 12:20:09 +0200 Subject: [PATCH 04/20] feat(dpp): add the most shielded actions one transition can carry max_shielded_actions_per_transition returns the smaller of max_shielded_transition_actions and the number of Orchard actions whose serialized transition fits max_state_transition_size. The size is a fixed part plus a per-action part, both measured on real serializations; the fixed part is the largest among the spend kinds and ShieldFromAssetLock. A test serializes transfer, unshield, withdrawal and identity top-up transitions at the bound (fit) and one action above it (do not fit). Co-Authored-By: Claude Opus 5.5 --- .../src/shielded/builder/max_actions_tests.rs | 127 ++++++++++++++++++ packages/rs-dpp/src/shielded/builder/mod.rs | 3 + .../shielded/max_actions_per_transition.rs | 34 +++++ packages/rs-dpp/src/shielded/mod.rs | 2 + .../signing_tests.rs | 10 +- 5 files changed, 174 insertions(+), 2 deletions(-) create mode 100644 packages/rs-dpp/src/shielded/builder/max_actions_tests.rs create mode 100644 packages/rs-dpp/src/shielded/max_actions_per_transition.rs diff --git a/packages/rs-dpp/src/shielded/builder/max_actions_tests.rs b/packages/rs-dpp/src/shielded/builder/max_actions_tests.rs new file mode 100644 index 00000000000..a0041e3e17e --- /dev/null +++ b/packages/rs-dpp/src/shielded/builder/max_actions_tests.rs @@ -0,0 +1,127 @@ +use super::test_helpers::{test_orchard_address, test_spendable_note, TestProver}; +use super::*; +use crate::address_funds::PlatformAddress; +use crate::identity::core_script::CoreScript; +use crate::serialization::PlatformSerializable; +use crate::shielded::max_shielded_actions_per_transition; +use crate::state_transition::StateTransition; +use crate::withdrawal::Pooling; +use grovedb_commitment_tree::{ + Anchor, ExtractedNoteCommitment, FullViewingKey, SpendAuthorizingKey, SpendingKey, +}; +use platform_value::Identifier; +use platform_version::version::PlatformVersion; + +const NOTE_VALUE: u64 = 100_000_000_000; + +fn keys() -> (FullViewingKey, SpendAuthorizingKey) { + let sk = SpendingKey::from_bytes([42u8; 32]).expect("valid spending key bytes"); + (FullViewingKey::from(&sk), SpendAuthorizingKey::from(&sk)) +} + +fn notes(count: usize) -> Vec { + (0..count) + .map(|_| test_spendable_note(NOTE_VALUE)) + .collect() +} + +fn anchor() -> Anchor { + let note = test_spendable_note(NOTE_VALUE); + note.merkle_path + .root(ExtractedNoteCommitment::from(note.note.commitment())) +} + +fn size(st: &StateTransition) -> usize { + st.serialize_to_bytes().expect("serialize").len() +} + +/// The serialized size of each kind of shielded spend with `actions` spent notes (one action +/// per note), keyed by kind. +fn spend_sizes(actions: usize) -> Vec<(&'static str, usize)> { + let pv = PlatformVersion::latest(); + let (fvk, ask) = keys(); + let addr = test_orchard_address(); + let (transfer, _) = build_shielded_transfer_transition( + notes(actions), + &addr, + 1_000, + &addr, + &fvk, + &ask, + anchor(), + &TestProver, + [0u8; 36], + pv, + ) + .expect("transfer"); + let (unshield, _) = build_unshield_transition( + notes(actions), + PlatformAddress::P2pkh([1u8; 20]), + 1_000, + &addr, + &fvk, + &ask, + anchor(), + &TestProver, + [0u8; 36], + pv, + ) + .expect("unshield"); + let (withdrawal, _) = build_shielded_withdrawal_transition( + notes(actions), + 1_000_000, + CoreScript::new_p2pkh([1u8; 20]), + 1, + Pooling::Never, + &addr, + &fvk, + &ask, + anchor(), + &TestProver, + [0u8; 36], + pv, + ) + .expect("withdrawal"); + let (top_up, _) = build_identity_top_up_from_shielded_pool_transition( + notes(actions), + Identifier::new([3u8; 32]), + 1_000, + &addr, + &fvk, + &ask, + anchor(), + &TestProver, + [0u8; 36], + pv, + ) + .expect("top up"); + vec![ + ("transfer", size(&transfer)), + ("unshield", size(&unshield)), + ("withdrawal", size(&withdrawal)), + ("identity top up", size(&top_up)), + ] +} + +/// The helper's action count fits `max_state_transition_size` in real serializations of every +/// shielded spend kind, and one action more does not fit any of them. +#[test] +fn should_bound_the_actions_of_every_spend_kind_by_the_transition_size_limit() { + let pv = PlatformVersion::latest(); + let max_size = pv.system_limits.max_state_transition_size as usize; + let bound = usize::from(max_shielded_actions_per_transition(pv)); + + for (kind, bytes) in spend_sizes(bound) { + assert!( + bytes <= max_size, + "{kind}: {bound} actions serialize to {bytes} B, over the {max_size} B limit" + ); + } + for (kind, bytes) in spend_sizes(bound + 1) { + assert!( + bytes > max_size, + "{kind}: {} actions serialize to {bytes} B, which still fits the {max_size} B limit", + bound + 1 + ); + } +} diff --git a/packages/rs-dpp/src/shielded/builder/mod.rs b/packages/rs-dpp/src/shielded/builder/mod.rs index 86a165614a0..2076ebaff8d 100644 --- a/packages/rs-dpp/src/shielded/builder/mod.rs +++ b/packages/rs-dpp/src/shielded/builder/mod.rs @@ -521,6 +521,9 @@ pub(crate) mod test_helpers { } } +#[cfg(test)] +mod max_actions_tests; + #[cfg(test)] mod mod_tests { use super::test_helpers::{test_orchard_address, test_spendable_note, TestProver}; diff --git a/packages/rs-dpp/src/shielded/max_actions_per_transition.rs b/packages/rs-dpp/src/shielded/max_actions_per_transition.rs new file mode 100644 index 00000000000..43057490fb8 --- /dev/null +++ b/packages/rs-dpp/src/shielded/max_actions_per_transition.rs @@ -0,0 +1,34 @@ +use platform_version::version::PlatformVersion; + +/// Bytes the Halo 2 proof and the action itself add to a serialized shielded transition for each +/// Orchard action. Measured on the serialized transitions: every extra action of a spend or +/// `ShieldFromAssetLock` transition adds exactly this much (2 actions 8,189 B, 3 actions +/// 10,870 B, 6 actions 18,913 B for a transfer). +const SHIELDED_ACTION_WIRE_SIZE: u64 = 2_681; + +/// Bytes of a serialized shielded transition that do not depend on its action count: the proof +/// base, the anchor, the binding signature and the transition's own fields. Measured for 2 actions: +/// transfer 2,827 B, unshield 2,848 B, withdrawal with a P2PKH script 2,855 B, identity top-up +/// 2,859 B, `ShieldFromAssetLock` 2,932 B (6 actions: 19,018 B). The constant is the largest of +/// these rounded up, so it holds for every kind and leaves room for a longer Core script. +const SHIELDED_TRANSITION_FIXED_WIRE_SIZE: u64 = 3_000; + +/// The most Orchard actions one shielded transition can carry on `platform_version`: the +/// smaller of `max_shielded_transition_actions` and the number of actions whose serialized +/// transition fits `max_state_transition_size`. A spend carries one action per note, so this is +/// also the most notes one spend can take. +/// +/// The size limit, not the action cap, binds today: with the 20 KiB limit 6 actions fit +/// (about 19 KB) and 7 do not (about 21.7 KB). The size of a transition is its fixed part plus +/// [`SHIELDED_ACTION_WIRE_SIZE`] per action, and the fixed part differs by a few dozen bytes +/// between the kinds, so the largest measured one is used for all of them. +pub fn max_shielded_actions_per_transition(platform_version: &PlatformVersion) -> u16 { + let limits = &platform_version.system_limits; + let fitting = limits + .max_state_transition_size + .saturating_sub(SHIELDED_TRANSITION_FIXED_WIRE_SIZE) + / SHIELDED_ACTION_WIRE_SIZE; + u16::try_from(fitting) + .unwrap_or(u16::MAX) + .min(limits.max_shielded_transition_actions) +} diff --git a/packages/rs-dpp/src/shielded/mod.rs b/packages/rs-dpp/src/shielded/mod.rs index 60805aa4a42..f5d4ff0dbc3 100644 --- a/packages/rs-dpp/src/shielded/mod.rs +++ b/packages/rs-dpp/src/shielded/mod.rs @@ -3,12 +3,14 @@ pub mod builder; mod compute_minimum_shielded_fee; mod identity_create_denomination; +mod max_actions_per_transition; pub mod memo; #[cfg(feature = "state-transitions")] mod sighash; use crate::util::hash::hash_single; pub use identity_create_denomination::is_allowed_identity_create_denomination; +pub use max_actions_per_transition::max_shielded_actions_per_transition; pub use memo::{ShieldedMemo, MEMO_PAYLOAD_SIZE, MEMO_SIZE}; use bincode::{Decode, DecodeUntrusted, Encode}; diff --git a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shield_from_asset_lock_transition/signing_tests.rs b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shield_from_asset_lock_transition/signing_tests.rs index 9ba80c940a9..b9411f606bd 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shield_from_asset_lock_transition/signing_tests.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shield_from_asset_lock_transition/signing_tests.rs @@ -297,8 +297,8 @@ async fn build_shield_from_asset_lock_transition_with_signer_end_to_end() { #[tokio::test] async fn seed_pool_batch_fits_max_state_transition_size() { - // The pool-seeding batch size (MAX_ACTIONS_PER_BATCH = 6 in - // rs-platform-wallet's seed_pool.rs) is bounded by the 20 KiB + // The pool-seeding batch size (`max_shielded_actions_per_transition`, + // 6 today) is bounded by the 20 KiB // transaction-size limit, not the 16-action consensus cap: the Halo 2 // proof grows ~2,681 bytes per action (measured: 2 actions → 8,294 B, // 6 → 19,018 B, 7 → 21,699 B — the last rejected by tenderdash's @@ -339,6 +339,12 @@ async fn seed_pool_batch_fits_max_state_transition_size() { max, ); + assert_eq!( + crate::shielded::max_shielded_actions_per_transition(platform_version), + 6, + "the seeding batch is the helper's bound", + ); + let v1 = extract_v1(st); assert_eq!( v1.actions.len(), From d87d16c3260adce8e71d1cd7f294831678e8f50f Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 12:20:09 +0200 Subject: [PATCH 05/20] fix(platform-wallet): bound shielded note selection by the state transition size Note selection capped a spend at max_shielded_transition_actions (16), but the 20 KiB max_state_transition_size fits only 6 actions, so plans of 7 to 16 notes were accepted and then rejected on submit. Exact and sweep selection now cap at the DPP size bound, and the pool seeding batch size uses the same helper instead of its own constant. Co-Authored-By: Claude Opus 5.5 --- .../wallet/shielded/fund_from_asset_lock.rs | 2 +- .../src/wallet/shielded/note_selection.rs | 91 +++++++++++++++---- .../src/wallet/shielded/operations.rs | 8 +- .../src/wallet/shielded/seed_pool.rs | 54 +++++------ 4 files changed, 100 insertions(+), 55 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs b/packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs index e0b03b89c03..bca4a752914 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs @@ -682,7 +682,7 @@ impl PlatformWallet { /// (`shield_from_asset_lock_num_actions(dummy_outputs)` — `2` for the /// classic single-output bundle, up to `6` for a pool-seeding batch /// (the 20 KiB `max_state_transition_size` cap, see - /// `MAX_ACTIONS_PER_BATCH` in `seed_pool.rs`; not the 16-action + /// `max_shielded_actions_per_transition` in dpp; not the 16-action /// consensus cap)). /// `asset_lock_base_cost` (`albc`) is the same constant Type 14 (address /// funding) uses, read from `dpp.state_transitions.identities.asset_locks` diff --git a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs index a7bbc1b922f..5bc30a21023 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs @@ -11,7 +11,7 @@ use dpp::shielded::{ compute_minimum_shielded_fee, compute_private_document_create_from_shielded_pool_fee, compute_shielded_identity_create_fee, compute_shielded_identity_top_up_fee, compute_shielded_unshield_fee, compute_shielded_withdrawal_fee, - is_allowed_identity_create_denomination, + is_allowed_identity_create_denomination, max_shielded_actions_per_transition, }; use dpp::version::PlatformVersion; use dpp::ProtocolError; @@ -170,7 +170,7 @@ pub fn select_notes( /// the largest-first prefixes are tried in turn and the first whose sum covers `amount` plus the /// fee for its own action count (at least `min_actions`) is selected. /// -/// One transition spends at most `max_shielded_transition_actions` notes: an amount that only +/// One transition spends at most [`max_shielded_actions_per_transition`] notes: an amount that only /// more notes than that would cover is refused with /// [`PlatformWalletError::ShieldedSpendTooManyNotes`]. /// @@ -239,13 +239,10 @@ fn spendable_largest_first( Ok(sorted) } -/// How many notes one shielded transition spends at most: one action per note. +/// How many notes one shielded transition spends at most: one action per note, as many as fit +/// the transition size limit. fn max_notes_per_transition(platform_version: &PlatformVersion) -> usize { - usize::from( - platform_version - .system_limits - .max_shielded_transition_actions, - ) + usize::from(max_shielded_actions_per_transition(platform_version)) } /// The most a sweep of `unspent` can send: over the largest-first prefixes one transition can @@ -1164,16 +1161,12 @@ mod tests { ); } - /// One transition spends at most `max_shielded_transition_actions` notes: a sweep of 17 - /// equal notes sweeps 16 of them. + /// One transition spends at most `max_shielded_actions_per_transition` notes: a sweep of + /// one note more sweeps that many. #[test] fn should_sweep_no_more_notes_than_one_transition_spends() { let platform_version = PlatformVersion::latest(); - let max = usize::from( - platform_version - .system_limits - .max_shielded_transition_actions, - ); + let max = usize::from(max_shielded_actions_per_transition(platform_version)); let notes: Vec = (0..=max as u64).map(|i| test_note(NOTE, i)).collect(); for kind in [ @@ -1196,11 +1189,7 @@ mod tests { #[test] fn should_refuse_an_amount_that_needs_more_notes_than_one_transition_spends() { let platform_version = PlatformVersion::latest(); - let max = usize::from( - platform_version - .system_limits - .max_shielded_transition_actions, - ); + let max = usize::from(max_shielded_actions_per_transition(platform_version)); let notes: Vec = (0..=max as u64).map(|i| test_note(NOTE, i)).collect(); let too_many = max as u64 * NOTE; @@ -1250,4 +1239,66 @@ mod tests { assert_eq!(fits.note_count(), max, "{kind:?}"); } } + + /// The 20 KiB transition-size limit, not the action cap, bounds a spend: an amount that + /// needs 7 notes is refused with a maximum of 6. + #[test] + fn should_refuse_an_amount_that_needs_more_notes_than_fit_the_transition_size() { + let platform_version = PlatformVersion::latest(); + let notes: Vec = (0..10).map(|i| test_note(NOTE, i)).collect(); + + for kind in [ + ShieldedSpendKind::Transfer, + ShieldedSpendKind::Unshield, + ShieldedSpendKind::Withdrawal, + ShieldedSpendKind::IdentityTopUp, + ] { + let planned = plan_spend( + ¬es, + kind, + ShieldedSpendAmount::Exact(6 * NOTE), + platform_version, + ); + assert!( + matches!( + planned, + Err(PlatformWalletError::ShieldedSpendTooManyNotes { needed: 7, max: 6 }) + ), + "{kind:?}: got {planned:?}" + ); + let selected = select_notes_with_fee( + ¬es, + 6 * NOTE, + SPEND_MIN_ACTIONS, + kind.fee_kind(), + platform_version, + ); + assert!( + matches!( + selected, + Err(PlatformWalletError::ShieldedSpendTooManyNotes { needed: 7, max: 6 }) + ), + "{kind:?}: got {:?}", + selected.map(|(notes, ..)| notes.len()) + ); + } + } + + /// A sweep of 10 equal notes plans the 6 that fit one transition. + #[test] + fn should_sweep_no_more_notes_than_fit_the_transition_size() { + let platform_version = PlatformVersion::latest(); + let notes: Vec = (0..10).map(|i| test_note(NOTE, i)).collect(); + + for kind in [ + ShieldedSpendKind::Transfer, + ShieldedSpendKind::Unshield, + ShieldedSpendKind::Withdrawal, + ShieldedSpendKind::IdentityTopUp, + ] { + let plan = plan_spend(¬es, kind, ShieldedSpendAmount::Sweep, platform_version) + .expect("plans"); + assert_eq!(plan.note_count(), 6, "{kind:?}"); + } + } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index cfb0b448241..7920b74ddea 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -8615,11 +8615,11 @@ mod spend_plan_tests { #[tokio::test] async fn should_check_the_plan_at_the_spends_captured_protocol_version() { let captured = PlatformVersion::get(13).expect("v13"); - let notes: Vec = (0..13).map(|i| note(i, NOTE)).collect(); - let amount = 11 * NOTE + 1; + let notes: Vec = (0..6).map(|i| note(i, NOTE)).collect(); + let amount = 4 * NOTE + 1; assert_ne!( - compute_minimum_shielded_fee(12, captured).expect("fee"), - compute_minimum_shielded_fee(12, sdk().version()).expect("fee"), + compute_minimum_shielded_fee(5, captured).expect("fee"), + compute_minimum_shielded_fee(5, sdk().version()).expect("fee"), "the two versions price the spend differently" ); let store = store_with(¬es).await; diff --git a/packages/rs-platform-wallet/src/wallet/shielded/seed_pool.rs b/packages/rs-platform-wallet/src/wallet/shielded/seed_pool.rs index 2cfbf32e171..6e8b1c81e0d 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/seed_pool.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/seed_pool.rs @@ -12,10 +12,9 @@ //! it submits a series of `ShieldFromAssetLock` (Type 18) transitions, //! each carrying one real note to the wallet's own default shielded //! address plus up to 5 **zero-value anonymity-set filler** outputs -//! (`dummy_outputs`). Each batch publishes up to 6 Orchard actions — NOT -//! the 16-action consensus cap (`max_shielded_transition_actions`), but -//! the most that fits the 20 KiB transaction-size limit; see -//! [`MAX_ACTIONS_PER_BATCH`]. Inbound transitions (Type 15 Shield, Type +//! (`dummy_outputs`). Each batch publishes as many Orchard actions as fit +//! the 20 KiB transaction-size limit (6 today), not the 16-action consensus +//! cap (`max_shielded_transition_actions`); see [`max_actions_per_batch`]. Inbound transitions (Type 15 Shield, Type //! 18 ShieldFromAssetLock) are NOT subject to the 250-note minimum, so //! seeding runs against an empty pool. //! @@ -31,6 +30,8 @@ use dash_sdk::platform::transition::put_settings::PutSettings; use dash_sdk::platform::types::shielded::fetch_shielded_notes_count; use dpp::address_funds::OrchardAddress; use dpp::balances::credits::CREDITS_PER_DUFF; +use dpp::shielded::max_shielded_actions_per_transition; +use dpp::version::PlatformVersion; use crate::wallet::asset_lock::orchestration::{AssetLockFunding, CL_FALLBACK_TIMEOUT}; use crate::wallet::shielded::fund_from_asset_lock::shield_from_asset_lock_num_actions; @@ -38,20 +39,15 @@ use crate::wallet::shielded::CachedOrchardProver; use crate::wallet::PlatformWallet; use crate::PlatformWalletError; -/// Maximum Orchard actions per seeding batch. -/// -/// The binding constraint is NOT the 16-action consensus cap -/// (`max_shielded_transition_actions`) but the 20 KiB transaction-size -/// limit (`system_limits.max_state_transition_size`, mirrored by -/// tenderdash's `mempool.max-tx-bytes = 20480`): the Halo 2 proof grows -/// with the action count, ~2,681 bytes per action on the wire. Measured -/// serialized `ShieldFromAssetLock` sizes (signing_tests size probe): -/// 2 actions → 8,294 B, 6 → 19,018 B, 7 → 21,699 B (rejected by -/// tenderdash as "Tx too large"). 6 actions is the largest batch that -/// fits, with ~1.4 KiB headroom for asset-lock-proof variants. Pinned by -/// `seed_pool_batch_fits_max_state_transition_size` in dpp's -/// shield_from_asset_lock signing tests. -const MAX_ACTIONS_PER_BATCH: usize = 6; +/// Maximum Orchard actions per seeding batch: the most actions one shielded transition carries +/// on `platform_version`, which is bounded by the transition size limit +/// (`system_limits.max_state_transition_size`, mirrored by tenderdash's +/// `mempool.max-tx-bytes = 20480`) and not by the consensus action cap, because the Halo 2 +/// proof grows with the action count. See [`max_shielded_actions_per_transition`] for the +/// measured sizes. +fn max_actions_per_batch(platform_version: &PlatformVersion) -> u64 { + u64::from(max_shielded_actions_per_transition(platform_version)) +} /// Default total pool-note target. Matches the consensus 250-note /// anonymity-set minimum the seeding exists to satisfy. @@ -104,7 +100,7 @@ pub struct SeedPoolOutcome { impl PlatformWallet { /// Seed the shielded pool up to `target_total_notes` by submitting a /// series of `ShieldFromAssetLock` (Type 18) batches, each adding up - /// to [`MAX_ACTIONS_PER_BATCH`] notes (1 real + up to 5 zero-value + /// to [`max_actions_per_batch`] notes (1 real + up to 5 zero-value /// anonymity-set fillers). /// /// Devnet/testnet-only: hard-errors on `Network::Mainnet` (the mainnet @@ -182,11 +178,9 @@ impl PlatformWallet { )) })?; - let batches_total_estimate = estimate_batches( - start_notes, - target_total_notes, - MAX_ACTIONS_PER_BATCH as u64, - ); + let max_batch_actions = max_actions_per_batch(sdk.version()); + let batches_total_estimate = + estimate_batches(start_notes, target_total_notes, max_batch_actions); // Already satisfied — nothing to do. if start_notes >= target_total_notes { @@ -222,8 +216,7 @@ impl PlatformWallet { // Notes this batch adds: 1 real + `dummy_outputs` fillers, // capped at the per-transition action limit. On the final // stretch, only add as many as still needed. - let notes_this_batch = - std::cmp::min(remaining, MAX_ACTIONS_PER_BATCH as u64).max(1) as usize; + let notes_this_batch = std::cmp::min(remaining, max_batch_actions).max(1) as usize; // `notes_this_batch` includes the real note; the rest are // fillers. (`max(1, ..)` above guarantees `>= 1`.) let dummy_outputs = notes_this_batch - 1; @@ -373,7 +366,7 @@ impl PlatformWallet { } } -/// Estimate the number of [`MAX_ACTIONS_PER_BATCH`]-note batches needed to +/// Estimate the number of [`max_actions_per_batch`]-note batches needed to /// move the pool count from `current` to `target`, given `per_batch` notes /// per batch. Returns `0` when already at/above target. Pure arithmetic so /// it can be unit-tested without a wallet/SDK. @@ -406,10 +399,10 @@ mod tests { #[test] fn batch_size_math_matches_action_count() { // The loop computes notes_this_batch = - // min(remaining, MAX_ACTIONS_PER_BATCH).max(1), dummy_outputs = + // min(remaining, max_actions_per_batch).max(1), dummy_outputs = // notes_this_batch - 1, and the on-wire action count must equal // max(1 + dummy_outputs, 2). Verify the coupling across the - // boundary cases the loop hits (MAX_ACTIONS_PER_BATCH == 6). + // boundary cases the loop hits (max_actions_per_batch == 6). for (remaining, expected_notes, expected_actions) in [ (250u64, 6usize, 6usize), // full batch (6, 6, 6), // exactly a full batch @@ -418,7 +411,8 @@ mod tests { (1, 1, 2), // 1 real, 0 fillers -> Orchard MIN_ACTIONS=2 ] { let notes_this_batch = - std::cmp::min(remaining, MAX_ACTIONS_PER_BATCH as u64).max(1) as usize; + std::cmp::min(remaining, max_actions_per_batch(PlatformVersion::latest())).max(1) + as usize; assert_eq!(notes_this_batch, expected_notes, "remaining={remaining}"); let dummy_outputs = notes_this_batch - 1; assert_eq!( From be3bb2e635c4afb6fa42a7aa8745f9d2dadaa7f4 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 12:30:29 +0200 Subject: [PATCH 06/20] fix(platform-wallet): refuse a shielded spend when the protocol version moved during the anchor fetch The anchor fetch that precedes the build can teach the SDK a newer protocol version, while the notes were selected and the plan checked at the version the spend captured. After the fetch, transfer, unshield, withdrawal and identity top-up now compare the SDK's version with the captured one through one shared check and refuse before building, recording activity or broadcasting. With a plan the refusal is ShieldedPlanChanged carrying the fee at the new version; without one it is a build error naming both versions. The note reservation is released as for any other build error. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/shielded/note_selection.rs | 2 +- .../src/wallet/shielded/operations.rs | 261 +++++++++++++++++- 2 files changed, 260 insertions(+), 3 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs index 5bc30a21023..e579b0f2e82 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs @@ -65,7 +65,7 @@ pub enum ShieldedFeeKind { impl ShieldedFeeKind { /// Compute the flat shielded fee for `num_actions` under this transition's formula. - fn compute( + pub(super) fn compute( self, num_actions: usize, platform_version: &PlatformVersion, diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index 7920b74ddea..cad27bf2e70 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -1597,6 +1597,13 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< let result = async { let (spends, anchor, anchor_height) = extract_spends_and_recorded_anchor(sdk, store, &selected_notes).await?; + ensure_version_unchanged( + sdk, + platform_version, + ShieldedSpendKind::IdentityTopUp.fee_kind(), + selected_notes.len(), + expected_plan, + )?; let anchor_bytes = anchor.to_bytes(); let (state_transition, fee_used) = build_identity_top_up_from_shielded_pool_transition( @@ -2367,6 +2374,13 @@ pub async fn unshield_with_plan( let result = async { let (spends, anchor, anchor_height) = extract_spends_and_recorded_anchor(sdk, store, &selected_notes).await?; + ensure_version_unchanged( + sdk, + platform_version, + ShieldedSpendKind::Unshield.fee_kind(), + selected_notes.len(), + expected_plan, + )?; // Capture the recorded anchor before the builder consumes it, so a // broadcast-accepted-but-unconfirmed spend can be auto-released once // this anchor is pruned from Platform's recorded set. @@ -2568,6 +2582,13 @@ pub async fn transfer_with_plan( let result = async { let (spends, anchor, anchor_height) = extract_spends_and_recorded_anchor(sdk, store, &selected_notes).await?; + ensure_version_unchanged( + sdk, + platform_version, + ShieldedSpendKind::Transfer.fee_kind(), + selected_notes.len(), + expected_plan, + )?; // Capture the recorded anchor before the builder consumes it, so a // broadcast-accepted-but-unconfirmed spend can be auto-released once // this anchor is pruned from Platform's recorded set. @@ -2770,6 +2791,13 @@ pub async fn withdraw_with_plan( let result = async { let (spends, anchor, anchor_height) = extract_spends_and_recorded_anchor(sdk, store, &selected_notes).await?; + ensure_version_unchanged( + sdk, + platform_version, + ShieldedSpendKind::Withdrawal.fee_kind(), + selected_notes.len(), + expected_plan, + )?; // Capture the recorded anchor before the builder consumes it, so a // broadcast-accepted-but-unconfirmed spend can be auto-released once // this anchor is pruned from Platform's recorded set. @@ -3664,6 +3692,38 @@ async fn reserve_unspent_notes( .await } +/// Refuse a spend, before anything is built, saved or broadcast, when the SDK's protocol +/// version is no longer `platform_version`, the one the spend captured to select its notes +/// and check its plan: the anchor fetch that precedes the build can teach the SDK a newer +/// one, and the fee shown and confirmed was priced at the old. With `expected_plan` the +/// refusal is [`PlatformWalletError::ShieldedPlanChanged`] carrying the fee at the new +/// version for the same notes; without one, a build error naming both versions. +fn ensure_version_unchanged( + sdk: &Arc, + platform_version: &PlatformVersion, + fee_kind: ShieldedFeeKind, + note_count: usize, + expected_plan: Option<&[u8; 32]>, +) -> Result<(), PlatformWalletError> { + let current = sdk.version(); + if current.protocol_version == platform_version.protocol_version { + return Ok(()); + } + if expected_plan.is_none() { + return Err(PlatformWalletError::ShieldedBuildError(format!( + "the protocol version moved from {} to {} while the spend was prepared", + platform_version.protocol_version, current.protocol_version + ))); + } + let fresh_fee = fee_kind + .compute(note_count.max(SPEND_MIN_ACTIONS), current) + .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; + Err(PlatformWalletError::ShieldedPlanChanged { + fresh_fee, + fresh_note_count: note_count, + }) +} + /// Refuse, before it is broadcast, a built spend whose fee is not `selected_fee`, the fee its /// `note_count` notes were selected (and, with `expected_plan`, confirmed) for: with a plan as /// [`PlatformWalletError::ShieldedPlanChanged`], without one as a build error. @@ -8159,7 +8219,7 @@ mod select_recorded_spends_tests { use grovedb_commitment_tree::{ExtractedNoteCommitment, Note, NoteValue, RandomSeed, Rho}; /// Unique temp path for a test tree (no `tempfile` dev-dep). - fn temp_tree_path(tag: &str) -> std::path::PathBuf { + pub(super) fn temp_tree_path(tag: &str) -> std::path::PathBuf { let nanos = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap() @@ -8183,7 +8243,7 @@ mod select_recorded_spends_tests { /// it, and `cmx` is the note's real extracted commitment so that appending /// `cmx` as the leaf at `position` makes `witness(position, d).root(cmx)` /// reproduce the tree's anchor at depth `d`. - fn real_note(position: u64) -> ShieldedNote { + pub(super) fn real_note(position: u64) -> ShieldedNote { let keys = OrchardKeySet::from_seed(&[0x42; 32], Network::Testnet, 0) .expect("ZIP-32 derivation from a fixed seed"); let recipient = keys.default_address; @@ -8777,4 +8837,201 @@ mod spend_plan_tests { ); assert_eq!(unspent(&store).await, 4, "nothing reserved"); } + + /// A spend whose version check is the only thing in its way: one real note in a real + /// tree, a plan made at protocol version 13, and a mocked anchor fetch whose answer + /// moves the SDK to the newest version. + struct VersionMovesDuringAnchorFetch { + sdk: Arc, + store: Arc>, + plan: ShieldedSpendPlan, + path: std::path::PathBuf, + } + + impl VersionMovesDuringAnchorFetch { + async fn new(kind: ShieldedSpendKind) -> Self { + use crate::wallet::shielded::file_store::FileBackedShieldedStore; + use dash_sdk::query_types::{NoParamQuery, ShieldedAnchors}; + + let path = select_recorded_spends_tests::temp_tree_path("version_moves"); + let mut store = FileBackedShieldedStore::open_path(&path, 100).expect("a store"); + let mut owned = select_recorded_spends_tests::real_note(0); + owned.value = 10 * NOTE; + store.append_commitment(&owned.cmx, true).expect("a leaf"); + store.checkpoint_tree(1).expect("a checkpoint"); + let anchor = store.tree_anchor().expect("an anchor"); + store.save_note(ID, &owned).expect("a note"); + let store = Arc::new(RwLock::new(store)); + + let mut sdk = dash_sdk::SdkBuilder::new_mock() + .with_initial_version(PlatformVersion::get(13).expect("v13")) + .build() + .expect("a mock SDK"); + assert_eq!(sdk.protocol_version_number(), 13, "the spend starts at v13"); + sdk.mock() + .expect_fetch(NoParamQuery {}, Some(ShieldedAnchors(vec![anchor]))) + .await + .expect("the anchor answer"); + let sdk = Arc::new(sdk); + let plan = plan_spend( + &sdk, + &store, + WALLET_ID, + 0, + kind, + ShieldedSpendAmount::Exact(NOTE), + ) + .await + .expect("plans"); + Self { + sdk, + store, + plan, + path, + } + } + + async fn run( + &self, + kind: ShieldedSpendKind, + expected_plan: Option<&[u8; 32]>, + ) -> Result<(), PlatformWalletError> { + let keys = OrchardKeySet::from_seed(&[0x42; 64], Network::Testnet, 0).expect("keys"); + let (sdk, store) = (&self.sdk, &self.store); + match kind { + ShieldedSpendKind::Transfer => { + transfer_with_plan( + sdk, + store, + None, + WALLET_ID, + &keys, + 0, + &keys.default_address, + NOTE, + [0; 36], + &UnreachableProver, + expected_plan, + ) + .await + } + ShieldedSpendKind::Unshield => { + unshield_with_plan( + sdk, + store, + None, + WALLET_ID, + &keys, + 0, + &PlatformAddress::P2pkh([9; 20]), + NOTE, + &UnreachableProver, + expected_plan, + ) + .await + } + ShieldedSpendKind::Withdrawal => { + withdraw_with_plan( + sdk, + store, + None, + WALLET_ID, + &keys, + 0, + &dashcore::Address::dummy(Network::Testnet, 1), + NOTE, + 1, + &UnreachableProver, + expected_plan, + ) + .await + } + ShieldedSpendKind::IdentityTopUp => identity_top_up_from_pool_with_plan( + sdk, + store, + None, + WALLET_ID, + &keys, + 0, + Identifier::new([5; 32]), + NOTE, + &UnreachableProver, + expected_plan, + ) + .await + .map(|_| ()), + } + } + } + + /// The network's protocol version advances while the spend fetches the recorded anchors + /// (the SDK learns it from that answer): every spend kind refuses before it builds, saves + /// activity or broadcasts, as a changed plan priced at the new version when it had a plan + /// and as a build error when it had none, and leaves its note unreserved. + #[tokio::test] + async fn should_refuse_a_spend_when_the_protocol_version_moved_during_the_anchor_fetch() { + for kind in [ + ShieldedSpendKind::Transfer, + ShieldedSpendKind::Unshield, + ShieldedSpendKind::Withdrawal, + ShieldedSpendKind::IdentityTopUp, + ] { + for planned in [true, false] { + let case = VersionMovesDuringAnchorFetch::new(kind).await; + let refused = case.run(kind, planned.then_some(&case.plan.digest)).await; + + assert_eq!( + case.sdk.protocol_version_number(), + PlatformVersion::latest().protocol_version, + "the anchor fetch moved the version ({kind:?})" + ); + let fresh = plan_spend( + &case.sdk, + &case.store, + WALLET_ID, + 0, + kind, + ShieldedSpendAmount::Exact(NOTE), + ) + .await + .expect("plans at the new version"); + assert_ne!(fresh.fee, case.plan.fee, "the fee moved ({kind:?})"); + match (planned, &refused) { + ( + true, + Err(PlatformWalletError::ShieldedPlanChanged { + fresh_fee, + fresh_note_count, + }), + ) => assert_eq!( + (*fresh_fee, *fresh_note_count), + (fresh.fee, fresh.note_count()), + "{kind:?}" + ), + (false, Err(PlatformWalletError::ShieldedBuildError(message))) => { + assert!( + message.contains("13") + && message.contains( + &PlatformVersion::latest().protocol_version.to_string() + ), + "the build error names both versions: {message}" + ) + } + _ => panic!("{kind:?} planned={planned}: got {refused:?}"), + } + let guard = case.store.read().await; + assert_eq!( + guard.get_unspent_notes(ID).expect("notes").len(), + 1, + "the note is released ({kind:?})" + ); + assert!( + guard.get_activity_ids(ID).expect("activity").is_empty(), + "no activity row ({kind:?})" + ); + drop(guard); + let _ = std::fs::remove_file(&case.path); + } + } + } } From bdabbbd9060687df1d64422fc909642ffc63c35e Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 13:13:52 +0200 Subject: [PATCH 07/20] fix(platform-wallet): plan a shielded withdrawal with its Core fee A shielded withdrawal plan now carries the Core fee rate: the rate is part of the plan digest, the plan reports the recipient amount (the Core reserve minus the Core fee from protocol 14), and exact and sweep amounts are checked against the protocol minimum (with the Core fee) and maximum before a plan is returned. A sweep is capped at the maximum so it stays executable. Running a withdrawal against a plan with another rate is refused as a changed plan, and an out-of-range amount is refused before any note is reserved, with a new typed error (FFI code 79) mirrored in Swift and Kotlin. The FFI and Swift plan APIs take the rate and return the recipient amount. Co-Authored-By: Claude Opus 5.5 --- .../dashsdk/errors/DashSdkError.kt | 13 +- .../dashsdk/errors/DashSdkErrorTest.kt | 16 + .../ERROR_CODE_REGISTRY.md | 6 +- packages/rs-platform-wallet-ffi/src/error.rs | 11 +- .../src/shielded_send.rs | 57 ++- .../src/shielded_types.rs | 6 +- packages/rs-platform-wallet/src/error.rs | 8 +- .../src/wallet/shielded/note_selection.rs | 349 +++++++++++++++--- .../src/wallet/shielded/operations.rs | 34 +- .../PlatformWalletManagerShieldedSync.swift | 29 +- .../PlatformWallet/PlatformWalletResult.swift | 14 +- .../ErrorHandlingTests.swift | 16 + .../ShieldedSpendPlanTests.swift | 23 +- 13 files changed, 496 insertions(+), 86 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 edc856f1f88..7ab25f657e0 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 @@ -810,13 +810,23 @@ sealed class DashSdkError( * `ErrorShieldedSpendTooManyNotes` (native code 78). The wallet's * notes cover a shielded spend, or its plan, only with more notes * than one shielded transition spends - * (`max_shielded_transition_actions`). Nothing was reserved, built or + * (`max_shielded_actions_per_transition`). Nothing was reserved, built or * broadcast: a smaller amount fits, or the notes can be merged first. * ← Swift `PlatformWalletError.shieldedSpendTooManyNotes`. */ class ShieldedSpendTooManyNotes(message: String, cause: Throwable? = null) : PlatformWallet(message, cause) + /** + * `ErrorShieldedWithdrawalAmountOutOfRange` (native code 79). A + * shielded withdrawal, or its plan, reserves an amount for Core below + * the protocol minimum for its Core fee rate or above the maximum. + * Nothing was reserved, built or broadcast: another amount fits. + * ← Swift `PlatformWalletError.shieldedWithdrawalAmountOutOfRange`. + */ + class ShieldedWithdrawalAmountOutOfRange(message: String, cause: Throwable? = null) : + PlatformWallet(message, cause) + /** * Any other `PlatformWalletFFIResultCode` without a dedicated type. * Carries the platform-wallet [nativeCode] (already de-offset) and @@ -1028,6 +1038,7 @@ sealed class DashSdkError( 76 -> PlatformWallet.PublicContactRequestUnconfirmed(message, cause) // ErrorPublicContactRequestUnconfirmed 77 -> PlatformWallet.ShieldedPlanChanged(message, cause) // ErrorShieldedPlanChanged 78 -> PlatformWallet.ShieldedSpendTooManyNotes(message, cause) // ErrorShieldedSpendTooManyNotes + 79 -> PlatformWallet.ShieldedWithdrawalAmountOutOfRange(message, cause) // ErrorShieldedWithdrawalAmountOutOfRange 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 ac3aaf7d290..d0a63f6897d 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 @@ -432,6 +432,22 @@ class DashSdkErrorTest { assertFalse("a smaller amount fits, not a retry", mapped.isRetryable) } + /** + * A shielded withdrawal amount outside the protocol bounds has its own + * code: nothing was sent, and another amount fits, so it is neither a + * retry nor a balance shortfall (41). + */ + @Test + fun shouldReportAWithdrawalAmountOutOfRangeByItsOwnCode() { + val detail = "Shielded withdrawal amount 1 is outside the allowed range 1000000 to 50000000000000" + val native = DashSDKException(DashSdkError.PLATFORM_WALLET_CODE_OFFSET + 79, detail) + val mapped = DashSdkError.fromNative(native) + assertTrue(mapped is DashSdkError.PlatformWallet.ShieldedWithdrawalAmountOutOfRange) + assertFalse(mapped is DashSdkError.PlatformWallet.PlatformShieldCapacityExceeded) + assertEquals(detail, mapped.message) + assertFalse("another amount fits, not a retry", mapped.isRetryable) + } + @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 c0091610dac..118e957146b 100644 --- a/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md +++ b/packages/rs-platform-wallet-ffi/ERROR_CODE_REGISTRY.md @@ -130,7 +130,8 @@ by open branches with no row here yet 63–66 the invitation-claim preflight, 67 `ErrorShieldedTreeInconsistent`); 68 to 76 proposed for DashPay private contact requests; 77 proposed for a shielded spend plan that changed; 78 proposed for a shielded spend of more -notes than one transition spends; 28, 30, +notes than one transition spends; 79 proposed for a shielded withdrawal amount +outside the protocol bounds; 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 @@ -195,7 +196,8 @@ Fork-era numbers remain in the collision history, which is immutable record. | 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 | `ErrorShieldedPlanChanged` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedPlanChanged`: a shielded spend run against a plan (`platform_wallet_manager_shielded_plan_spend`, then a `_with_plan` transfer, unshield, withdraw or identity top-up export) selected different notes or a different fee than the plan, as the wallet's notes changed since. Nothing was reserved, built or broadcast; plan again and confirm the new fee. Mapped by the blanket conversion and kept by `map_spend_result`. Swift types it (`PlatformWalletError.shieldedPlanChanged`, `ErrorHandlingTests` pin) and wraps the plan (`PlatformWalletManager.shieldedPlanSpend`, overloads of the four spends taking an explicit `plan:`, beside their unchanged originals); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedPlanChanged`, `DashSdkErrorTest` pin) with no JNI binding of the plan | -| 78 | `ErrorShieldedSpendTooManyNotes` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedSpendTooManyNotes`: the wallet's notes cover a shielded spend (transfer, unshield, withdrawal, identity top-up or private document create from the pool) or its plan (`platform_wallet_manager_shielded_plan_spend`) only with more notes than one shielded transition spends (`max_shielded_transition_actions`, 16). Nothing was reserved, built or broadcast; a smaller amount fits, or the notes can be merged first. Before, the selection took the notes anyway and Platform rejected the transition. Not a balance shortfall (41 is the Platform-address shield's capacity). Mapped by the blanket conversion and kept by `map_spend_result`. Swift types it (`PlatformWalletError.shieldedSpendTooManyNotes`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedSpendTooManyNotes`, `DashSdkErrorTest` pin) | +| 78 | `ErrorShieldedSpendTooManyNotes` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedSpendTooManyNotes`: the wallet's notes cover a shielded spend (transfer, unshield, withdrawal, identity top-up or private document create from the pool) or its plan (`platform_wallet_manager_shielded_plan_spend`) only with more notes than one shielded transition spends (`dpp::shielded::max_shielded_actions_per_transition`, 6 at protocol 14, bounded by the transition size). Nothing was reserved, built or broadcast; a smaller amount fits, or the notes can be merged first. Before, the selection took the notes anyway and Platform rejected the transition. Not a balance shortfall (41 is the Platform-address shield's capacity). Mapped by the blanket conversion and kept by `map_spend_result`. Swift types it (`PlatformWalletError.shieldedSpendTooManyNotes`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedSpendTooManyNotes`, `DashSdkErrorTest` pin) | +| 79 | `ErrorShieldedWithdrawalAmountOutOfRange` | Shielded spend plan | Proposed. Maps `PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`: a shielded withdrawal, or its plan (`platform_wallet_manager_shielded_plan_spend`, kind 2), reserves an amount for Core below the protocol minimum for its Core fee rate (`min_withdrawal_amount_with_core_fee` from protocol 14) or above `max_withdrawal_amount`. Nothing was reserved, built or broadcast; another amount fits. Mapped by the blanket conversion and kept by `map_spend_result`. Swift types it (`PlatformWalletError.shieldedWithdrawalAmountOutOfRange`, `ErrorHandlingTests` pin); Kotlin types it (`DashSdkError.PlatformWallet.ShieldedWithdrawalAmountOutOfRange`, `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 8486291e04e..ca63d0d9f78 100644 --- a/packages/rs-platform-wallet-ffi/src/error.rs +++ b/packages/rs-platform-wallet-ffi/src/error.rs @@ -778,11 +778,17 @@ pub enum PlatformWalletFFIResultCode { /// Maps `PlatformWalletError::ShieldedSpendTooManyNotes`: the wallet's /// notes cover a shielded spend (or its plan) only with more notes than - /// one shielded transition can spend (`max_shielded_transition_actions`). + /// one shielded transition can spend (`max_shielded_actions_per_transition`). /// Nothing was reserved, built or broadcast. A smaller amount fits, or the /// notes can be merged first. ErrorShieldedSpendTooManyNotes = 78, + /// Maps `PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`: a + /// shielded withdrawal (or its plan) reserves an amount for Core below the + /// protocol minimum for its Core fee rate or above the maximum. Nothing was + /// reserved, built or broadcast. Another amount fits. + ErrorShieldedWithdrawalAmountOutOfRange = 79, + /// The named thing does not exist. /// /// Originally (and still mostly) the code for every `Option` returned as an @@ -1123,6 +1129,9 @@ impl From for PlatformWalletFFIResult { PlatformWalletError::ShieldedSpendTooManyNotes { .. } => { PlatformWalletFFIResultCode::ErrorShieldedSpendTooManyNotes } + PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { .. } => { + PlatformWalletFFIResultCode::ErrorShieldedWithdrawalAmountOutOfRange + } // The core-transaction sibling of the shielded pair above: the // do-not-retry signal must survive the boundary as a typed code // so hosts can distinguish it from a definitive rejection. diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index e6926d37044..466a3d5ee87 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -262,11 +262,12 @@ pub unsafe extern "C" fn platform_wallet_shielded_estimate_fee( /// Map a spend `kind` byte, numbered as [`shielded_fee_formula`] numbers the /// spends' fee kinds, to the spend it plans; `None` for any other byte. -fn shielded_spend_kind(kind: u8) -> Option { +/// `core_fee_per_byte` is the Core fee rate of a withdrawal and read for it only. +fn shielded_spend_kind(kind: u8, core_fee_per_byte: u32) -> Option { match kind { 0 => Some(ShieldedSpendKind::Transfer), 1 => Some(ShieldedSpendKind::Unshield), - 2 => Some(ShieldedSpendKind::Withdrawal), + 2 => Some(ShieldedSpendKind::Withdrawal { core_fee_per_byte }), 4 => Some(ShieldedSpendKind::IdentityTopUp), _ => None, } @@ -278,10 +279,11 @@ impl From<&ShieldedSpendPlan> for ShieldedSpendPlanFFI { kind: match plan.kind { ShieldedSpendKind::Transfer => 0, ShieldedSpendKind::Unshield => 1, - ShieldedSpendKind::Withdrawal => 2, + ShieldedSpendKind::Withdrawal { .. } => 2, ShieldedSpendKind::IdentityTopUp => 4, }, amount: plan.amount, + recipient_amount: plan.recipient_amount, fee: plan.fee, total_input: plan.total_input, total_debited: plan.total_debited(), @@ -311,6 +313,14 @@ unsafe fn read_plan_digest(digest: *const u8) -> [u8; 32] { /// shield from an identity, spends no notes). With `sweep_all`, the spend /// sends every spendable note minus the fee for all of them, and `amount` must /// be `0`; otherwise it sends `amount` credits and the fee comes on top. +/// `core_fee_per_byte` is the Core fee rate of a withdrawal (kind `2`) and is +/// ignored for the other kinds. A withdrawal's `amount` is the reserve for +/// Core, of which the Core fee is taken: the plan's `recipient_amount` is what +/// reaches the Core address. The amount must lie within the protocol bounds +/// for that rate (a withdrawal sweep is capped at the maximum), else +/// `ErrorShieldedWithdrawalAmountOutOfRange`; a rate above the protocol cap +/// returns `ErrorWalletOperation`. Run the withdraw export with the same +/// rate: another rate refuses with `ErrorShieldedPlanChanged`. /// /// Writes the plan to `out_plan`. Run it with the spend's `_with_plan` export /// and the plan's `digest`, which refuses with `ErrorShieldedPlanChanged` @@ -333,12 +343,13 @@ pub unsafe extern "C" fn platform_wallet_manager_shielded_plan_spend( kind: u8, amount: u64, sweep_all: bool, + core_fee_per_byte: u32, out_plan: *mut ShieldedSpendPlanFFI, ) -> PlatformWalletFFIResult { check_ptr!(wallet_id_bytes); check_ptr!(out_plan); - let Some(kind) = shielded_spend_kind(kind) else { + let Some(kind) = shielded_spend_kind(kind, core_fee_per_byte) else { return PlatformWalletFFIResult::err( PlatformWalletFFIResultCode::ErrorInvalidParameter, format!("unknown shielded spend kind {kind} (expected 0/1/2/4)"), @@ -960,6 +971,9 @@ pub(crate) fn map_spend_result( // More notes than one transition spends: nothing was reserved or // built; a smaller amount fits. Err(e @ PlatformWalletError::ShieldedSpendTooManyNotes { .. }) => e.into(), + // A withdrawal amount outside the protocol bounds for its Core fee + // rate: nothing was reserved or built; another amount fits. + Err(e @ PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { .. }) => e.into(), // Retryable: the wallet couldn't build the spend against any // Platform-recorded anchor yet (its commitment tree is mid-block after // an index-chunk sync). Nothing was broadcast and the notes were @@ -3228,7 +3242,7 @@ mod tests { let mut out = ShieldedSpendPlanFFI::default(); let plan = |wallet_id: *const u8, kind: u8, amount: u64, sweep: bool, out| { platform_wallet_manager_shielded_plan_spend( - 0, wallet_id, 0, kind, amount, sweep, out, + 0, wallet_id, 0, kind, amount, sweep, 1, out, ) .code }; @@ -3266,13 +3280,19 @@ mod tests { for (kind, byte) in [ (ShieldedSpendKind::Transfer, 0), (ShieldedSpendKind::Unshield, 1), - (ShieldedSpendKind::Withdrawal, 2), + ( + ShieldedSpendKind::Withdrawal { + core_fee_per_byte: 5, + }, + 2, + ), (ShieldedSpendKind::IdentityTopUp, 4), ] { - assert_eq!(shielded_spend_kind(byte), Some(kind)); + assert_eq!(shielded_spend_kind(byte, 5), Some(kind)); let plan = ShieldedSpendPlan { kind, amount: 10, + recipient_amount: 7, fee: 3, total_input: 20, nullifiers: vec![[1; 32], [2; 32]], @@ -3283,6 +3303,7 @@ mod tests { ShieldedSpendPlanFFI { kind: byte, amount: 10, + recipient_amount: 7, fee: 3, total_input: 20, total_debited: 13, @@ -3385,6 +3406,28 @@ mod tests { assert_eq!(PlatformWalletFFIResult::from(too_many()).code as i32, 78); } + /// A withdrawal amount outside the protocol bounds keeps its own code through the spend + /// contract, the planning export and the blanket conversion alike. + #[test] + fn should_keep_a_withdrawal_amount_out_of_range_at_its_own_code() { + let out_of_range = || PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { + amount: 1, + min: 1_000_000, + max: 50_000_000_000_000, + }; + let result = map_spend_result(Err(out_of_range()), "shielded spend plan"); + assert_eq!( + result.code, + PlatformWalletFFIResultCode::ErrorShieldedWithdrawalAmountOutOfRange + ); + assert_eq!(result.code as i32, 79); + assert!(message_of(&result).contains("outside the allowed range")); + assert_eq!( + PlatformWalletFFIResult::from(out_of_range()).code as i32, + 79 + ); + } + /// A panic while planning is caught and reported as a failed read: planning reserves and /// sends nothing, so it is not the spend's do-not-retry contract. #[test] diff --git a/packages/rs-platform-wallet-ffi/src/shielded_types.rs b/packages/rs-platform-wallet-ffi/src/shielded_types.rs index 63c2a78eead..47cec607e6b 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_types.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_types.rs @@ -98,8 +98,12 @@ pub struct ShieldedShieldPreflightFFI { #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] pub struct ShieldedSpendPlanFFI { pub kind: u8, - /// What the recipient gets. + /// What the spend reserves for the recipient: the amount sent, or for a + /// withdrawal the reserve for Core, of which the Core fee is taken. pub amount: u64, + /// What the recipient receives: `amount`, except for a withdrawal from + /// protocol version 14, where it is `amount` minus the Core fee. + pub recipient_amount: u64, /// The exact fee for the selected notes. pub fee: u64, /// The sum of the selected notes. diff --git a/packages/rs-platform-wallet/src/error.rs b/packages/rs-platform-wallet/src/error.rs index e970cf841d9..216dc3f5ef3 100644 --- a/packages/rs-platform-wallet/src/error.rs +++ b/packages/rs-platform-wallet/src/error.rs @@ -1077,11 +1077,17 @@ pub enum PlatformWalletError { }, /// The notes cover the spend only with more notes than one shielded transition can spend - /// (`max_shielded_transition_actions`). Refused before any note was reserved or anything + /// (`max_shielded_actions_per_transition`). Refused before any note was reserved or anything /// built; a smaller amount, or merging notes first, fits. #[error("Shielded spend needs {needed} notes, more than the {max} one transition can spend")] ShieldedSpendTooManyNotes { needed: usize, max: usize }, + /// A shielded withdrawal's amount (the reserve for Core) is below the protocol minimum for + /// its Core fee rate or above the maximum. Refused before any note was reserved or anything + /// built; consensus would reject it after the proof. + #[error("Shielded withdrawal amount {amount} is outside the allowed range {min} to {max}")] + ShieldedWithdrawalAmountOutOfRange { amount: u64, min: u64, max: u64 }, + /// A Platform Payment-account shield cannot be represented from the /// wallet's deterministic address-input set at the requested amount. /// Distinct from [`ShieldedInsufficientBalance`](Self::ShieldedInsufficientBalance), diff --git a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs index e579b0f2e82..5c9f3d9c072 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs @@ -14,6 +14,9 @@ use dpp::shielded::{ is_allowed_identity_create_denomination, max_shielded_actions_per_transition, }; use dpp::version::PlatformVersion; +use dpp::withdrawal::{ + core_fee_in_credits, min_withdrawal_amount_with_core_fee, validate_core_fee_per_byte_cap, +}; use dpp::ProtocolError; use sha2::{Digest, Sha256}; @@ -301,8 +304,12 @@ pub enum ShieldedSpendKind { Transfer, /// Unshield to a Platform address. Unshield, - /// ShieldedWithdrawal to a Core address. - Withdrawal, + /// ShieldedWithdrawal to a Core address at a Core fee rate: the rate fixes what the Core + /// fee takes from the amount reserved for Core, so it is part of the plan. + Withdrawal { + /// The Core asset-unlock fee rate, in duffs per byte. + core_fee_per_byte: u32, + }, /// IdentityTopUpFromShieldedPool. IdentityTopUp, } @@ -313,7 +320,7 @@ impl ShieldedSpendKind { match self { ShieldedSpendKind::Transfer => ShieldedFeeKind::Base, ShieldedSpendKind::Unshield => ShieldedFeeKind::Unshield, - ShieldedSpendKind::Withdrawal => ShieldedFeeKind::Withdrawal, + ShieldedSpendKind::Withdrawal { .. } => ShieldedFeeKind::Withdrawal, ShieldedSpendKind::IdentityTopUp => ShieldedFeeKind::IdentityTopUp, } } @@ -322,7 +329,7 @@ impl ShieldedSpendKind { match self { ShieldedSpendKind::Transfer => 0, ShieldedSpendKind::Unshield => 1, - ShieldedSpendKind::Withdrawal => 2, + ShieldedSpendKind::Withdrawal { .. } => 2, ShieldedSpendKind::IdentityTopUp => 3, } } @@ -346,42 +353,110 @@ pub enum ShieldedSpendAmount { #[derive(Clone, Debug, PartialEq, Eq)] pub struct ShieldedSpendPlan { pub kind: ShieldedSpendKind, - /// What the recipient gets. + /// What the spend reserves for the recipient: the amount sent, or for a withdrawal the + /// reserve for Core, of which the Core fee is taken. pub amount: Credits, + /// What the recipient receives. The amount, except for a withdrawal from protocol version + /// 14, where it is the reserve minus the Core fee at the kind's rate. + pub recipient_amount: Credits, /// The exact fee for the selected notes. pub fee: Credits, /// The sum of the selected notes. pub total_input: Credits, /// The selected notes' nullifiers, sorted. pub nullifiers: Vec<[u8; 32]>, - /// Commits to the kind, the amount, the fee and the selected notes. + /// Commits to the kind (a withdrawal's Core fee rate too), the amount, the fee and the + /// selected notes. pub digest: [u8; 32], } +/// The digest a plan commits to. `nullifiers` must be sorted. +fn spend_digest( + kind: ShieldedSpendKind, + amount: Credits, + fee: Credits, + nullifiers: &[[u8; 32]], +) -> [u8; 32] { + let mut hasher = Sha256::new(); + hasher.update(b"shielded-spend-plan"); + hasher.update([kind.tag()]); + if let ShieldedSpendKind::Withdrawal { core_fee_per_byte } = kind { + hasher.update(core_fee_per_byte.to_le_bytes()); + } + hasher.update(amount.to_le_bytes()); + hasher.update(fee.to_le_bytes()); + for nullifier in nullifiers { + hasher.update(nullifier); + } + hasher.finalize().into() +} + +/// The bounds of a withdrawal's `reserve` for Core at `core_fee_per_byte`, from the DPP helpers +/// consensus validates with: `(minimum, maximum, Core fee)`. From protocol version 14 (the +/// versions that cap the Core fee rate) the Core fee is carved out of the reserve and the minimum +/// leaves the protocol floor above it; before, the fee is drawn from the Core credit pool on top +/// of the reserve, so the minimum is the floor and the fee is 0. A rate above the cap is refused, +/// as consensus refuses it. +fn withdrawal_bounds( + core_fee_per_byte: u32, + platform_version: &PlatformVersion, +) -> Result<(Credits, Credits, Credits), PlatformWalletError> { + let limits = &platform_version.system_limits; + if limits.max_core_fee_per_byte.is_none() { + return Ok(( + limits.min_withdrawal_amount, + limits.max_withdrawal_amount, + 0, + )); + } + let capped = validate_core_fee_per_byte_cap(core_fee_per_byte, platform_version); + if let Some(error) = capped.first_error() { + return Err(PlatformWalletError::ShieldedBuildError(error.to_string())); + } + let core_fee = core_fee_in_credits(core_fee_per_byte).ok_or_else(|| { + PlatformWalletError::ShieldedBuildError("the Core fee overflows credits".to_string()) + })?; + Ok(( + min_withdrawal_amount_with_core_fee(core_fee_per_byte, platform_version), + limits.max_withdrawal_amount, + core_fee, + )) +} + +/// Refuse a withdrawal `amount` (the reserve for Core) outside what the protocol accepts at +/// `core_fee_per_byte`, as [`PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`]. Returns +/// what the recipient receives. Store-free, so callers can run it before reserving any note. +pub(crate) fn ensure_withdrawal_amount_in_range( + amount: Credits, + core_fee_per_byte: u32, + platform_version: &PlatformVersion, +) -> Result { + let (min, max, core_fee) = withdrawal_bounds(core_fee_per_byte, platform_version)?; + if amount < min || amount > max { + return Err(PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { amount, min, max }); + } + // In range, so at least the minimum, which is above the Core fee. + Ok(amount - core_fee) +} + impl ShieldedSpendPlan { fn new( kind: ShieldedSpendKind, amount: Credits, + recipient_amount: Credits, fee: Credits, total_input: Credits, mut nullifiers: Vec<[u8; 32]>, ) -> Self { nullifiers.sort_unstable(); - let mut hasher = Sha256::new(); - hasher.update(b"shielded-spend-plan"); - hasher.update([kind.tag()]); - hasher.update(amount.to_le_bytes()); - hasher.update(fee.to_le_bytes()); - for nullifier in &nullifiers { - hasher.update(nullifier); - } Self { kind, amount, + recipient_amount, fee, total_input, + digest: spend_digest(kind, amount, fee, &nullifiers), nullifiers, - digest: hasher.finalize().into(), } } @@ -401,7 +476,13 @@ impl ShieldedSpendPlan { /// ([`select_notes_with_fee`] at [`SPEND_MIN_ACTIONS`]) and their exact fee. /// /// A [`ShieldedSpendAmount::Sweep`] sends the most the notes one transition can spend send after -/// their fee ([`sweep_amount`]); the plan selects exactly those notes. +/// their fee ([`sweep_amount`]); the plan selects exactly those notes. A withdrawal sweep is +/// capped at the largest withdrawal the protocol accepts. +/// +/// A withdrawal's amount must lie within the protocol bounds for its Core fee rate +/// ([`ensure_withdrawal_amount_in_range`]), else +/// [`PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`]; the plan's `recipient_amount` is +/// what reaches Core after the Core fee. pub fn plan_spend( unspent: &[ShieldedNote], kind: ShieldedSpendKind, @@ -411,9 +492,25 @@ pub fn plan_spend( let fee_kind = kind.fee_kind(); let amount = match amount { ShieldedSpendAmount::Exact(amount) => amount, - ShieldedSpendAmount::Sweep => sweep_amount(unspent, fee_kind, platform_version)?, + ShieldedSpendAmount::Sweep => { + let sweep = sweep_amount(unspent, fee_kind, platform_version)?; + match kind { + // Capped at the largest withdrawal, so the plan stays executable. + ShieldedSpendKind::Withdrawal { core_fee_per_byte } => { + let (_, max, _) = withdrawal_bounds(core_fee_per_byte, platform_version)?; + sweep.min(max) + } + _ => sweep, + } + } }; ensure_positive_amount(amount)?; + let recipient_amount = match kind { + ShieldedSpendKind::Withdrawal { core_fee_per_byte } => { + ensure_withdrawal_amount_in_range(amount, core_fee_per_byte, platform_version)? + } + _ => amount, + }; let (selected, total_input, fee) = select_notes_with_fee( unspent, amount, @@ -424,13 +521,14 @@ pub fn plan_spend( Ok(ShieldedSpendPlan::new( kind, amount, + recipient_amount, fee, total_input, selected.iter().map(|n| n.nullifier).collect(), )) } -/// Refuse a spend whose fresh selection (`selected`, `total_input`, `fee` for `kind` and +/// Refuse a spend whose fresh selection (`selected`, `fee` for `kind` and /// `amount`) does not match the plan whose digest is `expected`. Reads the borrowed selection /// only, so nothing is cloned for a selection it refuses. pub(crate) fn ensure_plan_holds( @@ -438,20 +536,14 @@ pub(crate) fn ensure_plan_holds( kind: ShieldedSpendKind, amount: Credits, fee: Credits, - total_input: Credits, selected: &[&ShieldedNote], ) -> Result<(), PlatformWalletError> { - let fresh = ShieldedSpendPlan::new( - kind, - amount, - fee, - total_input, - selected.iter().map(|n| n.nullifier).collect(), - ); - if fresh.digest != *expected { + let mut nullifiers: Vec<[u8; 32]> = selected.iter().map(|n| n.nullifier).collect(); + nullifiers.sort_unstable(); + if spend_digest(kind, amount, fee, &nullifiers) != *expected { return Err(PlatformWalletError::ShieldedPlanChanged { - fresh_fee: fresh.fee, - fresh_note_count: fresh.note_count(), + fresh_fee: fee, + fresh_note_count: nullifiers.len(), }); } Ok(()) @@ -926,7 +1018,7 @@ mod tests { compute_shielded_unshield_fee(2, platform_version), ), ( - ShieldedSpendKind::Withdrawal, + withdrawal(1), compute_shielded_withdrawal_fee(2, platform_version), ), ( @@ -937,7 +1029,7 @@ mod tests { let plan = plan_spend( ¬es, kind, - ShieldedSpendAmount::Exact(1), + ShieldedSpendAmount::Exact(NOTE / 2), platform_version, ) .expect("one note covers it"); @@ -1031,15 +1123,15 @@ mod tests { .expect("selects") } - let (same, total, fee) = selected(¬es, kind, platform_version); - ensure_plan_holds(&plan.digest, kind, 2 * NOTE, fee, total, &same) + let (same, _, fee) = selected(¬es, kind, platform_version); + ensure_plan_holds(&plan.digest, kind, 2 * NOTE, fee, &same) .expect("an unchanged selection holds"); // A larger note arrives: one note now covers it, at a different fee. let mut grown = notes.clone(); grown.push(test_note(10 * NOTE, 7)); - let (moved, total, fee) = selected(&grown, kind, platform_version); - let err = ensure_plan_holds(&plan.digest, kind, 2 * NOTE, fee, total, &moved) + let (moved, _, fee) = selected(&grown, kind, platform_version); + let err = ensure_plan_holds(&plan.digest, kind, 2 * NOTE, fee, &moved) .expect_err("a moved selection must not hold"); assert!( matches!( @@ -1058,15 +1150,8 @@ mod tests { plan.digest ); // The same notes for another kind or amount are another plan. - let err = ensure_plan_holds( - &plan.digest, - kind, - 2 * NOTE - 1, - plan.fee, - plan.total_input, - &same, - ) - .expect_err("another amount"); + let err = ensure_plan_holds(&plan.digest, kind, 2 * NOTE - 1, plan.fee, &same) + .expect_err("another amount"); assert!(matches!( err, PlatformWalletError::ShieldedPlanChanged { .. } @@ -1172,7 +1257,7 @@ mod tests { for kind in [ ShieldedSpendKind::Transfer, ShieldedSpendKind::Unshield, - ShieldedSpendKind::Withdrawal, + withdrawal(1), ShieldedSpendKind::IdentityTopUp, ] { let plan = plan_spend(¬es, kind, ShieldedSpendAmount::Sweep, platform_version) @@ -1196,7 +1281,7 @@ mod tests { for kind in [ ShieldedSpendKind::Transfer, ShieldedSpendKind::Unshield, - ShieldedSpendKind::Withdrawal, + withdrawal(1), ShieldedSpendKind::IdentityTopUp, ] { let planned = plan_spend( @@ -1250,7 +1335,7 @@ mod tests { for kind in [ ShieldedSpendKind::Transfer, ShieldedSpendKind::Unshield, - ShieldedSpendKind::Withdrawal, + withdrawal(1), ShieldedSpendKind::IdentityTopUp, ] { let planned = plan_spend( @@ -1293,7 +1378,7 @@ mod tests { for kind in [ ShieldedSpendKind::Transfer, ShieldedSpendKind::Unshield, - ShieldedSpendKind::Withdrawal, + withdrawal(1), ShieldedSpendKind::IdentityTopUp, ] { let plan = plan_spend(¬es, kind, ShieldedSpendAmount::Sweep, platform_version) @@ -1301,4 +1386,172 @@ mod tests { assert_eq!(plan.note_count(), 6, "{kind:?}"); } } + + fn withdrawal(core_fee_per_byte: u32) -> ShieldedSpendKind { + ShieldedSpendKind::Withdrawal { core_fee_per_byte } + } + + /// A withdrawal's amount is the Core reserve; the recipient gets it minus the Core fee, and + /// every other kind sends the amount itself. + #[test] + fn should_report_a_withdrawals_recipient_amount_net_of_the_core_fee() { + let platform_version = PlatformVersion::latest(); + let notes = vec![test_note(NOTE, 0)]; + let plan = plan_spend( + ¬es, + withdrawal(5), + ShieldedSpendAmount::Exact(NOTE / 2), + platform_version, + ) + .expect("plans"); + let core_fee = dpp::withdrawal::core_fee_in_credits(5).expect("core fee"); + assert_eq!(plan.amount, NOTE / 2); + assert_eq!(plan.recipient_amount, NOTE / 2 - core_fee); + + let transfer = plan_spend( + ¬es, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Exact(NOTE / 2), + platform_version, + ) + .expect("plans"); + assert_eq!(transfer.recipient_amount, transfer.amount); + } + + /// Below protocol 14 the Core fee is drawn from the pool, not the reserve. + #[test] + fn should_send_a_withdrawal_reserve_whole_below_the_core_fee_carve_out() { + let v13 = PlatformVersion::get(13).expect("protocol version 13"); + let notes = vec![test_note(NOTE, 0)]; + let plan = plan_spend( + ¬es, + withdrawal(5), + ShieldedSpendAmount::Exact(NOTE / 2), + v13, + ) + .expect("plans"); + assert_eq!(plan.recipient_amount, plan.amount); + } + + /// The Core fee rate is part of the plan: another rate is another plan. + #[test] + fn should_commit_a_withdrawal_plan_to_its_core_fee_rate() { + let platform_version = PlatformVersion::latest(); + let notes = vec![test_note(NOTE, 0)]; + let amount = ShieldedSpendAmount::Exact(NOTE / 2); + let at_1 = plan_spend(¬es, withdrawal(1), amount, platform_version).expect("plans"); + let at_5 = plan_spend(¬es, withdrawal(5), amount, platform_version).expect("plans"); + assert_ne!(at_1.digest, at_5.digest); + + let selected: Vec<&ShieldedNote> = notes.iter().collect(); + ensure_plan_holds( + &at_1.digest, + withdrawal(1), + at_1.amount, + at_1.fee, + &selected, + ) + .expect("the planned rate holds"); + let err = ensure_plan_holds( + &at_1.digest, + withdrawal(5), + at_1.amount, + at_1.fee, + &selected, + ) + .expect_err("another rate must not hold"); + assert!(matches!( + err, + PlatformWalletError::ShieldedPlanChanged { .. } + )); + } + + /// An exact amount outside what the protocol accepts is refused before a plan is returned. + #[test] + fn should_refuse_a_withdrawal_amount_outside_the_protocol_bounds() { + let platform_version = PlatformVersion::latest(); + let rate = 5; + let min = dpp::withdrawal::min_withdrawal_amount_with_core_fee(rate, platform_version); + let max = platform_version.system_limits.max_withdrawal_amount; + let notes = vec![test_note(2 * max, 0)]; + for amount in [1, min - 1, max + 1] { + let planned = plan_spend( + ¬es, + withdrawal(rate), + ShieldedSpendAmount::Exact(amount), + platform_version, + ); + assert!( + matches!( + planned, + Err(PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { + amount: a, min: lo, max: hi + }) if (a, lo, hi) == (amount, min, max) + ), + "{amount}: got {planned:?}" + ); + } + for amount in [min, max] { + plan_spend( + ¬es, + withdrawal(rate), + ShieldedSpendAmount::Exact(amount), + platform_version, + ) + .unwrap_or_else(|e| panic!("{amount} is in range: {e:?}")); + } + } + + /// A sweep above the largest withdrawal is capped at it so the plan stays executable; a + /// sweep below the smallest is refused. + #[test] + fn should_cap_a_withdrawal_sweep_at_the_protocol_maximum_and_refuse_one_below_the_minimum() { + let platform_version = PlatformVersion::latest(); + let max = platform_version.system_limits.max_withdrawal_amount; + let plan = plan_spend( + &[test_note(2 * max, 0)], + withdrawal(5), + ShieldedSpendAmount::Sweep, + platform_version, + ) + .expect("plans"); + assert_eq!(plan.amount, max); + assert_eq!(plan.note_count(), 1); + + let fee = compute_shielded_withdrawal_fee(2, platform_version).expect("fee"); + let planned = plan_spend( + &[test_note(fee + 1, 0)], + withdrawal(5), + ShieldedSpendAmount::Sweep, + platform_version, + ); + assert!( + matches!( + planned, + Err(PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { amount: 1, .. }) + ), + "got {planned:?}" + ); + } + + /// A Core fee rate above the protocol cap is refused, as consensus refuses it. + #[test] + fn should_refuse_a_withdrawal_core_fee_rate_above_the_protocol_cap() { + let platform_version = PlatformVersion::latest(); + let cap = platform_version + .system_limits + .max_core_fee_per_byte + .expect("a cap from protocol 14"); + let notes = vec![test_note(NOTE, 0)]; + let planned = plan_spend( + ¬es, + withdrawal(cap + 1), + ShieldedSpendAmount::Exact(NOTE / 2), + platform_version, + ); + assert!( + matches!(planned, Err(PlatformWalletError::ShieldedBuildError(_))), + "got {planned:?}" + ); + } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index cad27bf2e70..3b76909fdf7 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -26,8 +26,8 @@ use super::activity_recorder::{ use super::keys::{AccountViewingKeys, OrchardKeySet}; use super::note_selection::{ ensure_allowed_denomination, ensure_plan_holds, ensure_positive_amount, - select_notes_for_denomination, select_notes_with_fee, ShieldedFeeKind, ShieldedSpendAmount, - ShieldedSpendKind, ShieldedSpendPlan, SPEND_MIN_ACTIONS, + ensure_withdrawal_amount_in_range, select_notes_for_denomination, select_notes_with_fee, + ShieldedFeeKind, ShieldedSpendAmount, ShieldedSpendKind, ShieldedSpendPlan, SPEND_MIN_ACTIONS, }; use super::store::{ PendingRedrive, PrivateContactPayment, PrivatePaymentEntry, ShieldedNote, ShieldedStore, @@ -2755,6 +2755,11 @@ pub async fn withdraw_with_plan( // One protocol version selects, checks the plan and builds: the SDK's may move meanwhile. let platform_version = sdk.version(); + // The amount is the reserve for Core: outside the protocol bounds for this Core fee rate + // consensus rejects the transition after the proof, so refuse it before any note is reserved. + ensure_positive_amount(amount)?; + ensure_withdrawal_amount_in_range(amount, core_fee_per_byte, platform_version)?; + let kind = ShieldedSpendKind::Withdrawal { core_fee_per_byte }; // Reserve against the 2-action floor: Orchard's BundleType::DEFAULT pads single-spend // bundles to 2 actions, and the builder prices the fee at spends.len().max(2). Reserving // for 1 would under-fee a single-note transition and the builder would reject it locally. @@ -2763,15 +2768,8 @@ pub async fn withdraw_with_plan( // `ShieldedFeeKind::Withdrawal` — reserving the base fee here would under-fund the document // cost and the builder would reject the spend (and the built-fee check below would refuse // it). - let (selected_notes, total_input, exact_fee, mut reservation) = reserve_unspent_notes( - store, - id, - amount, - ShieldedSpendKind::Withdrawal, - expected_plan, - platform_version, - ) - .await?; + let (selected_notes, total_input, exact_fee, mut reservation) = + reserve_unspent_notes(store, id, amount, kind, expected_plan, platform_version).await?; info!( account, @@ -2794,7 +2792,7 @@ pub async fn withdraw_with_plan( ensure_version_unchanged( sdk, platform_version, - ShieldedSpendKind::Withdrawal.fee_kind(), + kind.fee_kind(), selected_notes.len(), expected_plan, )?; @@ -3815,8 +3813,8 @@ async fn reserve_notes_matching( other => other?, }; if let Some((kind, expected)) = expected_plan { - let (selected, total_input, exact_fee) = &selection; - ensure_plan_holds(expected, kind, amount, *exact_fee, *total_input, selected)?; + let (selected, _, exact_fee) = &selection; + ensure_plan_holds(expected, kind, amount, *exact_fee, selected)?; } let (selected, total_input, exact_fee) = selection.into_owned(); let reservation = mark_notes_pending(&mut *guard, store, id, &selected)?; @@ -8930,7 +8928,7 @@ mod spend_plan_tests { ) .await } - ShieldedSpendKind::Withdrawal => { + ShieldedSpendKind::Withdrawal { core_fee_per_byte } => { withdraw_with_plan( sdk, store, @@ -8940,7 +8938,7 @@ mod spend_plan_tests { 0, &dashcore::Address::dummy(Network::Testnet, 1), NOTE, - 1, + core_fee_per_byte, &UnreachableProver, expected_plan, ) @@ -8973,7 +8971,9 @@ mod spend_plan_tests { for kind in [ ShieldedSpendKind::Transfer, ShieldedSpendKind::Unshield, - ShieldedSpendKind::Withdrawal, + ShieldedSpendKind::Withdrawal { + core_fee_per_byte: 1, + }, ShieldedSpendKind::IdentityTopUp, ] { for planned in [true, false] { diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 0bc0cab4359..f6364b1faab 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -105,8 +105,12 @@ public enum ShieldedSpendAmount: Sendable, Equatable { /// `PlatformWalletError.shieldedPlanChanged` when the notes moved since. public struct ShieldedSpendPlan: Sendable, Equatable { public let kind: ShieldedSpendKind - /// What the recipient gets. + /// What the spend reserves for the recipient: the amount sent, or for a + /// withdrawal the reserve for Core, of which the Core fee is taken. public let amount: UInt64 + /// What the recipient receives: `amount`, except for a withdrawal from + /// protocol version 14, where it is `amount` minus the Core fee. + public let recipientAmount: UInt64 /// The exact fee for the selected notes. public let fee: UInt64 /// The sum of the selected notes. @@ -128,6 +132,7 @@ extension ShieldedSpendPlan { self.init( kind: kind, amount: ffi.amount, + recipientAmount: ffi.recipient_amount, fee: ffi.fee, totalInput: ffi.total_input, totalDebited: ffi.total_debited, @@ -738,14 +743,24 @@ extension PlatformWalletManager { /// the number of notes. Nothing is reserved or broadcast. Pass the plan /// as `plan:` to the matching spend to run exactly it. /// - /// Throws `invalidParameter` for a kind or amount Rust refuses, and + /// `coreFeePerByte` is the Core fee rate of a `.withdrawal`, required for + /// it and ignored for the other kinds. A withdrawal's amount is the + /// reserve for Core: the plan's `recipientAmount` is what reaches the Core + /// address after the Core fee, and the withdrawal must run with the same + /// rate (another rate throws `shieldedPlanChanged`). A withdrawal sweep is + /// capped at the protocol's largest withdrawal. + /// + /// Throws `invalidParameter` for a kind or amount Rust refuses (or a + /// withdrawal without `coreFeePerByte`), `shieldedWithdrawalAmountOutOfRange` + /// for a withdrawal amount outside the protocol bounds for its rate, and /// `walletOperation` when the notes cannot pay the amount and its fee /// (or the amount is zero), as the spends do. public func shieldedPlanSpend( walletId: Data, account: UInt32 = 0, kind: ShieldedSpendKind, - amount: ShieldedSpendAmount + amount: ShieldedSpendAmount, + coreFeePerByte: UInt32? = nil ) async throws -> ShieldedSpendPlan { guard isConfigured, handle != NULL_HANDLE else { throw PlatformWalletError.invalidHandle( @@ -757,6 +772,11 @@ extension PlatformWalletManager { "walletId must be exactly 32 bytes" ) } + if kind == .withdrawal && coreFeePerByte == nil { + throw PlatformWalletError.invalidParameter( + "a withdrawal plan needs coreFeePerByte" + ) + } let (credits, sweepAll): (UInt64, Bool) switch amount { case .exact(let value): (credits, sweepAll) = (value, false) @@ -774,7 +794,8 @@ extension PlatformWalletManager { // A plain value struct: nothing in it is allocated by Rust. var out = ShieldedSpendPlanFFI() try platform_wallet_manager_shielded_plan_spend( - handle, widPtr, account, kind.rawValue, credits, sweepAll, &out + handle, widPtr, account, kind.rawValue, credits, sweepAll, + coreFeePerByte ?? 0, &out ).check() return try ShieldedSpendPlan(ffi: out) } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift index 9820fadfec5..6dfc18cba9d 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletResult.swift @@ -330,6 +330,10 @@ public enum PlatformWalletResultCode: Int32, Sendable { /// notes than one shielded transition spends. Nothing was reserved, built /// or broadcast: a smaller amount fits, or the notes can be merged first. case errorShieldedSpendTooManyNotes = 78 + /// A shielded withdrawal, or its plan, reserves an amount for Core below + /// the protocol minimum for its Core fee rate or above the maximum. + /// Nothing was reserved, built or broadcast: another amount fits. + case errorShieldedWithdrawalAmountOutOfRange = 79 /// 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. @@ -485,6 +489,8 @@ public enum PlatformWalletResultCode: Int32, Sendable { self = .errorShieldedPlanChanged case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_SPEND_TOO_MANY_NOTES: self = .errorShieldedSpendTooManyNotes + case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_WITHDRAWAL_AMOUNT_OUT_OF_RANGE: + self = .errorShieldedWithdrawalAmountOutOfRange case PLATFORM_WALLET_FFI_RESULT_CODE_NOT_FOUND: self = .notFound case PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_UNKNOWN: @@ -765,6 +771,10 @@ public enum PlatformWalletError: LocalizedError { /// reserved, built or broadcast: a smaller amount fits, or the notes can /// be merged first. case shieldedSpendTooManyNotes(String) + /// A shielded withdrawal, or its plan, reserves an amount for Core below + /// the protocol minimum for its Core fee rate or above the maximum (code + /// 79). Nothing was reserved, built or broadcast: another amount fits. + case shieldedWithdrawalAmountOutOfRange(String) case walletAlreadyExists(String) /// Definitive shielded-broadcast failure: the shielded transition never /// left the wallet (refused before anything was sent), so it cannot @@ -999,7 +1009,7 @@ public enum PlatformWalletError: LocalizedError { .privateContactRecoveryUnsupported(let m), .privateContactStoreNotRead(let m), .sdkPinnedBelowProtocolVersion(let m), .publicContactRequestUnconfirmed(let m), .shieldedPlanChanged(let m), - .shieldedSpendTooManyNotes(let m), + .shieldedSpendTooManyNotes(let m), .shieldedWithdrawalAmountOutOfRange(let m), .walletAlreadyExists(let m), .shieldedBroadcastFailed(let m), .shieldedBroadcastUnconfirmed(let m), .shieldedSpendUnconfirmed(let m), .shieldedNoRecordedAnchor(let m), .shieldedInsufficientBalance(let m), @@ -1141,6 +1151,8 @@ public enum PlatformWalletError: LocalizedError { self = .shieldedPlanChanged(detail) case .errorShieldedSpendTooManyNotes: self = .shieldedSpendTooManyNotes(detail) + case .errorShieldedWithdrawalAmountOutOfRange: + self = .shieldedWithdrawalAmountOutOfRange(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 b6a72fa539e..f660ea8634e 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ErrorHandlingTests.swift @@ -636,6 +636,22 @@ final class ErrorHandlingTests: XCTestCase { XCTAssertEqual(message, detail) } + /// A withdrawal amount outside the protocol bounds keeps its own code and + /// typed case, apart from a balance shortfall (41). + func testShouldReportAWithdrawalAmountOutOfRangeByItsOwnCode() { + let code = PlatformWalletResultCode( + ffi: PLATFORM_WALLET_FFI_RESULT_CODE_ERROR_SHIELDED_WITHDRAWAL_AMOUNT_OUT_OF_RANGE + ) + XCTAssertEqual(code, .errorShieldedWithdrawalAmountOutOfRange) + XCTAssertEqual(code.rawValue, 79) + let detail = "Shielded withdrawal amount 1 is outside the allowed range 1000000 to 50000000000000" + guard case .shieldedWithdrawalAmountOutOfRange(let message) = + PlatformWalletError(code: code, message: detail) else { + return XCTFail("lost typed withdrawal-out-of-range error") + } + XCTAssertEqual(message, detail) + } + func testShouldReadEveryFieldOfThePrivateContactReadiness() { var ffi = PrivateContactReadinessFFI() ffi.private_payments_restored = false diff --git a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift index 216ac356014..10a54e10396 100644 --- a/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift +++ b/packages/swift-sdk/SwiftTests/SwiftDashSDKTests/ShieldedSpendPlanTests.swift @@ -28,7 +28,7 @@ final class ShieldedSpendPlanTests: XCTestCase { private func plan(kind: ShieldedSpendKind, digestCount: Int = 32) -> ShieldedSpendPlan { ShieldedSpendPlan( - kind: kind, amount: 1, fee: 2, totalInput: 3, totalDebited: 3, noteCount: 1, + kind: kind, amount: 1, recipientAmount: 1, fee: 2, totalInput: 3, totalDebited: 3, noteCount: 1, digest: Data(repeating: 9, count: digestCount)) } @@ -72,6 +72,7 @@ final class ShieldedSpendPlanTests: XCTestCase { var ffi = ShieldedSpendPlanFFI() ffi.kind = 4 ffi.amount = 100 + ffi.recipient_amount = 60 ffi.fee = .max ffi.total_input = 300 ffi.total_debited = 200 @@ -82,10 +83,25 @@ final class ShieldedSpendPlanTests: XCTestCase { XCTAssertEqual( try ShieldedSpendPlan(ffi: ffi), ShieldedSpendPlan( - kind: .identityTopUp, amount: 100, fee: .max, totalInput: 300, + kind: .identityTopUp, amount: 100, recipientAmount: 60, fee: .max, totalInput: 300, totalDebited: 200, noteCount: .max, digest: Data((0..<32).map(UInt8.init)))) } + /// A withdrawal plan without its Core fee rate is refused before the FFI. + func testShouldRequireTheCoreFeeRateOfAWithdrawalPlan() async { + let manager = makeManager() + await assertThrows("plan", Self.isInvalidParameter) { + _ = try await manager.shieldedPlanSpend( + walletId: Self.walletId, kind: .withdrawal, amount: .exact(5)) + } + await assertThrows("plan", Self.isInvalidHandle) { + _ = try await manager.shieldedPlanSpend( + walletId: Self.walletId, kind: .withdrawal, amount: .exact(5), + coreFeePerByte: 1) + } + await manager.shutdown() + } + func testShouldRejectAPlanKindTheFFINeverWrites() { var ffi = ShieldedSpendPlanFFI() ffi.kind = 3 @@ -122,7 +138,8 @@ final class ShieldedSpendPlanTests: XCTestCase { for amount in amounts { await assertThrows("plan \(kind) \(amount)", Self.isInvalidHandle) { _ = try await manager.shieldedPlanSpend( - walletId: Self.walletId, account: 3, kind: kind, amount: amount) + walletId: Self.walletId, account: 3, kind: kind, amount: amount, + coreFeePerByte: 1) } } } From dbb05dd0e4a3eec0a707ed83ff7e9196932069b2 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 13:20:19 +0200 Subject: [PATCH 08/20] fix(platform-wallet): order equal-value notes by nullifier and describe the bounded sweep Notes of equal value are now ordered by nullifier, so the notes a spend selects and its plan digest no longer depend on the order the store holds them in. The sweep docs in the FFI and the Swift SDK now describe what the sweep does: the largest notes first, at most as many as one transition spends, a note joining only when it adds more than the fee it costs, and a withdrawal sweep capped at the maximum withdrawal. Co-Authored-By: Claude Opus 5.5 --- .../src/shielded_send.rs | 11 ++++--- .../src/wallet/shielded/note_selection.rs | 30 +++++++++++++++++-- .../PlatformWalletManagerShieldedSync.swift | 5 +++- 3 files changed, 39 insertions(+), 7 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 466a3d5ee87..260180ce71f 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -311,8 +311,12 @@ unsafe fn read_plan_digest(digest: *const u8) -> [u8; 32] { /// `kind` numbers the spend as `platform_wallet_shielded_estimate_fee` does: /// `0` transfer, `1` unshield, `2` withdrawal, `4` identity top-up (`3`, the /// shield from an identity, spends no notes). With `sweep_all`, the spend -/// sends every spendable note minus the fee for all of them, and `amount` must -/// be `0`; otherwise it sends `amount` credits and the fee comes on top. +/// sends the most the largest notes can send after their fee, and `amount` must +/// be `0`; otherwise it sends `amount` credits and the fee comes on top. A +/// sweep takes the notes largest first, at most as many as one transition +/// spends, and a note joins only when it adds more than the fee it costs, so a +/// note worth less than that stays unspent; a withdrawal sweep is also capped +/// at the maximum withdrawal. /// `core_fee_per_byte` is the Core fee rate of a withdrawal (kind `2`) and is /// ignored for the other kinds. A withdrawal's `amount` is the reserve for /// Core, of which the Core fee is taken: the plan's `recipient_amount` is what @@ -328,8 +332,7 @@ unsafe fn read_plan_digest(digest: *const u8) -> [u8; 32] { /// returns `ErrorInvalidParameter`; notes that cannot pay the amount and its /// fee, or a zero amount, return `ErrorWalletOperation`, and an amount only /// more notes than one transition spends would cover returns -/// `ErrorShieldedSpendTooManyNotes`, as the spends do. A sweep plans the most -/// the notes one transition spends can send. A panic inside returns +/// `ErrorShieldedSpendTooManyNotes`, as the spends do. A panic inside returns /// `ErrorWalletOperation`: planning reserves and sends nothing. /// /// # Safety diff --git a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs index 5c9f3d9c072..dd5f110f015 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs @@ -228,7 +228,7 @@ pub fn select_notes_with_fee<'a>( }) } -/// The unspent notes of `unspent`, largest first; [`PlatformWalletError::ShieldedNoUnspentNotes`] +/// The unspent notes of `unspent`, largest first (equal values by nullifier, ascending); [`PlatformWalletError::ShieldedNoUnspentNotes`] /// when there are none. fn spendable_largest_first( unspent: &[ShieldedNote], @@ -238,7 +238,8 @@ fn spendable_largest_first( if sorted.is_empty() { return Err(PlatformWalletError::ShieldedNoUnspentNotes); } - sorted.sort_by_key(|note| std::cmp::Reverse(note.value)); + // Equal values order by nullifier, so the selection does not depend on the store's order. + sorted.sort_by(|a, b| b.value.cmp(&a.value).then(a.nullifier.cmp(&b.nullifier))); Ok(sorted) } @@ -642,6 +643,31 @@ mod tests { } } + /// Notes of equal value are ordered by nullifier, so the same notes held in another order + /// select the same notes and plan the same digest. + #[test] + fn test_equal_value_notes_select_the_same_in_any_insertion_order() { + let platform_version = PlatformVersion::latest(); + let a = test_note(1_000_000_000_000, 1); + let b = test_note(1_000_000_000_000, 2); + let forward = vec![a.clone(), b.clone()]; + let reverse = vec![b, a]; + // One note covers the amount, so which of the two enters the plan is the tie-break. + let plan = |notes: &[ShieldedNote]| { + plan_spend( + notes, + ShieldedSpendKind::Transfer, + ShieldedSpendAmount::Exact(1_000), + platform_version, + ) + .expect("one note covers the amount") + }; + let (forward, reverse) = (plan(&forward), plan(&reverse)); + assert_eq!(forward.nullifiers, reverse.nullifiers); + assert_eq!(forward.digest, reverse.digest); + assert_eq!(forward.nullifiers, vec![[1u8; 32]]); + } + #[test] fn test_select_exact_amount() { let notes = vec![test_note(100, 0), test_note(200, 1), test_note(300, 2)]; diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index f6364b1faab..8f6ae0e8ff6 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -92,7 +92,10 @@ public enum ShieldedSpendKind: UInt8, Sendable { } /// What a planned shielded spend sends: an exact amount with the fee on top, -/// or every spendable note minus the fee for all of them. +/// or the most the largest notes can send after their fee: largest first, at +/// most as many notes as one transition spends, a note joining only when it +/// adds more than the fee it costs (a withdrawal sweep is also capped at the +/// maximum withdrawal); notes left out stay unspent. public enum ShieldedSpendAmount: Sendable, Equatable { case exact(UInt64) case sweepAll From 692b73182184a7b16a1ff79057a8ff5ebe3415ff Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 15:20:58 +0200 Subject: [PATCH 09/20] feat(dpp): share shielded withdrawal preflight and recipient output Add preflight_shielded_withdrawal, which applies the rate and reserve rules of the protocol version's withdrawal structure generation and the Core fee accounting of its asset unlock conversion generation, and returns the output the conversion queues: the reserve truncated to whole duffs, minus the Core fee from the carve-out generation. The shielded structure validators and the conversion now call the same rate, range and fee functions, so consensus behavior is unchanged for every protocol version; tests pin the validator and the conversion against the preflight at v13 and v14. Co-Authored-By: Claude Opus 5.5 --- .../v0/state_transition_validation/mod.rs | 52 ++++ .../v0/state_transition_validation/v0.rs | 18 +- .../v0/state_transition_validation/v1.rs | 37 +-- .../v1/mod.rs | 50 +++- packages/rs-dpp/src/withdrawal/mod.rs | 283 +++++++++++++++++- 5 files changed, 384 insertions(+), 56 deletions(-) diff --git a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/mod.rs b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/mod.rs index f38d2488668..7de280c55cc 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/mod.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/mod.rs @@ -353,4 +353,56 @@ mod tests { )] ); } + + /// The shared preflight and the structure validator, which both own the rules through the + /// same DPP functions, agree on every rate and reserve below: the validator's rate and range + /// verdicts are the preflight's, at the generation before the cap and the one with it. + #[test] + fn the_structure_validator_and_the_withdrawal_preflight_agree() { + for version in [13, 14] { + let platform_version = PlatformVersion::get(version).expect("protocol version"); + let platform_fee = + compute_shielded_withdrawal_fee(1, platform_version).expect("platform fee"); + let limits = &platform_version.system_limits; + let reserves = [ + limits.min_withdrawal_amount, + limits.min_withdrawal_amount + core_fee_in_credits(1).expect("fee") - 1, + limits.min_withdrawal_amount + core_fee_in_credits(1).expect("fee"), + 1_000_000_001, + 2_000_000_999, + limits.max_withdrawal_amount, + limits.max_withdrawal_amount + 1, + ]; + for rate in [0, 1, 4, 5, 6_765, 10_946] { + for reserve in reserves { + let validated = transition(reserve + platform_fee, rate) + .validate_structure(platform_version); + let preflight = crate::withdrawal::preflight_shielded_withdrawal( + reserve, + rate, + platform_version, + ); + // Before the cap generation the validator leaves the reserve range to drive. + let range_only = matches!( + &preflight, + Err(ConsensusError::BasicError( + BasicError::WithdrawalBelowMinAmountError(_) + | BasicError::InvalidIdentityCreditWithdrawalTransitionAmountError( + _ + ) + )) + ); + if version == 13 && range_only { + assert!(validated.is_valid(), "v{version} {rate} {reserve}"); + continue; + } + assert_eq!( + validated.errors.first(), + preflight.as_ref().err(), + "v{version} rate {rate} reserve {reserve}" + ); + } + } + } + } } diff --git a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v0.rs b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v0.rs index c8e0f52d460..bc6b936bc72 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v0.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v0.rs @@ -1,19 +1,16 @@ use crate::consensus::basic::identity::{ - InvalidCreditWithdrawalTransitionCoreFeeError, InvalidCreditWithdrawalTransitionOutputScriptError, NotImplementedCreditWithdrawalTransitionPoolingError, }; use crate::consensus::basic::state_transition::ShieldedInvalidValueBalanceError; use crate::consensus::basic::BasicError; -use crate::state_transition::identity_credit_withdrawal_transition::MIN_CORE_FEE_PER_BYTE; use crate::state_transition::shielded_withdrawal_transition::v0::ShieldedWithdrawalTransitionV0; use crate::state_transition::state_transitions::shielded::common_validation::{ validate_actions_count, validate_anchor_not_zero, validate_encrypted_note_sizes, validate_proof_not_empty, }; -use crate::util::is_non_zero_fibonacci_number::is_non_zero_fibonacci_number; use crate::validation::SimpleConsensusValidationResult; -use crate::withdrawal::Pooling; +use crate::withdrawal::{validate_core_fee_per_byte_is_non_zero_fibonacci, Pooling}; use platform_version::version::PlatformVersion; impl ShieldedWithdrawalTransitionV0 { @@ -95,16 +92,9 @@ impl ShieldedWithdrawalTransitionV0 { } // core_fee_per_byte must be a non-zero Fibonacci number. - if !is_non_zero_fibonacci_number(self.core_fee_per_byte as u64) { - return SimpleConsensusValidationResult::new_with_error( - BasicError::InvalidCreditWithdrawalTransitionCoreFeeError( - InvalidCreditWithdrawalTransitionCoreFeeError::new( - self.core_fee_per_byte, - MIN_CORE_FEE_PER_BYTE, - ), - ) - .into(), - ); + let result = validate_core_fee_per_byte_is_non_zero_fibonacci(self.core_fee_per_byte); + if !result.is_valid() { + return result; } // output_script must be a canonical P2PKH or P2SH script. diff --git a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v1.rs b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v1.rs index c2659bad8af..5fefd290b2e 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v1.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v1.rs @@ -1,10 +1,10 @@ -use crate::consensus::basic::identity::InvalidIdentityCreditWithdrawalTransitionAmountError; -use crate::consensus::basic::state_transition::WithdrawalBelowMinAmountError; -use crate::consensus::basic::BasicError; use crate::shielded::compute_shielded_withdrawal_fee; use crate::state_transition::shielded_withdrawal_transition::v0::ShieldedWithdrawalTransitionV0; use crate::validation::SimpleConsensusValidationResult; -use crate::withdrawal::{min_withdrawal_amount_with_core_fee, validate_core_fee_per_byte_cap}; +use crate::withdrawal::{ + min_withdrawal_amount_with_core_fee, validate_core_fee_per_byte_cap, + validate_withdrawal_reserved_amount_range, +}; use platform_version::version::PlatformVersion; impl ShieldedWithdrawalTransitionV0 { @@ -44,35 +44,18 @@ impl ShieldedWithdrawalTransitionV0 { min_withdrawal_amount_with_core_fee(self.core_fee_per_byte, platform_version); let max_withdrawal_amount = platform_version.system_limits.max_withdrawal_amount; - if reserved_amount < minimum_reserved_amount { - return SimpleConsensusValidationResult::new_with_error( - BasicError::WithdrawalBelowMinAmountError(WithdrawalBelowMinAmountError::new( - reserved_amount, - minimum_reserved_amount, - max_withdrawal_amount, - )) - .into(), - ); - } - - if reserved_amount > max_withdrawal_amount { - return SimpleConsensusValidationResult::new_with_error( - InvalidIdentityCreditWithdrawalTransitionAmountError::new( - reserved_amount, - minimum_reserved_amount, - max_withdrawal_amount, - ) - .into(), - ); - } - - SimpleConsensusValidationResult::new() + validate_withdrawal_reserved_amount_range( + reserved_amount, + minimum_reserved_amount, + max_withdrawal_amount, + ) } } #[cfg(test)] mod tests { use super::*; + use crate::consensus::basic::BasicError; use crate::consensus::ConsensusError; use crate::identity::core_script::CoreScript; use crate::shielded::SerializedAction; diff --git a/packages/rs-dpp/src/withdrawal/document_try_into_asset_unlock_base_transaction_info/v1/mod.rs b/packages/rs-dpp/src/withdrawal/document_try_into_asset_unlock_base_transaction_info/v1/mod.rs index 5c32a9f631c..ad05200de4e 100644 --- a/packages/rs-dpp/src/withdrawal/document_try_into_asset_unlock_base_transaction_info/v1/mod.rs +++ b/packages/rs-dpp/src/withdrawal/document_try_into_asset_unlock_base_transaction_info/v1/mod.rs @@ -1,9 +1,8 @@ use crate::document::{Document, DocumentV0Getters}; use crate::identity::convert_credits_to_duffs; use crate::system_data_contracts::withdrawals_contract::v1::document_types::withdrawal; -use crate::withdrawal::WithdrawalTransactionIndex; +use crate::withdrawal::{asset_unlock_core_fee_duffs, WithdrawalTransactionIndex}; use crate::ProtocolError; -use dashcore::transaction::special_transaction::asset_unlock::qualified_asset_unlock::ASSET_UNLOCK_TX_SIZE; use dashcore::transaction::special_transaction::asset_unlock::unqualified_asset_unlock::{ AssetUnlockBasePayload, AssetUnlockBaseTransactionInfo, }; @@ -23,18 +22,7 @@ impl Document { let core_fee_per_byte: u32 = properties.get_integer(withdrawal::properties::CORE_FEE_PER_BYTE)?; - let max_core_fee_per_byte = platform_version - .system_limits - .max_core_fee_per_byte - .ok_or_else(|| { - ProtocolError::Generic( - "asset unlock conversion v1 requires a Core fee limit".to_string(), - ) - })?; - let effective_core_fee_per_byte = core_fee_per_byte.min(max_core_fee_per_byte); - let requested_fee = (ASSET_UNLOCK_TX_SIZE as u64) - .checked_mul(effective_core_fee_per_byte as u64) - .ok_or_else(|| ProtocolError::Generic("asset unlock fee overflow".to_string()))?; + let requested_fee = asset_unlock_core_fee_duffs(core_fee_per_byte, platform_version)?; let withdrawal_amount_duffs = convert_credits_to_duffs(withdrawal_amount)?; let output_script = ScriptBuf::from_bytes(output_script_bytes); @@ -207,4 +195,38 @@ mod tests { convert_credits_to_duffs(amount).expect("duffs") ); } + + /// The preflight pays what the conversion queues: the same output for the same reserve and + /// rate, at the generation that carves the fee out and the one before it. + #[test] + fn the_conversion_pays_what_the_withdrawal_preflight_reports() { + for version in [13, 14] { + let platform_version = PlatformVersion::get(version).expect("platform version"); + for rate in [1u32, 5, 6_765] { + for amount in [2_000_000_001u64, 2_345_678_999, 3_999_999_999] { + let mut document = withdrawal_document(Some(1), amount); + document.properties_mut().insert( + withdrawal::properties::CORE_FEE_PER_BYTE.to_string(), + rate.into(), + ); + let tx = document + .try_into_asset_unlock_base_transaction_info(1, platform_version) + .expect("asset unlock info"); + let reserve = crate::withdrawal::preflight_shielded_withdrawal( + amount, + rate, + platform_version, + ) + .expect("in range"); + assert_eq!( + tx.output[0].value, reserve.output_duffs, + "v{version} rate {rate} amount {amount}" + ); + if version == 14 { + assert_eq!(tx.base_payload.fee as u64, reserve.core_fee_duffs); + } + } + } + } + } } diff --git a/packages/rs-dpp/src/withdrawal/mod.rs b/packages/rs-dpp/src/withdrawal/mod.rs index b33fc05f110..d6ca46fd7bf 100644 --- a/packages/rs-dpp/src/withdrawal/mod.rs +++ b/packages/rs-dpp/src/withdrawal/mod.rs @@ -11,12 +11,26 @@ use serde_repr::{Deserialize_repr, Serialize_repr}; use crate::balances::credits::CREDITS_PER_DUFF; #[cfg(feature = "state-transitions")] -use crate::consensus::basic::identity::InvalidCreditWithdrawalTransitionCoreFeeError; +use crate::consensus::basic::identity::{ + InvalidCreditWithdrawalTransitionCoreFeeError, + InvalidIdentityCreditWithdrawalTransitionAmountError, +}; +#[cfg(feature = "state-transitions")] +use crate::consensus::basic::state_transition::WithdrawalBelowMinAmountError; +#[cfg(feature = "state-transitions")] +use crate::consensus::basic::unsupported_version_error::UnsupportedVersionError; +#[cfg(feature = "state-transitions")] +use crate::consensus::basic::BasicError; +#[cfg(feature = "state-transitions")] +use crate::consensus::ConsensusError; use crate::fee::Credits; #[cfg(feature = "state-transitions")] use crate::state_transition::identity_credit_withdrawal_transition::MIN_CORE_FEE_PER_BYTE; #[cfg(feature = "state-transitions")] +use crate::util::is_non_zero_fibonacci_number::is_non_zero_fibonacci_number; +#[cfg(feature = "state-transitions")] use crate::validation::SimpleConsensusValidationResult; +use crate::ProtocolError; use dashcore::transaction::special_transaction::asset_unlock::qualified_asset_unlock::ASSET_UNLOCK_TX_SIZE; use platform_version::version::PlatformVersion; @@ -110,6 +124,184 @@ pub fn min_withdrawal_amount_with_core_fee( .saturating_add(core_fee) } +/// Rejects a Core fee rate that is not a non-zero Fibonacci number. +/// +/// Stateless rule of every shielded withdrawal structure generation, shared with +/// [`preflight_shielded_withdrawal`]. +#[cfg(feature = "state-transitions")] +pub fn validate_core_fee_per_byte_is_non_zero_fibonacci( + core_fee_per_byte: u32, +) -> SimpleConsensusValidationResult { + if is_non_zero_fibonacci_number(core_fee_per_byte as u64) { + SimpleConsensusValidationResult::new() + } else { + SimpleConsensusValidationResult::new_with_error( + InvalidCreditWithdrawalTransitionCoreFeeError::new( + core_fee_per_byte, + MIN_CORE_FEE_PER_BYTE, + ) + .into(), + ) + } +} + +/// Rejects a `reserved_amount` (what a withdrawal reserves for Core) outside +/// `[minimum_reserved_amount, maximum_reserved_amount]`. +#[cfg(feature = "state-transitions")] +pub fn validate_withdrawal_reserved_amount_range( + reserved_amount: Credits, + minimum_reserved_amount: Credits, + maximum_reserved_amount: Credits, +) -> SimpleConsensusValidationResult { + if reserved_amount < minimum_reserved_amount { + return SimpleConsensusValidationResult::new_with_error( + BasicError::WithdrawalBelowMinAmountError(WithdrawalBelowMinAmountError::new( + reserved_amount, + minimum_reserved_amount, + maximum_reserved_amount, + )) + .into(), + ); + } + + if reserved_amount > maximum_reserved_amount { + return SimpleConsensusValidationResult::new_with_error( + InvalidIdentityCreditWithdrawalTransitionAmountError::new( + reserved_amount, + minimum_reserved_amount, + maximum_reserved_amount, + ) + .into(), + ); + } + + SimpleConsensusValidationResult::new() +} + +/// The Core fee in duffs an asset unlock transaction requests at `core_fee_per_byte` from +/// protocol version 14: the rate is clamped to the version's `max_core_fee_per_byte`. Errors +/// for a version without a cap, which does not carve the fee out of the withdrawn amount. +pub fn asset_unlock_core_fee_duffs( + core_fee_per_byte: u32, + platform_version: &PlatformVersion, +) -> Result { + let max_core_fee_per_byte = platform_version + .system_limits + .max_core_fee_per_byte + .ok_or_else(|| { + ProtocolError::Generic( + "asset unlock conversion v1 requires a Core fee limit".to_string(), + ) + })?; + (ASSET_UNLOCK_TX_SIZE as u64) + .checked_mul(core_fee_per_byte.min(max_core_fee_per_byte) as u64) + .ok_or_else(|| ProtocolError::Generic("asset unlock fee overflow".to_string())) +} + +/// What a shielded withdrawal's reserve for Core pays out, as the withdrawal document +/// conversion turns it into the asset unlock output. +#[cfg(feature = "state-transitions")] +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ShieldedWithdrawalReserve { + /// The Core fee carved out of the reserve, in duffs. 0 before protocol version 14, where + /// Core draws the fee from its credit pool on top of the reserve. + pub core_fee_duffs: u64, + /// The asset unlock output, in duffs: the reserve truncated to whole duffs, minus the fee. + pub output_duffs: u64, +} + +#[cfg(feature = "state-transitions")] +impl ShieldedWithdrawalReserve { + /// The output in credits: at most the reserve, without its sub-duff remainder and the Core + /// fee. + pub fn output_credits(&self) -> Credits { + self.output_duffs.saturating_mul(CREDITS_PER_DUFF) + } +} + +/// Checks a shielded withdrawal that reserves `reserved_amount` for Core at `core_fee_per_byte` +/// the way consensus does, and returns what it pays out. +/// +/// The rules follow the protocol version's `validate_withdrawal_structure` generation: a +/// non-zero Fibonacci rate always; from the generation that caps the rate also the cap, and a +/// reserve above the floor plus the Core fee. Before it the reserve must lie in +/// `[min_withdrawal_amount, max_withdrawal_amount]`, which drive enforces on the net amount +/// there. The accounting follows the generation of `try_into_asset_unlock_base_transaction_info`. +/// The reserve is gross: what the withdrawal debits is not changed by the result. +#[cfg(feature = "state-transitions")] +pub fn preflight_shielded_withdrawal( + reserved_amount: Credits, + core_fee_per_byte: u32, + platform_version: &PlatformVersion, +) -> Result { + let limits = &platform_version.system_limits; + let mut result = validate_core_fee_per_byte_is_non_zero_fibonacci(core_fee_per_byte); + match platform_version + .dpp + .state_transitions + .shielded + .validate_withdrawal_structure + { + 0 => { + if result.is_valid() { + result = validate_withdrawal_reserved_amount_range( + reserved_amount, + limits.min_withdrawal_amount, + limits.max_withdrawal_amount, + ); + } + } + 1 => { + if result.is_valid() { + result = validate_core_fee_per_byte_cap(core_fee_per_byte, platform_version); + } + if result.is_valid() { + result = validate_withdrawal_reserved_amount_range( + reserved_amount, + min_withdrawal_amount_with_core_fee(core_fee_per_byte, platform_version), + limits.max_withdrawal_amount, + ); + } + } + version => { + return Err( + BasicError::UnsupportedVersionError(UnsupportedVersionError::new(version, 0, 1)) + .into(), + ) + } + } + if let Some(error) = result.errors.into_iter().next() { + return Err(error); + } + + // Whole duffs first, then the fee: the order the withdrawal document conversion uses. + let core_fee_duffs = match platform_version + .dpp + .document_versions + .document_method_versions + .try_into_asset_unlock_base_transaction_info + { + 0 => 0, + // A table that selects the carving generation without a cap cannot account for it. + 1 => asset_unlock_core_fee_duffs(core_fee_per_byte, platform_version).map_err(|_| { + ConsensusError::from(BasicError::UnsupportedVersionError( + UnsupportedVersionError::new(1, 0, 0), + )) + })?, + version => { + return Err( + BasicError::UnsupportedVersionError(UnsupportedVersionError::new(version, 0, 1)) + .into(), + ) + } + }; + Ok(ShieldedWithdrawalReserve { + core_fee_duffs, + // A reserve in range exceeds the fee: the minimum adds the fee to the floor. + output_duffs: (reserved_amount / CREDITS_PER_DUFF).saturating_sub(core_fee_duffs), + }) +} + /// Serde helper for `Pooling` fields exposed through the JS surface. /// /// `Pooling` is `#[repr(u8)]` with `Serialize_repr` / `Deserialize_repr`, so the @@ -357,6 +549,95 @@ mod core_fee_tests { assert!(validate_core_fee_per_byte_cap(u32::MAX, platform_version).is_valid()); } + fn rate_error(result: Result, rate: u32) { + assert_matches!( + result, + Err(ConsensusError::BasicError( + BasicError::InvalidCreditWithdrawalTransitionCoreFeeError(error) + )) if error.core_fee_per_byte() == rate + ); + } + + #[test] + fn preflight_truncates_the_reserve_to_whole_duffs_before_the_core_fee() { + let version_14 = PlatformVersion::get(14).expect("protocol version 14"); + + // 1_000_000 duffs and 1 credit: the credit is dropped, then the 190-duff fee. + let reserve = + preflight_shielded_withdrawal(1_000_000_001, 1, version_14).expect("in range"); + assert_eq!(reserve.core_fee_duffs, 190); + assert_eq!(reserve.output_duffs, 999_810); + assert_eq!(reserve.output_credits(), 999_810_000); + + // A larger reserve at a higher rate, off a duff boundary by 999 credits. + let reserve = + preflight_shielded_withdrawal(2_345_678_999, 5, version_14).expect("in range"); + assert_eq!(reserve.core_fee_duffs, 950); + assert_eq!( + reserve.output_credits(), + (2_345_678 - 950) * CREDITS_PER_DUFF + ); + } + + #[test] + fn preflight_before_the_core_fee_carve_out_pays_the_whole_duffs_of_the_reserve() { + let version_13 = PlatformVersion::get(13).expect("protocol version 13"); + + let reserve = + preflight_shielded_withdrawal(1_000_000_999, 1, version_13).expect("in range"); + assert_eq!(reserve.core_fee_duffs, 0); + assert_eq!(reserve.output_credits(), 1_000_000_000); + } + + #[test] + fn preflight_refuses_a_zero_or_non_fibonacci_rate_before_and_after_the_cap() { + for version in [13, 14] { + let platform_version = PlatformVersion::get(version).expect("protocol version"); + for rate in [0, 4] { + rate_error( + preflight_shielded_withdrawal(2_000_000_000, rate, platform_version), + rate, + ); + } + } + } + + #[test] + fn preflight_refuses_a_rate_above_the_cap_only_once_the_cap_applies() { + let version_13 = PlatformVersion::get(13).expect("protocol version 13"); + let version_14 = PlatformVersion::get(14).expect("protocol version 14"); + + assert!(preflight_shielded_withdrawal(2_000_000_000, 10_946, version_13).is_ok()); + rate_error( + preflight_shielded_withdrawal(2_000_000_000, 10_946, version_14), + 10_946, + ); + } + + #[test] + fn preflight_keeps_the_reserve_bounds_of_each_generation() { + let version_13 = PlatformVersion::get(13).expect("protocol version 13"); + let version_14 = PlatformVersion::get(14).expect("protocol version 14"); + let floor = version_14.system_limits.min_withdrawal_amount; + let max = version_14.system_limits.max_withdrawal_amount; + let carved_floor = min_withdrawal_amount_with_core_fee(1, version_14); + + assert!(preflight_shielded_withdrawal(floor, 1, version_13).is_ok()); + assert_matches!( + preflight_shielded_withdrawal(floor, 1, version_14), + Err(ConsensusError::BasicError( + BasicError::WithdrawalBelowMinAmountError(_) + )) + ); + assert!(preflight_shielded_withdrawal(carved_floor, 1, version_14).is_ok()); + assert_matches!( + preflight_shielded_withdrawal(max + 1, 1, version_14), + Err(ConsensusError::BasicError( + BasicError::InvalidIdentityCreditWithdrawalTransitionAmountError(_) + )) + ); + } + #[test] fn should_add_the_core_fee_to_the_withdrawal_floor() { let platform_version = PlatformVersion::latest(); From 226946f99bcd9251cb43a2ca5c7f83c9283df0a4 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 15:32:53 +0200 Subject: [PATCH 10/20] fix(platform-wallet): plan withdrawals with DPP's preflight and rounded recipient amount The withdrawal planner now delegates its rate and amount checks and the recipient output to dpp::withdrawal::preflight_shielded_withdrawal instead of rebuilding the rules. recipient_amount is the output DPP pays (the reserve truncated to whole duffs, minus the Core fee from protocol 14); amount stays the gross reserve and debit. A zero or non-Fibonacci rate is refused at every protocol version, as the structure validator refuses it, so a plan that could not execute is no longer returned. The FFI and Swift docs for recipient_amount describe the rounded output. Co-Authored-By: Claude Opus 5.5 --- .../src/shielded_send.rs | 10 +- .../src/shielded_types.rs | 5 +- .../src/wallet/shielded/note_selection.rs | 170 ++++++++++++------ .../PlatformWalletManagerShieldedSync.swift | 7 +- 4 files changed, 131 insertions(+), 61 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 260180ce71f..6a11d4b3060 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -320,10 +320,12 @@ unsafe fn read_plan_digest(digest: *const u8) -> [u8; 32] { /// `core_fee_per_byte` is the Core fee rate of a withdrawal (kind `2`) and is /// ignored for the other kinds. A withdrawal's `amount` is the reserve for /// Core, of which the Core fee is taken: the plan's `recipient_amount` is what -/// reaches the Core address. The amount must lie within the protocol bounds -/// for that rate (a withdrawal sweep is capped at the maximum), else -/// `ErrorShieldedWithdrawalAmountOutOfRange`; a rate above the protocol cap -/// returns `ErrorWalletOperation`. Run the withdraw export with the same +/// reaches the Core address, the reserve truncated to whole duffs minus the +/// Core fee. The amount must lie within the protocol bounds for that rate (a +/// withdrawal sweep is capped at the maximum), else +/// `ErrorShieldedWithdrawalAmountOutOfRange`; a rate the protocol refuses (zero, +/// not a Fibonacci number, or above the cap from protocol 14) returns +/// `ErrorWalletOperation`. Run the withdraw export with the same /// rate: another rate refuses with `ErrorShieldedPlanChanged`. /// /// Writes the plan to `out_plan`. Run it with the spend's `_with_plan` export diff --git a/packages/rs-platform-wallet-ffi/src/shielded_types.rs b/packages/rs-platform-wallet-ffi/src/shielded_types.rs index 47cec607e6b..fa3f96054e2 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_types.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_types.rs @@ -101,8 +101,9 @@ pub struct ShieldedSpendPlanFFI { /// What the spend reserves for the recipient: the amount sent, or for a /// withdrawal the reserve for Core, of which the Core fee is taken. pub amount: u64, - /// What the recipient receives: `amount`, except for a withdrawal from - /// protocol version 14, where it is `amount` minus the Core fee. + /// What the recipient receives: `amount`, except for a withdrawal, where + /// it is the output the protocol pays: `amount` truncated to whole duffs, + /// minus the Core fee from protocol version 14. pub recipient_amount: u64, /// The exact fee for the selected notes. pub fee: u64, diff --git a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs index dd5f110f015..04ddc0dc20a 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs @@ -6,6 +6,8 @@ use super::store::ShieldedNote; use crate::error::PlatformWalletError; +use dpp::consensus::basic::BasicError; +use dpp::consensus::ConsensusError; use dpp::fee::Credits; use dpp::shielded::{ compute_minimum_shielded_fee, compute_private_document_create_from_shielded_pool_fee, @@ -14,9 +16,7 @@ use dpp::shielded::{ is_allowed_identity_create_denomination, max_shielded_actions_per_transition, }; use dpp::version::PlatformVersion; -use dpp::withdrawal::{ - core_fee_in_credits, min_withdrawal_amount_with_core_fee, validate_core_fee_per_byte_cap, -}; +use dpp::withdrawal::preflight_shielded_withdrawal; use dpp::ProtocolError; use sha2::{Digest, Sha256}; @@ -357,8 +357,9 @@ pub struct ShieldedSpendPlan { /// What the spend reserves for the recipient: the amount sent, or for a withdrawal the /// reserve for Core, of which the Core fee is taken. pub amount: Credits, - /// What the recipient receives. The amount, except for a withdrawal from protocol version - /// 14, where it is the reserve minus the Core fee at the kind's rate. + /// What the recipient receives. The amount, except for a withdrawal: there the output DPP + /// pays for the reserve, in credits: the reserve truncated to whole duffs, minus the Core + /// fee at the kind's rate from protocol version 14. pub recipient_amount: Credits, /// The exact fee for the selected notes. pub fee: Credits, @@ -392,52 +393,34 @@ fn spend_digest( hasher.finalize().into() } -/// The bounds of a withdrawal's `reserve` for Core at `core_fee_per_byte`, from the DPP helpers -/// consensus validates with: `(minimum, maximum, Core fee)`. From protocol version 14 (the -/// versions that cap the Core fee rate) the Core fee is carved out of the reserve and the minimum -/// leaves the protocol floor above it; before, the fee is drawn from the Core credit pool on top -/// of the reserve, so the minimum is the floor and the fee is 0. A rate above the cap is refused, -/// as consensus refuses it. -fn withdrawal_bounds( - core_fee_per_byte: u32, - platform_version: &PlatformVersion, -) -> Result<(Credits, Credits, Credits), PlatformWalletError> { - let limits = &platform_version.system_limits; - if limits.max_core_fee_per_byte.is_none() { - return Ok(( - limits.min_withdrawal_amount, - limits.max_withdrawal_amount, - 0, - )); - } - let capped = validate_core_fee_per_byte_cap(core_fee_per_byte, platform_version); - if let Some(error) = capped.first_error() { - return Err(PlatformWalletError::ShieldedBuildError(error.to_string())); - } - let core_fee = core_fee_in_credits(core_fee_per_byte).ok_or_else(|| { - PlatformWalletError::ShieldedBuildError("the Core fee overflows credits".to_string()) - })?; - Ok(( - min_withdrawal_amount_with_core_fee(core_fee_per_byte, platform_version), - limits.max_withdrawal_amount, - core_fee, - )) -} - -/// Refuse a withdrawal `amount` (the reserve for Core) outside what the protocol accepts at -/// `core_fee_per_byte`, as [`PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`]. Returns -/// what the recipient receives. Store-free, so callers can run it before reserving any note. +/// Refuse a withdrawal `amount` (the reserve for Core) that DPP's shared preflight refuses at +/// `core_fee_per_byte` and `platform_version`: a rate that cannot execute, or a reserve outside +/// the bounds ([`PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`]). Returns what the +/// recipient receives, the rounded output DPP pays; the reserve itself stays the gross debit. +/// Store-free, so callers can run it before reserving any note. pub(crate) fn ensure_withdrawal_amount_in_range( amount: Credits, core_fee_per_byte: u32, platform_version: &PlatformVersion, ) -> Result { - let (min, max, core_fee) = withdrawal_bounds(core_fee_per_byte, platform_version)?; - if amount < min || amount > max { - return Err(PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { amount, min, max }); + match preflight_shielded_withdrawal(amount, core_fee_per_byte, platform_version) { + Ok(reserve) => Ok(reserve.output_credits()), + Err(ConsensusError::BasicError(BasicError::WithdrawalBelowMinAmountError(error))) => { + Err(PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { + amount, + min: error.min_amount(), + max: error.max_amount(), + }) + } + Err(ConsensusError::BasicError( + BasicError::InvalidIdentityCreditWithdrawalTransitionAmountError(error), + )) => Err(PlatformWalletError::ShieldedWithdrawalAmountOutOfRange { + amount, + min: error.min_amount(), + max: error.max_amount(), + }), + Err(error) => Err(PlatformWalletError::ShieldedBuildError(error.to_string())), } - // In range, so at least the minimum, which is above the Core fee. - Ok(amount - core_fee) } impl ShieldedSpendPlan { @@ -480,10 +463,10 @@ impl ShieldedSpendPlan { /// their fee ([`sweep_amount`]); the plan selects exactly those notes. A withdrawal sweep is /// capped at the largest withdrawal the protocol accepts. /// -/// A withdrawal's amount must lie within the protocol bounds for its Core fee rate -/// ([`ensure_withdrawal_amount_in_range`]), else -/// [`PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`]; the plan's `recipient_amount` is -/// what reaches Core after the Core fee. +/// A withdrawal must pass DPP's shared preflight ([`ensure_withdrawal_amount_in_range`]): a rate +/// that cannot execute is refused, and an amount outside the protocol bounds is +/// [`PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`]. The plan's `recipient_amount` is +/// the rounded output DPP pays; its `amount` stays the gross reserve. pub fn plan_spend( unspent: &[ShieldedNote], kind: ShieldedSpendKind, @@ -497,9 +480,8 @@ pub fn plan_spend( let sweep = sweep_amount(unspent, fee_kind, platform_version)?; match kind { // Capped at the largest withdrawal, so the plan stays executable. - ShieldedSpendKind::Withdrawal { core_fee_per_byte } => { - let (_, max, _) = withdrawal_bounds(core_fee_per_byte, platform_version)?; - sweep.min(max) + ShieldedSpendKind::Withdrawal { .. } => { + sweep.min(platform_version.system_limits.max_withdrawal_amount) } _ => sweep, } @@ -1580,4 +1562,88 @@ mod tests { "got {planned:?}" ); } + + /// The recipient gets what DPP's conversion pays: the reserve truncated to whole duffs, then + /// the Core fee. The plan keeps the gross reserve as `amount` and debits it. + #[test] + fn should_report_the_rounded_output_dpp_pays_for_a_non_duff_aligned_exact_amount() { + let v14 = PlatformVersion::get(14).expect("protocol version 14"); + let notes = vec![test_note(NOTE, 0)]; + let plan = plan_spend( + ¬es, + withdrawal(1), + ShieldedSpendAmount::Exact(1_000_000_001), + v14, + ) + .expect("plans"); + assert_eq!(plan.amount, 1_000_000_001); + assert_eq!(plan.recipient_amount, 999_810_000); + assert_eq!(plan.total_debited(), 1_000_000_001 + plan.fee); + } + + /// A sweep's reserve is whatever the notes leave after the fee, rarely duff aligned. + #[test] + fn should_report_the_rounded_output_for_a_non_duff_aligned_sweep() { + let v14 = PlatformVersion::get(14).expect("protocol version 14"); + let fee = compute_shielded_withdrawal_fee(2, v14).expect("fee"); + let plan = plan_spend( + &[test_note(fee + 2_000_000_999, 0)], + withdrawal(1), + ShieldedSpendAmount::Sweep, + v14, + ) + .expect("plans"); + assert_eq!(plan.amount, 2_000_000_999); + assert_eq!(plan.recipient_amount, (2_000_000 - 190) * 1_000); + } + + /// Before the carve-out the output is still the reserve's whole duffs. + #[test] + fn should_round_a_withdrawal_reserve_to_whole_duffs_below_the_core_fee_carve_out() { + let v13 = PlatformVersion::get(13).expect("protocol version 13"); + let plan = plan_spend( + &[test_note(NOTE, 0)], + withdrawal(5), + ShieldedSpendAmount::Exact(1_000_000_999), + v13, + ) + .expect("plans"); + assert_eq!(plan.amount, 1_000_000_999); + assert_eq!(plan.recipient_amount, 1_000_000_000); + } + + /// A zero or non-Fibonacci rate cannot execute at any protocol version, so it plans at none, + /// exact or sweep. + #[test] + fn should_refuse_a_zero_or_non_fibonacci_withdrawal_rate_before_and_after_the_cap() { + for version in [13, 14] { + let platform_version = PlatformVersion::get(version).expect("protocol version"); + let notes = vec![test_note(NOTE, 0)]; + for rate in [0, 4] { + for amount in [ + ShieldedSpendAmount::Exact(NOTE / 2), + ShieldedSpendAmount::Sweep, + ] { + let planned = plan_spend(¬es, withdrawal(rate), amount, platform_version); + assert!( + matches!(planned, Err(PlatformWalletError::ShieldedBuildError(_))), + "v{version} rate {rate} {amount:?}: got {planned:?}" + ); + } + } + } + } + + /// The cap refuses only from the version that has one. + #[test] + fn should_refuse_a_withdrawal_rate_above_the_cap_only_from_the_version_that_caps_it() { + let v13 = PlatformVersion::get(13).expect("protocol version 13"); + plan_spend( + &[test_note(NOTE, 0)], + withdrawal(10_946), + ShieldedSpendAmount::Exact(NOTE / 2), + v13, + ) + .expect("protocol 13 has no cap"); + } } diff --git a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift index 8f6ae0e8ff6..268762c6e96 100644 --- a/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift +++ b/packages/swift-sdk/Sources/SwiftDashSDK/PlatformWallet/PlatformWalletManagerShieldedSync.swift @@ -111,8 +111,9 @@ public struct ShieldedSpendPlan: Sendable, Equatable { /// What the spend reserves for the recipient: the amount sent, or for a /// withdrawal the reserve for Core, of which the Core fee is taken. public let amount: UInt64 - /// What the recipient receives: `amount`, except for a withdrawal from - /// protocol version 14, where it is `amount` minus the Core fee. + /// What the recipient receives: `amount`, except for a withdrawal, where + /// it is the output the protocol pays: `amount` truncated to whole duffs, + /// minus the Core fee from protocol version 14. public let recipientAmount: UInt64 /// The exact fee for the selected notes. public let fee: UInt64 @@ -749,7 +750,7 @@ extension PlatformWalletManager { /// `coreFeePerByte` is the Core fee rate of a `.withdrawal`, required for /// it and ignored for the other kinds. A withdrawal's amount is the /// reserve for Core: the plan's `recipientAmount` is what reaches the Core - /// address after the Core fee, and the withdrawal must run with the same + /// address: the reserve's whole duffs minus the Core fee, and the withdrawal must run with the same /// rate (another rate throws `shieldedPlanChanged`). A withdrawal sweep is /// capped at the protocol's largest withdrawal. /// From 58ee1cbd61525c4ad5f72fbecc228e3d1a78c8fd Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 16:04:48 +0200 Subject: [PATCH 11/20] fix(platform-wallet): check the captured protocol version and fee right before a shielded spend is dispatched The SDK's protocol version can advance at any await after the check that follows the anchor fetch: while the proof is made or while the activity row and the recovery record are written. The notes were selected, the plan confirmed and the transition built at the version the spend captured, and consensus carves the active version's fee from the signed gross amount, so a spend dispatched after such a move could pay a fee and credit a recipient amount other than the confirmed ones. Transfer, unshield, withdrawal and identity top-up now share one check, made once the transition is built and again by save_spend_then_broadcast after its last awaited write: the SDK's version is the captured one, and the fee the network applies at it equals the selected and the built fee. The built-fee comparison no longer compares two old-version values. A refusal is a changed plan priced at the new version, sent as a spend that never left the wallet: the saved record is retired, the notes are released and the activity row fails. The mock SDK can now report a chosen protocol version in its answers, so tests make the SDK learn a newer one at a chosen moment. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/shielded/operations.rs | 407 ++++++++++++++++-- packages/rs-sdk/src/mock/sdk.rs | 16 +- 2 files changed, 388 insertions(+), 35 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index 3b76909fdf7..a38964c01ed 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -1619,9 +1619,18 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< platform_version, ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - // Built at the version the notes were selected and the plan checked at, the fee is - // the selected one; refuse anything else before it is broadcast. - ensure_built_fee(fee_used, exact_fee, selected_notes.len(), expected_plan)?; + // The fee the builder charged must be the selected one and the one the network applies + // at the SDK's version now; the same check runs again right before dispatch. + let dispatch_check = DispatchCheck { + sdk, + platform_version, + fee_kind: ShieldedSpendKind::IdentityTopUp.fee_kind(), + note_count: selected_notes.len(), + selected_fee: exact_fee, + built_fee: fee_used, + expected_plan, + }; + dispatch_check.ensure_holds()?; pending_entry = record_pending_activity( store, @@ -1653,6 +1662,7 @@ pub(in crate::wallet) async fn identity_top_up_from_pool_with_metadata< // identity-create paths accept the same class of outcome. broadcast_shielded_spend_with_redrive_with_metadata( sdk, + &dispatch_check, store, id, &pending_entry, @@ -2401,9 +2411,18 @@ pub async fn unshield_with_plan( platform_version, ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - // Built at the version the notes were selected and the plan checked at, the fee is - // the selected one; refuse anything else before it is broadcast. - ensure_built_fee(fee_used, exact_fee, selected_notes.len(), expected_plan)?; + // The fee the builder charged must be the selected one and the one the network applies + // at the SDK's version now; the same check runs again right before dispatch. + let dispatch_check = DispatchCheck { + sdk, + platform_version, + fee_kind: ShieldedSpendKind::Unshield.fee_kind(), + note_count: selected_notes.len(), + selected_fee: exact_fee, + built_fee: fee_used, + expected_plan, + }; + dispatch_check.ensure_holds()?; // Live activity: a confirmed Unshield is `direction out`, // counterparty = the 21-byte serialized PlatformAddress, exact @@ -2430,6 +2449,7 @@ pub async fn unshield_with_plan( trace!("Unshield: state transition built, saving and broadcasting..."); broadcast_shielded_spend_with_redrive( sdk, + &dispatch_check, store, id, &pending_entry, @@ -2609,9 +2629,18 @@ pub async fn transfer_with_plan( platform_version, ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - // Built at the version the notes were selected and the plan checked at, the fee is - // the selected one; refuse anything else before it is broadcast. - ensure_built_fee(fee_used, exact_fee, selected_notes.len(), expected_plan)?; + // The fee the builder charged must be the selected one and the one the network applies + // at the SDK's version now; the same check runs again right before dispatch. + let dispatch_check = DispatchCheck { + sdk, + platform_version, + fee_kind: ShieldedSpendKind::Transfer.fee_kind(), + note_count: selected_notes.len(), + selected_fee: exact_fee, + built_fee: fee_used, + expected_plan, + }; + dispatch_check.ensure_holds()?; // Live activity: a confirmed transfer is a `Sent` (direction out), // counterparty = the recipient's 43-byte raw Orchard address, memo @@ -2638,6 +2667,7 @@ pub async fn transfer_with_plan( trace!("Shielded transfer: state transition built, saving and broadcasting..."); broadcast_shielded_spend_with_redrive( sdk, + &dispatch_check, store, id, &pending_entry, @@ -2819,9 +2849,18 @@ pub async fn withdraw_with_plan( platform_version, ) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; - // Built at the version the notes were selected and the plan checked at, the fee is - // the selected one; refuse anything else before it is broadcast. - ensure_built_fee(fee_used, exact_fee, selected_notes.len(), expected_plan)?; + // The fee the builder charged must be the selected one and the one the network applies + // at the SDK's version now; the same check runs again right before dispatch. + let dispatch_check = DispatchCheck { + sdk, + platform_version, + fee_kind: kind.fee_kind(), + note_count: selected_notes.len(), + selected_fee: exact_fee, + built_fee: fee_used, + expected_plan, + }; + dispatch_check.ensure_holds()?; // Live activity: a Withdrawal (direction out), counterparty = the // Core output script bytes, exact metered fee. @@ -2847,6 +2886,7 @@ pub async fn withdraw_with_plan( trace!("Shielded withdrawal: state transition built, saving and broadcasting..."); broadcast_shielded_spend_with_redrive( sdk, + &dispatch_check, store, id, &pending_entry, @@ -3184,6 +3224,7 @@ async fn broadcast_identity_create_with_redrive( reservation, st, IDENTITY_CREATE_OPERATION, + || Ok(()), || broadcast_identity_create(sdk, st, identity_id, submitted_public_keys), ) .await @@ -3723,28 +3764,76 @@ fn ensure_version_unchanged( } /// Refuse, before it is broadcast, a built spend whose fee is not `selected_fee`, the fee its -/// `note_count` notes were selected (and, with `expected_plan`, confirmed) for: with a plan as -/// [`PlatformWalletError::ShieldedPlanChanged`], without one as a build error. +/// `note_count` notes were selected (and, with `expected_plan`, confirmed) for, or whose +/// `applied_fee` is not: the fee the network carves from the signed gross amount at the SDK's +/// version now, so that the recipient receives what was confirmed. With a plan the refusal is +/// [`PlatformWalletError::ShieldedPlanChanged`] carrying `applied_fee`, without one a build +/// error. fn ensure_built_fee( built_fee: Credits, selected_fee: Credits, + applied_fee: Credits, note_count: usize, expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { - if built_fee == selected_fee { + if built_fee == selected_fee && applied_fee == selected_fee { return Ok(()); } Err(match expected_plan { Some(_) => PlatformWalletError::ShieldedPlanChanged { - fresh_fee: built_fee, + fresh_fee: applied_fee, fresh_note_count: note_count, }, None => PlatformWalletError::ShieldedBuildError(format!( - "the built fee {built_fee} is not the selected fee {selected_fee}" + "the built fee {built_fee} and the fee the network applies {applied_fee} are not \ + the selected fee {selected_fee}" )), }) } +/// What a built shielded spend must still match when it is dispatched: the protocol version +/// it captured, and the fee it was selected, confirmed and built at. Checked once the +/// transition is built and again by [`save_spend_then_broadcast`] after every awaited write +/// that follows, because the SDK's version can advance at any `.await` (a verified query of +/// another task) while the build and the writes were made at the captured one. +struct DispatchCheck<'a> { + sdk: &'a Arc, + /// The version the spend captured to select its notes, check its plan and build. + platform_version: &'a PlatformVersion, + fee_kind: ShieldedFeeKind, + note_count: usize, + /// The fee the notes were selected (and, with a plan, confirmed) for. + selected_fee: Credits, + /// The fee the builder charged, which the signed gross amount carries. + built_fee: Credits, + expected_plan: Option<&'a [u8; 32]>, +} + +impl DispatchCheck<'_> { + /// The SDK's version is the captured one, and the fee the network applies at it is the + /// selected and built one, so the recipient receives the amount that was confirmed. + fn ensure_holds(&self) -> Result<(), PlatformWalletError> { + ensure_version_unchanged( + self.sdk, + self.platform_version, + self.fee_kind, + self.note_count, + self.expected_plan, + )?; + let applied_fee = self + .fee_kind + .compute(self.note_count.max(SPEND_MIN_ACTIONS), self.sdk.version()) + .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; + ensure_built_fee( + self.built_fee, + self.selected_fee, + applied_fee, + self.note_count, + self.expected_plan, + ) + } +} + /// Plan a `kind` spend of `amount` from `account`'s notes: the notes the spend would select /// now and their exact fee ([`note_selection::plan_spend`](super::note_selection::plan_spend)). /// Reads the store only; nothing is reserved. @@ -4081,6 +4170,7 @@ pub(super) const MAX_REDRIVE_ATTEMPTS: u32 = 3; #[allow(clippy::too_many_arguments)] async fn broadcast_shielded_spend_with_redrive( sdk: &Arc, + dispatch_check: &DispatchCheck<'_>, store: &Arc>, id: SubwalletId, pending_entry: &Option, @@ -4094,6 +4184,7 @@ async fn broadcast_shielded_spend_with_redrive( ) -> Result { broadcast_shielded_spend_with_redrive_with_metadata( sdk, + dispatch_check, store, id, pending_entry, @@ -4123,6 +4214,7 @@ async fn broadcast_shielded_spend_with_redrive( #[allow(clippy::too_many_arguments)] async fn broadcast_shielded_spend_with_redrive_with_metadata( sdk: &Arc, + dispatch_check: &DispatchCheck<'_>, store: &Arc>, id: SubwalletId, pending_entry: &Option, @@ -4144,6 +4236,7 @@ async fn broadcast_shielded_spend_with_redrive_with_metadata( reservation, state_transition, operation, + || dispatch_check.ensure_holds(), || broadcast_shielded_spend_classified(sdk, state_transition, operation, wait), ) .await @@ -4162,13 +4255,17 @@ async fn broadcast_shielded_spend_with_redrive_with_metadata( /// the caller releases them ([`settle_failed_spend`]), and so does a spend /// dropped while a save waits for the store. /// -/// Once the record is saved the notes are handed over, with nothing awaited +/// Right after the record is saved, `still_dispatchable` is the last check before dispatch: +/// a spend that no longer matches what it was built and confirmed for is refused with nothing +/// broadcast, as one whose transition never left the wallet ([`settle_failed_spend`]). +/// +/// Once the record is saved and checked the notes are handed over, with nothing awaited /// in between: from then on they belong to the spend's resolution, whatever /// happens to this call. An exit or a drop during the dispatches or the /// result wait leaves the reservation and the record, which a restart /// restores and the redrive pass resolves. #[allow(clippy::too_many_arguments)] -async fn save_spend_then_broadcast( +async fn save_spend_then_broadcast( store: &Arc>, id: SubwalletId, pending_entry: &Option, @@ -4178,10 +4275,12 @@ async fn save_spend_then_broadcast( reservation: &mut NoteReservation, state_transition: &StateTransition, operation: &'static str, + still_dispatchable: R, broadcast: B, ) -> Result where S: ShieldedStore, + R: FnOnce() -> Result<(), PlatformWalletError>, B: FnOnce() -> Fut, Fut: Future>, { @@ -4199,6 +4298,16 @@ where anchor_height, ) .await?; + // The last check, after every write awaited above: what the spend was built and + // confirmed for (`still_dispatchable`) must still hold. When it does not, nothing is + // sent and the spend fails as one that never left the wallet, which retires the record + // just saved, releases the notes and fails the activity row. + if let Err(error) = still_dispatchable() { + return Err(SpendFailure { + error, + never_delivered: true, + }); + } // Saved: the notes are the spend's resolution's from here on. reservation.hand_over(); broadcast().await @@ -6725,9 +6834,22 @@ mod redrive_tests { id: SubwalletId, ) -> Result<(), SpendFailure> { let transition = self.transition(); + let fee = ShieldedFeeKind::Base + .compute(spend.notes.len().max(SPEND_MIN_ACTIONS), sdk.version()) + .expect("a fee"); + let dispatch_check = DispatchCheck { + sdk, + platform_version: sdk.version(), + fee_kind: ShieldedFeeKind::Base, + note_count: spend.notes.len(), + selected_fee: fee, + built_fee: fee, + expected_plan: None, + }; match self { Self::Shared => broadcast_shielded_spend_with_redrive_with_metadata( sdk, + &dispatch_check, &spend.store, id, &spend.entry, @@ -6941,6 +7063,7 @@ mod redrive_tests { &mut reservation, &transition, "transfer", + || Ok(()), || { // Nothing is dispatched before the record is on the file. let durable = @@ -7074,6 +7197,7 @@ mod redrive_tests { &mut spend.reservation, &transition, "transfer", + || Ok(()), || async { dispatched.store(true, Ordering::SeqCst); Err(match outcome { @@ -8242,6 +8366,11 @@ mod select_recorded_spends_tests { /// `cmx` as the leaf at `position` makes `witness(position, d).root(cmx)` /// reproduce the tree's anchor at depth `d`. pub(super) fn real_note(position: u64) -> ShieldedNote { + real_note_worth(position, 100_000) + } + + /// [`real_note`] worth `value` credits. + pub(super) fn real_note_worth(position: u64, value: u64) -> ShieldedNote { let keys = OrchardKeySet::from_seed(&[0x42; 32], Network::Testnet, 0) .expect("ZIP-32 derivation from a fixed seed"); let recipient = keys.default_address; @@ -8264,7 +8393,7 @@ mod select_recorded_spends_tests { }) .expect("a canonical rseed exists"); - let value = NoteValue::from_raw(100_000); + let value = NoteValue::from_raw(value); let note = Note::from_parts(recipient, value, rho, rseed) .into_option() .expect("valid note parts"); @@ -8284,7 +8413,7 @@ mod select_recorded_spends_tests { nullifier: [0x07; 32], block_height: 1, is_spent: false, - value: 100_000, + value: note.value().inner(), note_data, } } @@ -8709,13 +8838,13 @@ mod spend_plan_tests { #[test] fn should_refuse_a_built_fee_other_than_the_planned_one() { let digest = [7; 32]; - ensure_built_fee(500, 500, 3, Some(&digest)).expect("the planned fee"); - ensure_built_fee(500, 500, 3, None).expect("the selected fee"); + ensure_built_fee(500, 500, 500, 3, Some(&digest)).expect("the planned fee"); + ensure_built_fee(500, 500, 500, 3, None).expect("the selected fee"); assert!( matches!( - ensure_built_fee(510, 500, 3, Some(&digest)), + ensure_built_fee(510, 500, 500, 3, Some(&digest)), Err(PlatformWalletError::ShieldedPlanChanged { - fresh_fee: 510, + fresh_fee: 500, fresh_note_count: 3 }) ), @@ -8723,11 +8852,29 @@ mod spend_plan_tests { ); assert!( matches!( - ensure_built_fee(510, 500, 3, None), + ensure_built_fee(510, 500, 500, 3, None), Err(PlatformWalletError::ShieldedBuildError(_)) ), "an unplanned spend" ); + // Built and selected at the old version, the network applies the new one's fee. + assert!( + matches!( + ensure_built_fee(500, 500, 530, 3, Some(&digest)), + Err(PlatformWalletError::ShieldedPlanChanged { + fresh_fee: 530, + fresh_note_count: 3 + }) + ), + "a planned spend whose fee moved" + ); + assert!( + matches!( + ensure_built_fee(500, 500, 530, 3, None), + Err(PlatformWalletError::ShieldedBuildError(_)) + ), + "an unplanned spend whose fee moved" + ); } /// With a plan, notes another spend took or a balance that no longer covers it are a @@ -8848,13 +8995,18 @@ mod spend_plan_tests { impl VersionMovesDuringAnchorFetch { async fn new(kind: ShieldedSpendKind) -> Self { + Self::serving(kind, PlatformVersion::latest().protocol_version).await + } + + /// The mocked answers report protocol version `served`, so one at the SDK's own + /// version teaches it nothing until [`Self::move_version_now`]. + async fn serving(kind: ShieldedSpendKind, served: u32) -> Self { use crate::wallet::shielded::file_store::FileBackedShieldedStore; use dash_sdk::query_types::{NoParamQuery, ShieldedAnchors}; let path = select_recorded_spends_tests::temp_tree_path("version_moves"); let mut store = FileBackedShieldedStore::open_path(&path, 100).expect("a store"); - let mut owned = select_recorded_spends_tests::real_note(0); - owned.value = 10 * NOTE; + let owned = select_recorded_spends_tests::real_note_worth(0, 10 * NOTE); store.append_commitment(&owned.cmx, true).expect("a leaf"); store.checkpoint_tree(1).expect("a checkpoint"); let anchor = store.tree_anchor().expect("an anchor"); @@ -8866,6 +9018,7 @@ mod spend_plan_tests { .build() .expect("a mock SDK"); assert_eq!(sdk.protocol_version_number(), 13, "the spend starts at v13"); + sdk.mock().set_response_protocol_version(served); sdk.mock() .expect_fetch(NoParamQuery {}, Some(ShieldedAnchors(vec![anchor]))) .await @@ -8894,7 +9047,42 @@ mod spend_plan_tests { kind: ShieldedSpendKind, expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { - let keys = OrchardKeySet::from_seed(&[0x42; 64], Network::Testnet, 0).expect("keys"); + self.run_with(kind, expected_plan, &UnreachableProver).await + } + + /// The SDK learns the newest protocol version from the next answer it verifies, as + /// a verified query of another task would teach it. + fn move_version_now(sdk: &Arc) { + use dash_sdk::query_types::ShieldedAnchors; + + std::thread::scope(|scope| { + scope.spawn(|| { + sdk.as_ref() + .clone() + .mock() + .set_response_protocol_version(PlatformVersion::latest().protocol_version); + tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .expect("a runtime") + .block_on(ShieldedAnchors::fetch_current_with_metadata(sdk)) + .expect("an answer"); + }); + }); + assert_eq!( + sdk.protocol_version_number(), + PlatformVersion::latest().protocol_version, + "the SDK learned the newest version" + ); + } + + async fn run_with( + &self, + kind: ShieldedSpendKind, + expected_plan: Option<&[u8; 32]>, + prover: &P, + ) -> Result<(), PlatformWalletError> { + let keys = OrchardKeySet::from_seed(&[0x42; 32], Network::Testnet, 0).expect("keys"); let (sdk, store) = (&self.sdk, &self.store); match kind { ShieldedSpendKind::Transfer => { @@ -8908,7 +9096,7 @@ mod spend_plan_tests { &keys.default_address, NOTE, [0; 36], - &UnreachableProver, + prover, expected_plan, ) .await @@ -8923,7 +9111,7 @@ mod spend_plan_tests { 0, &PlatformAddress::P2pkh([9; 20]), NOTE, - &UnreachableProver, + prover, expected_plan, ) .await @@ -8939,7 +9127,7 @@ mod spend_plan_tests { &dashcore::Address::dummy(Network::Testnet, 1), NOTE, core_fee_per_byte, - &UnreachableProver, + prover, expected_plan, ) .await @@ -8953,7 +9141,7 @@ mod spend_plan_tests { 0, Identifier::new([5; 32]), NOTE, - &UnreachableProver, + prover, expected_plan, ) .await @@ -9034,4 +9222,157 @@ mod spend_plan_tests { } } } + + /// When, after the spend checked the version at the anchor, the SDK learns the newer one. + #[derive(Clone, Copy, Debug)] + enum LearnsVersion { + /// While the proof is made, as a verified query of another task answers meanwhile. + WhileProving, + /// While the spend waits for the store to record its activity row. + WhileRecordingActivity, + } + + /// The real prover, which first does what `when` asks of the world. + struct VersionMovingProver { + when: LearnsVersion, + sdk: Arc, + store: Arc>, + held: std::sync::Mutex< + Option< + tokio::sync::OwnedRwLockWriteGuard< + crate::wallet::shielded::file_store::FileBackedShieldedStore, + >, + >, + >, + key: &'static crate::wallet::shielded::prover::CachedOrchardProver, + } + + impl OrchardProver for VersionMovingProver { + fn proving_key(&self) -> &ProvingKey { + match self.when { + LearnsVersion::WhileProving => { + VersionMovesDuringAnchorFetch::move_version_now(&self.sdk) + } + // The store stays locked from here, so the spend parks at the write that + // records its activity row. + LearnsVersion::WhileRecordingActivity => { + *self.held.lock().expect("the lock") = Some( + self.store + .clone() + .try_write_owned() + .expect("nobody holds the store while proving"), + ); + } + } + OrchardProver::proving_key(&self.key) + } + } + + /// The version check at the anchor passed, and the SDK learns the newer version later, + /// while the spend is proved or while its activity row is recorded: every spend kind is + /// refused as a changed plan priced at the new version, nothing is broadcast, and no + /// note stays reserved, no activity row pending and no recovery record saved. + #[tokio::test] + async fn should_refuse_a_spend_when_the_protocol_version_moved_after_the_anchor_check() { + let key: &'static crate::wallet::shielded::prover::CachedOrchardProver = + Box::leak(Box::default()); + for when in [ + LearnsVersion::WhileProving, + LearnsVersion::WhileRecordingActivity, + ] { + for kind in [ + ShieldedSpendKind::Transfer, + ShieldedSpendKind::Unshield, + ShieldedSpendKind::Withdrawal { + core_fee_per_byte: 1, + }, + ShieldedSpendKind::IdentityTopUp, + ] { + let case = VersionMovesDuringAnchorFetch::serving(kind, 13).await; + let prover = VersionMovingProver { + when, + sdk: case.sdk.clone(), + store: case.store.clone(), + held: std::sync::Mutex::new(None), + key, + }; + let mut spend = Box::pin(case.run_with(kind, Some(&case.plan.digest), &prover)); + let refused = match when { + LearnsVersion::WhileProving => spend.await, + LearnsVersion::WhileRecordingActivity => { + // Poll until the spend parks on the held store lock. + loop { + let polled = std::future::poll_fn(|cx| { + std::task::Poll::Ready(spend.as_mut().poll(cx)) + }) + .await; + if let std::task::Poll::Ready(done) = polled { + panic!("{kind:?} was not parked on the store: {done:?}"); + } + if prover.held.lock().expect("the lock").is_some() { + break; + } + tokio::task::yield_now().await; + } + VersionMovesDuringAnchorFetch::move_version_now(&case.sdk); + drop(prover.held.lock().expect("the lock").take()); + spend.await + } + }; + + assert!( + matches!( + refused, + Err(PlatformWalletError::ShieldedPlanChanged { .. }) + ), + "{when:?} {kind:?} is refused as a changed plan, got {refused:?}" + ); + let fresh = plan_spend( + &case.sdk, + &case.store, + WALLET_ID, + 0, + kind, + ShieldedSpendAmount::Exact(NOTE), + ) + .await + .expect("plans at the new version"); + assert_ne!( + fresh.fee, case.plan.fee, + "the fee moved ({when:?} {kind:?})" + ); + match &refused { + Err(PlatformWalletError::ShieldedPlanChanged { + fresh_fee, + fresh_note_count, + }) => assert_eq!( + (*fresh_fee, *fresh_note_count), + (fresh.fee, fresh.note_count()), + "{when:?} {kind:?}" + ), + other => panic!("{when:?} {kind:?}: got {other:?}"), + } + let guard = case.store.read().await; + assert_eq!( + guard.get_unspent_notes(ID).expect("notes").len(), + 1, + "the note is released ({when:?} {kind:?})" + ); + assert!( + guard + .get_activity(ID, 0, 10) + .expect("activity") + .iter() + .all(|row| row.status != ShieldedActivityStatus::Pending), + "no activity row reads in flight ({when:?} {kind:?})" + ); + assert!( + guard.pending_redrives(ID).expect("records").is_empty(), + "no recovery record stays ({when:?} {kind:?})" + ); + drop(guard); + let _ = std::fs::remove_file(&case.path); + } + } + } } diff --git a/packages/rs-sdk/src/mock/sdk.rs b/packages/rs-sdk/src/mock/sdk.rs index 75da6f48760..a2cfae3014b 100644 --- a/packages/rs-sdk/src/mock/sdk.rs +++ b/packages/rs-sdk/src/mock/sdk.rs @@ -48,6 +48,9 @@ pub struct MockDashPlatformSdk { /// The block time the metadata of a response answered from an expectation reports /// ([Self::set_response_time_ms]); 0 unless set. response_time_ms: u64, + /// The protocol version the metadata of a response answered from an expectation reports + /// ([Self::set_response_protocol_version]); the latest unless set. + response_protocol_version: u32, /// The block height the metadata of a response answered from an expectation reports /// ([Self::set_response_height]); 0 unless set. response_height: u64, @@ -90,6 +93,7 @@ impl MockDashPlatformSdk { dapi, sdk: ArcSwapOption::new(None), response_time_ms: 0, + response_protocol_version: dpp::version::LATEST_VERSION, response_height: 0, response_heights_of: BTreeMap::new(), response_heights_for: BTreeMap::new(), @@ -103,6 +107,14 @@ impl MockDashPlatformSdk { self } + /// Sets the protocol version the metadata of every response answered from an expectation + /// reports, for code under test that needs the SDK to learn a newer version at a chosen + /// moment: the SDK ratchets to the version of the next response it verifies. + pub fn set_response_protocol_version(&mut self, protocol_version: u32) -> &mut Self { + self.response_protocol_version = protocol_version; + self + } + /// Sets the block height the metadata of every response answered from an expectation /// reports, for code under test that reads the height a response was proved at. pub fn set_response_height(&mut self, height: u64) -> &mut Self { @@ -648,14 +660,14 @@ impl MockDashPlatformSdk { let key = Key::new(&request); let data = match self.from_proof_expectations.get(&key) { - // Report the latest protocol version so the proof path's ratchet + // Report the latest protocol version unless set, so the proof path's ratchet // (`maybe_update_protocol_version`) fires as it would against a real // network; `default()` reports 0, which the ratchet ignores. Some(d) => ( ( Option::::mock_deserialize(self, d), ResponseMetadata { - protocol_version: dpp::version::LATEST_VERSION, + protocol_version: self.response_protocol_version, time_ms: self.response_time_ms, height: self .response_heights_for From defb0901742c17e5fb1f6465ab57c33bb5ca2632 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 18:16:43 +0200 Subject: [PATCH 12/20] fix(platform-wallet): check a shielded spend against the verified network protocol version A pinned SDK keeps its operation version while verified answers still advance the network observation, so a plan priced at the pin passed the version check although the network applies its fee at its own version. The post-anchor and dispatch checks, and planning, now compare against the verified network version as well and refuse instead of overriding the pin. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/shielded/operations.rs | 261 +++++++++++++++++- 1 file changed, 246 insertions(+), 15 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index a38964c01ed..41bedeffba1 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -3731,12 +3731,17 @@ async fn reserve_unspent_notes( .await } -/// Refuse a spend, before anything is built, saved or broadcast, when the SDK's protocol -/// version is no longer `platform_version`, the one the spend captured to select its notes -/// and check its plan: the anchor fetch that precedes the build can teach the SDK a newer -/// one, and the fee shown and confirmed was priced at the old. With `expected_plan` the -/// refusal is [`PlatformWalletError::ShieldedPlanChanged`] carrying the fee at the new -/// version for the same notes; without one, a build error naming both versions. +/// Refuse a spend, before anything is built, saved or broadcast, when the protocol version +/// the network applies is no longer `platform_version`, the one the spend captured to select +/// its notes and check its plan: the SDK's own version moved (the anchor fetch that precedes +/// the build can teach it a newer one), or the SDK's last verified network observation differs +/// from it. The two are not the same: a version pinned with `SdkBuilder::with_version` never +/// moves, while verified answers still advance the observation, and the network then applies +/// its fee at its own version whatever the SDK builds at. The pin is never overridden; the +/// spend is refused instead. With `expected_plan` the refusal is +/// [`PlatformWalletError::ShieldedPlanChanged`] carrying the fee at the version the network +/// applies for the same notes; without one, a build error naming both versions. A network +/// version this SDK has no tables for is a build error either way: it cannot be priced. fn ensure_version_unchanged( sdk: &Arc, platform_version: &PlatformVersion, @@ -3745,17 +3750,28 @@ fn ensure_version_unchanged( expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { let current = sdk.version(); - if current.protocol_version == platform_version.protocol_version { + let network = sdk.protocol_version_info().verified_version; + let captured = platform_version.protocol_version; + if current.protocol_version == captured && !matches!(network, Some(n) if n != captured) { return Ok(()); } + // What the network applies: its verified version when the SDK has one, else the SDK's. + let applied_version = match network { + Some(n) => PlatformVersion::get(n).map_err(|_| { + PlatformWalletError::ShieldedBuildError(format!( + "the network runs protocol version {n}, which this SDK does not support, so the spend built at protocol version {captured} is not priced" + )) + })?, + None => current, + }; if expected_plan.is_none() { return Err(PlatformWalletError::ShieldedBuildError(format!( - "the protocol version moved from {} to {} while the spend was prepared", - platform_version.protocol_version, current.protocol_version + "the protocol version moved from {captured} to {} while the spend was prepared", + applied_version.protocol_version ))); } let fresh_fee = fee_kind - .compute(note_count.max(SPEND_MIN_ACTIONS), current) + .compute(note_count.max(SPEND_MIN_ACTIONS), applied_version) .map_err(|e| PlatformWalletError::ShieldedBuildError(e.to_string()))?; Err(PlatformWalletError::ShieldedPlanChanged { fresh_fee, @@ -3763,6 +3779,24 @@ fn ensure_version_unchanged( }) } +/// Refuse to plan a spend, whose fee is priced at the SDK's version, when the SDK has verified +/// a different network version: the network would apply its fee at its own, and the SDK's +/// version is a pin that is not overridden here. Plan again once the SDK builds at the version +/// the network runs. +fn ensure_plan_version_matches_network( + sdk: &Arc, +) -> Result<(), PlatformWalletError> { + let version = sdk.version().protocol_version; + match sdk.protocol_version_info().verified_version { + Some(network) if network != version => Err(PlatformWalletError::ShieldedBuildError( + format!( + "the SDK builds at protocol version {version} but the network runs {network}, so a spend would be priced at a version the network does not apply" + ), + )), + _ => Ok(()), + } +} + /// Refuse, before it is broadcast, a built spend whose fee is not `selected_fee`, the fee its /// `note_count` notes were selected (and, with `expected_plan`, confirmed) for, or whose /// `applied_fee` is not: the fee the network carves from the signed gross amount at the SDK's @@ -3845,6 +3879,7 @@ pub async fn plan_spend( kind: ShieldedSpendKind, amount: ShieldedSpendAmount, ) -> Result { + ensure_plan_version_matches_network(sdk)?; let unspent = store .read() .await @@ -9001,6 +9036,17 @@ mod spend_plan_tests { /// The mocked answers report protocol version `served`, so one at the SDK's own /// version teaches it nothing until [`Self::move_version_now`]. async fn serving(kind: ShieldedSpendKind, served: u32) -> Self { + Self::serving_with(kind, served, false).await + } + + /// [`Self::serving`] for an SDK whose operation version is pinned to v13 + /// (`SdkBuilder::with_version`): it still learns the verified network version from + /// the answers, but never moves its own. + async fn serving_pinned(kind: ShieldedSpendKind, served: u32) -> Self { + Self::serving_with(kind, served, true).await + } + + async fn serving_with(kind: ShieldedSpendKind, served: u32, pinned: bool) -> Self { use crate::wallet::shielded::file_store::FileBackedShieldedStore; use dash_sdk::query_types::{NoParamQuery, ShieldedAnchors}; @@ -9013,10 +9059,15 @@ mod spend_plan_tests { store.save_note(ID, &owned).expect("a note"); let store = Arc::new(RwLock::new(store)); - let mut sdk = dash_sdk::SdkBuilder::new_mock() - .with_initial_version(PlatformVersion::get(13).expect("v13")) - .build() - .expect("a mock SDK"); + let v13 = PlatformVersion::get(13).expect("v13"); + let builder = dash_sdk::SdkBuilder::new_mock(); + let mut sdk = if pinned { + builder.with_version(v13) + } else { + builder.with_initial_version(v13) + } + .build() + .expect("a mock SDK"); assert_eq!(sdk.protocol_version_number(), 13, "the spend starts at v13"); sdk.mock().set_response_protocol_version(served); sdk.mock() @@ -9230,6 +9281,9 @@ mod spend_plan_tests { WhileProving, /// While the spend waits for the store to record its activity row. WhileRecordingActivity, + /// While the proof is made, a pinned SDK verifies an answer of the newest network + /// version: its own version never moves, only the verified network version does. + VerifiedNetworkWhileProving, } /// The real prover, which first does what `when` asks of the world. @@ -9253,6 +9307,10 @@ mod spend_plan_tests { LearnsVersion::WhileProving => { VersionMovesDuringAnchorFetch::move_version_now(&self.sdk) } + LearnsVersion::VerifiedNetworkWhileProving => self + .sdk + .mock_verified_protocol_version(PlatformVersion::latest().protocol_version) + .expect("a mock SDK"), // The store stays locked from here, so the spend parks at the write that // records its activity row. LearnsVersion::WhileRecordingActivity => { @@ -9298,7 +9356,9 @@ mod spend_plan_tests { }; let mut spend = Box::pin(case.run_with(kind, Some(&case.plan.digest), &prover)); let refused = match when { - LearnsVersion::WhileProving => spend.await, + LearnsVersion::WhileProving | LearnsVersion::VerifiedNetworkWhileProving => { + spend.await + } LearnsVersion::WhileRecordingActivity => { // Poll until the spend parks on the held store lock. loop { @@ -9375,4 +9435,175 @@ mod spend_plan_tests { } } } + + /// What a pinned v13 SDK's spend leaves behind when it is refused as a changed plan priced + /// at the newest network version: the note released, no activity row, no recovery record. + async fn assert_pinned_spend_refused( + case: &VersionMovesDuringAnchorFetch, + kind: ShieldedSpendKind, + refused: Result<(), PlatformWalletError>, + ) { + let network = PlatformVersion::latest().protocol_version; + let info = case.sdk.protocol_version_info(); + assert_eq!(info.verified_version, Some(network), "{kind:?}"); + assert_eq!( + case.sdk.protocol_version_number(), + 13, + "the pin held ({kind:?})" + ); + let at_network = kind + .fee_kind() + .compute(SPEND_MIN_ACTIONS, PlatformVersion::latest()) + .expect("the fee at the network version"); + assert_ne!(at_network, case.plan.fee, "the fee moved ({kind:?})"); + match refused { + Err(PlatformWalletError::ShieldedPlanChanged { + fresh_fee, + fresh_note_count, + }) => assert_eq!( + (fresh_fee, fresh_note_count), + (at_network, 1), + "priced at the network version ({kind:?})" + ), + other => panic!("{kind:?}: got {other:?}"), + } + let guard = case.store.read().await; + assert_eq!( + guard.get_unspent_notes(ID).expect("notes").len(), + 1, + "the note is released ({kind:?})" + ); + assert!( + guard + .get_activity(ID, 0, 10) + .expect("activity") + .iter() + .all(|row| row.status != ShieldedActivityStatus::Pending), + "no activity row reads in flight ({kind:?})" + ); + assert!( + guard.pending_redrives(ID).expect("records").is_empty(), + "no recovery record ({kind:?})" + ); + } + + const EVERY_SPEND_KIND: [ShieldedSpendKind; 4] = [ + ShieldedSpendKind::Transfer, + ShieldedSpendKind::Unshield, + ShieldedSpendKind::Withdrawal { + core_fee_per_byte: 1, + }, + ShieldedSpendKind::IdentityTopUp, + ]; + + /// The SDK is pinned to v13 and has verified an answer of the newest network version: its + /// operation version stays v13, so only the verified network version shows the plan was + /// priced at a version the network no longer applies. Every spend kind is refused before + /// it builds. + #[tokio::test] + async fn should_refuse_a_pinned_sdk_spend_whose_verified_network_version_differs() { + for kind in EVERY_SPEND_KIND { + let case = VersionMovesDuringAnchorFetch::serving_pinned(kind, 13).await; + // The plan was made before the SDK verified anything newer. + case.sdk + .mock_verified_protocol_version(PlatformVersion::latest().protocol_version) + .expect("a mock SDK"); + + let refused = case.run(kind, Some(&case.plan.digest)).await; + + assert_pinned_spend_refused(&case, kind, refused).await; + let _ = std::fs::remove_file(&case.path); + } + } + + /// The same, learned after the check at the anchor passed: while the spend is proved. + #[tokio::test] + async fn should_refuse_a_pinned_sdk_spend_when_the_network_version_is_verified_while_proving() { + let key: &'static crate::wallet::shielded::prover::CachedOrchardProver = + Box::leak(Box::default()); + for kind in EVERY_SPEND_KIND { + let case = VersionMovesDuringAnchorFetch::serving_pinned(kind, 13).await; + let prover = VersionMovingProver { + when: LearnsVersion::VerifiedNetworkWhileProving, + sdk: case.sdk.clone(), + store: case.store.clone(), + held: std::sync::Mutex::new(None), + key, + }; + + let refused = case.run_with(kind, Some(&case.plan.digest), &prover).await; + + assert_pinned_spend_refused(&case, kind, refused).await; + let _ = std::fs::remove_file(&case.path); + } + } + + /// A pinned SDK that already verified a different network version plans nothing: the fee + /// would be priced at a version the network does not apply, and the pin is not overridden. + #[tokio::test] + async fn should_refuse_to_plan_with_a_pinned_sdk_whose_verified_network_version_differs() { + let network = PlatformVersion::latest().protocol_version; + let case = + VersionMovesDuringAnchorFetch::serving_pinned(ShieldedSpendKind::Unshield, 13).await; + case.sdk + .mock_verified_protocol_version(network) + .expect("a mock SDK"); + + let planned = plan_spend( + &case.sdk, + &case.store, + WALLET_ID, + 0, + ShieldedSpendKind::Unshield, + ShieldedSpendAmount::Exact(NOTE), + ) + .await; + + assert!( + matches!(&planned, Err(PlatformWalletError::ShieldedBuildError(message)) + if message.contains("13") && message.contains(&network.to_string())), + "got {planned:?}" + ); + let _ = std::fs::remove_file(&case.path); + } + + /// The network runs a protocol version this SDK has no tables for: the spend cannot be + /// priced at it, so it is refused as a build error, planned or not. + #[tokio::test] + async fn should_refuse_a_spend_when_the_verified_network_version_is_unsupported() { + let unsupported = PlatformVersion::latest().protocol_version + 1; + for planned in [true, false] { + let case = + VersionMovesDuringAnchorFetch::serving_pinned(ShieldedSpendKind::Unshield, 13) + .await; + case.sdk + .mock_verified_protocol_version(unsupported) + .expect("a mock SDK"); + + let refused = case + .run( + ShieldedSpendKind::Unshield, + planned.then_some(&case.plan.digest), + ) + .await; + + assert!( + matches!(&refused, Err(PlatformWalletError::ShieldedBuildError(message)) + if message.contains(&unsupported.to_string()) + && message.contains("does not support")), + "planned={planned}: got {refused:?}" + ); + assert_eq!( + case.store + .read() + .await + .get_unspent_notes(ID) + .expect("notes") + .len(), + 1, + "the note is released" + ); + let _ = std::fs::remove_file(&case.path); + } + } } From 13bf4e5c55829a390b2365f5ff54d777e3a17d27 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 18:33:18 +0200 Subject: [PATCH 13/20] fix(platform-wallet): keep recovery from dispatching a shielded spend whose captured context changed A saved spend record is dispatchable by the redrive pass from the moment it is saved, before the foreground's last check, and again after a restart. The record now keeps the context its spend was priced and built in (operation version, verified network version, fee model, planned fee) in a versioned nullable column, and the redrive pass re-broadcasts it only while that context still holds. Records saved without one are re-broadcast as before. Co-Authored-By: Claude Opus 5.5 --- .../src/shielded_send.rs | 1 + packages/rs-platform-wallet/README.md | 10 + .../rs-platform-wallet/src/manager/load.rs | 1 + .../src/wallet/platform_wallet.rs | 1 + .../src/wallet/shielded/balance_tests.rs | 1 + .../src/wallet/shielded/coordinator.rs | 7 + .../src/wallet/shielded/file_store.rs | 162 +++++++- .../src/wallet/shielded/operations.rs | 355 +++++++++++++++++- .../src/wallet/shielded/store.rs | 82 ++++ .../wallet/shielded/viewing_key_bind_tests.rs | 2 + 10 files changed, 613 insertions(+), 9 deletions(-) diff --git a/packages/rs-platform-wallet-ffi/src/shielded_send.rs b/packages/rs-platform-wallet-ffi/src/shielded_send.rs index 6a11d4b3060..d3ed3e65b6e 100644 --- a/packages/rs-platform-wallet-ffi/src/shielded_send.rs +++ b/packages/rs-platform-wallet-ffi/src/shielded_send.rs @@ -2873,6 +2873,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: true, + spend_context: None, anchor_height: None, }, ) diff --git a/packages/rs-platform-wallet/README.md b/packages/rs-platform-wallet/README.md index 7e38a91f9f4..a2a971edefb 100644 --- a/packages/rs-platform-wallet/README.md +++ b/packages/rs-platform-wallet/README.md @@ -188,6 +188,16 @@ the unconditional `clear_pending` defeats the protection it gives: a cleanup that runs after a purge, a rebind or a wallet's replacement would release a newer attempt's notes or delete its records. +A note spend's saved record also keeps the protocol context the spend was +priced and built in (`PendingRedrive::spend_context`, a `SpendContext`: the +operation version, the verified network version, the fee model and the planned +fee), and `PendingRedrive` struct literals require it. The redrive pass +re-broadcasts a record only while that context still holds, so a store must +keep it with the record and give it back unchanged after a restart; +`FileBackedShieldedStore` keeps it in a versioned `spend_context` column, NULL +for a record saved before it was kept, which is re-broadcast with nothing +checked, and keeps without loading a row whose context does not read. + Anchored note reservations and saved records now keep the proved height of the anchor set their anchor was read from: `set_pending_spend` takes an `anchor_height: Option`, `StalePendingSpend` carries it as a fourth diff --git a/packages/rs-platform-wallet/src/manager/load.rs b/packages/rs-platform-wallet/src/manager/load.rs index 002186924f9..1118177ece7 100644 --- a/packages/rs-platform-wallet/src/manager/load.rs +++ b/packages/rs-platform-wallet/src/manager/load.rs @@ -2122,6 +2122,7 @@ mod private_payment_hold_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, PrivateContactPayment { diff --git a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs index d15df075a30..c76b7cea63d 100644 --- a/packages/rs-platform-wallet/src/wallet/platform_wallet.rs +++ b/packages/rs-platform-wallet/src/wallet/platform_wallet.rs @@ -3669,6 +3669,7 @@ mod private_contact_request_redrive_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/balance_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/balance_tests.rs index b9700306b2e..9cdadf3e739 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/balance_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/balance_tests.rs @@ -365,6 +365,7 @@ async fn local_balance_restores_funds_and_durable_pending_reservations_offline() attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs b/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs index 3720a2deefe..2890813a7f1 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/coordinator.rs @@ -2932,6 +2932,7 @@ mod tests { attempts: 0, identity_nonce_finalized: true, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, cmxs, @@ -3506,6 +3507,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; coordinator @@ -3883,6 +3885,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; coordinator @@ -3997,6 +4000,7 @@ mod tests { attempts: 0, identity_nonce_finalized: true, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -4498,6 +4502,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: Some(*anchor_height), }, ) @@ -4603,6 +4608,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -4702,6 +4708,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/file_store.rs b/packages/rs-platform-wallet/src/wallet/shielded/file_store.rs index 1b22d0a32f7..90ff623ec0b 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/file_store.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/file_store.rs @@ -24,7 +24,8 @@ use grovedb_commitment_tree::{ClientPersistentCommitmentTree, Position, Retentio use super::balance::{ShieldedBalanceSource, ShieldedLocalAccountBalance}; use super::store::{ PendingRedrive, PrivateContactPayment, PrivatePaymentEntry, PrivatePaymentRecord, ShieldedNote, - ShieldedOutgoingNote, ShieldedStore, StalePendingSpend, SubwalletId, SubwalletState, + ShieldedOutgoingNote, ShieldedStore, SpendContext, StalePendingSpend, SubwalletId, + SubwalletState, }; use crate::error::PlatformWalletError; use crate::wallet::platform_wallet::WalletId; @@ -189,10 +190,25 @@ impl FileBackedShieldedStore { .transaction() .map_err(|e| FileShieldedStoreError::Storage(format!("begin redrive: {e}")))?; let nullifier_blob: Vec = redrive.nullifiers.iter().flatten().copied().collect(); + // A context with no layout is refused, not saved without: the record would + // then be re-broadcast with nothing checked. + let spend_context = match redrive.spend_context { + Some(context) => Some( + context + .to_bytes() + .ok_or_else(|| { + FileShieldedStoreError::Storage( + "the spend's protocol context has no stored form".to_string(), + ) + })? + .to_vec(), + ), + None => None, + }; tx.execute( "INSERT OR REPLACE INTO shielded_pending_spends \ - (wallet_id, account_index, activity_id, anchor, nullifiers, st_bytes, attempts, identity_nonce_finalized, identity_user_abandoned, private_contact_payment, anchor_height) \ - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)", + (wallet_id, account_index, activity_id, anchor, nullifiers, st_bytes, attempts, identity_nonce_finalized, identity_user_abandoned, private_contact_payment, anchor_height, spend_context) \ + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)", rusqlite::params![ id.wallet_id.as_slice(), id.account_index, @@ -209,6 +225,7 @@ impl FileBackedShieldedStore { redrive .anchor_height .and_then(|height| i64::try_from(height).ok()), + spend_context, ], ) .map_err(|e| FileShieldedStoreError::Storage(format!("persist redrive: {e}")))?; @@ -465,6 +482,19 @@ impl FileBackedShieldedStore { FileShieldedStoreError::Storage(format!("upgrade pending schema: {e}")) })?; } + // The protocol context a note spend was priced and built in + // (`PendingRedrive::spend_context`), versioned by its first byte: NULL for a + // record saved before it was kept, which is re-broadcast with nothing checked. + if !columns.iter().any(|existing| existing == "spend_context") { + pending_conn + .execute( + "ALTER TABLE shielded_pending_spends ADD COLUMN spend_context BLOB", + [], + ) + .map_err(|e| { + FileShieldedStoreError::Storage(format!("upgrade pending schema: {e}")) + })?; + } // The private contact request a record pays for, when it does. if !columns .iter() @@ -576,7 +606,7 @@ impl FileBackedShieldedStore { .prepare( "SELECT wallet_id, account_index, activity_id, anchor, nullifiers, st_bytes, \ attempts, identity_nonce_finalized, identity_user_abandoned, \ - private_contact_payment, anchor_height FROM shielded_pending_spends", + private_contact_payment, anchor_height, spend_context FROM shielded_pending_spends", ) .map_err(|e| FileShieldedStoreError::Storage(format!("prepare rehydrate: {e}")))?; let rows = stmt @@ -611,6 +641,13 @@ impl FileBackedShieldedStore { .ok() .flatten() .and_then(|height| u64::try_from(height).ok()); + // NULL is a record saved without a context; one that does not read is kept + // as damaged rather than re-broadcast with nothing checked. + let spend_context = match row.get::<_, Option>>(11) { + Ok(None) => Ok(None), + Ok(Some(bytes)) => SpendContext::from_bytes(&bytes).map(Some).ok_or(()), + Err(_) => Err(()), + }; let decoded: rusqlite::Result<_> = (|| { Ok(( row.get::<_, Vec>(0)?, @@ -629,6 +666,7 @@ impl FileBackedShieldedStore { readable_wallet_id, private_contact_payment, anchor_height, + spend_context, decoded, )) }) @@ -639,6 +677,7 @@ impl FileBackedShieldedStore { readable_wallet_id, private_contact_payment, anchor_height, + spend_context, decoded, ) = row.map_err(|e| FileShieldedStoreError::RecoveryCorrupted { account_index: None, @@ -721,6 +760,8 @@ impl FileBackedShieldedStore { return Err(corrupted("invalid nullifier width")); } let nullifiers: Vec<[u8; 32]> = nullifiers.as_chunks::<32>().0.to_vec(); + let spend_context = + spend_context.map_err(|()| corrupted("unreadable spend context"))?; Ok(( SubwalletId::new(wallet_id, account_index), PendingRedrive { @@ -732,6 +773,7 @@ impl FileBackedShieldedStore { anchor_height, identity_nonce_finalized, identity_user_abandoned, + spend_context, }, )) })(); @@ -1774,6 +1816,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; { @@ -1836,6 +1879,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; let payment = PrivateContactPayment { @@ -1909,6 +1953,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; let payment = PrivateContactPayment { @@ -1989,6 +2034,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; { @@ -2043,6 +2089,10 @@ mod tests { !record.identity_user_abandoned, "legacy guards require explicit recovery" ); + assert_eq!( + record.spend_context, None, + "legacy records carry no protocol context" + ); record.identity_nonce_finalized = true; record.identity_user_abandoned = true; store.arm_redrive(id, record).unwrap(); @@ -2087,6 +2137,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -2117,6 +2168,94 @@ mod tests { } } + /// The protocol context a spend saves with its record survives a reopen, in the stored + /// form of every fee model a spend checks, and a context that does not read keeps its + /// note-spend row without loading it, so recovery never re-broadcasts it unchecked. + #[test] + fn should_keep_a_spends_protocol_context_across_a_reopen() { + use super::super::note_selection::ShieldedFeeKind; + use dpp::state_transition::shielded_transfer_transition::v0::ShieldedTransferTransitionV0; + + let path = temp_tree_path("spend_context"); + let id = SubwalletId::new([0x6C; 32], 0); + let transition: StateTransition = ShieldedTransferTransitionV0 { + actions: vec![], + value_balance: 1_000, + anchor: [0x53; 32], + proof: vec![], + binding_signature: [0; 64], + } + .into(); + let record = |activity: u8, spend_context| PendingRedrive { + activity_id: [activity; 32], + anchor: [0x53; 32], + nullifiers: vec![[activity ^ 0xFF; 32]], + st_bytes: transition.serialize_to_bytes().unwrap(), + attempts: 0, + identity_nonce_finalized: false, + identity_user_abandoned: false, + spend_context, + anchor_height: Some(5), + }; + let kinds = [ + ShieldedFeeKind::Base, + ShieldedFeeKind::Unshield, + ShieldedFeeKind::Withdrawal, + ShieldedFeeKind::IdentityTopUp, + ShieldedFeeKind::IdentityCreate { num_keys: 3 }, + ]; + let saved: Vec = kinds + .into_iter() + .enumerate() + .map(|(i, fee_kind)| { + record( + i as u8 + 1, + Some(SpendContext { + operation_version: 13, + network_version: (i % 2 == 0).then_some(14), + fee_kind, + planned_fee: 168_934_000 + i as u64, + }), + ) + }) + .collect(); + { + let mut store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); + for redrive in &saved { + store.arm_redrive(id, redrive.clone()).unwrap(); + } + } + let store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); + let mut got = store.pending_redrives(id).unwrap(); + got.sort_by_key(|redrive| redrive.activity_id); + assert_eq!(got, saved); + drop(store); + + // A context of another format, or one that is cut short, is not read. + for damaged in ["x'02000000000000000000000000000000000000000000'", "x'01'"] { + rusqlite::Connection::open(&path) + .unwrap() + .execute( + &format!("UPDATE shielded_pending_spends SET spend_context = {damaged}"), + [], + ) + .unwrap(); + let store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); + assert!( + store.pending_redrives(id).unwrap().is_empty(), + "{damaged}: not loaded, so never re-broadcast unchecked" + ); + let rows: u32 = rusqlite::Connection::open(&path) + .unwrap() + .query_row("SELECT COUNT(*) FROM shielded_pending_spends", [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(rows, saved.len() as u32, "{damaged}: the rows are kept"); + } + let _ = std::fs::remove_file(&path); + } + /// A saved payment's private contact request association that does not /// read back fails restoring its wallet's reservations, rather than losing /// the pair it holds: a non-null value that does not decode on a record @@ -2144,6 +2283,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, // As a spend saved by this build keeps it. anchor_height: Some(5), }; @@ -2258,6 +2398,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; { @@ -2273,6 +2414,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -2339,6 +2481,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -2393,6 +2536,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -2427,6 +2571,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; { @@ -2455,6 +2600,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; { @@ -2505,6 +2651,7 @@ mod tests { attempts: 5, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; let note_spend = PendingRedrive { @@ -2515,6 +2662,7 @@ mod tests { attempts: 1, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; { @@ -2561,6 +2709,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; @@ -2639,6 +2788,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -3063,6 +3213,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; let expected = PrivatePaymentRecord { @@ -3217,6 +3368,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; let mut store = FileBackedShieldedStore::open_path(&path, 100).expect("open"); @@ -3318,6 +3470,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, payment, @@ -3383,6 +3536,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index 41bedeffba1..3c3992f776a 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -31,7 +31,7 @@ use super::note_selection::{ }; use super::store::{ PendingRedrive, PrivateContactPayment, PrivatePaymentEntry, ShieldedNote, ShieldedStore, - SubwalletId, + SpendContext, SubwalletId, }; use crate::broadcast_outcome::{ broadcast_tracking_delivery, broadcast_was_refused, carries_consensus_rejection, @@ -1020,6 +1020,7 @@ async fn arm_identity_shield_redrive( attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -3224,6 +3225,7 @@ async fn broadcast_identity_create_with_redrive( reservation, st, IDENTITY_CREATE_OPERATION, + None, || Ok(()), || broadcast_identity_create(sdk, st, identity_id, submitted_public_keys), ) @@ -3749,12 +3751,12 @@ fn ensure_version_unchanged( note_count: usize, expected_plan: Option<&[u8; 32]>, ) -> Result<(), PlatformWalletError> { - let current = sdk.version(); - let network = sdk.protocol_version_info().verified_version; let captured = platform_version.protocol_version; - if current.protocol_version == captured && !matches!(network, Some(n) if n != captured) { + if network_applies_version(sdk, captured) { return Ok(()); } + let current = sdk.version(); + let network = sdk.protocol_version_info().verified_version; // What the network applies: its verified version when the SDK has one, else the SDK's. let applied_version = match network { Some(n) => PlatformVersion::get(n).map_err(|_| { @@ -3779,6 +3781,31 @@ fn ensure_version_unchanged( }) } +/// Whether the protocol version the network applies is `captured`: the SDK builds at it, and +/// the network version it last verified, if any, is it ([`ensure_version_unchanged`]). +fn network_applies_version(sdk: &Arc, captured: u32) -> bool { + sdk.version().protocol_version == captured + && !matches!(sdk.protocol_version_info().verified_version, Some(n) if n != captured) +} + +/// Whether the `context` a saved spend of `note_count` notes was priced and built in still +/// holds, for a recovery broadcast of it: the network applies the version it was built at +/// ([`network_applies_version`]), the network version it was saved under was that one, and the +/// fee at it is the planned one. A saved context is never overridden or repaired: a spend +/// whose context does not hold is not broadcast. +fn recovery_context_holds( + sdk: &Arc, + context: &SpendContext, + note_count: usize, +) -> bool { + network_applies_version(sdk, context.operation_version) + && !matches!(context.network_version, Some(n) if n != context.operation_version) + && context + .fee_kind + .compute(note_count.max(SPEND_MIN_ACTIONS), sdk.version()) + .is_ok_and(|fee| fee == context.planned_fee) +} + /// Refuse to plan a spend, whose fee is priced at the SDK's version, when the SDK has verified /// a different network version: the network would apply its fee at its own, and the SDK's /// version is a pin that is not overridden here. Plan again once the SDK builds at the version @@ -3844,6 +3871,17 @@ struct DispatchCheck<'a> { } impl DispatchCheck<'_> { + /// What the spend's recovery record keeps of this check, so that no recovery broadcast + /// dispatches the saved transition once it no longer holds ([`SpendContext`]). + fn spend_context(&self) -> SpendContext { + SpendContext { + operation_version: self.platform_version.protocol_version, + network_version: self.sdk.protocol_version_info().verified_version, + fee_kind: self.fee_kind, + planned_fee: self.selected_fee, + } + } + /// The SDK's version is the captured one, and the fee the network applies at it is the /// selected and built one, so the recipient receives the amount that was confirmed. fn ensure_holds(&self) -> Result<(), PlatformWalletError> { @@ -4271,6 +4309,7 @@ async fn broadcast_shielded_spend_with_redrive_with_metadata( reservation, state_transition, operation, + Some(dispatch_check.spend_context()), || dispatch_check.ensure_holds(), || broadcast_shielded_spend_classified(sdk, state_transition, operation, wait), ) @@ -4290,6 +4329,10 @@ async fn broadcast_shielded_spend_with_redrive_with_metadata( /// the caller releases them ([`settle_failed_spend`]), and so does a spend /// dropped while a save waits for the store. /// +/// The record carries `context`, when the spend has one, so that a recovery broadcast of it +/// ([`redrive_pending_spends`]) holds to the same check: it is dispatchable by recovery from +/// the moment it is saved, before `still_dispatchable` has run, and after a restart. +/// /// Right after the record is saved, `still_dispatchable` is the last check before dispatch: /// a spend that no longer matches what it was built and confirmed for is refused with nothing /// broadcast, as one whose transition never left the wallet ([`settle_failed_spend`]). @@ -4310,6 +4353,7 @@ async fn save_spend_then_broadcast( reservation: &mut NoteReservation, state_transition: &StateTransition, operation: &'static str, + context: Option, still_dispatchable: R, broadcast: B, ) -> Result @@ -4320,7 +4364,7 @@ where Fut: Future>, { arm_pending_release(store, id, anchor, anchor_height, pending_entry, notes).await?; - arm_redrive_before_broadcast( + arm_redrive_with_context( store, id, pending_entry.as_ref().map(|entry| entry.id), @@ -4331,6 +4375,7 @@ where None, None, anchor_height, + context, ) .await?; // The last check, after every write awaited above: what the spend was built and @@ -4475,6 +4520,38 @@ pub(crate) async fn arm_redrive_before_broadcast( private_contact: Option, payment_started: Option<&PaymentStarted>, anchor_recorded_at: u64, +) -> Result<(), PlatformWalletError> { + arm_redrive_with_context( + store, + id, + activity_id, + anchor, + nullifiers, + state_transition, + operation, + private_contact, + payment_started, + anchor_recorded_at, + None, + ) + .await +} + +/// [`arm_redrive_before_broadcast`], keeping `spend_context` with the record +/// ([`PendingRedrive::spend_context`]). +#[allow(clippy::too_many_arguments)] +async fn arm_redrive_with_context( + store: &Arc>, + id: SubwalletId, + activity_id: Option<[u8; 32]>, + anchor: [u8; 32], + nullifiers: Vec<[u8; 32]>, + state_transition: &StateTransition, + operation: &'static str, + private_contact: Option, + payment_started: Option<&PaymentStarted>, + anchor_recorded_at: u64, + spend_context: Option, ) -> Result<(), PlatformWalletError> { use dpp::serialization::PlatformSerializable; @@ -4510,6 +4587,7 @@ pub(crate) async fn arm_redrive_before_broadcast( attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context, anchor_height: Some(anchor_recorded_at), }; let mut store = store.write().await; @@ -4902,6 +4980,21 @@ pub(super) async fn redrive_pending_spends( if !recorded.contains(&redrive.anchor) || redrive.attempts >= MAX_REDRIVE_ATTEMPTS { continue; } + // A record saved with the context it was priced and built in is re-broadcast only + // while that still holds. It is kept, unclaimed, never retired from here: whether + // the foreground spend dispatched it before the context changed is not known, and + // the spend that saved it settles it as it ends, or the scan or the prune backstop + // resolves it. + if let Some(context) = &redrive.spend_context { + if !recovery_context_holds(sdk, context, redrive.nullifiers.len()) { + warn!( + saved = ?context, + "redrive: the context the spend was priced in no longer holds; keeping the \ + record without re-broadcasting it" + ); + continue; + } + } let st = match StateTransition::deserialize_from_bytes_trusted(&redrive.st_bytes) { Ok(st) => st, Err(e) => { @@ -5307,6 +5400,7 @@ mod redrive_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: true, + spend_context: None, anchor_height: None, }; store.arm_redrive(id, archived.clone()).unwrap(); @@ -5358,6 +5452,7 @@ mod redrive_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -5431,6 +5526,7 @@ mod redrive_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -5460,6 +5556,7 @@ mod redrive_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -5572,6 +5669,7 @@ mod redrive_tests { attempts: MAX_REDRIVE_ATTEMPTS, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -5947,6 +6045,7 @@ mod redrive_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, payment, @@ -6630,6 +6729,7 @@ mod redrive_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -6667,6 +6767,7 @@ mod redrive_tests { attempts, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; { @@ -6727,6 +6828,7 @@ mod redrive_tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; { @@ -7098,6 +7200,7 @@ mod redrive_tests { &mut reservation, &transition, "transfer", + None, || Ok(()), || { // Nothing is dispatched before the record is on the file. @@ -7232,6 +7335,7 @@ mod redrive_tests { &mut spend.reservation, &transition, "transfer", + None, || Ok(()), || async { dispatched.store(true, Ordering::SeqCst); @@ -7357,6 +7461,18 @@ mod redrive_tests { ); let saved = store.pending_redrives(id).expect("the records"); assert_eq!(saved.len(), 1, "{spend_path:?}"); + assert_eq!( + saved[0].spend_context.map(|context| context.planned_fee), + match spend_path { + SpendPath::Shared => Some( + ShieldedFeeKind::Base + .compute(SPEND_MIN_ACTIONS, sdk_handle.version()) + .expect("a fee") + ), + SpendPath::IdentityCreate => None, + }, + "{spend_path:?}: the record keeps the context its spend was checked against" + ); assert_eq!( saved[0].st_bytes, transition.serialize_to_bytes().expect("serializes"), @@ -7906,6 +8022,235 @@ mod redrive_tests { ShieldedActivityStatus::Failed ); } + + // ── A saved spend is re-broadcast only while its captured context holds ── + + /// A mock SDK pinned to v13, and a handle to it. + fn pinned_v13_sdk() -> (dash_sdk::Sdk, Arc) { + let sdk = dash_sdk::SdkBuilder::new_mock() + .with_version(PlatformVersion::get(13).expect("v13")) + .build() + .expect("mock sdk"); + let handle = Arc::new(sdk.clone()); + (sdk, handle) + } + + /// The context of a one-note transfer priced and built at `version`, whose fee is the + /// fee at `version` plus `fee_drift`. + fn transfer_context(version: u32, network: Option, fee_drift: u64) -> SpendContext { + SpendContext { + operation_version: version, + network_version: network, + fee_kind: ShieldedFeeKind::Base, + planned_fee: ShieldedFeeKind::Base + .compute( + SPEND_MIN_ACTIONS, + PlatformVersion::get(version).expect("a version"), + ) + .expect("a fee") + + fee_drift, + } + } + + fn saved_transfer( + attempts: u32, + spend_context: Option, + ) -> (StateTransition, PendingRedrive) { + let transition = SpendPath::Shared.transition(); + let record = PendingRedrive { + activity_id: [0x7D; 32], + anchor: SPEND_ANCHOR, + nullifiers: vec![spend_note().nullifier], + st_bytes: transition.serialize_to_bytes().expect("serializes"), + attempts, + identity_nonce_finalized: false, + identity_user_abandoned: false, + spend_context, + anchor_height: Some(SPEND_ANCHOR_HEIGHT), + }; + (transition, record) + } + + /// The recovery pass re-broadcasts a saved spend only while the context it was priced and + /// built in still holds: the SDK builds at the captured version, the network it verified + /// runs that version, and the fee at it is the planned one. Otherwise (the network moved + /// to another version, the SDK's version differs from the captured one, or the fee is not + /// the planned one) nothing is sent, the attempt is not claimed and the record stays with + /// its notes, as a spend that was claimed before stays as it was. A record with no + /// context is re-broadcast as ever. + #[tokio::test] + async fn should_not_rebroadcast_a_saved_spend_whose_captured_context_no_longer_holds() { + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + + // The case, the saved context, the network version the SDK verified, the attempts + // already claimed, and whether recovery re-broadcasts. + #[allow(clippy::type_complexity)] + let cases: [(&str, Option, Option, u32, bool); 7] = [ + ("holds", Some(transfer_context(13, None, 0)), None, 0, true), + ( + "holds, the network verified the same version", + Some(transfer_context(13, Some(13), 0)), + Some(13), + 0, + true, + ), + ("no context", None, None, 0, true), + ( + "the network verified another version", + Some(transfer_context(13, None, 0)), + Some(PlatformVersion::latest().protocol_version), + 0, + false, + ), + ( + "claimed before, the network verified another version", + Some(transfer_context(13, None, 0)), + Some(PlatformVersion::latest().protocol_version), + 1, + false, + ), + ( + "captured at another operation version", + Some(transfer_context(14, None, 0)), + None, + 0, + false, + ), + ( + "the fee is not the planned one", + Some(transfer_context(13, None, 1)), + None, + 0, + false, + ), + ]; + for (name, context, verified, attempts, rebroadcast) in cases { + let (mut sdk, handle) = pinned_v13_sdk(); + if let Some(network) = verified { + handle + .mock_verified_protocol_version(network) + .expect("a mock SDK"); + } + let store = Arc::new(RwLock::new(InMemoryShieldedStore::new())); + let id = SubwalletId::new([0x5E; 32], 0); + let (transition, record) = saved_transfer(attempts, context); + store.write().await.arm_redrive(id, record).expect("armed"); + let recorded = [SPEND_ANCHOR].into_iter().collect(); + + redrive_pending_spends(&handle, &store, id, &recorded, &CancellationToken::new()).await; + + let request = transition + .broadcast_request_for_state_transition() + .expect("serializes"); + let sent = sdk.mock().request_count(&request).await; + let left = store.read().await.pending_redrives(id).expect("records"); + assert_eq!(left.len(), 1, "{name}: the record stays"); + if rebroadcast { + assert!(sent > 0, "{name}: re-broadcast"); + assert_eq!(left[0].attempts, attempts + 1, "{name}"); + } else { + assert_eq!(sent, 0, "{name}: nothing is sent"); + assert_eq!(left[0].attempts, attempts, "{name}: no attempt is claimed"); + } + } + } + + /// A spend whose context stopped holding right after its record was saved is refused as + /// never delivered, and the process exits before that settles it: the record is still in + /// the store a restart opens, with its context, and the redrive pass of the restarted + /// wallet does not broadcast it once the network it verifies runs another version. + #[tokio::test] + async fn should_not_redrive_after_a_restart_a_spend_refused_right_after_its_record_was_saved() { + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + use std::task::{Context, Waker}; + + let id = SubwalletId::new([0x74; 32], 0); + let dir = tempfile::tempdir().expect("a directory"); + let path = dir.path().join("tree.sqlite"); + let ReservedSpend { + store, + notes, + mut reservation, + entry, + } = ReservedSpend::at(&path, id, [0x7E; 32]).await; + let transition = SpendPath::Shared.transition(); + let context = transfer_context(13, None, 0); + let moved = PlatformWalletError::ShieldedPlanChanged { + fresh_fee: 1, + fresh_note_count: 1, + }; + + let mut cx = Context::from_waker(Waker::noop()); + let mut spend = Box::pin(save_spend_then_broadcast( + &store, + id, + &entry, + SPEND_ANCHOR, + SPEND_ANCHOR_HEIGHT, + ¬es, + &mut reservation, + &transition, + "transfer", + Some(context), + // The network moved after the record was saved. + || Err(moved), + || async { + Err::<(), SpendFailure>( + PlatformWalletError::ShieldedBuildError("dispatched".to_string()).into(), + ) + }, + )); + let std::task::Poll::Ready(Err(failure)) = spend.as_mut().poll(&mut cx) else { + panic!("the spend is refused when its record is saved"); + }; + assert!(failure.never_delivered); + // The process exits before the failure settles: nothing runs, not even the + // reservation's drop, which would release the notes and their record. + drop(spend); + std::mem::forget(reservation); + drop(store); + + let (mut restarted_sdk, restarted_handle) = pinned_v13_sdk(); + restarted_handle + .mock_verified_protocol_version(PlatformVersion::latest().protocol_version) + .expect("a mock SDK"); + let restarted = Arc::new(RwLock::new(restarted_store(&path, id))); + assert_eq!( + restarted + .read() + .await + .pending_redrives(id) + .expect("records")[0] + .spend_context, + Some(context), + "the record kept its context across the restart" + ); + + let recorded = [SPEND_ANCHOR].into_iter().collect(); + redrive_pending_spends( + &restarted_handle, + &restarted, + id, + &recorded, + &CancellationToken::new(), + ) + .await; + + let request = transition + .broadcast_request_for_state_transition() + .expect("serializes"); + assert_eq!( + restarted_sdk.mock().request_count(&request).await, + 0, + "the redrive does not broadcast it" + ); + let left = restarted + .read() + .await + .pending_redrives(id) + .expect("records"); + assert_eq!((left.len(), left[0].attempts), (1, 0), "kept, unclaimed"); + } } #[cfg(test)] diff --git a/packages/rs-platform-wallet/src/wallet/shielded/store.rs b/packages/rs-platform-wallet/src/wallet/shielded/store.rs index b2672e56d00..48439cd77d6 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/store.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/store.rs @@ -185,6 +185,85 @@ pub struct PendingRedrive { /// automatic retries and permit separately authorized new payments. /// This is never a proof of failure and is always false for note spends. pub identity_user_abandoned: bool, + /// What the spend was priced and built for, checked again before any recovery + /// broadcast of [`Self::st_bytes`]: see [`SpendContext`]. `None` for a record saved + /// without one (by a build before contexts were kept, or a spend with no fee model of + /// its own to check), which recovery re-broadcasts as it always did. + pub spend_context: Option, +} + +/// The protocol context a note-consuming spend was selected, confirmed and built in, saved +/// with its recovery record so that no recovery path, in this process or after a restart, +/// broadcasts the saved transition once the network applies something else than it was +/// priced for: the fee a transition carries is metered at the protocol version the network +/// runs when it executes, so a transition built for one version pays out differently at +/// another. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SpendContext { + /// The protocol version the spend was priced and built at: the SDK's operation version. + pub operation_version: u32, + /// The network protocol version the SDK had verified when the record was saved, if any. + pub network_version: Option, + /// The fee model the spend's fee follows. + pub fee_kind: super::note_selection::ShieldedFeeKind, + /// The fee the spend was selected, confirmed and built for. + pub planned_fee: u64, +} + +impl SpendContext { + /// The version of [`Self::to_bytes`]'s layout, its first byte. A reader refuses any other. + const FORMAT: u8 = 1; + const LEN: usize = 1 + 4 + 4 + 1 + 4 + 8; + + /// The bytes the file store keeps it as: the format byte, then the operation version, + /// the network version (0 when unknown), the fee model's tag and parameter and the + /// planned fee, little-endian. `None` for a fee model with no layout (a private + /// document create, which has no such context). + pub(super) fn to_bytes(self) -> Option<[u8; Self::LEN]> { + use super::note_selection::ShieldedFeeKind as Kind; + let (tag, parameter) = match self.fee_kind { + Kind::Base => (0u8, 0u32), + Kind::Unshield => (1, 0), + Kind::Withdrawal => (2, 0), + Kind::IdentityCreate { num_keys } => (3, u32::try_from(num_keys).ok()?), + Kind::IdentityTopUp => (4, 0), + Kind::PrivateDocumentCreate { .. } => return None, + }; + let mut bytes = [0u8; Self::LEN]; + bytes[0] = Self::FORMAT; + bytes[1..5].copy_from_slice(&self.operation_version.to_le_bytes()); + bytes[5..9].copy_from_slice(&self.network_version.unwrap_or(0).to_le_bytes()); + bytes[9] = tag; + bytes[10..14].copy_from_slice(¶meter.to_le_bytes()); + bytes[14..].copy_from_slice(&self.planned_fee.to_le_bytes()); + Some(bytes) + } + + /// The context [`Self::to_bytes`] wrote, or `None` for other bytes. + pub(super) fn from_bytes(bytes: &[u8]) -> Option { + use super::note_selection::ShieldedFeeKind as Kind; + if bytes.len() != Self::LEN || bytes[0] != Self::FORMAT { + return None; + } + let parameter = u32::from_le_bytes(bytes[10..14].try_into().ok()?); + let fee_kind = match bytes[9] { + 0 => Kind::Base, + 1 => Kind::Unshield, + 2 => Kind::Withdrawal, + 3 => Kind::IdentityCreate { + num_keys: usize::try_from(parameter).ok()?, + }, + 4 => Kind::IdentityTopUp, + _ => return None, + }; + let network_version = u32::from_le_bytes(bytes[5..9].try_into().ok()?); + Some(Self { + operation_version: u32::from_le_bytes(bytes[1..5].try_into().ok()?), + network_version: (network_version != 0).then_some(network_version), + fee_kind, + planned_fee: u64::from_le_bytes(bytes[14..].try_into().ok()?), + }) + } } /// The DashPay private contact request a saved spend pays for: which identity @@ -2034,6 +2113,7 @@ mod tests { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; @@ -2431,6 +2511,7 @@ mod tests { attempts: 7, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; let note_spend = PendingRedrive { @@ -2441,6 +2522,7 @@ mod tests { attempts: 1, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }; store.arm_redrive(id, identity_guard.clone()).unwrap(); diff --git a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs index dd0c190a281..d12696a1573 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/viewing_key_bind_tests.rs @@ -528,6 +528,7 @@ async fn bind_persists_viewing_keys_and_restart_rebinds_seedlessly() { attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) @@ -1081,6 +1082,7 @@ async fn should_keep_wallet_and_coordinator_keys_when_guarded_registration_is_re attempts: 0, identity_nonce_finalized: false, identity_user_abandoned: false, + spend_context: None, anchor_height: None, }, ) From 084d1f8487a6d8e2a6c833127a1a17f5f3ed4f8c Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 18:47:46 +0200 Subject: [PATCH 14/20] fix(platform-wallet): refuse a shielded spend plan for a transition not active at its protocol version A plan, and a spend run without one, is refused when the transition it executes as is not active at the protocol version it is made at. The activation versions are the ones DPP and Drive-ABCI gate on: the shielded pool's for transfer, unshield and withdrawal, and the identity top-up's own, so an identity top-up is refused at protocol 13 and accepted from 14. The version-movement fixtures started an identity top-up at 13; it now starts at 14. The fee of an identity top-up does not change from 14 to the newest version, so there the fixtures assert the refusal on the version moving alone. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/shielded/note_selection.rs | 102 ++++++++++++++- .../src/wallet/shielded/operations.rs | 118 ++++++++++++++---- 2 files changed, 196 insertions(+), 24 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs index 04ddc0dc20a..0d6125e3452 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/note_selection.rs @@ -6,6 +6,7 @@ use super::store::ShieldedNote; use crate::error::PlatformWalletError; +use dpp::consensus::basic::state_transition::StateTransitionNotActiveError; use dpp::consensus::basic::BasicError; use dpp::consensus::ConsensusError; use dpp::fee::Credits; @@ -15,7 +16,12 @@ use dpp::shielded::{ compute_shielded_unshield_fee, compute_shielded_withdrawal_fee, is_allowed_identity_create_denomination, max_shielded_actions_per_transition, }; -use dpp::version::PlatformVersion; +use dpp::state_transition::StateTransitionType; +use dpp::version::feature_initial_protocol_versions::{ + IDENTITY_TOP_UP_FROM_SHIELDED_POOL_INITIAL_PROTOCOL_VERSION, + SHIELDED_POOL_INITIAL_PROTOCOL_VERSION, +}; +use dpp::version::{PlatformVersion, ProtocolVersion}; use dpp::withdrawal::preflight_shielded_withdrawal; use dpp::ProtocolError; use sha2::{Digest, Sha256}; @@ -326,6 +332,30 @@ impl ShieldedSpendKind { } } + /// The state transition the spend executes as, and the protocol version it activates at: + /// the activation DPP's `StateTransition::active_version_range` and Drive-ABCI's + /// `is_allowed` gate enforce. + fn activation(self) -> (StateTransitionType, ProtocolVersion) { + match self { + ShieldedSpendKind::Transfer => ( + StateTransitionType::ShieldedTransfer, + SHIELDED_POOL_INITIAL_PROTOCOL_VERSION, + ), + ShieldedSpendKind::Unshield => ( + StateTransitionType::Unshield, + SHIELDED_POOL_INITIAL_PROTOCOL_VERSION, + ), + ShieldedSpendKind::Withdrawal { .. } => ( + StateTransitionType::ShieldedWithdrawal, + SHIELDED_POOL_INITIAL_PROTOCOL_VERSION, + ), + ShieldedSpendKind::IdentityTopUp => ( + StateTransitionType::IdentityTopUpFromShieldedPool, + IDENTITY_TOP_UP_FROM_SHIELDED_POOL_INITIAL_PROTOCOL_VERSION, + ), + } + } + fn tag(self) -> u8 { match self { ShieldedSpendKind::Transfer => 0, @@ -463,6 +493,8 @@ impl ShieldedSpendPlan { /// their fee ([`sweep_amount`]); the plan selects exactly those notes. A withdrawal sweep is /// capped at the largest withdrawal the protocol accepts. /// +/// The spend's transition must be active at `platform_version` ([`ensure_spend_kind_active`]). +/// /// A withdrawal must pass DPP's shared preflight ([`ensure_withdrawal_amount_in_range`]): a rate /// that cannot execute is refused, and an amount outside the protocol bounds is /// [`PlatformWalletError::ShieldedWithdrawalAmountOutOfRange`]. The plan's `recipient_amount` is @@ -473,6 +505,7 @@ pub fn plan_spend( amount: ShieldedSpendAmount, platform_version: &PlatformVersion, ) -> Result { + ensure_spend_kind_active(kind, platform_version)?; let fee_kind = kind.fee_kind(); let amount = match amount { ShieldedSpendAmount::Exact(amount) => amount, @@ -532,6 +565,27 @@ pub(crate) fn ensure_plan_holds( Ok(()) } +/// Refuse a `kind` spend whose transition is not active at `platform_version`: consensus rejects +/// it there, so no plan or spend may be made for it. Store-free, so callers can run it before +/// reserving any note. +pub(crate) fn ensure_spend_kind_active( + kind: ShieldedSpendKind, + platform_version: &PlatformVersion, +) -> Result<(), PlatformWalletError> { + let (transition, active_from) = kind.activation(); + if platform_version.protocol_version < active_from { + return Err(PlatformWalletError::ShieldedBuildError( + StateTransitionNotActiveError::new( + transition.to_string(), + platform_version.protocol_version, + active_from, + ) + .to_string(), + )); + } + Ok(()) +} + /// Reject a zero spend `amount`. Lock-free, so callers can run it before taking the store lock /// or `shield_guard`. pub(crate) fn ensure_positive_amount(amount: u64) -> Result<(), PlatformWalletError> { @@ -1646,4 +1700,50 @@ mod tests { ) .expect("protocol 13 has no cap"); } + + /// `IdentityTopUpFromShieldedPool` activates at protocol version 14: a plan made at 13 could + /// not execute on the version it quotes, so it is refused there and accepted from 14. + #[test] + fn should_refuse_an_identity_top_up_plan_before_the_version_that_activates_it() { + let notes = [test_note(NOTE, 0)]; + let plan_at = |version| { + plan_spend( + ¬es, + ShieldedSpendKind::IdentityTopUp, + ShieldedSpendAmount::Exact(NOTE / 2), + PlatformVersion::get(version).expect("protocol version"), + ) + }; + + assert!( + matches!(plan_at(13), Err(PlatformWalletError::ShieldedBuildError(_))), + "an identity top-up is not active at protocol 13" + ); + plan_at(14).expect("an identity top-up is active at protocol 14"); + } + + /// The other shielded kinds activate with the shielded pool, at protocol version 12. + #[test] + fn should_refuse_a_shielded_spend_plan_only_before_the_shielded_pool_activates() { + let notes = [test_note(NOTE, 0)]; + for kind in [ + ShieldedSpendKind::Transfer, + ShieldedSpendKind::Unshield, + withdrawal(1), + ] { + let plan_at = |version| { + plan_spend( + ¬es, + kind, + ShieldedSpendAmount::Exact(NOTE / 2), + PlatformVersion::get(version).expect("protocol version"), + ) + }; + assert!( + matches!(plan_at(11), Err(PlatformWalletError::ShieldedBuildError(_))), + "{kind:?} is not active at protocol 11" + ); + plan_at(12).unwrap_or_else(|e| panic!("{kind:?} is active at protocol 12: {e}")); + } + } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index 3c3992f776a..86bbefe000d 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -26,8 +26,9 @@ use super::activity_recorder::{ use super::keys::{AccountViewingKeys, OrchardKeySet}; use super::note_selection::{ ensure_allowed_denomination, ensure_plan_holds, ensure_positive_amount, - ensure_withdrawal_amount_in_range, select_notes_for_denomination, select_notes_with_fee, - ShieldedFeeKind, ShieldedSpendAmount, ShieldedSpendKind, ShieldedSpendPlan, SPEND_MIN_ACTIONS, + ensure_spend_kind_active, ensure_withdrawal_amount_in_range, select_notes_for_denomination, + select_notes_with_fee, ShieldedFeeKind, ShieldedSpendAmount, ShieldedSpendKind, + ShieldedSpendPlan, SPEND_MIN_ACTIONS, }; use super::store::{ PendingRedrive, PrivateContactPayment, PrivatePaymentEntry, ShieldedNote, ShieldedStore, @@ -3719,8 +3720,10 @@ async fn reserve_unspent_notes( expected_plan: Option<&[u8; 32]>, platform_version: &PlatformVersion, ) -> Result<(Vec, u64, u64, NoteReservation), PlatformWalletError> { - // All amount-based spends reject zero before waiting on a concurrent sync's store lock. + // All amount-based spends reject zero before waiting on a concurrent sync's store lock, and + // a transition their protocol version does not activate. ensure_positive_amount(amount)?; + ensure_spend_kind_active(kind, platform_version)?; reserve_notes_matching( store, id, @@ -9082,6 +9085,39 @@ mod spend_plan_tests { reservation.cancel().await; } + /// A spend reserves nothing for a transition its protocol version does not activate: an + /// identity top-up from the pool is refused at 13 and reserves its notes at 14. + #[tokio::test] + async fn should_refuse_a_spend_of_a_transition_not_active_at_its_version_and_reserve_nothing() { + let store = store_with(&[note(0, NOTE)]).await; + let reserve_at = |version| { + let store = store.clone(); + async move { + reserve_unspent_notes( + &store, + ID, + NOTE / 2, + ShieldedSpendKind::IdentityTopUp, + None, + PlatformVersion::get(version).expect("a version"), + ) + .await + } + }; + + let refused = reserve_at(13).await; + assert!( + matches!(refused, Err(PlatformWalletError::ShieldedBuildError(_))), + "an identity top-up is not active at protocol 13, got {:?}", + refused.map(|(selected, ..)| selected.len()) + ); + assert_eq!(unspent(&store).await, 1, "nothing reserved at 13"); + + let (_, _, _, reservation) = reserve_at(14).await.expect("active at protocol 14"); + assert_eq!(unspent(&store).await, 0, "the note is reserved at 14"); + reservation.cancel().await; + } + /// A note added or spent after the plan moves the selection: the spend is refused and /// no note is left reserved. #[tokio::test] @@ -9363,9 +9399,36 @@ mod spend_plan_tests { assert_eq!(unspent(&store).await, 4, "nothing reserved"); } + /// The protocol version a `kind` spend starts at in these fixtures: 13, or 14 for an + /// identity top-up, which activates there ([`ensure_spend_kind_active`]). + fn start_version(kind: ShieldedSpendKind) -> u32 { + match kind { + ShieldedSpendKind::IdentityTopUp => 14, + _ => 13, + } + } + + /// The fee of a `kind` plan made at its start version moves with the network's newest + /// version, except for an identity top-up, whose fee is the same from 14 to the newest: + /// the spend is refused there on the version moving alone, with the plan's own fee. + fn assert_fee_moved_with_version( + kind: ShieldedSpendKind, + fee_at_newest: Credits, + planned_fee: Credits, + context: &str, + ) { + match kind { + ShieldedSpendKind::IdentityTopUp => assert_eq!( + fee_at_newest, planned_fee, + "the fee holds from 14 ({context})" + ), + _ => assert_ne!(fee_at_newest, planned_fee, "the fee moved ({context})"), + } + } + /// A spend whose version check is the only thing in its way: one real note in a real - /// tree, a plan made at protocol version 13, and a mocked anchor fetch whose answer - /// moves the SDK to the newest version. + /// tree, a plan made at the kind's start version ([`start_version`]), and a mocked anchor + /// fetch whose answer moves the SDK to the newest version. struct VersionMovesDuringAnchorFetch { sdk: Arc, store: Arc>, @@ -9384,7 +9447,8 @@ mod spend_plan_tests { Self::serving_with(kind, served, false).await } - /// [`Self::serving`] for an SDK whose operation version is pinned to v13 + /// [`Self::serving`] for an SDK whose operation version is pinned to the kind's start + /// version /// (`SdkBuilder::with_version`): it still learns the verified network version from /// the answers, but never moves its own. async fn serving_pinned(kind: ShieldedSpendKind, served: u32) -> Self { @@ -9404,16 +9468,20 @@ mod spend_plan_tests { store.save_note(ID, &owned).expect("a note"); let store = Arc::new(RwLock::new(store)); - let v13 = PlatformVersion::get(13).expect("v13"); + let start = PlatformVersion::get(start_version(kind)).expect("the start version"); let builder = dash_sdk::SdkBuilder::new_mock(); let mut sdk = if pinned { - builder.with_version(v13) + builder.with_version(start) } else { - builder.with_initial_version(v13) + builder.with_initial_version(start) } .build() .expect("a mock SDK"); - assert_eq!(sdk.protocol_version_number(), 13, "the spend starts at v13"); + assert_eq!( + sdk.protocol_version_number(), + start.protocol_version, + "the spend starts at its start version" + ); sdk.mock().set_response_protocol_version(served); sdk.mock() .expect_fetch(NoParamQuery {}, Some(ShieldedAnchors(vec![anchor]))) @@ -9579,7 +9647,7 @@ mod spend_plan_tests { ) .await .expect("plans at the new version"); - assert_ne!(fresh.fee, case.plan.fee, "the fee moved ({kind:?})"); + assert_fee_moved_with_version(kind, fresh.fee, case.plan.fee, &format!("{kind:?}")); match (planned, &refused) { ( true, @@ -9594,7 +9662,7 @@ mod spend_plan_tests { ), (false, Err(PlatformWalletError::ShieldedBuildError(message))) => { assert!( - message.contains("13") + message.contains(&start_version(kind).to_string()) && message.contains( &PlatformVersion::latest().protocol_version.to_string() ), @@ -9691,7 +9759,7 @@ mod spend_plan_tests { }, ShieldedSpendKind::IdentityTopUp, ] { - let case = VersionMovesDuringAnchorFetch::serving(kind, 13).await; + let case = VersionMovesDuringAnchorFetch::serving(kind, start_version(kind)).await; let prover = VersionMovingProver { when, sdk: case.sdk.clone(), @@ -9742,9 +9810,11 @@ mod spend_plan_tests { ) .await .expect("plans at the new version"); - assert_ne!( - fresh.fee, case.plan.fee, - "the fee moved ({when:?} {kind:?})" + assert_fee_moved_with_version( + kind, + fresh.fee, + case.plan.fee, + &format!("{when:?} {kind:?}"), ); match &refused { Err(PlatformWalletError::ShieldedPlanChanged { @@ -9781,7 +9851,7 @@ mod spend_plan_tests { } } - /// What a pinned v13 SDK's spend leaves behind when it is refused as a changed plan priced + /// What a pinned SDK's spend leaves behind when it is refused as a changed plan priced /// at the newest network version: the note released, no activity row, no recovery record. async fn assert_pinned_spend_refused( case: &VersionMovesDuringAnchorFetch, @@ -9793,14 +9863,14 @@ mod spend_plan_tests { assert_eq!(info.verified_version, Some(network), "{kind:?}"); assert_eq!( case.sdk.protocol_version_number(), - 13, + start_version(kind), "the pin held ({kind:?})" ); let at_network = kind .fee_kind() .compute(SPEND_MIN_ACTIONS, PlatformVersion::latest()) .expect("the fee at the network version"); - assert_ne!(at_network, case.plan.fee, "the fee moved ({kind:?})"); + assert_fee_moved_with_version(kind, at_network, case.plan.fee, &format!("{kind:?}")); match refused { Err(PlatformWalletError::ShieldedPlanChanged { fresh_fee, @@ -9841,14 +9911,15 @@ mod spend_plan_tests { ShieldedSpendKind::IdentityTopUp, ]; - /// The SDK is pinned to v13 and has verified an answer of the newest network version: its - /// operation version stays v13, so only the verified network version shows the plan was + /// The SDK is pinned to the kind's start version and has verified an answer of the newest + /// network version: its operation version stays put, so only the verified network version shows the plan was /// priced at a version the network no longer applies. Every spend kind is refused before /// it builds. #[tokio::test] async fn should_refuse_a_pinned_sdk_spend_whose_verified_network_version_differs() { for kind in EVERY_SPEND_KIND { - let case = VersionMovesDuringAnchorFetch::serving_pinned(kind, 13).await; + let case = + VersionMovesDuringAnchorFetch::serving_pinned(kind, start_version(kind)).await; // The plan was made before the SDK verified anything newer. case.sdk .mock_verified_protocol_version(PlatformVersion::latest().protocol_version) @@ -9867,7 +9938,8 @@ mod spend_plan_tests { let key: &'static crate::wallet::shielded::prover::CachedOrchardProver = Box::leak(Box::default()); for kind in EVERY_SPEND_KIND { - let case = VersionMovesDuringAnchorFetch::serving_pinned(kind, 13).await; + let case = + VersionMovesDuringAnchorFetch::serving_pinned(kind, start_version(kind)).await; let prover = VersionMovingProver { when: LearnsVersion::VerifiedNetworkWhileProving, sdk: case.sdk.clone(), From 69fed5384fd6c7681f1b5064519e8e16f94b47f3 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 18:48:59 +0200 Subject: [PATCH 15/20] docs(dpp): justify the in-place extractions in shipped withdrawal generations Comment, at each edited call site of the shielded withdrawal structure generations and the asset unlock conversion generation, why the extraction cannot change consensus: the same predicate, error payload, ordering and arithmetic, and the protocol versions that select the generation. Co-Authored-By: Claude Opus 5.5 --- .../v0/state_transition_validation/v0.rs | 10 ++++++++++ .../v0/state_transition_validation/v1.rs | 8 ++++++++ .../v1/mod.rs | 7 +++++++ 3 files changed, 25 insertions(+) diff --git a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v0.rs b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v0.rs index bc6b936bc72..99b95fe5d6b 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v0.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v0.rs @@ -92,6 +92,16 @@ impl ShieldedWithdrawalTransitionV0 { } // core_fee_per_byte must be a non-zero Fibonacci number. + // + // In-place change to a shipped generation, inert: the inline check moved unchanged into + // `validate_core_fee_per_byte_is_non_zero_fibonacci`, which the shielded withdrawal + // preflight shares. It is the same predicate (`is_non_zero_fibonacci_number` of the rate + // as a `u64`), the same error (`InvalidCreditWithdrawalTransitionCoreFeeError` with the + // rate and `MIN_CORE_FEE_PER_BYTE`, as a `BasicError`) and the same place in the order of + // checks, after the pooling check and before the output script check. This generation is + // `validate_withdrawal_structure` 0, which protocol versions 1 to 13 select (the shielded + // withdrawal is active from 12), and `validate_structure_v1` runs it first, so versions + // 14 and 15 reach this line too. let result = validate_core_fee_per_byte_is_non_zero_fibonacci(self.core_fee_per_byte); if !result.is_valid() { return result; diff --git a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v1.rs b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v1.rs index 5fefd290b2e..61dc18950a7 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v1.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shielded_withdrawal_transition/v0/state_transition_validation/v1.rs @@ -44,6 +44,14 @@ impl ShieldedWithdrawalTransitionV0 { min_withdrawal_amount_with_core_fee(self.core_fee_per_byte, platform_version); let max_withdrawal_amount = platform_version.system_limits.max_withdrawal_amount; + // In-place change to a shipped generation, inert: the two inline range checks moved + // unchanged into `validate_withdrawal_reserved_amount_range`, which the shielded + // withdrawal preflight shares. It tests the same comparisons in the same order (below the + // minimum first, then above the maximum) and returns the same errors built from the same + // reserved amount, minimum and maximum: `WithdrawalBelowMinAmountError` and + // `InvalidIdentityCreditWithdrawalTransitionAmountError`, as `BasicError`s. This + // generation is `validate_withdrawal_structure` 1, which protocol versions 14 and 15 + // select. validate_withdrawal_reserved_amount_range( reserved_amount, minimum_reserved_amount, diff --git a/packages/rs-dpp/src/withdrawal/document_try_into_asset_unlock_base_transaction_info/v1/mod.rs b/packages/rs-dpp/src/withdrawal/document_try_into_asset_unlock_base_transaction_info/v1/mod.rs index ad05200de4e..73df5a8aa33 100644 --- a/packages/rs-dpp/src/withdrawal/document_try_into_asset_unlock_base_transaction_info/v1/mod.rs +++ b/packages/rs-dpp/src/withdrawal/document_try_into_asset_unlock_base_transaction_info/v1/mod.rs @@ -22,6 +22,13 @@ impl Document { let core_fee_per_byte: u32 = properties.get_integer(withdrawal::properties::CORE_FEE_PER_BYTE)?; + // In-place change to a shipped generation, inert: the inline fee arithmetic moved + // unchanged into `asset_unlock_core_fee_duffs`, which the shielded withdrawal preflight + // shares. It reads the same `max_core_fee_per_byte` limit and fails with the same + // message when it is absent, clamps the rate to it, multiplies by `ASSET_UNLOCK_TX_SIZE` + // with the same overflow check and message, and still runs before the credits are + // converted to duffs. This generation is `try_into_asset_unlock_base_transaction_info` 1, + // which protocol versions 14 and 15 select. let requested_fee = asset_unlock_core_fee_duffs(core_fee_per_byte, platform_version)?; let withdrawal_amount_duffs = convert_credits_to_duffs(withdrawal_amount)?; let output_script = ScriptBuf::from_bytes(output_script_bytes); From 40b07fae3407bafc8cbe2553db0169ff1baffb60 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 23:24:18 +0200 Subject: [PATCH 16/20] fix(platform-wallet): recheck the pricing version after the store read when planning a shielded spend Planning captured the SDK's pricing version once and checked it against the verified network version before the store read, but priced the plan with the SDK's version read after that await. Another task could verify a different protocol version meanwhile, so the host could display and confirm a fee that execution would then refuse. The captured version is now rechecked right after the store read, before the notes are planned, and the plan is priced with that same captured version. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/shielded/operations.rs | 82 +++++++++++++++---- 1 file changed, 68 insertions(+), 14 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index 86bbefe000d..ea02de87bb0 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -3809,21 +3809,28 @@ fn recovery_context_holds( .is_ok_and(|fee| fee == context.planned_fee) } -/// Refuse to plan a spend, whose fee is priced at the SDK's version, when the SDK has verified -/// a different network version: the network would apply its fee at its own, and the SDK's -/// version is a pin that is not overridden here. Plan again once the SDK builds at the version -/// the network runs. +/// Refuse to plan a spend, whose fee is priced at the `captured` version, when the SDK has +/// verified a different network version or builds at another one now: the network would apply +/// its fee at its own, and the SDK's version is a pin that is not overridden here. Plan again +/// once the SDK builds at the version the network runs. fn ensure_plan_version_matches_network( sdk: &Arc, + captured: &PlatformVersion, ) -> Result<(), PlatformWalletError> { - let version = sdk.version().protocol_version; - match sdk.protocol_version_info().verified_version { - Some(network) if network != version => Err(PlatformWalletError::ShieldedBuildError( - format!( - "the SDK builds at protocol version {version} but the network runs {network}, so a spend would be priced at a version the network does not apply" - ), - )), - _ => Ok(()), + let version = captured.protocol_version; + let network = sdk + .protocol_version_info() + .verified_version + .filter(|network| *network != version) + .or_else(|| { + (sdk.version().protocol_version != version).then(|| sdk.version().protocol_version) + }); + match network { + Some(network) => Err(PlatformWalletError::ShieldedBuildError(format!( + "the SDK builds at protocol version {version} but the network runs {network}, \ + so a spend would be priced at a version the network does not apply" + ))), + None => Ok(()), } } @@ -3920,13 +3927,18 @@ pub async fn plan_spend( kind: ShieldedSpendKind, amount: ShieldedSpendAmount, ) -> Result { - ensure_plan_version_matches_network(sdk)?; + // The pricing version is captured once; the store read is an await, during which another + // task can verify a different network version, so it is checked again right before the + // notes are planned at it. + let version = sdk.version(); + ensure_plan_version_matches_network(sdk, version)?; let unspent = store .read() .await .get_unspent_notes(SubwalletId::new(wallet_id, account)) .map_err(|e| PlatformWalletError::ShieldedStoreError(e.to_string()))?; - super::note_selection::plan_spend(&unspent, kind, amount, sdk.version()) + ensure_plan_version_matches_network(sdk, version)?; + super::note_selection::plan_spend(&unspent, kind, amount, version) } /// Select and reserve, in one write-locked critical section, notes covering @@ -9984,6 +9996,48 @@ mod spend_plan_tests { let _ = std::fs::remove_file(&case.path); } + /// The network version another task verifies while the plan's store read is suspended is + /// not planned around: the plan would price a fee at the pinned version that the network + /// does not apply, which the host would display and confirm but could never use. + #[tokio::test] + async fn should_refuse_to_plan_when_the_network_version_is_verified_during_the_store_read() { + use std::task::{Context, Poll, Waker}; + + let network = PlatformVersion::latest().protocol_version; + let case = + VersionMovesDuringAnchorFetch::serving_pinned(ShieldedSpendKind::Unshield, 13).await; + // Hold the store so that the planner suspends at its read. + let held = case.store.write().await; + let mut planning = Box::pin(plan_spend( + &case.sdk, + &case.store, + WALLET_ID, + 0, + ShieldedSpendKind::Unshield, + ShieldedSpendAmount::Exact(NOTE), + )); + let mut cx = Context::from_waker(Waker::noop()); + assert!( + planning.as_mut().poll(&mut cx).is_pending(), + "planning waits for the store" + ); + // Another task verifies a newer protocol version meanwhile. + case.sdk + .mock_verified_protocol_version(network) + .expect("a mock SDK"); + drop(held); + + let Poll::Ready(planned) = planning.as_mut().poll(&mut cx) else { + panic!("planning finishes once the store is free"); + }; + assert!( + matches!(&planned, Err(PlatformWalletError::ShieldedBuildError(message)) + if message.contains("13") && message.contains(&network.to_string())), + "got {planned:?}" + ); + let _ = std::fs::remove_file(&case.path); + } + /// The network runs a protocol version this SDK has no tables for: the spend cannot be /// priced at it, so it is refused as a build error, planned or not. #[tokio::test] From 5d64902ab1a3378909be8b2237af47689a1abb46 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Thu, 12 Nov 2026 23:42:40 +0200 Subject: [PATCH 17/20] fix(platform-wallet): check the spend context before every shielded dispatch attempt The foreground check of a shielded spend's context ran once, above the broadcast retry loop, and recovery checked it before awaiting its claim lock. A protocol version verified by another task during a retry or a claim wait could still send the old signed bytes under a newer fee schedule. The broadcast tracker now runs the check immediately before every single dispatch. When it refuses a later dispatch after an earlier one may have been delivered, no further dispatch is sent and the spend stays unconfirmed with its notes reserved; refused before the first one, it never left the wallet. Recovery checks the context again once its claim is held, right before its broadcast. Co-Authored-By: Claude Opus 5.5 --- .../src/broadcast_outcome.rs | 157 +++++++++++++-- .../src/wallet/shielded/operations.rs | 182 +++++++++++++++++- 2 files changed, 324 insertions(+), 15 deletions(-) diff --git a/packages/rs-platform-wallet/src/broadcast_outcome.rs b/packages/rs-platform-wallet/src/broadcast_outcome.rs index 96b840e8742..ba498484df9 100644 --- a/packages/rs-platform-wallet/src/broadcast_outcome.rs +++ b/packages/rs-platform-wallet/src/broadcast_outcome.rs @@ -181,6 +181,33 @@ pub(crate) async fn broadcast_tracking_delivery( sdk: &dash_sdk::Sdk, state_transition: &dpp::state_transition::StateTransition, ) -> BroadcastDelivery { + broadcast_tracking_delivery_checked(sdk, state_transition, || { + Ok::<(), std::convert::Infallible>(()) + }) + .await + .unwrap_or_else(|stopped| match stopped.error {}) +} + +/// A broadcast that `check` stopped before a dispatch +/// ([`broadcast_tracking_delivery_checked`]). +#[derive(Debug)] +pub(crate) struct DispatchStopped { + /// What the check refused with. + pub(crate) error: E, + /// An earlier dispatch was sent, so the transition may have been delivered and may still + /// execute. False when the check refused the very first dispatch: nothing was sent. + pub(crate) may_have_been_delivered: bool, +} + +/// [`broadcast_tracking_delivery`], running `check` immediately before every single dispatch, +/// the first one included. A refusal stops the dispatches: the transition is not sent again, +/// and the [`DispatchStopped`] says whether an earlier dispatch may have delivered it, which +/// the caller must not read as "never left the wallet". +pub(crate) async fn broadcast_tracking_delivery_checked( + sdk: &dash_sdk::Sdk, + state_transition: &dpp::state_transition::StateTransition, + check: impl FnMut() -> Result<(), E>, +) -> Result> { use dash_sdk::dapi_client::RequestSettings; use dash_sdk::platform::transition::broadcast::BroadcastStateTransition; use dash_sdk::platform::transition::put_settings::PutSettings; @@ -192,31 +219,67 @@ pub(crate) async fn broadcast_tracking_delivery( }, ..PutSettings::default() }; - track_delivery(state_transition, spend_broadcast_dispatches(sdk), || { - state_transition.broadcast(sdk, Some(single_dispatch)) - }) + track_delivery_checked( + state_transition, + spend_broadcast_dispatches(sdk), + check, + || state_transition.broadcast(sdk, Some(single_dispatch)), + ) .await } /// The classification [`broadcast_tracking_delivery`] makes of /// `state_transition`'s broadcast, over the outcomes `dispatch` returns, one /// call per single dispatch, at most `dispatches` of them. +#[cfg(test)] async fn track_delivery( state_transition: &dpp::state_transition::StateTransition, dispatches: usize, - mut dispatch: F, + dispatch: F, ) -> BroadcastDelivery where F: FnMut() -> Fut, Fut: std::future::Future>, +{ + track_delivery_checked( + state_transition, + dispatches, + || Ok::<(), std::convert::Infallible>(()), + dispatch, + ) + .await + .unwrap_or_else(|stopped| match stopped.error {}) +} + +/// [`track_delivery`], running `check` before every dispatch +/// ([`broadcast_tracking_delivery_checked`]). +async fn track_delivery_checked( + state_transition: &dpp::state_transition::StateTransition, + dispatches: usize, + mut check: C, + mut dispatch: F, +) -> Result> +where + C: FnMut() -> Result<(), E>, + F: FnMut() -> Fut, + Fut: std::future::Future>, { use dash_sdk::dapi_client::DapiClientError; let mut maybe_delivered: Option = None; for _ in 0..dispatches.max(1) { + // Immediately before every dispatch, nothing awaited in between: the context the + // transition was built in must still hold. Any earlier dispatch that got here was + // sent and did not prove the transition left out of every mempool. + if let Err(error) = check() { + return Err(DispatchStopped { + error, + may_have_been_delivered: maybe_delivered.is_some(), + }); + } let error = match dispatch().await { - Ok(()) => return BroadcastDelivery::Admitted, - Err(error) if node_holds_transition(&error) => return BroadcastDelivery::Admitted, + Ok(()) => return Ok(BroadcastDelivery::Admitted), + Err(error) if node_holds_transition(&error) => return Ok(BroadcastDelivery::Admitted), Err(error) => error, }; // Refused before anything was sent: no address, or the SDK's own @@ -234,27 +297,27 @@ where ) ); if never_sent { - return match maybe_delivered { + return Ok(match maybe_delivered { Some(_) => BroadcastDelivery::MaybeDelivered(error), None => BroadcastDelivery::NeverDelivered(error), - }; + }); } // An endpoint's verdict ends the dispatches, and proves nothing. The // verdict of a node that is behind does not end them: the same bytes // go to the next dispatch's node. if carries_consensus_rejection(&error) && !is_address_nonce_ahead(state_transition, &error) { - return BroadcastDelivery::MaybeDelivered(error); + return Ok(BroadcastDelivery::MaybeDelivered(error)); } maybe_delivered = Some(error); } - match maybe_delivered { + Ok(match maybe_delivered { Some(error) => BroadcastDelivery::MaybeDelivered(error), // Unreachable: every pass sets it or returns. None => BroadcastDelivery::MaybeDelivered(dash_sdk::Error::Generic( "no broadcast dispatch was made".to_string(), )), - } + }) } /// Whether `error` says a node already holds the transition @@ -816,4 +879,76 @@ mod tests { "{delivery:?}" ); } + + /// What [`track_delivery_checked`] makes of dispatches that fail as `lost` says, when + /// `check` refuses once `moved` is set (which the first dispatch does), and how many + /// dispatches it made. + async fn tracked_with_moving_check( + lost: dash_sdk::Error, + moves_at_dispatch: usize, + ) -> (Result>, usize) { + let dispatched = Mutex::new(0usize); + let lost = &lost; + let delivery = track_delivery_checked( + &withdrawal(), + BUDGET, + || { + if *dispatched.lock().expect("count") > moves_at_dispatch { + Err("the context moved".to_string()) + } else { + Ok(()) + } + }, + || { + *dispatched.lock().expect("count") += 1; + std::future::ready(Err(copy(lost))) + }, + ) + .await; + let dispatched = *dispatched.lock().expect("count"); + (delivery, dispatched) + } + + /// The check runs before every dispatch: one that moves after a failed first dispatch stops + /// the second, which is not sent, and the stop says the first may have been delivered. + #[tokio::test] + async fn should_not_send_a_later_dispatch_the_check_stops_and_keep_the_earlier_one_maybe_delivered( + ) { + for lost in [grpc(Code::Unavailable), grpc(Code::DeadlineExceeded)] { + let (delivery, dispatched) = tracked_with_moving_check(lost, 0).await; + assert_eq!(dispatched, 1, "the second dispatch is not sent"); + let Err(stopped) = delivery else { + panic!("the check stops the broadcast: {delivery:?}"); + }; + assert_eq!(stopped.error, "the context moved"); + assert!(stopped.may_have_been_delivered); + } + } + + /// A check that refuses before the first dispatch sends nothing, and the stop says nothing + /// could have been delivered. + #[tokio::test] + async fn should_not_send_anything_when_the_check_refuses_the_first_dispatch() { + let (delivery, dispatched) = + tracked_with_moving_check(grpc(Code::Unavailable), usize::MAX).await; + assert!(delivery.is_ok()); + assert!(dispatched > 1, "a check that holds changes nothing"); + + let dispatched = Mutex::new(0usize); + let delivery = track_delivery_checked( + &withdrawal(), + BUDGET, + || Err::<(), _>("moved"), + || { + *dispatched.lock().expect("count") += 1; + std::future::ready(Err(grpc(Code::Unavailable))) + }, + ) + .await; + let Err(stopped) = delivery else { + panic!("the check stops the broadcast: {delivery:?}"); + }; + assert!(!stopped.may_have_been_delivered); + assert_eq!(*dispatched.lock().expect("count"), 0); + } } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index ea02de87bb0..9d559c2c92a 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -35,8 +35,8 @@ use super::store::{ SpendContext, SubwalletId, }; use crate::broadcast_outcome::{ - broadcast_tracking_delivery, broadcast_was_refused, carries_consensus_rejection, - BroadcastDelivery, + broadcast_tracking_delivery, broadcast_tracking_delivery_checked, broadcast_was_refused, + carries_consensus_rejection, BroadcastDelivery, }; use crate::changeset::{PlatformWalletChangeSet, ShieldedChangeSet}; use crate::error::{preserve_signer_key_unavailable_or, PlatformWalletError}; @@ -1898,6 +1898,7 @@ pub(in crate::wallet) async fn private_document_create_from_pool_with_metadata< &state_transition, "private document create from shielded pool", SpendResultWait::AffectedState, + || Ok(()), ) .await }, @@ -4326,7 +4327,11 @@ async fn broadcast_shielded_spend_with_redrive_with_metadata( operation, Some(dispatch_check.spend_context()), || dispatch_check.ensure_holds(), - || broadcast_shielded_spend_classified(sdk, state_transition, operation, wait), + || { + broadcast_shielded_spend_classified(sdk, state_transition, operation, wait, || { + dispatch_check.ensure_holds() + }) + }, ) .await } @@ -5024,6 +5029,19 @@ pub(super) async fn redrive_pending_spends( let Some(attempts) = claim_redrive_attempt(store, id, &redrive).await else { continue; }; + // The claim waited for the store: the context is checked again right before the + // broadcast, as another task can verify a newer network version meanwhile. The + // claimed attempt stays counted; the record stays, unretired. + if let Some(context) = &redrive.spend_context { + if !recovery_context_holds(sdk, context, redrive.nullifiers.len()) { + warn!( + saved = ?context, + "redrive: the context the spend was priced in stopped holding while its \ + claim waited; keeping the record without re-broadcasting it" + ); + continue; + } + } let broadcast_result = st.broadcast(sdk, None).await; let err_display = broadcast_result .as_ref() @@ -5105,6 +5123,10 @@ impl From for SpendFailure { /// result, telling a failure whose transition never left the wallet from one /// that may have reached the network: /// +/// - `still_dispatchable` runs immediately before every dispatch. When it refuses the first, +/// nothing was sent and the spend never left the wallet (the check's error, +/// [`SpendFailure::never_delivered`] set); when it refuses a later one, an earlier dispatch +/// may have been delivered, so no further one is sent and the spend reads as unconfirmed; /// - refused before anything was sent ([`BroadcastDelivery::NeverDelivered`]): /// [`PlatformWalletError::ShieldedBroadcastFailed`], with /// [`SpendFailure::never_delivered`] set, so the caller retires the saved @@ -5125,8 +5147,47 @@ async fn broadcast_shielded_spend_classified( state_transition: &StateTransition, operation: &'static str, wait: SpendResultWait, + still_dispatchable: impl FnMut() -> Result<(), PlatformWalletError>, ) -> Result<(StateTransitionProofResult, ResponseMetadata), SpendFailure> { - match broadcast_tracking_delivery(sdk, state_transition).await { + let delivery = match broadcast_tracking_delivery_checked( + sdk, + state_transition, + still_dispatchable, + ) + .await + { + Ok(delivery) => delivery, + // The check refused a dispatch: the transition is not sent again, whatever the + // build, the writes and the earlier dispatches were made under. + Err(stopped) if !stopped.may_have_been_delivered => { + return Err(SpendFailure { + error: stopped.error, + never_delivered: true, + }); + } + // An earlier dispatch may have been delivered and may still execute: the outcome + // stays unconfirmed, with the notes reserved and the record saved, for the scan + // and the redrive pass (which holds to the same context) to resolve. + Err(stopped) => { + warn!( + operation, + error = %stopped.error, + "Shielded spend not dispatched again: its context no longer holds, and an \ + earlier dispatch may have been delivered" + ); + return Err(SpendFailure::from( + PlatformWalletError::ShieldedSpendUnconfirmed { + operation, + reason: format!( + "a later dispatch was not sent because its context no longer \ + holds ({}), and an earlier one may have been delivered", + stopped.error + ), + }, + )); + } + }; + match delivery { BroadcastDelivery::Admitted => {} BroadcastDelivery::NeverDelivered(e) => { return Err(SpendFailure { @@ -8170,6 +8231,119 @@ mod redrive_tests { } } + /// The network version another task verifies while the recovery pass waits for the claim + /// lock of a saved spend is not broadcast around: the context is checked again once the + /// claim is held, right before the broadcast, so the saved bytes are not sent under a fee + /// schedule the spend was not priced in. + #[tokio::test] + async fn should_not_rebroadcast_a_saved_spend_whose_context_moved_while_the_claim_waited() { + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + use std::task::{Context, Poll, Waker}; + + let (mut sdk, handle) = pinned_v13_sdk(); + let store = Arc::new(RwLock::new(InMemoryShieldedStore::new())); + let id = SubwalletId::new([0x5F; 32], 0); + let (transition, record) = saved_transfer(0, Some(transfer_context(13, None, 0))); + store.write().await.arm_redrive(id, record).expect("armed"); + let recorded = [SPEND_ANCHOR].into_iter().collect(); + + // A reader lets the pass load its records, and holds its claim (a write) back. + let reader = store.read().await; + let cancel = CancellationToken::new(); + let mut recovery = Box::pin(redrive_pending_spends( + &handle, &store, id, &recorded, &cancel, + )); + let mut cx = Context::from_waker(Waker::noop()); + assert!( + recovery.as_mut().poll(&mut cx).is_pending(), + "the pass waits for the claim lock" + ); + // Another task verifies a newer protocol version meanwhile. + handle + .mock_verified_protocol_version(PlatformVersion::latest().protocol_version) + .expect("a mock SDK"); + drop(reader); + let Poll::Ready(()) = recovery.as_mut().poll(&mut cx) else { + panic!("the pass finishes once the claim lock is free"); + }; + + let request = transition + .broadcast_request_for_state_transition() + .expect("serializes"); + assert_eq!( + sdk.mock().request_count(&request).await, + 0, + "nothing is sent" + ); + assert_eq!( + store + .read() + .await + .pending_redrives(id) + .expect("records") + .len(), + 1, + "the record stays" + ); + } + + /// A shielded spend's dispatches check the context before each one, and a check that + /// refuses a later dispatch after an earlier one may have been delivered reads as an + /// unconfirmed spend, which keeps the notes reserved; refused before the first dispatch + /// it reads as a spend that never left the wallet. + #[tokio::test] + async fn should_report_a_spend_unconfirmed_when_the_context_moves_after_a_dispatch() { + let (_sdk, handle) = pinned_v13_sdk(); + let transition = SpendPath::Shared.transition(); + let moved = || PlatformWalletError::ShieldedBuildError("the context moved".to_string()); + + let calls = std::cell::Cell::new(0usize); + let failure = broadcast_shielded_spend_classified( + &handle, + &transition, + "transfer", + SpendResultWait::ExecutionProved, + || { + calls.set(calls.get() + 1); + if calls.get() == 1 { + Ok(()) + } else { + Err(moved()) + } + }, + ) + .await + .expect_err("the second dispatch is refused"); + assert_eq!(calls.get(), 2, "the check runs before each dispatch"); + assert!(!failure.never_delivered); + assert!( + matches!( + failure.error, + PlatformWalletError::ShieldedSpendUnconfirmed { + operation: "transfer", + .. + } + ), + "{:?}", + failure.error + ); + + let failure = broadcast_shielded_spend_classified( + &handle, + &transition, + "transfer", + SpendResultWait::ExecutionProved, + || Err(moved()), + ) + .await + .expect_err("the first dispatch is refused"); + assert!(failure.never_delivered); + assert!(matches!( + failure.error, + PlatformWalletError::ShieldedBuildError(_) + )); + } + /// A spend whose context stopped holding right after its record was saved is refused as /// never delivered, and the process exits before that settles it: the record is still in /// the store a restart opens, with its context, and the redrive pass of the restarted From 4cbf6b6359260375c1d1b32aabebad819c86544b Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 00:07:28 +0200 Subject: [PATCH 18/20] fix(platform-wallet): size the shielded seeding batch with its asset-lock proof The seeding batch size assumed the fixed part of a transition that carries a ChainLock proof. An InstantSend proof embeds the whole funding transaction and its InstantLock, about 184 bytes per funding input, so a six-action batch exceeds the 20,480-byte transition limit from seven inputs on. dpp gains max_shield_from_asset_lock_actions, which adds the proof's own serialized length to the fixed part. Once the funding resolved and its proof is known, the wallet clamps the batch (and its fee) to that bound; a lock too large for any batch keeps a single output and falls back to the ChainLock proof. Co-Authored-By: Claude Opus 5.5 --- .../shielded/max_actions_per_transition.rs | 30 ++++++++ packages/rs-dpp/src/shielded/mod.rs | 4 +- .../signing_tests.rs | 76 +++++++++++++++++++ .../wallet/shielded/fund_from_asset_lock.rs | 76 ++++++++++++++++++- .../src/wallet/shielded/seed_pool.rs | 3 +- 5 files changed, 186 insertions(+), 3 deletions(-) diff --git a/packages/rs-dpp/src/shielded/max_actions_per_transition.rs b/packages/rs-dpp/src/shielded/max_actions_per_transition.rs index 43057490fb8..7476553d8c7 100644 --- a/packages/rs-dpp/src/shielded/max_actions_per_transition.rs +++ b/packages/rs-dpp/src/shielded/max_actions_per_transition.rs @@ -1,3 +1,4 @@ +use crate::identity::state_transition::asset_lock_proof::AssetLockProof; use platform_version::version::PlatformVersion; /// Bytes the Halo 2 proof and the action itself add to a serialized shielded transition for each @@ -32,3 +33,32 @@ pub fn max_shielded_actions_per_transition(platform_version: &PlatformVersion) - .unwrap_or(u16::MAX) .min(limits.max_shielded_transition_actions) } + +/// The most Orchard actions a `ShieldFromAssetLock` carrying `asset_lock_proof` can have on +/// `platform_version`, when the transition has to fit `max_state_transition_size`. +/// +/// [`max_shielded_actions_per_transition`] assumes the fixed part of a transition that carries +/// a ChainLock proof, which names only an outpoint and a height. An InstantSend proof embeds the +/// whole funding transaction and its InstantLock instead, about 184 bytes per funding input +/// (measured on built transitions: 6 actions are 19,420 B with 1 input, 20,528 B with 7, over +/// the 20,480 B limit), so a lock with many inputs fits fewer actions. The bound adds the proof's +/// own serialized length to the fixed part, so it holds for any proof; it counts the ChainLock +/// proof already inside [`SHIELDED_TRANSITION_FIXED_WIRE_SIZE`] twice, a few dozen bytes. +/// +/// It can be below the 2 actions a shielded transition has at least: the lock then does not +/// fit an InstantSend proof at all and only a ChainLock proof can consume it. +pub fn max_shield_from_asset_lock_actions( + platform_version: &PlatformVersion, + asset_lock_proof: &AssetLockProof, +) -> u16 { + let limits = &platform_version.system_limits; + let proof_size = asset_lock_proof + .serialized_len_in_state_transition() + .map_or(u64::MAX, |len| len as u64); + let fixed = SHIELDED_TRANSITION_FIXED_WIRE_SIZE.saturating_add(proof_size); + let fitting = + limits.max_state_transition_size.saturating_sub(fixed) / SHIELDED_ACTION_WIRE_SIZE; + u16::try_from(fitting) + .unwrap_or(u16::MAX) + .min(limits.max_shielded_transition_actions) +} diff --git a/packages/rs-dpp/src/shielded/mod.rs b/packages/rs-dpp/src/shielded/mod.rs index f5d4ff0dbc3..89a15e79ca5 100644 --- a/packages/rs-dpp/src/shielded/mod.rs +++ b/packages/rs-dpp/src/shielded/mod.rs @@ -10,7 +10,9 @@ mod sighash; use crate::util::hash::hash_single; pub use identity_create_denomination::is_allowed_identity_create_denomination; -pub use max_actions_per_transition::max_shielded_actions_per_transition; +pub use max_actions_per_transition::{ + max_shield_from_asset_lock_actions, max_shielded_actions_per_transition, +}; pub use memo::{ShieldedMemo, MEMO_PAYLOAD_SIZE, MEMO_SIZE}; use bincode::{Decode, DecodeUntrusted, Encode}; diff --git a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shield_from_asset_lock_transition/signing_tests.rs b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shield_from_asset_lock_transition/signing_tests.rs index b9411f606bd..3d8aa8a6a20 100644 --- a/packages/rs-dpp/src/state_transition/state_transitions/shielded/shield_from_asset_lock_transition/signing_tests.rs +++ b/packages/rs-dpp/src/state_transition/state_transitions/shielded/shield_from_asset_lock_transition/signing_tests.rs @@ -356,3 +356,79 @@ async fn seed_pool_batch_fits_max_state_transition_size() { "dummy outputs are zero-value: value_balance must equal the real amount", ); } + +/// A signed-looking Instant proof whose funding transaction spends `inputs` P2PKH coins: each +/// input carries a 107-byte unlocking script (a DER signature and a compressed key), and the +/// InstantLock names every input, as Core's does. +fn make_instant_asset_lock_proof_with_signed_inputs(inputs: u32) -> AssetLockProof { + use crate::identity::state_transition::asset_lock_proof::InstantAssetLockProof; + use crate::tests::fixtures::{ + instant_asset_lock_is_lock_fixture, + instant_asset_lock_proof_transaction_fixture_with_inputs, + }; + use dashcore::ScriptBuf; + + let mut transaction = + instant_asset_lock_proof_transaction_fixture_with_inputs(None, None, inputs); + for input in &mut transaction.input { + input.script_sig = ScriptBuf::from_bytes(vec![0x30; 107]); + } + let mut instant_lock = instant_asset_lock_is_lock_fixture(transaction.txid()); + instant_lock.inputs = transaction + .input + .iter() + .map(|input| input.previous_output) + .collect(); + AssetLockProof::Instant(InstantAssetLockProof::new(instant_lock, transaction, 0)) +} + +/// An Instant proof serializes the whole funding transaction and its InstantLock, about 184 +/// bytes per funding input on top of a Chain proof, so the largest batch a lock can carry +/// shrinks with its inputs: the bound the helper gives for the lock's own proof must build a +/// transition within `max_state_transition_size`, whatever the number of inputs. Each size +/// measured here is of a built, serialized `ShieldFromAssetLock` of 6 actions (1 input: +/// 19,420 B, 7: 20,528 B, 20: 22,920 B, 100: 37,640 B against the 20,480 B limit). +#[tokio::test] +async fn seed_pool_batch_with_an_instant_proof_fits_max_state_transition_size() { + use crate::serialization::PlatformSerializable; + use crate::shielded::builder::test_helpers::{test_orchard_address, TestProver}; + use crate::shielded::max_shield_from_asset_lock_actions; + + let platform_version = PlatformVersion::latest(); + let recipient = test_orchard_address(); + let signer = FixedKeySigner::new([7u8; 32]); + let path = DerivationPath::default(); + let max = platform_version.system_limits.max_state_transition_size as usize; + + let mut batch_by_inputs = Vec::new(); + for inputs in [1u32, 6, 7, 20, 50] { + let proof = make_instant_asset_lock_proof_with_signed_inputs(inputs); + let actions = usize::from(max_shield_from_asset_lock_actions(platform_version, &proof)); + assert!(actions >= 2, "{inputs} inputs: {actions} actions"); + batch_by_inputs.push((inputs, actions)); + let st = build_shield_from_asset_lock_transition_with_signer( + &recipient, + 50_000u64, + proof, + &path, + &signer, + &TestProver, + [0u8; 36], + None, + None, + actions - 1, + platform_version, + ) + .await + .expect("builder should succeed"); + let len = st.serialize_to_bytes().expect("serialize").len(); + assert!( + len <= max, + "{inputs} inputs, {actions} actions: {len} > {max}" + ); + } + // A single-input lock keeps the full batch; a funding transaction with 7 inputs does not + // fit it any more. + assert_eq!(batch_by_inputs[0], (1, 6)); + assert!(batch_by_inputs[2].1 < 6, "{batch_by_inputs:?}"); +} diff --git a/packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs b/packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs index bca4a752914..97d42e4d1a1 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/fund_from_asset_lock.rs @@ -42,7 +42,7 @@ use dpp::balances::credits::CREDITS_PER_DUFF; use dpp::fee::Credits; use dpp::prelude::AssetLockProof; use dpp::shielded::builder::{build_shield_from_asset_lock_transition_with_signer, OrchardProver}; -use dpp::shielded::compute_minimum_shielded_fee; +use dpp::shielded::{compute_minimum_shielded_fee, max_shield_from_asset_lock_actions}; use dpp::state_transition::proof_result::StateTransitionProofResult; use key_wallet::wallet::managed_wallet_info::asset_lock_builder::AssetLockFundingType; @@ -443,6 +443,14 @@ impl PlatformWallet { // residual to the (sole) `None` bucket; the preflight will // change in lockstep with the DPP-side multi-output bundle // builder. + // + // The batch is sized for the lock's own proof first: the lock is built, and its + // proof known, only after the funding resolved, and an InstantSend proof of a funding + // transaction with many inputs leaves room for fewer actions than the ChainLock + // proof the batch size was chosen for. The fee follows the actions the transition + // carries. + let dummy_outputs = dummy_outputs_fitting_proof(dummy_outputs, &proof, self.sdk.version()); + let num_actions = shield_from_asset_lock_num_actions(dummy_outputs); let asset_lock_value_credits = lookup_asset_lock_value_credits(self, &proof, tracked_out_point.as_ref()).await?; // `pool_fee = compute_minimum_shielded_fee(2) + asset_lock_base_cost` — the SAME flat fee @@ -955,6 +963,20 @@ where }) } +/// The `dummy_outputs` fillers a `ShieldFromAssetLock` carrying `proof` can have, so that the +/// transition fits `max_state_transition_size`: an InstantSend proof embeds its whole funding +/// transaction, which takes room from the Orchard actions. Fewer fillers shrink the batch +/// and its fee together ([`shield_from_asset_lock_num_actions`]); a lock too large for any +/// batch keeps the 2 actions of a single output, and the ChainLock fallback takes it from there. +fn dummy_outputs_fitting_proof( + dummy_outputs: usize, + proof: &AssetLockProof, + platform_version: &dpp::version::PlatformVersion, +) -> usize { + let max_actions = usize::from(max_shield_from_asset_lock_actions(platform_version, proof)); + dummy_outputs.min(max_actions.saturating_sub(1)) +} + /// Pre-flight check for the recipient list. /// /// Today: non-empty, exactly one recipient whose `Credits` value is @@ -1055,6 +1077,58 @@ mod tests { use crate::wallet::persister::WalletPersister; use crate::wallet::platform_wallet::{PlatformWalletInfo, WalletId}; + /// A seeding batch is sized for the lock's own proof: an InstantSend proof of a funding + /// transaction with many inputs leaves room for fewer actions, a ChainLock proof for the + /// full batch, and a lock too large for any batch keeps a single output. + #[test] + fn should_size_the_batch_for_the_asset_lock_proof_it_carries() { + use dpp::identity::state_transition::asset_lock_proof::InstantAssetLockProof; + use dpp::tests::fixtures::{ + instant_asset_lock_is_lock_fixture, + instant_asset_lock_proof_transaction_fixture_with_inputs, + }; + use dpp::version::PlatformVersion; + + let version = PlatformVersion::latest(); + let full_batch = 5; + let instant = |inputs: u32| { + let mut transaction = + instant_asset_lock_proof_transaction_fixture_with_inputs(None, None, inputs); + for input in &mut transaction.input { + input.script_sig = dashcore::ScriptBuf::from_bytes(vec![0x30; 107]); + } + let mut lock = instant_asset_lock_is_lock_fixture(transaction.txid()); + lock.inputs = transaction + .input + .iter() + .map(|i| i.previous_output) + .collect(); + AssetLockProof::Instant(InstantAssetLockProof::new(lock, transaction, 0)) + }; + let chain = AssetLockProof::Chain(ChainAssetLockProof { + core_chain_locked_height: 100, + out_point: OutPoint::from([11u8; 36]), + }); + + assert_eq!(dummy_outputs_fitting_proof(full_batch, &chain, version), 5); + assert_eq!( + dummy_outputs_fitting_proof(full_batch, &instant(1), version), + 5 + ); + assert_eq!( + dummy_outputs_fitting_proof(full_batch, &instant(7), version), + 4, + "a 7-input lock does not fit 6 actions" + ); + assert_eq!(dummy_outputs_fitting_proof(2, &instant(7), version), 2); + assert_eq!( + dummy_outputs_fitting_proof(full_batch, &instant(100), version), + 0, + "no batch fits a 100-input InstantSend proof" + ); + assert_eq!(dummy_outputs_fitting_proof(0, &instant(1), version), 0); + } + // The preflight is a pure length/cardinality check; the // recipient type is irrelevant for what we're testing. Using // `u8` as the placeholder type avoids needing to construct a diff --git a/packages/rs-platform-wallet/src/wallet/shielded/seed_pool.rs b/packages/rs-platform-wallet/src/wallet/shielded/seed_pool.rs index 6e8b1c81e0d..8cf7befd518 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/seed_pool.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/seed_pool.rs @@ -44,7 +44,8 @@ use crate::PlatformWalletError; /// (`system_limits.max_state_transition_size`, mirrored by tenderdash's /// `mempool.max-tx-bytes = 20480`) and not by the consensus action cap, because the Halo 2 /// proof grows with the action count. See [`max_shielded_actions_per_transition`] for the -/// measured sizes. +/// measured sizes. A lock whose InstantSend proof is large (many funding inputs) carries a +/// smaller batch, sized once its proof is known (`shielded_fund_from_asset_lock`). fn max_actions_per_batch(platform_version: &PlatformVersion) -> u64 { u64::from(max_shielded_actions_per_transition(platform_version)) } From 3cfaed43744818234f50330a3054619efcde56d3 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 02:04:58 +0200 Subject: [PATCH 19/20] fix(platform-wallet): rebroadcast a recovered shielded spend through the checked dispatcher Recovery re-broadcast a saved spend with the SDK's own broadcast, whose default retries send further attempts with no context check in between: a network version learned during a failed first attempt could precede another unchecked send. Recovery now uses the same per-dispatch checked dispatcher as the foreground spend, with the saved-context check run before every attempt and no SDK-internal retries. A refusal sends nothing more and keeps the saved record, its attempt count and the note reservations; a refusal after an earlier attempt is logged as possibly delivered, never as not sent. Co-Authored-By: Claude Opus 5.5 --- .../rs-platform-wallet/src/test_support.rs | 25 +++- .../src/wallet/shielded/operations.rs | 122 ++++++++++++++++-- 2 files changed, 130 insertions(+), 17 deletions(-) diff --git a/packages/rs-platform-wallet/src/test_support.rs b/packages/rs-platform-wallet/src/test_support.rs index 9dd50f7e669..b266e881778 100644 --- a/packages/rs-platform-wallet/src/test_support.rs +++ b/packages/rs-platform-wallet/src/test_support.rs @@ -986,11 +986,27 @@ pub(crate) mod tracing_capture { /// Level and message of every event recorded while registered as the /// current thread's active recorder (see [`RecordingGuard`]). #[derive(Clone, Default)] - pub(crate) struct RecordedEvents(Arc>>); + pub(crate) struct RecordedEvents { + events: Arc>>, + on_event: Option, + } + + /// What runs, inline on the emitting thread, for every recorded event's message. + type EventHook = Arc; impl RecordedEvents { + /// A recorder that also runs `hook` with the message of every event, the moment it + /// is emitted: for a test that needs the world to change at a chosen point of the + /// code under test. + pub(crate) fn with_hook(hook: impl Fn(&str) + Send + Sync + 'static) -> Self { + Self { + events: Arc::default(), + on_event: Some(Arc::new(hook)), + } + } + pub(crate) fn entries(&self) -> Vec<(Level, String)> { - self.0.lock().expect("recorded events mutex").clone() + self.events.lock().expect("recorded events mutex").clone() } fn record(&self, event: &tracing::Event<'_>) { @@ -1004,7 +1020,10 @@ pub(crate) mod tracing_capture { } let mut visitor = MessageVisitor(String::new()); event.record(&mut visitor); - self.0 + if let Some(hook) = &self.on_event { + hook(&visitor.0); + } + self.events .lock() .expect("recorded events mutex") .push((*event.metadata().level(), visitor.0)); diff --git a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs index 9d559c2c92a..67c1d46ae36 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/operations.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/operations.rs @@ -5029,20 +5029,39 @@ pub(super) async fn redrive_pending_spends( let Some(attempts) = claim_redrive_attempt(store, id, &redrive).await else { continue; }; - // The claim waited for the store: the context is checked again right before the - // broadcast, as another task can verify a newer network version meanwhile. The - // claimed attempt stays counted; the record stays, unretired. - if let Some(context) = &redrive.spend_context { - if !recovery_context_holds(sdk, context, redrive.nullifiers.len()) { - warn!( - saved = ?context, - "redrive: the context the spend was priced in stopped holding while its \ - claim waited; keeping the record without re-broadcasting it" - ); - continue; - } - } - let broadcast_result = st.broadcast(sdk, None).await; + // The context is checked immediately before every dispatch, the first one included + // (the claim waited for the store, and another task can verify a newer network + // version meanwhile, or while an earlier dispatch is in flight), and the SDK's own + // retries are not used: no attempt is sent unchecked. A refusal sends nothing more. + // The claimed attempt stays counted and the record stays, unretired. + let broadcast_result = + match broadcast_tracking_delivery_checked(sdk, &st, || match &redrive.spend_context { + Some(context) + if !recovery_context_holds(sdk, context, redrive.nullifiers.len()) => + { + Err(()) + } + _ => Ok(()), + }) + .await + { + Ok(BroadcastDelivery::Admitted) => Ok(()), + // Recovery never retires a record from here: a spend that was never delivered is + // resolved by the spend that saved it, the scan or the prune backstop. + Ok(BroadcastDelivery::MaybeDelivered(e) | BroadcastDelivery::NeverDelivered(e)) => { + Err(e) + } + Err(stopped) => { + warn!( + saved = ?redrive.spend_context, + may_have_been_delivered = stopped.may_have_been_delivered, + "redrive: the context the spend was priced in stopped holding before a \ + dispatch; not sending it again, keeping the record and its notes (an \ + earlier dispatch, if any, may have been delivered)" + ); + continue; + } + }; let err_display = broadcast_result .as_ref() .err() @@ -8287,6 +8306,81 @@ mod redrive_tests { ); } + /// Recovery re-broadcasts a saved spend in single dispatches, as the foreground spend + /// does, at the SDK's configured budget: none of them is left to the SDK's own retry + /// loop, which no check runs inside of. + #[tokio::test] + async fn should_rebroadcast_a_saved_spend_in_single_checked_dispatches() { + use crate::broadcast_outcome::spend_broadcast_dispatches; + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + + let (mut sdk, handle) = pinned_v13_sdk(); + let store = Arc::new(RwLock::new(InMemoryShieldedStore::new())); + let id = SubwalletId::new([0x60; 32], 0); + let (transition, record) = saved_transfer(0, Some(transfer_context(13, None, 0))); + store.write().await.arm_redrive(id, record).expect("armed"); + let recorded = [SPEND_ANCHOR].into_iter().collect(); + + redrive_pending_spends(&handle, &store, id, &recorded, &CancellationToken::new()).await; + + let request = transition + .broadcast_request_for_state_transition() + .expect("serializes"); + assert_eq!( + sdk.mock().request_count(&request).await, + spend_broadcast_dispatches(&handle), + "every failed dispatch is followed by another, up to the budget" + ); + let left = store.read().await.pending_redrives(id).expect("records"); + assert_eq!(left.len(), 1, "the record stays"); + assert_eq!(left[0].attempts, 1, "one attempt is claimed for the pass"); + } + + /// The SDK learns a newer verified network version during recovery's first, failed + /// transport attempt: no second attempt is sent under the fee schedule the spend was not + /// priced in, whatever the SDK's retry budget. The first attempt may have been delivered, + /// so the record stays with its notes reserved, and its attempt stays counted. + #[tokio::test] + async fn should_not_send_another_recovery_attempt_when_the_version_is_learned_during_the_first() + { + use crate::test_support::tracing_capture::{RecordedEvents, RecordingGuard}; + use dash_sdk::platform::transition::broadcast_request::BroadcastRequestForStateTransition; + + let (mut sdk, handle) = pinned_v13_sdk(); + let store = Arc::new(RwLock::new(InMemoryShieldedStore::new())); + let id = SubwalletId::new([0x61; 32], 0); + let (transition, record) = saved_transfer(0, Some(transfer_context(13, None, 0))); + store.write().await.arm_redrive(id, record).expect("armed"); + let recorded = [SPEND_ANCHOR].into_iter().collect(); + + // The mock transport logs each execution after counting it and before it answers: + // the first one is where the SDK learns the newer version. + let learner = Arc::clone(&handle); + let learned = std::sync::atomic::AtomicBool::new(false); + let _recording = RecordingGuard::install(RecordedEvents::with_hook(move |message| { + if message == "mock execute" && !learned.swap(true, std::sync::atomic::Ordering::SeqCst) + { + learner + .mock_verified_protocol_version(PlatformVersion::latest().protocol_version) + .expect("a mock SDK"); + } + })); + + redrive_pending_spends(&handle, &store, id, &recorded, &CancellationToken::new()).await; + + let request = transition + .broadcast_request_for_state_transition() + .expect("serializes"); + assert_eq!( + sdk.mock().request_count(&request).await, + 1, + "the first attempt is the only one sent" + ); + let left = store.read().await.pending_redrives(id).expect("records"); + assert_eq!(left.len(), 1, "the record stays"); + assert_eq!(left[0].attempts, 1, "the claimed attempt stays counted"); + } + /// A shielded spend's dispatches check the context before each one, and a check that /// refuses a later dispatch after an earlier one may have been delivered reads as an /// unconfirmed spend, which keeps the notes reserved; refused before the first dispatch From 2715247731f1bfe02c02f58e83861a342c0cd295 Mon Sep 17 00:00:00 2001 From: romchornyi Date: Fri, 13 Nov 2026 09:27:27 +0200 Subject: [PATCH 20/20] fix(platform-wallet): keep the reservations of a recovery record whose spend context is unreadable A note-spend recovery row whose saved spend context had an unsupported format byte or was truncated was skipped whole on open, so its notes were restored as spendable although the transition may already have been delivered. Such a row is now quarantined: its nullifier reservations are restored (out of selection and the spendable balance, releasable by the scan or the prune backstop), but the record is never armed, so recovery cannot re-broadcast it. It stays distinct from a legacy NULL context, which still recovers as before. Records whose other fields do not decode keep the damaged-row handling. Co-Authored-By: Claude Opus 5.5 --- .../src/wallet/shielded/file_store.rs | 92 ++++++++++++++++++- .../src/wallet/shielded/store.rs | 29 ++++++ 2 files changed, 117 insertions(+), 4 deletions(-) diff --git a/packages/rs-platform-wallet/src/wallet/shielded/file_store.rs b/packages/rs-platform-wallet/src/wallet/shielded/file_store.rs index 90ff623ec0b..67b144391e2 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/file_store.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/file_store.rs @@ -760,8 +760,13 @@ impl FileBackedShieldedStore { return Err(corrupted("invalid nullifier width")); } let nullifiers: Vec<[u8; 32]> = nullifiers.as_chunks::<32>().0.to_vec(); - let spend_context = - spend_context.map_err(|()| corrupted("unreadable spend context"))?; + // A note spend whose context does not read keeps its reservations, in + // quarantine and never armed; any other record fails as before. + let context_unreadable = spend_context.is_err(); + if context_unreadable && (note_spend_kind.is_none() || nullifiers.is_empty()) { + return Err(corrupted("unreadable spend context")); + } + let spend_context = spend_context.unwrap_or(None); Ok(( SubwalletId::new(wallet_id, account_index), PendingRedrive { @@ -775,9 +780,10 @@ impl FileBackedShieldedStore { identity_user_abandoned, spend_context, }, + context_unreadable, )) })(); - let (id, redrive) = match decoded { + let (id, redrive, context_unreadable) = match decoded { Ok(decoded) => decoded, Err(error) => { if let Some(kind) = note_spend_kind { @@ -797,6 +803,24 @@ impl FileBackedShieldedStore { return Err(error); } }; + if context_unreadable { + tracing::warn!( + account_index, + "quarantining a shielded note-spend recovery row whose spend context is \ + unreadable: its notes stay reserved and it is never re-broadcast" + ); + if private_contact_payment.is_some() + || note_spend_kind == Some(PRIVATE_DOCUMENT_CREATE_KIND) + { + self.unloaded_private_contact_payments + .insert(readable_wallet_id); + } + self.subwallets + .entry(id) + .or_default() + .quarantine_redrive(&redrive); + continue; + } if let Some(payment) = private_contact_payment { self.private_contact_payments .insert((id, redrive.activity_id), payment); @@ -2240,11 +2264,46 @@ mod tests { [], ) .unwrap(); - let store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); + let mut store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); assert!( store.pending_redrives(id).unwrap().is_empty(), "{damaged}: not loaded, so never re-broadcast unchecked" ); + // The host restores its notes from a snapshot after the open: the ones the + // unreadable records spend stay reserved, out of selection and the balance. + for record in &saved { + store + .save_note( + id, + &ShieldedNote { + position: u64::from(record.activity_id[0]), + cmx: [record.activity_id[0]; 32], + nullifier: record.nullifiers[0], + block_height: 1, + is_spent: false, + value: 10, + note_data: vec![], + }, + ) + .unwrap(); + } + assert!( + store.get_unspent_notes(id).unwrap().is_empty(), + "{damaged}: the notes of an unresolved spend are not selectable" + ); + assert_eq!( + store.spendable_balance(id).unwrap(), + 0, + "{damaged}: nor spendable" + ); + assert_eq!( + store.stale_pending_spends(id).unwrap().len(), + saved.len(), + "{damaged}: the prune backstop can still release them" + ); + drop(store); + let store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); + assert!(store.pending_redrives(id).unwrap().is_empty()); let rows: u32 = rusqlite::Connection::open(&path) .unwrap() .query_row("SELECT COUNT(*) FROM shielded_pending_spends", [], |row| { @@ -2253,6 +2312,31 @@ mod tests { .unwrap(); assert_eq!(rows, saved.len() as u32, "{damaged}: the rows are kept"); } + // A quarantined record resolves as an armed one does: the scan seeing its + // nullifier drops the row. + let mut store = FileBackedShieldedStore::open_path(&path, 100).unwrap(); + store + .save_note( + id, + &ShieldedNote { + position: 0, + cmx: [1; 32], + nullifier: saved[0].nullifiers[0], + block_height: 1, + is_spent: false, + value: 10, + note_data: vec![], + }, + ) + .unwrap(); + store.mark_spent(id, &saved[0].nullifiers[0]).unwrap(); + let rows: u32 = rusqlite::Connection::open(&path) + .unwrap() + .query_row("SELECT COUNT(*) FROM shielded_pending_spends", [], |row| { + row.get(0) + }) + .unwrap(); + assert_eq!(rows, saved.len() as u32 - 1, "the resolved row is dropped"); let _ = std::fs::remove_file(&path); } diff --git a/packages/rs-platform-wallet/src/wallet/shielded/store.rs b/packages/rs-platform-wallet/src/wallet/shielded/store.rs index 48439cd77d6..305d8d7bd7f 100644 --- a/packages/rs-platform-wallet/src/wallet/shielded/store.rs +++ b/packages/rs-platform-wallet/src/wallet/shielded/store.rs @@ -1077,6 +1077,11 @@ pub(super) struct SubwalletState { /// (mark_spent / clear_pending) drops the whole record — a /// transition lands or dies atomically for all its nullifiers. pub redrives: BTreeMap<[u8; 32], PendingRedrive>, + /// Records whose saved spend context did not read back, by activity id, with the + /// nullifiers they carry. Their reservations are held like an armed record's, but they + /// are never armed: no recovery pass can see them, so none re-broadcasts them. They go + /// as an armed record does, when any of their nullifiers resolves. + pub quarantined_redrives: BTreeMap<[u8; 32], Vec<[u8; 32]>>, /// Notes this subwallet SENT, recovered via OVK during the scan. /// Append-only send history in recording order. pub outgoing_notes: Vec, @@ -1167,6 +1172,14 @@ impl SubwalletState { for id in &dropped { self.redrives.remove(id); } + let mut dropped = dropped; + self.quarantined_redrives.retain(|id, nullifiers| { + let hit = nullifiers.contains(nullifier); + if hit { + dropped.push(*id); + } + !hit + }); dropped } @@ -1302,6 +1315,22 @@ impl SubwalletState { removed } + /// Hold the reservation of a record whose spend context is unreadable, without arming + /// it: its notes stay out of selection and the balance, and it is never re-broadcast. + pub(super) fn quarantine_redrive(&mut self, redrive: &PendingRedrive) { + for n in &redrive.nullifiers { + self.mark_pending(n); + self.set_pending_spend( + n, + redrive.anchor, + redrive.activity_id, + redrive.anchor_height, + ); + } + self.quarantined_redrives + .insert(redrive.activity_id, redrive.nullifiers.clone()); + } + /// Arm (or overwrite by activity id) a re-drivable record. pub(super) fn arm_redrive(&mut self, redrive: PendingRedrive) { self.redrives.insert(redrive.activity_id, redrive);